Merge pull request #126 from runkids/feat/agents

v0.19.0
This commit is contained in:
Willie
2026-04-11 15:21:46 +08:00
committed by GitHub
339 changed files with 29866 additions and 5761 deletions
+7
View File
@@ -72,6 +72,13 @@
- **Fix**: Use `>/dev/null 2>&1` (redirect both stdout AND stderr) for cleanup commands in steps that need pure JSON output
- **Runbooks affected**: extras_flatten_runbook.md
### [gotcha] chmod 0444 does not block writes when running as root
- **Context**: `TestLog_SyncPartialStatus` used `os.Chmod(dir, 0444)` to make a target directory read-only, expecting sync to fail on that target and log `"status":"partial"`
- **Discovery**: The devcontainer runs as root. Root ignores POSIX permission bits — `chmod 0444` has no effect. The "broken" target synced successfully, so the oplog recorded `"status":"ok"` instead of `"partial"`
- **Fix**: Use a **dangling symlink** instead: `os.Symlink("/nonexistent/path", targetPath)`. This makes `os.Stat` return "not exist" (passes config validation) but `os.MkdirAll` fails because the symlink entry blocks directory creation. Works regardless of UID
- **Runbooks affected**: `tests/integration/log_test.go` (`TestLog_SyncPartialStatus`)
### [gotcha] Full-directory mdproof runs cause inter-runbook state leakage
- **Context**: Running `mdproof --report json /path/to/tests/` executes all runbooks sequentially in the same environment (same ssenv). Earlier runbooks install skills, modify config, fill trash — this state persists for later runbooks
+126
View File
@@ -1,5 +1,131 @@
# Changelog
## [0.19.0] - 2026-04-11
### New Features
#### Agent Management
Agents are now a first-class resource type alongside skills. You can install, sync, audit, and manage agent files (`.md`) across agent-capable targets (Claude, Cursor, OpenCode, Augment) with the same workflow as skills.
- **Agents source directory** — agents live in `~/.config/skillshare/agents/` (or `.skillshare/agents/` in project mode). `skillshare init` creates the directory automatically, and `agents_source` is a new config field that can be customized
```bash
skillshare init # creates skills/ and agents/
skillshare init -p # same for project mode
```
- **Positional kind filter** — most commands accept an `agents` keyword to scope the operation to agents only. Without it, commands operate on skills (existing behavior is unchanged)
```bash
skillshare sync agents # sync agents only
skillshare sync --all # sync skills + agents + extras
skillshare list agents # list installed agents
skillshare check agents # detect drift on agent repos
skillshare update agents # update agents
skillshare audit agents # scan agents for security issues
skillshare uninstall agents # uninstall by kind
skillshare enable foo --kind agent
skillshare disable foo --kind agent
```
- **Install agents from repos** — `install` auto-detects agents in three layouts:
- `agents/` convention subdirectory
- mixed-kind repos with both `SKILL.md` and `agents/`
- pure-agent repos (root `.md` files, no `SKILL.md`)
```bash
skillshare install github.com/team/agents # auto-detect
skillshare install github.com/team/repo --kind agent # force agent mode
skillshare install github.com/team/repo --agent cr # specific agents
```
Conventional files (`README.md`, `LICENSE.md`, `CHANGELOG.md`) are automatically excluded
- **Tracked agent repos** — agents can be installed with `--track` for git-pull updates, including nested discovery. `check`, `update`, `doctor`, and `uninstall` all recognise tracked agent repos, and the `--group` / `-G` flag filters by repo group
- **Agent sync modes** — merge (default, per-file symlink), symlink (whole directory), and copy are all supported. `skillshare sync agents` skips targets that don't declare an `agents:` path and prints a warning
- **`.agentignore` support** — agents can be excluded via `.agentignore` and `.agentignore.local` using the same gitignore-style patterns as `.skillignore`. The Web UI Config page now has a dedicated `.agentignore` tab
- **Agent audit** — `skillshare audit` scans agent files individually against the full audit rule set, with Skills/Agents tab switching in both the TUI and Web UI. Audit results carry a `kind` field so tooling can filter by resource type
- **Agent backup and restore** — sync automatically backs up agents before applying changes, in both global and project mode. The backup TUI and trash TUI tag agents with an `[A]` badge and route restores to the correct source directory
- **Project-mode agent support** — every agent command works in project mode with `-p`. Agents are reconciled alongside skills into `.skillshare/`
- **JSON output for agents** — `install --json` and `update --json` now emit agent-aware payloads and apply the same audit block-threshold gate as skills. Useful for scripted agent workflows
```bash
skillshare update agents --json --audit-threshold high
```
- **Kind badges** — TUI and Web UI surface `[S]` / `[A]` badges throughout (list, diff, audit, trash, backup, detail, update, targets pages) so you can tell at a glance what kind of resource you're looking at
#### Unified Web UI Resources
- **`/resources` route** — the old `/skills` page is now `/resources`, with Skills and Agents tabs. Tab state persists to localStorage, and the underline tab style follows the active theme (playful mode gets wobble borders)
- **Targets page redesign** — equal Skills and Agents sections, with a modal picker for adding targets. Filter Studio links include a `?kind=` param so you jump directly to the right context
- **Update page redesign** — a new three-phase flow (selecting → updating → done) with skills/agents tabs, group-based sorting, and status cards. EventSource streaming is properly cleaned up on page change
- **Filter Studio agent support** — agent filters can be edited via `PATCH /api/targets/:name` (`agent_include`, `agent_exclude`, `agent_mode`) and via the CLI (`targets edit --add-agent-include`, `--remove-agent-include`, `--agent-mode`, and so on). The UI Filter Studio is a single-context view driven by `?kind=skill|agent`
- **Audit cache** — audit results are now cached with React Query and invalidated on mutation. The audit card icon colour follows the max severity, and the count no longer mixes agent totals with finding counts
- **Collect page scope switcher** — a new segmented control lets you collect skills or agents from targets
#### Theme System
- **`internal/theme` package** — unified light/dark terminal palette with WCAG-AA-compliant light colours and softened dark primary. Resolution order: `NO_COLOR` > `SKILLSHARE_THEME` > OSC 11 terminal probe > dark fallback. All TUIs, list output, audit output, and plain CLI output now route through the theme
```bash
SKILLSHARE_THEME=light skillshare list
SKILLSHARE_THEME=dark skillshare audit
```
`skillshare doctor` includes a theme check to help debug unreadable colours
#### Install & TUI Polish
- **Explicit `SKILL.md` URLs resolve to one skill** — pasting a direct `blob/.../SKILL.md` URL now installs only that skill, bypassing the orchestrator pack prompt. Previously, the URL would trigger the full multi-select picker even though the intent was clear
```bash
skillshare install https://github.com/team/repo/blob/main/frontend/tdd/SKILL.md
```
Refs: #124
- **Radio checklist follows the cursor** — the single-select TUI (used for orchestrator selection, branch selection, and similar flows) now auto-selects the focused row. No more confusing empty-selection state — pressing Enter always confirms the item your cursor is on
- **Diff TUI** — single-line items with group headers instead of the old verbose-per-item layout. Agent diffs are shown with an `[A]` badge
- **List TUI** — entries are now grouped by tracked repo root and local top directory, with a new `k:kind` filter tag for quick agent/skill filtering inside the fuzzy filter
#### Centralized Metadata Store
- **`.metadata.json` replaces sidecar files and `registry.yaml`** — installation metadata is now stored in a single atomic file per source (`~/.config/skillshare/skills/.metadata.json`). This fixes long-standing issues with grouped skill collisions (e.g. two skills both named `dev` in different folders) where the old basename-keyed registry would mix them up
- **Automatic migration** — the first load after upgrade reads any existing `registry.yaml` and per-skill `.skillshare-meta.json` sidecars, merges them into `.metadata.json`, and cleans up the old files. Idempotent — safe to run repeatedly
- **Full-path keys** — lookups use the full source-relative path, so nested skills never collide
- No user action required; existing installs continue to work
### Bug Fixes
- **Sync extras no longer flood when `agents` target overlaps** — targets that declare an extras entry called `agents` are now skipped automatically when agent sync is active, preventing duplicate file writes
- **Nested agent discovery** — `check agents` now uses the recursive discovery engine, so agents in sub-folders (e.g. `demo/code-reviewer.md`) are detected correctly
- **Doctor drift count excludes disabled agents** — agents disabled via `.agentignore` no longer count toward the drift total reported by `skillshare doctor`
- **Audit card mixes counts** — the Web UI audit card no longer mixes agent counts with finding counts, and excludes `_cross-skill` from the card total (shown separately)
- **Audit scans disabled agents too** — the audit scan walks every agent file regardless of `.agentignore` state, so hidden agents still get checked
- **List TUI tab bar clipping** — the tab bar no longer gets cut off in the split-detail layout on narrow terminals
- **Sync extras indent** — removed the stray space between the checkmark and the path in `sync` extras output; summary headers are now consistent across skills, agents, and extras
- **UI skill detail agent mode** — the detail page hides the Files section for agents (single-file resources), remembers the selected tab via localStorage, and shows the correct folder-view labels
- **Sync page layout** — the stats row and ignored-skills grouping are now easier to scan
- **Button warning variant** — the shared `Button` component now supports a `warning` variant that was already referenced by several pages
- **Check progress bar pop-in** — removed the loading progress bar that caused layout shift on the Skills page
- **Tracked repo check status** — the propagated check status is now applied to every item within the repo, not just the root
- **Target name colouring in doctor** — only the status word is coloured in `doctor` target output, not the full line
### Breaking Changes
- **`audit --all` flag removed** — use the positional kind filter instead:
```bash
skillshare audit # skills (default, unchanged)
skillshare audit agents # agents only
```
The old `--all` flag is gone because audit now runs per kind and the Web UI has dedicated tabs
## [0.18.9] - 2026-04-07
### New Features
+17 -6
View File
@@ -22,7 +22,7 @@
</p>
<p align="center">
<strong>One source of truth for AI CLI skills, rules, commands & more. Sync everywhere with one command — from personal to organization-wide.</strong><br>
<strong>One source of truth for AI CLI skills, agents, rules, commands & more. Sync everywhere with one command — from personal to organization-wide.</strong><br>
Codex, Claude Code, OpenClaw, OpenCode & 50+ more.
</p>
@@ -40,7 +40,7 @@
</p>
> [!NOTE]
> **Latest**: [v0.18.3](https://github.com/runkids/skillshare/releases/tag/v0.18.3) — enable/disable skills, skills sub-key config, upgrade auto-sudo. [All releases →](https://github.com/runkids/skillshare/releases)
> **Latest**: [v0.19.0](https://github.com/runkids/skillshare/releases/tag/v0.19.0) — agent management, filter studio, unified resources UI. [All releases →](https://github.com/runkids/skillshare/releases)
## Why skillshare
@@ -50,6 +50,7 @@ You edit in one, forget to copy to another, and lose track of what's where.
skillshare fixes this:
- **One source, every agent** — sync to Claude, Cursor, Codex & 50+ more with `skillshare sync`
- **Agent management** — sync custom agents alongside skills to agent-capable targets
- **More than skills** — manage rules, commands, prompts & any file-based resource with [extras](https://skillshare.runkids.cc/docs/reference/targets/configuration#extras)
- **Install from anywhere** — GitHub, GitLab, Bitbucket, Azure DevOps, or any self-hosted Git
- **Built-in security** — audit skills for prompt injection and data exfiltration before use
@@ -68,6 +69,7 @@ skillshare fixes this:
┌─────────────────────────────────────────────────────────────┐
│ Source Directory │
│ ~/.config/skillshare/skills/ ← skills (SKILL.md) │
│ ~/.config/skillshare/agents/ ← agents │
│ ~/.config/skillshare/extras/ ← rules, commands, etc. │
└─────────────────────────────────────────────────────────────┘
│ sync
@@ -78,10 +80,10 @@ skillshare fixes this:
└───────────┘ └───────────┘ └───────────┘
```
| Platform | Skills Source | Extras Source | Link Type |
|----------|---------------|---------------|-----------|
| macOS/Linux | `~/.config/skillshare/skills/` | `~/.config/skillshare/extras/` | Symlinks |
| Windows | `%AppData%\skillshare\skills\` | `%AppData%\skillshare\extras\` | NTFS Junctions (no admin required) |
| Platform | Skills Source | Agents Source | Extras Source | Link Type |
|----------|---------------|---------------|---------------|-----------|
| macOS/Linux | `~/.config/skillshare/skills/` | `~/.config/skillshare/agents/` | `~/.config/skillshare/extras/` | Symlinks |
| Windows | `%AppData%\skillshare\skills\` | `%AppData%\skillshare\agents\` | `%AppData%\skillshare\extras\` | NTFS Junctions (no admin required) |
| | Imperative (install-per-command) | Declarative (skillshare) |
|---|---|---|
@@ -180,6 +182,13 @@ skillshare audit
skillshare init -p && skillshare sync
```
**Agents** —sync custom agents to agent-capable targets
```bash
skillshare sync agents # sync agents only
skillshare sync --all # sync skills + agents + extras together
```
**Extras** —manage rules, commands, prompts & more
```bash
@@ -242,6 +251,8 @@ Thanks to everyone who helped shape skillshare.
<a href="https://github.com/Curtion"><img src="https://github.com/Curtion.png" width="50" style="border-radius:50%" alt="Curtion"></a>
<a href="https://github.com/amdoi7"><img src="https://github.com/amdoi7.png" width="50" style="border-radius:50%" alt="amdoi7"></a>
<a href="https://github.com/jessica-engel"><img src="https://github.com/jessica-engel.png" width="50" style="border-radius:50%" alt="jessica-engel"></a>
<a href="https://github.com/AlimuratYusup"><img src="https://github.com/AlimuratYusup.png" width="50" style="border-radius:50%" alt="AlimuratYusup"></a>
<a href="https://github.com/thor-shuang"><img src="https://github.com/thor-shuang.png" width="50" style="border-radius:50%" alt="thor-shuang"></a>
---
+445
View File
@@ -0,0 +1,445 @@
# CLI E2E Runbook: Agents Commands
Validates all agent-related CLI commands: list, sync, status, diff,
collect, uninstall, trash, update, backup, and doctor.
**Origin**: v0.17.0 — agents support added as a new resource kind alongside skills.
## Scope
- Agent CRUD lifecycle (create source → sync → uninstall → trash → restore)
- Kind filter: `agents`, `--all`, default (skills-only)
- JSON output for all commands that support it
- Diff and collect workflows
- Backup and restore round-trip
- Doctor agent checks
- Update with no tracked agents (local-only)
## Environment
Run inside devcontainer via mdproof (no ssenv wrapper needed).
All commands use `-g` to force global mode since `/workspace/.skillshare/` triggers project mode auto-detection.
## Steps
### 1. Setup: init global config and create agent source files
```bash
ss init -g --force --no-copy --all-targets --no-git --no-skill
AGENTS_DIR=~/.config/skillshare/agents
mkdir -p "$AGENTS_DIR"
cat > "$AGENTS_DIR/tutor.md" <<'EOF'
---
name: tutor
description: A tutoring agent
---
# Tutor Agent
Helps with learning.
EOF
cat > "$AGENTS_DIR/reviewer.md" <<'EOF'
---
name: reviewer
description: A code review agent
---
# Reviewer Agent
Reviews code for quality.
EOF
cat > "$AGENTS_DIR/debugger.md" <<'EOF'
---
name: debugger
description: A debugging agent
---
# Debugger Agent
Helps debug issues.
EOF
ls "$AGENTS_DIR"
```
Expected:
- exit_code: 0
- tutor.md
- reviewer.md
- debugger.md
### 2. List agents — shows source agents
```bash
ss list agents --no-tui -g
```
Expected:
- exit_code: 0
- tutor
- reviewer
- debugger
### 3. List agents — JSON includes kind field
```bash
ss list agents --json -g
```
Expected:
- exit_code: 0
- jq: length == 3
- jq: all(.[]; .kind == "agent")
- jq: [.[].name] | sort | . == ["debugger","reviewer","tutor"]
### 4. List default — skills only, no agents
```bash
ss list --json -g
```
Expected:
- exit_code: 0
- Not tutor
- Not reviewer
### 5. Sync agents — creates symlinks
```bash
ss sync agents -g
```
Expected:
- exit_code: 0
- regex: linked|synced
Verify:
```bash
CLAUDE_AGENTS=~/.claude/agents
test -L "$CLAUDE_AGENTS/tutor.md" && echo "tutor: symlinked" || echo "tutor: MISSING"
test -L "$CLAUDE_AGENTS/reviewer.md" && echo "reviewer: symlinked" || echo "reviewer: MISSING"
test -L "$CLAUDE_AGENTS/debugger.md" && echo "debugger: symlinked" || echo "debugger: MISSING"
```
Expected:
- exit_code: 0
- tutor: symlinked
- reviewer: symlinked
- debugger: symlinked
- Not MISSING
### 6. Sync agents — dry-run JSON shows no errors
```bash
ss sync agents --dry-run --json -g
```
Expected:
- exit_code: 0
### 7. Sync default — does NOT sync agents to unconfigured targets
```bash
CURSOR_AGENTS=~/.cursor/agents
rm -rf "$CURSOR_AGENTS" 2>/dev/null || true
ss sync -g
test -d "$CURSOR_AGENTS" && echo "cursor agents dir: EXISTS" || echo "cursor agents dir: not created"
```
Expected:
- exit_code: 0
- cursor agents dir: not created
### 8. Sync all — syncs both skills and agents
```bash
ss sync --all -g
```
Expected:
- exit_code: 0
### 9. Status — shows skills and agents by default
```bash
ss status -g
```
Expected:
- exit_code: 0
- regex: [Aa]gent
- regex: [Ss]ource
### 10. Status JSON — includes agents by default
```bash
ss status --json -g
```
Expected:
- exit_code: 0
- jq: .agents.exists == true
- jq: .agents.count == 3
### 12. Diff agents — no drift after sync
```bash
ss diff agents --no-tui -g
```
Expected:
- exit_code: 0
### 13. Diff agents — JSON output
```bash
ss diff agents --json -g
```
Expected:
- exit_code: 0
### 14. Collect agents — no local agents to collect
```bash
ss collect agents --force -g
```
Expected:
- exit_code: 0
- regex: [Nn]o local agents
### 15. Collect agents — collects a local agent file
```bash
CLAUDE_AGENTS=~/.claude/agents
mkdir -p "$CLAUDE_AGENTS"
rm -f "$CLAUDE_AGENTS/local-agent.md"
cat > "$CLAUDE_AGENTS/local-agent.md" <<'EOF'
---
name: local-agent
description: A locally created agent
---
# Local Agent
Created directly in target.
EOF
ss collect agents --force -g
```
Expected:
- exit_code: 0
- regex: [Cc]ollected
Verify:
```bash
AGENTS_DIR=~/.config/skillshare/agents
test -f "$AGENTS_DIR/local-agent.md" && echo "local-agent: collected to source" || echo "local-agent: NOT IN SOURCE"
```
Expected:
- exit_code: 0
- local-agent: collected to source
- Not NOT IN SOURCE
### 16. Uninstall agents — force remove single agent
```bash
ss uninstall agents local-agent --force -g
```
Expected:
- exit_code: 0
- regex: [Rr]emov|local-agent
### 17. Verify agent was removed by JSON uninstall (step 16)
```bash
AGENTS_DIR=~/.config/skillshare/agents
test -f "$AGENTS_DIR/local-agent.md" && echo "FAIL: still exists" || echo "local-agent: removed"
```
Expected:
- exit_code: 0
- local-agent: removed
- Not FAIL
### 18. Trash agents — list shows uninstalled agent
```bash
ss trash agents list --no-tui -g
```
Expected:
- exit_code: 0
- local-agent
### 19. Trash agents — restore from trash
```bash
ss trash agents restore local-agent -g
```
Expected:
- exit_code: 0
- regex: [Rr]estor
Verify:
```bash
AGENTS_DIR=~/.config/skillshare/agents
test -f "$AGENTS_DIR/local-agent.md" && echo "local-agent: restored" || echo "FAIL: not restored"
```
Expected:
- exit_code: 0
- local-agent: restored
- Not FAIL
### 20. Uninstall agents --all
```bash
ss uninstall agents --all --force -g
```
Expected:
- exit_code: 0
- regex: [Rr]emov|[Uu]ninstall
Verify:
```bash
AGENTS_DIR=~/.config/skillshare/agents
COUNT=$(ls "$AGENTS_DIR"/*.md 2>/dev/null | wc -l | tr -d ' ')
echo "Remaining agents: $COUNT (expected: 0)"
```
Expected:
- exit_code: 0
- Remaining agents: 0 (expected: 0)
### 21. Uninstall agents — validation errors
```bash
ss uninstall agents -g 2>&1 || true
```
Expected:
- regex: name|--all|required|specify
### 22. Sync agents after uninstall — targets cleaned
```bash
ss sync agents -g
CLAUDE_AGENTS=~/.claude/agents
COUNT=$(ls "$CLAUDE_AGENTS"/*.md 2>/dev/null | wc -l | tr -d ' ')
echo "Remaining symlinks: $COUNT"
```
Expected:
- exit_code: 0
- regex: prun|[Nn]o agents
### 23. Update agents — no agents found
```bash
ss update agents --all -g
```
Expected:
- regex: [Nn]o agents|[Nn]o project agents
### 24. Re-create agents and test update — local only
```bash
AGENTS_DIR=~/.config/skillshare/agents
mkdir -p "$AGENTS_DIR"
cat > "$AGENTS_DIR/helper.md" <<'EOF'
---
name: helper
description: A helper agent
---
# Helper
EOF
ss update agents --all -g
```
Expected:
- regex: local|no tracked|up to date|[Nn]o agents
### 25. Update agents — --group not supported
```bash
ss update agents --group mygroup -g 2>&1 || true
```
Expected:
- regex: not supported|--group
### 26. Backup agents
```bash
ss sync agents -g
ss backup agents -g
```
Expected:
- exit_code: 0
- regex: [Bb]ackup|created|nothing
### 27. Backup agents — list shows backup entries
```bash
ss backup --list -g
```
Expected:
- exit_code: 0
### 28. Doctor — includes agent checks
```bash
ss doctor -g
```
Expected:
- exit_code: 0
- regex: [Aa]gent
### 29. List all — shows both skills and agents
```bash
ss list --all --json -g
```
Expected:
- exit_code: 0
- jq: map(select(.kind == "agent")) | length > 0
### 30. Cleanup remaining agents
```bash
ss uninstall agents --all --force -g 2>/dev/null || true
ss sync agents -g 2>/dev/null || true
```
Expected:
- exit_code: 0
## Pass Criteria
- [ ] `list agents` shows only agents, not skills
- [ ] `list agents --json` includes `kind: "agent"` for all entries
- [ ] Default `list` (no kind) excludes agents
- [ ] `sync agents` creates symlinks in agent target directories
- [ ] `sync agents --dry-run` makes no changes
- [ ] Default `sync` does NOT sync agents
- [ ] `sync all` syncs both skills and agents
- [ ] `status` shows both skills and agents by default
- [ ] `status --json` includes agents section
- [ ] `diff agents` shows drift status
- [ ] `collect agents` collects local agent files to source
- [ ] `uninstall agents <name> --force` moves agent to trash
- [ ] `uninstall agents --all --force` removes all agents
- [ ] `uninstall agents` without name or --all → validation error
- [ ] `trash agents list` shows trashed agents
- [ ] `trash agents restore <name>` restores agent from trash
- [ ] `update agents --all` handles no-agents and local-only cases
- [ ] `update agents --group` → not supported error
- [ ] `backup agents` creates agent backup
- [ ] `doctor` includes agent diagnostic checks
- [ ] `list all --json` returns mixed skills + agents
@@ -0,0 +1,190 @@
# CLI E2E Runbook: Agent Include/Exclude Filters
Validates `targets.<name>.agents.include` and `targets.<name>.agents.exclude`
are applied during `sync agents`, including pruning agents that were synced
before the filter was added.
## Scope
- Global-mode agent filters under `targets.<name>.agents`
- Include filter keeps only matching agents and prunes prior non-matching links
- Exclude filter removes matching agents from the target on re-sync
- Nested agent paths are filtered by flattened target filename
## Environment
Run inside devcontainer via mdproof.
Each step is self-contained because mdproof setup resets config between steps.
Use `-g` to force global mode.
## Steps
### 1. Include filter keeps matching agents and prunes previously synced non-matches
```bash
set -e
BASE=~/.config/skillshare
AGENTS_DIR="$BASE/agents"
SKILLS_DIR="$BASE/skills"
TARGET=~/.claude/agents
rm -rf "$AGENTS_DIR" "$SKILLS_DIR" "$TARGET"
mkdir -p "$AGENTS_DIR" "$SKILLS_DIR" "$TARGET"
cat > "$AGENTS_DIR/team-alpha.md" <<'EOF'
# Team Alpha
EOF
cat > "$AGENTS_DIR/team-beta.md" <<'EOF'
# Team Beta
EOF
cat > "$AGENTS_DIR/personal.md" <<'EOF'
# Personal
EOF
cat > "$BASE/config.yaml" <<'EOF'
source: ~/.config/skillshare/skills
targets:
claude:
agents:
path: ~/.claude/agents
EOF
ss sync agents -g >/dev/null
find "$TARGET" -maxdepth 1 -type l -printf 'before: %f\n' | sort
cat > "$BASE/config.yaml" <<'EOF'
source: ~/.config/skillshare/skills
targets:
claude:
agents:
path: ~/.claude/agents
include: [team-*]
EOF
ss sync agents -g >/dev/null
find "$TARGET" -maxdepth 1 \( -type l -o -type f \) -printf 'after: %f\n' | sort
test -L "$TARGET/team-alpha.md" && echo "team-alpha linked=yes" || echo "team-alpha linked=no"
test -L "$TARGET/team-beta.md" && echo "team-beta linked=yes" || echo "team-beta linked=no"
test ! -e "$TARGET/personal.md" && echo "personal present=no" || echo "personal present=yes"
```
Expected:
- exit_code: 0
- before: personal.md
- before: team-alpha.md
- before: team-beta.md
- after: team-alpha.md
- after: team-beta.md
- Not after: personal.md
- team-alpha linked=yes
- team-beta linked=yes
- personal present=no
### 2. Exclude filter prunes matching agents that were previously synced
```bash
set -e
BASE=~/.config/skillshare
AGENTS_DIR="$BASE/agents"
SKILLS_DIR="$BASE/skills"
TARGET=~/.claude/agents
rm -rf "$AGENTS_DIR" "$SKILLS_DIR" "$TARGET"
mkdir -p "$AGENTS_DIR" "$SKILLS_DIR" "$TARGET"
cat > "$AGENTS_DIR/stable-reviewer.md" <<'EOF'
# Stable Reviewer
EOF
cat > "$AGENTS_DIR/draft-notes.md" <<'EOF'
# Draft Notes
EOF
cat > "$AGENTS_DIR/draft-checklist.md" <<'EOF'
# Draft Checklist
EOF
cat > "$BASE/config.yaml" <<'EOF'
source: ~/.config/skillshare/skills
targets:
claude:
agents:
path: ~/.claude/agents
EOF
ss sync agents -g >/dev/null
find "$TARGET" -maxdepth 1 -type l -printf 'before: %f\n' | sort
cat > "$BASE/config.yaml" <<'EOF'
source: ~/.config/skillshare/skills
targets:
claude:
agents:
path: ~/.claude/agents
exclude: [draft-*]
EOF
ss sync agents -g >/dev/null
find "$TARGET" -maxdepth 1 \( -type l -o -type f \) -printf 'after: %f\n' | sort
test -L "$TARGET/stable-reviewer.md" && echo "stable-reviewer linked=yes" || echo "stable-reviewer linked=no"
test ! -e "$TARGET/draft-notes.md" && echo "draft-notes present=no" || echo "draft-notes present=yes"
test ! -e "$TARGET/draft-checklist.md" && echo "draft-checklist present=no" || echo "draft-checklist present=yes"
```
Expected:
- exit_code: 0
- before: draft-checklist.md
- before: draft-notes.md
- before: stable-reviewer.md
- after: stable-reviewer.md
- Not after: draft-notes.md
- Not after: draft-checklist.md
- stable-reviewer linked=yes
- draft-notes present=no
- draft-checklist present=no
### 3. Nested agents are filtered by flattened target filename
```bash
set -e
BASE=~/.config/skillshare
AGENTS_DIR="$BASE/agents"
SKILLS_DIR="$BASE/skills"
TARGET=~/.claude/agents
rm -rf "$AGENTS_DIR" "$SKILLS_DIR" "$TARGET"
mkdir -p "$AGENTS_DIR/team/backend" "$AGENTS_DIR/solo" "$SKILLS_DIR" "$TARGET"
cat > "$AGENTS_DIR/team/backend/reviewer.md" <<'EOF'
# Nested Team Reviewer
EOF
cat > "$AGENTS_DIR/solo/helper.md" <<'EOF'
# Solo Helper
EOF
cat > "$BASE/config.yaml" <<'EOF'
source: ~/.config/skillshare/skills
targets:
claude:
agents:
path: ~/.claude/agents
include: [team__*]
EOF
ss sync agents -g >/dev/null
find "$TARGET" -maxdepth 1 \( -type l -o -type f \) -printf 'after: %f\n' | sort
test -L "$TARGET/team__backend__reviewer.md" && echo "team__backend__reviewer linked=yes" || echo "team__backend__reviewer linked=no"
test ! -e "$TARGET/solo__helper.md" && echo "solo__helper present=no" || echo "solo__helper present=yes"
```
Expected:
- exit_code: 0
- after: team__backend__reviewer.md
- Not after: solo__helper.md
- team__backend__reviewer linked=yes
- solo__helper present=no
## Pass Criteria
- Include filters prune already-synced non-matching agents on the next `sync agents`
- Exclude filters remove matching agents from the target while keeping non-matching ones
- Nested agent paths are matched against flattened target filenames
@@ -0,0 +1,197 @@
# CLI E2E Runbook: Collect Multiple Targets
Validates that `ss collect` requires an explicit target name or `--all` when
multiple eligible targets are configured. Covers both skills and agents in
global and project modes.
## Scope
- Global `collect` plain-text warning for skills
- Global `collect --json` error envelope for skills
- Global `collect agents` plain-text warning
- Global `collect agents --json` error envelope
- Project `collect -p` plain-text warning for skills
- Project `collect -p --json` error envelope for skills
- Project `collect -p agents` plain-text warning
- Project `collect -p agents --json` error envelope
## Environment
- Run inside devcontainer via mdproof
- Global steps use mdproof's default initialized HOME
- Project steps create a fresh project under `/tmp`
- JSON error steps intentionally swallow the non-zero exit code and assert on
the returned error object
## Steps
### Step 1: Global collect skills warns when multiple targets exist
```bash
set -e
rm -rf /tmp/collect-multi-global-skills
mkdir -p \
/tmp/collect-multi-global-skills/.config \
/tmp/collect-multi-global-skills/.local/share \
/tmp/collect-multi-global-skills/.local/state \
/tmp/collect-multi-global-skills/.cache \
/tmp/collect-multi-global-skills/.claude \
/tmp/collect-multi-global-skills/.cursor
HOME=/tmp/collect-multi-global-skills /workspace/bin/skillshare init -g --force --all-targets --no-git --no-skill >/dev/null 2>&1
OUTPUT=$(HOME=/tmp/collect-multi-global-skills /workspace/bin/skillshare collect -g 2>&1)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- Multiple targets found. Specify a target name or use --all
- claude
- cursor
- universal
### Step 2: Global collect skills --json returns an error envelope
```bash
set -e
rm -rf /tmp/collect-multi-global-skills-json
mkdir -p \
/tmp/collect-multi-global-skills-json/.config \
/tmp/collect-multi-global-skills-json/.local/share \
/tmp/collect-multi-global-skills-json/.local/state \
/tmp/collect-multi-global-skills-json/.cache \
/tmp/collect-multi-global-skills-json/.claude \
/tmp/collect-multi-global-skills-json/.cursor
HOME=/tmp/collect-multi-global-skills-json /workspace/bin/skillshare init -g --force --all-targets --no-git --no-skill >/dev/null 2>&1
OUTPUT=$(HOME=/tmp/collect-multi-global-skills-json /workspace/bin/skillshare collect --json -g 2>&1 || true)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .error == "multiple targets found; specify a target name or use --all"
### Step 3: Global collect agents warns when multiple agent targets exist
```bash
set -e
rm -rf /tmp/collect-multi-global-agents
mkdir -p \
/tmp/collect-multi-global-agents/.config \
/tmp/collect-multi-global-agents/.local/share \
/tmp/collect-multi-global-agents/.local/state \
/tmp/collect-multi-global-agents/.cache \
/tmp/collect-multi-global-agents/.claude \
/tmp/collect-multi-global-agents/.cursor
HOME=/tmp/collect-multi-global-agents /workspace/bin/skillshare init -g --force --all-targets --no-git --no-skill >/dev/null 2>&1
OUTPUT=$(HOME=/tmp/collect-multi-global-agents /workspace/bin/skillshare collect agents -g 2>&1)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- Multiple targets found. Specify a target name or use --all
- claude
- cursor
### Step 4: Global collect agents --json returns an error envelope
```bash
set -e
rm -rf /tmp/collect-multi-global-agents-json
mkdir -p \
/tmp/collect-multi-global-agents-json/.config \
/tmp/collect-multi-global-agents-json/.local/share \
/tmp/collect-multi-global-agents-json/.local/state \
/tmp/collect-multi-global-agents-json/.cache \
/tmp/collect-multi-global-agents-json/.claude \
/tmp/collect-multi-global-agents-json/.cursor
HOME=/tmp/collect-multi-global-agents-json /workspace/bin/skillshare init -g --force --all-targets --no-git --no-skill >/dev/null 2>&1
OUTPUT=$(HOME=/tmp/collect-multi-global-agents-json /workspace/bin/skillshare collect agents --json -g 2>&1 || true)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .error == "multiple targets found; specify a target name or use --all"
### Step 5: Project collect skills warns when multiple targets exist
```bash
set -e
rm -rf /tmp/collect-multi-project-skills
mkdir -p /tmp/collect-multi-project-skills
cd /tmp/collect-multi-project-skills
ss init -p --targets claude,cursor >/dev/null 2>&1
OUTPUT=$(ss collect -p 2>&1)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- Multiple targets found. Specify a target name or use --all
- claude
- cursor
### Step 6: Project collect skills --json returns an error envelope
```bash
set -e
rm -rf /tmp/collect-multi-project-skills-json
mkdir -p /tmp/collect-multi-project-skills-json
cd /tmp/collect-multi-project-skills-json
ss init -p --targets claude,cursor >/dev/null 2>&1
OUTPUT=$(ss collect --json -p 2>&1 || true)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .error == "multiple targets found; specify a target name or use --all"
### Step 7: Project collect agents warns when multiple agent targets exist
```bash
set -e
rm -rf /tmp/collect-multi-project-agents
mkdir -p /tmp/collect-multi-project-agents
cd /tmp/collect-multi-project-agents
ss init -p --targets claude,cursor >/dev/null 2>&1
OUTPUT=$(ss collect agents -p 2>&1)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- Multiple targets found. Specify a target name or use --all
- claude
- cursor
### Step 8: Project collect agents --json returns an error envelope
```bash
set -e
rm -rf /tmp/collect-multi-project-agents-json
mkdir -p /tmp/collect-multi-project-agents-json
cd /tmp/collect-multi-project-agents-json
ss init -p --targets claude,cursor >/dev/null 2>&1
OUTPUT=$(ss collect agents --json -p 2>&1 || true)
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .error == "multiple targets found; specify a target name or use --all"
## Pass Criteria
- All 8 steps pass
- Plain-text collect warns instead of silently collecting from multiple targets
- JSON collect returns a structured error envelope with the exact target-selection error
@@ -0,0 +1,249 @@
# CLI E2E Runbook: Collect Overwrite Semantics
Validates source-conflict behavior for `ss collect`: default collect skips
existing source content, `--force` overwrites, and `--json` implies force.
Covers skills and agents in global and project modes.
## Scope
- Global skills skip without force
- Global skills `--json` overwrites existing source
- Global agents skip without force
- Global agents `--force --json` overwrites existing source
- Project skills skip without force
- Project skills `--force --json` overwrites existing source
- Project agents skip without force
- Project agents `--json` overwrites existing source
## Environment
- Run inside devcontainer via mdproof
- Global steps use a fresh mdproof HOME
- Project steps create fresh projects under `/tmp`
- Skip steps use `printf 'y\n'` to confirm the collect action, then assert the
source content remains unchanged
- Overwrite steps keep stdout as pure JSON and verify file content silently
## Steps
### Step 1: Global collect skills skips an existing source skill by default
```bash
set -e
mkdir -p ~/.config/skillshare/skills/dupe-skill ~/.claude/skills/dupe-skill
cat > ~/.config/skillshare/skills/dupe-skill/SKILL.md <<'EOF'
# Source Skill
Source version survives.
EOF
cat > ~/.claude/skills/dupe-skill/SKILL.md <<'EOF'
# Target Skill
Target version should not overwrite.
EOF
OUTPUT=$(printf 'y\n' | ss collect claude -g 2>&1)
grep -q "Source version survives." ~/.config/skillshare/skills/dupe-skill/SKILL.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- already exists in source
- 1 skipped
### Step 2: Global collect skills --json overwrites the existing source skill
```bash
set -e
mkdir -p ~/.config/skillshare/skills/dupe-skill ~/.claude/skills/dupe-skill
cat > ~/.config/skillshare/skills/dupe-skill/SKILL.md <<'EOF'
# Source Skill
Old source version.
EOF
cat > ~/.claude/skills/dupe-skill/SKILL.md <<'EOF'
# Target Skill
Target version wins via json.
EOF
OUTPUT=$(ss collect claude --json -g)
grep -q "Target version wins via json." ~/.config/skillshare/skills/dupe-skill/SKILL.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .pulled == ["dupe-skill"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 3: Global collect agents skips an existing source agent by default
```bash
set -e
mkdir -p ~/.config/skillshare/agents ~/.claude/agents
cat > ~/.config/skillshare/agents/dupe-agent.md <<'EOF'
# Source Agent
Source agent survives.
EOF
cat > ~/.claude/agents/dupe-agent.md <<'EOF'
# Target Agent
Target agent should not overwrite.
EOF
OUTPUT=$(printf 'y\n' | ss collect agents claude -g 2>&1)
grep -q "Source agent survives." ~/.config/skillshare/agents/dupe-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- already exists in source
- 1 skipped
### Step 4: Global collect agents --force --json overwrites the existing source agent
```bash
set -e
mkdir -p ~/.config/skillshare/agents ~/.claude/agents
cat > ~/.config/skillshare/agents/dupe-agent.md <<'EOF'
# Source Agent
Old source agent.
EOF
cat > ~/.claude/agents/dupe-agent.md <<'EOF'
# Target Agent
Target agent force wins.
EOF
OUTPUT=$(ss collect agents claude --force --json -g)
grep -q "Target agent force wins." ~/.config/skillshare/agents/dupe-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .pulled == ["dupe-agent.md"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 5: Project collect skills skips an existing source skill by default
```bash
set -e
rm -rf /tmp/collect-overwrite-project-skills-skip
mkdir -p /tmp/collect-overwrite-project-skills-skip
cd /tmp/collect-overwrite-project-skills-skip
ss init -p --targets claude >/dev/null 2>&1
mkdir -p .skillshare/skills/dupe-skill .claude/skills/dupe-skill
cat > .skillshare/skills/dupe-skill/SKILL.md <<'EOF'
# Source Skill
Project source survives.
EOF
cat > .claude/skills/dupe-skill/SKILL.md <<'EOF'
# Target Skill
Project target should not overwrite.
EOF
OUTPUT=$(printf 'y\n' | ss collect claude -p 2>&1)
grep -q "Project source survives." .skillshare/skills/dupe-skill/SKILL.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- already exists in source
- 1 skipped
### Step 6: Project collect skills --force --json overwrites the existing source skill
```bash
set -e
rm -rf /tmp/collect-overwrite-project-skills-force
mkdir -p /tmp/collect-overwrite-project-skills-force
cd /tmp/collect-overwrite-project-skills-force
ss init -p --targets claude >/dev/null 2>&1
mkdir -p .skillshare/skills/dupe-skill .claude/skills/dupe-skill
cat > .skillshare/skills/dupe-skill/SKILL.md <<'EOF'
# Source Skill
Old project source.
EOF
cat > .claude/skills/dupe-skill/SKILL.md <<'EOF'
# Target Skill
Project force overwrite wins.
EOF
OUTPUT=$(ss collect claude --force --json -p)
grep -q "Project force overwrite wins." .skillshare/skills/dupe-skill/SKILL.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .pulled == ["dupe-skill"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 7: Project collect agents skips an existing source agent by default
```bash
set -e
rm -rf /tmp/collect-overwrite-project-agents-skip
mkdir -p /tmp/collect-overwrite-project-agents-skip
cd /tmp/collect-overwrite-project-agents-skip
ss init -p --targets claude >/dev/null 2>&1
mkdir -p .skillshare/agents .claude/agents
cat > .skillshare/agents/dupe-agent.md <<'EOF'
# Source Agent
Project source agent survives.
EOF
cat > .claude/agents/dupe-agent.md <<'EOF'
# Target Agent
Project target agent should not overwrite.
EOF
OUTPUT=$(printf 'y\n' | ss collect agents claude -p 2>&1)
grep -q "Project source agent survives." .skillshare/agents/dupe-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- already exists in source
- 1 skipped
### Step 8: Project collect agents --json overwrites the existing source agent
```bash
set -e
rm -rf /tmp/collect-overwrite-project-agents-json
mkdir -p /tmp/collect-overwrite-project-agents-json
cd /tmp/collect-overwrite-project-agents-json
ss init -p --targets claude >/dev/null 2>&1
mkdir -p .skillshare/agents .claude/agents
cat > .skillshare/agents/dupe-agent.md <<'EOF'
# Source Agent
Old project source agent.
EOF
cat > .claude/agents/dupe-agent.md <<'EOF'
# Target Agent
Project json overwrite wins.
EOF
OUTPUT=$(ss collect agents claude --json -p)
grep -q "Project json overwrite wins." .skillshare/agents/dupe-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .pulled == ["dupe-agent.md"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
## Pass Criteria
- All 8 steps pass
- Default collect preserves existing source content for both skills and agents
- Explicit `--force` and implicit force via `--json` overwrite existing source content
@@ -0,0 +1,230 @@
# CLI E2E Runbook: Collect Skills and Agents
Validates `ss collect` for both resource kinds across global and project modes.
Each step is self-contained because mdproof setup provides a fresh initialized
environment and `/tmp` is shared across runs.
## Scope
- Global `collect` for skills with `--dry-run --json`
- Global `collect` for skills with real writes to source
- Global `collect agents` with `--dry-run --json`
- Global `collect agents` with real writes to source
- Project `collect -p` JSON output for skills
- Project `collect -p agents --dry-run --json` does not write
- Project `collect -p agents --json` writes to `.skillshare/agents`
## Environment
- Run inside devcontainer via mdproof
- Global steps use `-g` and explicitly target `claude`
- Project steps create fresh projects under `/tmp`
- Assertions rely on `--json` output plus silent file-system checks
## Steps
### Step 1: Global collect skills dry-run previews without writing
```bash
set -e
rm -rf ~/.claude/skills/collect-dry-skill ~/.config/skillshare/skills/collect-dry-skill
mkdir -p ~/.claude/skills/collect-dry-skill
cat > ~/.claude/skills/collect-dry-skill/SKILL.md <<'EOF'
# Collect Dry Skill
EOF
OUTPUT=$(ss collect claude --json --dry-run -g)
test ! -e ~/.config/skillshare/skills/collect-dry-skill
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .dry_run == true
- jq: .pulled == ["collect-dry-skill"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 2: Global collect skills copies a local skill to source
```bash
set -e
rm -rf \
~/.claude/skills/collect-dry-skill \
~/.claude/skills/collect-live-skill \
~/.config/skillshare/skills/collect-dry-skill \
~/.config/skillshare/skills/collect-live-skill
mkdir -p ~/.claude/skills/collect-live-skill
cat > ~/.claude/skills/collect-live-skill/SKILL.md <<'EOF'
# Collect Live Skill
Collected from target.
EOF
OUTPUT=$(ss collect claude --json -g)
test -f ~/.config/skillshare/skills/collect-live-skill/SKILL.md
grep -q "Collected from target." ~/.config/skillshare/skills/collect-live-skill/SKILL.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .dry_run == false
- jq: .pulled == ["collect-live-skill"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 3: Global collect agents dry-run previews without writing
```bash
set -e
rm -f ~/.claude/agents/collect-dry-agent.md ~/.config/skillshare/agents/collect-dry-agent.md
mkdir -p ~/.claude/agents
cat > ~/.claude/agents/collect-dry-agent.md <<'EOF'
---
name: collect-dry-agent
description: Dry-run agent
---
# Collect Dry Agent
EOF
OUTPUT=$(ss collect agents claude --json --dry-run -g)
test ! -e ~/.config/skillshare/agents/collect-dry-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .dry_run == true
- jq: .pulled == ["collect-dry-agent.md"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 4: Global collect agents copies a local agent to source
```bash
set -e
rm -f \
~/.claude/agents/collect-dry-agent.md \
~/.claude/agents/collect-live-agent.md \
~/.config/skillshare/agents/collect-dry-agent.md \
~/.config/skillshare/agents/collect-live-agent.md
mkdir -p ~/.claude/agents
cat > ~/.claude/agents/collect-live-agent.md <<'EOF'
---
name: collect-live-agent
description: Live collect agent
---
# Collect Live Agent
Collected from target.
EOF
OUTPUT=$(ss collect agents claude --json -g)
test -f ~/.config/skillshare/agents/collect-live-agent.md
grep -q "Collected from target." ~/.config/skillshare/agents/collect-live-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .dry_run == false
- jq: .pulled == ["collect-live-agent.md"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 5: Project collect skills outputs JSON and writes into .skillshare/skills
```bash
set -e
rm -rf /tmp/collect-project-skills
mkdir -p /tmp/collect-project-skills
cd /tmp/collect-project-skills
ss init -p --targets claude >/dev/null 2>&1
mkdir -p .claude/skills/project-collect-skill
cat > .claude/skills/project-collect-skill/SKILL.md <<'EOF'
# Project Collect Skill
Collected into project source.
EOF
OUTPUT=$(ss collect claude --json -p)
test -f .skillshare/skills/project-collect-skill/SKILL.md
grep -q "Collected into project source." .skillshare/skills/project-collect-skill/SKILL.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .dry_run == false
- jq: .pulled == ["project-collect-skill"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 6: Project collect agents dry-run previews without writing
```bash
set -e
rm -rf /tmp/collect-project-agents-dry
mkdir -p /tmp/collect-project-agents-dry
cd /tmp/collect-project-agents-dry
ss init -p --targets claude >/dev/null 2>&1
mkdir -p .claude/agents
cat > .claude/agents/project-dry-agent.md <<'EOF'
---
name: project-dry-agent
description: Project dry-run agent
---
# Project Dry Agent
EOF
OUTPUT=$(ss collect agents claude --json --dry-run -p)
test ! -e .skillshare/agents/project-dry-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .dry_run == true
- jq: .pulled == ["project-dry-agent.md"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
### Step 7: Project collect agents outputs JSON and writes into .skillshare/agents
```bash
set -e
rm -rf /tmp/collect-project-agents-live
mkdir -p /tmp/collect-project-agents-live
cd /tmp/collect-project-agents-live
ss init -p --targets claude >/dev/null 2>&1
mkdir -p .claude/agents
cat > .claude/agents/project-live-agent.md <<'EOF'
---
name: project-live-agent
description: Project live agent
---
# Project Live Agent
Collected into project agent source.
EOF
OUTPUT=$(ss collect agents claude --json -p)
test -f .skillshare/agents/project-live-agent.md
grep -q "Collected into project agent source." .skillshare/agents/project-live-agent.md
printf '%s\n' "$OUTPUT"
```
Expected:
- exit_code: 0
- jq: .dry_run == false
- jq: .pulled == ["project-live-agent.md"]
- jq: (.skipped | length) == 0
- jq: (.failed | length) == 0
## Pass Criteria
- All 7 steps exit successfully
- Dry-run steps report `dry_run: true` and do not write to source
- Global collect writes to `~/.config/skillshare/skills` and `~/.config/skillshare/agents`
- Project collect writes to `.skillshare/skills` and `.skillshare/agents`
- All collect commands emit valid JSON without UI noise on stdout
+23 -23
View File
@@ -25,7 +25,7 @@ Run inside devcontainer.
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents/curriculum
mkdir -p ~/.config/skillshare/extras/agents/software
echo "# Tactician" > ~/.config/skillshare/extras/agents/curriculum/tactician.md
@@ -33,25 +33,25 @@ echo "# Planner" > ~/.config/skillshare/extras/agents/curriculum/planner.md
echo "# Implementer" > ~/.config/skillshare/extras/agents/software/implementer.md
echo "# Reviewer" > ~/.config/skillshare/extras/agents/reviewer.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss sync extras --json -g
```
Expected:
- exit_code: 0
- jq: .extras[0].targets[0].synced == 4
- jq: [.extras[] | select(.name == "agents")][0].targets[0].synced == 4
### 2. Verify flat file layout — no subdirectories in target
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents/sub1 ~/.config/skillshare/extras/agents/sub2
echo "a" > ~/.config/skillshare/extras/agents/sub1/a.md
echo "b" > ~/.config/skillshare/extras/agents/sub2/b.md
echo "c" > ~/.config/skillshare/extras/agents/root.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss sync extras -g >/dev/null
echo "files=$(find ~/.claude/agents/ -maxdepth 1 -name '*.md' | wc -l)"
echo "dirs=$(find ~/.claude/agents/ -mindepth 1 -type d | wc -l)"
@@ -66,11 +66,11 @@ Expected:
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents
echo "x" > ~/.config/skillshare/extras/agents/x.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss extras list --json -g
```
@@ -82,32 +82,32 @@ Expected:
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents/team-a
mkdir -p ~/.config/skillshare/extras/agents/team-b
echo "# From team-a" > ~/.config/skillshare/extras/agents/team-a/agent.md
echo "# From team-b" > ~/.config/skillshare/extras/agents/team-b/agent.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss sync extras --json -g
```
Expected:
- exit_code: 0
- jq: .extras[0].targets[0].synced == 1
- jq: .extras[0].targets[0].skipped == 1
- jq: .extras[0].targets[0].warnings | length == 1
- jq: [.extras[] | select(.name == "agents")][0].targets[0].synced == 1
- jq: [.extras[] | select(.name == "agents")][0].targets[0].skipped == 1
- jq: [.extras[] | select(.name == "agents")][0].targets[0].warnings | length == 1
### 5. Flatten collision warning in human-readable output
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents/a ~/.config/skillshare/extras/agents/b
echo "1" > ~/.config/skillshare/extras/agents/a/same.md
echo "2" > ~/.config/skillshare/extras/agents/b/same.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss sync extras -g
```
@@ -119,11 +119,11 @@ Expected:
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents
echo "x" > ~/.config/skillshare/extras/agents/x.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss extras agents --no-flatten -g >/dev/null
ss extras list --json -g
```
@@ -136,11 +136,11 @@ Expected:
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents
echo "x" > ~/.config/skillshare/extras/agents/x.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents -g >/dev/null
ss extras init agents --target ~/.claude/agents -g >/dev/null 2>&1
ss extras agents --flatten -g >/dev/null
ss extras list --json -g
```
@@ -153,11 +153,11 @@ Expected:
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents
echo "x" > ~/.config/skillshare/extras/agents/x.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss extras agents --mode symlink -g 2>&1 || true
```
@@ -168,12 +168,12 @@ Expected:
```bash
ss extras remove agents --force -g >/dev/null 2>&1 || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents 2>/dev/null || true
rm -rf ~/.claude/agents ~/.config/skillshare/extras/agents ~/.config/skillshare/agents 2>/dev/null || true
mkdir -p ~/.config/skillshare/extras/agents/sub
echo "# Keep" > ~/.config/skillshare/extras/agents/sub/keep.md
echo "# Remove" > ~/.config/skillshare/extras/agents/sub/remove.md
mkdir -p ~/.claude/agents
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null
ss extras init agents --target ~/.claude/agents --flatten -g >/dev/null 2>&1
ss sync extras -g >/dev/null
rm ~/.config/skillshare/extras/agents/sub/remove.md
ss sync extras --json -g
@@ -181,7 +181,7 @@ ss sync extras --json -g
Expected:
- exit_code: 0
- jq: .extras[0].targets[0].pruned == 1
- jq: [.extras[] | select(.name == "agents")][0].targets[0].pruned == 1
## Pass Criteria
@@ -0,0 +1,200 @@
# CLI E2E Runbook: Install Mixed Repo (Skills + Agents)
Validates that `skillshare install` from a repo containing both skills and agents
installs skills to the skills source and agents to the agents source, then sync
distributes agents only to targets with an agents path configured.
**Origin**: Bug fix — agents from mixed repos were incorrectly ignored or installed to skills dir.
## Scope
- Mixed repo install: skills go to `~/.config/skillshare/skills/`, agents go to `~/.config/skillshare/agents/`
- Pure agent repo install: agents go to agents dir
- Sync agents: targets with agents path receive agents, targets without are skipped with warning
- Project mode: agents go to `.skillshare/agents/`, not global agents dir
## Environment
Run inside devcontainer via mdproof (no ssenv wrapper needed).
All global commands use `-g` to force global mode.
## Steps
### 1. Create mixed git repo with skills and agents
```bash
rm -rf /tmp/mixed-repo
mkdir -p /tmp/mixed-repo/skills/demo-skill /tmp/mixed-repo/agents
cat > /tmp/mixed-repo/skills/demo-skill/SKILL.md <<'EOF'
---
name: demo-skill
---
# Demo Skill
A demo skill for testing.
EOF
cat > /tmp/mixed-repo/agents/demo-agent.md <<'EOF'
---
name: demo-agent
description: A demo agent
---
# Demo Agent
A demo agent for testing.
EOF
cd /tmp/mixed-repo && git init && git config user.email "test@test.com" && git config user.name "test" && git add -A && git commit -m "init" 2>&1
ls skills/demo-skill/SKILL.md agents/demo-agent.md
```
Expected:
- exit_code: 0
- SKILL.md
- demo-agent.md
### 2. Install mixed repo — both skills and agents found
```bash
ss install -g file:///tmp/mixed-repo --yes --force
```
Expected:
- exit_code: 0
- regex: 1 skill\(s\), 1 agent\(s\)
- Installed: demo-skill
- Installed agent: demo-agent
### 3. Verify skill in skills source, agent in agents source
```bash
SKILLS_DIR=~/.config/skillshare/skills
AGENTS_DIR=~/.config/skillshare/agents
test -f "$SKILLS_DIR/demo-skill/SKILL.md" && echo "skill: in skills dir" || echo "skill: MISSING"
test -f "$AGENTS_DIR/demo-agent.md" && echo "agent: in agents dir" || echo "agent: MISSING"
test -f "$SKILLS_DIR/demo-agent.md" && echo "agent: WRONG in skills dir" || echo "agent: not in skills dir (correct)"
```
Expected:
- exit_code: 0
- skill: in skills dir
- agent: in agents dir
- agent: not in skills dir (correct)
- Not MISSING
- Not WRONG
### 4. Sync all — agents go to targets with agents path
```bash
ss sync all -g
```
Expected:
- exit_code: 0
### 5. Verify agents synced to claude (has agents path) but not to targets without
```bash
CLAUDE_AGENTS=~/.claude/agents
test -L "$CLAUDE_AGENTS/demo-agent.md" && echo "claude: agent synced" || echo "claude: agent MISSING"
```
Expected:
- exit_code: 0
- claude: agent synced
- Not MISSING
### 6. Sync agents — warning lists targets without agents path
```bash
ss sync agents -g 2>&1
```
Expected:
- exit_code: 0
- regex: skipped for agents
### 7. Create pure agent repo and install
```bash
rm -rf /tmp/agent-only-repo
mkdir -p /tmp/agent-only-repo/agents
cat > /tmp/agent-only-repo/agents/helper.md <<'EOF'
---
name: helper
description: A helper agent
---
# Helper Agent
EOF
cd /tmp/agent-only-repo && git init && git config user.email "test@test.com" && git config user.name "test" && git add -A && git commit -m "init" 2>&1
ss install -g file:///tmp/agent-only-repo --yes --force
```
Expected:
- exit_code: 0
- regex: 1 agent\(s\)
- helper
### 8. Verify pure agent repo installed to agents dir
```bash
AGENTS_DIR=~/.config/skillshare/agents
test -f "$AGENTS_DIR/helper.md" && echo "helper: in agents dir" || echo "helper: MISSING"
SKILLS_DIR=~/.config/skillshare/skills
test -d "$SKILLS_DIR/helper" && echo "helper: WRONG in skills dir" || echo "helper: not in skills dir (correct)"
```
Expected:
- exit_code: 0
- helper: in agents dir
- helper: not in skills dir (correct)
- Not MISSING
- Not WRONG
### 9. Project mode — install mixed repo to project agents dir
```bash
rm -rf /tmp/test-project
mkdir -p /tmp/test-project
cd /tmp/test-project
ss init -p --targets claude 2>&1
ss install -p file:///tmp/mixed-repo --yes --force 2>&1
```
Expected:
- exit_code: 0
- Installed: demo-skill
- Installed agent: demo-agent
### 10. Verify project mode paths
```bash
cd /tmp/test-project
test -f .skillshare/skills/demo-skill/SKILL.md && echo "project skill: correct" || echo "project skill: MISSING"
test -f .skillshare/agents/demo-agent.md && echo "project agent: correct" || echo "project agent: MISSING"
GLOBAL_AGENTS=~/.config/skillshare/agents
test -f "$GLOBAL_AGENTS/demo-agent.md" && echo "global agent: EXISTS (wrong for project install)" || echo "global agent: not there (correct)"
```
Expected:
- exit_code: 0
- project skill: correct
- project agent: correct
- Not MISSING
### 11. Cleanup
```bash
rm -rf /tmp/mixed-repo /tmp/agent-only-repo /tmp/test-project
ss uninstall demo-skill --force -g 2>/dev/null || true
ss uninstall agents --all --force -g 2>/dev/null || true
```
Expected:
- exit_code: 0
## Pass Criteria
- [ ] Mixed repo install shows "N skill(s), N agent(s)" in Found message
- [ ] Skills installed to skills source dir
- [ ] Agents installed to agents source dir (not skills dir)
- [ ] Pure agent repo installs agents correctly
- [ ] Sync distributes agents to targets with agents path
- [ ] Sync shows warning listing targets without agents path
- [ ] Project mode install puts agents in `.skillshare/agents/`, not global
@@ -0,0 +1,187 @@
# Issue #124: Orchestrator Repo Install
Verify that repos with root + child skills install children as independent skills, root appears in selection, and blob URLs resolve correctly.
Repo structure under test:
```
SKILL.md (root: name derived from repo dir)
src/main.go
skills/
writer/SKILL.md (child: "writer")
reader/SKILL.md (child: "reader")
```
## Steps
### Step 1: Create local orchestrator repo
```bash
rm -rf /tmp/orchestrator-repo
mkdir -p /tmp/orchestrator-repo/skills/writer /tmp/orchestrator-repo/skills/reader /tmp/orchestrator-repo/src
git config --global user.email "test@test.com" 2>/dev/null
git config --global user.name "Test" 2>/dev/null
cat > /tmp/orchestrator-repo/SKILL.md << 'SKILL'
---
name: office-cli
description: Office CLI orchestrator
---
# Office CLI
Root skill for the orchestrator pack.
SKILL
cat > /tmp/orchestrator-repo/src/main.go << 'GO'
package main
func main() {}
GO
cat > /tmp/orchestrator-repo/skills/writer/SKILL.md << 'SKILL'
---
name: writer
description: Writer skill
---
# Writer
A child skill for writing.
SKILL
echo "# Writer docs" > /tmp/orchestrator-repo/skills/writer/README.md
cat > /tmp/orchestrator-repo/skills/reader/SKILL.md << 'SKILL'
---
name: reader
description: Reader skill
---
# Reader
A child skill for reading.
SKILL
cd /tmp/orchestrator-repo && git init -q && git add -A && git commit -m "init" -q
echo "REPO_READY"
```
Expected:
- exit_code: 0
- REPO_READY
### Step 2: Install all skills with --json
Install the orchestrator repo using `--json --all` to skip prompts. Verify 3 independent skills are installed. Root name = `orchestrator-repo` (from directory).
```bash
/workspace/bin/skillshare install file:///tmp/orchestrator-repo --json --all -g 2>/dev/null
```
Expected:
- exit_code: 0
- jq: .skills | length == 3
- jq: .skills | sort | . == ["orchestrator-repo","reader","writer"]
- jq: .failed | length == 0
### Step 3: Root dir does NOT contain child skill dirs
Root copy should exclude `skills/writer/` and `skills/reader/` but keep `src/`.
```bash
ROOT_DIR="$HOME/.config/skillshare/skills/orchestrator-repo"
echo "ROOT_EXISTS=$(test -d "$ROOT_DIR" && echo yes || echo no)"
echo "ROOT_SKILL_MD=$(test -f "$ROOT_DIR/SKILL.md" && echo yes || echo no)"
echo "ROOT_SRC=$(test -d "$ROOT_DIR/src" && echo yes || echo no)"
echo "NO_CHILD_WRITER=$(test -d "$ROOT_DIR/skills/writer" && echo LEAKED || echo clean)"
echo "NO_CHILD_READER=$(test -d "$ROOT_DIR/skills/reader" && echo LEAKED || echo clean)"
```
Expected:
- exit_code: 0
- ROOT_EXISTS=yes
- ROOT_SKILL_MD=yes
- ROOT_SRC=yes
- NO_CHILD_WRITER=clean
- NO_CHILD_READER=clean
### Step 4: Children exist as siblings under parent
Children at `orchestrator-repo/writer/` and `orchestrator-repo/reader/`, each with own SKILL.md.
```bash
SKILLS_DIR="$HOME/.config/skillshare/skills"
echo "WRITER_EXISTS=$(test -f "$SKILLS_DIR/orchestrator-repo/writer/SKILL.md" && echo yes || echo no)"
echo "READER_EXISTS=$(test -f "$SKILLS_DIR/orchestrator-repo/reader/SKILL.md" && echo yes || echo no)"
echo "WRITER_README=$(test -f "$SKILLS_DIR/orchestrator-repo/writer/README.md" && echo yes || echo no)"
```
Expected:
- exit_code: 0
- WRITER_EXISTS=yes
- READER_EXISTS=yes
- WRITER_README=yes
### Step 5: All 3 skills appear independently in list
```bash
/workspace/bin/skillshare list --json -g 2>/dev/null
```
Expected:
- exit_code: 0
- jq: [.[] | .name] | sort | . == ["orchestrator-repo","orchestrator-repo__reader","orchestrator-repo__writer"]
### Step 6: Install root skill only via --skill filter
Root skill is individually selectable (issue #124 fix: root included in selection).
```bash
/workspace/bin/skillshare uninstall --all -g --force >/dev/null 2>&1
/workspace/bin/skillshare install file:///tmp/orchestrator-repo --json --skill orchestrator-repo -g 2>/dev/null
```
Expected:
- exit_code: 0
- jq: .skills == ["orchestrator-repo"]
### Step 7: Root-only install has no child content
```bash
SKILLS_DIR="$HOME/.config/skillshare/skills"
echo "ROOT_EXISTS=$(test -f "$SKILLS_DIR/orchestrator-repo/SKILL.md" && echo yes || echo no)"
echo "NO_WRITER=$(test -d "$SKILLS_DIR/orchestrator-repo/writer" && echo LEAKED || echo clean)"
echo "NO_READER=$(test -d "$SKILLS_DIR/orchestrator-repo/reader" && echo LEAKED || echo clean)"
```
Expected:
- exit_code: 0
- ROOT_EXISTS=yes
- NO_WRITER=clean
- NO_READER=clean
### Step 8: Install child-only without root
```bash
/workspace/bin/skillshare uninstall --all -g --force >/dev/null 2>&1
/workspace/bin/skillshare install file:///tmp/orchestrator-repo --json --skill writer -g 2>/dev/null
```
Expected:
- exit_code: 0
- jq: .skills == ["writer"]
### Step 9: Blob URL parsing — trailing SKILL.md stripped (unit tests)
The blob URL fix resolves `github.com/.../blob/main/skills/foo/SKILL.md` to `subdir="skills/foo"`. Run the specific subtests.
```bash
cd /workspace && go test ./internal/install -run "TestParseSource_GitHubShorthand/github_blob_URL" -count=1 -v 2>&1 | tail -10
```
Expected:
- exit_code: 0
- PASS
- regex: blob_URL
## Pass Criteria
- Steps 2-5: Orchestrator install creates 3 independent skills; root excludes child dirs; children are siblings
- Steps 6-7: Root skill is individually selectable and installs cleanly without child leakage
- Step 8: Child skill installs independently without root
- Step 9: Blob URL unit tests pass, confirming trailing SKILL.md is properly resolved
@@ -0,0 +1,253 @@
# CLI E2E Runbook: Target Command Options (Skills + Agents)
Validates `skillshare target` command options across plain list, JSON list,
target info/settings, and both global/project mode for skill and agent
configuration.
**Origin**: v0.19.x — target settings gained explicit agents options alongside
existing skills options, and docs needed regression coverage against code.
## Scope
- `target help` advertises skill and agent settings flags
- `target list --no-tui` and `target list --json` expose agent metadata for
supported targets while leaving unsupported targets agent-free
- `target <name>` supports `--mode`, `--target-naming`, include/exclude, and
the agent counterparts `--agent-mode`, `--add/remove-agent-include/exclude`
- Agent filter flags are rejected for unsupported targets and for
`agent-mode=symlink`
- Project mode mirrors the same skill/agent target settings behavior
## Environment
Run inside devcontainer via mdproof.
Use `-g`/`-p` explicitly to avoid auto-mode ambiguity.
## Steps
### 1. Help output lists skill and agent target settings
```bash
ss target help
```
Expected:
- exit_code: 0
- --mode
- --agent-mode
- --target-naming
- --add-include
- --add-exclude
- --remove-include
- --remove-exclude
- --add-agent-include
- --add-agent-exclude
- --remove-agent-include
- --remove-agent-exclude
### 2. Global plain target list shows skills and agents sections
```bash
set -e
BASE=~/.config/skillshare
mkdir -p "$BASE/skills/team-alpha" "$BASE/agents" "$HOME/custom-tool/skills"
printf '%s\n' \
'---' \
'name: team-alpha' \
'description: Team Alpha skill' \
'metadata:' \
' targets: [claude]' \
'---' \
'# Team Alpha' \
> "$BASE/skills/team-alpha/SKILL.md"
printf '%s\n' \
'---' \
'name: reviewer' \
'description: Review agent' \
'---' \
'# Reviewer' \
> "$BASE/agents/reviewer.md"
ss target add custom-tool "$HOME/custom-tool/skills" -g
ss target list --no-tui -g
```
Expected:
- exit_code: 0
- claude
- custom-tool
- Skills:
- Agents:
- /.claude/agents
### 3. Global JSON target list includes agent metadata only for supported targets
```bash
ss target list --json -g
```
Expected:
- exit_code: 0
- jq: .targets | length >= 2
- jq: (.targets[] | select(.name == "claude").agentPath | type) == "string"
- jq: (.targets[] | select(.name == "claude").agentMode) == "merge"
- jq: (.targets[] | select(.name == "claude").agentExpectedCount) >= 0
- jq: (.targets[] | select(.name == "custom-tool").agentPath) == null
### 4. Global skill settings flags update target mode, naming, and filters
```bash
set -e
ss target claude --mode copy -g
ss target claude --target-naming standard -g
ss target claude --add-include "team-*" -g
ss target claude --add-exclude "_legacy*" -g
ss target claude -g
```
Expected:
- exit_code: 0
- Changed claude mode: merge -> copy
- Changed claude target naming: flat -> standard
- added include: team-*
- added exclude: _legacy*
- Mode: copy
- Naming: standard
- Include: team-*
- Exclude: _legacy*
### 5. Global agent settings flags update agent mode and agent filters
```bash
set -e
ss target claude --agent-mode copy -g
ss target claude --add-agent-include "team-*" -g
ss target claude --add-agent-exclude "draft-*" -g
ss target claude -g
```
Expected:
- exit_code: 0
- Changed claude agent mode: merge -> copy
- added agent include: team-*
- added agent exclude: draft-*
- Agents:
- Mode: copy
- Include: team-*
- Exclude: draft-*
### 6. Agent filter guard rails reject symlink mode and unsupported targets
```bash
set -e
ss target claude --agent-mode symlink -g
ss target claude -g
set +e
SYMLINK_ERR=$(ss target claude --add-agent-include "retry-*" -g 2>&1)
SYMLINK_STATUS=$?
CUSTOM_ERR=$(ss target custom-tool --add-agent-include "retry-*" -g 2>&1)
CUSTOM_STATUS=$?
set -e
printf 'REJECTED_SYMLINK=%d\n' "$SYMLINK_STATUS"
printf '%s\n' "$SYMLINK_ERR"
printf 'REJECTED_CUSTOM=%d\n' "$CUSTOM_STATUS"
printf '%s\n' "$CUSTOM_ERR"
```
Expected:
- exit_code: 0
- Changed claude agent mode: copy -> symlink
- Filters: ignored in symlink mode
- REJECTED_SYMLINK=1
- ignored in symlink mode
- REJECTED_CUSTOM=1
- target 'custom-tool' does not have an agents path
### 7. Global remove flags clear both skill and agent filters
```bash
set -e
ss target claude --agent-mode copy -g
ss target claude --remove-include "team-*" -g
ss target claude --remove-exclude "_legacy*" -g
ss target claude --remove-agent-include "team-*" -g
ss target claude --remove-agent-exclude "draft-*" -g
ss target claude -g
```
Expected:
- exit_code: 0
- Changed claude agent mode: symlink -> copy
- removed include: team-*
- removed exclude: _legacy*
- removed agent include: team-*
- removed agent exclude: draft-*
- Include: (none)
- Exclude: (none)
### 8. Project mode mirrors skill and agent target settings
```bash
set -e
PROJECT=/tmp/target-options-project
rm -rf "$PROJECT"
mkdir -p "$PROJECT/.skillshare/skills" "$PROJECT/.skillshare/agents"
cat > "$PROJECT/.skillshare/config.yaml" <<'EOF'
targets:
- claude
EOF
cd "$PROJECT"
ss target claude --mode copy -p
ss target claude --target-naming standard -p
ss target claude --add-include "proj-*" -p
ss target claude --add-exclude "draft-*" -p
ss target claude --agent-mode copy -p
ss target claude --add-agent-include "proj-*" -p
ss target claude --add-agent-exclude "draft-*" -p
ss target claude -p
```
Expected:
- exit_code: 0
- Changed claude mode: merge -> copy
- Changed claude target naming: flat -> standard
- added include: proj-*
- added exclude: draft-*
- Changed claude agent mode: merge -> copy
- added agent include: proj-*
- added agent exclude: draft-*
- Mode: copy
- Naming: standard
- Include: proj-*
- Exclude: draft-*
- Agents:
### 9. Project JSON target list includes agent metadata
```bash
cd /tmp/target-options-project
ss target list --json -p
```
Expected:
- exit_code: 0
- jq: .targets | length == 1
- jq: (.targets[0].name) == "claude"
- jq: (.targets[0].agentMode) == "copy"
- jq: (.targets[0].agentInclude) == ["proj-*"]
- jq: (.targets[0].agentExclude) == ["draft-*"]
## Pass Criteria
- The `target` command exposes both skill and agent settings in help and list
output
- Global and project target settings accept and persist skill/agent mode and
include/exclude changes
- Agent-only guard rails behave correctly for unsupported targets and
symlink-mode agent targets
+32 -35
View File
@@ -17,14 +17,14 @@ Verifies `skillshare ui --base-path` serves the dashboard and API under a sub-pa
## Environment
Run inside devcontainer. Uses `/tmp/` for isolated HOME and a fake UI dist.
Server uses port **19421** to avoid conflicts with existing UI on 19420.
Server uses port **49821** to avoid conflicts with existing UI on 19420.
## Step 0: Setup isolated HOME and fake UI dist
```bash
# Kill any leftover servers from previous runs on ports used by this runbook
fuser -k 19421/tcp 2>/dev/null || true
fuser -k 19422/tcp 2>/dev/null || true
# Kill any leftover UI servers from previous test runs
kill $(cat /tmp/basepath-server.pid /tmp/basepath-server2.pid 2>/dev/null) 2>/dev/null || true
rm -f /tmp/basepath-server.pid /tmp/basepath-server2.pid
sleep 1
export E2E_HOME="/tmp/ss-e2e-basepath"
@@ -73,12 +73,13 @@ export XDG_DATA_HOME="$E2E_HOME/.local/share"
export XDG_STATE_HOME="$E2E_HOME/.local/state"
export XDG_CACHE_HOME="$E2E_HOME/.cache"
fuser -k 19421/tcp 2>/dev/null || true
kill $(cat /tmp/basepath-server.pid 2>/dev/null) 2>/dev/null || true
rm -f /tmp/basepath-server.pid
sleep 1
cd /workspace
go run ./cmd/skillshare ui --base-path /skillshare --host 0.0.0.0 --port 19421 --no-open -g > /tmp/basepath-server.log 2>&1 &
/workspace/bin/skillshare ui --base-path /skillshare --host 0.0.0.0 --port 49821 --no-open -g > /tmp/basepath-server.log 2>&1 &
SERVER_PID=$!
echo $SERVER_PID > /tmp/basepath-server.pid
echo "server_pid=$SERVER_PID"
sleep 5
@@ -88,12 +89,12 @@ cat /tmp/basepath-server.log
Expected:
- exit_code: 0
- regex: server_pid=\d+
- regex: running at http://.*:19421/skillshare/
- regex: running at http://.*:49821/skillshare/
## Step 2: API health with prefix returns 200
```bash
curl -sf http://localhost:19421/skillshare/api/health
curl -sf http://localhost:49821/skillshare/api/health
```
Expected:
@@ -103,7 +104,7 @@ Expected:
## Step 3: API health without prefix returns 404
```bash
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:19421/api/health)
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:49821/api/health)
echo "status=$HTTP_CODE"
test "$HTTP_CODE" = "404" && echo "correctly_rejected=yes"
```
@@ -116,8 +117,8 @@ Expected:
## Step 4: Bare path redirects to trailing slash
```bash
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:19421/skillshare)
LOCATION=$(curl -s -o /dev/null -w "%{redirect_url}" http://localhost:19421/skillshare)
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:49821/skillshare)
LOCATION=$(curl -s -o /dev/null -w "%{redirect_url}" http://localhost:49821/skillshare)
echo "status=$HTTP_CODE"
echo "location=$LOCATION"
```
@@ -130,7 +131,7 @@ Expected:
## Step 5: Root path returns 404
```bash
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:19421/)
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:49821/)
echo "status=$HTTP_CODE"
test "$HTTP_CODE" = "404" && echo "root_blocked=yes"
```
@@ -143,7 +144,7 @@ Expected:
## Step 6: Index.html served with __BASE_PATH__ injection
```bash
BODY=$(curl -sf http://localhost:19421/skillshare/)
BODY=$(curl -sf http://localhost:49821/skillshare/)
echo "$BODY"
echo "$BODY" | grep -q '__BASE_PATH__' && echo "injection_found=yes"
echo "$BODY" | grep -q '"/skillshare"' && echo "value_correct=yes"
@@ -158,8 +159,8 @@ Expected:
## Step 7: SPA fallback serves index.html for unknown routes
```bash
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:19421/skillshare/skills/nonexistent)
BODY=$(curl -sf http://localhost:19421/skillshare/skills/nonexistent)
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:49821/skillshare/skills/nonexistent)
BODY=$(curl -sf http://localhost:49821/skillshare/skills/nonexistent)
echo "status=$HTTP_CODE"
echo "$BODY" | grep -q '__BASE_PATH__' && echo "spa_fallback_ok=yes"
```
@@ -172,7 +173,7 @@ Expected:
## Step 8: API overview returns valid data
```bash
curl -sf http://localhost:19421/skillshare/api/overview
curl -sf http://localhost:49821/skillshare/api/overview
```
Expected:
@@ -183,7 +184,8 @@ Expected:
## Step 9: Stop server and cleanup
```bash
fuser -k 19421/tcp 2>/dev/null || true
kill $(cat /tmp/basepath-server.pid 2>/dev/null) 2>/dev/null || true
rm -f /tmp/basepath-server.pid
sleep 1
echo "server_stopped=yes"
```
@@ -195,8 +197,7 @@ Expected:
## Step 10: --base-path missing value returns error
```bash
cd /workspace
go run ./cmd/skillshare ui --base-path 2>&1 || true
/workspace/bin/skillshare ui --base-path 2>&1 || true
```
Expected:
@@ -205,8 +206,7 @@ Expected:
## Step 11: -b short flag missing value returns error
```bash
cd /workspace
go run ./cmd/skillshare ui -b 2>&1 || true
/workspace/bin/skillshare ui -b 2>&1 || true
```
Expected:
@@ -223,32 +223,29 @@ export XDG_STATE_HOME="$E2E_HOME/.local/state"
export XDG_CACHE_HOME="$E2E_HOME/.cache"
export SKILLSHARE_UI_BASE_PATH="/from-env"
# Kill any leftover servers from previous steps or runs
fuser -k 19421/tcp 2>/dev/null || true
fuser -k 19422/tcp 2>/dev/null || true
kill $(cat /tmp/basepath-server.pid /tmp/basepath-server2.pid 2>/dev/null) 2>/dev/null || true
rm -f /tmp/basepath-server.pid /tmp/basepath-server2.pid
sleep 1
cd /workspace
go run ./cmd/skillshare ui --host 0.0.0.0 --port 19422 --no-open -g > /tmp/basepath-env.log 2>&1 &
sleep 5
cat /tmp/basepath-env.log
/workspace/bin/skillshare ui --host 0.0.0.0 --port 49822 --no-open -g > /tmp/basepath-env.log 2>&1 &
echo $! > /tmp/basepath-server2.pid
sleep 3
cat /tmp/basepath-env.log >&2
curl -sf http://localhost:19422/from-env/api/health
fuser -k 19422/tcp 2>/dev/null || true
curl -sf http://localhost:49822/from-env/api/health
kill $(cat /tmp/basepath-server2.pid 2>/dev/null) 2>/dev/null || true
```
Expected:
- exit_code: 0
- regex: running at http://.*:19422/from-env/
- jq: .status == "ok"
## Step 13: Final cleanup
```bash
# Ensure all servers from this runbook are stopped
fuser -k 19421/tcp 2>/dev/null || true
fuser -k 19422/tcp 2>/dev/null || true
kill $(cat /tmp/basepath-server.pid /tmp/basepath-server2.pid 2>/dev/null) 2>/dev/null || true
sleep 1
rm -f /tmp/basepath-server.pid /tmp/basepath-server2.pid
rm -rf /tmp/ss-e2e-basepath /tmp/basepath-server.log /tmp/basepath-env.log
echo "cleanup_done=yes"
```
+18 -16
View File
@@ -5,6 +5,8 @@ import (
"sort"
"strings"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
@@ -60,12 +62,12 @@ type analyzeDataLoadedMsg struct {
func newAnalyzeTUIModel(loadFn func() analyzeLoadResult, modeLabel string, initialFilter string) analyzeTUIModel {
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
fi.Placeholder = "filter skills"
return analyzeTUIModel{
@@ -268,7 +270,7 @@ func (m analyzeTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
delegate := analyzeSkillDelegate{}
l := list.New(nil, delegate, 0, 0)
l.Title = m.listTitle()
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
@@ -498,7 +500,7 @@ func (m analyzeTUIModel) renderFooter(scrollInfo string) string {
b.WriteString("\n")
help := m.helpText()
help = appendScrollInfo(help, scrollInfo)
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
}
@@ -524,12 +526,12 @@ func (m analyzeTUIModel) renderTargetBar() string {
label = fmt.Sprintf("%d targets (%d)", len(g.names), g.entry.SkillCount)
}
if i == m.groupIdx {
parts = append(parts, tc.Cyan.Render("► "+label))
parts = append(parts, theme.Accent().Render("► "+label))
} else {
parts = append(parts, tc.Dim.Render(label))
parts = append(parts, theme.Dim().Render(label))
}
}
return " " + strings.Join(parts, tc.Dim.Render(" · ")) + "\n"
return " " + strings.Join(parts, theme.Dim().Render(" · ")) + "\n"
}
func (m analyzeTUIModel) renderStatsLine() string {
@@ -546,17 +548,17 @@ func (m analyzeTUIModel) renderStatsLine() string {
countStr = fmt.Sprintf("%d skills", g.entry.SkillCount)
}
return tc.Help.Render(fmt.Sprintf("%s Always: %s tokens On-demand: %s tokens Total: %s tokens %s",
return theme.Dim().MarginLeft(2).Render(fmt.Sprintf("%s Always: %s tokens On-demand: %s tokens Total: %s tokens %s",
countStr,
formatTokensStr(m.filteredDescChars),
formatTokensStr(m.filteredBodyChars),
formatTokensStr(totalChars),
tc.Dim.Render("(1 token ≈ 4 chars)"),
theme.Dim().Render("(1 token ≈ 4 chars)"),
)) + "\n"
}
func (m analyzeTUIModel) renderDetailHeader(e analyzeSkillEntry, width int) string {
title := tc.ListTitle.Render(e.Name)
title := theme.Title().Render(e.Name)
return lipgloss.NewStyle().Width(width).Render(title)
}
@@ -582,9 +584,9 @@ func (m analyzeTUIModel) renderDetailBody(e analyzeSkillEntry, width int) string
for _, issue := range e.LintIssues {
var icon string
if issue.Severity == ssync.LintError {
icon = tc.Red.Render("✗")
icon = theme.Danger().Render("✗")
} else {
icon = tc.Yellow.Render("⚠")
icon = theme.Warning().Render("⚠")
}
qualityRows = append(qualityRows, icon+" "+issue.Message)
}
@@ -595,10 +597,10 @@ func (m analyzeTUIModel) renderDetailBody(e analyzeSkillEntry, width int) string
// Metadata
var metaRows []string
if e.relPath != "" {
metaRows = append(metaRows, renderFactRow("Path", tc.Cyan.Render(e.relPath)))
metaRows = append(metaRows, renderFactRow("Path", theme.Accent().Render(e.relPath)))
}
if e.isTracked {
metaRows = append(metaRows, renderFactRow("Tracked", tc.Green.Render("✓")))
metaRows = append(metaRows, renderFactRow("Tracked", theme.Success().Render("✓")))
}
if len(e.targetNames) > 0 {
metaRows = append(metaRows, renderFactRow("Restricted to", strings.Join(e.targetNames, ", ")))
@@ -621,7 +623,7 @@ func (m analyzeTUIModel) renderDetailBody(e analyzeSkillEntry, width int) string
lines[len(lines)-1] += "..."
}
body := strings.Join(lines, "\n")
b.WriteString(renderDetailSection("Description", tc.Value.Render(body), width))
b.WriteString(renderDetailSection("Description", lipgloss.NewStyle().Render(body), width))
}
return b.String()
+5 -3
View File
@@ -5,6 +5,8 @@ import (
"sort"
"strings"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
@@ -69,8 +71,8 @@ var analyzeDots = map[string]string{
// Pre-computed lint icons (same pattern as analyzeDots).
var (
lintIconError = tc.Red.Render("✗") + " "
lintIconWarning = tc.Yellow.Render("⚠") + " "
lintIconError = theme.Danger().Render("✗") + " "
lintIconWarning = theme.Warning().Render("⚠") + " "
)
func lintIcon(issues []ssync.LintIssue) string {
@@ -138,7 +140,7 @@ func (d analyzeSkillDelegate) Render(w io.Writer, m list.Model, index int, listI
if gap < 1 {
gap = 1
}
line := dot + " " + nameLabel + strings.Repeat(" ", gap) + tc.Dim.Render(tokenStr)
line := dot + " " + nameLabel + strings.Repeat(" ", gap) + theme.Dim().Render(tokenStr)
// Reuse the shared ▌ prefix row style (same as list, audit, log TUIs)
renderPrefixRow(w, line, width, isSelected)
+109 -31
View File
@@ -11,6 +11,7 @@ import (
"skillshare/internal/audit"
"skillshare/internal/config"
"skillshare/internal/oplog"
"skillshare/internal/resource"
"skillshare/internal/sync"
"skillshare/internal/ui"
"skillshare/internal/utils"
@@ -130,6 +131,9 @@ func cmdAudit(args []string) error {
}
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare audit agents" or "--all").
kind, rest := parseKindArg(rest)
// Check for "rules" subcommand before standard audit arg parsing.
if len(rest) > 0 && rest[0] == "rules" {
return cmdAuditRules(mode, rest[1:])
@@ -161,6 +165,7 @@ func cmdAudit(args []string) error {
var (
sourcePath string
agentsSourcePath string
projectRoot string
defaultThreshold string
configProfile string
@@ -184,6 +189,7 @@ func cmdAudit(args []string) error {
return err
}
sourcePath = rt.sourcePath
agentsSourcePath = rt.agentsSourcePath
projectRoot = cwd
defaultThreshold = rt.config.Audit.BlockThreshold
configProfile = rt.config.Audit.Profile
@@ -196,6 +202,7 @@ func cmdAudit(args []string) error {
return err
}
sourcePath = cfg.Source
agentsSourcePath = cfg.EffectiveAgentsSource()
defaultThreshold = cfg.Audit.BlockThreshold
configProfile = cfg.Audit.Profile
configDedupe = cfg.Audit.DedupeMode
@@ -203,6 +210,11 @@ func cmdAudit(args []string) error {
cfgPath = config.ConfigPath()
}
// When kind is agents-only, override sourcePath to the agents source directory.
if kind == kindAgents && agentsSourcePath != "" {
sourcePath = agentsSourcePath
}
policy := audit.ResolvePolicy(audit.PolicyInputs{
Profile: opts.Profile,
Threshold: opts.Threshold,
@@ -230,13 +242,13 @@ func cmdAudit(args []string) error {
switch {
case !hasTargets:
results, summary, err = auditInstalled(sourcePath, modeString(mode), projectRoot, threshold, opts, registry)
results, summary, err = auditInstalled(sourcePath, agentsSourcePath, modeString(mode), projectRoot, threshold, kind, opts, registry)
case isSinglePath:
results, summary, err = auditPath(opts.Targets[0], modeString(mode), projectRoot, threshold, opts.Format, opts.PolicyLine, registry)
case isSingleName:
results, summary, err = auditSkillByName(sourcePath, opts.Targets[0], modeString(mode), projectRoot, threshold, opts.Format, opts.PolicyLine, registry)
results, summary, err = auditSkillByName(sourcePath, opts.Targets[0], modeString(mode), projectRoot, threshold, opts.Format, opts.PolicyLine, kind, registry)
default:
results, summary, err = auditFiltered(sourcePath, opts.Targets, opts.Groups, modeString(mode), projectRoot, threshold, opts, registry)
results, summary, err = auditFiltered(sourcePath, agentsSourcePath, opts.Targets, opts.Groups, modeString(mode), projectRoot, threshold, kind, opts, registry)
}
if err != nil {
logAuditOp(cfgPath, rest, summary, start, err, false)
@@ -465,14 +477,44 @@ func scanSkillPath(skillPath, projectRoot string, registry *audit.Registry) (*au
return audit.ScanSkill(skillPath)
}
func toAuditInputs(skills []auditSkillRef) []audit.SkillInput {
inputs := make([]audit.SkillInput, len(skills))
for i, s := range skills {
inputs[i] = audit.SkillInput{Name: s.name, Path: s.path}
func toAuditInputs(items []auditSkillRef, isFile bool) []audit.SkillInput {
inputs := make([]audit.SkillInput, len(items))
for i, item := range items {
inputs[i] = audit.SkillInput{Name: item.name, Path: item.path, IsFile: isFile}
}
return inputs
}
func collectInstalledAgentPaths(agentsSourcePath string) ([]auditSkillRef, error) {
if agentsSourcePath == "" {
return nil, nil
}
if _, err := os.Stat(agentsSourcePath); os.IsNotExist(err) {
return nil, nil
}
discovered, err := resource.AgentKind{}.Discover(agentsSourcePath)
if err != nil {
return nil, fmt.Errorf("failed to discover agents: %w", err)
}
var agentPaths []auditSkillRef
// Audit scans ALL agents including disabled ones — security risks don't respect .agentignore.
for _, d := range discovered {
agentPaths = append(agentPaths, auditSkillRef{name: d.FlatName, path: d.AbsPath})
}
return agentPaths, nil
}
func discoverForKind(kind resourceKindFilter, sourcePath string) ([]auditSkillRef, error) {
if kind == kindAgents {
return collectInstalledAgentPaths(sourcePath)
}
return collectInstalledSkillPaths(sourcePath)
}
func toInputsForKind(kind resourceKindFilter, items []auditSkillRef) []audit.SkillInput {
return toAuditInputs(items, kind == kindAgents)
}
func scanPathTarget(targetPath, projectRoot string, registry *audit.Registry) (*audit.Result, error) {
info, err := os.Stat(targetPath)
if err != nil {
@@ -487,7 +529,7 @@ func scanPathTarget(targetPath, projectRoot string, registry *audit.Registry) (*
return audit.ScanFile(targetPath)
}
func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditOptions, reg *audit.Registry) ([]*audit.Result, auditRunSummary, error) {
func auditInstalled(sourcePath, agentsSourcePath, mode, projectRoot, threshold string, kind resourceKindFilter, opts auditOptions, reg *audit.Registry) ([]*audit.Result, auditRunSummary, error) {
jsonOutput := opts.isStructured()
base := auditRunSummary{
Scope: "all",
@@ -495,12 +537,18 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
Threshold: threshold,
}
// Phase 0: discover skills.
// Phase 0: discover skills/agents.
var spinner *ui.Spinner
if !jsonOutput {
spinner = ui.StartSpinner("Discovering skills...")
spinner = ui.StartSpinner(fmt.Sprintf("Discovering %s...", kind.Noun(2)))
}
var skillPaths []auditSkillRef
var err error
if kind == kindAgents {
skillPaths, err = collectInstalledAgentPaths(sourcePath)
} else {
skillPaths, err = collectInstalledSkillPaths(sourcePath)
}
skillPaths, err := collectInstalledSkillPaths(sourcePath)
if err != nil {
if spinner != nil {
spinner.Fail("Discovery failed")
@@ -509,18 +557,18 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
}
if len(skillPaths) == 0 {
if spinner != nil {
spinner.Success("No skills found")
spinner.Success(fmt.Sprintf("No %s found", kind.Noun(2)))
}
return []*audit.Result{}, base, nil
}
if spinner != nil {
spinner.Success(fmt.Sprintf("Found %d skill(s)", len(skillPaths)))
spinner.Success(fmt.Sprintf("Found %d %s", len(skillPaths), kind.Noun(len(skillPaths))))
}
// Phase 0.5: large audit confirmation prompt.
if len(skillPaths) > largeAuditThreshold && !jsonOutput && !opts.Yes && ui.IsTTY() {
ui.Warning("Found %d skills. This may take a while.", len(skillPaths))
ui.Info("Tip: use 'audit --group <dir>' or 'audit <name>' to scan specific skills")
ui.Warning("Found %d %s. This may take a while.", len(skillPaths), kind.Noun(len(skillPaths)))
ui.Info("Tip: use 'audit --group <dir>' or 'audit <name>' to scan specific %s", kind.Noun(2))
fmt.Print(" Continue? [y/N]: ")
var answer string
fmt.Scanln(&answer)
@@ -533,7 +581,7 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
var headerMinWidth int
if !jsonOutput {
fmt.Println()
subtitle := auditHeaderSubtitle(fmt.Sprintf("Scanning %d skills for threats", len(skillPaths)), mode, sourcePath, threshold, opts.PolicyLine)
subtitle := auditHeaderSubtitle(fmt.Sprintf("Scanning %d %s for threats", len(skillPaths), kind.Noun(len(skillPaths))), mode, sourcePath, threshold, opts.PolicyLine)
headerMinWidth = auditHeaderMinWidth(subtitle)
ui.HeaderBoxWithMinWidth(auditHeaderTitle(mode), subtitle, headerMinWidth)
}
@@ -544,14 +592,15 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
}
var progressBar *ui.ProgressBar
if !jsonOutput {
progressBar = ui.StartProgress("Scanning skills", len(skillPaths))
progressBar = ui.StartProgress(fmt.Sprintf("Scanning %s", kind.Noun(2)), len(skillPaths))
}
onDone := func() {
if progressBar != nil {
progressBar.Increment()
}
}
scanResults := audit.ParallelScan(toAuditInputs(skillPaths), projectRoot, onDone, reg)
scanInputs := toInputsForKind(kind, skillPaths)
scanResults := audit.ParallelScan(scanInputs, projectRoot, onDone, reg)
if progressBar != nil {
progressBar.Stop()
}
@@ -574,6 +623,7 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
}
sr.Result.Threshold = threshold
sr.Result.IsBlocked = sr.Result.HasSeverityAtOrAbove(threshold)
sr.Result.Kind = kind.SingularNoun()
// Use relative path so TUI shows group hierarchy (e.g. "frontend/vue/skill").
if rel, err := filepath.Rel(sourcePath, sr.Result.ScanTarget); err == nil && rel != sr.Result.SkillName {
sr.Result.SkillName = rel
@@ -594,14 +644,23 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
}
applyPolicyToSummary(&summary, opts)
if err := presentAuditResults(results, elapsed, scanResults, summary, jsonOutput, opts, headerMinWidth); err != nil {
tuiCtx := &auditTUIContext{
kind: kind,
sourcePath: sourcePath,
agentsSourcePath: agentsSourcePath,
projectRoot: projectRoot,
threshold: threshold,
registry: reg,
mode: mode,
}
if err := presentAuditResults(results, elapsed, scanResults, summary, jsonOutput, opts, headerMinWidth, tuiCtx); err != nil {
return results, summary, err
}
return results, summary, nil
}
func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot, threshold string, opts auditOptions, reg *audit.Registry) ([]*audit.Result, auditRunSummary, error) {
func auditFiltered(sourcePath, agentsSourcePath string, names, groups []string, mode, projectRoot, threshold string, kind resourceKindFilter, opts auditOptions, reg *audit.Registry) ([]*audit.Result, auditRunSummary, error) {
jsonOutput := opts.isStructured()
base := auditRunSummary{
Scope: "filtered",
@@ -609,7 +668,13 @@ func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot,
Threshold: threshold,
}
allSkills, err := collectInstalledSkillPaths(sourcePath)
var allSkills []auditSkillRef
var err error
if kind == kindAgents {
allSkills, err = collectInstalledAgentPaths(sourcePath)
} else {
allSkills, err = collectInstalledSkillPaths(sourcePath)
}
if err != nil {
return nil, base, err
}
@@ -658,7 +723,7 @@ func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot,
}
for _, w := range warnings {
if !jsonOutput {
ui.Warning("skill not found: %s", w)
ui.Warning("%s not found: %s", kind.SingularNoun(), w)
}
}
@@ -670,7 +735,7 @@ func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot,
var headerMinWidth int
if !jsonOutput {
fmt.Println()
subtitle := auditHeaderSubtitle(fmt.Sprintf("Scanning %d skills for threats", len(matched)), mode, sourcePath, threshold, opts.PolicyLine)
subtitle := auditHeaderSubtitle(fmt.Sprintf("Scanning %d %s for threats", len(matched), kind.Noun(len(matched))), mode, sourcePath, threshold, opts.PolicyLine)
headerMinWidth = auditHeaderMinWidth(subtitle)
ui.HeaderBoxWithMinWidth(auditHeaderTitle(mode), subtitle, headerMinWidth)
}
@@ -681,14 +746,15 @@ func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot,
}
var progressBar *ui.ProgressBar
if !jsonOutput {
progressBar = ui.StartProgress("Scanning skills", len(matched))
progressBar = ui.StartProgress(fmt.Sprintf("Scanning %s", kind.Noun(2)), len(matched))
}
onDone := func() {
if progressBar != nil {
progressBar.Increment()
}
}
scanResults := audit.ParallelScan(toAuditInputs(matched), projectRoot, onDone, reg)
scanInputs := toInputsForKind(kind, matched)
scanResults := audit.ParallelScan(scanInputs, projectRoot, onDone, reg)
if progressBar != nil {
progressBar.Stop()
}
@@ -711,6 +777,7 @@ func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot,
}
sr.Result.Threshold = threshold
sr.Result.IsBlocked = sr.Result.HasSeverityAtOrAbove(threshold)
sr.Result.Kind = kind.SingularNoun()
if rel, err := filepath.Rel(sourcePath, sr.Result.ScanTarget); err == nil && rel != sr.Result.SkillName {
sr.Result.SkillName = rel
}
@@ -730,14 +797,23 @@ func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot,
}
applyPolicyToSummary(&summary, opts)
if err := presentAuditResults(results, elapsed, scanResults, summary, jsonOutput, opts, headerMinWidth); err != nil {
tuiCtx := &auditTUIContext{
kind: kind,
sourcePath: sourcePath,
agentsSourcePath: agentsSourcePath,
projectRoot: projectRoot,
threshold: threshold,
registry: reg,
mode: mode,
}
if err := presentAuditResults(results, elapsed, scanResults, summary, jsonOutput, opts, headerMinWidth, tuiCtx); err != nil {
return results, summary, err
}
return results, summary, nil
}
func auditSkillByName(sourcePath, name, mode, projectRoot, threshold, format, policyLine string, reg *audit.Registry) ([]*audit.Result, auditRunSummary, error) {
func auditSkillByName(sourcePath, name, mode, projectRoot, threshold, format, policyLine string, kind resourceKindFilter, reg *audit.Registry) ([]*audit.Result, auditRunSummary, error) {
summary := auditRunSummary{
Scope: "single",
Skill: name,
@@ -750,19 +826,20 @@ func auditSkillByName(sourcePath, name, mode, projectRoot, threshold, format, po
// Short-name fallback: search installed skills by flat name or basename.
resolved := resolveSkillPath(sourcePath, name)
if resolved == "" {
return nil, summary, fmt.Errorf("skill not found: %s", name)
return nil, summary, fmt.Errorf("%s not found: %s", kind.SingularNoun(), name)
}
skillPath = resolved
}
start := time.Now()
result, err := scanSkillPath(skillPath, projectRoot, reg)
result, err := scanPathTarget(skillPath, projectRoot, reg)
if err != nil {
return nil, summary, fmt.Errorf("scan error: %w", err)
}
elapsed := time.Since(start)
result.Threshold = threshold
result.IsBlocked = result.HasSeverityAtOrAbove(threshold)
result.Kind = kind.SingularNoun()
if rel, err := filepath.Rel(sourcePath, result.ScanTarget); err == nil && rel != result.SkillName {
result.SkillName = rel
}
@@ -772,8 +849,9 @@ func auditSkillByName(sourcePath, name, mode, projectRoot, threshold, format, po
summary.Skill = name
summary.Mode = mode
if format == formatText {
subtitle := auditHeaderSubtitle(fmt.Sprintf("Scanning skill: %s", name), mode, sourcePath, threshold, policyLine)
summaryLines := buildAuditSummaryLines(summary)
label := kind.SingularNoun()
subtitle := auditHeaderSubtitle(fmt.Sprintf("Scanning %s: %s", label, name), mode, sourcePath, threshold, policyLine)
summaryLines := buildAuditSummaryLines(summary, kind)
minWidth := auditHeaderMinWidth(subtitle)
ui.HeaderBoxWithMinWidth(auditHeaderTitle(mode), subtitle, minWidth)
fmt.Println()
+2 -2
View File
@@ -22,10 +22,10 @@ func cmdAuditProject(root, specificSkill string) (auditRunSummary, bool, error)
}
if specificSkill != "" {
_, summary, err := auditSkillByName(rt.sourcePath, specificSkill, "project", root, threshold, formatText, "", nil)
_, summary, err := auditSkillByName(rt.sourcePath, specificSkill, "project", root, threshold, formatText, "", kindSkills, nil)
return summary, summary.Failed > 0, err
}
_, summary, err := auditInstalled(rt.sourcePath, "project", root, threshold, auditOptions{}, nil)
_, summary, err := auditInstalled(rt.sourcePath, "", "project", root, threshold, kindSkills, auditOptions{}, nil)
return summary, summary.Failed > 0, err
}
+105 -9
View File
@@ -2,11 +2,13 @@ package main
import (
"fmt"
"path/filepath"
"sort"
"strings"
"time"
"skillshare/internal/audit"
"skillshare/internal/theme"
"skillshare/internal/ui"
)
@@ -18,10 +20,21 @@ func riskColor(label string) string {
return ui.Dim
}
// auditTUIContext carries info needed to scan the "other" kind for TUI tab switching.
type auditTUIContext struct {
kind resourceKindFilter
sourcePath string // skills source (always)
agentsSourcePath string // agents source (always)
projectRoot string
threshold string
registry *audit.Registry
mode string
}
// presentAuditResults handles the common output path for audit scans:
// prints per-skill list only when TUI is unavailable, always prints summary,
// and launches TUI when conditions are met.
func presentAuditResults(results []*audit.Result, elapsed []time.Duration, scanOutputs []audit.ScanOutput, summary auditRunSummary, jsonOutput bool, opts auditOptions, headerMinWidth int) error {
func presentAuditResults(results []*audit.Result, elapsed []time.Duration, scanOutputs []audit.ScanOutput, summary auditRunSummary, jsonOutput bool, opts auditOptions, headerMinWidth int, tuiCtx *auditTUIContext) error {
useTUI := !jsonOutput && shouldLaunchTUI(opts.NoTUI, nil) && len(results) > 1
if !jsonOutput {
@@ -37,16 +50,94 @@ func presentAuditResults(results []*audit.Result, elapsed []time.Duration, scanO
}
fmt.Println()
}
summaryLines := buildAuditSummaryLines(summary)
var kindSlice []resourceKindFilter
if tuiCtx != nil {
kindSlice = []resourceKindFilter{tuiCtx.kind}
}
summaryLines := buildAuditSummaryLines(summary, kindSlice...)
printAuditSummary(summary, summaryLines, headerMinWidth)
}
if useTUI {
return runAuditTUI(results, scanOutputs, summary)
if tuiCtx != nil {
return launchAuditTUIWithTabs(results, scanOutputs, summary, tuiCtx)
}
return runAuditTUI(results, scanOutputs, summary, nil, nil, auditRunSummary{}, auditTabSkills)
}
return nil
}
func launchAuditTUIWithTabs(results []*audit.Result, scanOutputs []audit.ScanOutput, summary auditRunSummary, ctx *auditTUIContext) error {
initialTab := auditTabSkills
if ctx.kind == kindAgents {
initialTab = auditTabAgents
}
// Scan the "other" kind for the second tab.
var otherResults []*audit.Result
var otherOutputs []audit.ScanOutput
var otherSummary auditRunSummary
otherKindFilter := kindAgents
otherSource := ctx.agentsSourcePath
if ctx.kind == kindAgents {
otherKindFilter = kindSkills
otherSource = ctx.sourcePath
}
if otherSource != "" {
otherPaths, err := discoverForKind(otherKindFilter, otherSource)
otherInputs := toInputsForKind(otherKindFilter, otherPaths)
if err == nil && len(otherPaths) > 0 {
otherScanResults := audit.ParallelScan(otherInputs, ctx.projectRoot, nil, ctx.registry)
for i := range otherPaths {
if i < len(otherScanResults) {
sr := otherScanResults[i]
if sr.Err == nil {
sr.Result.Threshold = ctx.threshold
sr.Result.IsBlocked = sr.Result.HasSeverityAtOrAbove(ctx.threshold)
sr.Result.Kind = otherKindFilter.SingularNoun()
if rel, relErr := filepath.Rel(otherSource, sr.Result.ScanTarget); relErr == nil {
sr.Result.SkillName = rel
}
otherResults = append(otherResults, sr.Result)
otherOutputs = append(otherOutputs, sr)
}
}
}
otherSummary = summarizeAuditResults(len(otherPaths), otherResults, ctx.threshold)
otherSummary.Mode = ctx.mode
}
}
// Filter out synthetic _cross-skill result — it's not a real resource.
var filteredResults []*audit.Result
var filteredOutputs []audit.ScanOutput
for i, r := range results {
if r.SkillName != audit.CrossSkillResultName {
filteredResults = append(filteredResults, r)
if i < len(scanOutputs) {
filteredOutputs = append(filteredOutputs, scanOutputs[i])
}
}
}
// Arrange into skills vs agents.
var skillResults, agentResults []*audit.Result
var skillOutputs, agentOutputs []audit.ScanOutput
var skillSummary, agentSummary auditRunSummary
if ctx.kind == kindAgents {
agentResults, agentOutputs, agentSummary = filteredResults, filteredOutputs, summary
skillResults, skillOutputs, skillSummary = otherResults, otherOutputs, otherSummary
} else {
skillResults, skillOutputs, skillSummary = filteredResults, filteredOutputs, summary
agentResults, agentOutputs, agentSummary = otherResults, otherOutputs, otherSummary
}
return runAuditTUI(skillResults, skillOutputs, skillSummary, agentResults, agentOutputs, agentSummary, initialTab)
}
// printSkillResultLine prints a single-line result for a skill during batch scan.
func printSkillResultLine(index, total int, result *audit.Result, elapsed time.Duration) {
prefix := fmt.Sprintf("[%d/%d]", index, total)
@@ -155,7 +246,7 @@ func printSkillResult(result *audit.Result, elapsed time.Duration) {
}
// buildAuditSummaryLines builds the summary box lines (without printing).
func buildAuditSummaryLines(summary auditRunSummary) []string {
func buildAuditSummaryLines(summary auditRunSummary, kind ...resourceKindFilter) []string {
var lines []string
maxSeverity := summary.MaxSeverity
if maxSeverity == "" {
@@ -167,8 +258,12 @@ func buildAuditSummaryLines(summary auditRunSummary) []string {
lines = append(lines, fmt.Sprintf(" Max sev: %s", ui.Colorize(ui.SeverityColor(maxSeverity), maxSeverity)))
// -- Result counts --
noun := "skill(s)"
if len(kind) > 0 {
noun = kind[0].Noun(summary.Scanned)
}
lines = append(lines, "")
lines = append(lines, fmt.Sprintf(" Scanned: %d skill(s)", summary.Scanned))
lines = append(lines, fmt.Sprintf(" Scanned: %d %s", summary.Scanned, noun))
lines = append(lines, fmt.Sprintf(" Passed: %d", summary.Passed))
if summary.Warning > 0 {
lines = append(lines, fmt.Sprintf(" Warning: %s", ui.Colorize(ui.Yellow, fmt.Sprintf("%d", summary.Warning))))
@@ -375,16 +470,16 @@ func formatCategoryBreakdownTUI(cats map[string]int) string {
label = short
}
if cc.count > 50 {
parts[i] = tc.Emphasis.Bold(true).Render(label+":") + tc.Emphasis.Bold(true).Render(fmt.Sprintf("%d", cc.count))
parts[i] = theme.Primary().Bold(true).Render(label+":") + theme.Primary().Bold(true).Render(fmt.Sprintf("%d", cc.count))
} else {
parts[i] = tc.Dim.Render(label + ":" + fmt.Sprintf("%d", cc.count))
parts[i] = theme.Dim().Render(label + ":" + fmt.Sprintf("%d", cc.count))
}
}
return strings.Join(parts, " ")
}
func printAuditHelp() {
fmt.Println(`Usage: skillshare audit [name...] [options]
fmt.Println(`Usage: skillshare audit [agents] [name...] [options]
skillshare audit --group <group> [options]
skillshare audit <path> [options]
@@ -432,5 +527,6 @@ Examples:
skillshare audit --format sarif # Output SARIF 2.1.0 for GitHub Code Scanning
skillshare audit --format markdown # Output Markdown report (for GitHub Issues/PRs)
skillshare audit --json # Same as --format json (deprecated)
skillshare audit -p --init-rules # Create project custom rules file`)
skillshare audit -p --init-rules # Create project custom rules file
skillshare audit agents # Scan agents only`)
}
+39 -38
View File
@@ -6,6 +6,7 @@ import (
"strings"
"skillshare/internal/audit"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
@@ -46,9 +47,9 @@ func (i arHeaderItem) Title() string {
countStr := fmt.Sprintf("%d", i.group.Total)
extra := ""
if i.group.Disabled > 0 {
extra = tc.Yellow.Render(fmt.Sprintf(" %d off", i.group.Disabled))
extra = theme.Warning().Render(fmt.Sprintf(" %d off", i.group.Disabled))
}
return fmt.Sprintf("%s %s %s%s", arrow, i.group.Pattern, tc.Dim.Render(countStr), extra)
return fmt.Sprintf("%s %s %s%s", arrow, i.group.Pattern, theme.Dim().Render(countStr), extra)
}
func (i arHeaderItem) Description() string { return "" }
@@ -64,9 +65,9 @@ type arRuleItem struct {
}
func (i arRuleItem) Title() string {
dot := tcSevStyle(i.rule.Severity).Render("●")
dot := theme.SeverityStyle(i.rule.Severity).Render("●")
if !i.rule.Enabled {
return fmt.Sprintf(" %s %s %s", dot, i.rule.ID, tc.Red.Render("off"))
return fmt.Sprintf(" %s %s %s", dot, i.rule.ID, theme.Danger().Render("off"))
}
return fmt.Sprintf(" %s %s", dot, i.rule.ID)
}
@@ -158,13 +159,13 @@ func newARModel(rules []audit.CompiledRule, mode runMode) arModel {
// Filter text input
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
m.filterInput = fi
// Create the list model once — rebuildItems will populate via SetItems.
m.list = list.New(nil, newPrefixDelegate(false), 0, 0)
m.list.Styles.Title = tc.ListTitle
m.list.Styles.Title = theme.Title()
m.list.SetShowStatusBar(false)
m.list.SetFilteringEnabled(false)
m.list.SetShowHelp(false)
@@ -418,7 +419,7 @@ func (m arModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
case "R":
m.pendingReset = true
m.flashMsg = tc.Yellow.Render("Press R again to reset all rules to defaults")
m.flashMsg = theme.Warning().Render("Press R again to reset all rules to defaults")
m.flashTicks = 5
return m, nil
case "ctrl+d":
@@ -472,11 +473,11 @@ func (m *arModel) toggleSelected() {
// execMutation runs a mutation function, shows flash feedback, and reloads rules.
func (m *arModel) execMutation(fn func() error, successMsg string) {
if err := fn(); err != nil {
m.flashMsg = tc.Red.Render("✗ " + err.Error())
m.flashMsg = theme.Danger().Render("✗ " + err.Error())
m.flashTicks = 3
return
}
m.flashMsg = tc.Green.Render("✓ " + successMsg)
m.flashMsg = theme.Success().Render("✓ " + successMsg)
m.flashTicks = 3
m.reloadRules()
m.rebuildItems()
@@ -611,7 +612,7 @@ func (m arModel) renderSevTabBar() string {
var parts []string
activeStyle := lipgloss.NewStyle().Bold(true).Underline(true)
inactiveStyle := tc.Dim
inactiveStyle := theme.Dim()
for i, tab := range sevTabs {
label := fmt.Sprintf("%s(%d)", tab.label, counts[i])
@@ -619,19 +620,19 @@ func (m arModel) renderSevTabBar() string {
// Color active tab by its severity
switch tab.sev {
case "CRITICAL":
parts = append(parts, activeStyle.Inherit(tc.Critical).Render(label))
parts = append(parts, activeStyle.Inherit(theme.Severity("critical")).Render(label))
case "HIGH":
parts = append(parts, activeStyle.Inherit(tc.High).Render(label))
parts = append(parts, activeStyle.Inherit(theme.Severity("high")).Render(label))
case "MEDIUM":
parts = append(parts, activeStyle.Inherit(tc.Medium).Render(label))
parts = append(parts, activeStyle.Inherit(theme.Severity("medium")).Render(label))
case "LOW":
parts = append(parts, activeStyle.Inherit(tc.Low).Render(label))
parts = append(parts, activeStyle.Inherit(theme.Severity("low")).Render(label))
case "INFO":
parts = append(parts, activeStyle.Inherit(tc.Info).Render(label))
parts = append(parts, activeStyle.Inherit(theme.Severity("info")).Render(label))
case "DISABLED":
parts = append(parts, activeStyle.Inherit(tc.Red).Render(label))
parts = append(parts, activeStyle.Inherit(theme.Danger()).Render(label))
default:
parts = append(parts, activeStyle.Inherit(tc.Cyan).Render(label))
parts = append(parts, activeStyle.Inherit(theme.Accent()).Render(label))
}
} else {
parts = append(parts, inactiveStyle.Render(label))
@@ -706,29 +707,29 @@ func (m arModel) renderPatternDetail(item arHeaderItem) string {
pg := item.group
row := func(label, value string) {
b.WriteString(tc.Label.Render(label))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(value)
b.WriteString("\n")
}
// Header
b.WriteString(tc.Title.Render(pg.Pattern))
b.WriteString(theme.Title().Render(pg.Pattern))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(strings.Repeat("─", 36)))
b.WriteString(theme.Dim().Render(strings.Repeat("─", 36)))
b.WriteString("\n\n")
row("Rules:", fmt.Sprintf("%d total", pg.Total))
row("Max Sev:", tcSevStyle(pg.MaxSeverity).Render(pg.MaxSeverity))
row("Enabled:", tc.Green.Render(fmt.Sprintf("%d", pg.Enabled)))
row("Max Sev:", theme.SeverityStyle(pg.MaxSeverity).Render(pg.MaxSeverity))
row("Enabled:", theme.Success().Render(fmt.Sprintf("%d", pg.Enabled)))
if pg.Disabled > 0 {
row("Disabled:", tc.Red.Render(fmt.Sprintf("%d", pg.Disabled)))
row("Disabled:", theme.Danger().Render(fmt.Sprintf("%d", pg.Disabled)))
} else {
row("Disabled:", tc.Dim.Render("0"))
row("Disabled:", theme.Dim().Render("0"))
}
// Severity distribution
b.WriteString("\n")
b.WriteString(tc.Label.Render("Severity:"))
b.WriteString(theme.Dim().Width(14).Render("Severity:"))
b.WriteString("\n")
sevCounts := make(map[string]int)
for _, r := range m.allRules {
@@ -739,7 +740,7 @@ func (m arModel) renderPatternDetail(item arHeaderItem) string {
for _, sev := range []string{"CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"} {
if count, ok := sevCounts[sev]; ok && count > 0 {
b.WriteString(" ")
b.WriteString(tcSevStyle(sev).Render(fmt.Sprintf("%-10s %d", sev, count)))
b.WriteString(theme.SeverityStyle(sev).Render(fmt.Sprintf("%-10s %d", sev, count)))
b.WriteString("\n")
}
}
@@ -752,7 +753,7 @@ func (m arModel) renderRuleDetail(item arRuleItem) string {
var b strings.Builder
row := func(label, value string) {
b.WriteString(tc.Label.Render(label))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(value)
b.WriteString("\n")
}
@@ -760,14 +761,14 @@ func (m arModel) renderRuleDetail(item arRuleItem) string {
r := item.rule
// Header
b.WriteString(tc.Title.Render(item.rule.ID))
b.WriteString(theme.Title().Render(item.rule.ID))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(strings.Repeat("─", 36)))
b.WriteString(theme.Dim().Render(strings.Repeat("─", 36)))
b.WriteString("\n\n")
row("ID:", r.ID)
row("Pattern:", tc.Emphasis.Render(r.Pattern))
row("Severity:", tcSevStyle(r.Severity).Render(r.Severity))
row("Pattern:", theme.Primary().Render(r.Pattern))
row("Severity:", theme.SeverityStyle(r.Severity).Render(r.Severity))
row("Message:", r.Message)
row("Regex:", r.Regex)
@@ -775,9 +776,9 @@ func (m arModel) renderRuleDetail(item arRuleItem) string {
row("Exclude:", r.Exclude)
}
statusStr := tc.Green.Render("enabled")
statusStr := theme.Success().Render("enabled")
if !r.Enabled {
statusStr = tc.Red.Render("disabled")
statusStr = theme.Danger().Render("disabled")
}
sourceLabel := r.Source
switch r.Source {
@@ -788,7 +789,7 @@ func (m arModel) renderRuleDetail(item arRuleItem) string {
case "builtin":
sourceLabel = "built-in"
}
row("Status:", statusStr+" "+tc.Dim.Render("("+sourceLabel+")"))
row("Status:", statusStr+" "+theme.Dim().Render("("+sourceLabel+")"))
return b.String()
}
@@ -820,7 +821,7 @@ func (m arModel) renderFlashAndHelp(scrollInfo string) string {
if m.useSplit() {
help += " Ctrl+d/u scroll"
}
b.WriteString(tc.Help.Render(appendScrollInfo(help, scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo(help, scrollInfo)))
}
b.WriteString("\n")
@@ -831,10 +832,10 @@ func (m arModel) renderFlashAndHelp(scrollInfo string) string {
func (m arModel) renderSeverityPicker() string {
var parts []string
for _, opt := range severityOptions {
badge := tcSevStyle(opt.sev).Render(opt.key + " " + opt.sev)
badge := theme.SeverityStyle(opt.sev).Render(opt.key + " " + opt.sev)
parts = append(parts, badge)
}
return tc.Help.Render("Set severity: ") + strings.Join(parts, tc.Dim.Render(" ")) + tc.Help.Render(" Esc cancel")
return theme.Dim().MarginLeft(2).Render("Set severity: ") + strings.Join(parts, theme.Dim().Render(" ")) + theme.Dim().MarginLeft(2).Render(" Esc cancel")
}
// runAuditRulesTUI starts the bubbletea TUI for browsing/toggling audit rules.
+212 -113
View File
@@ -8,6 +8,7 @@ import (
"time"
"skillshare/internal/audit"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
@@ -15,21 +16,24 @@ import (
"github.com/charmbracelet/lipgloss"
)
// ac holds audit-specific styles that don't belong in the shared tc palette.
var ac = struct {
File lipgloss.Style // file:line locations — cyan
Snippet lipgloss.Style // code snippet highlight
ItemName lipgloss.Style // list item name — light gray
}{
File: lipgloss.NewStyle().Foreground(lipgloss.Color("6")),
Snippet: lipgloss.NewStyle().Foreground(lipgloss.Color("179")),
ItemName: lipgloss.NewStyle().Foreground(lipgloss.Color("252")),
type auditTab int
const (
auditTabSkills auditTab = iota
auditTabAgents
)
func (t auditTab) noun() string {
if t == auditTabAgents {
return "agents"
}
return "skills"
}
// acSevCount returns severity color for non-zero counts, dim for zero.
func acSevCount(count int, style lipgloss.Style) lipgloss.Style {
if count == 0 {
return tc.Dim
return theme.Dim()
}
return style
}
@@ -38,17 +42,18 @@ func acSevCount(count int, style lipgloss.Style) lipgloss.Style {
type auditItem struct {
result *audit.Result
elapsed time.Duration
kind string // "skill" or "agent"
}
func (i auditItem) Title() string {
name := colorSkillPath(compactAuditPath(i.result.SkillName))
if len(i.result.Findings) == 0 {
return tc.Green.Render("✓") + " " + name
return theme.Success().Render("✓") + " " + name
}
if i.result.IsBlocked {
return tc.Red.Render("✗") + " " + name
return theme.Danger().Render("✗") + " " + name
}
return tc.Yellow.Render("!") + " " + name
return theme.Warning().Render("!") + " " + name
}
// compactAuditPath strips tracked repo prefix (first segment starting with "_")
@@ -69,10 +74,13 @@ func compactAuditPath(name string) string {
return strings.Join(segments, "/")
}
// auditRepoKey extracts the grouping key from a skill name.
// auditRepoKey extracts the grouping key from a skill/agent name.
// For tracked repos: "_repo-name/skill" → "_repo-name"
// For nested agents: "demo/code-reviewer.md" → "demo"
// For flat names: "my-skill" → "" (standalone)
func auditRepoKey(name string) string {
segments := strings.Split(name, "/")
if strings.HasPrefix(segments[0], "_") {
if len(segments) > 1 {
return segments[0]
}
return ""
@@ -212,62 +220,86 @@ type auditTUIModel struct {
termHeight int
summary auditRunSummary
// Tab switching (skills ↔ agents)
activeTab auditTab
skillItems []auditItem
agentItems []auditItem
skillSummary auditRunSummary
agentSummary auditRunSummary
tabCounts [2]int // [skills, agents]
}
func newAuditTUIModel(results []*audit.Result, scanOutputs []audit.ScanOutput, summary auditRunSummary) auditTUIModel {
// Build items sorted: by severity (findings first), then by name.
items := make([]auditItem, 0, len(results))
for idx, r := range results {
var elapsed time.Duration
if idx < len(scanOutputs) {
elapsed = scanOutputs[idx].Elapsed
}
items = append(items, auditItem{result: r, elapsed: elapsed})
}
func sortAuditItems(items []auditItem) {
sort.Slice(items, func(i, j int) bool {
ri, rj := items[i].result, items[j].result
// Primary: group by repo key (tracked repos first, then standalone).
ki, kj := auditRepoKey(ri.SkillName), auditRepoKey(rj.SkillName)
if ki != kj {
// Both tracked: alphabetical
if ki != "" && kj != "" {
return ki < kj
}
// Tracked before standalone
return ki != ""
}
// Secondary: skills with findings come first.
hasI, hasJ := len(ri.Findings) > 0, len(rj.Findings) > 0
if hasI != hasJ {
return hasI
}
if hasI && hasJ {
// Higher severity (lower rank) first.
rankI := audit.SeverityRank(ri.MaxSeverity())
rankJ := audit.SeverityRank(rj.MaxSeverity())
if rankI != rankJ {
return rankI < rankJ
}
// Higher risk score first.
if ri.RiskScore != rj.RiskScore {
return ri.RiskScore > rj.RiskScore
}
}
return ri.SkillName < rj.SkillName
})
}
// Cap items for list widget performance.
allItems := items
displayItems := items
func newAuditTUIModel(
skillResults []*audit.Result, skillOutputs []audit.ScanOutput, skillSummary auditRunSummary,
agentResults []*audit.Result, agentOutputs []audit.ScanOutput, agentSummary auditRunSummary,
initialTab auditTab,
) auditTUIModel {
buildItems := func(results []*audit.Result, outputs []audit.ScanOutput, kind string) []auditItem {
items := make([]auditItem, 0, len(results))
for idx, r := range results {
var elapsed time.Duration
if idx < len(outputs) {
elapsed = outputs[idx].Elapsed
}
items = append(items, auditItem{result: r, elapsed: elapsed, kind: kind})
}
sortAuditItems(items)
return items
}
skillItems := buildItems(skillResults, skillOutputs, "skill")
agentItems := buildItems(agentResults, agentOutputs, "agent")
var activeItems []auditItem
var activeSummary auditRunSummary
if initialTab == auditTabAgents {
activeItems = agentItems
activeSummary = agentSummary
} else {
activeItems = skillItems
activeSummary = skillSummary
}
displayItems := activeItems
if len(displayItems) > maxListItems {
displayItems = displayItems[:maxListItems]
}
listItems := buildGroupedAuditItems(displayItems)
l := list.New(listItems, auditDelegate{}, 0, 0)
l.Title = fmt.Sprintf("Audit results (%d scanned)", summary.Scanned)
l.Styles.Title = tc.ListTitle
l.Title = fmt.Sprintf("Audit results (%d scanned)", activeSummary.Scanned)
l.Styles.Title = theme.Title()
l.Styles.NoItems = l.Styles.NoItems.PaddingLeft(2)
l.SetStatusBarItemName(initialTab.noun(), initialTab.noun())
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
@@ -275,20 +307,43 @@ func newAuditTUIModel(results []*audit.Result, scanOutputs []audit.ScanOutput, s
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
m := auditTUIModel{
list: l,
allItems: allItems,
matchCount: len(allItems),
filterInput: fi,
summary: summary,
list: l,
allItems: activeItems,
matchCount: len(activeItems),
filterInput: fi,
summary: activeSummary,
activeTab: initialTab,
skillItems: skillItems,
agentItems: agentItems,
skillSummary: skillSummary,
agentSummary: agentSummary,
tabCounts: [2]int{len(skillItems), len(agentItems)},
}
skipGroupItem(&m.list, 1)
return m
}
func (m *auditTUIModel) switchTab() {
if m.activeTab == auditTabAgents {
m.allItems = m.agentItems
m.summary = m.agentSummary
} else {
m.allItems = m.skillItems
m.summary = m.skillSummary
}
m.filterText = ""
m.filterInput.SetValue("")
m.detailScroll = 0
m.applyFilter()
m.list.Title = fmt.Sprintf("Audit results (%d scanned)", m.summary.Scanned)
m.list.SetStatusBarItemName(m.activeTab.noun(), m.activeTab.noun())
skipGroupItem(&m.list, 1)
}
func (m auditTUIModel) Init() tea.Cmd { return nil }
func (m *auditTUIModel) applyFilter() {
@@ -391,6 +446,14 @@ func (m auditTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.detailScroll = 0
}
return m, nil
case "tab":
m.activeTab = (m.activeTab + 1) % 2
m.switchTab()
return m, nil
case "shift+tab":
m.activeTab = (m.activeTab - 1 + 2) % 2
m.switchTab()
return m, nil
}
}
@@ -426,6 +489,9 @@ func (m auditTUIModel) View() string {
// ── Horizontal split layout ──
var b strings.Builder
b.WriteString(m.renderTabBar())
b.WriteString("\n")
panelHeight := m.auditPanelHeight()
leftWidth := auditListWidth(m.termWidth)
@@ -438,7 +504,7 @@ func (m auditTUIModel) View() string {
Render(m.list.View())
// Border column
borderStyle := tc.Border.
borderStyle := theme.Dim().
Height(panelHeight).MaxHeight(panelHeight)
borderCol := strings.Repeat("│\n", panelHeight)
borderPanel := borderStyle.Render(strings.TrimRight(borderCol, "\n"))
@@ -465,7 +531,7 @@ func (m auditTUIModel) View() string {
b.WriteString(m.renderSummaryFooter())
// Help line
b.WriteString(tc.Help.Render(appendScrollInfo("↑↓ navigate ←→ page / filter Ctrl+d/u scroll detail q quit", scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo("Tab skills/agents ↑↓ navigate ←→ page / filter Ctrl+d/u scroll detail q quit", scrollInfo)))
return b.String()
}
@@ -474,6 +540,9 @@ func (m auditTUIModel) View() string {
func (m auditTUIModel) viewVertical() string {
var b strings.Builder
b.WriteString(m.renderTabBar())
b.WriteString("\n")
b.WriteString(m.list.View())
b.WriteString("\n\n")
@@ -489,17 +558,43 @@ func (m auditTUIModel) viewVertical() string {
b.WriteString(m.renderSummaryFooter())
b.WriteString(tc.Help.Render(appendScrollInfo("↑↓ navigate ←→ page / filter Ctrl+d/u scroll q quit", scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo("Tab skills/agents ↑↓ navigate ←→ page / filter Ctrl+d/u scroll q quit", scrollInfo)))
b.WriteString("\n")
return b.String()
}
func (m auditTUIModel) renderTabBar() string {
type tab struct {
label string
tab auditTab
count int
}
tabs := []tab{
{"Skills", auditTabSkills, m.tabCounts[0]},
{"Agents", auditTabAgents, m.tabCounts[1]},
}
activeStyle := lipgloss.NewStyle().Bold(true).Underline(true)
inactiveStyle := theme.Dim()
var parts []string
for _, t := range tabs {
label := fmt.Sprintf("%s(%d)", t.label, t.count)
if t.tab == m.activeTab {
parts = append(parts, activeStyle.Inherit(theme.Accent()).Render(label))
} else {
parts = append(parts, inactiveStyle.Render(label))
}
}
return " " + strings.Join(parts, " ")
}
func (m auditTUIModel) renderFilterBar() string {
return renderTUIFilterBar(
m.filterInput.View(), m.filtering, m.filterText,
m.matchCount, len(m.allItems), maxListItems,
"results", m.renderPageInfo(),
m.activeTab.noun(), m.renderPageInfo(),
)
}
@@ -512,38 +607,38 @@ func (m auditTUIModel) renderPageInfo() string {
// Line 2 (if any): category threat breakdown.
func (m auditTUIModel) renderSummaryFooter() string {
s := m.summary
pipe := tc.Dim.Render(" | ")
pipe := theme.Dim().Render(" | ")
// ── Line 1: counts + severity ──
// Label is always dim; value uses semantic color + bold for non-zero emphasis.
parts := []string{
tc.Dim.Render("Scanned: ") + tc.Emphasis.Render(formatNumber(s.Scanned)),
tc.Dim.Render("Passed: ") + tc.Dim.Render(formatNumber(s.Passed)),
theme.Dim().Render("Scanned: ") + theme.Primary().Render(formatNumber(s.Scanned)),
theme.Dim().Render("Passed: ") + theme.Dim().Render(formatNumber(s.Passed)),
}
if s.Warning > 0 {
parts = append(parts, tc.Dim.Render("Warning: ")+tc.Yellow.Bold(true).Render(formatNumber(s.Warning)))
parts = append(parts, theme.Dim().Render("Warning: ")+theme.Warning().Bold(true).Render(formatNumber(s.Warning)))
} else {
parts = append(parts, tc.Dim.Render("Warning: ")+tc.Dim.Render(formatNumber(s.Warning)))
parts = append(parts, theme.Dim().Render("Warning: ")+theme.Dim().Render(formatNumber(s.Warning)))
}
if s.Failed > 0 {
parts = append(parts, tc.Dim.Render("Failed: ")+tc.Red.Bold(true).Render(formatNumber(s.Failed)))
parts = append(parts, theme.Dim().Render("Failed: ")+theme.Danger().Bold(true).Render(formatNumber(s.Failed)))
} else {
parts = append(parts, tc.Dim.Render("Failed: ")+tc.Dim.Render(formatNumber(s.Failed)))
parts = append(parts, theme.Dim().Render("Failed: ")+theme.Dim().Render(formatNumber(s.Failed)))
}
sevParts := []string{
acSevCount(s.Critical, tc.Critical).Render(fmt.Sprintf("%d", s.Critical)),
acSevCount(s.High, tc.High).Render(fmt.Sprintf("%d", s.High)),
acSevCount(s.Medium, tc.Medium).Render(fmt.Sprintf("%d", s.Medium)),
acSevCount(s.Low, tc.Low).Render(fmt.Sprintf("%d", s.Low)),
acSevCount(s.Info, tc.Info).Render(fmt.Sprintf("%d", s.Info)),
acSevCount(s.Critical, theme.Severity("critical")).Render(fmt.Sprintf("%d", s.Critical)),
acSevCount(s.High, theme.Severity("high")).Render(fmt.Sprintf("%d", s.High)),
acSevCount(s.Medium, theme.Severity("medium")).Render(fmt.Sprintf("%d", s.Medium)),
acSevCount(s.Low, theme.Severity("low")).Render(fmt.Sprintf("%d", s.Low)),
acSevCount(s.Info, theme.Severity("info")).Render(fmt.Sprintf("%d", s.Info)),
}
sep := tc.Dim.Render("/")
parts = append(parts, tc.Dim.Render("c/h/m/l/i = ")+strings.Join(sevParts, sep))
sep := theme.Dim().Render("/")
parts = append(parts, theme.Dim().Render("c/h/m/l/i = ")+strings.Join(sevParts, sep))
parts = append(parts, tc.Dim.Render(fmt.Sprintf("Auditable: %.0f%% avg", s.AvgAnalyzability*100)))
parts = append(parts, theme.Dim().Render(fmt.Sprintf("Auditable: %.0f%% avg", s.AvgAnalyzability*100)))
if s.PolicyProfile != "" {
parts = append(parts, tc.Dim.Render("Policy: ")+tuiColorizeProfile(s.PolicyProfile))
parts = append(parts, theme.Dim().Render("Policy: ")+tuiColorizeProfile(s.PolicyProfile))
}
var b strings.Builder
@@ -554,7 +649,7 @@ func (m auditTUIModel) renderSummaryFooter() string {
// ── Line 2: category breakdown with semantic colors ──
if threatsLine := formatCategoryBreakdownTUI(s.ByCategory); threatsLine != "" {
b.WriteString(" ")
b.WriteString(tc.Dim.Render("Threats: "))
b.WriteString(theme.Dim().Render("Threats: "))
b.WriteString(threatsLine)
b.WriteString("\n")
}
@@ -570,24 +665,24 @@ func (m auditTUIModel) renderDetailContent(item auditItem) string {
r := item.result
row := func(label, value string) {
b.WriteString(tc.Label.Render(label))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(value)
b.WriteString("\n")
}
// ── Header ──
b.WriteString(tc.Title.Render(r.SkillName))
b.WriteString(theme.Title().Render(r.SkillName))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(strings.Repeat("─", 40)))
b.WriteString(theme.Dim().Render(strings.Repeat("─", 40)))
b.WriteString("\n\n")
// ── Summary section ──
// Risk — colorized by severity
riskText := fmt.Sprintf("%s (%d/100)", strings.ToUpper(r.RiskLabel), r.RiskScore)
riskStyle := tcSevStyle(r.RiskLabel)
riskStyle := theme.SeverityStyle(r.RiskLabel)
if r.RiskLabel == "clean" {
riskStyle = tc.Green
riskStyle = theme.Success()
}
row("Risk:", riskStyle.Render(riskText))
@@ -596,52 +691,52 @@ func (m auditTUIModel) renderDetailContent(item auditItem) string {
if maxSev == "" {
maxSev = "NONE"
}
maxSevStyle := tcSevStyle(maxSev)
maxSevStyle := theme.SeverityStyle(maxSev)
if strings.ToUpper(maxSev) == "NONE" {
maxSevStyle = tc.Green
maxSevStyle = theme.Success()
}
row("Max sev:", maxSevStyle.Render(maxSev))
// Block status
if r.IsBlocked {
row("Status:", tc.Red.Render("✗ BLOCKED"))
row("Status:", theme.Danger().Render("✗ BLOCKED"))
} else if len(r.Findings) == 0 {
row("Status:", tc.Green.Render("✓ Clean"))
row("Status:", theme.Success().Render("✓ Clean"))
} else {
row("Status:", tc.Yellow.Render("! Has findings (not blocked)"))
row("Status:", theme.Warning().Render("! Has findings (not blocked)"))
}
// Auditable — analyzability percentage
auditableText := fmt.Sprintf("%.0f%%", r.Analyzability*100)
if r.Analyzability >= 0.70 {
row("Auditable:", tc.Green.Render(auditableText))
row("Auditable:", theme.Success().Render(auditableText))
} else if r.TotalBytes > 0 {
row("Auditable:", tc.Yellow.Render(auditableText))
row("Auditable:", theme.Warning().Render(auditableText))
} else {
row("Auditable:", tc.Dim.Render("—"))
row("Auditable:", theme.Dim().Render("—"))
}
// Commands — tier profile
if !r.TierProfile.IsEmpty() {
row("Commands:", tc.Dim.Render(r.TierProfile.String()))
row("Commands:", theme.Dim().Render(r.TierProfile.String()))
}
// Threshold
if r.Threshold != "" {
row("Threshold:", tc.Dim.Render("severity >= ")+tcSevStyle(r.Threshold).Render(strings.ToUpper(r.Threshold)))
row("Threshold:", theme.Dim().Render("severity >= ")+theme.SeverityStyle(r.Threshold).Render(strings.ToUpper(r.Threshold)))
}
// Policy
if m.summary.PolicyProfile != "" {
policyText := tuiColorizeProfile(m.summary.PolicyProfile) +
tc.Dim.Render(" / dedupe:") + tuiColorizeDedupe(m.summary.PolicyDedupe) +
tc.Dim.Render(" / analyzers:") + tuiColorizeAnalyzers(m.summary.PolicyAnalyzers)
theme.Dim().Render(" / dedupe:") + tuiColorizeDedupe(m.summary.PolicyDedupe) +
theme.Dim().Render(" / analyzers:") + tuiColorizeAnalyzers(m.summary.PolicyAnalyzers)
row("Policy:", policyText)
}
// Scan time
if item.elapsed > 0 {
row("Scan time:", tc.Dim.Render(fmt.Sprintf("%.1fs", item.elapsed.Seconds())))
row("Scan time:", theme.Dim().Render(fmt.Sprintf("%.1fs", item.elapsed.Seconds())))
}
// Severity breakdown — only non-zero counts are colorized; zeros are dim
@@ -650,23 +745,23 @@ func (m auditTUIModel) renderDetailContent(item auditItem) string {
for _, f := range r.Findings {
counts[f.Severity]++
}
sep := tc.Dim.Render("/")
sevLine := acSevCount(counts["CRITICAL"], tc.Critical).Render(fmt.Sprintf("%d", counts["CRITICAL"])) + sep +
acSevCount(counts["HIGH"], tc.High).Render(fmt.Sprintf("%d", counts["HIGH"])) + sep +
acSevCount(counts["MEDIUM"], tc.Medium).Render(fmt.Sprintf("%d", counts["MEDIUM"])) + sep +
acSevCount(counts["LOW"], tc.Low).Render(fmt.Sprintf("%d", counts["LOW"])) + sep +
acSevCount(counts["INFO"], tc.Info).Render(fmt.Sprintf("%d", counts["INFO"]))
row("Severity:", tc.Dim.Render("c/h/m/l/i = ")+sevLine)
row("Total:", tc.Emphasis.Render(fmt.Sprintf("%d", len(r.Findings)))+tc.Dim.Render(" finding(s)"))
sep := theme.Dim().Render("/")
sevLine := acSevCount(counts["CRITICAL"], theme.Severity("critical")).Render(fmt.Sprintf("%d", counts["CRITICAL"])) + sep +
acSevCount(counts["HIGH"], theme.Severity("high")).Render(fmt.Sprintf("%d", counts["HIGH"])) + sep +
acSevCount(counts["MEDIUM"], theme.Severity("medium")).Render(fmt.Sprintf("%d", counts["MEDIUM"])) + sep +
acSevCount(counts["LOW"], theme.Severity("low")).Render(fmt.Sprintf("%d", counts["LOW"])) + sep +
acSevCount(counts["INFO"], theme.Severity("info")).Render(fmt.Sprintf("%d", counts["INFO"]))
row("Severity:", theme.Dim().Render("c/h/m/l/i = ")+sevLine)
row("Total:", theme.Primary().Render(fmt.Sprintf("%d", len(r.Findings)))+theme.Dim().Render(" finding(s)"))
}
b.WriteString("\n")
// ── Findings detail ──
if len(r.Findings) > 0 {
b.WriteString(tc.Title.Render("Findings"))
b.WriteString(theme.Title().Render("Findings"))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(strings.Repeat("─", 40)))
b.WriteString(theme.Dim().Render(strings.Repeat("─", 40)))
b.WriteString("\n\n")
sorted := make([]audit.Finding, len(r.Findings))
@@ -677,34 +772,34 @@ func (m auditTUIModel) renderDetailContent(item auditItem) string {
for idx, f := range sorted {
// [N] SEVERITY pattern
sevBadge := tcSevStyle(f.Severity).Render(strings.ToUpper(f.Severity))
header := tc.Dim.Render(fmt.Sprintf("[%d] ", idx+1))
patternText := tc.Emphasis.Bold(true).Render(f.Pattern)
sevBadge := theme.SeverityStyle(f.Severity).Render(strings.ToUpper(f.Severity))
header := theme.Dim().Render(fmt.Sprintf("[%d] ", idx+1))
patternText := theme.Primary().Bold(true).Render(f.Pattern)
b.WriteString(header + sevBadge + " " + patternText + "\n")
// Message
b.WriteString(tc.Dim.Render(" "))
b.WriteString(tc.Dim.Render(f.Message))
b.WriteString(theme.Dim().Render(" "))
b.WriteString(theme.Dim().Render(f.Message))
b.WriteString("\n")
// Metadata: ruleID / analyzer / category
if meta := findingMetaTUI(f); meta != "" {
b.WriteString(tc.Dim.Render(" "))
b.WriteString(ac.File.Render(meta))
b.WriteString(theme.Dim().Render(" "))
b.WriteString(theme.Accent().Render(meta))
b.WriteString("\n")
}
// Location: file:line
loc := fmt.Sprintf("%s:%d", f.File, f.Line)
b.WriteString(tc.Dim.Render(" "))
b.WriteString(ac.File.Render(loc))
b.WriteString(theme.Dim().Render(" "))
b.WriteString(theme.Accent().Render(loc))
b.WriteString("\n")
// Snippet — with │ gutter
if f.Snippet != "" {
gutter := tc.Dim.Render(" │ ")
gutter := theme.Dim().Render(" │ ")
b.WriteString(gutter)
b.WriteString(ac.Snippet.Render(f.Snippet))
b.WriteString(theme.Warning().Render(f.Snippet))
b.WriteString("\n")
}
@@ -716,9 +811,9 @@ func (m auditTUIModel) renderDetailContent(item auditItem) string {
}
// auditFooterLines returns the number of lines the footer occupies below the panel.
// gap(2) + filter(1) + summary(1-2) + help(1) = 5 or 6
// gap(2) + tab(1) + filter(1) + summary(1-2) + help(1) = 6 or 7
func (m auditTUIModel) auditFooterLines() int {
n := 5 // gap(2) + filter + summary-line1 + help
n := 6 // gap(2) + tab(1) + filter + summary-line1 + help
if len(m.summary.ByCategory) > 0 {
n++ // summary-line2 (threats)
}
@@ -764,23 +859,23 @@ func auditDetailPanelWidth(termWidth int) int {
func tuiColorizeProfile(profile string) string {
label := policyProfileLabel(profile)
if label == "STRICT" {
return tc.Yellow.Render(label)
return theme.Warning().Render(label)
}
return tc.Dim.Render(label)
return theme.Dim().Render(label)
}
// tuiColorizeDedupe returns a lipgloss-styled UPPERCASE dedupe mode.
func tuiColorizeDedupe(dedupe string) string {
label := policyDedupeLabel(dedupe)
if label == "LEGACY" {
return tc.Yellow.Render(label)
return theme.Warning().Render(label)
}
return tc.Dim.Render(label)
return theme.Dim().Render(label)
}
// tuiColorizeAnalyzers returns a lipgloss-styled UPPERCASE analyzer list.
func tuiColorizeAnalyzers(analyzers []string) string {
return tc.Dim.Render(policyAnalyzersLabel(analyzers))
return theme.Dim().Render(policyAnalyzersLabel(analyzers))
}
// findingMetaTUI builds a compact "ruleID / analyzer / category" string for TUI detail.
@@ -803,8 +898,12 @@ func findingMetaTUI(f audit.Finding) string {
}
// runAuditTUI starts the bubbletea TUI for audit results.
func runAuditTUI(results []*audit.Result, scanOutputs []audit.ScanOutput, summary auditRunSummary) error {
model := newAuditTUIModel(results, scanOutputs, summary)
func runAuditTUI(
skillResults []*audit.Result, skillOutputs []audit.ScanOutput, skillSummary auditRunSummary,
agentResults []*audit.Result, agentOutputs []audit.ScanOutput, agentSummary auditRunSummary,
initialTab auditTab,
) error {
model := newAuditTUIModel(skillResults, skillOutputs, skillSummary, agentResults, agentOutputs, agentSummary, initialTab)
p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
_, err := p.Run()
return err
+100 -13
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -21,10 +22,21 @@ func cmdBackup(args []string) error {
if err != nil {
return err
}
if mode == modeProject {
return fmt.Errorf("backup is not supported in project mode")
// Extract kind filter (e.g. "skillshare backup agents" or "--all").
kind, args := parseKindArgWithAll(args)
// Project mode is only supported for agents.
if mode == modeProject && kind != kindAgents && kind != kindAll {
return fmt.Errorf("backup is not supported in project mode (except for agents)")
}
cwd, _ := os.Getwd()
if mode == modeAuto && kind == kindAgents && projectConfigExists(cwd) {
mode = modeProject
}
applyModeLabel(mode)
start := time.Now()
var targetName string
doList := false
@@ -63,7 +75,11 @@ func cmdBackup(args []string) error {
return backupCleanup()
}
err = createBackup(targetName, dryRun)
if kind == kindAgents {
err = createAgentBackup(mode, cwd, targetName, dryRun)
} else {
err = createBackup(targetName, dryRun)
}
if !dryRun {
e := oplog.NewEntry("backup", statusFromErr(err), time.Since(start))
@@ -322,11 +338,24 @@ func cmdRestore(args []string) error {
if err != nil {
return err
}
if mode == modeProject {
return fmt.Errorf("restore is not supported in project mode")
// Extract kind filter (e.g. "skillshare restore agents").
// Extract kind filter (e.g. "skillshare restore agents" or "--all").
kind, args := parseKindArgWithAll(args)
// Project mode is only supported for agents.
if mode == modeProject && kind != kindAgents && kind != kindAll {
return fmt.Errorf("restore is not supported in project mode (except for agents)")
}
cwd, _ := os.Getwd()
if mode == modeAuto && kind == kindAgents && projectConfigExists(cwd) {
mode = modeProject
}
applyModeLabel(mode)
start := time.Now()
_ = start // used below
var targetName string
var fromTimestamp string
@@ -357,6 +386,11 @@ func cmdRestore(args []string) error {
}
}
// Agent restore uses agent-specific backup entries (name suffixed with "-agents")
if kind == kindAgents {
return restoreAgentBackup(mode, cwd, targetName, fromTimestamp, force, dryRun)
}
// No target specified → TUI dispatch (or plain text fallback)
if targetName == "" && fromTimestamp == "" && !dryRun {
return restoreTUIDispatch(noTUI)
@@ -460,22 +494,41 @@ func restoreTUIDispatch(noTUI bool) error {
if projectConfigExists(cwd) {
mode = modeProject
}
trashBase := resolveTrashBase(mode, cwd)
items := trash.List(trashBase)
skillTrashBase := resolveTrashBase(mode, cwd, kindSkills)
agentTrashBase := resolveTrashBase(mode, cwd, kindAgents)
// Merge skill + agent trash
var items []trash.TrashEntry
for _, e := range trash.List(skillTrashBase) {
e.Kind = "skill"
items = append(items, e)
}
for _, e := range trash.List(agentTrashBase) {
e.Kind = "agent"
items = append(items, e)
}
if len(items) == 0 {
ui.Info("Trash is empty")
return nil
}
sort.Slice(items, func(i, j int) bool {
return items[i].Date.After(items[j].Date)
})
modeLabel := "global"
if mode == modeProject {
modeLabel = "project"
}
cfgPath := resolveTrashCfgPath(mode, cwd)
destDir, err := resolveSourceDir(mode, cwd)
destDir, err := resolveSourceDir(mode, cwd, kindSkills)
if err != nil {
return err
}
return runTrashTUI(items, trashBase, destDir, cfgPath, modeLabel)
agentDestDir, err := resolveSourceDir(mode, cwd, kindAgents)
if err != nil {
return err
}
return runTrashTUI(items, skillTrashBase, agentTrashBase, destDir, agentDestDir, cfgPath, modeLabel)
}
return nil
@@ -503,6 +556,28 @@ func restoreFromLatest(targetName, targetPath string, opts backup.RestoreOptions
return nil
}
func restoreFromTimestampInDir(backupDir, targetName, targetPath, timestamp string, opts backup.RestoreOptions) error {
backupInfo, err := backup.GetBackupByTimestampInDir(backupDir, timestamp)
if err != nil {
return err
}
if err := backup.RestoreToPath(backupInfo.Path, targetName, targetPath, opts); err != nil {
return err
}
ui.Success("Restored %s from backup %s", targetName, timestamp)
return nil
}
func restoreFromLatestInDir(backupDir, targetName, targetPath string, opts backup.RestoreOptions) error {
timestamp, err := backup.RestoreLatestInDir(backupDir, targetName, targetPath, opts)
if err != nil {
return err
}
ui.Success("Restored %s from latest backup (%s)", targetName, timestamp)
return nil
}
func previewRestoreFromTimestamp(targetName, targetPath, timestamp string, opts backup.RestoreOptions) error {
backupInfo, err := backup.GetBackupByTimestamp(timestamp)
if err != nil {
@@ -537,7 +612,7 @@ func previewRestoreFromLatest(targetName, targetPath string, opts backup.Restore
}
func printBackupHelp() {
fmt.Println(`Usage: skillshare backup [target] [options]
fmt.Println(`Usage: skillshare backup [agents] [target] [options]
Create a snapshot of target skill directories.
Without arguments, backs up all targets.
@@ -546,6 +621,9 @@ Arguments:
target Target name to backup (optional; backs up all if omitted)
Options:
--all Backup both skills and agents
--project, -p Use project mode (.skillshare/backups/); agents only
--global, -g Use global mode (default for skills)
--list, -l List all existing backups
--cleanup, -c Remove old backups based on retention policy
--dry-run, -n Preview what would be backed up or cleaned up
@@ -557,11 +635,14 @@ Examples:
skillshare backup claude # Backup only claude
skillshare backup --list # List all backups
skillshare backup --cleanup # Remove old backups
skillshare backup --cleanup --dry-run # Preview cleanup`)
skillshare backup --cleanup --dry-run # Preview cleanup
skillshare backup agents # Backup all agent targets
skillshare backup agents -p # Backup project agent targets
skillshare backup --all # Backup skills + agents`)
}
func printRestoreHelp() {
fmt.Println(`Usage: skillshare restore [target] [options]
fmt.Println(`Usage: skillshare restore [agents] [target] [options]
Restore target skills from a backup snapshot.
Without arguments, launches an interactive TUI.
@@ -570,6 +651,9 @@ Arguments:
target Target name to restore (optional)
Options:
--all Restore both skills and agents
--project, -p Use project mode (.skillshare/backups/); agents only
--global, -g Use global mode (default for skills)
--from, -f <ts> Restore from specific timestamp (e.g. 2024-01-15_14-30-45)
--force Overwrite non-empty target directory
--dry-run, -n Preview what would be restored without making changes
@@ -581,5 +665,8 @@ Examples:
skillshare restore claude # Restore claude from latest backup
skillshare restore claude --from 2024-01-15_14-30-45
skillshare restore claude --dry-run # Preview restore
skillshare restore --no-tui # List backups (no TUI)`)
skillshare restore --no-tui # List backups (no TUI)
skillshare restore agents claude # Restore agents claude target
skillshare restore agents claude -p # Restore project agents
skillshare restore --all claude # Restore skills + agents`)
}
+158
View File
@@ -0,0 +1,158 @@
package main
import (
"fmt"
"path/filepath"
"skillshare/internal/backup"
"skillshare/internal/config"
"skillshare/internal/ui"
)
// createAgentBackup backs up agent target directories.
// Agent backups use "<target>-agents" as the backup entry name.
// In project mode, backups are stored under .skillshare/backups/.
func createAgentBackup(mode runMode, cwd, targetName string, dryRun bool) error {
backupDir, targets, err := resolveAgentBackupContext(mode, cwd)
if err != nil {
return err
}
modeLabel := "global"
if mode == modeProject {
modeLabel = "project"
}
ui.Header(fmt.Sprintf("Creating agent backup (%s)", modeLabel))
if dryRun {
ui.Warning("Dry run mode - no backups will be created")
}
created := 0
for _, at := range targets {
if targetName != "" && at.name != targetName {
continue
}
entryName := at.name + "-agents"
if dryRun {
ui.Info("%s: would backup agents from %s", entryName, at.agentPath)
continue
}
backupPath, backupErr := backup.CreateInDir(backupDir, entryName, at.agentPath)
if backupErr != nil {
ui.Warning("Failed to backup %s: %v", entryName, backupErr)
continue
}
if backupPath != "" {
ui.StepDone(entryName, backupPath)
created++
} else {
ui.StepSkip(entryName, "nothing to backup")
}
}
if created == 0 && !dryRun {
ui.Info("No agent targets to backup")
}
return nil
}
// restoreAgentBackup restores agent target directories from backup.
func restoreAgentBackup(mode runMode, cwd, targetName, fromTimestamp string, force, dryRun bool) error {
if targetName == "" {
return fmt.Errorf("usage: skillshare restore agents <target> [--from <timestamp>] [--force] [--dry-run]")
}
backupDir, targets, err := resolveAgentBackupContext(mode, cwd)
if err != nil {
return err
}
// Find the target's agent path.
var agentPath string
for _, at := range targets {
if at.name == targetName {
agentPath = at.agentPath
break
}
}
if agentPath == "" {
return fmt.Errorf("target '%s' has no agent path configured", targetName)
}
entryName := targetName + "-agents"
ui.Header(fmt.Sprintf("Restoring agents for %s", targetName))
if dryRun {
ui.Warning("Dry run mode - no changes will be made")
ui.Info("Would restore %s to %s", entryName, agentPath)
return nil
}
opts := backup.RestoreOptions{Force: force}
if fromTimestamp != "" {
return restoreFromTimestampInDir(backupDir, entryName, agentPath, fromTimestamp, opts)
}
return restoreFromLatestInDir(backupDir, entryName, agentPath, opts)
}
// agentTarget holds resolved name + agent path for backup/restore.
type agentTarget struct {
name string
agentPath string
}
// resolveAgentBackupContext returns the backup directory and agent-capable targets
// for the given mode.
func resolveAgentBackupContext(mode runMode, cwd string) (string, []agentTarget, error) {
if mode == modeProject {
return resolveProjectAgentBackupContext(cwd)
}
return resolveGlobalAgentBackupContext()
}
func resolveGlobalAgentBackupContext() (string, []agentTarget, error) {
cfg, err := config.Load()
if err != nil {
return "", nil, err
}
return resolveGlobalAgentBackupContextFromCfg(cfg)
}
// resolveGlobalAgentBackupContextFromCfg is like resolveGlobalAgentBackupContext
// but accepts an already-loaded config to avoid redundant config.Load() calls.
func resolveGlobalAgentBackupContextFromCfg(cfg *config.Config) (string, []agentTarget, error) {
builtinAgents := config.DefaultAgentTargets()
var targets []agentTarget
for name := range cfg.Targets {
agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name)
if agentPath != "" {
targets = append(targets, agentTarget{name: name, agentPath: agentPath})
}
}
return backup.BackupDir(), targets, nil
}
func resolveProjectAgentBackupContext(cwd string) (string, []agentTarget, error) {
projCfg, err := config.LoadProject(cwd)
if err != nil {
return "", nil, fmt.Errorf("cannot load project config: %w", err)
}
builtinAgents := config.ProjectAgentTargets()
var targets []agentTarget
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, cwd)
if agentPath != "" {
targets = append(targets, agentTarget{name: entry.Name, agentPath: agentPath})
}
}
backupDir := filepath.Join(cwd, ".skillshare", "backups")
return backupDir, targets, nil
}
+120 -23
View File
@@ -51,7 +51,7 @@ type checkOptions struct {
type skillWithMeta struct {
name string
path string
meta *install.SkillMeta
meta *install.MetadataEntry
}
// collectCheckItems reads metadata and partitions items for parallel checking.
@@ -69,31 +69,34 @@ func collectCheckItems(sourceDir string, repos []string, skills []string) (
})
}
// Load centralized metadata store once for all skills.
store := install.LoadMetadataOrNew(sourceDir)
urlGroups := make(map[string][]skillWithMeta)
var localResults []checkSkillResult
for _, skill := range skills {
skillPath := filepath.Join(sourceDir, skill)
meta, err := install.ReadMeta(skillPath)
entry := store.GetByPath(skill)
if err != nil || meta == nil || meta.RepoURL == "" {
if entry == nil || entry.RepoURL == "" {
result := checkSkillResult{Name: skill, Status: "local"}
if meta != nil {
result.Source = meta.Source
result.Version = meta.Version
if !meta.InstalledAt.IsZero() {
result.InstalledAt = meta.InstalledAt.Format("2006-01-02")
if entry != nil {
result.Source = entry.Source
result.Version = entry.Version
if !entry.InstalledAt.IsZero() {
result.InstalledAt = entry.InstalledAt.Format("2006-01-02")
}
}
localResults = append(localResults, result)
continue
}
groupKey := urlBranchKey(meta.RepoURL, meta.Branch)
groupKey := urlBranchKey(entry.RepoURL, entry.Branch)
urlGroups[groupKey] = append(urlGroups[groupKey], skillWithMeta{
name: skill,
path: skillPath,
meta: meta,
meta: entry,
})
}
@@ -171,6 +174,9 @@ func cmdCheck(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare check agents" or "--all").
kind, rest := parseKindArgWithAll(rest)
scope := "global"
if mode == modeProject {
scope = "project"
@@ -188,6 +194,12 @@ func cmdCheck(args []string) error {
cfgPath := config.ConfigPath()
if mode == modeProject {
cfgPath = config.ProjectConfigPath(cwd)
if kind == kindAgents {
agentsDir := filepath.Join(cwd, ".skillshare", "agents")
renderAgentCheck(agentsDir, opts.groups, opts.json)
logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, nil)
return nil
}
cmdErr := cmdCheckProject(cwd, opts)
logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, cmdErr)
return cmdErr
@@ -198,6 +210,14 @@ func cmdCheck(args []string) error {
return err
}
// Agent-only check: scan agents source directory and skip repo checks.
if kind == kindAgents {
agentsDir := cfg.EffectiveAgentsSource()
renderAgentCheck(agentsDir, opts.groups, opts.json)
logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, nil)
return nil
}
// No names and no groups → check all (existing behavior)
if len(opts.names) == 0 && len(opts.groups) == 0 {
cmdErr := runCheck(cfg.Source, opts.json, targetNamesFromConfig(cfg.Targets))
@@ -522,7 +542,7 @@ func resolveSkillStatuses(
// Pre-fill base result fields for each skill
type pending struct {
result checkSkillResult
meta *install.SkillMeta
meta *install.MetadataEntry
}
items := make([]pending, len(group))
for i, sw := range group {
@@ -631,13 +651,14 @@ func runCheckFiltered(sourceDir string, opts *checkOptions) error {
resolveSpinner = ui.StartSpinner("Resolving skills...")
}
checkStore, _ := install.LoadMetadata(sourceDir)
var targets []updateTarget
seen := map[string]bool{}
var resolveWarnings []string
for _, name := range opts.names {
// Check group directory first (same logic as update)
if isGroupDir(name, sourceDir) {
if isGroupDir(name, sourceDir, checkStore) {
groupMatches, groupErr := resolveGroupUpdatable(name, sourceDir)
if groupErr != nil {
resolveWarnings = append(resolveWarnings, fmt.Sprintf("%s: %v", name, groupErr))
@@ -727,10 +748,12 @@ func runCheckFiltered(sourceDir string, opts *checkOptions) error {
// Single skill: show per-skill detail like update does
if len(targets) == 1 && !targets[0].isRepo {
t := targets[0]
skillPath := filepath.Join(sourceDir, t.name)
if meta, metaErr := install.ReadMeta(skillPath); metaErr == nil && meta != nil && meta.Source != "" {
ui.StepContinue("Skill", t.name)
ui.StepContinue("Source", meta.Source)
detailStore, _ := install.LoadMetadata(sourceDir)
if detailStore != nil {
if entry := detailStore.Get(t.name); entry != nil && entry.Source != "" {
ui.StepContinue("Skill", t.name)
ui.StepContinue("Source", entry.Source)
}
}
}
}
@@ -892,8 +915,78 @@ func formatSourceShort(source string) string {
return source
}
// renderAgentCheck runs CheckAgents and displays results (text or JSON).
// If groups is non-empty, only agents in those group subdirectories are shown.
func renderAgentCheck(agentsDir string, groups []string, jsonMode bool) {
agentResults := check.CheckAgents(agentsDir)
if len(groups) > 0 {
filtered, err := filterAgentResultsByGroups(agentResults, groups, agentsDir)
if err != nil {
if jsonMode {
writeJSONError(err) //nolint:errcheck
return
}
ui.Error("%v", err)
return
}
agentResults = filtered
}
trackedIndices := make([]int, 0, len(agentResults))
tracked := make([]check.AgentCheckResult, 0, len(agentResults))
for i := range agentResults {
if agentResults[i].Source != "" {
trackedIndices = append(trackedIndices, i)
tracked = append(tracked, agentResults[i])
}
}
if len(tracked) > 0 {
if jsonMode {
check.EnrichAgentResultsWithRemote(tracked, nil)
} else {
sp := ui.StartSpinner(fmt.Sprintf("Checking %d tracked agent(s)...", len(tracked)))
check.EnrichAgentResultsWithRemote(tracked, func() { sp.Success("Check complete") })
fmt.Println()
}
for i, idx := range trackedIndices {
agentResults[idx] = tracked[i]
}
}
if jsonMode {
out, _ := json.MarshalIndent(agentResults, "", " ")
fmt.Println(string(out))
return
}
ui.Header(ui.WithModeLabel("Checking agents"))
ui.StepStart("Agents source", agentsDir)
if len(agentResults) == 0 {
ui.Info("No agents found")
} else {
fmt.Println()
for _, r := range agentResults {
switch r.Status {
case "up_to_date":
ui.ListItem("success", r.Name, "up to date")
case "update_available":
ui.ListItem("warning", r.Name, "update available")
case "drifted":
ui.ListItem("warning", r.Name, r.Message)
case "dirty":
ui.ListItem("warning", r.Name, r.Message)
case "local":
ui.ListItem("info", r.Name, "local agent")
case "error":
ui.ListItem("error", r.Name, r.Message)
}
}
}
fmt.Println()
}
func printCheckHelp() {
fmt.Println(`Usage: skillshare check [name...] [options]
fmt.Println(`Usage: skillshare check [agents] [name...] [options]
skillshare check --group <group> [options]
Check for available updates to tracked repositories and installed skills.
@@ -908,11 +1001,12 @@ Arguments:
name... Skill name(s) or tracked repo name(s) (optional)
Options:
--group, -G <name> Check all updatable skills in a group (repeatable)
--project, -p Check project-level skills (.skillshare/)
--global, -g Check global skills (~/.config/skillshare)
--json Output results as JSON
--help, -h Show this help
--all Check both skills and agents
--group, -G <name> Check all updatable skills in a group (repeatable)
--project, -p Check project-level skills (.skillshare/)
--global, -g Check global skills (~/.config/skillshare)
--json Output results as JSON
--help, -h Show this help
Examples:
skillshare check # Check all items
@@ -921,5 +1015,8 @@ Examples:
skillshare check --group frontend # Check all skills in frontend/
skillshare check x -G backend # Mix names and groups
skillshare check --json # Output as JSON (for CI)
skillshare check -p # Check project skills`)
skillshare check -p # Check project skills
skillshare check agents # Check all agents
skillshare check agents -G demo # Check agents in demo/
skillshare check --all # Check skills + agents`)
}
+41 -21
View File
@@ -4,6 +4,8 @@ import (
"fmt"
"strings"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
)
@@ -78,12 +80,26 @@ type checklistModel struct {
func newChecklistModel(cfg checklistConfig) checklistModel {
sel := make(map[int]bool, len(cfg.items))
selCount := 0
selectedIdx := -1
for i, item := range cfg.items {
if item.preSelected {
if cfg.singleSelect {
if selectedIdx == -1 {
sel[i] = true
selCount = 1
selectedIdx = i
}
continue
}
sel[i] = true
selCount++
}
}
if cfg.singleSelect && len(cfg.items) > 0 && selectedIdx == -1 {
sel[0] = true
selCount = 1
selectedIdx = 0
}
hasDesc := false
for _, item := range cfg.items {
@@ -96,10 +112,13 @@ func newChecklistModel(cfg checklistConfig) checklistModel {
listItems := makeChecklistItems(cfg.items, sel, cfg.singleSelect)
l := list.New(listItems, newPrefixDelegate(hasDesc), 0, 0)
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(true)
l.SetFilteringEnabled(true)
l.SetShowHelp(false)
if cfg.singleSelect && selectedIdx >= 0 {
l.Select(selectedIdx)
}
itemName := cfg.itemName
if itemName == "" {
@@ -170,17 +189,8 @@ func (m checklistModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
break
}
if m.singleSelect {
// Radio: clear all, select this one
wasSelected := m.selected[item.idx]
for k := range m.selected {
delete(m.selected, k)
}
if !wasSelected {
m.selected[item.idx] = true
m.selCount = 1
} else {
m.selCount = 0
}
// Radio: select the focused item and keep exactly one choice active.
m.selectSingle(item.idx)
} else {
m.selected[item.idx] = !m.selected[item.idx]
if m.selected[item.idx] {
@@ -210,17 +220,12 @@ func (m checklistModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "enter":
if m.singleSelect {
// Single select: enter confirms current cursor item
item, ok := m.list.SelectedItem().(checklistItem)
if !ok {
break
}
// If nothing was space-toggled, select the cursor item
if m.selCount == 0 {
m.result = []int{item.idx}
} else {
m.result = m.collectSelected()
}
m.selectSingle(item.idx)
m.result = []int{item.idx}
} else {
m.result = m.collectSelected()
}
@@ -235,9 +240,24 @@ func (m checklistModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
m.list, cmd = m.list.Update(msg)
if m.singleSelect && m.list.FilterState() != list.Filtering && len(m.items) > 0 {
m.selectSingle(m.list.Index())
}
return m, cmd
}
func (m *checklistModel) selectSingle(idx int) {
if !m.singleSelect || idx < 0 || idx >= len(m.items) {
return
}
for k := range m.selected {
delete(m.selected, k)
}
m.selected[idx] = true
m.selCount = 1
m.refreshItems()
}
func (m *checklistModel) refreshItems() {
cursor := m.list.Index()
items := makeChecklistItems(m.items, m.selected, m.singleSelect)
@@ -267,14 +287,14 @@ func (m checklistModel) View() string {
var help string
if m.singleSelect {
help = "↑↓ navigate space/enter select / filter esc cancel"
help = "↑↓ navigate enter select / filter esc cancel"
} else {
help = "↑↓ navigate space toggle a all enter confirm / filter esc cancel"
}
if m.header != "" {
help += " │ " + m.header
}
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
+114 -1
View File
@@ -1,6 +1,10 @@
package main
import "testing"
import (
"testing"
tea "github.com/charmbracelet/bubbletea"
)
func TestChecklistItem_Title_MultiSelect(t *testing.T) {
item := checklistItem{idx: 0, label: "claude", selected: false, singleSelect: false}
@@ -47,6 +51,115 @@ func TestChecklistItem_PreSelected(t *testing.T) {
}
}
func TestChecklistItem_PreSelected_SingleSelectUsesFirstAndMovesCursor(t *testing.T) {
cfg := checklistConfig{
title: "Test",
singleSelect: true,
items: []checklistItemData{
{label: "a", preSelected: false},
{label: "b", preSelected: true},
{label: "c", preSelected: true},
},
}
m := newChecklistModel(cfg)
if m.selCount != 1 {
t.Fatalf("selCount: got %d, want 1", m.selCount)
}
if !m.selected[1] {
t.Fatalf("item 1 should be selected")
}
if m.list.Index() != 1 {
t.Fatalf("cursor index: got %d, want 1", m.list.Index())
}
}
func TestChecklistItem_SingleSelectDefaultsToFirst(t *testing.T) {
cfg := checklistConfig{
title: "Test",
singleSelect: true,
items: []checklistItemData{
{label: "a"},
{label: "b"},
},
}
m := newChecklistModel(cfg)
if m.selCount != 1 {
t.Fatalf("selCount: got %d, want 1", m.selCount)
}
if !m.selected[0] {
t.Fatalf("item 0 should be selected by default")
}
if m.list.Index() != 0 {
t.Fatalf("cursor index: got %d, want 0", m.list.Index())
}
}
func TestChecklistItem_SingleSelectNavigationUpdatesSelection(t *testing.T) {
cfg := checklistConfig{
title: "Test",
singleSelect: true,
items: []checklistItemData{
{label: "a", preSelected: true},
{label: "b"},
{label: "c"},
},
}
model := newChecklistModel(cfg)
modelAny, _ := model.Update(tea.KeyMsg{Type: tea.KeyDown})
m := modelAny.(checklistModel)
if !m.selected[1] {
t.Fatalf("item 1 should be selected after moving cursor down")
}
if m.selected[0] {
t.Fatalf("item 0 should no longer be selected after moving cursor down")
}
if m.list.Index() != 1 {
t.Fatalf("cursor index: got %d, want 1", m.list.Index())
}
}
func TestChecklistItem_SingleSelectEnterConfirmsFocusedItem(t *testing.T) {
cfg := checklistConfig{
title: "Test",
singleSelect: true,
items: []checklistItemData{
{label: "a", preSelected: true},
{label: "b"},
},
}
model := newChecklistModel(cfg)
modelAny, _ := model.Update(tea.KeyMsg{Type: tea.KeyDown})
m := modelAny.(checklistModel)
modelAny, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = modelAny.(checklistModel)
if len(m.result) != 1 || m.result[0] != 1 {
t.Fatalf("result: got %v, want [1]", m.result)
}
}
func TestChecklistItem_SingleSelectSpaceDoesNotClearSelection(t *testing.T) {
cfg := checklistConfig{
title: "Test",
singleSelect: true,
items: []checklistItemData{
{label: "a", preSelected: true},
{label: "b"},
},
}
model := newChecklistModel(cfg)
modelAny, _ := model.Update(tea.KeyMsg{Type: tea.KeySpace})
m := modelAny.(checklistModel)
if m.selCount != 1 {
t.Fatalf("selCount: got %d, want 1", m.selCount)
}
if !m.selected[0] {
t.Fatalf("item 0 should remain selected after pressing space")
}
}
func TestChecklistItem_FilterValue(t *testing.T) {
item := checklistItem{idx: 0, label: "claude", desc: "AI assistant"}
if got := item.FilterValue(); got != "claude AI assistant" {
+68 -212
View File
@@ -3,29 +3,15 @@ package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/pterm/pterm"
"skillshare/internal/config"
"skillshare/internal/oplog"
"skillshare/internal/sync"
"skillshare/internal/ui"
)
// collectJSONOutput is the JSON representation for collect --json output.
type collectJSONOutput struct {
Pulled []string `json:"pulled"`
Skipped []string `json:"skipped"`
Failed map[string]string `json:"failed"`
DryRun bool `json:"dry_run"`
Duration string `json:"duration"`
}
// collectLocalSkills collects local skills from targets (non-symlinked)
func collectLocalSkills(targets map[string]config.TargetConfig, source, globalMode string) []sync.LocalSkillInfo {
// collectLocalSkills collects local skills from targets (non-symlinked).
func collectLocalSkills(targets map[string]config.TargetConfig, source, globalMode string, warn bool) []sync.LocalSkillInfo {
var allLocalSkills []sync.LocalSkillInfo
for name, target := range targets {
sc := target.SkillsConfig()
@@ -35,7 +21,9 @@ func collectLocalSkills(targets map[string]config.TargetConfig, source, globalMo
}
skills, err := sync.FindLocalSkills(sc.Path, source, mode)
if err != nil {
ui.Warning("%s: %v", name, err)
if warn {
ui.Warning("%s: %v", name, err)
}
continue
}
for i := range skills {
@@ -46,12 +34,8 @@ func collectLocalSkills(targets map[string]config.TargetConfig, source, globalMo
return allLocalSkills
}
// displayLocalSkills shows the local skills found
func displayLocalSkills(skills []sync.LocalSkillInfo) {
ui.Header(ui.WithModeLabel("Local skills found"))
for _, skill := range skills {
ui.ListItem("info", skill.Name, fmt.Sprintf("[%s] %s", skill.TargetName, skill.Path))
}
func skillDisplayItem(s sync.LocalSkillInfo) collectDisplayItem {
return collectDisplayItem{Name: s.Name, TargetName: s.TargetName, Path: s.Path}
}
func cmdCollect(args []string) error {
@@ -82,125 +66,63 @@ func cmdCollect(args []string) error {
applyModeLabel(mode)
kind, rest := parseKindArg(rest)
opts := parseCollectOptions(rest)
scope := "global"
cfgPath := config.ConfigPath()
if mode == modeProject {
err := cmdCollectProject(rest, cwd)
logCollectOp(config.ProjectConfigPath(cwd), start, err)
return err
scope = "project"
cfgPath = config.ProjectConfigPath(cwd)
}
dryRun := false
force := false
collectAll := false
jsonOutput := false
var targetName string
summary := newCollectLogSummary(kind, scope, opts)
for _, arg := range rest {
switch arg {
case "--dry-run", "-n":
dryRun = true
case "--force", "-f":
force = true
case "--all", "-a":
collectAll = true
case "--json":
jsonOutput = true
default:
if targetName == "" && !strings.HasPrefix(arg, "-") {
targetName = arg
}
switch mode {
case modeProject:
if kind == kindAgents {
summary, err = cmdCollectProjectAgents(cwd, opts, start)
} else {
summary, err = cmdCollectProject(opts, cwd, start)
}
default:
cfg, loadErr := config.Load()
if loadErr != nil {
err = collectCommandError(loadErr, opts.jsonOutput)
logCollectOp(cfgPath, start, err, summary)
return err
}
if kind == kindAgents {
summary, err = cmdCollectAgents(cfg, opts, start)
} else {
summary, err = cmdCollectGlobal(cfg, opts, start)
}
}
// --json implies --force (skip confirmation prompts)
if jsonOutput {
force = true
}
cfg, err := config.Load()
if err != nil {
if jsonOutput {
return writeJSONError(err)
}
return err
}
// Select targets to collect from
targets, err := selectCollectTargets(cfg, targetName, collectAll)
if err != nil {
return err
}
if targets == nil {
return nil // User needs to specify target
}
// Collect all local skills
var sp *ui.Spinner
if !jsonOutput {
ui.Header(ui.WithModeLabel("Collect"))
sp = ui.StartSpinner("Scanning for local skills...")
}
allLocalSkills := collectLocalSkills(targets, cfg.Source, cfg.Mode)
if len(allLocalSkills) == 0 {
if sp != nil {
sp.Success("No local skills found")
}
if jsonOutput {
return collectOutputJSON(nil, dryRun, start, nil)
}
return nil
}
if sp != nil {
sp.Success(fmt.Sprintf("Found %d local skill(s)", len(allLocalSkills)))
displayLocalSkills(allLocalSkills)
}
if dryRun {
if jsonOutput {
names := make([]string, len(allLocalSkills))
for i, s := range allLocalSkills {
names[i] = s.Name
}
logCollectOp(config.ConfigPath(), start, nil)
return collectOutputJSON(&sync.PullResult{Pulled: names}, true, start, nil)
}
ui.Info("Dry run - no changes made")
return nil
}
// Confirm unless --force (JSON implies force)
if !force {
if !confirmCollect() {
ui.Info("Cancelled")
return nil
}
}
if jsonOutput {
result, collectErr := sync.PullSkills(allLocalSkills, cfg.Source, sync.PullOptions{
DryRun: dryRun,
Force: force,
})
logCollectOp(config.ConfigPath(), start, collectErr)
return collectOutputJSON(result, dryRun, start, collectErr)
}
err = executeCollect(allLocalSkills, cfg.Source, dryRun, force)
logCollectOp(config.ConfigPath(), start, err)
logCollectOp(cfgPath, start, err, summary)
return err
}
func logCollectOp(cfgPath string, start time.Time, cmdErr error) {
e := oplog.NewEntry("collect", statusFromErr(cmdErr), time.Since(start))
if cmdErr != nil {
e.Message = cmdErr.Error()
func cmdCollectGlobal(cfg *config.Config, opts collectOptions, start time.Time) (collectLogSummary, error) {
summary := newCollectLogSummary(kindSkills, "global", opts)
targets, err := selectCollectTargets(cfg, opts.targetName, opts.collectAll, opts.jsonOutput)
if err != nil {
return summary, collectCommandError(err, opts.jsonOutput)
}
oplog.WriteWithLimit(cfgPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
if targets == nil {
return summary, nil
}
return runCollectPlan(collectPlan{
kind: kindSkills, source: cfg.Source,
scan: func(warn bool) collectResources {
skills := collectLocalSkills(targets, cfg.Source, cfg.Mode, warn)
return toCollectResources(skills, cfg.Source, skillDisplayItem, sync.PullSkills)
},
}, opts, start, "global")
}
func selectCollectTargets(cfg *config.Config, targetName string, collectAll bool) (map[string]config.TargetConfig, error) {
func selectCollectTargets(cfg *config.Config, targetName string, collectAll, jsonOutput bool) (map[string]config.TargetConfig, error) {
if targetName != "" {
if t, exists := cfg.Targets[targetName]; exists {
return map[string]config.TargetConfig{targetName: t}, nil
@@ -208,11 +130,18 @@ func selectCollectTargets(cfg *config.Config, targetName string, collectAll bool
return nil, fmt.Errorf("target '%s' not found", targetName)
}
if len(cfg.Targets) == 0 {
return cfg.Targets, nil
}
if collectAll || len(cfg.Targets) == 1 {
return cfg.Targets, nil
}
// If no target specified and multiple targets exist, ask or require --all
if jsonOutput {
return nil, fmt.Errorf("multiple targets found; specify a target name or use --all")
}
ui.Warning("Multiple targets found. Specify a target name or use --all")
fmt.Println(" Available targets:")
for name := range cfg.Targets {
@@ -221,85 +150,10 @@ func selectCollectTargets(cfg *config.Config, targetName string, collectAll bool
return nil, nil
}
func confirmCollect() bool {
fmt.Println()
fmt.Print("Collect these skills to source? [y/N]: ")
var input string
fmt.Scanln(&input)
input = strings.ToLower(strings.TrimSpace(input))
return input == "y" || input == "yes"
}
func executeCollect(skills []sync.LocalSkillInfo, source string, dryRun, force bool) error {
ui.Header(ui.WithModeLabel("Collecting skills"))
result, err := sync.PullSkills(skills, source, sync.PullOptions{
DryRun: dryRun,
Force: force,
})
if err != nil {
return err
}
// Display results
for _, name := range result.Pulled {
ui.StepDone(name, "copied to source")
}
for _, name := range result.Skipped {
ui.StepSkip(name, "already exists in source, use --force to overwrite")
}
for name, err := range result.Failed {
ui.StepFail(name, err.Error())
}
ui.OperationSummary("Collect", 0,
ui.Metric{Label: "collected", Count: len(result.Pulled), HighlightColor: pterm.Green},
ui.Metric{Label: "skipped", Count: len(result.Skipped), HighlightColor: pterm.Yellow},
ui.Metric{Label: "failed", Count: len(result.Failed), HighlightColor: pterm.Red},
)
if len(result.Pulled) > 0 {
showCollectNextSteps(source)
}
return nil
}
// collectOutputJSON converts a collect result to JSON and writes to stdout.
func collectOutputJSON(result *sync.PullResult, dryRun bool, start time.Time, collectErr error) error {
output := collectJSONOutput{
DryRun: dryRun,
Duration: formatDuration(start),
}
output.Failed = make(map[string]string)
if result != nil {
output.Pulled = result.Pulled
output.Skipped = result.Skipped
for k, v := range result.Failed {
output.Failed[k] = v.Error()
}
}
return writeJSONResult(&output, collectErr)
}
func showCollectNextSteps(source string) {
fmt.Println()
if ui.ModeLabel == "project" {
ui.Info("Run 'skillshare sync -p' to distribute to all targets")
return
}
ui.Info("Run 'skillshare sync' to distribute to all targets")
// Check if source has git
gitDir := filepath.Join(source, ".git")
if _, err := os.Stat(gitDir); err == nil {
ui.Info("Commit changes: cd %s && git add . && git commit", source)
}
}
func printCollectHelp() {
fmt.Println(`Usage: skillshare collect [target] [options]
fmt.Println(`Usage: skillshare collect [agents] [target] [options]
Collect local skills from target(s) to source directory.
Collect local skills or agents from target(s) to the source directory.
Arguments:
[target] Target name to collect from (optional)
@@ -307,14 +161,16 @@ Arguments:
Options:
--all, -a Collect from all targets
--dry-run, -n Preview changes without applying
--force, -f Skip confirmation prompts
--json Output results as JSON
--force, -f Overwrite existing items in source and skip confirmation
--json Output results as JSON (implies --force)
--project, -p Use project-level config
--global, -g Use global config
--help, -h Show this help
Examples:
skillshare collect claude Collect from Claude target
skillshare collect --all Collect from all targets
skillshare collect --dry-run Preview what would be collected`)
skillshare collect claude Collect skills from the Claude target
skillshare collect --all Collect skills from all targets
skillshare collect --dry-run Preview what would be collected
skillshare collect agents claude Collect agents from the Claude target
skillshare collect agents --json Collect agents as JSON output`)
}
+172
View File
@@ -0,0 +1,172 @@
package main
import (
"fmt"
"path/filepath"
"time"
"skillshare/internal/config"
"skillshare/internal/sync"
"skillshare/internal/ui"
)
func collectLocalAgents(targets map[string]string, source string, warn bool) []sync.LocalAgentInfo {
var allLocalAgents []sync.LocalAgentInfo
for name, targetPath := range targets {
agents, err := sync.FindLocalAgents(targetPath, source)
if err != nil {
if warn {
ui.Warning("%s: %v", name, err)
}
continue
}
for i := range agents {
agents[i].TargetName = name
}
allLocalAgents = append(allLocalAgents, agents...)
}
return allLocalAgents
}
func agentDisplayItem(a sync.LocalAgentInfo) collectDisplayItem {
return collectDisplayItem{Name: a.Name, TargetName: a.TargetName, Path: a.Path}
}
func cmdCollectAgents(cfg *config.Config, opts collectOptions, start time.Time) (collectLogSummary, error) {
summary := newCollectLogSummary(kindAgents, "global", opts)
targets, err := selectCollectAgentTargets(cfg, opts.targetName, opts.collectAll, opts.jsonOutput)
if err != nil {
return summary, collectCommandError(err, opts.jsonOutput)
}
if targets == nil {
return summary, nil
}
source := cfg.EffectiveAgentsSource()
return runCollectPlan(collectPlan{
kind: kindAgents, source: source,
scan: func(warn bool) collectResources {
agents := collectLocalAgents(targets, source, warn)
return toCollectResources(agents, source, agentDisplayItem, sync.PullAgents)
},
}, opts, start, "global")
}
func selectCollectAgentTargets(cfg *config.Config, targetName string, collectAll, jsonOutput bool) (map[string]string, error) {
builtinAgents := config.DefaultAgentTargets()
if targetName != "" {
target, ok := cfg.Targets[targetName]
if !ok {
return nil, fmt.Errorf("target '%s' not found", targetName)
}
agentPath := resolveAgentTargetPath(target, builtinAgents, targetName)
if agentPath == "" {
return nil, fmt.Errorf("target '%s' does not support agents", targetName)
}
return map[string]string{targetName: agentPath}, nil
}
targets := make(map[string]string)
for name := range cfg.Targets {
agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name)
if agentPath == "" {
continue
}
targets[name] = agentPath
}
if len(targets) == 0 {
return targets, nil
}
if collectAll || len(targets) <= 1 {
return targets, nil
}
if jsonOutput {
return nil, fmt.Errorf("multiple targets found; specify a target name or use --all")
}
ui.Warning("Multiple targets found. Specify a target name or use --all")
fmt.Println(" Available targets:")
for name := range targets {
fmt.Printf(" - %s\n", name)
}
return nil, nil
}
func cmdCollectProjectAgents(projectRoot string, opts collectOptions, start time.Time) (collectLogSummary, error) {
summary := newCollectLogSummary(kindAgents, "project", opts)
projCfg, err := config.LoadProject(projectRoot)
if err != nil {
return summary, collectCommandError(fmt.Errorf("cannot load project config: %w", err), opts.jsonOutput)
}
targets, err := selectCollectProjectAgentTargets(projCfg, projectRoot, opts.targetName, opts.collectAll, opts.jsonOutput)
if err != nil {
return summary, collectCommandError(err, opts.jsonOutput)
}
if targets == nil {
return summary, nil
}
source := filepath.Join(projectRoot, ".skillshare", "agents")
return runCollectPlan(collectPlan{
kind: kindAgents, source: source,
scan: func(warn bool) collectResources {
agents := collectLocalAgents(targets, source, warn)
return toCollectResources(agents, source, agentDisplayItem, sync.PullAgents)
},
}, opts, start, "project")
}
func selectCollectProjectAgentTargets(projCfg *config.ProjectConfig, projectRoot, targetName string, collectAll, jsonOutput bool) (map[string]string, error) {
builtinAgents := config.ProjectAgentTargets()
if targetName != "" {
for _, entry := range projCfg.Targets {
if entry.Name != targetName {
continue
}
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
if agentPath == "" {
return nil, fmt.Errorf("target '%s' does not support agents in project config", targetName)
}
return map[string]string{targetName: agentPath}, nil
}
return nil, fmt.Errorf("target '%s' not found in project config", targetName)
}
targets := make(map[string]string)
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
if agentPath == "" {
continue
}
targets[entry.Name] = agentPath
}
if len(targets) == 0 {
return targets, nil
}
if collectAll || len(targets) <= 1 {
return targets, nil
}
if jsonOutput {
return nil, fmt.Errorf("multiple targets found; specify a target name or use --all")
}
ui.Warning("Multiple targets found. Specify a target name or use --all")
fmt.Println(" Available targets:")
for _, entry := range projCfg.Targets {
if _, ok := targets[entry.Name]; ok {
fmt.Printf(" - %s\n", entry.Name)
}
}
return nil, nil
}
+24 -50
View File
@@ -2,73 +2,39 @@ package main
import (
"fmt"
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/sync"
"skillshare/internal/ui"
)
func cmdCollectProject(args []string, root string) error {
dryRun := false
force := false
collectAll := false
var targetName string
for _, arg := range args {
switch arg {
case "--dry-run", "-n":
dryRun = true
case "--force", "-f":
force = true
case "--all", "-a":
collectAll = true
default:
if targetName == "" && !strings.HasPrefix(arg, "-") {
targetName = arg
}
}
}
func cmdCollectProject(opts collectOptions, root string, start time.Time) (collectLogSummary, error) {
summary := newCollectLogSummary(kindSkills, "project", opts)
runtime, err := loadProjectRuntime(root)
if err != nil {
return err
return summary, collectCommandError(err, opts.jsonOutput)
}
targets, err := selectCollectProjectTargets(runtime, targetName, collectAll)
targets, err := selectCollectProjectTargets(runtime, opts.targetName, opts.collectAll, opts.jsonOutput)
if err != nil {
return err
return summary, collectCommandError(err, opts.jsonOutput)
}
if targets == nil {
return nil
return summary, nil
}
ui.Header(ui.WithModeLabel("Collect"))
sp := ui.StartSpinner("Scanning for local skills...")
allLocalSkills := collectLocalSkills(targets, runtime.sourcePath, "")
if len(allLocalSkills) == 0 {
sp.Success("No local skills found")
return nil
}
sp.Success(fmt.Sprintf("Found %d local skill(s)", len(allLocalSkills)))
displayLocalSkills(allLocalSkills)
if dryRun {
ui.Info("Dry run - no changes made")
return nil
}
if !force {
if !confirmCollect() {
ui.Info("Cancelled")
return nil
}
}
return executeCollect(allLocalSkills, runtime.sourcePath, dryRun, force)
return runCollectPlan(collectPlan{
kind: kindSkills, source: runtime.sourcePath,
scan: func(warn bool) collectResources {
skills := collectLocalSkills(targets, runtime.sourcePath, "", warn)
return toCollectResources(skills, runtime.sourcePath, skillDisplayItem, sync.PullSkills)
},
}, opts, start, "project")
}
func selectCollectProjectTargets(runtime *projectRuntime, targetName string, collectAll bool) (map[string]config.TargetConfig, error) {
func selectCollectProjectTargets(runtime *projectRuntime, targetName string, collectAll, jsonOutput bool) (map[string]config.TargetConfig, error) {
if targetName != "" {
if t, ok := runtime.targets[targetName]; ok {
return map[string]config.TargetConfig{targetName: t}, nil
@@ -76,10 +42,18 @@ func selectCollectProjectTargets(runtime *projectRuntime, targetName string, col
return nil, fmt.Errorf("target '%s' not found in project config", targetName)
}
if len(runtime.targets) == 0 {
return runtime.targets, nil
}
if collectAll || len(runtime.targets) == 1 {
return runtime.targets, nil
}
if jsonOutput {
return nil, fmt.Errorf("multiple targets found; specify a target name or use --all")
}
ui.Warning("Multiple targets found. Specify a target name or use --all")
fmt.Println(" Available targets:")
for _, entry := range runtime.config.Targets {
+304
View File
@@ -0,0 +1,304 @@
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/pterm/pterm"
"skillshare/internal/oplog"
"skillshare/internal/sync"
"skillshare/internal/ui"
)
type collectOptions struct {
dryRun bool
force bool
collectAll bool
jsonOutput bool
targetName string
}
type collectLogSummary struct {
Kind string
Scope string
Pulled int
Skipped int
Failed int
DryRun bool
Force bool
}
type collectDisplayItem struct {
Name string
TargetName string
Path string
}
// collectJSONOutput is the JSON representation for collect --json output.
type collectJSONOutput struct {
Pulled []string `json:"pulled"`
Skipped []string `json:"skipped"`
Failed map[string]string `json:"failed"`
DryRun bool `json:"dry_run"`
Duration string `json:"duration"`
}
func parseCollectOptions(args []string) collectOptions {
opts := collectOptions{}
for _, arg := range args {
switch arg {
case "--dry-run", "-n":
opts.dryRun = true
case "--force", "-f":
opts.force = true
case "--all", "-a":
opts.collectAll = true
case "--json":
opts.jsonOutput = true
default:
if opts.targetName == "" && !strings.HasPrefix(arg, "-") {
opts.targetName = arg
}
}
}
if opts.jsonOutput {
opts.force = true
}
return opts
}
func newCollectLogSummary(kind resourceKindFilter, scope string, opts collectOptions) collectLogSummary {
return collectLogSummary{
Kind: kind.String(),
Scope: scope,
DryRun: opts.dryRun,
Force: opts.force,
}
}
func updateCollectLogSummary(summary collectLogSummary, result *sync.PullResult) collectLogSummary {
if result == nil {
return summary
}
summary.Pulled = len(result.Pulled)
summary.Skipped = len(result.Skipped)
summary.Failed = len(result.Failed)
return summary
}
func collectCommandError(err error, jsonOutput bool) error {
if err == nil {
return nil
}
if jsonOutput {
return writeJSONError(err)
}
return err
}
// collectPlan describes what to collect (kind + source) and how to scan for it.
// The scan callback is called lazily so the spinner wraps the actual I/O.
type collectPlan struct {
kind resourceKindFilter
source string
scan func(warn bool) collectResources
}
// collectResources holds the results of scanning a target for local resources.
type collectResources struct {
items []collectDisplayItem
names []string
pull func(sync.PullOptions) (*sync.PullResult, error)
}
// toCollectResources converts a typed slice into collectResources.
// toDisplay maps each item to a collectDisplayItem; pull is the batch pull function.
func toCollectResources[T any](
items []T,
source string,
toDisplay func(T) collectDisplayItem,
pull func([]T, string, sync.PullOptions) (*sync.PullResult, error),
) collectResources {
display := make([]collectDisplayItem, len(items))
names := make([]string, len(items))
for i, item := range items {
d := toDisplay(item)
display[i] = d
names[i] = d.Name
}
return collectResources{
items: display,
names: names,
pull: func(opts sync.PullOptions) (*sync.PullResult, error) {
return pull(items, source, opts)
},
}
}
// runCollectPlan is the unified collection flow for both skills and agents.
func runCollectPlan(plan collectPlan, opts collectOptions, start time.Time, scope string) (collectLogSummary, error) {
label := plan.kind.String()
summary := newCollectLogSummary(plan.kind, scope, opts)
var sp *ui.Spinner
if !opts.jsonOutput {
header := "Collect"
if plan.kind == kindAgents {
header = "Collect agents"
}
ui.Header(ui.WithModeLabel(header))
sp = ui.StartSpinner(fmt.Sprintf("Scanning for local %s...", label))
}
res := plan.scan(!opts.jsonOutput)
if len(res.items) == 0 {
if sp != nil {
sp.Success(fmt.Sprintf("No local %s found", label))
}
if opts.jsonOutput {
return summary, collectOutputJSON(nil, opts.dryRun, start, nil)
}
return summary, nil
}
if sp != nil {
sp.Success(fmt.Sprintf("Found %d local %s", len(res.items), label))
displayLocalCollectItems(fmt.Sprintf("Local %s found", label), res.items)
}
if opts.dryRun {
result := &sync.PullResult{Pulled: res.names}
summary = updateCollectLogSummary(summary, result)
if opts.jsonOutput {
return summary, collectOutputJSON(result, true, start, nil)
}
ui.Info("Dry run - no changes made")
return summary, nil
}
if !opts.force {
if !confirmCollect(label) {
ui.Info("Cancelled")
return summary, nil
}
}
result, collectErr := res.pull(sync.PullOptions{
DryRun: opts.dryRun,
Force: opts.force,
})
summary = updateCollectLogSummary(summary, result)
if opts.jsonOutput {
return summary, collectOutputJSON(result, opts.dryRun, start, collectErr)
}
if collectErr != nil {
return summary, collectErr
}
return summary, renderCollectResult(label, result, plan.source)
}
func displayLocalCollectItems(title string, items []collectDisplayItem) {
ui.Header(ui.WithModeLabel(title))
for _, item := range items {
ui.ListItem("info", item.Name, fmt.Sprintf("[%s] %s", item.TargetName, item.Path))
}
}
func confirmCollect(resourceLabel string) bool {
fmt.Println()
fmt.Printf("Collect these %s to source? [y/N]: ", resourceLabel)
var input string
fmt.Scanln(&input)
input = strings.ToLower(strings.TrimSpace(input))
return input == "y" || input == "yes"
}
func renderCollectResult(resourceLabel string, result *sync.PullResult, source string) error {
ui.Header(ui.WithModeLabel("Collecting " + resourceLabel))
for _, name := range result.Pulled {
ui.StepDone(name, "copied to source")
}
for _, name := range result.Skipped {
ui.StepSkip(name, "already exists in source, use --force to overwrite")
}
for name, err := range result.Failed {
ui.StepFail(name, err.Error())
}
ui.OperationSummary("Collect", 0,
ui.Metric{Label: "collected", Count: len(result.Pulled), HighlightColor: pterm.Green},
ui.Metric{Label: "skipped", Count: len(result.Skipped), HighlightColor: pterm.Yellow},
ui.Metric{Label: "failed", Count: len(result.Failed), HighlightColor: pterm.Red},
)
if len(result.Pulled) > 0 {
showCollectNextSteps(resourceLabel, source)
}
return nil
}
// collectOutputJSON converts a collect result to JSON and writes to stdout.
func collectOutputJSON(result *sync.PullResult, dryRun bool, start time.Time, collectErr error) error {
output := collectJSONOutput{
DryRun: dryRun,
Duration: formatDuration(start),
Failed: make(map[string]string),
}
if result != nil {
output.Pulled = result.Pulled
output.Skipped = result.Skipped
for k, v := range result.Failed {
output.Failed[k] = v.Error()
}
}
return writeJSONResult(&output, collectErr)
}
func showCollectNextSteps(resourceLabel, source string) {
fmt.Println()
if resourceLabel == "agents" {
if ui.ModeLabel == "project" {
ui.Info("Run 'skillshare sync -p agents' to distribute to all agent targets")
} else {
ui.Info("Run 'skillshare sync agents' to distribute to all agent targets")
}
} else if ui.ModeLabel == "project" {
ui.Info("Run 'skillshare sync -p' to distribute to all targets")
} else {
ui.Info("Run 'skillshare sync' to distribute to all targets")
}
gitDir := filepath.Join(source, ".git")
if _, err := os.Stat(gitDir); err == nil {
ui.Info("Commit changes: cd %s && git add . && git commit", source)
}
}
func logCollectOp(cfgPath string, start time.Time, cmdErr error, summary collectLogSummary) {
status := statusFromErr(cmdErr)
if cmdErr == nil && summary.Failed > 0 {
status = "partial"
}
e := oplog.NewEntry("collect", status, time.Since(start))
e.Args = map[string]any{
"kind": summary.Kind,
"scope": summary.Scope,
"pulled": summary.Pulled,
"skipped": summary.Skipped,
"failed": summary.Failed,
"dry_run": summary.DryRun,
"force": summary.Force,
}
if cmdErr != nil {
e.Message = cmdErr.Error()
}
oplog.WriteWithLimit(cfgPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
}
+37 -19
View File
@@ -45,6 +45,7 @@ type diffJSONTarget struct {
type diffJSONItem struct {
Action string `json:"action"`
Name string `json:"name"`
Kind string `json:"kind,omitempty"` // "skill" or "agent"
Reason string `json:"reason"`
IsSync bool `json:"is_sync"`
}
@@ -72,6 +73,9 @@ func cmdDiff(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare diff agents").
kind, rest := parseKindArg(rest)
scope := "global"
cfgPath := config.ConfigPath()
if mode == modeProject {
@@ -104,9 +108,9 @@ func cmdDiff(args []string) error {
var cmdErr error
if mode == modeProject {
cmdErr = cmdDiffProject(cwd, targetName, opts, start)
cmdErr = cmdDiffProject(cwd, targetName, kind, opts, start)
} else {
cmdErr = cmdDiffGlobal(targetName, opts, start)
cmdErr = cmdDiffGlobal(targetName, kind, opts, start)
}
logDiffOp(cfgPath, targetName, scope, 0, start, cmdErr)
return cmdErr
@@ -146,6 +150,7 @@ type targetDiffResult struct {
type copyDiffEntry struct {
action string // "add", "modify", "remove"
name string
kind string // "skill" or "agent" (empty defaults to "skill")
reason string
isSync bool // true = needs sync, false = local-only
files []fileDiffEntry // file-level diffs (nil until populated)
@@ -357,12 +362,17 @@ func (dp *diffProgress) stop() {
}
}
func cmdDiffGlobal(targetName string, opts diffRenderOpts, start time.Time) error {
func cmdDiffGlobal(targetName string, kind resourceKindFilter, opts diffRenderOpts, start time.Time) error {
cfg, err := config.Load()
if err != nil {
return err
}
// Agent-only diff
if kind == kindAgents {
return diffGlobalAgents(cfg, targetName, opts, start)
}
var spinner *ui.Spinner
if !opts.jsonOutput {
spinner = ui.StartSpinner("Discovering skills")
@@ -469,6 +479,9 @@ func cmdDiffGlobal(targetName string, opts diffRenderOpts, start time.Time) erro
})
}
// Merge agent diffs into skill results so they appear together
results = mergeAgentDiffsGlobal(cfg, results, targetName)
if opts.jsonOutput {
return diffOutputJSONWithExtras(results, extrasResults, start)
}
@@ -482,6 +495,20 @@ func cmdDiffGlobal(targetName string, opts diffRenderOpts, start time.Time) erro
return nil
}
func diffItemToJSON(item copyDiffEntry) diffJSONItem {
k := item.kind
if k == "" {
k = "skill"
}
return diffJSONItem{
Action: item.action,
Name: item.name,
Kind: k,
Reason: item.reason,
IsSync: item.isSync,
}
}
func diffOutputJSON(results []targetDiffResult, start time.Time) error {
output := diffJSONOutput{
Duration: formatDuration(start),
@@ -496,12 +523,7 @@ func diffOutputJSON(results []targetDiffResult, start time.Time) error {
Exclude: r.exclude,
}
for _, item := range r.items {
jt.Items = append(jt.Items, diffJSONItem{
Action: item.action,
Name: item.name,
Reason: item.reason,
IsSync: item.isSync,
})
jt.Items = append(jt.Items, diffItemToJSON(item))
}
output.Targets = append(output.Targets, jt)
}
@@ -528,12 +550,7 @@ func diffOutputJSONWithExtras(results []targetDiffResult, extrasResults []extraD
Exclude: r.exclude,
}
for _, item := range r.items {
jt.Items = append(jt.Items, diffJSONItem{
Action: item.action,
Name: item.name,
Reason: item.reason,
IsSync: item.isSync,
})
jt.Items = append(jt.Items, diffItemToJSON(item))
}
o.Targets = append(o.Targets, jt)
}
@@ -804,7 +821,7 @@ func categorizeItems(items []copyDiffEntry) []actionCategory {
for _, item := range items {
switch {
case item.reason == "source only":
case item.reason == "source only" || item.reason == "not in target":
add("new", "new", "New", item.name)
case item.reason == "deleted from target":
add("restore", "new", "Restore", item.name)
@@ -814,7 +831,7 @@ func categorizeItems(items []copyDiffEntry) []actionCategory {
add("override", "override", "Local Override", item.name)
case strings.Contains(item.reason, "orphan"):
add("orphan", "orphan", "Orphan", item.name)
case item.reason == "local only" || item.reason == "not in source":
case item.reason == "local only" || item.reason == "not in source" || item.reason == "local file":
add("local", "local", "Local Only", item.name)
default:
add("warn", "warn", item.reason, item.name)
@@ -1041,7 +1058,7 @@ func pluralS(n int) string {
}
func printDiffHelp() {
fmt.Println(`Usage: skillshare diff [target] [options]
fmt.Println(`Usage: skillshare diff [agents|all] [target] [options]
Show differences between source skills and target directories.
Previews what 'sync' would change without modifying anything.
@@ -1063,5 +1080,6 @@ Examples:
skillshare diff claude # Diff a single target
skillshare diff -p # Diff project-mode targets
skillshare diff --stat # Show file-level stat
skillshare diff --patch # Show full text diff`)
skillshare diff --patch # Show full text diff
skillshare diff agents # Diff agents targets only`)
}
+286
View File
@@ -0,0 +1,286 @@
package main
import (
"os"
"path/filepath"
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/resource"
"skillshare/internal/ui"
"skillshare/internal/utils"
)
// diffProjectAgents computes agent diffs for project mode.
func diffProjectAgents(root, targetName string, opts diffRenderOpts, start time.Time) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
}
rt, err := loadProjectRuntime(root)
if err != nil {
return err
}
agentsSource := rt.agentsSourcePath
agents, _ := resource.AgentKind{}.Discover(agentsSource)
builtinAgents := config.ProjectAgentTargets()
var results []targetDiffResult
for _, entry := range rt.config.Targets {
if targetName != "" && entry.Name != targetName {
continue
}
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, root)
if agentPath == "" {
continue
}
r := computeAgentDiff(entry.Name, agentPath, agents)
results = append(results, r)
}
if opts.jsonOutput {
return diffOutputJSON(results, start)
}
if len(results) == 0 {
ui.Info("No agent-capable targets found")
return nil
}
renderGroupedDiffs(results, opts)
return nil
}
// diffGlobalAgents computes agent diffs for global mode.
func diffGlobalAgents(cfg *config.Config, targetName string, opts diffRenderOpts, start time.Time) error {
agentsSource := cfg.EffectiveAgentsSource()
agents, _ := resource.AgentKind{}.Discover(agentsSource)
builtinAgents := config.DefaultAgentTargets()
var results []targetDiffResult
for name := range cfg.Targets {
if targetName != "" && name != targetName {
continue
}
agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name)
if agentPath == "" {
continue
}
r := computeAgentDiff(name, agentPath, agents)
results = append(results, r)
}
if opts.jsonOutput {
return diffOutputJSON(results, start)
}
if len(results) == 0 {
ui.Info("No agent-capable targets found")
return nil
}
renderGroupedDiffs(results, opts)
return nil
}
// mergeAgentDiffsGlobal computes agent diffs for all targets and merges them
// into existing skill diff results. Targets with agent diffs get their items
// appended; targets without a skill result get a new entry.
func mergeAgentDiffsGlobal(cfg *config.Config, results []targetDiffResult, targetName string) []targetDiffResult {
agentsSource := cfg.EffectiveAgentsSource()
agents, _ := resource.AgentKind{}.Discover(agentsSource)
builtinAgents := config.DefaultAgentTargets()
var agentResults []targetDiffResult
for name := range cfg.Targets {
if targetName != "" && name != targetName {
continue
}
agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name)
if agentPath == "" {
continue
}
agentResults = append(agentResults, computeAgentDiff(name, agentPath, agents))
}
return mergeAgentResults(results, agentResults)
}
// mergeAgentDiffsProject computes agent diffs for project targets and merges
// them into existing skill diff results.
func mergeAgentDiffsProject(root string, results []targetDiffResult, targetName string) []targetDiffResult {
if !projectConfigExists(root) {
return results
}
rt, err := loadProjectRuntime(root)
if err != nil {
return results
}
agentsSource := rt.agentsSourcePath
agents, _ := resource.AgentKind{}.Discover(agentsSource)
builtinAgents := config.ProjectAgentTargets()
var agentResults []targetDiffResult
for _, entry := range rt.config.Targets {
if targetName != "" && entry.Name != targetName {
continue
}
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, root)
if agentPath == "" {
continue
}
agentResults = append(agentResults, computeAgentDiff(entry.Name, agentPath, agents))
}
return mergeAgentResults(results, agentResults)
}
// mergeAgentResults merges agent diff results into skill results by target name.
func mergeAgentResults(skillResults, agentResults []targetDiffResult) []targetDiffResult {
if len(agentResults) == 0 {
return skillResults
}
idx := make(map[string]int, len(skillResults))
for i, r := range skillResults {
idx[r.name] = i
}
for _, ar := range agentResults {
if len(ar.items) == 0 {
continue
}
if i, ok := idx[ar.name]; ok {
skillResults[i].items = append(skillResults[i].items, ar.items...)
skillResults[i].syncCount += ar.syncCount
skillResults[i].localCount += ar.localCount
if !ar.synced {
skillResults[i].synced = false
}
} else {
skillResults = append(skillResults, ar)
}
}
return skillResults
}
// computeAgentDiff compares source agents against a target directory.
func computeAgentDiff(targetName, targetDir string, agents []resource.DiscoveredResource) targetDiffResult {
r := targetDiffResult{
name: targetName,
mode: "merge",
synced: true,
}
// Build map of expected agents
expected := make(map[string]resource.DiscoveredResource, len(agents))
for _, a := range agents {
expected[a.FlatName] = a
}
// Check what exists in target (store type for symlink detection)
existing := make(map[string]os.FileMode) // key=filename, value=type bits
if entries, err := os.ReadDir(targetDir); err == nil {
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(strings.ToLower(e.Name()), ".md") {
continue
}
existing[e.Name()] = e.Type()
}
}
// Missing in target (need sync)
for flatName, agent := range expected {
fileType, ok := existing[flatName]
if !ok {
r.items = append(r.items, copyDiffEntry{
action: "add",
name: flatName,
kind: "agent",
reason: "not in target",
isSync: true,
})
r.synced = false
r.syncCount++
continue
}
targetPath := filepath.Join(targetDir, flatName)
if fileType&os.ModeSymlink != 0 || utils.IsSymlinkOrJunction(targetPath) {
absLink, err := utils.ResolveLinkTarget(targetPath)
if err != nil {
r.items = append(r.items, copyDiffEntry{
action: "modify",
name: flatName,
kind: "agent",
reason: "link target unreadable",
isSync: true,
})
r.synced = false
r.syncCount++
continue
}
absSource, _ := filepath.Abs(agent.AbsPath)
if !utils.PathsEqual(absLink, absSource) {
r.items = append(r.items, copyDiffEntry{
action: "modify",
name: flatName,
kind: "agent",
reason: "symlink points elsewhere",
isSync: true,
})
r.synced = false
r.syncCount++
}
continue
}
r.items = append(r.items, copyDiffEntry{
action: "modify",
name: flatName,
kind: "agent",
reason: "local copy (sync --force to replace)",
isSync: true,
})
r.synced = false
r.syncCount++
}
// Extra in target (orphans)
for name, fileType := range existing {
if _, ok := expected[name]; !ok {
targetPath := filepath.Join(targetDir, name)
if fileType&os.ModeSymlink != 0 || utils.IsSymlinkOrJunction(targetPath) {
r.items = append(r.items, copyDiffEntry{
action: "remove",
name: name,
kind: "agent",
reason: "orphan symlink",
isSync: true,
})
r.synced = false
r.syncCount++
} else {
r.items = append(r.items, copyDiffEntry{
action: "local",
name: name,
kind: "agent",
reason: "local file",
})
r.localCount++
}
}
}
r.synced = r.syncCount == 0 && r.localCount == 0
return r
}
+7 -1
View File
@@ -10,7 +10,10 @@ import (
"skillshare/internal/ui"
)
func cmdDiffProject(root, targetName string, opts diffRenderOpts, start time.Time) error {
func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffRenderOpts, start time.Time) error {
if kind == kindAgents {
return diffProjectAgents(root, targetName, opts, start)
}
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
@@ -122,6 +125,9 @@ func cmdDiffProject(root, targetName string, opts diffRenderOpts, start time.Tim
})
}
// Merge agent diffs into skill results so they appear together
results = mergeAgentDiffsProject(root, results, targetName)
if opts.jsonOutput {
return diffOutputJSONWithExtras(results, extrasResults, start)
}
+106 -85
View File
@@ -8,6 +8,8 @@ import (
"strings"
"sync"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
@@ -42,30 +44,30 @@ type diffExtraItem struct {
}
func (i diffExtraItem) Title() string {
icon := "✓"
if i.result.errMsg != "" {
r := i.result
var icon, desc string
if r.errMsg != "" {
icon = "✗"
} else if !i.result.synced {
desc = r.errMsg
} else if r.synced {
icon = "✓"
desc = "synced"
} else {
icon = "~"
desc = fmt.Sprintf("%d diff", len(r.items))
}
return fmt.Sprintf("%s %s → %s", icon, i.result.extraName, shortenPath(i.result.targetPath))
return fmt.Sprintf("%s %s → %s %s", icon, r.extraName, shortenPath(r.targetPath), theme.Dim().Render(desc))
}
func (i diffExtraItem) Description() string {
if i.result.errMsg != "" {
return i.result.errMsg
}
if i.result.synced {
return fmt.Sprintf("synced (%s)", i.result.mode)
}
return fmt.Sprintf("%d difference(s) (%s)", len(i.result.items), i.result.mode)
}
func (i diffExtraItem) Description() string { return "" }
func (i diffExtraItem) FilterValue() string { return i.result.extraName }
// diffSeparatorItem is a non-selectable visual separator between skills and extras.
// diffSeparatorItem is a non-selectable visual separator / group header.
type diffSeparatorItem struct {
label string
count int // 0 = no count displayed
space bool // true = empty spacer row
}
func (s diffSeparatorItem) Title() string { return s.label }
@@ -96,13 +98,21 @@ func (d diffItemDelegate) Render(w io.Writer, m list.Model, index int, item list
}
func renderDiffSeparatorRow(w io.Writer, sep diffSeparatorItem, width int) {
label := tc.Dim.Render(sep.label)
if sep.space {
fmt.Fprint(w, "")
return
}
label := sep.label
if sep.count > 0 {
label += fmt.Sprintf(" (%d)", sep.count)
}
label = theme.Dim().Render(label)
lineWidth := width - lipgloss.Width(label) - 3
if lineWidth < 2 {
lineWidth = 2
}
line := strings.Repeat("─", lineWidth)
fmt.Fprint(w, tc.Dim.Render("─ ")+label+" "+tc.Dim.Render(line))
fmt.Fprint(w, theme.Dim().Render("─ ")+label+" "+theme.Dim().Render(line))
}
// skipDiffSeparator advances the list selection past diffSeparatorItem entries.
@@ -124,21 +134,10 @@ func skipDiffSeparator(l *list.Model, direction int) {
func (i diffTargetItem) Title() string {
r := i.result
if r.errMsg != "" {
return fmt.Sprintf("%s %s", tc.Red.Render("✗"), r.name)
return fmt.Sprintf("%s %s", theme.Danger().Render("✗"), r.name)
}
if r.synced {
return fmt.Sprintf("%s %s", tc.Green.Render("✓"), r.name)
}
return fmt.Sprintf("%s %s", tc.Yellow.Render("!"), r.name)
}
func (i diffTargetItem) Description() string {
r := i.result
if r.errMsg != "" {
return "error"
}
if r.synced {
return "synced"
return fmt.Sprintf("%s %s", theme.Success().Render("✓"), r.name)
}
var parts []string
if r.syncCount > 0 {
@@ -147,12 +146,15 @@ func (i diffTargetItem) Description() string {
if r.localCount > 0 {
parts = append(parts, fmt.Sprintf("%d local", r.localCount))
}
if len(parts) == 0 {
return "0 diff(s)"
desc := "0 diff(s)"
if len(parts) > 0 {
desc = strings.Join(parts, ", ")
}
return strings.Join(parts, ", ")
return fmt.Sprintf("%s %s %s", theme.Warning().Render("!"), r.name, theme.Dim().Render(desc))
}
func (i diffTargetItem) Description() string { return "" }
func (i diffTargetItem) FilterValue() string { return i.result.name }
// --- Model ---
@@ -211,19 +213,22 @@ func newDiffTUIModel(results []targetDiffResult, extrasSlice ...[]extraDiffResul
extras = extrasSlice[0]
}
listItems := make([]list.Item, len(sorted))
for i, r := range sorted {
listItems[i] = diffTargetItem{result: r}
// Build list items with group headers
var listItems []list.Item
listItems = append(listItems, diffSeparatorItem{label: "Targets", count: len(sorted)})
for _, r := range sorted {
listItems = append(listItems, diffTargetItem{result: r})
}
// Append extras with a separator
// Append extras with spacer + separator
if len(extras) > 0 {
listItems = append(listItems, diffSeparatorItem{label: "Extras"})
listItems = append(listItems, diffSeparatorItem{space: true})
listItems = append(listItems, diffSeparatorItem{label: "Extras", count: len(extras)})
for _, r := range extras {
listItems = append(listItems, diffExtraItem{result: r})
}
}
delegate := diffItemDelegate{inner: newPrefixDelegate(true)}
delegate := diffItemDelegate{inner: newPrefixDelegate(false)}
tl := list.New(listItems, delegate, 0, 0)
var errN, diffN, syncN int
@@ -248,20 +253,21 @@ func newDiffTUIModel(results []targetDiffResult, extrasSlice ...[]extraDiffResul
titleParts = append(titleParts, fmt.Sprintf("%d ok", syncN))
}
tl.Title = fmt.Sprintf("Diff — %s", strings.Join(titleParts, ", "))
tl.Styles.Title = tc.ListTitle
tl.Styles.Title = theme.Title()
tl.SetShowStatusBar(false)
tl.SetFilteringEnabled(false)
tl.SetShowHelp(false)
tl.SetShowPagination(false)
skipDiffSeparator(&tl, 1)
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
return diffTUIModel{
allItems: sorted,
@@ -460,12 +466,14 @@ func (m diffTUIModel) handleDiffKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
func (m *diffTUIModel) applyDiffFilter() {
needle := strings.ToLower(m.filterText)
if needle == "" {
items := make([]list.Item, len(m.allItems))
for i, r := range m.allItems {
items[i] = diffTargetItem{result: r}
var items []list.Item
items = append(items, diffSeparatorItem{label: "Targets", count: len(m.allItems)})
for _, r := range m.allItems {
items = append(items, diffTargetItem{result: r})
}
if len(m.allExtras) > 0 {
items = append(items, diffSeparatorItem{label: "Extras"})
items = append(items, diffSeparatorItem{space: true})
items = append(items, diffSeparatorItem{label: "Extras", count: len(m.allExtras)})
for _, r := range m.allExtras {
items = append(items, diffExtraItem{result: r})
}
@@ -473,6 +481,7 @@ func (m *diffTUIModel) applyDiffFilter() {
m.matchCount = len(items)
m.targetList.SetItems(items)
m.targetList.ResetSelected()
skipDiffSeparator(&m.targetList, 1)
m.cachedItems = nil // invalidate cache
return
}
@@ -536,7 +545,7 @@ func (m diffTUIModel) viewDiffHorizontal() string {
b.WriteString(m.renderDiffFilterBar())
// Help
b.WriteString(tc.Help.Render(appendScrollInfo("↑↓ navigate / filter Enter expand Ctrl+d/u scroll q quit", scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo("↑↓ navigate / filter Enter expand Ctrl+d/u scroll q quit", scrollInfo)))
b.WriteString("\n")
return b.String()
@@ -556,7 +565,7 @@ func (m diffTUIModel) viewDiffVertical() string {
b.WriteString(detailStr)
b.WriteString("\n")
b.WriteString(tc.Help.Render(appendScrollInfo("↑↓ navigate / filter Enter expand Ctrl+d/u scroll q quit", scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo("↑↓ navigate / filter Enter expand Ctrl+d/u scroll q quit", scrollInfo)))
b.WriteString("\n")
return b.String()
@@ -577,8 +586,8 @@ func (m diffTUIModel) buildExtraDetail(selected diffExtraItem) string {
var b strings.Builder
row := func(label, value string) {
b.WriteString(tc.Label.Render(label))
b.WriteString(tc.Value.Render(value))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(lipgloss.NewStyle().Render(value))
b.WriteString("\n")
}
@@ -588,17 +597,17 @@ func (m diffTUIModel) buildExtraDetail(selected diffExtraItem) string {
b.WriteString("\n")
if r.errMsg != "" {
b.WriteString(tc.Red.Render(" " + r.errMsg))
b.WriteString(theme.Danger().Render(" " + r.errMsg))
b.WriteString("\n")
return b.String()
}
if r.synced {
b.WriteString(tc.Green.Render(" ✓ Fully synced"))
b.WriteString(theme.Success().Render(" ✓ Fully synced"))
b.WriteString("\n")
return b.String()
}
b.WriteString(tc.Yellow.Render(fmt.Sprintf(" %d difference(s):", len(r.items))))
b.WriteString(theme.Warning().Render(fmt.Sprintf(" %d difference(s):", len(r.items))))
b.WriteString("\n")
hasLocal := false
for _, item := range r.items {
@@ -606,16 +615,16 @@ func (m diffTUIModel) buildExtraDetail(selected diffExtraItem) string {
var style lipgloss.Style
switch item.action {
case "add":
prefix, style = "+ ", tc.Green
prefix, style = "+ ", theme.Success()
case "remove":
prefix, style = "- ", tc.Red
prefix, style = "- ", theme.Danger()
case "modify":
prefix, style = "~ ", tc.Cyan
prefix, style = "~ ", theme.Accent()
if item.reason == "not a symlink (local file)" {
hasLocal = true
}
default:
prefix, style = " ", tc.Dim
prefix, style = " ", theme.Dim()
}
b.WriteString(style.Render(fmt.Sprintf(" %s%s %s", prefix, item.file, item.reason)))
b.WriteString("\n")
@@ -623,12 +632,12 @@ func (m diffTUIModel) buildExtraDetail(selected diffExtraItem) string {
// Next Steps
b.WriteString("\n")
b.WriteString(tc.Title.Render("── Next Steps ──"))
b.WriteString(theme.Title().Render("── Next Steps ──"))
b.WriteString("\n")
b.WriteString(tc.Cyan.Render(" → skillshare sync extras"))
b.WriteString(theme.Accent().Render(" → skillshare sync extras"))
b.WriteString("\n")
if hasLocal {
b.WriteString(tc.Cyan.Render(" → skillshare extras collect " + r.extraName))
b.WriteString(theme.Accent().Render(" → skillshare extras collect " + r.extraName))
b.WriteString("\n")
}
@@ -653,8 +662,8 @@ func (m diffTUIModel) buildDiffDetail() string {
var b strings.Builder
row := func(label, value string) {
b.WriteString(tc.Label.Render(label))
b.WriteString(tc.Value.Render(value))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(lipgloss.NewStyle().Render(value))
b.WriteString("\n")
}
@@ -677,14 +686,14 @@ func (m diffTUIModel) buildDiffDetail() string {
// Error
if r.errMsg != "" {
b.WriteString(tc.Red.Render(" " + r.errMsg))
b.WriteString(theme.Danger().Render(" " + r.errMsg))
b.WriteString("\n")
return b.String()
}
// Fully synced
if r.synced {
b.WriteString(tc.Green.Render(" ✓ Fully synced"))
b.WriteString(theme.Success().Render(" ✓ Fully synced"))
b.WriteString("\n")
return b.String()
}
@@ -695,6 +704,14 @@ func (m diffTUIModel) buildDiffDetail() string {
return b.String()
}
// Build agent name set for [A] badge rendering
agentNames := make(map[string]bool, len(m.cachedItems))
for _, item := range m.cachedItems {
if item.kind == "agent" {
agentNames[item.name] = true
}
}
// Use cached sorted categories (refreshed on selection change)
cats := m.cachedCats
for _, cat := range cats {
@@ -707,19 +724,19 @@ func (m diffTUIModel) buildDiffDetail() string {
var kindStyle lipgloss.Style
switch cat.kind {
case "new", "restore":
kindStyle = tc.Green
kindStyle = theme.Success()
case "modified":
kindStyle = tc.Cyan
kindStyle = theme.Accent()
case "override":
kindStyle = tc.Yellow
kindStyle = theme.Warning()
case "orphan":
kindStyle = tc.Red
kindStyle = theme.Danger()
case "local":
kindStyle = tc.Dim
kindStyle = theme.Dim()
case "warn":
kindStyle = tc.Red
kindStyle = theme.Danger()
default:
kindStyle = tc.Dim
kindStyle = theme.Dim()
}
header := fmt.Sprintf(" %s %d %s:", cat.label, n, skillWord)
@@ -728,7 +745,11 @@ func (m diffTUIModel) buildDiffDetail() string {
if cat.expand {
for _, name := range cat.names {
b.WriteString(tc.Dim.Render(" " + name))
if agentNames[name] {
b.WriteString(" " + theme.Accent().Render("[A]") + " " + theme.Dim().Render(name))
} else {
b.WriteString(theme.Dim().Render(" " + name))
}
b.WriteString("\n")
}
}
@@ -738,20 +759,20 @@ func (m diffTUIModel) buildDiffDetail() string {
if m.expandedSkill != "" {
if len(m.expandedFiles) > 0 {
b.WriteString("\n")
b.WriteString(tc.Separator.Render(fmt.Sprintf("── %s files ──", m.expandedSkill)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("── %s files ──", m.expandedSkill)))
b.WriteString("\n")
for _, f := range m.expandedFiles {
var icon string
var style lipgloss.Style
switch f.Action {
case "add":
icon, style = "+", tc.Green
icon, style = "+", theme.Success()
case "delete":
icon, style = "-", tc.Red
icon, style = "-", theme.Danger()
case "modify":
icon, style = "~", tc.Cyan
icon, style = "~", theme.Accent()
default:
icon, style = "?", tc.Dim
icon, style = "?", theme.Dim()
}
b.WriteString(style.Render(fmt.Sprintf(" %s %s", icon, f.RelPath)))
b.WriteString("\n")
@@ -761,25 +782,25 @@ func (m diffTUIModel) buildDiffDetail() string {
// Unified diff content
if m.expandedDiff != "" {
b.WriteString("\n")
b.WriteString(tc.Separator.Render(fmt.Sprintf("── %s diff ──", m.expandedSkill)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("── %s diff ──", m.expandedSkill)))
b.WriteString("\n")
for _, line := range strings.Split(strings.TrimRight(m.expandedDiff, "\n"), "\n") {
switch {
case strings.HasPrefix(line, "+ "):
b.WriteString(tc.Green.Render(line))
b.WriteString(theme.Success().Render(line))
case strings.HasPrefix(line, "- "):
b.WriteString(tc.Red.Render(line))
b.WriteString(theme.Danger().Render(line))
case strings.HasPrefix(line, "--- "):
b.WriteString(tc.Cyan.Render(line))
b.WriteString(theme.Accent().Render(line))
default:
b.WriteString(tc.Dim.Render(line))
b.WriteString(theme.Dim().Render(line))
}
b.WriteString("\n")
}
}
if len(m.expandedFiles) == 0 && m.expandedDiff == "" {
b.WriteString("\n")
b.WriteString(tc.Dim.Render(" (No file-level diff available)"))
b.WriteString(theme.Dim().Render(" (No file-level diff available)"))
b.WriteString("\n")
}
}
@@ -798,7 +819,7 @@ func (m diffTUIModel) buildDiffDetail() string {
}
if len(hints) > 0 {
b.WriteString("\n")
b.WriteString(tc.Title.Render("── Next Steps ──"))
b.WriteString(theme.Title().Render("── Next Steps ──"))
b.WriteString("\n")
seen := map[string]bool{}
for _, h := range hints {
@@ -806,7 +827,7 @@ func (m diffTUIModel) buildDiffDetail() string {
continue
}
seen[h] = true
b.WriteString(tc.Cyan.Render(fmt.Sprintf(" → skillshare %s", h)))
b.WriteString(theme.Accent().Render(fmt.Sprintf(" → skillshare %s", h)))
b.WriteString("\n")
}
}
+182 -41
View File
@@ -13,8 +13,10 @@ import (
"skillshare/internal/backup"
"skillshare/internal/config"
"skillshare/internal/install"
"skillshare/internal/resource"
"skillshare/internal/skillignore"
"skillshare/internal/sync"
"skillshare/internal/theme"
"skillshare/internal/trash"
"skillshare/internal/ui"
"skillshare/internal/utils"
@@ -141,7 +143,7 @@ func cmdDoctorGlobal(jsonMode bool) error {
ui.Header("Storage")
checkBackupStatus(result, false, backup.BackupDir())
checkTrashStatus(result, trash.TrashDir())
checkVersionDoctor(cfg, result)
checkVersionDoctor(cfg, result, false)
if jsonMode {
return finalizeDoctorJSON(restoreUI, result, updateCh)
@@ -187,10 +189,11 @@ func cmdDoctorProject(root string, jsonMode bool) error {
}
cfg := &config.Config{
Source: rt.sourcePath,
Targets: rt.targets,
Mode: "merge",
Audit: rt.config.Audit,
Source: rt.sourcePath,
AgentsSource: rt.agentsSourcePath,
Targets: rt.targets,
Mode: "merge",
Audit: rt.config.Audit,
}
runDoctorChecks(cfg, result, true)
@@ -198,7 +201,7 @@ func cmdDoctorProject(root string, jsonMode bool) error {
ui.Header("Storage")
checkBackupStatus(result, true, "")
checkTrashStatus(result, trash.ProjectTrashDir(root))
checkVersionDoctor(cfg, result)
checkVersionDoctor(cfg, result, true)
if jsonMode {
return finalizeDoctorJSON(restoreUI, result, updateCh)
@@ -220,8 +223,10 @@ func runDoctorChecks(cfg *config.Config, result *doctorResult, isProject bool) {
sp.Stop()
checkSource(cfg, result, discovered, discoverErr)
checkAgentsSource(cfg, result)
checkSkillignore(result, stats)
checkSymlinkSupport(result)
checkTheme(result)
if !isProject {
checkGitStatus(cfg.Source, result)
@@ -231,7 +236,7 @@ func runDoctorChecks(cfg *config.Config, result *doctorResult, isProject bool) {
checkSkillsValidity(cfg.Source, result, discovered)
checkSkillIntegrity(result, discovered)
checkSkillTargetsField(result, discovered, targetNamesFromConfig(cfg.Targets))
targetCache := checkTargets(cfg, result)
targetCache := checkTargets(cfg, result, isProject)
printSymlinkCompatHint(cfg.Targets, cfg.Mode, isProject)
checkSyncDrift(cfg, result, discovered, targetCache)
checkBrokenSymlinks(cfg, result)
@@ -303,6 +308,39 @@ func checkSource(cfg *config.Config, result *doctorResult, discovered []sync.Dis
result.addCheck("source", checkPass, fmt.Sprintf("Source: %s (%d skills)", cfg.Source, skillCount), nil)
}
func checkAgentsSource(cfg *config.Config, result *doctorResult) {
agentsSource := cfg.EffectiveAgentsSource()
info, err := os.Stat(agentsSource)
if err != nil {
if os.IsNotExist(err) {
ui.Info("Agents source: %s (not created yet)", agentsSource)
result.addCheck("agents_source", checkPass, fmt.Sprintf("Agents source: %s (not created yet)", agentsSource), nil)
return
}
ui.Error("Agents source error: %s", err)
result.addError()
result.addCheck("agents_source", checkError, fmt.Sprintf("Agents source error: %v", err), nil)
return
}
if !info.IsDir() {
ui.Error("Agents source is not a directory: %s", agentsSource)
result.addError()
result.addCheck("agents_source", checkError, fmt.Sprintf("Agents source is not a directory: %s", agentsSource), nil)
return
}
agentCount := 0
entries, _ := os.ReadDir(agentsSource)
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(strings.ToLower(e.Name()), ".md") {
agentCount++
}
}
ui.Success("Agents source: %s (%d agents)", agentsSource, agentCount)
result.addCheck("agents_source", checkPass, fmt.Sprintf("Agents source: %s (%d agents)", agentsSource, agentCount), nil)
}
func checkSymlinkSupport(result *doctorResult) {
testLink := filepath.Join(os.TempDir(), "skillshare_symlink_test")
testTarget := filepath.Join(os.TempDir(), "skillshare_symlink_target")
@@ -324,6 +362,60 @@ func checkSymlinkSupport(result *doctorResult) {
result.addCheck("symlink_support", checkPass, "Link support: OK", nil)
}
// checkTheme reports the resolved theme mode and source. Emits a warning
// status when the theme fell back to dark due to probe failure or non-TTY
// environments — users can resolve by setting SKILLSHARE_THEME explicitly.
func checkTheme(result *doctorResult) {
tm := theme.Get()
var status string
switch tm.Source {
case "env", "detected", "no-color":
status = checkPass
case "fallback-dark-no-tty", "fallback-dark-probe-failed":
status = checkWarning
default:
status = checkInfo
}
msg := fmt.Sprintf("Theme: %s (%s)", tm.Mode, tm.Source)
if tm.NoColor {
msg = "Theme: no-color mode"
}
details := []string{
fmt.Sprintf("source: %s", tm.Source),
fmt.Sprintf("override: SKILLSHARE_THEME=%s", envOrDefault("SKILLSHARE_THEME", "auto")),
fmt.Sprintf("no_color: %v", tm.NoColor),
fmt.Sprintf("term: %s", envOrDefault("TERM", "(unset)")),
}
switch status {
case checkPass:
ui.Success(msg)
case checkWarning:
ui.Warning(msg)
if tm.Source == "fallback-dark-probe-failed" {
ui.Info(" Tip: set SKILLSHARE_THEME=light or SKILLSHARE_THEME=dark for best colors")
}
default:
ui.Info(msg)
}
if status == checkWarning {
result.addWarning()
}
result.addCheck("theme", status, msg, details)
}
// envOrDefault returns the value of env var name or the given default.
func envOrDefault(name, def string) string {
if v := os.Getenv(name); v != "" {
return v
}
return def
}
// cachedTargetStatus stores CheckStatusMerge/Copy results so checkSyncDrift
// can reuse them without a second call.
type cachedTargetStatus struct {
@@ -332,10 +424,23 @@ type cachedTargetStatus struct {
status sync.TargetStatus
}
func checkTargets(cfg *config.Config, result *doctorResult) map[string]cachedTargetStatus {
func checkTargets(cfg *config.Config, result *doctorResult, isProject bool) map[string]cachedTargetStatus {
ui.Header("Checking targets")
cache := make(map[string]cachedTargetStatus)
// Prepare agent context for per-target agent checks
agentsSource := cfg.EffectiveAgentsSource()
agentsExist := dirExists(agentsSource)
var discoveredAgents []resource.DiscoveredResource
if agentsExist {
all, _ := resource.AgentKind{}.Discover(agentsSource)
discoveredAgents = resource.ActiveAgents(all)
}
builtinAgents := config.DefaultAgentTargets()
if isProject {
builtinAgents = config.ProjectAgentTargets()
}
var details []string
hasError := false
@@ -362,15 +467,23 @@ func checkTargets(cfg *config.Config, result *doctorResult) map[string]cachedTar
targetIssues := checkTargetIssues(target, cfg.Source)
// Target name header
fmt.Printf("%s%s%s\n", ui.Bold, name, ui.Reset)
if len(targetIssues) > 0 {
ui.Error("%s [%s]: %s", name, mode, strings.Join(targetIssues, ", "))
fmt.Printf(" skills %s[%s] %s%s\n", ui.Red, mode, strings.Join(targetIssues, ", "), ui.Reset)
result.addError()
details = append(details, fmt.Sprintf("%s: %s", name, strings.Join(targetIssues, ", ")))
hasError = true
} else {
cached := displayTargetStatus(name, target, cfg.Source, mode)
cached := displayTargetStatus(target, cfg.Source, mode)
cache[name] = cached
}
// Agent sub-check for this target
if agentsExist {
checkAgentTargetInline(name, target, builtinAgents, discoveredAgents, result)
}
}
if hasError {
@@ -426,9 +539,9 @@ func checkTargetIssues(target config.TargetConfig, source string) []string {
return targetIssues
}
func displayTargetStatus(name string, target config.TargetConfig, source, mode string) cachedTargetStatus {
func displayTargetStatus(target config.TargetConfig, source, mode string) cachedTargetStatus {
sc := target.SkillsConfig()
var statusStr string
var statusWord, detail string
var cached cachedTargetStatus
cached.mode = mode
needsSync := false
@@ -440,12 +553,14 @@ func displayTargetStatus(name string, target config.TargetConfig, source, mode s
cached.syncedCount = linkedCount
switch status {
case sync.StatusMerged:
statusStr = fmt.Sprintf("merged (%d shared, %d local)", linkedCount, localCount)
statusWord = "merged"
detail = fmt.Sprintf("(%d shared, %d local)", linkedCount, localCount)
case sync.StatusLinked:
statusStr = "linked (needs sync to apply merge mode)"
statusWord = "linked"
detail = "(needs sync)"
needsSync = true
default:
statusStr = status.String()
statusWord = status.String()
}
case "copy":
status, managedCount, localCount := sync.CheckStatusCopy(sc.Path)
@@ -453,27 +568,34 @@ func displayTargetStatus(name string, target config.TargetConfig, source, mode s
cached.syncedCount = managedCount
switch status {
case sync.StatusCopied:
statusStr = fmt.Sprintf("copied (%d managed, %d local)", managedCount, localCount)
statusWord = "copied"
detail = fmt.Sprintf("(%d managed, %d local)", managedCount, localCount)
case sync.StatusLinked:
statusStr = "linked (needs sync to apply copy mode)"
statusWord = "linked"
detail = "(needs sync)"
needsSync = true
default:
statusStr = status.String()
statusWord = status.String()
}
default:
status := sync.CheckStatus(sc.Path, source)
cached.status = status
statusStr = status.String()
statusWord = status.String()
if status == sync.StatusMerged {
statusStr = "merged (needs sync to apply symlink mode)"
statusWord = "merged"
detail = "(needs sync)"
needsSync = true
}
}
statusColor := ui.Green
if needsSync {
ui.Warning("%s [%s]: %s", name, mode, statusStr)
statusColor = ui.Yellow
}
if detail != "" {
fmt.Printf(" skills [%s] %s%s%s %s%s%s\n", mode, statusColor, statusWord, ui.Reset, ui.Dim, detail, ui.Reset)
} else {
ui.Success("%s [%s]: %s", name, mode, statusStr)
fmt.Printf(" skills [%s] %s%s%s\n", mode, statusColor, statusWord, ui.Reset)
}
return cached
}
@@ -635,7 +757,7 @@ func checkSkillIntegrity(result *doctorResult, discovered []sync.DiscoveredSkill
return
}
// Phase 1: filter to skills that have meta with file hashes (cheap ReadMeta only)
// Phase 1: filter to skills that have meta with file hashes
type verifiable struct {
name string
path string
@@ -644,22 +766,26 @@ func checkSkillIntegrity(result *doctorResult, discovered []sync.DiscoveredSkill
var toVerify []verifiable
var skippedNames []string
store := install.NewMetadataStore()
if len(discovered) > 0 {
sourceDir := strings.TrimSuffix(discovered[0].SourcePath, discovered[0].RelPath)
sourceDir = strings.TrimRight(sourceDir, `/\`)
store = install.LoadMetadataOrNew(sourceDir)
}
for _, skill := range discovered {
meta, err := install.ReadMeta(skill.SourcePath)
if err != nil {
continue
}
if meta == nil {
entry := store.GetByPath(skill.RelPath)
if entry == nil {
continue // Local skill without meta — expected, skip silently
}
if meta.FileHashes == nil {
if entry.FileHashes == nil {
skippedNames = append(skippedNames, skill.RelPath)
continue
}
toVerify = append(toVerify, verifiable{
name: skill.RelPath,
path: skill.SourcePath,
stored: meta.FileHashes,
stored: entry.FileHashes,
})
}
@@ -927,14 +1053,14 @@ func checkExtras(extras []config.ExtraConfig, result *doctorResult, isProject bo
files, err := sync.DiscoverExtraFiles(sourceDir)
if err != nil {
result.addError()
ui.Error("%s: source directory missing (%s)", extra.Name, sourceDir)
ui.Error("%s: source missing (%s)", extra.Name, sourceDir)
details = append(details, fmt.Sprintf("%s: source directory missing", extra.Name))
hasIssue = true
continue
}
ui.Success("%s: source exists (%d files)", extra.Name, len(files))
reachable := 0
var unreachableTargets []string
for _, t := range extra.Targets {
targetPath := config.ExpandPath(t.Path)
if isProject && !filepath.IsAbs(targetPath) {
@@ -943,14 +1069,17 @@ func checkExtras(extras []config.ExtraConfig, result *doctorResult, isProject bo
if _, err := os.Stat(filepath.Dir(targetPath)); err == nil {
reachable++
} else {
ui.Warning("%s: target %s not reachable (parent dir missing: %s)", extra.Name, t.Path, filepath.Dir(targetPath))
unreachableTargets = append(unreachableTargets, t.Path)
}
}
if reachable == len(extra.Targets) {
ui.Success("%s: all targets reachable (%d/%d)", extra.Name, reachable, len(extra.Targets))
ui.Success("%s: %d files, %d/%d targets OK", extra.Name, len(files), reachable, len(extra.Targets))
} else {
result.addWarning()
ui.Warning("%s: some targets unreachable (%d/%d)", extra.Name, reachable, len(extra.Targets))
ui.Warning("%s: %d files, %d/%d targets unreachable", extra.Name, len(files), len(extra.Targets)-reachable, len(extra.Targets))
for _, t := range unreachableTargets {
fmt.Printf(" %s%s (parent dir missing)%s\n", ui.Dim, t, ui.Reset)
}
details = append(details, fmt.Sprintf("%s: %d/%d targets unreachable", extra.Name, len(extra.Targets)-reachable, len(extra.Targets)))
hasIssue = true
}
@@ -1061,22 +1190,34 @@ func formatBytes(b int64) string {
}
// checkVersionDoctor checks CLI and skill versions
func checkVersionDoctor(cfg *config.Config, result *doctorResult) {
func checkVersionDoctor(cfg *config.Config, result *doctorResult, isProject bool) {
ui.Header("Version")
// CLI version
ui.Success("CLI: %s", version)
result.addCheck("cli_version", checkPass, fmt.Sprintf("CLI: %s", version), nil)
// Skill version (reads metadata.version from SKILL.md)
// Skill version: try SKILL.md frontmatter first, then metadata store
localVersion := versioncheck.ReadLocalSkillVersion(cfg.Source)
if localVersion == "" {
// Distinguish "file not found" from "version field missing"
// Try metadata store (tracks installed version even without metadata.version in SKILL.md)
store := install.LoadMetadataOrNew(cfg.Source)
if entry := store.Get("skillshare"); entry != nil && entry.Version != "" {
localVersion = strings.TrimPrefix(entry.Version, "v")
}
}
if localVersion == "" {
skillFile := filepath.Join(cfg.Source, "skillshare", "SKILL.md")
if _, err := os.Stat(skillFile); os.IsNotExist(err) {
ui.Warning("Skill: not found")
ui.Info(" Run: skillshare upgrade --skill")
result.addCheck("skill_version", checkWarning, "Skill: not found", nil)
if isProject {
ui.Info("Skill: not installed")
result.addCheck("skill_version", checkInfo, "Skill: not installed in project", nil)
} else {
ui.Warning("Skill: not found")
ui.Info(" Run: skillshare upgrade --skill")
result.addCheck("skill_version", checkWarning, "Skill: not found", nil)
}
} else {
ui.Warning("Skill: missing version")
result.addCheck("skill_version", checkWarning, "Skill: missing version", nil)
+122
View File
@@ -0,0 +1,122 @@
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"skillshare/internal/config"
"skillshare/internal/resource"
"skillshare/internal/sync"
"skillshare/internal/ui"
)
// checkAgentTargetInline validates the agent target for a single target,
// printing as an indented sub-item under the target name in doctor output.
// It applies the target's include/exclude filters to compute the expected count.
func checkAgentTargetInline(name string, target config.TargetConfig, builtinAgents map[string]config.TargetConfig, allAgents []resource.DiscoveredResource, result *doctorResult) {
agentPath := resolveAgentTargetPath(target, builtinAgents, name)
if agentPath == "" {
return
}
ac := target.AgentsConfig()
mode := ac.Mode
if mode == "" {
mode = "merge"
}
// Apply per-target include/exclude filters to get expected agent count
filtered, filterErr := sync.FilterAgents(allAgents, ac.Include, ac.Exclude)
if filterErr != nil {
fmt.Printf(" agents %s[%s] invalid filter: %s%s\n", ui.Red, mode, filterErr.Error(), ui.Reset)
result.addError()
result.addCheck("agent_target_"+name, checkError,
fmt.Sprintf("Agent target %s: invalid filter: %v", name, filterErr), nil)
return
}
agentCount := len(filtered)
// Build details for JSON output
var details []string
details = append(details, fmt.Sprintf("path: %s", agentPath))
details = append(details, fmt.Sprintf("mode: %s", mode))
if len(ac.Include) > 0 {
details = append(details, fmt.Sprintf("include: %s", strings.Join(ac.Include, ", ")))
}
if len(ac.Exclude) > 0 {
details = append(details, fmt.Sprintf("exclude: %s", strings.Join(ac.Exclude, ", ")))
}
info, err := os.Stat(agentPath)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf(" agents %s[%s] not created%s\n", ui.Gray, mode, ui.Reset)
result.addCheck("agent_target_"+name, checkPass,
fmt.Sprintf("Agent target %s: not created yet", name), details)
return
}
fmt.Printf(" agents %s[%s] error: %s%s\n", ui.Red, mode, err.Error(), ui.Reset)
result.addError()
result.addCheck("agent_target_"+name, checkError,
fmt.Sprintf("Agent target %s: %v", name, err), details)
return
}
if !info.IsDir() {
fmt.Printf(" agents %s[%s] error: not a directory%s\n", ui.Red, mode, ui.Reset)
result.addError()
result.addCheck("agent_target_"+name, checkError,
fmt.Sprintf("Agent target %s: path is not a directory", name), details)
return
}
linked, broken := countAgentLinksAndBroken(agentPath)
if broken > 0 {
msg := fmt.Sprintf("[%s] %d linked, %d broken", mode, linked, broken)
fmt.Printf(" agents %s%s%s\n", ui.Yellow, msg, ui.Reset)
result.addWarning()
result.addCheck("agent_target_"+name, checkWarning,
fmt.Sprintf("Agent target %s: %s", name, msg), details)
return
}
if linked != agentCount && agentCount > 0 {
fmt.Printf(" agents [%s] %sdrift%s %s(%d/%d linked)%s\n", mode, ui.Yellow, ui.Reset, ui.Dim, linked, agentCount, ui.Reset)
result.addWarning()
result.addCheck("agent_target_"+name, checkWarning,
fmt.Sprintf("Agent target %s: drift (%d/%d agents linked)", name, linked, agentCount), details)
return
}
fmt.Printf(" agents [%s] %ssynced%s %s(%d/%d linked)%s\n", mode, ui.Green, ui.Reset, ui.Dim, linked, agentCount, ui.Reset)
result.addCheck("agent_target_"+name, checkPass,
fmt.Sprintf("Agent target %s: %d agents synced", name, linked), details)
}
// countAgentLinksAndBroken counts .md symlinks and broken symlinks in a directory.
func countAgentLinksAndBroken(dir string) (linked, broken int) {
entries, err := os.ReadDir(dir)
if err != nil {
return 0, 0
}
for _, e := range entries {
if e.IsDir() {
continue
}
if !strings.HasSuffix(strings.ToLower(e.Name()), ".md") {
continue
}
if e.Type()&os.ModeSymlink == 0 {
continue
}
// It's a symlink — check if target exists (os.Stat follows symlinks)
if _, statErr := os.Stat(filepath.Join(dir, e.Name())); statErr != nil {
broken++
} else {
linked++
}
}
return linked, broken
}
+28 -6
View File
@@ -33,6 +33,12 @@ func cmdToggleSkill(args []string, enable bool) error {
return err
}
// Extract --kind flag before parsing other args
kind, rest, err := parseKindFlag(rest)
if err != nil {
return err
}
var dryRun bool
var patterns []string
for _, arg := range rest {
@@ -68,20 +74,35 @@ func cmdToggleSkill(args []string, enable bool) error {
}
applyModeLabel(mode)
isAgent := kind == kindAgents
var ignorePath string
var cfgPath string
if mode == modeProject {
ignorePath = filepath.Join(cwd, ".skillshare", "skills", ".skillignore")
if isAgent {
ignorePath = filepath.Join(cwd, ".skillshare", "agents", ".agentignore")
} else {
ignorePath = filepath.Join(cwd, ".skillshare", "skills", ".skillignore")
}
cfgPath = config.ProjectConfigPath(cwd)
} else {
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
ignorePath = filepath.Join(cfg.Source, ".skillignore")
if isAgent {
ignorePath = filepath.Join(cfg.EffectiveAgentsSource(), ".agentignore")
} else {
ignorePath = filepath.Join(cfg.Source, ".skillignore")
}
cfgPath = config.ConfigPath()
}
ignoreLabel := ".skillignore"
if isAgent {
ignoreLabel = ".agentignore"
}
changed := false
for _, pattern := range patterns {
if dryRun {
@@ -96,25 +117,25 @@ func cmdToggleSkill(args []string, enable bool) error {
if enable {
removed, err := skillignore.RemovePattern(ignorePath, pattern)
if err != nil {
return fmt.Errorf("failed to update .skillignore: %w", err)
return fmt.Errorf("failed to update %s: %w", ignoreLabel, err)
}
if !removed {
ui.Warning("%s is not disabled", pattern)
continue
}
changed = true
ui.Success("Enabled: %s (removed from .skillignore)", pattern)
ui.Success("Enabled: %s (removed from %s)", pattern, ignoreLabel)
} else {
added, err := skillignore.AddPattern(ignorePath, pattern)
if err != nil {
return fmt.Errorf("failed to update .skillignore: %w", err)
return fmt.Errorf("failed to update %s: %w", ignoreLabel, err)
}
if !added {
ui.Warning("%s is already disabled", pattern)
continue
}
changed = true
ui.Success("Disabled: %s (added to .skillignore)", pattern)
ui.Success("Disabled: %s (added to %s)", pattern, ignoreLabel)
}
}
@@ -124,6 +145,7 @@ func cmdToggleSkill(args []string, enable bool) error {
e := oplog.NewEntry(action, "ok", time.Since(start))
e.Args = map[string]any{
"patterns": patterns,
"kind": kind.String(),
}
oplog.Write(cfgPath, oplog.OpsFile, e)
}
+36 -34
View File
@@ -5,9 +5,11 @@ import (
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"skillshare/internal/config"
)
type extrasInitPhase int
@@ -48,14 +50,14 @@ func newExtrasInitTUIModel() extrasInitTUIModel {
ti := textinput.New()
ti.Placeholder = "rules"
ti.Focus()
ti.PromptStyle = tc.Cyan
ti.Cursor.Style = tc.Cyan
ti.PromptStyle = theme.Accent()
ti.Cursor.Style = theme.Accent()
si := textinput.New()
si.Placeholder = "Leave empty to use default"
si.CharLimit = 256
si.PromptStyle = tc.Cyan
si.Cursor.Style = tc.Cyan
si.PromptStyle = theme.Accent()
si.Cursor.Style = theme.Accent()
return extrasInitTUIModel{
phase: extrasPhaseNameInput,
@@ -238,32 +240,32 @@ func (m extrasInitTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
func (m extrasInitTUIModel) View() string {
var b strings.Builder
b.WriteString(tc.Title.Render("Extras Init"))
b.WriteString(theme.Title().Render("Extras Init"))
b.WriteString("\n\n")
switch m.phase {
case extrasPhaseNameInput:
b.WriteString(tc.Cyan.Render("Extra name: "))
b.WriteString(theme.Accent().Render("Extra name: "))
b.WriteString(m.textInput.View())
if m.err != nil {
b.WriteString("\n" + tc.Red.Render(m.err.Error()))
b.WriteString("\n" + theme.Danger().Render(m.err.Error()))
}
b.WriteString("\n\n")
b.WriteString(tc.Help.Render("enter confirm esc cancel"))
b.WriteString(theme.Dim().MarginLeft(2).Render("enter confirm esc cancel"))
case extrasPhaseSourceInput:
b.WriteString(tc.Dim.Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString("\n\n")
b.WriteString(tc.Cyan.Render("Source directory (optional): "))
b.WriteString(theme.Accent().Render("Source directory (optional): "))
b.WriteString(m.sourceInput.View())
b.WriteString("\n\n")
b.WriteString(tc.Help.Render("enter to skip (use default) esc back"))
b.WriteString(theme.Dim().MarginLeft(2).Render("enter to skip (use default) esc back"))
case extrasPhaseTargetInput:
b.WriteString(tc.Dim.Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Name: %s", m.name)))
if m.sourceValue != "" {
b.WriteString("\n")
b.WriteString(tc.Dim.Render(fmt.Sprintf("Source: %s", m.sourceValue)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Source: %s", m.sourceValue)))
}
if len(m.targets) > 0 {
b.WriteString("\n")
@@ -272,22 +274,22 @@ func (m extrasInitTUIModel) View() string {
if t.flatten {
modeLabel += ", flatten"
}
b.WriteString(tc.Dim.Render(fmt.Sprintf(" → %s (%s)", t.path, modeLabel)))
b.WriteString(theme.Dim().Render(fmt.Sprintf(" → %s (%s)", t.path, modeLabel)))
b.WriteString("\n")
}
}
b.WriteString("\n")
b.WriteString(tc.Cyan.Render(fmt.Sprintf("Target #%d path: ", len(m.targets)+1)))
b.WriteString(theme.Accent().Render(fmt.Sprintf("Target #%d path: ", len(m.targets)+1)))
b.WriteString(m.textInput.View())
b.WriteString("\n\n")
b.WriteString(tc.Help.Render("enter confirm esc back"))
b.WriteString(theme.Dim().MarginLeft(2).Render("enter confirm esc back"))
case extrasPhaseModeSelect:
b.WriteString(tc.Dim.Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(fmt.Sprintf("Target: %s", m.targets[len(m.targets)-1].path)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Target: %s", m.targets[len(m.targets)-1].path)))
b.WriteString("\n\n")
b.WriteString(tc.Cyan.Render("Sync mode:"))
b.WriteString(theme.Accent().Render("Sync mode:"))
b.WriteString("\n")
for i, mode := range syncModes {
cursor := " "
@@ -304,43 +306,43 @@ func (m extrasInitTUIModel) View() string {
desc = " (directory symlink)"
}
if i == m.currMode {
b.WriteString(tc.Cyan.Render(cursor+mode) + tc.Dim.Render(desc))
b.WriteString(theme.Accent().Render(cursor+mode) + theme.Dim().Render(desc))
} else {
b.WriteString(tc.Dim.Render(cursor + mode + desc))
b.WriteString(theme.Dim().Render(cursor + mode + desc))
}
b.WriteString("\n")
}
b.WriteString("\n")
b.WriteString(tc.Help.Render("↑↓/jk navigate enter/space select esc back"))
b.WriteString(theme.Dim().MarginLeft(2).Render("↑↓/jk navigate enter/space select esc back"))
case extrasPhaseFlattenToggle:
b.WriteString(tc.Dim.Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString("\n")
lastTarget := m.targets[len(m.targets)-1]
b.WriteString(tc.Dim.Render(fmt.Sprintf("Target: %s (%s)", lastTarget.path, lastTarget.mode)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Target: %s (%s)", lastTarget.path, lastTarget.mode)))
b.WriteString("\n\n")
b.WriteString(tc.Cyan.Render("Flatten files into target root? (y/N) "))
b.WriteString(theme.Accent().Render("Flatten files into target root? (y/N) "))
b.WriteString("\n\n")
b.WriteString(tc.Help.Render("y yes n/enter no esc back"))
b.WriteString(theme.Dim().MarginLeft(2).Render("y yes n/enter no esc back"))
case extrasPhaseAddMore:
b.WriteString(tc.Dim.Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString(theme.Dim().Render(fmt.Sprintf("Name: %s", m.name)))
b.WriteString("\n")
for _, t := range m.targets {
modeLabel := t.mode
if t.flatten {
modeLabel += ", flatten"
}
b.WriteString(tc.Dim.Render(fmt.Sprintf(" → %s (%s)", t.path, modeLabel)))
b.WriteString(theme.Dim().Render(fmt.Sprintf(" → %s (%s)", t.path, modeLabel)))
b.WriteString("\n")
}
b.WriteString("\n")
b.WriteString(tc.Cyan.Render("Add another target? (y/N) "))
b.WriteString(theme.Accent().Render("Add another target? (y/N) "))
b.WriteString("\n\n")
b.WriteString(tc.Help.Render("y yes n/enter no esc back"))
b.WriteString(theme.Dim().MarginLeft(2).Render("y yes n/enter no esc back"))
case extrasPhaseConfirm:
b.WriteString(tc.Cyan.Render("Summary:"))
b.WriteString(theme.Accent().Render("Summary:"))
b.WriteString("\n")
b.WriteString(fmt.Sprintf(" Name: %s\n", m.name))
if m.sourceValue != "" {
@@ -354,9 +356,9 @@ func (m extrasInitTUIModel) View() string {
b.WriteString(fmt.Sprintf(" → %s (%s)\n", t.path, modeLabel))
}
b.WriteString("\n")
b.WriteString(tc.Cyan.Render("Create this extra? (Y/n) "))
b.WriteString(theme.Accent().Render("Create this extra? (Y/n) "))
b.WriteString("\n\n")
b.WriteString(tc.Help.Render("y/enter confirm n cancel"))
b.WriteString(theme.Dim().MarginLeft(2).Render("y/enter confirm n cancel"))
}
return b.String()
+44 -43
View File
@@ -8,6 +8,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/sync"
"skillshare/internal/theme"
"skillshare/internal/ui"
"github.com/charmbracelet/bubbles/list"
@@ -107,7 +108,7 @@ func newExtrasListTUIModel(
l := list.New(nil, delegate, 0, 0)
l.Title = fmt.Sprintf("Extras (%s)", modeLabel)
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
@@ -115,12 +116,12 @@ func newExtrasListTUIModel(
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
fi.Placeholder = "filter by name"
return extrasListTUIModel{
@@ -425,29 +426,29 @@ func (m extrasListTUIModel) viewExtrasVertical() string {
func (m extrasListTUIModel) renderExtrasDetail(e extrasListEntry) string {
var b strings.Builder
b.WriteString(tc.Title.Render(e.Name))
b.WriteString(theme.Title().Render(e.Name))
b.WriteString("\n\n")
label := tc.Label.Render("Source")
label := theme.Dim().Width(14).Render("Source")
if e.SourceExists {
b.WriteString(label + shortenPath(e.SourceDir) + "\n")
} else {
b.WriteString(label + tc.Dim.Render("not found") + "\n")
b.WriteString(label + theme.Dim().Render("not found") + "\n")
}
label = tc.Label.Render("Files")
label = theme.Dim().Width(14).Render("Files")
if e.SourceExists {
b.WriteString(label + fmt.Sprintf("%d", e.FileCount) + "\n")
} else {
b.WriteString(label + tc.Dim.Render("—") + "\n")
b.WriteString(label + theme.Dim().Render("—") + "\n")
}
b.WriteString("\n")
b.WriteString(tc.Title.Render("Targets"))
b.WriteString(theme.Title().Render("Targets"))
b.WriteString("\n")
if len(e.Targets) == 0 {
b.WriteString(tc.Dim.Render(" No targets configured") + "\n")
b.WriteString(theme.Dim().Render(" No targets configured") + "\n")
} else {
hasDrift := false
for _, t := range e.Targets {
@@ -456,18 +457,18 @@ func (m extrasListTUIModel) renderExtrasDetail(e extrasListEntry) string {
switch t.Status {
case "synced":
icon = "✓"
style = tc.Green
style = theme.Success()
case "drift":
icon = "△"
style = tc.Yellow
style = theme.Warning()
hasDrift = true
case "not synced":
icon = "✗"
style = tc.Red
style = theme.Danger()
hasDrift = true
default:
icon = "-"
style = tc.Dim
style = theme.Dim()
}
statusText := ""
if t.Status != "synced" {
@@ -478,29 +479,29 @@ func (m extrasListTUIModel) renderExtrasDetail(e extrasListEntry) string {
modeLabel += ", flatten"
}
fmt.Fprintf(&b, " %s %s (%s)%s\n",
style.Render(icon), shortenPath(t.Path), modeLabel, tc.Dim.Render(statusText))
style.Render(icon), shortenPath(t.Path), modeLabel, theme.Dim().Render(statusText))
}
if hasDrift {
b.WriteString("\n" + tc.Yellow.Render("hint:") + " press S to sync, or use --force to overwrite conflicts\n")
b.WriteString("\n" + theme.Warning().Render("hint:") + " press S to sync, or use --force to overwrite conflicts\n")
}
}
if e.SourceExists && e.FileCount > 0 {
b.WriteString("\n")
b.WriteString(tc.Title.Render("Files"))
b.WriteString(theme.Title().Render("Files"))
b.WriteString("\n")
files := discoverExtraFileNames(e.SourceDir)
maxShow := 10
for i, f := range files {
if i >= maxShow {
b.WriteString(tc.Dim.Render(fmt.Sprintf(" … and %d more", len(files)-maxShow)) + "\n")
b.WriteString(theme.Dim().Render(fmt.Sprintf(" … and %d more", len(files)-maxShow)) + "\n")
break
}
prefix := "├── "
if i == len(files)-1 || i == maxShow-1 {
prefix = "└── "
}
b.WriteString(tc.Dim.Render(" "+prefix) + f + "\n")
b.WriteString(theme.Dim().Render(" "+prefix) + f + "\n")
}
}
@@ -530,17 +531,17 @@ func (m extrasListTUIModel) renderExtrasHelp(scrollInfo string) string {
if m.filtering {
helpText = "Enter lock Esc clear q quit"
}
return tc.Help.Render(appendScrollInfo(helpText, scrollInfo))
return theme.Dim().MarginLeft(2).Render(appendScrollInfo(helpText, scrollInfo))
}
func renderExtrasActionMsg(msg string) string {
if strings.HasPrefix(msg, "✓") {
return tc.Green.Render(msg)
return theme.Success().Render(msg)
}
if strings.HasPrefix(msg, "✗") {
return tc.Red.Render(msg)
return theme.Danger().Render(msg)
}
return tc.Yellow.Render(msg)
return theme.Warning().Render(msg)
}
// ─── Helpers ─────────────────────────────────────────────────────────
@@ -661,7 +662,7 @@ func (m extrasListTUIModel) renderConfirmOverlay() string {
}
return fmt.Sprintf("\n%s\n\n%s\n\nProceed? [Y/n] ",
tc.Title.Render(title), body)
theme.Title().Render(title), body)
}
// ─── Target Sub-Menu ─────────────────────────────────────────────────
@@ -764,14 +765,14 @@ func (m extrasListTUIModel) renderTargetMenu() string {
title = "Toggle flatten"
}
fmt.Fprintf(&b, "\n%s\n\n", tc.Title.Render(title))
fmt.Fprintf(&b, "\n%s\n\n", theme.Title().Render(title))
if m.targetAction == "mode" || m.targetAction == "flatten" {
// No "All targets" for mode — list targets directly
for i, t := range m.targetMenuItems {
prefix := " "
if i == m.targetCursor {
prefix = tc.Cyan.Render(">") + " "
prefix = theme.Accent().Render(">") + " "
}
fmt.Fprintf(&b, "%s%s (%s)\n", prefix, shortenPath(t.Path), t.Mode)
}
@@ -779,7 +780,7 @@ func (m extrasListTUIModel) renderTargetMenu() string {
for i := 0; i <= len(m.targetMenuItems); i++ {
prefix := " "
if i == m.targetCursor {
prefix = tc.Cyan.Render(">") + " "
prefix = theme.Accent().Render(">") + " "
}
if i == 0 {
fmt.Fprintf(&b, "%s%s\n", prefix, "All targets")
@@ -790,7 +791,7 @@ func (m extrasListTUIModel) renderTargetMenu() string {
}
}
fmt.Fprintf(&b, "\n%s\n", tc.Help.Render("↑↓ select Enter confirm Esc cancel"))
fmt.Fprintf(&b, "\n%s\n", theme.Dim().MarginLeft(2).Render("↑↓ select Enter confirm Esc cancel"))
return b.String()
}
@@ -846,14 +847,14 @@ func (m extrasListTUIModel) handleModePickerKey(msg tea.KeyMsg) (tea.Model, tea.
func (m extrasListTUIModel) renderModePicker() string {
var b strings.Builder
fmt.Fprintf(&b, "\n%s\n", tc.Title.Render("Change mode"))
fmt.Fprintf(&b, "%s %s\n\n", tc.Dim.Render("Extra:"), m.modePickerExtra)
fmt.Fprintf(&b, "%s %s\n\n", tc.Dim.Render("Target:"), shortenPath(m.modePickerTarget))
fmt.Fprintf(&b, "\n%s\n", theme.Title().Render("Change mode"))
fmt.Fprintf(&b, "%s %s\n\n", theme.Dim().Render("Extra:"), m.modePickerExtra)
fmt.Fprintf(&b, "%s %s\n\n", theme.Dim().Render("Target:"), shortenPath(m.modePickerTarget))
for i, mode := range extrasSyncModes {
cursor := " "
if i == m.modeCursor {
cursor = tc.Cyan.Render(">") + " "
cursor = theme.Accent().Render(">") + " "
}
var desc string
switch mode {
@@ -865,13 +866,13 @@ func (m extrasListTUIModel) renderModePicker() string {
desc = " (directory symlink)"
}
if i == m.modeCursor {
fmt.Fprintf(&b, "%s%s%s\n", cursor, tc.Cyan.Render(mode), tc.Dim.Render(desc))
fmt.Fprintf(&b, "%s%s%s\n", cursor, theme.Accent().Render(mode), theme.Dim().Render(desc))
} else {
fmt.Fprintf(&b, "%s%s%s\n", cursor, mode, tc.Dim.Render(desc))
fmt.Fprintf(&b, "%s%s%s\n", cursor, mode, theme.Dim().Render(desc))
}
}
fmt.Fprintf(&b, "\n%s\n", tc.Help.Render("↑↓ select Enter confirm Esc cancel"))
fmt.Fprintf(&b, "\n%s\n", theme.Dim().MarginLeft(2).Render("↑↓ select Enter confirm Esc cancel"))
return b.String()
}
@@ -1307,9 +1308,9 @@ func (m extrasListTUIModel) renderExtrasContentOverlay() string {
}
b.WriteString("\n")
b.WriteString(tc.Title.Render(fmt.Sprintf(" %s", extraName)))
b.WriteString(theme.Title().Render(fmt.Sprintf(" %s", extraName)))
if fileName != "" {
b.WriteString(tc.Dim.Render(fmt.Sprintf(" ─ %s", fileName)))
b.WriteString(theme.Dim().Render(fmt.Sprintf(" ─ %s", fileName)))
}
b.WriteString("\n\n")
@@ -1326,7 +1327,7 @@ func (m extrasListTUIModel) renderExtrasContentOverlay() string {
PaddingLeft(1).
Render(sidebarStr)
borderStyle := tc.Border.Height(contentHeight).MaxHeight(contentHeight)
borderStyle := theme.Dim().Height(contentHeight).MaxHeight(contentHeight)
borderCol := strings.Repeat("│\n", contentHeight)
borderPanel := borderStyle.Render(strings.TrimRight(borderCol, "\n"))
@@ -1344,7 +1345,7 @@ func (m extrasListTUIModel) renderExtrasContentOverlay() string {
if scrollInfo != "" {
help += " " + scrollInfo
}
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
@@ -1355,8 +1356,8 @@ func (m extrasListTUIModel) renderExtrasSidebarStr(width, height int) string {
return "(no files)"
}
selectedStyle := lipgloss.NewStyle().Bold(true).Foreground(tc.BrandYellow)
dirStyle := tc.Cyan
selectedStyle := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#D4D93C"))
dirStyle := theme.Accent()
fileStyle := lipgloss.NewStyle()
total := len(m.treeNodes)
@@ -1401,7 +1402,7 @@ func (m extrasListTUIModel) renderExtrasSidebarStr(width, height int) string {
}
if total > height {
lines = append(lines, tc.Dim.Render(fmt.Sprintf(" (%d/%d)", m.treeCursor+1, total)))
lines = append(lines, theme.Dim().Render(fmt.Sprintf(" (%d/%d)", m.treeCursor+1, total)))
}
return strings.Join(lines, "\n")
+7 -5
View File
@@ -3,6 +3,8 @@ package main
import (
"io"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
)
@@ -41,10 +43,10 @@ func (extrasListDelegate) Render(w io.Writer, m list.Model, index int, item list
// extrasStatusBadge returns a short colored status indicator based on aggregate target status.
func extrasStatusBadge(e extrasListEntry) string {
if !e.SourceExists {
return tc.Dim.Render("no source")
return theme.Dim().Render("no source")
}
if len(e.Targets) == 0 {
return tc.Dim.Render("no targets")
return theme.Dim().Render("no targets")
}
synced := 0
@@ -60,10 +62,10 @@ func extrasStatusBadge(e extrasListEntry) string {
total := len(e.Targets)
if synced == total {
return tc.Green.Render("✓")
return theme.Success().Render("✓")
}
if drift > 0 {
return tc.Yellow.Render("△")
return theme.Warning().Render("△")
}
return tc.Red.Render("✗")
return theme.Danger().Render("✗")
}
+5 -1
View File
@@ -377,10 +377,14 @@ func performFreshInit(opts *initOptions, home string) error {
ui.Warning("Dry run mode - no changes will be made")
}
// Create source directory if needed
// Create source directories if needed
if err := createSourceDir(sourcePath, opts.dryRun); err != nil {
return err
}
agentsSourcePath := filepath.Join(filepath.Dir(sourcePath), "agents")
if err := createSourceDir(agentsSourcePath, opts.dryRun); err != nil {
return err
}
// Copy skills from selected directory
if copyFromPath != "" {
+3
View File
@@ -216,6 +216,9 @@ func performProjectInit(root string, opts projectInitOptions) error {
if err := os.MkdirAll(filepath.Join(root, ".skillshare", "skills"), 0755); err != nil {
return fmt.Errorf("failed to create .skillshare/skills: %w", err)
}
if err := os.MkdirAll(filepath.Join(root, ".skillshare", "agents"), 0755); err != nil {
return fmt.Errorf("failed to create .skillshare/agents: %w", err)
}
if err := ensureProjectGitignore(root, opts.configMode == "local"); err != nil {
return err
+90 -40
View File
@@ -97,6 +97,23 @@ func parseInstallArgs(args []string) (*installArgs, bool, error) {
result.opts.Branch = branch
case arg == "--track" || arg == "-t":
result.opts.Track = true
case arg == "--kind":
if i+1 >= len(args) {
return nil, false, fmt.Errorf("--kind requires a value (skill or agent)")
}
i++
kind := strings.ToLower(args[i])
if kind != "skill" && kind != "agent" {
return nil, false, fmt.Errorf("--kind must be 'skill' or 'agent', got %q", args[i])
}
result.opts.Kind = kind
case arg == "--agent" || arg == "-a":
if i+1 >= len(args) {
return nil, false, fmt.Errorf("-a requires agent name(s)")
}
i++
result.opts.AgentNames = strings.Split(args[i], ",")
result.opts.Kind = "agent"
case arg == "--skill" || arg == "-s":
if i+1 >= len(args) {
return nil, false, fmt.Errorf("--skill requires a value")
@@ -115,6 +132,8 @@ func parseInstallArgs(args []string) (*installArgs, bool, error) {
}
i++
result.opts.Into = args[i]
case strings.HasPrefix(arg, "--into="):
result.opts.Into = strings.TrimPrefix(arg, "--into=")
case arg == "--all":
result.opts.All = true
case arg == "--yes" || arg == "-y":
@@ -171,6 +190,9 @@ func parseInstallArgs(args []string) (*installArgs, bool, error) {
if result.opts.HasSkillFilter() && result.opts.Track {
return nil, false, fmt.Errorf("--skill cannot be used with --track")
}
if result.opts.HasAgentFilter() && result.opts.Track {
return nil, false, fmt.Errorf("--agent cannot be used with --track")
}
if result.opts.ShouldInstallAll() && result.opts.Track {
return nil, false, fmt.Errorf("--all/--yes cannot be used with --track")
}
@@ -191,6 +213,16 @@ func parseInstallArgs(args []string) (*installArgs, bool, error) {
return result, false, nil
}
func applyInstallJSONDefaults(parsed *installArgs) {
if !parsed.jsonOutput {
return
}
parsed.opts.Force = true
if !parsed.opts.HasSkillFilter() && !parsed.opts.HasAgentFilter() {
parsed.opts.All = true
}
}
// destWithInto returns the destination path, prepending opts.Into if set.
func destWithInto(sourceDir string, opts install.InstallOptions, skillName string) string {
if opts.Into != "" {
@@ -199,6 +231,14 @@ func destWithInto(sourceDir string, opts install.InstallOptions, skillName strin
return filepath.Join(sourceDir, skillName)
}
// agentsDirWithInto returns agentsDir joined with opts.Into (if set).
func agentsDirWithInto(agentsDir string, opts install.InstallOptions) string {
if opts.Into != "" {
return filepath.Join(agentsDir, opts.Into)
}
return agentsDir
}
// ensureIntoDirExists creates the Into subdirectory if opts.Into is set.
func ensureIntoDirExists(sourceDir string, opts install.InstallOptions) error {
if opts.Into == "" {
@@ -219,17 +259,17 @@ func parseOptsFromProjectConfig(cfg *config.ProjectConfig) install.ParseOptions
// resolveSkillFromName resolves a skill name to source using metadata
func resolveSkillFromName(skillName string, cfg *config.Config) (*install.Source, error) {
skillPath := filepath.Join(cfg.Source, skillName)
meta, err := install.ReadMeta(skillPath)
store, err := install.LoadMetadataWithMigration(cfg.Source, "")
if err != nil {
return nil, fmt.Errorf("skill '%s' not found or has no metadata", skillName)
}
if meta == nil {
entry := store.GetByPath(skillName)
if entry == nil || entry.Source == "" {
return nil, fmt.Errorf("skill '%s' has no metadata, cannot update", skillName)
}
source, err := install.ParseSourceWithOptions(meta.Source, parseOptsFromConfig(cfg))
source, err := install.ParseSourceWithOptions(entry.Source, parseOptsFromConfig(cfg))
if err != nil {
return nil, fmt.Errorf("invalid source in metadata: %w", err)
}
@@ -295,11 +335,32 @@ func cmdInstall(args []string) error {
applyModeLabel(mode)
if mode == modeProject {
summary, err := cmdInstallProject(rest, cwd)
parsed, showHelp, parseErr := parseInstallArgs(rest)
if showHelp {
printInstallHelp()
return parseErr
}
if parseErr != nil {
return parseErr
}
applyInstallJSONDefaults(parsed)
jsonUI := newJSONUISuppressor(parsed.jsonOutput)
defer jsonUI.Flush()
jsonWriteResult := func(summary installLogSummary, cmdErr error) error {
jsonUI.Flush()
return installOutputJSON(summary, start, cmdErr)
}
summary, err := cmdInstallProjectParsed(parsed, cwd)
if summary.Mode == "" {
summary.Mode = "project"
}
logInstallOp(config.ProjectConfigPath(cwd), rest, start, err, summary)
if parsed.jsonOutput {
return jsonWriteResult(summary, err)
}
return err
}
@@ -311,46 +372,30 @@ func cmdInstall(args []string) error {
if parseErr != nil {
return parseErr
}
// --json implies --force and --all (skip prompts for non-interactive use)
if parsed.jsonOutput {
parsed.opts.Force = true
if !parsed.opts.HasSkillFilter() {
parsed.opts.All = true
}
}
applyInstallJSONDefaults(parsed)
// When no source is given, only bare "install" is valid — reject incompatible flags
if parsed.sourceArg == "" {
hasSourceFlags := parsed.opts.Name != "" || parsed.opts.Into != "" ||
parsed.opts.Track || len(parsed.opts.Skills) > 0 ||
len(parsed.opts.Exclude) > 0 || parsed.opts.All || parsed.opts.Yes || parsed.opts.Update ||
parsed.opts.Branch != ""
if hasSourceFlags && !parsed.jsonOutput {
return fmt.Errorf("flags --name, --into, --track, --skill, --exclude, --all, --yes, and --update require a source argument")
parsed.opts.Track || parsed.opts.HasSkillFilter() || parsed.opts.HasAgentFilter() ||
len(parsed.opts.Exclude) > 0 || parsed.opts.Update || parsed.opts.Branch != "" ||
parsed.opts.Kind != ""
if hasSourceFlags || ((parsed.opts.All || parsed.opts.Yes) && !parsed.jsonOutput) {
return fmt.Errorf("flags --name, --into, --track, --skill, --agent, --kind, --exclude, --all, --yes, --branch, and --update require a source argument")
}
}
// In JSON mode, redirect all UI output to stderr early so the
// logo, spinner, step, and handler output don't corrupt stdout.
var restoreJSONUI func()
restoreJSONUIIfNeeded := func() {
if restoreJSONUI != nil {
restoreJSONUI()
restoreJSONUI = nil
}
}
if parsed.jsonOutput {
restoreJSONUI = suppressUIToDevnull()
}
defer restoreJSONUIIfNeeded()
jsonUI := newJSONUISuppressor(parsed.jsonOutput)
defer jsonUI.Flush()
jsonWriteError := func(err error) error {
restoreJSONUIIfNeeded()
jsonUI.Flush()
return writeJSONError(err)
}
jsonWriteResult := func(summary installLogSummary, cmdErr error) error {
restoreJSONUIIfNeeded()
jsonUI.Flush()
return installOutputJSON(summary, start, cmdErr)
}
@@ -375,6 +420,7 @@ func cmdInstall(args []string) error {
return err
}
parsed.opts.SourceDir = cfg.Source
source, resolvedFromMeta, err := resolveInstallSource(parsed.sourceArg, parsed.opts, cfg)
if err == nil && parsed.opts.Branch != "" {
source.Branch = parsed.opts.Branch
@@ -411,10 +457,10 @@ func cmdInstall(args []string) error {
summary.Source = parsed.sourceArg
}
if err == nil && !parsed.opts.DryRun && len(summary.InstalledSkills) > 0 {
reg, regErr := config.LoadRegistry(cfg.RegistryDir)
if regErr != nil {
ui.Warning("Failed to load registry: %v", regErr)
} else if rErr := config.ReconcileGlobalSkills(cfg, reg); rErr != nil {
store, storeErr := install.LoadMetadataWithMigration(cfg.Source, "")
if storeErr != nil {
ui.Warning("Failed to load metadata: %v", storeErr)
} else if rErr := config.ReconcileGlobalSkills(cfg, store); rErr != nil {
ui.Warning("Failed to reconcile global skills config: %v", rErr)
}
}
@@ -433,10 +479,10 @@ func cmdInstall(args []string) error {
summary.Source = parsed.sourceArg
}
if err == nil && !parsed.opts.DryRun && len(summary.InstalledSkills) > 0 {
reg, regErr := config.LoadRegistry(cfg.RegistryDir)
if regErr != nil {
ui.Warning("Failed to load registry: %v", regErr)
} else if rErr := config.ReconcileGlobalSkills(cfg, reg); rErr != nil {
store, storeErr := install.LoadMetadataWithMigration(cfg.Source, "")
if storeErr != nil {
ui.Warning("Failed to load metadata: %v", storeErr)
} else if rErr := config.ReconcileGlobalSkills(cfg, store); rErr != nil {
ui.Warning("Failed to reconcile global skills config: %v", rErr)
}
}
@@ -535,11 +581,13 @@ Sources:
Options:
--name <name> Override installed name when exactly one skill is installed
--kind <kind> Restrict discovery/install to skill or agent
--into <dir> Install into subdirectory (e.g. "frontend" or "frontend/react")
--force, -f Overwrite existing skill; also continue if audit would block
--update, -u Update existing (git pull if possible, else reinstall)
--branch, -b <name> Git branch to clone from (default: remote default)
--track, -t Install as tracked repo (preserves .git for updates)
--agent, -a <names> Select specific agents from a multi-agent repo (comma-separated)
--skill, -s <names> Select specific skills from multi-skill repo (comma-separated;
supports glob patterns like "core-*", "test-?")
--exclude <names> Skip specific skills during install (comma-separated;
@@ -568,6 +616,8 @@ Examples:
skillshare install ~/my-skill -T high # Override block threshold for this run
Selective install (non-interactive):
skillshare install org/agents --kind agent # Agents only
skillshare install org/agents -a reviewer,tutor # Specific agents
skillshare install anthropics/skills -s pdf,commit # Specific skills
skillshare install anthropics/skills -s "core-*" # Glob pattern
skillshare install anthropics/skills --all # All skills
+20 -16
View File
@@ -13,18 +13,22 @@ var (
_ install.InstallContext = (*projectInstallContext)(nil)
)
// toSkillEntryDTOs converts config.SkillEntry (or its alias ProjectSkill)
// to install.SkillEntryDTO to avoid circular imports between install and config.
func toSkillEntryDTOs(skills []config.SkillEntry) []install.SkillEntryDTO {
dtos := make([]install.SkillEntryDTO, len(skills))
for i, s := range skills {
dtos[i] = install.SkillEntryDTO{
Name: s.Name,
Source: s.Source,
Tracked: s.Tracked,
Group: s.Group,
Branch: s.Branch,
// storeToSkillEntryDTOs converts MetadataStore entries to []install.SkillEntryDTO.
func storeToSkillEntryDTOs(store *install.MetadataStore) []install.SkillEntryDTO {
names := store.List() // sorted
dtos := make([]install.SkillEntryDTO, 0, len(names))
for _, name := range names {
entry := store.Get(name)
if entry == nil {
continue
}
dtos = append(dtos, install.SkillEntryDTO{
Name: name,
Source: entry.Source,
Tracked: entry.Tracked,
Group: entry.Group,
Branch: entry.Branch,
})
}
return dtos
}
@@ -35,16 +39,16 @@ func toSkillEntryDTOs(skills []config.SkillEntry) []install.SkillEntryDTO {
// globalInstallContext implements install.InstallContext for global mode.
type globalInstallContext struct {
cfg *config.Config
reg *config.Registry
cfg *config.Config
store *install.MetadataStore
}
func (g *globalInstallContext) SourcePath() string { return g.cfg.Source }
func (g *globalInstallContext) ConfigSkills() []install.SkillEntryDTO {
return toSkillEntryDTOs(g.reg.Skills)
return storeToSkillEntryDTOs(g.store)
}
func (g *globalInstallContext) Reconcile() error {
return config.ReconcileGlobalSkills(g.cfg, g.reg)
return config.ReconcileGlobalSkills(g.cfg, g.store)
}
func (g *globalInstallContext) PostInstallSkill(string) error { return nil }
func (g *globalInstallContext) Mode() string { return "global" }
@@ -61,7 +65,7 @@ type projectInstallContext struct {
func (p *projectInstallContext) SourcePath() string { return p.runtime.sourcePath }
func (p *projectInstallContext) ConfigSkills() []install.SkillEntryDTO {
return toSkillEntryDTOs(p.runtime.registry.Skills)
return storeToSkillEntryDTOs(p.runtime.skillsStore)
}
func (p *projectInstallContext) Reconcile() error {
return reconcileProjectRemoteSkills(p.runtime)
+313 -30
View File
@@ -16,6 +16,17 @@ import (
)
func handleTrackedRepoInstall(source *install.Source, cfg *config.Config, opts install.InstallOptions) (installLogSummary, error) {
trackedKind, err := install.InferTrackedKind(source, opts.Kind)
if err != nil {
return installLogSummary{}, err
}
opts.Kind = trackedKind
trackSourceDir := cfg.Source
if trackedKind == "agent" {
trackSourceDir = cfg.EffectiveAgentsSource()
}
logSummary := installLogSummary{
Source: source.Raw,
DryRun: opts.DryRun,
@@ -50,7 +61,7 @@ func handleTrackedRepoInstall(source *install.Source, cfg *config.Config, opts i
}
}
result, err := install.InstallTrackedRepo(source, cfg.Source, opts)
result, err := install.InstallTrackedRepo(source, trackSourceDir, opts)
if err != nil {
if errors.Is(err, install.ErrSkipSameRepo) {
treeSpinner.Warn(firstWarningLine(err.Error()))
@@ -72,8 +83,13 @@ func handleTrackedRepoInstall(source *install.Source, cfg *config.Config, opts i
fmt.Println()
ui.Warning("[dry-run] Would install tracked repo")
} else {
ui.StepContinue("Found", fmt.Sprintf("%d skill(s)", result.SkillCount))
renderTrackedRepoMeta(result.RepoName, result.Skills, result.RepoPath)
if trackedKind == "agent" {
ui.StepContinue("Found", fmt.Sprintf("%d agent(s)", result.AgentCount))
renderTrackedAgentRepoMeta(result.RepoName, result.Agents, result.RepoPath)
} else {
ui.StepContinue("Found", fmt.Sprintf("%d skill(s)", result.SkillCount))
renderTrackedRepoMeta(result.RepoName, result.Skills, result.RepoPath)
}
}
// Display warnings and risk info
@@ -93,8 +109,13 @@ func handleTrackedRepoInstall(source *install.Source, cfg *config.Config, opts i
// Show next steps
if !opts.DryRun {
ui.SectionLabel("Next Steps")
ui.Info("Run 'skillshare sync' to distribute skills to all targets")
ui.Info("Run 'skillshare update %s' to update this repo later", result.RepoName)
if trackedKind == "agent" {
ui.Info("Run 'skillshare sync agents' to distribute agents to all targets")
ui.Info("Run 'skillshare update agents --all' to update tracked agent repos later")
} else {
ui.Info("Run 'skillshare sync' to distribute skills to all targets")
ui.Info("Run 'skillshare update %s' to update this repo later", result.RepoName)
}
}
return logSummary, nil
@@ -218,16 +239,31 @@ func handleGitInstall(source *install.Source, cfg *config.Config, opts install.I
logSummary.InstalledSkills = append(logSummary.InstalledSkills, skill.Name)
logSummary.SkillCount = len(logSummary.InstalledSkills)
}
installDiscoveredAgents(discovery, cfg, opts)
return logSummary, nil
}
// Step 3: Show found skills
if len(discovery.Skills) == 0 {
ui.StepEnd("Found", "No skills (no SKILL.md files)")
// Step 3: Show found resources
if len(discovery.Skills) == 0 && len(discovery.Agents) == 0 {
ui.StepEnd("Found", "No skills or agents found")
return logSummary, nil
}
ui.StepEnd("Found", fmt.Sprintf("%d skill(s)", len(discovery.Skills)))
// Pure agent repo — no skills, only agents
if len(discovery.Skills) == 0 && len(discovery.Agents) > 0 {
ui.StepEnd("Found", fmt.Sprintf("%d agent(s)", len(discovery.Agents)))
agentsRoot := cfg.EffectiveAgentsSource()
agentsDir := agentsDirWithInto(agentsRoot, opts)
agentOpts := opts
agentOpts.SourceDir = agentsRoot
return handleAgentInstall(discovery, agentsDir, agentOpts, logSummary)
}
foundMsg := fmt.Sprintf("%d skill(s)", len(discovery.Skills))
if len(discovery.Agents) > 0 {
foundMsg += fmt.Sprintf(", %d agent(s)", len(discovery.Agents))
}
ui.StepEnd("Found", foundMsg)
// Apply --exclude early so excluded skills never appear in prompts
if len(opts.Exclude) > 0 {
@@ -295,6 +331,7 @@ func handleGitInstall(source *install.Source, cfg *config.Config, opts install.I
logSummary.InstalledSkills = append(logSummary.InstalledSkills, skill.Name)
logSummary.SkillCount = len(logSummary.InstalledSkills)
}
installDiscoveredAgents(discovery, cfg, opts)
return logSummary, nil
}
@@ -319,6 +356,7 @@ func handleGitInstall(source *install.Source, cfg *config.Config, opts install.I
logSummary.InstalledSkills = append(logSummary.InstalledSkills, batchSummary.InstalledSkills...)
logSummary.FailedSkills = append(logSummary.FailedSkills, batchSummary.FailedSkills...)
logSummary.SkillCount = len(logSummary.InstalledSkills)
installDiscoveredAgents(discovery, cfg, opts)
return logSummary, nil
}
@@ -354,6 +392,7 @@ func handleGitInstall(source *install.Source, cfg *config.Config, opts install.I
logSummary.InstalledSkills = append(logSummary.InstalledSkills, batchSummary.InstalledSkills...)
logSummary.FailedSkills = append(logSummary.FailedSkills, batchSummary.FailedSkills...)
logSummary.SkillCount = len(logSummary.InstalledSkills)
installDiscoveredAgents(discovery, cfg, opts)
return logSummary, nil
}
@@ -401,7 +440,7 @@ func installSelectedSkills(selected []install.SkillInfo, discovery *install.Disc
}
}
// Reorder: install root skill first so children can nest under it
// Reorder: install root skill first so children nest under it on disk.
orderedSkills := selected
if rootIdx > 0 {
orderedSkills = make([]install.SkillInfo, 0, len(selected))
@@ -410,9 +449,6 @@ func installSelectedSkills(selected []install.SkillInfo, discovery *install.Disc
orderedSkills = append(orderedSkills, selected[rootIdx+1:]...)
}
// Track if root was installed (children are already included in root)
rootInstalled := false
for i, skill := range orderedSkills {
if installSpinner != nil {
installSpinner.NextStep(fmt.Sprintf("Installing %s...", skill.Name))
@@ -425,6 +461,10 @@ func installSelectedSkills(selected []install.SkillInfo, discovery *install.Disc
}
// Determine destination path and effective --into for force hints.
// Orchestrator repos: when the root skill is also selected, children
// install as siblings under <parentName>/ so they remain independent
// skills discoverable by sync (issue #124). The root copy excludes
// child skill directories so they do not duplicate.
var destPath string
skillOpts := opts
if skill.Path == "." {
@@ -443,15 +483,6 @@ func installSelectedSkills(selected []install.SkillInfo, discovery *install.Disc
destPath = destWithInto(cfg.Source, opts, skill.Name)
}
// If root was installed, children are already included - skip reinstall
if rootInstalled && skill.Path != "." {
results = append(results, skillInstallResult{skill: skill, success: true, message: fmt.Sprintf("included in %s", parentName)})
if progressBar != nil {
progressBar.Increment()
}
continue
}
installResult, err := install.InstallFromDiscovery(discovery, skill, destPath, skillOpts)
if err != nil {
r := skillInstallResult{skill: skill, success: false, message: err.Error(), err: err}
@@ -465,9 +496,6 @@ func installSelectedSkills(selected []install.SkillInfo, discovery *install.Disc
continue
}
if skill.Path == "." {
rootInstalled = true
}
message := "installed"
if len(installResult.Warnings) > 0 {
message = fmt.Sprintf("installed (%d warning(s))", len(installResult.Warnings))
@@ -900,14 +928,14 @@ func installFromGlobalConfig(cfg *config.Config, opts install.InstallOptions) (i
AuditVerbose: opts.AuditVerbose,
}
reg, regErr := config.LoadRegistry(cfg.RegistryDir)
if regErr != nil {
return summary, fmt.Errorf("failed to load registry: %w", regErr)
store, storeErr := install.LoadMetadataWithMigration(cfg.Source, "")
if storeErr != nil {
return summary, fmt.Errorf("failed to load metadata: %w", storeErr)
}
ctx := &globalInstallContext{cfg: cfg, reg: reg}
ctx := &globalInstallContext{cfg: cfg, store: store}
if len(ctx.ConfigSkills()) == 0 {
ui.Info("No remote skills defined in registry")
ui.Info("No remote skills defined in metadata")
ui.Info("Install a skill first: skillshare install <source>")
return summary, nil
}
@@ -1003,6 +1031,14 @@ func renderTrackedRepoMeta(repoName string, skills []string, repoPath string) {
ui.StepEnd("Location", repoPath)
}
func renderTrackedAgentRepoMeta(repoName string, agents []string, repoPath string) {
ui.StepContinue("Tracked", repoName)
if len(agents) > 0 && len(agents) <= 10 {
ui.StepContinue("Agents", strings.Join(agents, ", "))
}
ui.StepEnd("Location", repoPath)
}
// truncateDesc truncates a description string to max runes, appending " ..." if truncated.
func truncateDesc(s string, max int) string {
runes := []rune(s)
@@ -1011,3 +1047,250 @@ func truncateDesc(s string, max int) string {
}
return string(runes[:max]) + " ..."
}
// handleAgentInstall installs agents from a pure-agent repo.
// Matches the skill install flow: single→direct, multi→TUI/flags, batch progress.
func handleAgentInstall(discovery *install.DiscoveryResult, agentsDir string, opts install.InstallOptions, logSummary installLogSummary) (installLogSummary, error) {
agents := discovery.Agents
// Single agent: install directly (matches single-skill pattern)
if len(agents) == 1 && !opts.HasAgentFilter() && !opts.ShouldInstallAll() {
agent := agents[0]
if opts.DryRun {
ui.Info(" %s (%s)", agent.Name, agent.FileName)
ui.Warning("[dry-run] Would install agent: %s", agent.Name)
return logSummary, nil
}
spinner := ui.StartSpinner(fmt.Sprintf("Installing agent %s...", agent.Name))
result, err := install.InstallAgentFromDiscovery(discovery, agent, agentsDir, opts)
spinner.Stop()
if err != nil {
ui.ErrorMsg("Failed to install agent %s: %v", agent.Name, err)
return logSummary, err
}
if result.Action == "skipped" {
ui.StepSkip(agent.Name, strings.Join(result.Warnings, "; "))
} else {
ui.SuccessMsg("Installed agent: %s", agent.Name)
logSummary.SkillCount = 1
logSummary.InstalledSkills = append(logSummary.InstalledSkills, agent.Name)
ui.SectionLabel("Next Steps")
ui.Info("Run 'skillshare sync agents' to distribute to all targets")
}
return logSummary, nil
}
// Dry-run: show list and return
if opts.DryRun {
selected := agents
if opts.HasAgentFilter() || opts.ShouldInstallAll() {
var err error
selected, err = selectAgents(agents, opts)
if err != nil {
return logSummary, err
}
}
fmt.Println()
for _, a := range selected {
ui.Info(" %s (%s)", a.Name, a.FileName)
}
ui.Warning("[dry-run] Would install %d agent(s)", len(selected))
return logSummary, nil
}
// Non-interactive: --all/--yes or -a filter
if opts.HasAgentFilter() || opts.ShouldInstallAll() {
selected, err := selectAgents(agents, opts)
if err != nil {
return logSummary, err
}
fmt.Println()
batchSummary := installSelectedAgents(selected, discovery, agentsDir, opts)
logSummary.InstalledSkills = append(logSummary.InstalledSkills, batchSummary.InstalledSkills...)
logSummary.FailedSkills = append(logSummary.FailedSkills, batchSummary.FailedSkills...)
logSummary.SkillCount = len(logSummary.InstalledSkills)
return logSummary, nil
}
// Non-TTY fallback
if !ui.IsTTY() {
ui.Info("Found %d agents. Non-interactive mode requires --all, --yes, or -a <names>", len(agents))
return logSummary, fmt.Errorf("interactive selection not available in non-TTY mode")
}
// Interactive TUI selection
fmt.Println()
selected, err := selectAgents(agents, opts)
if err != nil {
return logSummary, err
}
if len(selected) == 0 {
ui.Info("No agents selected")
return logSummary, nil
}
fmt.Println()
batchSummary := installSelectedAgents(selected, discovery, agentsDir, opts)
logSummary.InstalledSkills = append(logSummary.InstalledSkills, batchSummary.InstalledSkills...)
logSummary.FailedSkills = append(logSummary.FailedSkills, batchSummary.FailedSkills...)
logSummary.SkillCount = len(logSummary.InstalledSkills)
return logSummary, nil
}
// installDiscoveredAgents installs agents from a mixed repo after skills have been installed.
func installDiscoveredAgents(discovery *install.DiscoveryResult, cfg *config.Config, opts install.InstallOptions) {
if len(discovery.Agents) == 0 {
return
}
if opts.Kind == "skill" {
return
}
agentsRoot := cfg.EffectiveAgentsSource()
agentsDir := agentsDirWithInto(agentsRoot, opts)
agentOpts := opts
agentOpts.SourceDir = agentsRoot
fmt.Println()
ui.Header("Installing agents")
for _, agent := range discovery.Agents {
spinner := ui.StartSpinner(fmt.Sprintf("Installing agent %s...", agent.Name))
result, err := install.InstallAgentFromDiscovery(discovery, agent, agentsDir, agentOpts)
spinner.Stop()
if err != nil {
ui.ErrorMsg("Failed to install agent %s: %v", agent.Name, err)
continue
}
if result.Action == "skipped" {
ui.StepSkip(agent.Name, strings.Join(result.Warnings, "; "))
} else if agentOpts.DryRun {
ui.Warning("[dry-run] Would install agent: %s", agent.Name)
} else {
ui.SuccessMsg("Installed agent: %s", agent.Name)
}
}
}
// agentInstallResult tracks the outcome of a single agent install.
type agentInstallResult struct {
agent install.AgentInfo
success bool
skipped bool
message string
}
// installSelectedAgents installs a batch of agents with progress display.
func installSelectedAgents(selected []install.AgentInfo, discovery *install.DiscoveryResult, agentsDir string, opts install.InstallOptions) installBatchSummary {
results := make([]agentInstallResult, 0, len(selected))
var installSpinner *ui.Spinner
var progressBar *ui.ProgressBar
if len(selected) > largeBatchProgressThreshold {
progressBar = ui.StartProgress("Installing agents", len(selected))
} else {
installSpinner = ui.StartSpinnerWithSteps("Installing...", len(selected))
}
for i, agent := range selected {
if installSpinner != nil {
installSpinner.NextStep(fmt.Sprintf("Installing %s...", agent.Name))
if i == 0 {
installSpinner.Update(fmt.Sprintf("Installing %s...", agent.Name))
}
}
if progressBar != nil {
progressBar.UpdateTitle(fmt.Sprintf("Installing %s", agent.Name))
}
result, err := install.InstallAgentFromDiscovery(discovery, agent, agentsDir, opts)
if err != nil {
results = append(results, agentInstallResult{agent: agent, message: err.Error()})
} else if result.Action == "skipped" {
results = append(results, agentInstallResult{agent: agent, skipped: true, message: strings.Join(result.Warnings, "; ")})
} else {
results = append(results, agentInstallResult{agent: agent, success: true})
}
if progressBar != nil {
progressBar.Increment()
}
}
if progressBar != nil {
progressBar.Stop()
}
displayAgentInstallResults(results, installSpinner)
summary := installBatchSummary{}
for _, r := range results {
if r.success {
summary.InstalledSkills = append(summary.InstalledSkills, r.agent.Name)
} else if !r.skipped {
summary.FailedSkills = append(summary.FailedSkills, r.agent.Name)
}
}
return summary
}
// displayAgentInstallResults renders the install outcome for a batch of agents.
func displayAgentInstallResults(results []agentInstallResult, spinner *ui.Spinner) {
var installed, failed, skippedCount int
for _, r := range results {
switch {
case r.success:
installed++
case r.skipped:
skippedCount++
default:
failed++
}
}
summaryMsg := buildInstallSummary(installed, failed, skippedCount)
if spinner != nil {
switch {
case failed > 0 && installed == 0:
spinner.Fail(summaryMsg)
case failed > 0:
spinner.Warn(summaryMsg)
default:
spinner.Success(summaryMsg)
}
} else {
fmt.Println()
if failed > 0 && installed == 0 {
ui.ErrorMsg("%s", summaryMsg)
} else {
ui.SuccessMsg("%s", summaryMsg)
}
}
if failed > 0 {
ui.SectionLabel("Failed")
for _, r := range results {
if !r.success && !r.skipped {
ui.StepFail(r.agent.Name, r.message)
}
}
}
if skippedCount > 0 {
ui.SectionLabel("Skipped")
for _, r := range results {
if r.skipped {
ui.StepSkip(r.agent.Name, r.message)
}
}
}
if installed > 0 {
ui.SectionLabel("Installed")
for _, r := range results {
if r.success {
ui.StepDone(r.agent.Name, "")
}
}
fmt.Println()
ui.SectionLabel("Next Steps")
ui.Info("Run 'skillshare sync agents' to distribute to all targets")
}
}
+27 -12
View File
@@ -10,17 +10,21 @@ import (
)
func cmdInstallProject(args []string, root string) (installLogSummary, error) {
summary := installLogSummary{
Mode: "project",
}
parsed, showHelp, err := parseInstallArgs(args)
if showHelp {
printInstallHelp()
return summary, nil
return installLogSummary{Mode: "project"}, nil
}
if err != nil {
return summary, err
return installLogSummary{Mode: "project"}, err
}
applyInstallJSONDefaults(parsed)
return cmdInstallProjectParsed(parsed, root)
}
func cmdInstallProjectParsed(parsed *installArgs, root string) (installLogSummary, error) {
summary := installLogSummary{
Mode: "project",
}
summary.DryRun = parsed.opts.DryRun
summary.Tracked = parsed.opts.Track
@@ -46,17 +50,17 @@ func cmdInstallProject(args []string, root string) (installLogSummary, error) {
if parsed.sourceArg == "" {
hasSourceFlags := parsed.opts.Name != "" || parsed.opts.Into != "" ||
parsed.opts.Track || len(parsed.opts.Skills) > 0 ||
len(parsed.opts.Exclude) > 0 || parsed.opts.All || parsed.opts.Yes || parsed.opts.Update ||
parsed.opts.Branch != ""
if hasSourceFlags {
return summary, fmt.Errorf("flags --name, --into, --track, --skill, --exclude, --all, --yes, and --update require a source argument")
parsed.opts.Track || parsed.opts.HasSkillFilter() || parsed.opts.HasAgentFilter() ||
len(parsed.opts.Exclude) > 0 || parsed.opts.Update || parsed.opts.Branch != "" ||
parsed.opts.Kind != ""
if hasSourceFlags || ((parsed.opts.All || parsed.opts.Yes) && !parsed.jsonOutput) {
return summary, fmt.Errorf("flags --name, --into, --track, --skill, --agent, --kind, --exclude, --all, --yes, --branch, and --update require a source argument")
}
summary.Source = "project-config"
return installFromProjectConfig(runtime, parsed.opts)
}
cfg := &config.Config{Source: runtime.sourcePath, GitLabHosts: runtime.config.GitLabHosts}
cfg := &config.Config{Source: runtime.sourcePath, AgentsSource: runtime.agentsSourcePath, GitLabHosts: runtime.config.GitLabHosts}
source, resolvedFromMeta, err := resolveInstallSource(parsed.sourceArg, parsed.opts, cfg)
if err == nil && parsed.opts.Branch != "" {
source.Branch = parsed.opts.Branch
@@ -72,6 +76,10 @@ func cmdInstallProject(args []string, root string) (installLogSummary, error) {
return summary, err
}
if !parsed.opts.DryRun {
freshStore, loadErr := install.LoadMetadata(runtime.sourcePath)
if loadErr == nil {
runtime.skillsStore = freshStore
}
return summary, reconcileProjectRemoteSkills(runtime)
}
return summary, nil
@@ -87,6 +95,13 @@ func cmdInstallProject(args []string, root string) (installLogSummary, error) {
return summary, nil
}
// Reload metadata store: install may have written new entries via WriteMeta
// that the pre-install runtime doesn't know about.
freshStore, loadErr := install.LoadMetadata(runtime.sourcePath)
if loadErr == nil {
runtime.skillsStore = freshStore
}
return summary, reconcileProjectRemoteSkills(runtime)
}
+70 -5
View File
@@ -101,16 +101,20 @@ func promptOrchestratorSelection(rootSkill install.SkillInfo, childSkills []inst
return nil, nil
}
// Build the full skill list (root first, then children) — used for both
// "entire pack" and individual selection so the root skill remains a
// selectable option in the multi-select UI (issue #124).
allSkills := make([]install.SkillInfo, 0, len(childSkills)+1)
allSkills = append(allSkills, rootSkill)
allSkills = append(allSkills, childSkills...)
// If "entire pack" selected, return all skills
if indices[0] == 0 {
allSkills := make([]install.SkillInfo, 0, len(childSkills)+1)
allSkills = append(allSkills, rootSkill)
allSkills = append(allSkills, childSkills...)
return allSkills, nil
}
// Stage 2: Select individual skills (children only, no root)
return promptMultiSelect(childSkills)
// Stage 2: Select individual skills (root + children)
return promptMultiSelect(allSkills)
}
// promptLargeRepoSelection presents a TUI directory picker for large repos.
@@ -285,3 +289,64 @@ func printSkillListCompact(skills []install.SkillInfo) {
}
ui.Info("... and %d more skill(s)", len(skills)-showCount)
}
// selectAgents routes agent selection through filter, all, or interactive TUI.
func selectAgents(agents []install.AgentInfo, opts install.InstallOptions) ([]install.AgentInfo, error) {
switch {
case opts.HasAgentFilter():
matched, notFound := filterAgentsByName(agents, opts.AgentNames)
if len(notFound) > 0 {
return nil, fmt.Errorf("agents not found: %s", strings.Join(notFound, ", "))
}
return matched, nil
case opts.ShouldInstallAll():
return agents, nil
default:
return promptAgentInstallSelection(agents)
}
}
// filterAgentsByName returns agents matching any of the given names (case-insensitive).
func filterAgentsByName(agents []install.AgentInfo, names []string) (matched []install.AgentInfo, notFound []string) {
nameSet := make(map[string]bool, len(names))
for _, n := range names {
nameSet[strings.ToLower(n)] = true
}
found := make(map[string]bool)
for _, a := range agents {
if nameSet[strings.ToLower(a.Name)] {
matched = append(matched, a)
found[strings.ToLower(a.Name)] = true
}
}
for _, n := range names {
if !found[strings.ToLower(n)] {
notFound = append(notFound, n)
}
}
return
}
// promptAgentInstallSelection shows a multi-select TUI for agent installation.
func promptAgentInstallSelection(agents []install.AgentInfo) ([]install.AgentInfo, error) {
items := make([]checklistItemData, len(agents))
for i, a := range agents {
items[i] = checklistItemData{label: a.Name, desc: a.FileName}
}
indices, err := runChecklistTUI(checklistConfig{
title: "Select agents to install",
items: items,
itemName: "agent",
})
if err != nil {
return nil, err
}
if indices == nil {
return nil, nil // cancelled
}
selected := make([]install.AgentInfo, len(indices))
for i, idx := range indices {
selected[i] = agents[idx]
}
return selected, nil
}
+11 -10
View File
@@ -6,11 +6,12 @@ import (
"sort"
"strings"
"skillshare/internal/install"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"skillshare/internal/install"
)
// dirPickerItemKind distinguishes directory entries from the "Install all" action.
@@ -86,7 +87,7 @@ func newDirPickerModel(skills []install.SkillInfo) dirPickerModel {
l := list.New(items, newPrefixDelegate(true), 0, 0)
l.Title = "Select directory"
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
@@ -95,8 +96,8 @@ func newDirPickerModel(skills []install.SkillInfo) dirPickerModel {
// Filter text input
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
m.list = l
m.allItems = items
@@ -306,7 +307,7 @@ func (m dirPickerModel) View() string {
} else {
help = "↑↓ navigate enter select / filter q quit"
}
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
@@ -410,7 +411,7 @@ func newSkillSelectModel(skills []install.SkillInfo) skillSelectModel {
l := list.New(items, newPrefixDelegate(false), 0, 0)
l.Title = skillSelectTitle(0, len(sorted))
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
@@ -419,8 +420,8 @@ func newSkillSelectModel(skills []install.SkillInfo) skillSelectModel {
// Filter text input
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
return skillSelectModel{
list: l,
@@ -608,7 +609,7 @@ func (m skillSelectModel) View() string {
))
help := "↑↓ navigate space toggle a all enter confirm / filter esc cancel"
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
+25
View File
@@ -54,6 +54,31 @@ func writeJSONError(err error) error {
return &jsonSilentError{cause: err}
}
// jsonUISuppressor encapsulates the common "suppress stdout/UI once,
// restore-once-and-only-once before writing the JSON payload" pattern that
// every --json-capable command needs. Call Flush before emitting JSON so
// the payload goes to real stdout; deferring Flush guarantees restoration
// even if the command returns early.
type jsonUISuppressor struct{ restore func() }
// newJSONUISuppressor suppresses UI only when jsonMode is true.
// Returns a zero-value suppressor otherwise, so callers can unconditionally
// defer Flush without extra branching.
func newJSONUISuppressor(jsonMode bool) *jsonUISuppressor {
if !jsonMode {
return &jsonUISuppressor{}
}
return &jsonUISuppressor{restore: suppressUIToDevnull()}
}
// Flush restores stdout/UI. Safe to call multiple times.
func (s *jsonUISuppressor) Flush() {
if s.restore != nil {
s.restore()
s.restore = nil
}
}
// suppressUIToDevnull temporarily redirects os.Stdout and the progress
// writer to /dev/null so that handler functions using fmt.Printf / ui.*
// produce zero visible output. This keeps --json output clean even when
+128
View File
@@ -0,0 +1,128 @@
package main
import "fmt"
// resourceKindFilter represents the kind filtering for CLI commands.
type resourceKindFilter int
const (
kindAll resourceKindFilter = iota // no filter — all kinds
kindSkills // skills only
kindAgents // agents only
)
// parseKindArg extracts a kind filter from the first positional argument.
// Returns the filter and remaining args.
// Recognized values: "skills", "skill", "agents", "agent".
// If the first arg is not a kind keyword, returns kindSkills with args unchanged
// (default is skills-only; use --all flag for both).
func parseKindArg(args []string) (resourceKindFilter, []string) {
if len(args) == 0 {
return kindSkills, args
}
switch args[0] {
case "skills", "skill":
return kindSkills, args[1:]
case "agents", "agent":
return kindAgents, args[1:]
default:
return kindSkills, args
}
}
// extractAllFlag scans args for --all, removes it, and returns true if found.
// Commands use this to let --all mean kindAll (skills + agents).
func extractAllFlag(args []string) (bool, []string) {
found := false
rest := make([]string, 0, len(args))
for _, a := range args {
if a == "--all" {
found = true
} else {
rest = append(rest, a)
}
}
return found, rest
}
// parseKindArgWithAll combines parseKindArg and extractAllFlag.
// It parses the positional kind keyword (agents/skills) and the --all flag.
// Used by commands where --all means kindAll (skills + agents).
func parseKindArgWithAll(args []string) (resourceKindFilter, []string) {
kind, rest := parseKindArg(args)
if allKinds, remaining := extractAllFlag(rest); allKinds {
kind = kindAll
rest = remaining
}
return kind, rest
}
// parseKindFlag extracts --kind flag from args.
// Returns the filter and remaining args with --kind removed.
func parseKindFlag(args []string) (resourceKindFilter, []string, error) {
kind := kindAll
rest := make([]string, 0, len(args))
for i := 0; i < len(args); i++ {
if args[i] == "--kind" {
if i+1 >= len(args) {
return kindAll, nil, fmt.Errorf("--kind requires a value (skill or agent)")
}
i++
switch args[i] {
case "skill", "skills":
kind = kindSkills
case "agent", "agents":
kind = kindAgents
default:
return kindAll, nil, fmt.Errorf("--kind must be 'skill' or 'agent', got %q", args[i])
}
} else {
rest = append(rest, args[i])
}
}
return kind, rest, nil
}
func (k resourceKindFilter) String() string {
switch k {
case kindSkills:
return "skills"
case kindAgents:
return "agents"
default:
return "all"
}
}
// Noun returns the pluralized resource noun for display.
// Noun(1) → "skill"/"agent", Noun(2+) → "skills"/"agents".
func (k resourceKindFilter) Noun(count int) string {
switch k {
case kindAgents:
if count == 1 {
return "agent"
}
return "agents"
default:
if count == 1 {
return "skill"
}
return "skills"
}
}
// SingularNoun returns the singular resource noun (no count needed).
func (k resourceKindFilter) SingularNoun() string {
return k.Noun(1)
}
func (k resourceKindFilter) IncludesSkills() bool {
return k == kindAll || k == kindSkills
}
func (k resourceKindFilter) IncludesAgents() bool {
return k == kindAll || k == kindAgents
}
+128
View File
@@ -0,0 +1,128 @@
package main
import "testing"
func TestParseKindArg(t *testing.T) {
tests := []struct {
args []string
wantKind resourceKindFilter
wantRest []string
}{
{nil, kindSkills, nil},
{[]string{}, kindSkills, []string{}},
{[]string{"skills"}, kindSkills, []string{}},
{[]string{"skill"}, kindSkills, []string{}},
{[]string{"agents"}, kindAgents, []string{}},
{[]string{"agent"}, kindAgents, []string{}},
{[]string{"all"}, kindSkills, []string{"all"}}, // "all" no longer a keyword
{[]string{"all", "--json"}, kindSkills, []string{"all", "--json"}}, // falls through to default
{[]string{"agents", "tutor"}, kindAgents, []string{"tutor"}},
{[]string{"--json"}, kindSkills, []string{"--json"}},
{[]string{"my-skill"}, kindSkills, []string{"my-skill"}},
}
for _, tt := range tests {
kind, rest := parseKindArg(tt.args)
if kind != tt.wantKind {
t.Errorf("parseKindArg(%v) kind = %v, want %v", tt.args, kind, tt.wantKind)
}
if len(rest) != len(tt.wantRest) {
t.Errorf("parseKindArg(%v) rest = %v, want %v", tt.args, rest, tt.wantRest)
}
}
}
func TestParseKindFlag(t *testing.T) {
tests := []struct {
args []string
wantKind resourceKindFilter
wantRest []string
wantErr bool
}{
{[]string{}, kindAll, []string{}, false},
{[]string{"--kind", "agent"}, kindAgents, []string{}, false},
{[]string{"--kind", "skill"}, kindSkills, []string{}, false},
{[]string{"--json", "--kind", "agent", "foo"}, kindAgents, []string{"--json", "foo"}, false},
{[]string{"--kind"}, kindAll, nil, true},
{[]string{"--kind", "invalid"}, kindAll, nil, true},
}
for _, tt := range tests {
kind, rest, err := parseKindFlag(tt.args)
if (err != nil) != tt.wantErr {
t.Errorf("parseKindFlag(%v) err = %v, wantErr %v", tt.args, err, tt.wantErr)
continue
}
if err != nil {
continue
}
if kind != tt.wantKind {
t.Errorf("parseKindFlag(%v) kind = %v, want %v", tt.args, kind, tt.wantKind)
}
if len(rest) != len(tt.wantRest) {
t.Errorf("parseKindFlag(%v) rest = %v, want %v", tt.args, rest, tt.wantRest)
}
}
}
func TestExtractAllFlag(t *testing.T) {
tests := []struct {
args []string
wantAll bool
wantRest []string
}{
{nil, false, []string{}},
{[]string{"--all"}, true, []string{}},
{[]string{"--json", "--all", "foo"}, true, []string{"--json", "foo"}},
{[]string{"--json"}, false, []string{"--json"}},
{[]string{"agents", "--all"}, true, []string{"agents"}},
{[]string{"--all", "--all"}, true, []string{}}, // duplicate --all
}
for _, tt := range tests {
gotAll, gotRest := extractAllFlag(tt.args)
if gotAll != tt.wantAll {
t.Errorf("extractAllFlag(%v) all = %v, want %v", tt.args, gotAll, tt.wantAll)
}
if len(gotRest) != len(tt.wantRest) {
t.Errorf("extractAllFlag(%v) rest = %v, want %v", tt.args, gotRest, tt.wantRest)
}
}
}
func TestParseKindArgWithAll(t *testing.T) {
tests := []struct {
args []string
wantKind resourceKindFilter
wantRest []string
}{
{nil, kindSkills, nil},
{[]string{"--all"}, kindAll, []string{}},
{[]string{"agents"}, kindAgents, []string{}},
{[]string{"agents", "--all"}, kindAll, []string{}},
{[]string{"--json", "--all"}, kindAll, []string{"--json"}},
{[]string{"--json"}, kindSkills, []string{"--json"}},
}
for _, tt := range tests {
kind, rest := parseKindArgWithAll(tt.args)
if kind != tt.wantKind {
t.Errorf("parseKindArgWithAll(%v) kind = %v, want %v", tt.args, kind, tt.wantKind)
}
if len(rest) != len(tt.wantRest) {
t.Errorf("parseKindArgWithAll(%v) rest = %v, want %v", tt.args, rest, tt.wantRest)
}
}
}
func TestResourceKindFilter_Includes(t *testing.T) {
if !kindAll.IncludesSkills() || !kindAll.IncludesAgents() {
t.Error("kindAll should include both")
}
if !kindSkills.IncludesSkills() || kindSkills.IncludesAgents() {
t.Error("kindSkills should include only skills")
}
if kindAgents.IncludesSkills() || !kindAgents.IncludesAgents() {
t.Error("kindAgents should include only agents")
}
}
+203 -87
View File
@@ -12,7 +12,9 @@ import (
"skillshare/internal/config"
"skillshare/internal/git"
"skillshare/internal/install"
"skillshare/internal/resource"
"skillshare/internal/sync"
"skillshare/internal/theme"
"skillshare/internal/ui"
"skillshare/internal/utils"
)
@@ -191,22 +193,43 @@ func sortSkillEntries(skills []skillEntry, sortBy string) {
}
return a < b // ascending
})
default: // "name" or empty
default: // "name" or empty — group by top-level bucket, then by RelPath
sort.SliceStable(skills, func(i, j int) bool {
return skills[i].Name < skills[j].Name
ti := skillTopGroup(skills[i])
tj := skillTopGroup(skills[j])
if ti != tj {
// Empty topGroup (standalone) sorts last so flat locals
// don't split named groups apart in the list TUI.
if ti == "" {
return false
}
if tj == "" {
return true
}
return ti < tj
}
return skills[i].RelPath < skills[j].RelPath
})
}
}
// buildSkillEntries builds skill entries from discovered skills.
// ReadMeta calls are parallelized with a bounded worker pool.
// Metadata is read from the centralized .metadata.json store.
func buildSkillEntries(discovered []sync.DiscoveredSkill) []skillEntry {
skills := make([]skillEntry, len(discovered))
// Pre-fill non-I/O fields
store := install.NewMetadataStore()
if len(discovered) > 0 {
sourceDir := strings.TrimSuffix(discovered[0].SourcePath, discovered[0].RelPath)
sourceDir = strings.TrimRight(sourceDir, `/\`)
store = install.LoadMetadataOrNew(sourceDir)
}
// Pre-fill non-I/O fields + metadata from store
for i, d := range discovered {
skills[i] = skillEntry{
Name: d.FlatName,
Kind: "skill",
IsNested: d.IsInRepo || utils.HasNestedSeparator(d.FlatName),
RelPath: d.RelPath,
Disabled: d.Disabled,
@@ -217,28 +240,17 @@ func buildSkillEntries(discovered []sync.DiscoveredSkill) []skillEntry {
skills[i].RepoName = parts[0]
}
}
}
// Parallel ReadMeta with bounded concurrency
const metaWorkers = 64
sem := make(chan struct{}, metaWorkers)
var wg gosync.WaitGroup
for i, d := range discovered {
wg.Add(1)
sem <- struct{}{}
go func(idx int, sourcePath string) {
defer wg.Done()
defer func() { <-sem }()
if meta, err := install.ReadMeta(sourcePath); err == nil && meta != nil {
skills[idx].Source = meta.Source
skills[idx].Type = meta.Type
skills[idx].InstalledAt = meta.InstalledAt.Format("2006-01-02")
skills[idx].Branch = meta.Branch
// Enrich from centralized metadata store
if entry := store.GetByPath(d.RelPath); entry != nil {
skills[i].Source = entry.Source
skills[i].Type = entry.Type
if !entry.InstalledAt.IsZero() {
skills[i].InstalledAt = entry.InstalledAt.Format("2006-01-02")
}
}(i, d.SourcePath)
skills[i].Branch = entry.Branch
}
}
wg.Wait()
// Fallback: for tracked-repo skills with no branch in metadata, read from git.
// Cache per-repo to avoid repeated subprocess calls for skills in the same repo.
@@ -261,6 +273,54 @@ func buildSkillEntries(discovered []sync.DiscoveredSkill) []skillEntry {
return skills
}
// discoverAndBuildAgentEntries discovers agents from the given source directory
// and builds skillEntry items with Kind="agent", enriched from the centralized
// metadata store.
func discoverAndBuildAgentEntries(agentsSource string) []skillEntry {
if agentsSource == "" {
return nil
}
discovered, err := resource.AgentKind{}.Discover(agentsSource)
if err != nil {
return nil
}
store := install.LoadMetadataOrNew(agentsSource)
entries := make([]skillEntry, len(discovered))
for i, d := range discovered {
entries[i] = skillEntry{
Name: d.Name,
Kind: "agent",
RelPath: d.RelPath,
IsNested: d.IsNested,
Disabled: d.Disabled,
}
// For tracked agents, set RepoName to the tracked repo root
// (e.g. "_vijaythecoder-awesome-claude-agents") so all agents under
// the same repo share one visual group — regardless of how deeply
// they're nested (agents/core, agents/specialized/python, etc.).
if d.IsInRepo && d.RepoRelPath != "" {
entries[i].RepoName = d.RepoRelPath
}
key := strings.TrimSuffix(d.RelPath, ".md")
if entry := store.GetByPath(key); entry != nil {
entries[i].Source = entry.Source
entries[i].Type = entry.Type
if !entry.InstalledAt.IsZero() {
entries[i].InstalledAt = entry.InstalledAt.Format("2006-01-02")
}
} else if d.RepoRelPath != "" {
repoPath := filepath.Join(agentsSource, filepath.FromSlash(d.RepoRelPath))
if repoURL, err := git.GetRemoteURL(repoPath); err == nil {
entries[i].Source = repoURL
entries[i].Type = "git"
}
}
}
return entries
}
// extractGroupDir returns the parent directory from a RelPath.
// "frontend/react-helper" → "frontend", "my-skill" → "", "_team/frontend/ui" → "_team/frontend"
func extractGroupDir(relPath string) string {
@@ -323,10 +383,11 @@ func hasGroups(skills []skillEntry) bool {
// displaySkillsVerbose displays skills in verbose mode, grouped by directory
func displaySkillsVerbose(skills []skillEntry) {
a := theme.ANSI()
if !hasGroups(skills) {
// Flat display — no grouping needed
for _, s := range skills {
fmt.Printf(" %s%s%s\n", ui.Cyan, s.Name, ui.Reset)
fmt.Printf(" %s%s%s\n", a.Accent, s.Name, a.Reset)
printVerboseDetails(s, " ")
}
return
@@ -338,7 +399,7 @@ func displaySkillsVerbose(skills []skillEntry) {
if i > 0 {
fmt.Println()
}
fmt.Printf(" %s%s/%s\n", ui.Dim, dir, ui.Reset)
fmt.Printf(" %s%s/%s\n", a.Dim, dir, a.Reset)
} else if i > 0 {
fmt.Println()
}
@@ -351,31 +412,33 @@ func displaySkillsVerbose(skills []skillEntry) {
indent = " "
detailIndent = " "
}
fmt.Printf("%s%s%s%s\n", indent, ui.Cyan, name, ui.Reset)
fmt.Printf("%s%s%s%s\n", indent, a.Accent, name, a.Reset)
printVerboseDetails(s, detailIndent)
}
}
}
func printVerboseDetails(s skillEntry, indent string) {
a := theme.ANSI()
if s.Disabled {
fmt.Printf("%s%sStatus:%s %sdisabled%s\n", indent, ui.Dim, ui.Reset, ui.Dim, ui.Reset)
fmt.Printf("%s%sStatus:%s %sdisabled%s\n", indent, a.Dim, a.Reset, a.Dim, a.Reset)
}
if s.RepoName != "" {
fmt.Printf("%s%sTracked repo:%s %s\n", indent, ui.Dim, ui.Reset, s.RepoName)
fmt.Printf("%s%sTracked repo:%s %s\n", indent, a.Dim, a.Reset, s.RepoName)
}
if s.Source != "" {
fmt.Printf("%s%sSource:%s %s\n", indent, ui.Dim, ui.Reset, s.Source)
fmt.Printf("%s%sType:%s %s\n", indent, ui.Dim, ui.Reset, s.Type)
fmt.Printf("%s%sInstalled:%s %s\n", indent, ui.Dim, ui.Reset, s.InstalledAt)
fmt.Printf("%s%sSource:%s %s\n", indent, a.Dim, a.Reset, s.Source)
fmt.Printf("%s%sType:%s %s\n", indent, a.Dim, a.Reset, s.Type)
fmt.Printf("%s%sInstalled:%s %s\n", indent, a.Dim, a.Reset, s.InstalledAt)
} else {
fmt.Printf("%s%sSource:%s (local - no metadata)\n", indent, ui.Dim, ui.Reset)
fmt.Printf("%s%sSource:%s (local - no metadata)\n", indent, a.Dim, a.Reset)
}
fmt.Println()
}
// displaySkillsCompact displays skills in compact mode, grouped by directory
func displaySkillsCompact(skills []skillEntry) {
a := theme.ANSI()
if !hasGroups(skills) {
// Flat display — identical to previous behavior
maxNameLen := 0
@@ -386,7 +449,7 @@ func displaySkillsCompact(skills []skillEntry) {
}
for _, s := range skills {
suffix := getSkillSuffix(s)
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Dim, ui.Reset)
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", a.Accent, a.Reset, maxNameLen, a.Dim, a.Reset)
fmt.Printf(format, s.Name, suffix)
}
return
@@ -398,7 +461,7 @@ func displaySkillsCompact(skills []skillEntry) {
if i > 0 {
fmt.Println()
}
fmt.Printf(" %s%s/%s\n", ui.Dim, dir, ui.Reset)
fmt.Printf(" %s%s/%s\n", a.Dim, dir, a.Reset)
} else if i > 0 {
fmt.Println()
}
@@ -416,10 +479,10 @@ func displaySkillsCompact(skills []skillEntry) {
name := displayName(s, dir)
suffix := getSkillSuffix(s)
if dir != "" {
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Dim, ui.Reset)
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", a.Accent, a.Reset, maxNameLen, a.Dim, a.Reset)
fmt.Printf(format, name, suffix)
} else {
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Dim, ui.Reset)
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", a.Accent, a.Reset, maxNameLen, a.Dim, a.Reset)
fmt.Printf(format, name, suffix)
}
}
@@ -512,6 +575,9 @@ func cmdList(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare list agents" or "--all").
kind, rest := parseKindArgWithAll(rest)
opts, err := parseListArgs(rest)
if opts.ShowHelp {
printListHelp()
@@ -522,7 +588,7 @@ func cmdList(args []string) error {
}
if mode == modeProject {
return cmdListProject(cwd, opts)
return cmdListProject(cwd, opts, kind)
}
cfg, err := config.Load()
@@ -533,114 +599,158 @@ func cmdList(args []string) error {
// TTY + not JSON + TUI enabled → launch TUI with async loading (no blank screen)
if !opts.JSON && shouldLaunchTUI(opts.NoTUI, cfg) {
loadFn := func() listLoadResult {
discovered, err := sync.DiscoverSourceSkillsAll(cfg.Source)
if err != nil {
return listLoadResult{err: fmt.Errorf("cannot discover skills: %w", err)}
// Always load both skills and agents — tab UI filters the view.
var allEntries []skillEntry
discovered, discErr := sync.DiscoverSourceSkillsAll(cfg.Source)
if discErr != nil {
return listLoadResult{err: fmt.Errorf("cannot discover skills: %w", discErr)}
}
skills := buildSkillEntries(discovered)
total := len(skills)
skills = filterSkillEntries(skills, opts.Pattern, opts.TypeFilter)
if opts.SortBy != "" {
sortSkillEntries(skills, opts.SortBy)
}
return listLoadResult{skills: toSkillItems(skills), totalCount: total}
allEntries = append(allEntries, buildSkillEntries(discovered)...)
allEntries = append(allEntries, discoverAndBuildAgentEntries(cfg.EffectiveAgentsSource())...)
total := len(allEntries)
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
// Always sort: buildGroupedItems relies on contiguous top-group
// blocks, which the default sort guarantees (tracked → named
// locals → standalone).
sortSkillEntries(allEntries, opts.SortBy)
return listLoadResult{skills: toSkillItems(allEntries), totalCount: total}
}
action, skillName, err := runListTUI(loadFn, "global", cfg.Source, cfg.Targets)
action, skillName, skillKind, err := runListTUI(loadFn, "global", cfg.Source, cfg.EffectiveAgentsSource(), cfg.Targets, kind)
if err != nil {
return err
}
switch action {
case "empty":
ui.Info("No skills installed")
ui.Info("Use 'skillshare install <source>' to install a skill")
resourceLabel := "skills"
if kind == kindAgents {
resourceLabel = "agents"
}
ui.Info("No %s installed", resourceLabel)
return nil
case "audit":
if skillKind == "agent" {
return cmdAudit([]string{"agents", "-g", skillName})
}
return cmdAudit([]string{"-g", skillName})
case "update":
if skillKind == "agent" {
return cmdUpdate([]string{"agents", "-g", skillName})
}
return cmdUpdate([]string{"-g", skillName})
case "uninstall":
if skillKind == "agent" {
return cmdUninstall([]string{"agents", "-g", "--force", skillName})
}
return cmdUninstall([]string{"-g", "--force", skillName})
}
return nil
}
// Non-TUI path (JSON or plain text): synchronous loading with spinner
resourceLabel := "skills"
if kind == kindAgents {
resourceLabel = "agents"
} else if kind == kindAll {
resourceLabel = "resources"
}
var sp *ui.Spinner
if !opts.JSON && ui.IsTTY() {
sp = ui.StartSpinner("Loading skills...")
sp = ui.StartSpinner(fmt.Sprintf("Loading %s...", resourceLabel))
}
discovered, err := sync.DiscoverSourceSkillsAll(cfg.Source)
if err != nil {
if sp != nil {
sp.Fail("Discovery failed")
var allEntries []skillEntry
var trackedRepos []string
var discoveredSkills []sync.DiscoveredSkill
if kind.IncludesSkills() {
var discErr error
discoveredSkills, discErr = sync.DiscoverSourceSkillsAll(cfg.Source)
if discErr != nil {
if sp != nil {
sp.Fail("Discovery failed")
}
return fmt.Errorf("cannot discover skills: %w", discErr)
}
return fmt.Errorf("cannot discover skills: %w", err)
trackedRepos = extractTrackedRepos(discoveredSkills)
if sp != nil {
sp.Update(fmt.Sprintf("Reading metadata for %d skills...", len(discoveredSkills)))
}
allEntries = append(allEntries, buildSkillEntries(discoveredSkills)...)
}
if kind.IncludesAgents() {
agentEntries := discoverAndBuildAgentEntries(cfg.EffectiveAgentsSource())
allEntries = append(allEntries, agentEntries...)
}
trackedRepos := extractTrackedRepos(discovered)
if sp != nil {
sp.Update(fmt.Sprintf("Reading metadata for %d skills...", len(discovered)))
sp.Success(fmt.Sprintf("Loaded %d %s", len(allEntries), resourceLabel))
}
skills := buildSkillEntries(discovered)
if sp != nil {
sp.Success(fmt.Sprintf("Loaded %d skills", len(skills)))
}
totalCount := len(skills)
totalCount := len(allEntries)
hasFilter := opts.Pattern != "" || opts.TypeFilter != ""
// Apply filter and sort
skills = filterSkillEntries(skills, opts.Pattern, opts.TypeFilter)
if opts.SortBy != "" {
sortSkillEntries(skills, opts.SortBy)
}
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
// Always sort so the TUI and plain-text renderers see contiguous
// top-level groups (tracked → named locals → standalone).
sortSkillEntries(allEntries, opts.SortBy)
// JSON output
if opts.JSON {
return displaySkillsJSON(skills)
return displaySkillsJSON(allEntries)
}
// Handle empty results before starting pager
if len(skills) == 0 && len(trackedRepos) == 0 && !hasFilter {
ui.Info("No skills installed")
ui.Info("Use 'skillshare install <source>' to install a skill")
// Handle empty results
if len(allEntries) == 0 && len(trackedRepos) == 0 && !hasFilter {
ui.Info("No %s installed", resourceLabel)
if kind.IncludesSkills() {
ui.Info("Use 'skillshare install <source>' to install a skill")
}
return nil
}
if hasFilter && len(skills) == 0 {
if hasFilter && len(allEntries) == 0 {
if opts.Pattern != "" && opts.TypeFilter != "" {
ui.Info("No skills matching %q (type: %s)", opts.Pattern, opts.TypeFilter)
ui.Info("No %s matching %q (type: %s)", resourceLabel, opts.Pattern, opts.TypeFilter)
} else if opts.Pattern != "" {
ui.Info("No skills matching %q", opts.Pattern)
ui.Info("No %s matching %q", resourceLabel, opts.Pattern)
} else {
ui.Info("No skills matching type %q", opts.TypeFilter)
ui.Info("No %s matching type %q", resourceLabel, opts.TypeFilter)
}
return nil
}
// Plain text output (--no-tui or non-TTY)
if len(skills) > 0 {
ui.Header("Installed skills")
if len(allEntries) > 0 {
headerLabel := "Installed skills"
if kind == kindAgents {
headerLabel = "Installed agents"
} else if kind == kindAll {
headerLabel = "Installed skills & agents"
}
ui.Header(headerLabel)
if opts.Verbose {
displaySkillsVerbose(skills)
displaySkillsVerbose(allEntries)
} else {
displaySkillsCompact(skills)
displaySkillsCompact(allEntries)
}
}
// Hide tracked repos section when filter/pattern is active
if len(trackedRepos) > 0 && !hasFilter {
displayTrackedRepos(trackedRepos, discovered, cfg.Source)
displayTrackedRepos(trackedRepos, discoveredSkills, cfg.Source)
}
// Show match stats when filter is active
if hasFilter && len(skills) > 0 {
if hasFilter && len(allEntries) > 0 {
fmt.Println()
if opts.Pattern != "" {
ui.Info("%d of %d skill(s) matching %q", len(skills), totalCount, opts.Pattern)
ui.Info("%d of %d %s matching %q", len(allEntries), totalCount, resourceLabel, opts.Pattern)
} else {
ui.Info("%d of %d skill(s)", len(skills), totalCount)
ui.Info("%d of %d %s", len(allEntries), totalCount, resourceLabel)
}
} else if !opts.Verbose && len(skills) > 0 {
} else if !opts.Verbose && len(allEntries) > 0 {
fmt.Println()
ui.Info("Use --verbose for more details")
}
@@ -650,6 +760,7 @@ func cmdList(args []string) error {
type skillEntry struct {
Name string
Kind string // "skill" or "agent"
Source string
Type string
InstalledAt string
@@ -663,6 +774,7 @@ type skillEntry struct {
// skillJSON is the JSON representation for --json output.
type skillJSON struct {
Name string `json:"name"`
Kind string `json:"kind,omitempty"` // "skill" or "agent"
RelPath string `json:"relPath"`
Source string `json:"source,omitempty"`
Type string `json:"type,omitempty"`
@@ -676,6 +788,7 @@ func displaySkillsJSON(skills []skillEntry) error {
for i, s := range skills {
items[i] = skillJSON{
Name: s.Name,
Kind: s.Kind,
RelPath: s.RelPath,
Source: s.Source,
Type: s.Type,
@@ -703,12 +816,13 @@ func abbreviateSource(source string) string {
}
func printListHelp() {
fmt.Println(`Usage: skillshare list [pattern] [options]
fmt.Println(`Usage: skillshare list [agents] [pattern] [options]
List all installed skills in the source directory.
An optional pattern filters skills by name, path, or source (case-insensitive).
Options:
--all List both skills and agents
--verbose, -v Show detailed information (source, type, install date)
--json, -j Output as JSON (useful for CI/scripts)
--no-tui Disable interactive TUI, use plain text output
@@ -724,5 +838,7 @@ Examples:
skillshare list --type local
skillshare list react --type github --sort newest
skillshare list --json | jq '.[].name'
skillshare list --verbose`)
skillshare list --verbose
skillshare list agents # List agents only
skillshare list --all # List skills + agents`)
}
+93 -49
View File
@@ -3,20 +3,30 @@ package main
import (
"fmt"
"path/filepath"
"time"
"skillshare/internal/config"
"skillshare/internal/sync"
"skillshare/internal/trash"
"skillshare/internal/ui"
)
func cmdListProject(root string, opts listOptions) error {
func cmdListProject(root string, opts listOptions, kind resourceKindFilter) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
}
sourcePath := filepath.Join(root, ".skillshare", "skills")
skillsSource := filepath.Join(root, ".skillshare", "skills")
agentsSource := filepath.Join(root, ".skillshare", "agents")
resourceLabel := "skills"
if kind == kindAgents {
resourceLabel = "agents"
} else if kind == kindAll {
resourceLabel = "resources"
}
// TTY + not JSON + TUI enabled → launch TUI with async loading (no blank screen)
if !opts.JSON && shouldLaunchTUI(opts.NoTUI, nil) {
@@ -30,31 +40,47 @@ func cmdListProject(root string, opts listOptions) error {
sortBy = "name"
}
loadFn := func() listLoadResult {
discovered, err := sync.DiscoverSourceSkillsAll(sourcePath)
// Always load both skills and agents — tab UI filters the view.
var allEntries []skillEntry
discovered, err := sync.DiscoverSourceSkillsAll(skillsSource)
if err != nil {
return listLoadResult{err: fmt.Errorf("cannot discover project skills: %w", err)}
}
skills := buildSkillEntries(discovered)
total := len(skills)
skills = filterSkillEntries(skills, opts.Pattern, opts.TypeFilter)
sortSkillEntries(skills, sortBy)
return listLoadResult{skills: toSkillItems(skills), totalCount: total}
allEntries = append(allEntries, buildSkillEntries(discovered)...)
allEntries = append(allEntries, discoverAndBuildAgentEntries(agentsSource)...)
total := len(allEntries)
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
sortSkillEntries(allEntries, sortBy)
return listLoadResult{skills: toSkillItems(allEntries), totalCount: total}
}
action, skillName, err := runListTUI(loadFn, "project", sourcePath, targets)
action, skillName, skillKind, err := runListTUI(loadFn, "project", skillsSource, agentsSource, targets, kind)
if err != nil {
return err
}
switch action {
case "empty":
ui.Info("No skills installed")
ui.Info("Use 'skillshare install -p <source>' to install a skill")
ui.Info("No %s installed", resourceLabel)
if kind.IncludesSkills() {
ui.Info("Use 'skillshare install -p <source>' to install a skill")
}
return nil
case "audit":
if skillKind == "agent" {
return cmdAudit([]string{"agents", "-p", skillName})
}
return cmdAudit([]string{"-p", skillName})
case "update":
if skillKind == "agent" {
return cmdUpdateAgentsProject([]string{skillName}, root, time.Now())
}
_, updateErr := cmdUpdateProject([]string{skillName}, root)
return updateErr
case "uninstall":
if skillKind == "agent" {
agentsDir := filepath.Join(root, ".skillshare", "agents")
uOpts := &uninstallOptions{skillNames: []string{skillName}, force: true}
return cmdUninstallAgents(agentsDir, uOpts, config.ProjectConfigPath(root), trash.ProjectAgentTrashDir(root), time.Now())
}
return cmdUninstallProject([]string{"--force", skillName}, root)
}
return nil
@@ -63,96 +89,114 @@ func cmdListProject(root string, opts listOptions) error {
// Non-TUI path (JSON or plain text): synchronous loading with spinner
var sp *ui.Spinner
if !opts.JSON && ui.IsTTY() {
sp = ui.StartSpinner("Loading skills...")
sp = ui.StartSpinner(fmt.Sprintf("Loading %s...", resourceLabel))
}
// Use DiscoverSourceSkillsAll so disabled skills appear in the listing
discovered, err := sync.DiscoverSourceSkillsAll(sourcePath)
if err != nil {
if sp != nil {
sp.Fail("Discovery failed")
var allEntries []skillEntry
var trackedRepos []string
var discoveredSkills []sync.DiscoveredSkill
if kind.IncludesSkills() {
var discErr error
discoveredSkills, discErr = sync.DiscoverSourceSkillsAll(skillsSource)
if discErr != nil {
if sp != nil {
sp.Fail("Discovery failed")
}
return fmt.Errorf("cannot discover project skills: %w", discErr)
}
return fmt.Errorf("cannot discover project skills: %w", err)
trackedRepos = extractTrackedRepos(discoveredSkills)
if sp != nil {
sp.Update(fmt.Sprintf("Reading metadata for %d skills...", len(discoveredSkills)))
}
allEntries = append(allEntries, buildSkillEntries(discoveredSkills)...)
}
if kind.IncludesAgents() {
allEntries = append(allEntries, discoverAndBuildAgentEntries(agentsSource)...)
}
trackedRepos := extractTrackedRepos(discovered)
if sp != nil {
sp.Update(fmt.Sprintf("Reading metadata for %d skills...", len(discovered)))
sp.Success(fmt.Sprintf("Loaded %d %s", len(allEntries), resourceLabel))
}
skills := buildSkillEntries(discovered)
if sp != nil {
sp.Success(fmt.Sprintf("Loaded %d skills", len(skills)))
}
totalCount := len(skills)
totalCount := len(allEntries)
hasFilter := opts.Pattern != "" || opts.TypeFilter != ""
// Apply filter and sort
skills = filterSkillEntries(skills, opts.Pattern, opts.TypeFilter)
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
sortBy := opts.SortBy
if sortBy == "" {
sortBy = "name" // project mode default
}
sortSkillEntries(skills, sortBy)
sortSkillEntries(allEntries, sortBy)
// JSON output
if opts.JSON {
return displaySkillsJSON(skills)
return displaySkillsJSON(allEntries)
}
// Handle empty results before starting pager
if len(skills) == 0 && len(trackedRepos) == 0 && !hasFilter {
ui.Info("No skills installed")
ui.Info("Use 'skillshare install -p <source>' to install a skill")
// Handle empty results
if len(allEntries) == 0 && len(trackedRepos) == 0 && !hasFilter {
ui.Info("No %s installed", resourceLabel)
if kind.IncludesSkills() {
ui.Info("Use 'skillshare install -p <source>' to install a skill")
}
return nil
}
if hasFilter && len(skills) == 0 {
if hasFilter && len(allEntries) == 0 {
if opts.Pattern != "" && opts.TypeFilter != "" {
ui.Info("No skills matching %q (type: %s)", opts.Pattern, opts.TypeFilter)
ui.Info("No %s matching %q (type: %s)", resourceLabel, opts.Pattern, opts.TypeFilter)
} else if opts.Pattern != "" {
ui.Info("No skills matching %q", opts.Pattern)
ui.Info("No %s matching %q", resourceLabel, opts.Pattern)
} else {
ui.Info("No skills matching type %q", opts.TypeFilter)
ui.Info("No %s matching type %q", resourceLabel, opts.TypeFilter)
}
return nil
}
// Plain text output (--no-tui or non-TTY)
if len(skills) > 0 {
ui.Header("Installed skills (project)")
if len(allEntries) > 0 {
headerLabel := "Installed skills (project)"
if kind == kindAgents {
headerLabel = "Installed agents (project)"
} else if kind == kindAll {
headerLabel = "Installed skills & agents (project)"
}
ui.Header(headerLabel)
if opts.Verbose {
displaySkillsVerbose(skills)
displaySkillsVerbose(allEntries)
} else {
displaySkillsCompact(skills)
displaySkillsCompact(allEntries)
}
}
// Hide tracked repos section when filter/pattern is active
if len(trackedRepos) > 0 && !hasFilter {
displayTrackedRepos(trackedRepos, discovered, sourcePath)
displayTrackedRepos(trackedRepos, discoveredSkills, skillsSource)
}
// Show match stats when filter is active
if hasFilter && len(skills) > 0 {
if hasFilter && len(allEntries) > 0 {
fmt.Println()
if opts.Pattern != "" {
ui.Info("%d of %d skill(s) matching %q", len(skills), totalCount, opts.Pattern)
ui.Info("%d of %d %s matching %q", len(allEntries), totalCount, resourceLabel, opts.Pattern)
} else {
ui.Info("%d of %d skill(s)", len(skills), totalCount)
ui.Info("%d of %d %s", len(allEntries), totalCount, resourceLabel)
}
} else {
fmt.Println()
trackedCount := 0
remoteCount := 0
for _, skill := range skills {
if skill.RepoName != "" {
for _, entry := range allEntries {
if entry.RepoName != "" {
trackedCount++
} else if skill.Source != "" {
} else if entry.Source != "" {
remoteCount++
}
}
localCount := len(skills) - trackedCount - remoteCount
ui.Info("%d skill(s): %d tracked, %d remote, %d local", len(skills), trackedCount, remoteCount, localCount)
localCount := len(allEntries) - trackedCount - remoteCount
ui.Info("%d %s: %d tracked, %d remote, %d local", len(allEntries), resourceLabel, trackedCount, remoteCount, localCount)
}
return nil
+279 -96
View File
@@ -9,6 +9,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/skillignore"
"skillshare/internal/theme"
"skillshare/internal/utils"
"github.com/charmbracelet/bubbles/list"
@@ -23,11 +24,20 @@ import (
// Keeps the widget fast — pagination + filter operate on at most this many items.
const maxListItems = 1000
// listTab represents the active tab filter in the list TUI.
type listTab int
const (
listTabAll listTab = iota // show all items (skills + agents)
listTabSkills // show skills only
listTabAgents // show agents only
)
// applyTUIFilterStyle sets filter prompt, cursor, and input cursor to the shared style.
func applyTUIFilterStyle(l *list.Model) {
l.Styles.FilterPrompt = tc.Filter
l.Styles.FilterCursor = tc.Filter
l.FilterInput.Cursor.Style = tc.Filter
l.Styles.FilterPrompt = theme.Accent()
l.Styles.FilterCursor = theme.Accent()
l.FilterInput.Cursor.Style = theme.Accent()
}
// listLoadResult holds the result of async skill loading inside the TUI.
@@ -60,15 +70,16 @@ type detailData struct {
// listTUIModel is the bubbletea model for the interactive skill list.
type listTUIModel struct {
list list.Model
totalCount int
modeLabel string // "global" or "project"
sourcePath string
targets map[string]config.TargetConfig
quitting bool
action string // "audit", "update", "uninstall", or "" (normal quit)
termWidth int
detailCache map[string]*detailData // key = RelPath; lazy-populated
list list.Model
totalCount int
modeLabel string // "global" or "project"
sourcePath string
agentsSourcePath string
targets map[string]config.TargetConfig
quitting bool
action string // "audit", "update", "uninstall", or "" (normal quit)
termWidth int
detailCache map[string]*detailData // key = RelPath; lazy-populated
// Async loading — spinner shown until data arrives
loading bool
@@ -77,6 +88,12 @@ type listTUIModel struct {
loadErr error // non-nil if loading failed
emptyResult bool // true when async load returned zero skills
// Tab filter — pre-filters allItems by kind (All / Skills / Agents)
activeTab listTab // currently selected tab
activeTabP *listTab // shared pointer for delegate to read current tab
tabCounts [3]int // cached counts: [all, skills, agents]
tabFiltered []skillItem // cached result of tabFilteredItems(); set by applyFilter()
// Application-level filter — replaces bubbles/list built-in fuzzy filter
// to avoid O(N*M) fuzzy scan on 100k+ items every keystroke.
allItems []skillItem // full item set (kept in memory, never passed to list)
@@ -90,12 +107,14 @@ type listTUIModel struct {
confirming bool // true when confirmation overlay is shown
confirmAction string // "audit", "update", "uninstall"
confirmSkill string // skill name for confirmation display
confirmKind string // "skill" or "agent"
// Content viewer overlay — dual-pane: left tree + right content
showContent bool
contentScroll int
contentText string // current file content (rendered)
contentSkillKey string // RelPath of skill being viewed
contentKind string // "skill" or "agent" — set when entering content view
termHeight int
treeAllNodes []treeNode // complete flat tree (includes collapsed children)
treeNodes []treeNode // visible nodes (collapsed children hidden)
@@ -106,8 +125,22 @@ type listTUIModel struct {
// newListTUIModel creates a new TUI model.
// When loadFn is non-nil, skills are loaded asynchronously inside the TUI (spinner shown).
// When loadFn is nil, skills/totalCount are used directly (pre-loaded).
func newListTUIModel(loadFn listLoadFn, skills []skillItem, totalCount int, modeLabel, sourcePath string, targets map[string]config.TargetConfig) listTUIModel {
delegate := listSkillDelegate{}
func newListTUIModel(loadFn listLoadFn, skills []skillItem, totalCount int, modeLabel, sourcePath, agentsSourcePath string, targets map[string]config.TargetConfig, initialKind resourceKindFilter) listTUIModel {
// Map CLI kind filter to initial tab
var initTab listTab
switch initialKind {
case kindAgents:
initTab = listTabAgents
case kindSkills:
initTab = listTabSkills
default:
initTab = listTabAll
}
// Shared pointer lets the delegate read the current tab without re-creation.
tabPtr := new(listTab)
*tabPtr = initTab
delegate := listSkillDelegate{activeTab: tabPtr}
// Build initial item set (empty if async loading)
var items []list.Item
@@ -120,45 +153,111 @@ func newListTUIModel(loadFn listLoadFn, skills []skillItem, totalCount int, mode
// Create list model — built-in filter DISABLED; we manage our own.
l := list.New(items, delegate, 0, 0)
l.Title = fmt.Sprintf("Installed skills (%s)", modeLabel)
l.Styles.Title = tc.ListTitle
l.SetShowStatusBar(false) // we render our own status with real total count
l.SetFilteringEnabled(false) // application-level filter replaces built-in
l.SetShowHelp(false) // we render our own help
l.SetShowPagination(false) // we render page info in our status line
l.Styles.Title = theme.Title()
l.Styles.NoItems = l.Styles.NoItems.PaddingLeft(2) // align with title
l.SetShowStatusBar(false) // we render our own status with real total count
l.SetFilteringEnabled(false) // application-level filter replaces built-in
l.SetShowHelp(false) // we render our own help
l.SetShowPagination(false) // we render page info in our status line
// Loading spinner
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
// Filter text input
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.Placeholder = "filter or t:tracked g:group r:repo"
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
fi.Placeholder = "filter or t:tracked g:group r:repo k:kind"
m := listTUIModel{
list: l,
totalCount: totalCount,
modeLabel: modeLabel,
sourcePath: sourcePath,
targets: targets,
detailCache: make(map[string]*detailData),
loading: loadFn != nil,
loadSpinner: sp,
loadFn: loadFn,
allItems: allItems,
matchCount: len(allItems),
filterInput: fi,
list: l,
totalCount: totalCount,
modeLabel: modeLabel,
sourcePath: sourcePath,
agentsSourcePath: agentsSourcePath,
targets: targets,
activeTab: initTab,
activeTabP: tabPtr,
detailCache: make(map[string]*detailData),
loading: loadFn != nil,
loadSpinner: sp,
loadFn: loadFn,
allItems: allItems,
matchCount: len(allItems),
filterInput: fi,
}
// Skip initial group header (index 0)
if loadFn == nil {
m.recomputeTabCounts()
m.applyFilter() // applies tab + text filter
skipGroupItem(&m.list, 1)
}
m.updateTitle()
return m
}
// recomputeTabCounts updates the cached per-tab counts from allItems.
func (m *listTUIModel) recomputeTabCounts() {
var skills, agents int
for _, item := range m.allItems {
if item.entry.Kind == "agent" {
agents++
} else {
skills++
}
}
m.tabCounts = [3]int{len(m.allItems), skills, agents}
}
// tabFilteredItems returns the subset of allItems matching the active tab.
// For listTabAll, items are reordered so skills come first then agents,
// keeping each kind's original order intact.
func (m *listTUIModel) tabFilteredItems() []skillItem {
if m.activeTab == listTabAll {
skills := make([]skillItem, 0, m.tabCounts[1])
agents := make([]skillItem, 0, m.tabCounts[2])
for _, item := range m.allItems {
if item.entry.Kind == "agent" {
agents = append(agents, item)
} else {
skills = append(skills, item)
}
}
return append(skills, agents...)
}
wantAgent := m.activeTab == listTabAgents
cap := m.tabCounts[1]
if wantAgent {
cap = m.tabCounts[2]
}
filtered := make([]skillItem, 0, cap)
for _, item := range m.allItems {
if (item.entry.Kind == "agent") == wantAgent {
filtered = append(filtered, item)
}
}
return filtered
}
// tabNoun returns the display noun for the active tab.
func (t listTab) noun() string {
switch t {
case listTabSkills:
return "skills"
case listTabAgents:
return "agents"
default:
return "resources"
}
}
// updateTitle sets the list title based on the active tab and mode.
func (m *listTUIModel) updateTitle() {
m.list.Title = fmt.Sprintf("Installed %s (%s)", m.activeTab.noun(), m.modeLabel)
}
func (m listTUIModel) Init() tea.Cmd {
if m.loading && m.loadFn != nil {
return tea.Batch(m.loadSpinner.Tick, doLoadCmd(m.loadFn))
@@ -172,11 +271,12 @@ func (m listTUIModel) Init() tea.Cmd {
// When filter is empty, all items are restored (full pagination).
func (m *listTUIModel) applyFilter() {
m.detailScroll = 0
m.tabFiltered = m.tabFilteredItems()
// No filter — restore full item set with group separators
// No filter — restore tab-filtered item set with group separators
if m.filterText == "" {
m.matchCount = len(m.allItems)
m.list.SetItems(buildGroupedItems(m.allItems))
m.matchCount = len(m.tabFiltered)
m.list.SetItems(buildGroupedItems(m.tabFiltered))
m.list.ResetSelected()
return
}
@@ -186,7 +286,7 @@ func (m *listTUIModel) applyFilter() {
// Structured match, capped at maxListItems
var matched []list.Item
count := 0
for _, item := range m.allItems {
for _, item := range m.tabFiltered {
if matchSkillItem(item, q) {
count++
if len(matched) < maxListItems {
@@ -229,10 +329,10 @@ func (m listTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
m.allItems = msg.result.skills
m.totalCount = msg.result.totalCount
m.matchCount = len(msg.result.skills)
// Populate list with group separators
m.list.SetItems(buildGroupedItems(msg.result.skills))
m.recomputeTabCounts()
m.applyFilter() // applies tab + text filter, sets matchCount
skipGroupItem(&m.list, 1)
m.updateTitle()
return m, nil
case tea.MouseMsg:
@@ -279,6 +379,7 @@ func (m listTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.confirming = false
m.confirmAction = ""
m.confirmSkill = ""
m.confirmKind = ""
return m, nil
}
return m, nil
@@ -313,6 +414,20 @@ func (m listTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "q", "ctrl+c":
m.quitting = true
return m, tea.Quit
case "tab":
m.activeTab = (m.activeTab + 1) % 3
*m.activeTabP = m.activeTab
m.applyFilter()
m.updateTitle()
skipGroupItem(&m.list, 1)
return m, nil
case "shift+tab":
m.activeTab = (m.activeTab - 1 + 3) % 3
*m.activeTabP = m.activeTab
m.applyFilter()
m.updateTitle()
skipGroupItem(&m.list, 1)
return m, nil
case "ctrl+d":
m.detailScroll += 8
return m, nil
@@ -376,6 +491,7 @@ func (m listTUIModel) enterConfirm(action string) (tea.Model, tea.Cmd) {
m.confirming = true
m.confirmAction = action
m.confirmSkill = name
m.confirmKind = item.entry.Kind
return m, nil
}
@@ -387,7 +503,12 @@ func (m listTUIModel) toggleDisabled() (tea.Model, tea.Cmd) {
return m, nil
}
ignorePath := filepath.Join(m.sourcePath, ".skillignore")
var ignorePath string
if item.entry.Kind == "agent" {
ignorePath = filepath.Join(m.agentsSourcePath, ".agentignore")
} else {
ignorePath = filepath.Join(m.sourcePath, ".skillignore")
}
pattern := item.entry.RelPath
if pattern == "" {
pattern = item.entry.Name
@@ -444,7 +565,7 @@ func (m listTUIModel) View() string {
// Loading state — spinner + message
if m.loading {
return fmt.Sprintf("\n %s Loading skills...\n", m.loadSpinner.View())
return fmt.Sprintf("\n %s Loading %s...\n", m.loadSpinner.View(), m.activeTab.noun())
}
// Content viewer — dual-pane
@@ -458,10 +579,14 @@ func (m listTUIModel) View() string {
if m.modeLabel == "project" {
flag = "-p"
}
cmd := fmt.Sprintf("skillshare %s %s %s", m.confirmAction, flag, m.confirmSkill)
kindArg := ""
if m.confirmKind == "agent" {
kindArg = "agents "
}
cmd := fmt.Sprintf("skillshare %s %s%s %s", m.confirmAction, kindArg, flag, m.confirmSkill)
if m.confirmAction == "uninstall" {
return fmt.Sprintf("\n %s\n\n → %s\n\n Proceed? [Y/n] ",
tc.Red.Render("Uninstall "+m.confirmSkill+"?"), cmd)
theme.Danger().Render("Uninstall "+m.confirmSkill+"?"), cmd)
}
return fmt.Sprintf("\n → %s\n\n Proceed? [Y/n] ", cmd)
}
@@ -472,18 +597,47 @@ func (m listTUIModel) View() string {
return m.viewVertical()
}
// renderTabBar renders the kind tab bar (All / Skills / Agents).
func (m listTUIModel) renderTabBar() string {
type tab struct {
label string
tab listTab
count int
}
tabs := []tab{
{"All", listTabAll, m.tabCounts[0]},
{"Skills", listTabSkills, m.tabCounts[1]},
{"Agents", listTabAgents, m.tabCounts[2]},
}
activeStyle := lipgloss.NewStyle().Bold(true).Underline(true)
inactiveStyle := theme.Dim()
var parts []string
for _, t := range tabs {
label := fmt.Sprintf("%s(%d)", t.label, t.count)
if t.tab == m.activeTab {
parts = append(parts, activeStyle.Inherit(theme.Accent()).Render(label))
} else {
parts = append(parts, inactiveStyle.Render(label))
}
}
return " " + strings.Join(parts, " ")
}
// renderFilterBar renders the status line for the list TUI.
func (m listTUIModel) renderFilterBar() string {
return renderTUIFilterBar(
m.filterInput.View(), m.filtering, m.filterText,
m.matchCount, len(m.allItems), maxListItems,
"skills", m.renderPageInfo(),
m.matchCount, len(m.tabFiltered), maxListItems,
m.activeTab.noun(), m.renderPageInfo(),
)
}
func (m *listTUIModel) syncListSize() {
if listSplitActive(m.termWidth) {
panelHeight := m.termHeight - 5
// tab(1) + gap(1) + panel + gap(1) + filter(1) + summary(1) + gap(1) + help(1) + trail(1) = 8 overhead
panelHeight := m.termHeight - 8
if panelHeight < 6 {
panelHeight = 6
}
@@ -491,7 +645,7 @@ func (m *listTUIModel) syncListSize() {
return
}
listHeight := m.termHeight - 20
listHeight := m.termHeight - 22
if listHeight < 6 {
listHeight = 6
}
@@ -535,7 +689,10 @@ func selectedSkillKey(item list.Item) string {
func (m listTUIModel) viewSplit() string {
var b strings.Builder
panelHeight := m.termHeight - 5
b.WriteString(m.renderTabBar())
b.WriteString("\n\n")
panelHeight := m.termHeight - 8
if panelHeight < 6 {
panelHeight = 6
}
@@ -564,12 +721,12 @@ func (m listTUIModel) viewSplit() string {
b.WriteString(m.renderFilterBar())
b.WriteString(m.renderSummaryFooter())
b.WriteString("\n")
helpText := "↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable X uninstall q quit"
helpText := "Tab skills/agents ↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable X uninstall q quit"
if m.filtering {
helpText = "t:type g:group r:repo Enter lock Esc clear q quit"
helpText = "t:type g:group r:repo k:kind Enter lock Esc clear q quit"
}
help := appendScrollInfo(helpText, scrollInfo)
b.WriteString(tc.Help.Render(help))
b.WriteString(formatHelpBar(help))
b.WriteString("\n")
return b.String()
@@ -578,13 +735,15 @@ func (m listTUIModel) viewSplit() string {
func (m listTUIModel) viewVertical() string {
var b strings.Builder
b.WriteString(m.renderTabBar())
b.WriteString("\n\n")
b.WriteString(m.list.View())
b.WriteString("\n\n")
b.WriteString(m.renderFilterBar())
var scrollInfo string
if item, ok := m.list.SelectedItem().(skillItem); ok {
detailHeight := m.termHeight - m.termHeight*2/5 - 8
detailHeight := m.termHeight - m.termHeight*2/5 - 10 // -2 for tab bar
if detailHeight < 6 {
detailHeight = 6
}
@@ -603,12 +762,12 @@ func (m listTUIModel) viewVertical() string {
b.WriteString(m.renderSummaryFooter())
b.WriteString("\n")
helpText := "↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable X uninstall q quit"
helpText := "Tab skills/agents ↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable X uninstall q quit"
if m.filtering {
helpText = "t:type g:group r:repo Enter lock Esc clear q quit"
helpText = "t:type g:group r:repo k:kind Enter lock Esc clear q quit"
}
help := appendScrollInfo(helpText, scrollInfo)
b.WriteString(tc.Help.Render(help))
b.WriteString(formatHelpBar(help))
b.WriteString("\n")
return b.String()
@@ -618,7 +777,7 @@ func (m listTUIModel) renderSummaryFooter() string {
localCount := 0
trackedCount := 0
remoteCount := 0
for _, item := range m.allItems {
for _, item := range m.tabFiltered {
switch {
case item.entry.RepoName != "":
trackedCount++
@@ -630,12 +789,12 @@ func (m listTUIModel) renderSummaryFooter() string {
}
parts := []string{
tc.Emphasis.Render(formatNumber(m.matchCount)) + tc.Dim.Render("/") + tc.Dim.Render(formatNumber(len(m.allItems))) + tc.Dim.Render(" visible"),
tc.Cyan.Render(formatNumber(localCount)) + tc.Dim.Render(" local"),
tc.Green.Render(formatNumber(trackedCount)) + tc.Dim.Render(" tracked"),
tc.Yellow.Render(formatNumber(remoteCount)) + tc.Dim.Render(" remote"),
theme.Primary().Render(formatNumber(m.matchCount)) + theme.Dim().Render("/") + theme.Dim().Render(formatNumber(len(m.tabFiltered))) + theme.Dim().Render(" visible"),
theme.Accent().Render(formatNumber(localCount)) + theme.Dim().Render(" local"),
theme.Success().Render(formatNumber(trackedCount)) + theme.Dim().Render(" tracked"),
theme.Warning().Render(formatNumber(remoteCount)) + theme.Dim().Render(" remote"),
}
return tc.Help.Render(strings.Join(parts, tc.Dim.Render(" | "))) + "\n"
return theme.Dim().MarginLeft(2).Render(strings.Join(parts, theme.Dim().Render(" | "))) + "\n"
}
// renderTUIFilterBar renders a unified filter + status line shared by all TUIs.
@@ -644,14 +803,14 @@ func renderTUIFilterBar(inputView string, filtering bool, filterText string, mat
if filtering {
if filterText == "" {
status := fmt.Sprintf(" %s %s%s", formatNumber(totalCount), noun, pageInfo)
return " " + inputView + tc.Help.Render(status) + "\n"
return " " + inputView + theme.Dim().MarginLeft(2).Render(status) + "\n"
}
status := fmt.Sprintf(" %s/%s %s", formatNumber(matchCount), formatNumber(totalCount), noun)
if maxShown > 0 && matchCount > maxShown {
status += fmt.Sprintf(" (first %s shown)", formatNumber(maxShown))
}
status += pageInfo
return " " + inputView + tc.Help.Render(status) + "\n"
return " " + inputView + theme.Dim().MarginLeft(2).Render(status) + "\n"
}
if filterText != "" {
status := fmt.Sprintf("filter: %s — %s/%s %s", filterText, formatNumber(matchCount), formatNumber(totalCount), noun)
@@ -659,9 +818,9 @@ func renderTUIFilterBar(inputView string, filtering bool, filterText string, mat
status += fmt.Sprintf(" (first %s shown)", formatNumber(maxShown))
}
status += pageInfo
return tc.Help.Render(status) + "\n"
return theme.Dim().MarginLeft(2).Render(status) + "\n"
}
return tc.Help.Render(fmt.Sprintf("%s %s%s", formatNumber(totalCount), noun, pageInfo)) + "\n"
return theme.Dim().MarginLeft(2).Render(fmt.Sprintf("%s %s%s", formatNumber(totalCount), noun, pageInfo)) + "\n"
}
// renderPageInfo returns page indicator like " · Page 2 of 4,729" or "" if single page.
@@ -701,13 +860,27 @@ func formatNumber(n int) string {
return b.String()
}
// getDetailData returns cached detail data for a skill, populating the cache on first access.
// getDetailData returns cached detail data for a skill or agent, populating the cache on first access.
func (m listTUIModel) getDetailData(e skillEntry) *detailData {
key := e.RelPath
if d, ok := m.detailCache[key]; ok {
return d
}
if e.Kind == "agent" {
// Agents are single .md files — read frontmatter from the file directly
agentFile := filepath.Join(m.agentsSourcePath, e.RelPath)
fm := utils.ParseFrontmatterFields(agentFile, []string{"description", "license"})
d := &detailData{
Description: fm["description"],
License: fm["license"],
Files: []string{filepath.Base(e.RelPath)},
SyncedTargets: m.findSyncedTargets(e),
}
m.detailCache[key] = d
return d
}
skillDir := filepath.Join(m.sourcePath, e.RelPath)
skillMD := filepath.Join(skillDir, "SKILL.md")
@@ -738,7 +911,7 @@ func renderDetailGroup(title string, rows []string, _ int) string {
}
var b strings.Builder
b.WriteString(tc.Title.Render(title))
b.WriteString(theme.Title().Render(title))
b.WriteString("\n")
for _, r := range filtered {
b.WriteString(" ")
@@ -756,7 +929,7 @@ func renderDetailCard(title string, body string, width int) string {
if title == "" {
return style.Render(body)
}
return style.Render(tc.Title.Render(title) + "\n" + body)
return style.Render(theme.Title().Render(title) + "\n" + body)
}
func renderDetailSection(title string, body string, width int) string {
@@ -764,7 +937,7 @@ func renderDetailSection(title string, body string, width int) string {
Width(width).
Align(lipgloss.Left).
Padding(0, 0)
return style.Render(tc.Title.Render(title) + "\n" + body)
return style.Render(theme.Title().Render(title) + "\n" + body)
}
// renderDetailBody renders the scrollable detail body for the selected skill.
@@ -795,22 +968,22 @@ func (m listTUIModel) renderDetailBody(e skillEntry, d *detailData, width int) s
// Source section (Installed date and Synced-to targets are in the header)
var sourceRows []string
if e.Source != "" {
sourceRows = append(sourceRows, renderFactRow("Source", tc.Cyan.Render(e.Source)))
sourceRows = append(sourceRows, renderFactRow("Source", theme.Accent().Render(e.Source)))
} else if e.RepoName != "" {
sourceRows = append(sourceRows, renderFactRow("Repo", e.RepoName))
}
if e.Branch != "" {
sourceRows = append(sourceRows, renderFactRow("Branch", tc.Cyan.Render(e.Branch)))
sourceRows = append(sourceRows, renderFactRow("Branch", theme.Accent().Render(e.Branch)))
}
if d.License != "" {
sourceRows = append(sourceRows, renderFactRow("License", tc.Green.Bold(true).Render(d.License)))
sourceRows = append(sourceRows, renderFactRow("License", theme.Success().Bold(true).Render(d.License)))
}
if len(d.Files) > 0 {
fileLabel := fmt.Sprintf("Files (%d)", len(d.Files))
sourceRows = append(sourceRows, renderFactRow(fileLabel, tc.Cyan.Render(strings.Join(d.Files, " · "))))
sourceRows = append(sourceRows, renderFactRow(fileLabel, theme.Accent().Render(strings.Join(d.Files, " · "))))
}
if len(d.SyncedTargets) > 0 {
sourceRows = append(sourceRows, renderFactRow("Synced to", tc.Cyan.Render(strings.Join(d.SyncedTargets, ", "))))
sourceRows = append(sourceRows, renderFactRow("Synced to", theme.Accent().Render(strings.Join(d.SyncedTargets, ", "))))
}
if len(sourceRows) > 0 {
b.WriteString(renderDetailSection("Details", strings.Join(sourceRows, "\n"), cardWidth))
@@ -831,13 +1004,13 @@ func renderDetailHeader(e skillEntry, d *detailData, width int) string {
var metaParts []string
metaParts = append(metaParts, detailStatusBits(e))
if e.InstalledAt != "" {
metaParts = append(metaParts, tc.Dim.Render(e.InstalledAt))
metaParts = append(metaParts, theme.Dim().Render(e.InstalledAt))
}
if len(d.SyncedTargets) > 0 {
metaParts = append(metaParts, tc.Cyan.Render(fmt.Sprintf("%d target(s)", len(d.SyncedTargets))))
metaParts = append(metaParts, theme.Accent().Render(fmt.Sprintf("%d target(s)", len(d.SyncedTargets))))
}
body.WriteString("\n\n")
body.WriteString(strings.Join(metaParts, tc.Dim.Render(" · ")))
body.WriteString(strings.Join(metaParts, theme.Dim().Render(" · ")))
return renderDetailCard("", body.String(), width)
}
@@ -845,30 +1018,38 @@ func renderDetailHeader(e skillEntry, d *detailData, width int) string {
func renderDetailParagraph(lines []string) []string {
rendered := make([]string, 0, len(lines))
for _, line := range lines {
rendered = append(rendered, tc.Value.Render(line))
rendered = append(rendered, lipgloss.NewStyle().Render(line))
}
return rendered
}
func detailStatusBits(e skillEntry) string {
var bits []string
// Kind label (Agent / Skill)
if e.Kind == "agent" {
bits = append(bits, theme.Accent().Render("Agent"))
} else {
bits = append(bits, theme.Accent().Render("Skill"))
}
switch {
case e.RepoName != "":
bits = append(bits, tc.Green.Render("tracked"))
bits = append(bits, theme.Success().Render("tracked"))
case e.Source != "":
bits = append(bits, tc.Yellow.Render("remote"))
bits = append(bits, theme.Warning().Render("remote"))
default:
bits = append(bits, tc.Dim.Render("local"))
bits = append(bits, theme.Dim().Render("local"))
}
if e.Disabled {
bits = append(bits, tc.Red.Render("disabled"))
bits = append(bits, theme.Danger().Render("disabled"))
}
return strings.Join(bits, " ")
}
func renderFactRow(label, value string) string {
labelStyle := lipgloss.NewStyle().Faint(true).Width(12)
return labelStyle.Render(label+":") + " " + tc.Value.Render(value)
return labelStyle.Render(label+":") + " " + lipgloss.NewStyle().Render(value)
}
// listSkillFiles returns visible file names in the skill directory.
@@ -913,36 +1094,38 @@ func (m listTUIModel) findSyncedTargets(e skillEntry) []string {
// runListTUI starts the bubbletea TUI for the skill list.
// When loadFn is non-nil, data is loaded asynchronously inside the TUI (no blank screen).
// Returns (action, skillName, error). action is "" on normal quit (q/ctrl+c).
func runListTUI(loadFn listLoadFn, modeLabel, sourcePath string, targets map[string]config.TargetConfig) (string, string, error) {
model := newListTUIModel(loadFn, nil, 0, modeLabel, sourcePath, targets)
// Returns (action, skillName, skillKind, error). action is "" on normal quit (q/ctrl+c).
func runListTUI(loadFn listLoadFn, modeLabel, sourcePath, agentsSourcePath string, targets map[string]config.TargetConfig, initialKind resourceKindFilter) (string, string, string, error) {
model := newListTUIModel(loadFn, nil, 0, modeLabel, sourcePath, agentsSourcePath, targets, initialKind)
p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
finalModel, err := p.Run()
if err != nil {
return "", "", err
return "", "", "", err
}
m, ok := finalModel.(listTUIModel)
if !ok || m.action == "" {
if m.loadErr != nil {
return "", "", m.loadErr
return "", "", "", m.loadErr
}
if m.emptyResult {
return "empty", "", nil
return "empty", "", "", nil
}
return "", "", nil
return "", "", "", nil
}
// Extract skill name from selected item
// Extract skill name and kind from selected item
var skillName string
var skillKind string
if item, ok := m.list.SelectedItem().(skillItem); ok {
if item.entry.RelPath != "" {
skillName = item.entry.RelPath
} else {
skillName = item.entry.Name
}
skillKind = item.entry.Kind
}
return m.action, skillName, nil
return m.action, skillName, skillKind, nil
}
// wordWrapLines splits text into lines that fit within maxWidth, breaking at word boundaries.
+114 -28
View File
@@ -7,6 +7,7 @@ import (
"sort"
"strings"
"skillshare/internal/theme"
"skillshare/internal/utils"
tea "github.com/charmbracelet/bubbletea"
@@ -139,12 +140,37 @@ func buildVisibleNodes(all []treeNode) []treeNode {
// loadContentForSkill populates the content viewer fields for the given skill.
func loadContentForSkill(m *listTUIModel, e skillEntry) {
skillDir := filepath.Join(m.sourcePath, e.RelPath)
m.contentSkillKey = e.RelPath
m.contentKind = e.Kind
m.contentScroll = 0
m.treeCursor = 0
m.treeScroll = 0
if e.Kind == "agent" {
// Agents are single .md files — render directly, minimal tree
agentFile := filepath.Join(m.agentsSourcePath, e.RelPath)
data, err := os.ReadFile(agentFile)
if err != nil {
m.contentText = fmt.Sprintf("(error reading agent: %v)", err)
m.treeAllNodes = nil
m.treeNodes = nil
return
}
raw := strings.TrimSpace(string(data))
if raw == "" {
m.contentText = "(empty)"
} else {
w := m.contentPanelWidth()
m.contentText = hardWrapContent(renderMarkdown(raw, w), w)
}
// Single-file tree: just the agent .md file
m.treeAllNodes = []treeNode{{name: filepath.Base(e.RelPath), relPath: e.RelPath}}
m.treeNodes = m.treeAllNodes
return
}
// Existing skill directory logic
skillDir := filepath.Join(m.sourcePath, e.RelPath)
m.treeAllNodes = buildTreeNodes(skillDir)
m.treeNodes = buildVisibleNodes(m.treeAllNodes)
@@ -172,8 +198,13 @@ func loadContentFile(m *listTUIModel) {
return
}
skillDir := filepath.Join(m.sourcePath, m.contentSkillKey)
filePath := filepath.Join(skillDir, node.relPath)
var filePath string
if m.contentKind == "agent" {
filePath = filepath.Join(m.agentsSourcePath, node.relPath)
} else {
skillDir := filepath.Join(m.sourcePath, m.contentSkillKey)
filePath = filepath.Join(skillDir, node.relPath)
}
var rawText string
if node.name == "SKILL.md" {
@@ -212,13 +243,17 @@ func autoPreviewFile(m *listTUIModel) {
}
}
// contentPanelWidth returns the available text width for the right content panel.
// This accounts for PaddingLeft(1) used in rendering, so content renders at
// the exact width the panel can display without line-wrapping.
// contentPanelWidth returns the available text width for the content panel.
// Agents use full-width (no sidebar); skills use dual-pane layout.
func (m *listTUIModel) contentPanelWidth() int {
if m.contentKind == "agent" {
w := m.termWidth - 4
if w < 40 {
w = 40
}
return w
}
sw := sidebarWidth(m.termWidth)
// lipgloss Width includes padding, so subtract 1 for PaddingLeft(1)
// Layout: leftMargin(1) + sidebar(sw) + PaddingLeft(1) + border(1) + PaddingLeft(1) + content + rightMargin(1)
w := m.termWidth - sw - 5 - 1
if w < 40 {
w = 40
@@ -238,10 +273,18 @@ func hardWrapContent(text string, width int) string {
// ─── Glamour Markdown Rendering ──────────────────────────────────────
// contentGlamourStyle returns a modified dark style with no backgrounds or margins
// that would bleed or overflow in the constrained dual-pane layout.
// contentGlamourStyle returns a glamour style tuned for the dual-pane list
// detail view. The base config tracks the resolved terminal theme so body
// text stays legible on light backgrounds (glamour's dark base uses light
// gray prose which disappears on white). Backgrounds and margins are
// stripped to avoid bleeding in the constrained layout.
func contentGlamourStyle() ansi.StyleConfig {
s := styles.DarkStyleConfig
var s ansi.StyleConfig
if theme.Get().Mode == theme.ModeLight {
s = styles.LightStyleConfig
} else {
s = styles.DarkStyleConfig
}
zero := uint(0)
s.Document.Margin = &zero
@@ -282,8 +325,8 @@ func renderMarkdown(text string, width int) string {
// ─── Keyboard Handling ───────────────────────────────────────────────
// handleContentKey handles keyboard input in the dual-pane content viewer.
// Keyboard always controls the left tree; Ctrl+d/u/g/G scroll the right panel.
// handleContentKey handles keyboard input in the content viewer.
// Agents (single file) only support scroll; skills support tree navigation + scroll.
func (m listTUIModel) handleContentKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "q", "ctrl+c":
@@ -293,35 +336,36 @@ func (m listTUIModel) handleContentKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.showContent = false
return m, nil
// Left tree: navigate
// Left tree: navigate (skills only — agents have no sidebar)
case "j", "down":
if m.treeCursor < len(m.treeNodes)-1 {
if m.contentKind != "agent" && m.treeCursor < len(m.treeNodes)-1 {
m.treeCursor++
m.ensureTreeCursorVisible()
autoPreviewFile(&m)
}
return m, nil
case "k", "up":
if m.treeCursor > 0 {
if m.contentKind != "agent" && m.treeCursor > 0 {
m.treeCursor--
m.ensureTreeCursorVisible()
autoPreviewFile(&m)
}
return m, nil
case "l", "right", "enter":
if len(m.treeNodes) > 0 && m.treeCursor < len(m.treeNodes) {
if m.contentKind != "agent" && len(m.treeNodes) > 0 && m.treeCursor < len(m.treeNodes) {
node := m.treeNodes[m.treeCursor]
if node.isDir {
toggleTreeDir(&m)
}
// Files are already auto-previewed by j/k
}
return m, nil
case "h", "left":
collapseOrParent(&m)
if m.contentKind != "agent" {
collapseOrParent(&m)
}
return m, nil
// Right content: scroll
// Content scroll
case "ctrl+d":
half := m.contentViewHeight() / 2
max := m.contentMaxScroll()
@@ -362,12 +406,54 @@ func sidebarWidth(termWidth int) int {
return w
}
// renderContentOverlay renders the full-screen dual-pane content viewer.
// renderContentOverlay renders the full-screen content viewer.
// Agents (single .md file) use a full-width layout without sidebar.
// Skills (directory with multiple files) use a dual-pane layout with file tree.
func renderContentOverlay(m listTUIModel) string {
if m.contentKind == "agent" {
return renderContentFullWidth(m)
}
return renderContentDualPane(m)
}
// renderContentFullWidth renders the content viewer without sidebar (for agents).
func renderContentFullWidth(m listTUIModel) string {
var b strings.Builder
titleStyle := tc.Title
dimStyle := tc.Dim
skillName := filepath.Base(m.contentSkillKey)
b.WriteString("\n")
b.WriteString(theme.Title().Render(fmt.Sprintf(" %s", skillName)))
b.WriteString("\n\n")
textW := m.contentPanelWidth()
contentHeight := m.contentViewHeight()
contentStr, scrollInfo := renderContentStr(m, textW, contentHeight)
panelW := textW + 2 // +2 for PaddingLeft(2)
panel := lipgloss.NewStyle().
Width(panelW).MaxWidth(panelW).
Height(contentHeight).MaxHeight(contentHeight).
PaddingLeft(2).
Render(contentStr)
b.WriteString(panel)
b.WriteString("\n\n")
help := "Ctrl+d/u scroll g/G top/bottom Esc back q quit"
if scrollInfo != "" {
help += " " + scrollInfo
}
b.WriteString(formatHelpBar(help))
b.WriteString("\n")
return b.String()
}
// renderContentDualPane renders the dual-pane content viewer with file tree sidebar.
func renderContentDualPane(m listTUIModel) string {
var b strings.Builder
titleStyle := theme.Title()
dimStyle := theme.Dim()
skillName := filepath.Base(m.contentSkillKey)
fileName := ""
@@ -403,7 +489,7 @@ func renderContentOverlay(m listTUIModel) string {
PaddingLeft(1).
Render(sidebarStr)
borderStyle := tc.Border.
borderStyle := theme.Dim().
Height(contentHeight).MaxHeight(contentHeight)
borderCol := strings.Repeat("│\n", contentHeight)
borderPanel := borderStyle.Render(strings.TrimRight(borderCol, "\n"))
@@ -422,7 +508,7 @@ func renderContentOverlay(m listTUIModel) string {
if scrollInfo != "" {
help += " " + scrollInfo
}
b.WriteString(tc.Help.Render(help))
b.WriteString(formatHelpBar(help))
b.WriteString("\n")
return b.String()
@@ -434,10 +520,10 @@ func renderSidebarStr(m listTUIModel, width, height int) string {
return "(no files)"
}
selectedStyle := lipgloss.NewStyle().Bold(true).Foreground(tc.BrandYellow)
dirStyle := tc.Cyan
selectedStyle := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#D4D93C"))
dirStyle := theme.Accent()
fileStyle := lipgloss.NewStyle()
dimStyle := tc.Dim
dimStyle := theme.Dim()
total := len(m.treeNodes)
start := m.treeScroll
+49
View File
@@ -0,0 +1,49 @@
package main
import (
"testing"
"skillshare/internal/theme"
)
// contentGlamourStyle must pick the glamour base style that matches the
// resolved terminal theme. Otherwise body prose rendered on a light
// terminal uses the dark-base near-white color ("252") and disappears.
func TestContentGlamourStyle_MatchesTheme(t *testing.T) {
t.Setenv("NO_COLOR", "")
cases := []struct {
mode string
wantBody string // expected Document.StylePrimitive.Color
}{
{"light", "234"}, // readable dark gray on light terminals
{"dark", "252"}, // readable near-white on dark terminals
}
for _, tc := range cases {
t.Run(tc.mode, func(t *testing.T) {
t.Setenv("SKILLSHARE_THEME", tc.mode)
theme.Reset()
defer theme.Reset()
s := contentGlamourStyle()
if s.Document.StylePrimitive.Color == nil {
t.Fatal("Document.Color is nil")
}
if got := *s.Document.StylePrimitive.Color; got != tc.wantBody {
t.Errorf("body Color = %q, want %q", got, tc.wantBody)
}
// Shared customizations must still apply regardless of base.
if s.Document.Margin == nil || *s.Document.Margin != 0 {
t.Errorf("Document.Margin = %v, want 0", s.Document.Margin)
}
if s.H1.StylePrimitive.BackgroundColor != nil {
t.Errorf("H1.BackgroundColor = %v, want nil", s.H1.StylePrimitive.BackgroundColor)
}
if s.H1.StylePrimitive.Color == nil || *s.H1.StylePrimitive.Color != "6" {
t.Errorf("H1.Color = %v, want \"6\"", s.H1.StylePrimitive.Color)
}
})
}
}
+37
View File
@@ -10,6 +10,7 @@ type filterQuery struct {
TypeTag string // "tracked", "remote", "local" (empty = any)
GroupTag string // substring match against group segment
RepoTag string // substring match against RepoName
KindTag string // "skill" or "agent" (empty = any)
FreeText string // remaining text after removing known tags
}
@@ -34,6 +35,10 @@ func parseFilterQuery(raw string) filterQuery {
q.RepoTag = val
continue
}
if val, ok := cutTag(lower, "k:", "kind:"); ok {
q.KindTag = normalizeKindValue(val)
continue
}
freeTokens = append(freeTokens, strings.ToLower(token))
}
@@ -69,6 +74,18 @@ func normalizeTypeValue(val string) string {
}
}
// normalizeKindValue maps plural forms to canonical kind names.
func normalizeKindValue(val string) string {
switch val {
case "agent", "agents":
return "agent"
case "skill", "skills":
return "skill"
default:
return val
}
}
// matchSkillItem returns true if the skill item matches all non-empty conditions in the query (AND logic).
func matchSkillItem(item skillItem, q filterQuery) bool {
e := item.entry
@@ -97,6 +114,11 @@ func matchSkillItem(item skillItem, q filterQuery) bool {
}
}
// Kind tag — exact match on skill kind
if q.KindTag != "" && e.Kind != q.KindTag {
return false
}
// Free text — substring match on FilterValue
if q.FreeText != "" {
fv := strings.ToLower(item.FilterValue())
@@ -141,3 +163,18 @@ func skillGroup(e skillEntry) string {
// Non-tracked: first segment is group
return parts[0]
}
// skillTopGroup returns the top-level visual grouping key for the list TUI.
// Tracked entries (including nested agents in deep repo subdirs) group by
// their tracked repo root. Non-tracked nested entries group by their first
// path segment (e.g. local "mma/foo" → "mma"). Flat root-level entries
// return "" which renders as the "standalone" bucket.
func skillTopGroup(e skillEntry) string {
if e.RepoName != "" {
return e.RepoName
}
if i := strings.Index(e.RelPath, "/"); i > 0 {
return e.RelPath[:i]
}
return ""
}
+66 -39
View File
@@ -5,6 +5,8 @@ import (
"io"
"strings"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
@@ -27,7 +29,10 @@ func (g groupItem) Title() string { return g.label }
func (g groupItem) Description() string { return "" }
// listSkillDelegate renders a compact single-line browser row for the list TUI.
type listSkillDelegate struct{}
// activeTab is a shared pointer so the delegate sees tab changes without re-creation.
type listSkillDelegate struct {
activeTab *listTab // nil-safe: treat nil as listTabAll
}
func (listSkillDelegate) Height() int { return 1 }
func (listSkillDelegate) Spacing() int { return 0 }
@@ -35,7 +40,7 @@ func (listSkillDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd {
return nil
}
func (listSkillDelegate) Render(w io.Writer, m list.Model, index int, item list.Item) {
func (d listSkillDelegate) Render(w io.Writer, m list.Model, index int, item list.Item) {
width := m.Width()
if width <= 0 {
width = 40
@@ -46,7 +51,8 @@ func (listSkillDelegate) Render(w io.Writer, m list.Model, index int, item list.
renderGroupRow(w, v, width)
case skillItem:
selected := index == m.Index()
renderSkillRow(w, v, width, selected)
allTab := d.activeTab != nil && *d.activeTab == listTabAll
renderSkillRow(w, v, width, selected, allTab)
}
}
@@ -55,7 +61,7 @@ func renderGroupRow(w io.Writer, g groupItem, width int) {
if g.count > 0 {
label += fmt.Sprintf(" (%d)", g.count)
}
label = tc.Dim.Render(label)
label = theme.Dim().Render(label)
lineWidth := width - lipgloss.Width(label) - 3 // "─ " prefix + " "
if lineWidth < 2 {
@@ -63,21 +69,21 @@ func renderGroupRow(w io.Writer, g groupItem, width int) {
}
line := strings.Repeat("─", lineWidth)
fmt.Fprint(w, tc.Dim.Render("─ ")+label+" "+tc.Dim.Render(line))
fmt.Fprint(w, theme.Dim().Render("─ ")+label+" "+theme.Dim().Render(line))
}
func renderSkillRow(w io.Writer, skill skillItem, width int, selected bool) {
renderPrefixRow(w, skillTitleLine(skill.entry), width, selected)
func renderSkillRow(w io.Writer, skill skillItem, width int, selected bool, allTab bool) {
renderPrefixRow(w, skillTitleLine(skill.entry, allTab), width, selected)
}
// renderPrefixRow renders a single-line list row with a "▌" prefix bar.
// Shared by list TUI and audit TUI delegates.
func renderPrefixRow(w io.Writer, line string, width int, selected bool) {
prefixStyle := tc.ListRowPrefix
bodyStyle := tc.ListRow
prefixStyle := theme.Dim()
bodyStyle := lipgloss.NewStyle().PaddingLeft(1)
if selected {
prefixStyle = tc.ListRowPrefixSelected
bodyStyle = tc.ListRowSelected
prefixStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#D4D93C"))
bodyStyle = theme.SelectedRow().PaddingLeft(1)
// Strip embedded ANSI so ListRowSelected's background fills the full
// row width — compound ANSI sequences (e.g. icon + name) contain
// resets that break the parent background propagation in lipgloss.
@@ -142,13 +148,13 @@ func (d prefixItemDelegate) Render(w io.Writer, m list.Model, index int, item li
// renderPrefixRowWithDesc renders a 2-line list row with a "▌" prefix bar.
// Line 1: title (same as renderPrefixRow). Line 2: description in muted style.
func renderPrefixRowWithDesc(w io.Writer, title, desc string, width int, selected bool) {
prefixStyle := tc.ListRowPrefix
bodyStyle := tc.ListRow
descStyle := tc.ListMeta
prefixStyle := theme.Dim()
bodyStyle := lipgloss.NewStyle().PaddingLeft(1)
descStyle := theme.Dim().PaddingLeft(1)
if selected {
prefixStyle = tc.ListRowPrefixSelected
bodyStyle = tc.ListRowSelected
descStyle = tc.ListMetaSelected
prefixStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#D4D93C"))
bodyStyle = theme.SelectedRow().PaddingLeft(1)
descStyle = theme.SelectedRow().PaddingLeft(1)
title = xansi.Strip(title)
desc = xansi.Strip(desc)
}
@@ -201,12 +207,20 @@ func (i skillItem) Description() string {
return ""
}
func skillTitleLine(e skillEntry) string {
func skillTitleLine(e skillEntry, allTab bool) string {
if e.Disabled {
// Disabled: dim the entire name + ⊘ prefix
return tc.Dim.Render("⊘ " + compactSkillPath(e))
return theme.Dim().Render("⊘ " + compactSkillPath(e))
}
title := colorSkillPath(compactSkillPath(e))
var prefix string
if allTab {
if e.Kind == "agent" {
prefix = theme.Accent().Render("[A]") + " "
} else {
prefix = theme.Accent().Render("[S]") + " "
}
}
title := prefix + colorSkillPath(compactSkillPath(e))
if badge := skillTypeBadge(e); badge != "" {
return title + " " + badge
}
@@ -241,10 +255,10 @@ func baseSkillPath(e skillEntry) string {
func skillTypeBadge(e skillEntry) string {
var badge string
if e.RepoName == "" && e.Source == "" {
badge = tc.BadgeLocal.Render("local")
badge = theme.Badge().Render("local")
}
if e.Disabled {
disabled := tc.BadgeDisabled.Render("disabled")
disabled := theme.Badge().Faint(true).Render("disabled")
if badge != "" {
return badge + " " + disabled
}
@@ -258,7 +272,7 @@ func skillTypeBadge(e skillEntry) string {
func colorSkillPath(path string) string {
segments := strings.Split(path, "/")
if len(segments) <= 1 {
return tc.Emphasis.Render(path)
return theme.Primary().Render(path)
}
dirs := segments[:len(segments)-1]
@@ -267,21 +281,21 @@ func colorSkillPath(path string) string {
var parts []string
for idx, dir := range dirs {
if idx == 0 {
parts = append(parts, tc.Cyan.Render(dir))
parts = append(parts, theme.Accent().Render(dir))
} else {
parts = append(parts, tc.Dim.Render(dir))
parts = append(parts, theme.Dim().Render(dir))
}
}
sep := tc.Faint.Render("/")
return strings.Join(parts, sep) + sep + tc.Emphasis.Render(name)
sep := theme.Dim().Render("/")
return strings.Join(parts, sep) + sep + theme.Primary().Render(name)
}
// colorSkillPathBold is like colorSkillPath but renders the skill name in bold
// for extra prominence in the detail panel header.
func colorSkillPathBold(path string) string {
segments := strings.Split(path, "/")
boldName := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("15"))
boldName := theme.Primary().Bold(true)
if len(segments) <= 1 {
return boldName.Render(path)
}
@@ -292,13 +306,13 @@ func colorSkillPathBold(path string) string {
var parts []string
for idx, dir := range dirs {
if idx == 0 {
parts = append(parts, tc.Cyan.Render(dir))
parts = append(parts, theme.Accent().Render(dir))
} else {
parts = append(parts, tc.Dim.Render(dir))
parts = append(parts, theme.Dim().Render(dir))
}
}
sep := tc.Faint.Render("/")
sep := theme.Dim().Render("/")
return strings.Join(parts, sep) + sep + boldName.Render(name)
}
@@ -318,16 +332,20 @@ func toSkillItems(entries []skillEntry) []skillItem {
return items
}
// buildGroupedItems inserts groupItem separators before each repo/local group.
// buildGroupedItems inserts groupItem separators before each top-level group.
// Skills must be sorted by RelPath (tracked repos with "_" prefix sort first).
// If all skills belong to a single group (e.g. all standalone), no separators are added.
// Grouping follows skillTopGroup(): tracked entries group by their repo root;
// local nested entries group by their first path segment; flat locals fall
// into "standalone". When items contain mixed kinds (skills + agents), the
// kind is included in the key so they stay in separate blocks.
func buildGroupedItems(skills []skillItem) []list.Item {
// Check if there are multiple groups.
groups := map[string]bool{}
hasMultiKinds := false
for _, s := range skills {
groups[s.entry.RepoName] = true
if len(groups) > 1 {
break
groups[s.entry.Kind+"\x00"+skillTopGroup(s.entry)] = true
if !hasMultiKinds && len(skills) > 0 && s.entry.Kind != skills[0].entry.Kind {
hasMultiKinds = true
}
}
@@ -357,12 +375,21 @@ func buildGroupedItems(skills []skillItem) []list.Item {
}
for _, s := range skills {
key := s.entry.RepoName // "" for local
top := skillTopGroup(s.entry)
key := s.entry.Kind + "\x00" + top
if key != currentGroup {
flush()
label := "standalone"
if key != "" {
label = strings.TrimPrefix(key, "_")
if top != "" {
label = strings.TrimPrefix(top, "_")
}
// Prefix with kind when mixed to visually separate skills/agents
if hasMultiKinds {
kindPrefix := "Skills"
if s.entry.Kind == "agent" {
kindPrefix = "Agents"
}
label = kindPrefix + " · " + label
}
items = append(items, groupItem{label: label})
currentGroup = key
+109
View File
@@ -123,6 +123,115 @@ func TestBuildGroupedItems_SingleGroup(t *testing.T) {
}
}
// Local nested skills (e.g. "mma/agent-browser") must form their own
// visual group even though they have no RepoName, so they don't get
// lumped together with flat root-level locals under "standalone".
func TestBuildGroupedItems_LocalNestedGroup(t *testing.T) {
// Pre-sorted: mma group items contiguous, then flat standalone.
// (sortSkillEntries places standalone last.)
skills := []skillItem{
{entry: skillEntry{Name: "agent-browser", RelPath: "mma/agent-browser"}},
{entry: skillEntry{Name: "docker-expert", RelPath: "mma/docker-expert"}},
{entry: skillEntry{Name: "flat-a", RelPath: "flat-a"}},
}
items := buildGroupedItems(skills)
// Expect: group("mma") + 2 skills + group("standalone") + 1 skill = 5
if len(items) != 5 {
t.Fatalf("buildGroupedItems local nested: got %d items, want 5", len(items))
}
g1, ok := items[0].(groupItem)
if !ok || g1.label != "mma" || g1.count != 2 {
t.Errorf("group 1: %+v, want label=mma count=2", g1)
}
g2, ok := items[3].(groupItem)
if !ok || g2.label != "standalone" || g2.count != 1 {
t.Errorf("group 2: %+v, want label=standalone count=1", g2)
}
}
// Agents deep inside a tracked repo (e.g. _repo/agents/core/x.md,
// _repo/agents/specialized/python/y.md) must all belong to ONE group
// keyed by the tracked repo root — not split into core/specialized buckets.
func TestBuildGroupedItems_TrackedAgentsDeepPath(t *testing.T) {
skills := []skillItem{
{entry: skillEntry{
Kind: "agent", Name: "code-reviewer",
RelPath: "_vijay-agents/agents/core/code-reviewer.md", RepoName: "_vijay-agents",
}},
{entry: skillEntry{
Kind: "agent", Name: "python-expert",
RelPath: "_vijay-agents/agents/specialized/python/python-expert.md", RepoName: "_vijay-agents",
}},
{entry: skillEntry{
Kind: "agent", Name: "local-agent",
RelPath: "local-agent.md",
}},
}
items := buildGroupedItems(skills)
// Expect: group("vijay-agents") + 2 agents + group("standalone") + 1 agent = 5
if len(items) != 5 {
t.Fatalf("buildGroupedItems tracked agents: got %d items, want 5", len(items))
}
g1, ok := items[0].(groupItem)
if !ok || g1.label != "vijay-agents" || g1.count != 2 {
t.Errorf("group 1: %+v, want label=vijay-agents count=2", g1)
}
g2, ok := items[3].(groupItem)
if !ok || g2.label != "standalone" || g2.count != 1 {
t.Errorf("group 2: %+v, want label=standalone count=1", g2)
}
}
func TestSkillTopGroup(t *testing.T) {
cases := []struct {
name string
e skillEntry
want string
}{
{"tracked repo", skillEntry{RepoName: "_repo", RelPath: "_repo/security/audit"}, "_repo"},
{"local nested", skillEntry{RelPath: "mma/docker-expert"}, "mma"},
{"local deep", skillEntry{RelPath: "frontend/react/hooks"}, "frontend"},
{"flat local", skillEntry{RelPath: "my-skill"}, ""},
{"empty", skillEntry{}, ""},
}
for _, tc := range cases {
if got := skillTopGroup(tc.e); got != tc.want {
t.Errorf("%s: skillTopGroup=%q, want %q", tc.name, got, tc.want)
}
}
}
// The default sort must group entries by top-level bucket so
// buildGroupedItems produces contiguous groups. Standalone entries
// (empty top group) must sort last so they don't split named groups.
func TestSortSkillEntries_TopGroupOrder(t *testing.T) {
skills := []skillEntry{
{Name: "react-best-practices", RelPath: "react-best-practices"},
{Name: "mma-slack", RelPath: "mma/slack"},
{Name: "tracked-a", RelPath: "_team-repo/a", RepoName: "_team-repo"},
{Name: "agent-browser", RelPath: "agent-browser"},
{Name: "mma-dogfood", RelPath: "mma/dogfood"},
}
sortSkillEntries(skills, "")
got := make([]string, len(skills))
for i, s := range skills {
got[i] = s.RelPath
}
want := []string{
"_team-repo/a", // tracked repo first (underscore sorts first)
"mma/dogfood", // then local nested "mma" group
"mma/slack", //
"agent-browser", // standalone flat items last, alphabetical
"react-best-practices", //
}
for i := range want {
if got[i] != want[i] {
t.Errorf("sort order[%d] = %q, want %q (full: %v)", i, got[i], want[i], got)
}
}
}
func TestSkillItem_Description_Tracked(t *testing.T) {
item := skillItem{entry: skillEntry{RepoName: "team-repo"}}
if got := item.Description(); got != "" {
+120 -8
View File
@@ -41,13 +41,15 @@ func TestListDetailStatusBits(t *testing.T) {
}
func TestListSummaryFooterCounts(t *testing.T) {
items := []skillItem{
{entry: skillEntry{Name: "local", RelPath: "local"}},
{entry: skillEntry{Name: "tracked", RelPath: "tracked", RepoName: "team/repo"}},
{entry: skillEntry{Name: "remote", RelPath: "remote", Source: "github.com/example/repo"}},
}
m := listTUIModel{
allItems: []skillItem{
{entry: skillEntry{Name: "local", RelPath: "local"}},
{entry: skillEntry{Name: "tracked", RelPath: "tracked", RepoName: "team/repo"}},
{entry: skillEntry{Name: "remote", RelPath: "remote", Source: "github.com/example/repo"}},
},
matchCount: 2,
allItems: items,
tabFiltered: items, // All tab — same as allItems
matchCount: 2,
}
got := m.renderSummaryFooter()
@@ -98,7 +100,7 @@ func TestListViewSplit_HeaderKeepsSkillNameWhenDetailScrolled(t *testing.T) {
},
}
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), nil)
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), "", nil, kindAll)
m.termWidth = 120
m.termHeight = 30
m.detailScroll = 999
@@ -133,7 +135,7 @@ func TestApplyFilter_WithTags(t *testing.T) {
{entry: skillEntry{Name: "remote-a", RelPath: "remote-a", Source: "github.com/foo/bar"}},
}
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), nil)
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), "", nil, kindAll)
// Filter by type:tracked — should match 2 items
m.filterText = "t:tracked"
@@ -184,3 +186,113 @@ func TestApplyFilter_WithTags(t *testing.T) {
t.Fatalf("cleared matchCount = %d, want %d", m.matchCount, len(items))
}
}
func TestTabCounts(t *testing.T) {
items := []skillItem{
{entry: skillEntry{Name: "s1", RelPath: "s1", Kind: "skill"}},
{entry: skillEntry{Name: "s2", RelPath: "s2", Kind: "skill"}},
{entry: skillEntry{Name: "a1", RelPath: "a1.md", Kind: "agent"}},
}
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), "", nil, kindAll)
want := [3]int{3, 2, 1}
if m.tabCounts != want {
t.Fatalf("tabCounts = %v, want %v", m.tabCounts, want)
}
}
func TestTabSwitchFiltersItems(t *testing.T) {
items := []skillItem{
{entry: skillEntry{Name: "skill-a", RelPath: "skill-a", Kind: "skill"}},
{entry: skillEntry{Name: "skill-b", RelPath: "skill-b", Kind: "skill"}},
{entry: skillEntry{Name: "agent-a", RelPath: "agent-a.md", Kind: "agent"}},
}
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), "", nil, kindAll)
// Default All tab — should show 3
if m.matchCount != 3 {
t.Fatalf("All tab matchCount = %d, want 3", m.matchCount)
}
// Switch to Skills tab
m.activeTab = listTabSkills
m.applyFilter()
if m.matchCount != 2 {
t.Fatalf("Skills tab matchCount = %d, want 2", m.matchCount)
}
// Switch to Agents tab
m.activeTab = listTabAgents
m.applyFilter()
if m.matchCount != 1 {
t.Fatalf("Agents tab matchCount = %d, want 1", m.matchCount)
}
}
func TestInitialKindSetsTab(t *testing.T) {
m := newListTUIModel(nil, nil, 0, "global", t.TempDir(), "", nil, kindAgents)
if m.activeTab != listTabAgents {
t.Fatalf("initialKind=kindAgents → activeTab = %d, want %d", m.activeTab, listTabAgents)
}
m2 := newListTUIModel(nil, nil, 0, "global", t.TempDir(), "", nil, kindSkills)
if m2.activeTab != listTabSkills {
t.Fatalf("initialKind=kindSkills → activeTab = %d, want %d", m2.activeTab, listTabSkills)
}
}
func TestTabWithFilterComposition(t *testing.T) {
items := []skillItem{
{entry: skillEntry{Name: "react", RelPath: "react", Kind: "skill"}},
{entry: skillEntry{Name: "vue", RelPath: "vue", Kind: "skill"}},
{entry: skillEntry{Name: "react-agent", RelPath: "react-agent.md", Kind: "agent"}},
}
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), "", nil, kindAll)
// Skills tab + text filter "react" → only skill "react"
m.activeTab = listTabSkills
m.filterText = "react"
m.applyFilter()
if m.matchCount != 1 {
t.Fatalf("Skills+react matchCount = %d, want 1", m.matchCount)
}
// All tab + text filter "react" → skill "react" + agent "react-agent"
m.activeTab = listTabAll
m.applyFilter()
if m.matchCount != 2 {
t.Fatalf("All+react matchCount = %d, want 2", m.matchCount)
}
}
func TestTabBarRendering(t *testing.T) {
items := []skillItem{
{entry: skillEntry{Name: "s1", RelPath: "s1", Kind: "skill"}},
{entry: skillEntry{Name: "a1", RelPath: "a1.md", Kind: "agent"}},
}
m := newListTUIModel(nil, items, len(items), "global", t.TempDir(), "", nil, kindAll)
bar := xansi.Strip(m.renderTabBar())
for _, want := range []string{"All(2)", "Skills(1)", "Agents(1)"} {
if !strings.Contains(bar, want) {
t.Fatalf("tab bar missing %q in %q", want, bar)
}
}
}
func TestUpdateTitle(t *testing.T) {
m := newListTUIModel(nil, nil, 0, "global", t.TempDir(), "", nil, kindAll)
if !strings.Contains(m.list.Title, "resources") {
t.Fatalf("All tab title = %q, want 'resources'", m.list.Title)
}
m.activeTab = listTabSkills
m.updateTitle()
if !strings.Contains(m.list.Title, "skills") {
t.Fatalf("Skills tab title = %q, want 'skills'", m.list.Title)
}
m.activeTab = listTabAgents
m.updateTitle()
if !strings.Contains(m.list.Title, "agents") {
t.Fatalf("Agents tab title = %q, want 'agents'", m.list.Title)
}
}
+60 -68
View File
@@ -6,25 +6,17 @@ import (
"strings"
"time"
"skillshare/internal/oplog"
"skillshare/internal/theme"
"skillshare/internal/ui"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"skillshare/internal/oplog"
"skillshare/internal/ui"
)
// lc holds log-specific styles that don't belong in the shared tc palette.
var lc = struct {
Bold lipgloss.Style // counts, totals — bold without color
Label lipgloss.Style // row labels — wider (22) than tc.Label (14)
}{
Bold: lipgloss.NewStyle().Bold(true),
Label: lipgloss.NewStyle().Faint(true).Width(22),
}
// logLoadFn is a function that loads log items (runs in a goroutine inside the TUI).
type logLoadFn func() ([]logItem, error)
@@ -95,7 +87,7 @@ func newLogTUIModel(loadFn logLoadFn, items []logItem, logLabel, modeLabel, conf
l := list.New(listItems, newPrefixDelegate(false), 0, 0)
l.Title = fmt.Sprintf("Log: %s (%s)", logLabel, modeLabel)
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false) // custom status line
l.SetFilteringEnabled(false) // application-level filter
l.SetShowHelp(false)
@@ -104,13 +96,13 @@ func newLogTUIModel(loadFn logLoadFn, items []logItem, logLabel, modeLabel, conf
// Loading spinner
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
// Filter text input
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
return logTUIModel{
list: l,
@@ -534,7 +526,7 @@ func (m logTUIModel) View() string {
b.WriteString("\n")
help := "s back to list q quit"
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
}
@@ -571,7 +563,7 @@ func (m logTUIModel) View() string {
b.WriteString(m.renderStatsFooter())
b.WriteString("\n")
b.WriteString(tc.Help.Render(appendScrollInfo(m.logHelpBar(), scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo(m.logHelpBar(), scrollInfo)))
b.WriteString("\n")
return b.String()
@@ -596,7 +588,7 @@ func (m logTUIModel) viewVertical() string {
b.WriteString(m.renderStatsFooter())
b.WriteString(tc.Help.Render(appendScrollInfo(m.logHelpBar(), scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo(m.logHelpBar(), scrollInfo)))
b.WriteString("\n")
return b.String()
@@ -622,7 +614,7 @@ func (m logTUIModel) logHelpBar() string {
help := strings.Join(parts, " ")
if m.lastDeletedMsg != "" {
help = tc.Green.Render(m.lastDeletedMsg) + " " + help
help = theme.Success().Render(m.lastDeletedMsg) + " " + help
}
return help
@@ -665,8 +657,8 @@ func renderLogDetailPanel(item logItem) string {
var b strings.Builder
row := func(label, value string) {
b.WriteString(lc.Label.Render(label))
b.WriteString(tc.Value.Render(value))
b.WriteString(theme.Dim().Width(22).Render(label))
b.WriteString(lipgloss.NewStyle().Render(value))
b.WriteString("\n")
}
@@ -676,17 +668,17 @@ func renderLogDetailPanel(item logItem) string {
row("Timestamp:", e.Timestamp)
// Command — cyan to match CLI palette
row("Command:", tc.Cyan.Render(strings.ToUpper(e.Command)))
row("Command:", theme.Accent().Render(strings.ToUpper(e.Command)))
// Status with color
statusDisplay := e.Status
switch e.Status {
case "ok":
statusDisplay = tc.Green.Render(e.Status)
statusDisplay = theme.Success().Render(e.Status)
case "error", "blocked":
statusDisplay = tc.Red.Render(e.Status)
statusDisplay = theme.Danger().Render(e.Status)
case "partial":
statusDisplay = tc.Yellow.Render(e.Status)
statusDisplay = theme.Warning().Render(e.Status)
}
row("Status:", statusDisplay)
@@ -712,7 +704,7 @@ func renderLogDetailPanel(item logItem) string {
for _, p := range pairs {
// List fields: render as multi-line bullet list for readability
if p.isList && len(p.listValues) > 0 {
b.WriteString(lc.Label.Render(p.key + ":"))
b.WriteString(theme.Dim().Width(22).Render(p.key + ":"))
b.WriteString("\n")
show := p.listValues
remaining := 0
@@ -721,11 +713,11 @@ func renderLogDetailPanel(item logItem) string {
show = show[:maxBulletItems]
}
for _, v := range show {
b.WriteString(" - " + tc.Value.Render(v) + "\n")
b.WriteString(" - " + lipgloss.NewStyle().Render(v) + "\n")
}
if remaining > 0 {
summary := fmt.Sprintf(" ... and %d more", remaining)
b.WriteString(tc.Dim.Render(summary) + "\n")
b.WriteString(theme.Dim().Render(summary) + "\n")
}
continue
}
@@ -738,9 +730,9 @@ func renderLogDetailPanel(item logItem) string {
// Colorize only severity/status fields to avoid visual noise
switch {
case strings.Contains(p.key, "failed") || strings.Contains(p.key, "scan-errors"):
value = tc.Red.Render(value)
value = theme.Danger().Render(value)
case strings.Contains(p.key, "warning"):
value = tc.Yellow.Render(value)
value = theme.Warning().Render(value)
case p.key == "risk":
value = colorizeRiskValue(value)
case p.key == "threshold":
@@ -757,7 +749,7 @@ func renderLogDetailPanel(item logItem) string {
// severityStyles maps the 5 severity levels (c/h/m/l/i) to lipgloss styles.
var severityStyles = []lipgloss.Style{
tc.Critical, tc.High, tc.Medium, tc.Low, tc.Info,
theme.Severity("critical"), theme.Severity("high"), theme.Severity("medium"), theme.Severity("low"), theme.Severity("info"),
}
// colorizeSeverityBreakdown colors each number in "0/0/1/0/0" to match audit summary.
@@ -769,16 +761,16 @@ func colorizeSeverityBreakdown(value string) string {
for i, p := range parts {
parts[i] = severityStyles[i].Render(p)
}
sep := tc.Dim.Render("/")
sep := theme.Dim().Render("/")
return strings.Join(parts, sep)
}
// colorizeThreshold applies color based on audit threshold level.
func colorizeThreshold(value string) string {
if ui.SeverityColorID(value) == "" {
return tc.Green.Render(value)
return theme.Success().Render(value)
}
return tcSevStyle(value).Render(value)
return theme.SeverityStyle(value).Render(value)
}
// colorizeRiskValue applies color based on the risk label embedded in the value string.
@@ -787,9 +779,9 @@ func colorizeRiskValue(value string) string {
sev := strings.SplitN(strings.ToUpper(value), " ", 2)[0]
sev = strings.TrimRight(sev, "(")
if ui.SeverityColorID(sev) == "" {
return tc.Green.Render(value)
return theme.Success().Render(value)
}
return tcSevStyle(sev).Render(value)
return theme.SeverityStyle(sev).Render(value)
}
// computeLogStatsFromItems converts logItems to oplog entries and computes stats.
@@ -810,21 +802,21 @@ func (m logTUIModel) renderStatsFooter() string {
rateStyle := statsSuccessRateColor(m.stats.SuccessRate)
parts := []string{
tc.Dim.Render(fmt.Sprintf("%d ops", m.stats.Total)),
theme.Dim().Render(fmt.Sprintf("%d ops", m.stats.Total)),
rateStyle.Render(fmt.Sprintf("✓ %.1f%%", m.stats.SuccessRate*100)),
}
if m.stats.LastOperation != nil {
ts, err := time.Parse(time.RFC3339, m.stats.LastOperation.Timestamp)
if err == nil {
lastPart := tc.Dim.Render("last: ") +
tc.Cyan.Render(m.stats.LastOperation.Command) +
tc.Dim.Render(fmt.Sprintf(" %s ago", formatRelativeTime(time.Since(ts))))
lastPart := theme.Dim().Render("last: ") +
theme.Accent().Render(m.stats.LastOperation.Command) +
theme.Dim().Render(fmt.Sprintf(" %s ago", formatRelativeTime(time.Since(ts))))
parts = append(parts, lastPart)
}
}
sep := tc.Dim.Render(" | ")
sep := theme.Dim().Render(" | ")
return " " + strings.Join(parts, sep) + "\n"
}
@@ -832,13 +824,13 @@ func (m logTUIModel) renderStatsFooter() string {
func (m logTUIModel) renderStatsPanel() string {
var b strings.Builder
b.WriteString(tc.Title.Render(" Operation Log Summary"))
b.WriteString(theme.Title().Render(" Operation Log Summary"))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(" " + strings.Repeat("─", 50)))
b.WriteString(theme.Dim().Render(" " + strings.Repeat("─", 50)))
b.WriteString("\n\n")
if m.stats.Total == 0 {
b.WriteString(tc.Dim.Render(" No entries"))
b.WriteString(theme.Dim().Render(" No entries"))
b.WriteString("\n")
return b.String()
}
@@ -850,20 +842,20 @@ func (m logTUIModel) renderStatsPanel() string {
}
rateColor := statsSuccessRateColor(m.stats.SuccessRate)
b.WriteString(fmt.Sprintf(" %s %s\n\n",
tc.Dim.Render("Total:"),
lc.Bold.Render(fmt.Sprintf("%d", m.stats.Total)),
theme.Dim().Render("Total:"),
lipgloss.NewStyle().Bold(true).Render(fmt.Sprintf("%d", m.stats.Total)),
))
b.WriteString(fmt.Sprintf(" %s %s %s\n\n",
tc.Dim.Render("OK:"),
theme.Dim().Render("OK:"),
rateColor.Render(fmt.Sprintf("%d/%d", okTotal, m.stats.Total)),
tc.Dim.Render(fmt.Sprintf("(%.1f%%)", m.stats.SuccessRate*100)),
theme.Dim().Render(fmt.Sprintf("(%.1f%%)", m.stats.SuccessRate*100)),
))
// ── Command breakdown with horizontal bars ──
header := fmt.Sprintf(" %-12s %-20s %s", "Command", "", "OK")
b.WriteString(tc.Dim.Render(header))
b.WriteString(theme.Dim().Render(header))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(" " + strings.Repeat("─", 42)))
b.WriteString(theme.Dim().Render(" " + strings.Repeat("─", 42)))
b.WriteString("\n")
type cmdEntry struct {
@@ -899,21 +891,21 @@ func (m logTUIModel) renderStatsPanel() string {
}
errBarLen := barLen - okBarLen
cmdBar := tc.Green.Render(strings.Repeat("▓", okBarLen))
cmdBar := theme.Success().Render(strings.Repeat("▓", okBarLen))
if errBarLen > 0 {
cmdBar += tc.Red.Render(strings.Repeat("▓", errBarLen))
cmdBar += theme.Danger().Render(strings.Repeat("▓", errBarLen))
}
padding := strings.Repeat(" ", cmdBarWidth-barLen)
// "✓6/9" format — ok out of total, self-explanatory
okRatio := fmt.Sprintf("✓%d/%d", cmd.cs.OK, cmd.cs.Total)
ratioColor := tc.Green
ratioColor := theme.Success()
if cmd.cs.OK < cmd.cs.Total {
ratioColor = tc.Red
ratioColor = theme.Danger()
}
b.WriteString(fmt.Sprintf(" %s %s%s %s\n",
tc.Dim.Render(fmt.Sprintf("%-12s", cmd.name)),
theme.Dim().Render(fmt.Sprintf("%-12s", cmd.name)),
cmdBar, padding, ratioColor.Render(okRatio)))
}
@@ -928,19 +920,19 @@ func (m logTUIModel) renderStatsPanel() string {
blockedTotal += cs.Blocked
}
b.WriteString(tc.Dim.Render(" " + strings.Repeat("─", 50)))
b.WriteString(theme.Dim().Render(" " + strings.Repeat("─", 50)))
b.WriteString("\n")
b.WriteString(fmt.Sprintf(" %s %s",
tc.Dim.Render("Status:"),
tc.Green.Render(fmt.Sprintf("✓ %d ok", okTotal))))
theme.Dim().Render("Status:"),
theme.Success().Render(fmt.Sprintf("✓ %d ok", okTotal))))
if errTotal > 0 {
b.WriteString(fmt.Sprintf(" %s", tc.Red.Render(fmt.Sprintf("✗ %d error", errTotal))))
b.WriteString(fmt.Sprintf(" %s", theme.Danger().Render(fmt.Sprintf("✗ %d error", errTotal))))
}
if partialTotal > 0 {
b.WriteString(fmt.Sprintf(" %s", tc.Yellow.Render(fmt.Sprintf("◐ %d partial", partialTotal))))
b.WriteString(fmt.Sprintf(" %s", theme.Warning().Render(fmt.Sprintf("◐ %d partial", partialTotal))))
}
if blockedTotal > 0 {
b.WriteString(fmt.Sprintf(" %s", tc.Red.Render(fmt.Sprintf("⊘ %d blocked", blockedTotal))))
b.WriteString(fmt.Sprintf(" %s", theme.Danger().Render(fmt.Sprintf("⊘ %d blocked", blockedTotal))))
}
b.WriteString("\n")
@@ -950,9 +942,9 @@ func (m logTUIModel) renderStatsPanel() string {
if err == nil {
ago := formatRelativeTime(time.Since(ts))
b.WriteString(fmt.Sprintf(" %s %s %s\n",
tc.Dim.Render("Last op:"),
tc.Cyan.Render(m.stats.LastOperation.Command),
tc.Dim.Render(fmt.Sprintf("(%s ago)", ago))))
theme.Dim().Render("Last op:"),
theme.Accent().Render(m.stats.LastOperation.Command),
theme.Dim().Render(fmt.Sprintf("(%s ago)", ago))))
}
}
@@ -963,11 +955,11 @@ func (m logTUIModel) renderStatsPanel() string {
func statsSuccessRateColor(rate float64) lipgloss.Style {
switch {
case rate >= 0.9:
return tc.Green.Bold(true)
return theme.Success().Bold(true)
case rate >= 0.7:
return tc.Yellow.Bold(true)
return theme.Warning().Bold(true)
default:
return tc.Red.Bold(true)
return theme.Danger().Bold(true)
}
}
+24 -15
View File
@@ -9,6 +9,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/install"
"skillshare/internal/theme"
"skillshare/internal/ui"
versioncheck "skillshare/internal/version"
)
@@ -52,6 +53,10 @@ func main() {
// Clean up any leftover .old files from Windows self-upgrade
cleanupOldBinary()
// Resolve theme early so OSC 11 probe overhead happens at startup,
// not inside a TUI render loop.
_ = theme.Get()
// Migrate Windows legacy ~/.config/skillshare → %AppData%\skillshare
results := config.MigrateWindowsLegacyDir()
@@ -196,21 +201,21 @@ func printUsage() {
// Core Commands
fmt.Println("CORE COMMANDS")
cmd("init", "", "Initialize skillshare")
cmd("install", "<source>", "Install a skill from local path or git repo")
cmd("uninstall", "<name>...", "Remove skills from source directory")
cmd("list", "", "List all installed skills")
cmd("install", "<source>", "Install skills/agents from local path or git repo")
cmd("uninstall", "<name>...", "Remove skills/agents from source directory")
cmd("list", "[agents] [pattern] [--all]", "List installed skills (or agents)")
cmd("search", "[query]", "Search or browse GitHub for skills")
cmd("sync", "[extras] [--all]", "Sync skills (or extras) to targets")
cmd("sync", "[agents] [--all]", "Sync skills/agents/extras to targets")
cmd("status", "", "Show status of all targets")
fmt.Println()
// Skill Management
fmt.Println("SKILL MANAGEMENT")
// Skill & Agent Management
fmt.Println("SKILL & AGENT MANAGEMENT")
cmd("new", "<name>", "Create a new skill with SKILL.md template")
cmd("enable", "<name|pattern>", "Enable a disabled skill (remove from .skillignore)")
cmd("disable", "<name|pattern>", "Disable a skill (add to .skillignore)")
cmd("check", "", "Check for available updates")
cmd("update", "<name>", "Update a skill or tracked repository")
cmd("enable", "<name|pattern>", "Enable a disabled skill/agent")
cmd("disable", "<name|pattern>", "Disable a skill/agent")
cmd("check", "[agents] [--all]", "Check for available updates")
cmd("update", "[agents] <name>", "Update a skill/agent or tracked repository")
cmd("update", "--all", "Update all tracked repositories")
cmd("upgrade", "", "Upgrade CLI and/or skillshare skill")
fmt.Println()
@@ -220,16 +225,16 @@ func printUsage() {
cmd("target add", "<name> [path]", "Add a target (path optional in project mode)")
cmd("target remove", "<name>", "Unlink target and restore skills")
cmd("target list", "", "List all targets")
cmd("diff", "", "Show differences between source and targets")
cmd("diff", "[target]", "Show differences between source and targets")
fmt.Println()
// Sync & Backup
fmt.Println("SYNC & BACKUP")
cmd("collect", "[target]", "Collect local skills from target(s) to source")
cmd("collect", "[agents] [target]", "Collect local skills/agents from target(s)")
cmd("backup", "", "Create backup of target(s)")
cmd("restore", "<target>", "Restore target from latest backup")
cmd("trash", "list", "List trashed skills")
cmd("trash", "restore <name>", "Restore a skill from trash")
cmd("trash", "[agents] list", "List trashed skills/agents")
cmd("trash", "[agents] restore <name>", "Restore a skill/agent from trash")
fmt.Println()
// Extras
@@ -248,7 +253,7 @@ func printUsage() {
// Utilities
fmt.Println("UTILITIES")
cmd("audit", "[name]", "Scan skills for security threats")
cmd("audit", "[agents] [name]", "Scan skills/agents for security threats")
cmd("hub", "<subcommand>", "Manage hubs (add, list, remove, default, index)")
cmd("log", "", "View operation log")
cmd("tui", "[on|off]", "Toggle interactive TUI mode")
@@ -268,8 +273,12 @@ func printUsage() {
fmt.Println("EXAMPLES")
fmt.Println(g + " skillshare status # Check current state")
fmt.Println(" skillshare sync --dry-run # Preview before sync")
fmt.Println(" skillshare sync agents # Sync agents only")
fmt.Println(" skillshare sync --all # Sync skills + agents + extras")
fmt.Println(" skillshare list --all # List skills + agents")
fmt.Println(" skillshare collect claude # Import local skills")
fmt.Println(" skillshare install anthropics/skills/pdf -p # Project install")
fmt.Println(" skillshare install repo -a my-agent # Install specific agent")
fmt.Println(" skillshare target add cursor -p # Project target")
fmt.Println(" skillshare push -m \"Add new skill\" # Push to remote")
fmt.Println(" skillshare pull # Pull from remote")
+3 -1
View File
@@ -4,6 +4,8 @@ import (
"errors"
"fmt"
"strings"
"skillshare/internal/theme"
)
var errCancelled = errors.New("cancelled")
@@ -125,7 +127,7 @@ func runNewWizard() (selectedPattern, selectedCategory string, createDirs bool)
// wizardHeader builds a compact breadcrumb string for the help bar footer.
// e.g. "✓ reviewer → quality"
func wizardHeader(pattern, category string) string {
check := tc.Green.Render("✓")
check := theme.Success().Render("✓")
var parts []string
if pattern != "" {
parts = append(parts, check+" "+pattern)
+22
View File
@@ -0,0 +1,22 @@
package main
import (
"path/filepath"
"skillshare/internal/config"
)
// resolveProjectPath expands ~ and resolves relative project paths against
// the project root so all project-mode comparisons use a single path form.
func resolveProjectPath(projectRoot, path string) string {
if path == "" {
return ""
}
resolved := config.ExpandPath(path)
if !filepath.IsAbs(resolved) {
return filepath.Join(projectRoot, filepath.FromSlash(resolved))
}
return resolved
}
+24 -11
View File
@@ -4,14 +4,17 @@ import (
"path/filepath"
"skillshare/internal/config"
"skillshare/internal/install"
)
type projectRuntime struct {
root string
config *config.ProjectConfig
registry *config.Registry
sourcePath string
targets map[string]config.TargetConfig
root string
config *config.ProjectConfig
skillsStore *install.MetadataStore
agentsStore *install.MetadataStore
sourcePath string
agentsSourcePath string
targets map[string]config.TargetConfig
}
func loadProjectRuntime(root string) (*projectRuntime, error) {
@@ -25,16 +28,26 @@ func loadProjectRuntime(root string) (*projectRuntime, error) {
return nil, err
}
reg, err := config.LoadRegistry(filepath.Join(root, ".skillshare"))
skillsDir := filepath.Join(root, ".skillshare", "skills")
agentsDir := filepath.Join(root, ".skillshare", "agents")
skillsStore, err := install.LoadMetadataWithMigration(skillsDir, "")
if err != nil {
return nil, err
}
agentsStore, err := install.LoadMetadataWithMigration(agentsDir, "agent")
if err != nil {
return nil, err
}
return &projectRuntime{
root: root,
config: cfg,
registry: reg,
sourcePath: filepath.Join(root, ".skillshare", "skills"),
targets: targets,
root: root,
config: cfg,
skillsStore: skillsStore,
agentsStore: agentsStore,
sourcePath: skillsDir,
agentsSourcePath: agentsDir,
targets: targets,
}, nil
}
+1 -1
View File
@@ -5,5 +5,5 @@ import (
)
func reconcileProjectRemoteSkills(runtime *projectRuntime) error {
return config.ReconcileProjectSkills(runtime.root, runtime.config, runtime.registry, runtime.sourcePath)
return config.ReconcileProjectSkills(runtime.root, runtime.config, runtime.skillsStore, runtime.sourcePath)
}
+91 -49
View File
@@ -12,10 +12,12 @@ import (
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"skillshare/internal/backup"
"skillshare/internal/config"
"skillshare/internal/oplog"
"skillshare/internal/theme"
"skillshare/internal/utils"
)
@@ -24,6 +26,24 @@ import (
// Left-right split layout: list on left, detail panel on right.
// ---------------------------------------------------------------------------
// isAgentBackupEntry returns true if the backup entry name represents an agent backup.
func isAgentBackupEntry(name string) bool {
return strings.HasSuffix(name, "-agents")
}
// agentBaseTarget returns the base target name by stripping the "-agents" suffix.
func agentBaseTarget(name string) string {
return strings.TrimSuffix(name, "-agents")
}
// resolveAgentBackupPath resolves the agent target path for a backup entry name,
// reusing the canonical resolveAgentTargetPath with builtin fallback.
func resolveAgentBackupPath(targets map[string]config.TargetConfig, entryName string) string {
baseName := agentBaseTarget(entryName)
tc := targets[baseName] // zero-value is safe — AgentsConfig returns empty, falls through to builtin
return resolveAgentTargetPath(tc, config.DefaultAgentTargets(), baseName)
}
// restorePhase tracks which screen is active.
type restorePhase int
@@ -45,7 +65,11 @@ type restoreTargetItem struct {
}
func (i restoreTargetItem) Title() string {
return i.summary.TargetName
name := i.summary.TargetName
if isAgentBackupEntry(name) {
return theme.Accent().Render("[A]") + " " + agentBaseTarget(name)
}
return name
}
func (i restoreTargetItem) Description() string {
return fmt.Sprintf("%d backup(s), latest: %s",
@@ -144,7 +168,7 @@ func newRestoreTUIModel(summaries []backup.TargetBackupSummary, backupDir string
tl := list.New(listItems, newPrefixDelegate(true), 0, 0)
tl.Title = fmt.Sprintf("Backup Restore — %d target(s)", len(summaries))
tl.Styles.Title = tc.ListTitle
tl.Styles.Title = theme.Title()
tl.SetShowStatusBar(false)
tl.SetFilteringEnabled(false)
tl.SetShowHelp(false)
@@ -152,12 +176,12 @@ func newRestoreTUIModel(summaries []backup.TargetBackupSummary, backupDir string
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
return restoreTUIModel{
phase: phaseTargetList,
@@ -199,7 +223,7 @@ func (m restoreTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case restoreDoneMsg:
if msg.action == "delete" {
if msg.err != nil {
m.resultMsg = tc.Red.Render(fmt.Sprintf("Delete failed: %s", msg.err))
m.resultMsg = theme.Danger().Render(fmt.Sprintf("Delete failed: %s", msg.err))
m.phase = phaseDone
return m, nil
}
@@ -208,16 +232,16 @@ func (m restoreTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.selectedVersion != nil {
label = m.selectedVersion.Label
}
m.resultMsg = tc.Green.Render(fmt.Sprintf("Deleted backup %s", label))
m.resultMsg = theme.Success().Render(fmt.Sprintf("Deleted backup %s", label))
m.confirmAction = ""
m.selectedVersion = nil
return m.enterVersionPhase()
}
m.phase = phaseDone
if msg.err != nil {
m.resultMsg = tc.Red.Render(fmt.Sprintf("Error: %s", msg.err))
m.resultMsg = theme.Danger().Render(fmt.Sprintf("Error: %s", msg.err))
} else {
m.resultMsg = tc.Green.Render(fmt.Sprintf("Restored %s from %s", m.selectedTarget, m.selectedVersion.Label))
m.resultMsg = theme.Success().Render(fmt.Sprintf("Restored %s from %s", m.selectedTarget, m.selectedVersion.Label))
}
return m, nil
@@ -435,7 +459,7 @@ func (m restoreTUIModel) enterVersionPhase() (tea.Model, tea.Cmd) {
lw := restoreListWidth(m.termWidth)
vl := list.New(listItems, newPrefixDelegate(true), 0, 0)
vl.Title = fmt.Sprintf("%s — select version", m.selectedTarget)
vl.Styles.Title = tc.ListTitle
vl.Styles.Title = theme.Title()
vl.SetShowStatusBar(false)
vl.SetFilteringEnabled(false)
vl.SetShowHelp(false)
@@ -462,14 +486,22 @@ func (m restoreTUIModel) startRestore() (tea.Model, tea.Cmd) {
cmd := func() tea.Msg {
start := time.Now()
targetCfg, ok := targets[targetName]
if !ok {
var destPath string
if isAgentBackupEntry(targetName) {
destPath = resolveAgentBackupPath(targets, targetName)
} else {
if tc, ok := targets[targetName]; ok {
destPath = tc.SkillsConfig().Path
}
}
if destPath == "" {
return restoreDoneMsg{err: fmt.Errorf("target '%s' not found in config", targetName)}
}
backupPath := filepath.Dir(version.Dir)
opts := backup.RestoreOptions{Force: true}
err := backup.RestoreToPath(backupPath, targetName, targetCfg.SkillsConfig().Path, opts)
err := backup.RestoreToPath(backupPath, targetName, destPath, opts)
e := oplog.NewEntry("restore", statusFromErr(err), time.Since(start))
e.Args = map[string]any{"target": targetName, "from": version.Label, "via": "tui"}
@@ -626,7 +658,7 @@ func (m restoreTUIModel) View() string {
case phaseDone:
return fmt.Sprintf("\n %s\n\n %s\n",
m.resultMsg, tc.Help.Render("Press any key to exit"))
m.resultMsg, theme.Dim().MarginLeft(2).Render("Press any key to exit"))
case phaseConfirm:
return m.viewRestoreConfirm()
@@ -674,7 +706,7 @@ func (m restoreTUIModel) viewHorizontal() string {
b.WriteString(m.renderRestoreFilterBar())
// Help
b.WriteString(tc.Help.Render(appendScrollInfo(m.restoreHelpText(), scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo(m.restoreHelpText(), scrollInfo)))
b.WriteString("\n")
return b.String()
@@ -709,7 +741,7 @@ func (m restoreTUIModel) viewVertical() string {
b.WriteString(detailStr)
b.WriteString("\n")
b.WriteString(tc.Help.Render(appendScrollInfo(m.restoreHelpText(), scrollInfo)))
b.WriteString(theme.Dim().MarginLeft(2).Render(appendScrollInfo(m.restoreHelpText(), scrollInfo)))
b.WriteString("\n")
return b.String()
@@ -768,7 +800,7 @@ func (m restoreTUIModel) viewRestoreConfirm() string {
if m.confirmAction == "delete" {
fmt.Fprintf(&b, " %s\n\n",
tc.Red.Render(fmt.Sprintf("Delete backup %s for %s?", m.selectedVersion.Label, m.selectedTarget)))
theme.Danger().Render(fmt.Sprintf("Delete backup %s for %s?", m.selectedVersion.Label, m.selectedTarget)))
} else {
fmt.Fprintf(&b, " Restore %s from backup %s?\n\n", m.selectedTarget, m.selectedVersion.Label)
}
@@ -798,7 +830,7 @@ func (m restoreTUIModel) viewRestoreConfirm() string {
}
b.WriteString("\n ")
b.WriteString(tc.Help.Render("y confirm n cancel"))
b.WriteString(theme.Dim().MarginLeft(2).Render("y confirm n cancel"))
b.WriteString("\n")
return b.String()
}
@@ -838,15 +870,20 @@ func (m restoreTUIModel) renderTargetDetail(s backup.TargetBackupSummary) string
var b strings.Builder
row := func(label, value string) {
b.WriteString(tc.Label.Render(label))
b.WriteString(tc.Value.Render(value))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(lipgloss.NewStyle().Render(value))
b.WriteString("\n")
}
row("Target: ", s.TargetName)
// Target path and current state
if t, ok := m.targets[s.TargetName]; ok {
if isAgentBackupEntry(s.TargetName) {
agentPath := resolveAgentBackupPath(m.targets, s.TargetName)
if agentPath != "" {
row("Path: ", agentPath)
row("Status: ", describeTargetState(agentPath))
}
} else if t, ok := m.targets[s.TargetName]; ok {
sc := t.SkillsConfig()
row("Path: ", sc.Path)
if sc.Mode != "" {
@@ -874,7 +911,7 @@ func (m restoreTUIModel) renderTargetDetail(s backup.TargetBackupSummary) string
if len(skillNames) > 0 {
b.WriteString("\n")
b.WriteString(tc.Separator.Render("── Latest backup skills ──────────────"))
b.WriteString(theme.Dim().Render("── Latest backup skills ──────────────"))
b.WriteString("\n")
const maxPreview = 20
show := skillNames
@@ -884,17 +921,17 @@ func (m restoreTUIModel) renderTargetDetail(s backup.TargetBackupSummary) string
for _, name := range show {
desc := readSkillDescription(filepath.Join(latestDir, name))
if desc != "" {
b.WriteString(tc.Value.Render(" " + name))
b.WriteString(lipgloss.NewStyle().Render(" " + name))
b.WriteString("\n")
b.WriteString(tc.Dim.Render(" " + truncateStr(desc, 60)))
b.WriteString(theme.Dim().Render(" " + truncateStr(desc, 60)))
b.WriteString("\n")
} else {
b.WriteString(tc.Value.Render(" " + name))
b.WriteString(lipgloss.NewStyle().Render(" " + name))
b.WriteString("\n")
}
}
if len(skillNames) > maxPreview {
b.WriteString(tc.Dim.Render(fmt.Sprintf(" ... and %d more", len(skillNames)-maxPreview)))
b.WriteString(theme.Dim().Render(fmt.Sprintf(" ... and %d more", len(skillNames)-maxPreview)))
b.WriteString("\n")
}
}
@@ -907,8 +944,8 @@ func (m restoreTUIModel) renderVersionDetail(v backup.BackupVersion) string {
var b strings.Builder
row := func(label, value string) {
b.WriteString(tc.Label.Render(label))
b.WriteString(tc.Value.Render(value))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(lipgloss.NewStyle().Render(value))
b.WriteString("\n")
}
@@ -920,37 +957,42 @@ func (m restoreTUIModel) renderVersionDetail(v backup.BackupVersion) string {
row("Size: ", "calculating...")
}
// Diff with current target
if t, ok := m.targets[m.selectedTarget]; ok {
added, removed, common := diffSkillSets(v.SkillNames, listDirNames(t.SkillsConfig().Path))
var diffPath string
if isAgentBackupEntry(m.selectedTarget) {
diffPath = resolveAgentBackupPath(m.targets, m.selectedTarget)
} else if t, ok := m.targets[m.selectedTarget]; ok {
diffPath = t.SkillsConfig().Path
}
if diffPath != "" {
added, removed, common := diffSkillSets(v.SkillNames, listDirNames(diffPath))
if len(added) > 0 || len(removed) > 0 {
b.WriteString("\n")
b.WriteString(tc.Separator.Render("── Diff vs current target ────────────"))
b.WriteString(theme.Dim().Render("── Diff vs current target ────────────"))
b.WriteString("\n")
if len(common) > 0 {
row("Same: ", fmt.Sprintf("%d skill(s)", len(common)))
}
if len(added) > 0 {
b.WriteString(tc.Label.Render("Restore: "))
b.WriteString(tc.Green.Render(fmt.Sprintf("+%d (in backup, not in target)", len(added))))
b.WriteString(theme.Dim().Width(14).Render("Restore: "))
b.WriteString(theme.Success().Render(fmt.Sprintf("+%d (in backup, not in target)", len(added))))
b.WriteString("\n")
for _, name := range added {
b.WriteString(tc.Green.Render(" + " + name))
b.WriteString(theme.Success().Render(" + " + name))
b.WriteString("\n")
}
}
if len(removed) > 0 {
b.WriteString(tc.Label.Render("Remove: "))
b.WriteString(tc.Red.Render(fmt.Sprintf("-%d (in target, not in backup)", len(removed))))
b.WriteString(theme.Dim().Width(14).Render("Remove: "))
b.WriteString(theme.Danger().Render(fmt.Sprintf("-%d (in target, not in backup)", len(removed))))
b.WriteString("\n")
for _, name := range removed {
b.WriteString(tc.Red.Render(" - " + name))
b.WriteString(theme.Danger().Render(" - " + name))
b.WriteString("\n")
}
}
} else if len(common) > 0 {
b.WriteString("\n")
b.WriteString(tc.Dim.Render(" Backup matches current target"))
b.WriteString(theme.Dim().Render(" Backup matches current target"))
b.WriteString("\n")
}
}
@@ -958,30 +1000,30 @@ func (m restoreTUIModel) renderVersionDetail(v backup.BackupVersion) string {
// Skill list with descriptions (cap I/O at 20 skills)
if len(v.SkillNames) > 0 {
b.WriteString("\n")
b.WriteString(tc.Separator.Render("── Contents ──────────────────────────"))
b.WriteString(theme.Dim().Render("── Contents ──────────────────────────"))
b.WriteString("\n")
const maxDetail = 20
for i, name := range v.SkillNames {
if i < maxDetail {
desc := readSkillDescription(filepath.Join(v.Dir, name))
files := listSkillFiles(filepath.Join(v.Dir, name))
b.WriteString(tc.Value.Render(" " + name))
b.WriteString(lipgloss.NewStyle().Render(" " + name))
b.WriteString("\n")
if desc != "" {
b.WriteString(tc.Dim.Render(" " + truncateStr(desc, 60)))
b.WriteString(theme.Dim().Render(" " + truncateStr(desc, 60)))
b.WriteString("\n")
}
if len(files) > 0 {
b.WriteString(tc.Dim.Render(" " + strings.Join(files, " ")))
b.WriteString(theme.Dim().Render(" " + strings.Join(files, " ")))
b.WriteString("\n")
}
} else {
b.WriteString(tc.Dim.Render(" " + name))
b.WriteString(theme.Dim().Render(" " + name))
b.WriteString("\n")
}
}
if len(v.SkillNames) > maxDetail {
b.WriteString(tc.Dim.Render(fmt.Sprintf(" ... %d skill(s) above shown without details", len(v.SkillNames)-maxDetail)))
b.WriteString(theme.Dim().Render(fmt.Sprintf(" ... %d skill(s) above shown without details", len(v.SkillNames)-maxDetail)))
b.WriteString("\n")
}
}
@@ -1005,13 +1047,13 @@ func describeTargetState(path string) string {
info, err := os.Lstat(path)
if err != nil {
if os.IsNotExist(err) {
return tc.Yellow.Render("not found")
return theme.Warning().Render("not found")
}
return tc.Red.Render("error")
return theme.Danger().Render("error")
}
if info.Mode()&os.ModeSymlink != 0 {
dest, _ := os.Readlink(path)
return tc.Cyan.Render("symlink → " + dest)
return theme.Accent().Render("symlink → " + dest)
}
entries, _ := os.ReadDir(path)
return fmt.Sprintf("directory (%d items)", len(entries))
+4 -4
View File
@@ -578,11 +578,11 @@ func installFromSearchResult(result search.SearchResult, cfg *config.Config) (er
logSummary.InstalledSkills = []string{result.Name}
// Reconcile global config with installed skills
reg, _ := config.LoadRegistry(cfg.RegistryDir)
if reg == nil {
reg = &config.Registry{}
store, _ := install.LoadMetadataWithMigration(cfg.Source, "")
if store == nil {
store = install.NewMetadataStore()
}
if rErr := config.ReconcileGlobalSkills(cfg, reg); rErr != nil {
if rErr := config.ReconcileGlobalSkills(cfg, store); rErr != nil {
ui.Warning("Failed to reconcile global skills config: %v", rErr)
}
+4 -4
View File
@@ -565,11 +565,11 @@ func batchInstallFromSearchWithProgress(selected []search.SearchResult, mode run
_ = reconcileProjectRemoteSkills(runtime)
}
} else {
reg, _ := config.LoadRegistry(cfg.RegistryDir)
if reg == nil {
reg = &config.Registry{}
store, _ := install.LoadMetadataWithMigration(cfg.Source, "")
if store == nil {
store = install.NewMetadataStore()
}
_ = config.ReconcileGlobalSkills(cfg, reg)
_ = config.ReconcileGlobalSkills(cfg, store)
}
renderBatchSearchInstallSummary(results, mode, time.Since(batchStart))
+13 -11
View File
@@ -7,8 +7,10 @@ import (
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"skillshare/internal/search"
"skillshare/internal/theme"
)
// ---------------------------------------------------------------------------
@@ -46,7 +48,7 @@ func (i searchSelectItem) Title() string {
}
title := check + " " + i.result.Name
if i.isHub {
badge := formatRiskBadgeLipgloss(i.result.RiskLabel)
badge := theme.FormatRiskBadge(i.result.RiskLabel)
if badge != "" {
title += badge
}
@@ -116,7 +118,7 @@ func newSearchSelectModel(results []search.SearchResult, isHub bool) searchSelec
l := list.New(items, newPrefixDelegate(true), 0, 0)
l.Title = searchSelectTitle(0, len(results))
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false) // custom status line
l.SetFilteringEnabled(false) // application-level filter
l.SetShowHelp(false)
@@ -125,8 +127,8 @@ func newSearchSelectModel(results []search.SearchResult, isHub bool) searchSelec
// Filter text input
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
return searchSelectModel{
list: l,
@@ -319,7 +321,7 @@ func (m searchSelectModel) View() string {
}
help := "↑↓ navigate ←→ page space toggle a all enter install s search again / filter esc cancel"
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
@@ -337,13 +339,13 @@ func (m searchSelectModel) renderSearchFilterBar() string {
// renderSearchDetailPanel renders the detail section for the selected search result.
func (m searchSelectModel) renderSearchDetailPanel(r search.SearchResult) string {
var b strings.Builder
b.WriteString(tc.Separator.Render(" ─────────────────────────────────────────"))
b.WriteString(theme.Dim().Render(" ─────────────────────────────────────────"))
b.WriteString("\n")
row := func(label, value string) {
b.WriteString(" ")
b.WriteString(tc.Label.Render(label))
b.WriteString(tc.Value.Render(value))
b.WriteString(theme.Dim().Width(14).Render(label))
b.WriteString(lipgloss.NewStyle().Render(value))
b.WriteString("\n")
}
@@ -365,7 +367,7 @@ func (m searchSelectModel) renderSearchDetailPanel(r search.SearchResult) string
indent := strings.Repeat(" ", labelOffset)
for _, line := range lines[1:] {
b.WriteString(indent)
b.WriteString(tc.Value.Render(line))
b.WriteString(lipgloss.NewStyle().Render(line))
b.WriteString("\n")
}
b.WriteString("\n")
@@ -381,7 +383,7 @@ func (m searchSelectModel) renderSearchDetailPanel(r search.SearchResult) string
// Risk (hub)
if m.isHub && r.RiskLabel != "" {
row("Risk:", riskLabelStyle(r.RiskLabel).Render(r.RiskLabel))
row("Risk:", theme.RiskLabelStyle(r.RiskLabel).Render(r.RiskLabel))
}
// Tags
@@ -390,7 +392,7 @@ func (m searchSelectModel) renderSearchDetailPanel(r search.SearchResult) string
for i, tag := range r.Tags {
tags[i] = "#" + tag
}
row("Tags:", tc.Target.Render(strings.Join(tags, " ")))
row("Tags:", theme.Accent().Render(strings.Join(tags, " ")))
}
return b.String()
+73 -15
View File
@@ -11,6 +11,7 @@ import (
"skillshare/internal/audit"
"skillshare/internal/config"
"skillshare/internal/git"
"skillshare/internal/resource"
"skillshare/internal/skillignore"
"skillshare/internal/sync"
"skillshare/internal/ui"
@@ -23,6 +24,7 @@ type statusJSONOutput struct {
SkillCount int `json:"skill_count"`
TrackedRepos []statusJSONRepo `json:"tracked_repos"`
Targets []statusJSONTarget `json:"targets"`
Agents *statusJSONAgents `json:"agents,omitempty"`
Audit statusJSONAudit `json:"audit"`
Version string `json:"version"`
}
@@ -139,23 +141,21 @@ func cmdStatus(args []string) error {
}
// JSON mode
output := statusJSONOutput{
Version: version,
}
discovered, stats, _ := sync.DiscoverSourceSkillsWithStats(cfg.Source)
trackedRepos := extractTrackedRepos(discovered)
output := statusJSONOutput{
Source: statusJSONSource{
Path: cfg.Source,
Exists: dirExists(cfg.Source),
Skillignore: buildSkillignoreJSON(stats),
},
SkillCount: len(discovered),
Version: version,
output.Source = statusJSONSource{
Path: cfg.Source,
Exists: dirExists(cfg.Source),
Skillignore: buildSkillignoreJSON(stats),
}
// Tracked repos (parallel dirty checks)
output.SkillCount = len(discovered)
output.TrackedRepos = buildTrackedRepoJSON(cfg.Source, trackedRepos, discovered)
// Targets
for name, target := range cfg.Targets {
sc := target.SkillsConfig()
tMode := getTargetMode(sc.Mode, cfg.Mode)
@@ -171,7 +171,6 @@ func cmdStatus(args []string) error {
})
}
// Audit
policy := audit.ResolvePolicy(audit.PolicyInputs{
ConfigProfile: cfg.Audit.Profile,
ConfigThreshold: cfg.Audit.BlockThreshold,
@@ -185,6 +184,8 @@ func cmdStatus(args []string) error {
Analyzers: policy.EffectiveAnalyzers(),
}
output.Agents = buildAgentStatusJSON(cfg)
return writeJSON(&output)
}
@@ -222,6 +223,20 @@ func printSourceStatus(cfg *config.Config, skillCount int, stats *skillignore.Ig
ui.Success("%s (%d skills, %s)", cfg.Source, skillCount, info.ModTime().Format("2006-01-02 15:04"))
printSkillignoreLine(stats)
// Agents source
agentsSource := cfg.EffectiveAgentsSource()
if agentsInfo, agentsErr := os.Stat(agentsSource); agentsErr == nil {
agentCount := 0
if entries, readErr := os.ReadDir(agentsSource); readErr == nil {
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(strings.ToLower(e.Name()), ".md") {
agentCount++
}
}
}
ui.Success("%s (%d agents, %s)", agentsSource, agentCount, agentsInfo.ModTime().Format("2006-01-02 15:04"))
}
}
func printSkillignoreLine(stats *skillignore.IgnoreStats) {
@@ -355,12 +370,26 @@ type targetStatusResult struct {
func printTargetsStatus(cfg *config.Config, discovered []sync.DiscoveredSkill) error {
ui.Header("Targets")
builtinAgents := config.DefaultAgentTargets()
agentsSource := cfg.EffectiveAgentsSource()
agentsExist := dirExists(agentsSource)
var agentCount int
if agentsExist {
agents, _ := resource.AgentKind{}.Discover(agentsSource)
agentCount = len(agents)
}
driftTotal := 0
for name, target := range cfg.Targets {
// Target name header
fmt.Printf("%s%s%s\n", ui.Bold, name, ui.Reset)
// Skills sub-item
sc := target.SkillsConfig()
mode := getTargetMode(sc.Mode, cfg.Mode)
res := getTargetStatusDetail(target, cfg.Source, mode)
ui.Status(name, res.statusStr, res.detail)
printTargetSubItem("skills", res.statusStr, res.detail)
if mode == "merge" || mode == "copy" {
filtered, err := sync.FilterSkills(discovered, sc.Include, sc.Exclude)
@@ -379,6 +408,21 @@ func printTargetsStatus(cfg *config.Config, discovered []sync.DiscoveredSkill) e
} else if len(sc.Include) > 0 || len(sc.Exclude) > 0 {
ui.Warning("%s: include/exclude ignored in symlink mode", name)
}
// Agents sub-item
if agentsExist {
agentPath := resolveAgentTargetPath(target, builtinAgents, name)
if agentPath != "" {
linked := countLinkedAgents(agentPath)
agentStatus := "merged"
driftLabel := ""
if linked != agentCount && agentCount > 0 {
agentStatus = "drift"
driftLabel = ui.Yellow + " (drift)" + ui.Reset
}
printTargetSubItem("agents", agentStatus, fmt.Sprintf("[merge] %d/%d linked%s", linked, agentCount, driftLabel))
}
}
}
if driftTotal > 0 {
ui.Warning("%d skill(s) not synced — run 'skillshare sync'", driftTotal)
@@ -386,6 +430,20 @@ func printTargetsStatus(cfg *config.Config, discovered []sync.DiscoveredSkill) e
return nil
}
// printTargetSubItem prints an indented sub-item line under a target.
func printTargetSubItem(kind, status, detail string) {
statusColor := ui.Gray
switch status {
case "merged", "synced", "copied", "linked":
statusColor = ui.Green
case "drift", "not exist":
statusColor = ui.Yellow
case "conflict", "broken":
statusColor = ui.Red
}
fmt.Printf(" %-8s %s%-12s%s %s\n", kind, statusColor, status, ui.Reset, ui.Dim+detail+ui.Reset)
}
func getTargetMode(targetMode, globalMode string) string {
if targetMode != "" {
return targetMode
@@ -503,7 +561,7 @@ func checkSkillVersion(cfg *config.Config) {
func printStatusHelp() {
fmt.Println(`Usage: skillshare status [options]
Show status of source, skills, and all targets.
Show status of source, skills, agents, and all targets.
Options:
--json Output results as JSON
@@ -512,7 +570,7 @@ Options:
--help, -h Show this help
Examples:
skillshare status Show current state
skillshare status Show current state (skills + agents)
skillshare status --json Output as JSON
skillshare status -p Show project status`)
}
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"skillshare/internal/config"
"skillshare/internal/resource"
)
// statusJSONAgents is the agent section of status --json output.
type statusJSONAgents struct {
Source string `json:"source"`
Exists bool `json:"exists"`
Count int `json:"count"`
Targets []statusJSONAgentTarget `json:"targets,omitempty"`
}
type statusJSONAgentTarget struct {
Name string `json:"name"`
Path string `json:"path"`
Expected int `json:"expected"`
Linked int `json:"linked"`
Drift bool `json:"drift"`
}
// buildAgentStatusJSON builds the agents section for status --json output.
func buildAgentStatusJSON(cfg *config.Config) *statusJSONAgents {
agentsSource := cfg.EffectiveAgentsSource()
exists := dirExists(agentsSource)
result := &statusJSONAgents{
Source: agentsSource,
Exists: exists,
}
if !exists {
return result
}
agents, _ := resource.AgentKind{}.Discover(agentsSource)
result.Count = len(agents)
builtinAgents := config.DefaultAgentTargets()
for name := range cfg.Targets {
agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name)
if agentPath == "" {
continue
}
linked := countLinkedAgents(agentPath)
result.Targets = append(result.Targets, statusJSONAgentTarget{
Name: name,
Path: agentPath,
Expected: len(agents),
Linked: linked,
Drift: linked != len(agents) && len(agents) > 0,
})
}
return result
}
// countLinkedAgents counts healthy .md symlinks in the target agent directory.
func countLinkedAgents(targetDir string) int {
linked, _ := countAgentLinksAndBroken(targetDir)
return linked
}
+101 -17
View File
@@ -9,6 +9,7 @@ import (
"skillshare/internal/audit"
"skillshare/internal/config"
"skillshare/internal/git"
"skillshare/internal/resource"
"skillshare/internal/skillignore"
"skillshare/internal/sync"
"skillshare/internal/ui"
@@ -34,7 +35,7 @@ func cmdStatusProject(root string) error {
trackedRepos := extractTrackedRepos(discovered)
sp.Stop()
printProjectSourceStatus(runtime.sourcePath, len(discovered), stats)
printProjectSourceStatus(runtime.sourcePath, runtime.agentsSourcePath, len(discovered), stats)
printProjectTrackedReposStatus(runtime.sourcePath, discovered, trackedRepos)
if err := printProjectTargetsStatus(runtime, discovered); err != nil {
return err
@@ -42,7 +43,7 @@ func cmdStatusProject(root string) error {
// Extras
if len(runtime.config.Extras) > 0 {
ui.Header("Extras (project)")
ui.Header("Extras")
printExtrasStatus(runtime.config.Extras, func(extra config.ExtraConfig) string {
return config.ExtrasSourceDirProject(root, extra.Name)
})
@@ -65,23 +66,21 @@ func cmdStatusProjectJSON(root string) error {
return writeJSONError(err)
}
output := statusJSONOutput{
Version: version,
}
discovered, stats, _ := sync.DiscoverSourceSkillsWithStats(runtime.sourcePath)
trackedRepos := extractTrackedRepos(discovered)
output := statusJSONOutput{
Source: statusJSONSource{
Path: runtime.sourcePath,
Exists: dirExists(runtime.sourcePath),
Skillignore: buildSkillignoreJSON(stats),
},
SkillCount: len(discovered),
Version: version,
output.Source = statusJSONSource{
Path: runtime.sourcePath,
Exists: dirExists(runtime.sourcePath),
Skillignore: buildSkillignoreJSON(stats),
}
// Tracked repos (parallel dirty checks)
output.SkillCount = len(discovered)
output.TrackedRepos = buildTrackedRepoJSON(runtime.sourcePath, trackedRepos, discovered)
// Targets
for _, entry := range runtime.config.Targets {
target, ok := runtime.targets[entry.Name]
if !ok {
@@ -104,7 +103,6 @@ func cmdStatusProjectJSON(root string) error {
})
}
// Audit
policy := audit.ResolvePolicy(audit.PolicyInputs{
ConfigProfile: runtime.config.Audit.Profile,
ConfigThreshold: runtime.config.Audit.BlockThreshold,
@@ -118,10 +116,59 @@ func cmdStatusProjectJSON(root string) error {
Analyzers: policy.EffectiveAnalyzers(),
}
output.Agents = buildProjectAgentStatusJSON(runtime)
return writeJSON(&output)
}
func printProjectSourceStatus(sourcePath string, skillCount int, stats *skillignore.IgnoreStats) {
// buildProjectAgentStatusJSON builds the agents section for project status --json.
func buildProjectAgentStatusJSON(rt *projectRuntime) *statusJSONAgents {
exists := dirExists(rt.agentsSourcePath)
result := &statusJSONAgents{
Source: rt.agentsSourcePath,
Exists: exists,
}
if !exists {
return result
}
agents, _ := resource.AgentKind{}.Discover(rt.agentsSourcePath)
result.Count = len(agents)
builtinAgents := config.ProjectAgentTargets()
for _, entry := range rt.config.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, rt.root)
if agentPath == "" {
continue
}
linked := countLinkedAgents(agentPath)
result.Targets = append(result.Targets, statusJSONAgentTarget{
Name: entry.Name,
Path: agentPath,
Expected: len(agents),
Linked: linked,
Drift: linked != len(agents) && len(agents) > 0,
})
}
return result
}
// resolveProjectAgentTargetPath resolves the agent path for a project target entry.
func resolveProjectAgentTargetPath(entry config.ProjectTargetEntry, builtinAgents map[string]config.TargetConfig, projectRoot string) string {
ac := entry.AgentsConfig()
if ac.Path != "" {
return resolveProjectPath(projectRoot, ac.Path)
}
if builtin, ok := builtinAgents[entry.Name]; ok {
return resolveProjectPath(projectRoot, builtin.Path)
}
return ""
}
func printProjectSourceStatus(sourcePath, agentsSourcePath string, skillCount int, stats *skillignore.IgnoreStats) {
ui.Header("Source (project)")
info, err := os.Stat(sourcePath)
if err != nil {
@@ -131,6 +178,15 @@ func printProjectSourceStatus(sourcePath string, skillCount int, stats *skillign
ui.Success(".skillshare/skills/ (%d skills, %s)", skillCount, info.ModTime().Format("2006-01-02 15:04"))
printSkillignoreLine(stats)
// Agents source
if agentsInfo, agentsErr := os.Stat(agentsSourcePath); agentsErr == nil {
agentCount := 0
if agents, discoverErr := (resource.AgentKind{}).Discover(agentsSourcePath); discoverErr == nil {
agentCount = len(agents)
}
ui.Success(".skillshare/agents/ (%d agents, %s)", agentCount, agentsInfo.ModTime().Format("2006-01-02 15:04"))
}
}
func printProjectTrackedReposStatus(sourcePath string, discovered []sync.DiscoveredSkill, trackedRepos []string) {
@@ -161,7 +217,16 @@ func printProjectTrackedReposStatus(sourcePath string, discovered []sync.Discove
}
func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.DiscoveredSkill) error {
ui.Header("Targets (project)")
ui.Header("Targets")
builtinAgents := config.ProjectAgentTargets()
agentsExist := dirExists(runtime.agentsSourcePath)
var agentCount int
if agentsExist {
agents, _ := (resource.AgentKind{}).Discover(runtime.agentsSourcePath)
agentCount = len(agents)
}
driftTotal := 0
for _, entry := range runtime.config.Targets {
target, ok := runtime.targets[entry.Name]
@@ -170,6 +235,10 @@ func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.Discov
continue
}
// Target name header
fmt.Printf("%s%s%s\n", ui.Bold, entry.Name, ui.Reset)
// Skills sub-item
sc := target.SkillsConfig()
mode := sc.Mode
if mode == "" {
@@ -177,7 +246,7 @@ func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.Discov
}
res := getTargetStatusDetail(target, runtime.sourcePath, mode)
ui.Status(entry.Name, res.statusStr, res.detail)
printTargetSubItem("skills", res.statusStr, res.detail)
if mode == "merge" || mode == "copy" {
filtered, err := sync.FilterSkills(discovered, sc.Include, sc.Exclude)
@@ -196,6 +265,21 @@ func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.Discov
} else if len(sc.Include) > 0 || len(sc.Exclude) > 0 {
ui.Warning("%s: include/exclude ignored in symlink mode", entry.Name)
}
// Agents sub-item
if agentsExist {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, runtime.root)
if agentPath != "" {
linked := countLinkedAgents(agentPath)
agentStatus := "merged"
driftLabel := ""
if linked != agentCount && agentCount > 0 {
agentStatus = "drift"
driftLabel = ui.Yellow + " (drift)" + ui.Reset
}
printTargetSubItem("agents", agentStatus, fmt.Sprintf("[merge] %d/%d linked%s", linked, agentCount, driftLabel))
}
}
}
if driftTotal > 0 {
ui.Warning("%d skill(s) not synced — run 'skillshare sync'", driftTotal)
+61 -10
View File
@@ -100,6 +100,9 @@ func cmdSync(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare sync agents").
kind, rest := parseKindArg(rest)
dryRun, force, jsonOutput := parseSyncFlags(rest)
prevDiagOutput := sync.DiagOutput
@@ -111,25 +114,39 @@ func cmdSync(args []string) error {
}
if mode == modeProject {
// Agent-only project sync
if kind == kindAgents {
return syncAgentsProject(cwd, dryRun, force, jsonOutput, start)
}
if hasAll && !jsonOutput {
// Run project extras sync after project skills sync (text mode)
defer func() {
fmt.Println()
if extrasErr := cmdSyncExtras(append([]string{"-p"}, rest...)); extrasErr != nil {
ui.Warning("Extras sync: %v", extrasErr)
}
}()
}
stats, results, projIgnoreStats, err := cmdSyncProject(cwd, dryRun, force, jsonOutput)
stats.ProjectScope = true
logSyncOp(config.ProjectConfigPath(cwd), stats, start, err)
// Append agent sync when kind=all or --all
if kind == kindAll || hasAll {
if agentErr := syncAgentsProject(cwd, dryRun, force, jsonOutput, start); agentErr != nil && err == nil {
err = agentErr
}
}
if jsonOutput {
if hasAll {
projCfg, loadErr := config.LoadProject(cwd)
if loadErr == nil && len(projCfg.Extras) > 0 {
agentPaths := collectAgentTargetPathsProject(cwd)
extrasEntries := runExtrasSyncEntries(projCfg.Extras, func(extra config.ExtraConfig) string {
return config.ExtrasSourceDirProject(cwd, extra.Name)
}, dryRun, force, cwd)
}, dryRun, force, cwd, agentPaths)
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, extrasEntries)
}
}
@@ -160,7 +177,14 @@ func cmdSync(args []string) error {
}
}
// Phase 1: Discovery
// Agent-only mode: skip skill discovery/sync entirely
if kind == kindAgents {
_, agentErr := syncAgentsGlobal(cfg, dryRun, force, jsonOutput, start)
logSyncOp(config.ConfigPath(), syncLogStats{DryRun: dryRun, Force: force}, start, agentErr)
return agentErr
}
// Phase 1: Discovery (skills)
var spinner *ui.Spinner
if !jsonOutput {
spinner = ui.StartSpinner("Discovering skills")
@@ -253,17 +277,24 @@ func cmdSync(args []string) error {
if jsonOutput {
if hasAll && len(cfg.Extras) > 0 {
agentPaths := collectAgentTargetPathsGlobal(cfg)
extrasEntries := runExtrasSyncEntries(cfg.Extras, func(extra config.ExtraConfig) string {
return config.ResolveExtrasSourceDir(extra, cfg.ExtrasSource, cfg.Source)
}, dryRun, force, "")
}, dryRun, force, "", agentPaths)
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, extrasEntries)
}
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr)
}
// Agent sync when kind=all or --all (after skill sync)
if kind == kindAll || hasAll {
if _, agentErr := syncAgentsGlobal(cfg, dryRun, force, jsonOutput, start); agentErr != nil && syncErr == nil {
syncErr = agentErr
}
}
if hasAll {
fmt.Println()
if extrasErr := cmdSyncExtras(rest); extrasErr != nil {
if extrasErr := cmdSyncExtras(append([]string{"-g"}, rest...)); extrasErr != nil {
ui.Warning("Extras sync: %v", extrasErr)
}
}
@@ -408,6 +439,25 @@ func backupTargetsBeforeSync(cfg *config.Config) {
ui.Success("%s -> %s", name, backupPath)
}
}
// Also backup agent targets if any exist.
backupDir, agentTargets, err := resolveGlobalAgentBackupContextFromCfg(cfg)
if err != nil || len(agentTargets) == 0 {
return
}
for _, at := range agentTargets {
entryName := at.name + "-agents"
bp, bErr := backup.CreateInDir(backupDir, entryName, at.agentPath)
if bErr != nil {
ui.Warning("Failed to backup %s: %v", entryName, bErr)
} else if bp != "" {
if !backedUp {
ui.Header("Backing up")
backedUp = true
}
ui.Success("%s -> %s", entryName, bp)
}
}
}
func syncTarget(name string, target config.TargetConfig, cfg *config.Config, dryRun, force bool) error {
@@ -766,12 +816,12 @@ func syncSymlinkMode(name string, target config.TargetConfig, source string, dry
}
func printSyncHelp() {
fmt.Println(`Usage: skillshare sync [options]
fmt.Println(`Usage: skillshare sync [agents] [options]
Sync skills from source to all configured targets.
Options:
--all Sync skills and extras
--all Sync skills, agents, and extras
--dry-run, -n Preview changes without applying
--force, -f Force sync (overwrite local changes)
--json Output results as JSON
@@ -785,6 +835,7 @@ Subcommands:
Examples:
skillshare sync Sync skills to all targets
skillshare sync --dry-run Preview sync changes
skillshare sync --all Sync skills and extras
skillshare sync -p Sync project-level skills`)
skillshare sync --all Sync skills, agents, and extras
skillshare sync -p Sync project-level skills
skillshare sync agents Sync agents only`)
}
+360
View File
@@ -0,0 +1,360 @@
package main
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"skillshare/internal/backup"
"skillshare/internal/config"
"skillshare/internal/resource"
"skillshare/internal/sync"
"skillshare/internal/ui"
)
// agentSyncStats aggregates per-target agent sync results.
type agentSyncStats struct {
linked, local, updated, pruned int
}
// syncAgentsGlobal discovers agents and syncs them to all agent-capable targets.
// Returns total stats and any error.
func syncAgentsGlobal(cfg *config.Config, dryRun, force, jsonOutput bool, start time.Time) (agentSyncStats, error) {
agentsSource := cfg.EffectiveAgentsSource()
// Check agent source exists
if _, err := os.Stat(agentsSource); err != nil {
if os.IsNotExist(err) {
if !jsonOutput {
ui.Info("No agents source directory (%s)", agentsSource)
}
return agentSyncStats{}, nil
}
return agentSyncStats{}, fmt.Errorf("cannot access agents source: %w", err)
}
// Discover agents (excludes disabled from sync)
allAgents, err := resource.AgentKind{}.Discover(agentsSource)
if err != nil {
return agentSyncStats{}, fmt.Errorf("cannot discover agents: %w", err)
}
agents := resource.ActiveAgents(allAgents)
if !jsonOutput {
ui.Header("Syncing agents")
if len(agents) == 0 {
ui.Info("No agents found in %s; pruning synced target entries only", agentsSource)
}
if dryRun {
ui.Warning("Dry run mode - no changes will be made")
}
}
// Backup agent targets before sync (non-dry-run only).
if !dryRun && !jsonOutput {
backupDir, agentTargets, _ := resolveGlobalAgentBackupContextFromCfg(cfg)
backedUp := false
for _, at := range agentTargets {
entryName := at.name + "-agents"
bp, bErr := backup.CreateInDir(backupDir, entryName, at.agentPath)
if bErr != nil {
ui.Warning("Failed to backup %s: %v", entryName, bErr)
} else if bp != "" {
if !backedUp {
ui.Header("Backing up")
backedUp = true
}
ui.Success("%s -> %s", entryName, bp)
}
}
}
// Resolve agent-capable targets: user config agents sub-key + built-in defaults
builtinAgents := config.DefaultAgentTargets()
var totals agentSyncStats
var syncErr error
var skippedTargets []string
var targetCount int
for name := range cfg.Targets {
agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name)
if agentPath == "" {
skippedTargets = append(skippedTargets, name)
continue
}
targetCount++
tc := cfg.Targets[name]
ac := tc.AgentsConfig()
filtered, filterErr := sync.FilterAgents(agents, ac.Include, ac.Exclude)
if filterErr != nil {
if !jsonOutput {
ui.Error("%s: invalid agent filter: %v", name, filterErr)
}
syncErr = fmt.Errorf("some agent targets failed to sync")
continue
}
stats, targetErr := syncAgentTarget(name, agentPath, ac.Mode, filtered, agentsSource, dryRun, force, jsonOutput)
if targetErr != nil {
syncErr = fmt.Errorf("some agent targets failed to sync")
}
totals.linked += stats.linked
totals.local += stats.local
totals.updated += stats.updated
totals.pruned += stats.pruned
}
if !jsonOutput {
ui.AgentSyncSummary(ui.AgentSyncStats{
Targets: targetCount,
Linked: totals.linked,
Local: totals.local,
Updated: totals.updated,
Pruned: totals.pruned,
Duration: time.Since(start),
})
if len(skippedTargets) > 0 {
sort.Strings(skippedTargets)
ui.Warning("%d target(s) skipped for agents (no agents path): %s",
len(skippedTargets), strings.Join(skippedTargets, ", "))
}
}
return totals, syncErr
}
// resolveAgentTargetPath returns the effective agent path for a target,
// checking user config first, then built-in defaults. Returns "" if none.
func resolveAgentTargetPath(tc config.TargetConfig, builtinAgents map[string]config.TargetConfig, name string) string {
if ac := tc.AgentsConfig(); ac.Path != "" {
return config.ExpandPath(ac.Path)
}
if builtin, ok := builtinAgents[name]; ok {
return config.ExpandPath(builtin.Path)
}
return ""
}
// syncAgentsProject syncs agents for project mode using .skillshare/agents/ as source
// and project-level target agent paths.
func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start time.Time) error {
agentsSource := filepath.Join(projectRoot, ".skillshare", "agents")
if _, err := os.Stat(agentsSource); err != nil {
if os.IsNotExist(err) {
if !jsonOutput {
ui.Info("No project agents directory (%s)", agentsSource)
}
return nil
}
return fmt.Errorf("cannot access project agents: %w", err)
}
allAgents, err := resource.AgentKind{}.Discover(agentsSource)
if err != nil {
return fmt.Errorf("cannot discover project agents: %w", err)
}
agents := resource.ActiveAgents(allAgents)
if !jsonOutput {
ui.Header("Syncing agents (project)")
if len(agents) == 0 {
ui.Info("No project agents found; pruning synced target entries only")
}
if dryRun {
ui.Warning("Dry run mode - no changes will be made")
}
}
// Load project config for target list
projCfg, loadErr := config.LoadProject(projectRoot)
if loadErr != nil {
return fmt.Errorf("cannot load project config: %w", loadErr)
}
builtinAgents := config.ProjectAgentTargets()
// Backup agent targets before sync (non-dry-run only).
if !dryRun && !jsonOutput {
backupDir := filepath.Join(projectRoot, ".skillshare", "backups")
backedUp := false
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
if agentPath == "" {
continue
}
entryName := entry.Name + "-agents"
bp, bErr := backup.CreateInDir(backupDir, entryName, agentPath)
if bErr != nil {
ui.Warning("Failed to backup %s: %v", entryName, bErr)
} else if bp != "" {
if !backedUp {
ui.Header("Backing up")
backedUp = true
}
ui.Success("%s -> %s", entryName, bp)
}
}
}
var totals agentSyncStats
var syncErr error
var skippedTargets []string
var targetCount int
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
if agentPath == "" {
skippedTargets = append(skippedTargets, entry.Name)
continue
}
targetCount++
ac := entry.AgentsConfig()
filtered, filterErr := sync.FilterAgents(agents, ac.Include, ac.Exclude)
if filterErr != nil {
if !jsonOutput {
ui.Error("%s: invalid agent filter: %v", entry.Name, filterErr)
}
syncErr = fmt.Errorf("some agent targets failed to sync")
continue
}
stats, targetErr := syncAgentTarget(entry.Name, agentPath, ac.Mode, filtered, agentsSource, dryRun, force, jsonOutput)
if targetErr != nil {
syncErr = fmt.Errorf("some agent targets failed to sync")
}
totals.linked += stats.linked
totals.local += stats.local
totals.updated += stats.updated
totals.pruned += stats.pruned
}
if !jsonOutput {
ui.AgentSyncSummary(ui.AgentSyncStats{
Targets: targetCount,
Linked: totals.linked,
Local: totals.local,
Updated: totals.updated,
Pruned: totals.pruned,
Duration: time.Since(start),
})
if len(skippedTargets) > 0 {
sort.Strings(skippedTargets)
ui.Warning("%d target(s) skipped for agents (no agents path): %s",
len(skippedTargets), strings.Join(skippedTargets, ", "))
}
}
return syncErr
}
// syncAgentTarget syncs agents to a single target directory.
// Shared by both global and project sync paths.
func syncAgentTarget(name, agentPath, modeOverride string, agents []resource.DiscoveredResource, agentsSource string, dryRun, force, jsonOutput bool) (agentSyncStats, error) {
mode := modeOverride
if mode == "" {
mode = "merge"
}
result, err := sync.SyncAgents(agents, agentsSource, agentPath, mode, dryRun, force)
if err != nil {
if !jsonOutput {
ui.Error("%s: agent sync failed: %v", name, err)
}
return agentSyncStats{}, err
}
var pruned []string
switch mode {
case "copy":
pruned, _ = sync.PruneOrphanAgentCopies(agentPath, agents, dryRun)
case "merge":
pruned, _ = sync.PruneOrphanAgentLinks(agentPath, agents, dryRun)
}
stats := agentSyncStats{
linked: len(result.Linked),
local: len(result.Skipped),
updated: len(result.Updated),
pruned: len(pruned),
}
if !jsonOutput {
reportAgentSyncResult(name, mode, stats, dryRun)
}
return stats, nil
}
// reportAgentSyncResult prints per-target agent sync status.
func reportAgentSyncResult(name, mode string, stats agentSyncStats, dryRun bool) {
if stats.linked > 0 || stats.updated > 0 || stats.pruned > 0 {
ui.Success("%s: agents %s (%d linked, %d local, %d updated, %d pruned)",
name, mode, stats.linked, stats.local, stats.updated, stats.pruned)
} else if stats.local > 0 {
ui.Success("%s: agents %s (%d local preserved)", name, mode, stats.local)
} else {
ui.Success("%s: agents %s (up to date)", name, mode)
}
}
// collectAgentTargetPathsGlobal returns the set of resolved agent target paths
// for all targets in the global config. Returns nil when agents source does not
// exist or contains no agent files (meaning no real agent sync would happen).
func collectAgentTargetPathsGlobal(cfg *config.Config) map[string]bool {
agentsSource := cfg.EffectiveAgentsSource()
if _, err := os.Stat(agentsSource); err != nil {
return nil
}
agents, err := resource.AgentKind{}.Discover(agentsSource)
if err != nil || len(agents) == 0 {
return nil
}
builtinAgents := config.DefaultAgentTargets()
paths := make(map[string]bool)
for name := range cfg.Targets {
agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name)
if agentPath != "" {
paths[filepath.Clean(agentPath)] = true
}
}
if len(paths) == 0 {
return nil
}
return paths
}
// collectAgentTargetPathsProject returns the set of resolved agent target paths
// for all targets in the project config. Returns nil when no agents exist.
func collectAgentTargetPathsProject(projectRoot string) map[string]bool {
agentsSource := filepath.Join(projectRoot, ".skillshare", "agents")
if _, err := os.Stat(agentsSource); err != nil {
return nil
}
agents, err := resource.AgentKind{}.Discover(agentsSource)
if err != nil || len(agents) == 0 {
return nil
}
projCfg, err := config.LoadProject(projectRoot)
if err != nil {
return nil
}
builtinAgents := config.ProjectAgentTargets()
paths := make(map[string]bool)
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
if agentPath != "" {
paths[filepath.Clean(agentPath)] = true
}
}
if len(paths) == 0 {
return nil
}
return paths
}
+103 -23
View File
@@ -13,6 +13,9 @@ import (
"skillshare/internal/ui"
)
// extrasAgentsName is the extras entry name that may overlap with the agents sync system.
const extrasAgentsName = "agents"
type syncExtrasJSONOutput struct {
Extras []syncExtrasJSONEntry `json:"extras"`
Duration string `json:"duration"`
@@ -24,13 +27,14 @@ type syncExtrasJSONEntry struct {
}
type syncExtrasJSONTarget struct {
Path string `json:"path"`
Mode string `json:"mode"`
Synced int `json:"synced"`
Skipped int `json:"skipped"`
Pruned int `json:"pruned"`
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Path string `json:"path"`
Mode string `json:"mode"`
Synced int `json:"synced"`
Skipped int `json:"skipped"`
Pruned int `json:"pruned"`
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"`
SkippedBy string `json:"skipped_by,omitempty"`
}
func cmdSyncExtras(args []string) error {
@@ -99,11 +103,20 @@ func cmdSyncExtrasGlobal(dryRun, force, jsonOutput bool, start time.Time) error
ui.Warning("Dry run mode - no changes will be made")
}
var totalSynced, totalSkipped, totalPruned, totalErrors int
// Detect overlap between extras "agents" and the agents sync system
var agentTargetPaths map[string]bool
for _, extra := range cfg.Extras {
if extra.Name == extrasAgentsName {
agentTargetPaths = collectAgentTargetPathsGlobal(cfg)
break
}
}
var totalSynced, totalSkipped, totalPruned, totalErrors, totalTargets int
var jsonEntries []syncExtrasJSONEntry
if !jsonOutput {
ui.Header(ui.WithModeLabel("Sync Extras"))
ui.Header(ui.WithModeLabel("Syncing extras"))
}
for _, extra := range cfg.Extras {
@@ -128,11 +141,24 @@ func cmdSyncExtrasGlobal(dryRun, force, jsonOutput bool, start time.Time) error
jsonEntry := syncExtrasJSONEntry{Name: extra.Name}
for _, target := range extra.Targets {
totalTargets++
mode := target.Mode
if mode == "" {
mode = "merge"
}
targetPath := config.ExpandPath(target.Path)
// Skip extras "agents" targets that overlap with the agents sync system
if extra.Name == extrasAgentsName && isExtrasTargetOverlappingAgents(targetPath, agentTargetPaths) {
if !jsonOutput {
ui.Warning("Skipping extras %q target %s — already managed by agents sync", extra.Name, shortenPath(targetPath))
}
jsonEntry.Targets = append(jsonEntry.Targets, syncExtrasJSONTarget{
Path: target.Path, Mode: mode, SkippedBy: extrasAgentsName,
})
continue
}
result, syncErr := sync.SyncExtra(extraSource, targetPath, mode, dryRun, force, target.Flatten, "")
shortTarget := shortenPath(targetPath)
@@ -143,7 +169,7 @@ func cmdSyncExtrasGlobal(dryRun, force, jsonOutput bool, start time.Time) error
if syncErr != nil {
if !jsonOutput {
ui.Warning(" %s: %v", shortTarget, syncErr)
ui.Warning("%s: %v", shortTarget, syncErr)
}
jsonTarget.Error = syncErr.Error()
jsonEntry.Targets = append(jsonEntry.Targets, jsonTarget)
@@ -173,11 +199,11 @@ func cmdSyncExtrasGlobal(dryRun, force, jsonOutput bool, start time.Time) error
if result.Pruned > 0 {
parts = append(parts, fmt.Sprintf("%d pruned", result.Pruned))
}
ui.Success(" %s %s (%s)", shortTarget, strings.Join(parts, ", "), mode)
ui.Success("%s %s (%s)", shortTarget, strings.Join(parts, ", "), mode)
} else if result.Skipped > 0 {
ui.Warning(" %s %d files skipped (use --force to override)", shortTarget, result.Skipped)
ui.Warning("%s %d files skipped (use --force to override)", shortTarget, result.Skipped)
} else {
ui.Success(" %s up to date (%s)", shortTarget, mode)
ui.Success("%s up to date (%s)", shortTarget, mode)
}
for _, e := range result.Errors {
@@ -217,6 +243,14 @@ func cmdSyncExtrasGlobal(dryRun, force, jsonOutput bool, start time.Time) error
return writeJSON(&output)
}
ui.ExtrasSyncSummary(ui.ExtrasSyncStats{
Targets: totalTargets,
Synced: totalSynced,
Skipped: totalSkipped,
Pruned: totalPruned,
Duration: time.Since(start),
})
if totalErrors > 0 {
return fmt.Errorf("%d extras sync error(s)", totalErrors)
}
@@ -245,11 +279,20 @@ func cmdSyncExtrasProject(cwd string, dryRun, force, jsonOutput bool, start time
ui.Warning("Dry run mode - no changes will be made")
}
var totalSynced, totalSkipped, totalPruned, totalErrors int
// Detect overlap between extras "agents" and the agents sync system
var agentTargetPaths map[string]bool
for _, extra := range projCfg.Extras {
if extra.Name == extrasAgentsName {
agentTargetPaths = collectAgentTargetPathsProject(cwd)
break
}
}
var totalSynced, totalSkipped, totalPruned, totalErrors, totalTargets int
var jsonEntries []syncExtrasJSONEntry
if !jsonOutput {
ui.Header(ui.WithModeLabel("Sync Extras"))
ui.Header(ui.WithModeLabel("Syncing extras"))
}
for _, extra := range projCfg.Extras {
@@ -269,15 +312,24 @@ func cmdSyncExtrasProject(cwd string, dryRun, force, jsonOutput bool, start time
jsonEntry := syncExtrasJSONEntry{Name: extra.Name}
for _, target := range extra.Targets {
totalTargets++
mode := target.Mode
if mode == "" {
mode = "merge"
}
// Expand ~ and resolve relative paths against project root
targetPath := config.ExpandPath(target.Path)
if !filepath.IsAbs(targetPath) {
targetPath = filepath.Join(cwd, targetPath)
targetPath := resolveProjectPath(cwd, target.Path)
// Skip extras "agents" targets that overlap with the agents sync system
if extra.Name == extrasAgentsName && isExtrasTargetOverlappingAgents(targetPath, agentTargetPaths) {
if !jsonOutput {
ui.Warning("Skipping extras %q target %s — already managed by agents sync", extra.Name, shortenPath(targetPath))
}
jsonEntry.Targets = append(jsonEntry.Targets, syncExtrasJSONTarget{
Path: target.Path, Mode: mode, SkippedBy: extrasAgentsName,
})
continue
}
result, syncErr := sync.SyncExtra(extraSource, targetPath, mode, dryRun, force, target.Flatten, cwd)
@@ -290,7 +342,7 @@ func cmdSyncExtrasProject(cwd string, dryRun, force, jsonOutput bool, start time
if syncErr != nil {
if !jsonOutput {
ui.Warning(" %s: %v", shortTarget, syncErr)
ui.Warning("%s: %v", shortTarget, syncErr)
}
jsonTarget.Error = syncErr.Error()
jsonEntry.Targets = append(jsonEntry.Targets, jsonTarget)
@@ -319,11 +371,11 @@ func cmdSyncExtrasProject(cwd string, dryRun, force, jsonOutput bool, start time
if result.Pruned > 0 {
parts = append(parts, fmt.Sprintf("%d pruned", result.Pruned))
}
ui.Success(" %s %s (%s)", shortTarget, strings.Join(parts, ", "), mode)
ui.Success("%s %s (%s)", shortTarget, strings.Join(parts, ", "), mode)
} else if result.Skipped > 0 {
ui.Warning(" %s %d files skipped (use --force to override)", shortTarget, result.Skipped)
ui.Warning("%s %d files skipped (use --force to override)", shortTarget, result.Skipped)
} else {
ui.Success(" %s up to date (%s)", shortTarget, mode)
ui.Success("%s up to date (%s)", shortTarget, mode)
}
for _, e := range result.Errors {
@@ -363,6 +415,14 @@ func cmdSyncExtrasProject(cwd string, dryRun, force, jsonOutput bool, start time
return writeJSON(&output)
}
ui.ExtrasSyncSummary(ui.ExtrasSyncStats{
Targets: totalTargets,
Synced: totalSynced,
Skipped: totalSkipped,
Pruned: totalPruned,
Duration: time.Since(start),
})
if totalErrors > 0 {
return fmt.Errorf("%d extras sync error(s)", totalErrors)
}
@@ -383,7 +443,8 @@ func syncVerb(mode string) string {
// runExtrasSync runs extras sync and returns JSON entries without printing.
// Used by sync --all --json to merge extras into the skills JSON output.
func runExtrasSyncEntries(extras []config.ExtraConfig, sourceFunc func(config.ExtraConfig) string, dryRun, force bool, projectRoot string) []syncExtrasJSONEntry {
// agentTargetPaths is used to skip extras "agents" targets that overlap with the agents sync system.
func runExtrasSyncEntries(extras []config.ExtraConfig, sourceFunc func(config.ExtraConfig) string, dryRun, force bool, projectRoot string, agentTargetPaths map[string]bool) []syncExtrasJSONEntry {
entries := make([]syncExtrasJSONEntry, 0, len(extras))
for _, extra := range extras {
extraSource := sourceFunc(extra)
@@ -401,6 +462,16 @@ func runExtrasSyncEntries(extras []config.ExtraConfig, sourceFunc func(config.Ex
mode = "merge"
}
targetPath := config.ExpandPath(target.Path)
if projectRoot != "" {
targetPath = resolveProjectPath(projectRoot, target.Path)
}
if extra.Name == extrasAgentsName && isExtrasTargetOverlappingAgents(targetPath, agentTargetPaths) {
entry.Targets = append(entry.Targets, syncExtrasJSONTarget{
Path: targetPath, Mode: mode, SkippedBy: extrasAgentsName,
})
continue
}
result, syncErr := sync.SyncExtra(extraSource, targetPath, mode, dryRun, force, target.Flatten, projectRoot)
jt := syncExtrasJSONTarget{Path: targetPath, Mode: mode}
@@ -423,6 +494,15 @@ func runExtrasSyncEntries(extras []config.ExtraConfig, sourceFunc func(config.Ex
return entries
}
// isExtrasTargetOverlappingAgents checks whether an extras target path overlaps
// with any active agent target path.
func isExtrasTargetOverlappingAgents(targetPath string, agentPaths map[string]bool) bool {
if len(agentPaths) == 0 {
return false
}
return agentPaths[filepath.Clean(targetPath)]
}
// cachedHome caches the home directory for shortenPath.
var cachedHome = func() string {
h, _ := os.UserHomeDir()
+163 -45
View File
@@ -11,6 +11,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/oplog"
"skillshare/internal/sync"
"skillshare/internal/targetsummary"
"skillshare/internal/ui"
"skillshare/internal/utils"
"skillshare/internal/validate"
@@ -113,11 +114,16 @@ Options:
Target Settings:
<name> --mode <mode> Set sync mode (merge, symlink, or copy)
<name> --agent-mode <mode> Set agents sync mode (merge, symlink, or copy)
<name> --target-naming <naming> Set target naming (flat or standard)
<name> --add-include <pattern> Add an include filter pattern
<name> --add-exclude <pattern> Add an exclude filter pattern
<name> --remove-include <pattern> Remove an include filter pattern
<name> --remove-exclude <pattern> Remove an exclude filter pattern
<name> --add-agent-include <pattern> Add an agent include filter pattern
<name> --add-agent-exclude <pattern> Add an agent exclude filter pattern
<name> --remove-agent-include <pattern> Remove an agent include filter pattern
<name> --remove-agent-exclude <pattern> Remove an agent exclude filter pattern
Examples:
skillshare target add cursor
@@ -125,7 +131,9 @@ Examples:
skillshare target remove cursor
skillshare target list
skillshare target cursor
skillshare target claude --agent-mode copy
skillshare target claude --add-include "team-*"
skillshare target claude --add-agent-include "team-*"
skillshare target claude --remove-include "team-*"
skillshare target claude --add-exclude "_legacy*"
@@ -257,6 +265,28 @@ func backupTargets(cfg *config.Config, toRemove []string) {
ui.Success("%s -> %s", targetName, backupPath)
}
}
// Also backup agent directories for targets being removed.
backupDir, agentTargets, err := resolveGlobalAgentBackupContextFromCfg(cfg)
if err != nil || len(agentTargets) == 0 {
return
}
removeSet := make(map[string]struct{}, len(toRemove))
for _, name := range toRemove {
removeSet[name] = struct{}{}
}
for _, at := range agentTargets {
if _, ok := removeSet[at.name]; !ok {
continue
}
entryName := at.name + "-agents"
bp, bErr := backup.CreateInDir(backupDir, entryName, at.agentPath)
if bErr != nil {
ui.Warning("Failed to backup %s: %v", entryName, bErr)
} else if bp != "" {
ui.Success("%s -> %s", entryName, bp)
}
}
}
// unlinkTarget unlinks a single target
@@ -412,11 +442,17 @@ func unlinkMergeMode(targetPath, sourcePath string) error {
// targetListJSONItem is the JSON representation for a single target.
type targetListJSONItem struct {
Name string `json:"name"`
Path string `json:"path"`
Mode string `json:"mode"`
Include []string `json:"include"`
Exclude []string `json:"exclude"`
Name string `json:"name"`
Path string `json:"path"`
Mode string `json:"mode"`
Include []string `json:"include"`
Exclude []string `json:"exclude"`
AgentPath string `json:"agentPath,omitempty"`
AgentMode string `json:"agentMode,omitempty"`
AgentInclude []string `json:"agentInclude,omitempty"`
AgentExclude []string `json:"agentExclude,omitempty"`
AgentLinkedCount *int `json:"agentLinkedCount,omitempty"`
AgentExpectedCount *int `json:"agentExpectedCount,omitempty"`
}
func targetList(jsonOutput bool) error {
@@ -429,30 +465,39 @@ func targetList(jsonOutput bool) error {
return targetListJSON(cfg)
}
ui.Header("Configured Targets")
for name, target := range cfg.Targets {
sc := target.SkillsConfig()
mode := sc.Mode
if mode == "" {
mode = "merge"
}
fmt.Printf(" %-12s %s (%s)\n", name, sc.Path, mode)
items, err := buildTargetTUIItems(false, "")
if err != nil {
return err
}
ui.Header("Configured Targets")
printTargetListPlain(items)
return nil
}
func targetListJSON(cfg *config.Config) error {
agentBuilder, err := targetsummary.NewGlobalBuilder(cfg)
if err != nil {
return err
}
var items []targetListJSONItem
for name, target := range cfg.Targets {
sc := target.SkillsConfig()
items = append(items, targetListJSONItem{
item := targetListJSONItem{
Name: name,
Path: sc.Path,
Mode: getTargetMode(sc.Mode, cfg.Mode),
Include: sc.Include,
Exclude: sc.Exclude,
})
}
agentSummary, err := agentBuilder.GlobalTarget(name, target)
if err != nil {
return err
}
applyTargetListAgentSummary(&item, agentSummary)
items = append(items, item)
}
output := struct {
Targets []targetListJSONItem `json:"targets"`
@@ -466,6 +511,10 @@ func targetInfo(name string, args []string) error {
if err != nil {
return err
}
settings, err := parseTargetSettingFlags(remaining)
if err != nil {
return err
}
cfg, err := config.Load()
if err != nil {
@@ -477,36 +526,59 @@ func targetInfo(name string, args []string) error {
return fmt.Errorf("target '%s' not found. Use 'skillshare target list' to see available targets", name)
}
// Parse --mode and --target-naming from remaining args
var newMode, newNaming string
for i := 0; i < len(remaining); i++ {
switch remaining[i] {
case "--mode", "-m":
if i+1 >= len(remaining) {
return fmt.Errorf("--mode requires a value (merge, symlink, or copy)")
}
newMode = remaining[i+1]
i++
case "--target-naming":
if i+1 >= len(remaining) {
return fmt.Errorf("--target-naming requires a value (flat or standard)")
}
newNaming = remaining[i+1]
i++
}
}
// Apply filter updates if any
if filterOpts.hasUpdates() {
start := time.Now()
s := target.EnsureSkills()
changes, fErr := applyFilterUpdates(&s.Include, &s.Exclude, filterOpts)
if fErr != nil {
return fErr
var changes []string
mutated := false
if filterOpts.Skills.hasUpdates() {
s := target.EnsureSkills()
skillChanges, fErr := applyFilterUpdates(&s.Include, &s.Exclude, filterOpts.Skills)
if fErr != nil {
return fErr
}
changes = append(changes, skillChanges...)
mutated = true
}
cfg.Targets[name] = target
if err := cfg.Save(); err != nil {
return err
if filterOpts.Agents.hasUpdates() {
agentBuilder, buildErr := targetsummary.NewGlobalBuilder(cfg)
if buildErr != nil {
return buildErr
}
agentSummary, buildErr := agentBuilder.GlobalTarget(name, target)
if buildErr != nil {
return buildErr
}
if agentSummary == nil {
return fmt.Errorf("target '%s' does not have an agents path", name)
}
if agentSummary.Mode == "symlink" {
return fmt.Errorf("target '%s' agent include/exclude filters are ignored in symlink mode; use --agent-mode merge or --agent-mode copy first", name)
}
ac := target.AgentsConfig()
include := append([]string(nil), ac.Include...)
exclude := append([]string(nil), ac.Exclude...)
agentChanges, fErr := applyFilterUpdates(&include, &exclude, filterOpts.Agents)
if fErr != nil {
return fErr
}
if len(agentChanges) > 0 {
a := target.EnsureAgents()
a.Include = include
a.Exclude = exclude
mutated = true
}
changes = append(changes, scopeFilterChanges("agents", agentChanges)...)
}
if mutated {
cfg.Targets[name] = target
if err := cfg.Save(); err != nil {
return err
}
}
for _, change := range changes {
ui.Success("%s: %s", name, change)
@@ -526,13 +598,17 @@ func targetInfo(name string, args []string) error {
}
// If --mode is provided, update the mode
if newMode != "" {
return updateTargetMode(cfg, name, target, newMode)
if settings.SkillMode != "" {
return updateTargetMode(cfg, name, target, settings.SkillMode)
}
if settings.AgentMode != "" {
return updateTargetAgentMode(cfg, name, target, settings.AgentMode)
}
// If --target-naming is provided, update the naming
if newNaming != "" {
return updateTargetNaming(cfg, name, target, newNaming)
if settings.Naming != "" {
return updateTargetNaming(cfg, name, target, settings.Naming)
}
// Show target info
@@ -564,6 +640,38 @@ func updateTargetMode(cfg *config.Config, name string, target config.TargetConfi
return nil
}
func updateTargetAgentMode(cfg *config.Config, name string, target config.TargetConfig, newMode string) error {
if newMode != "merge" && newMode != "symlink" && newMode != "copy" {
return fmt.Errorf("invalid agent mode '%s'. Use 'merge', 'symlink', or 'copy'", newMode)
}
agentBuilder, err := targetsummary.NewGlobalBuilder(cfg)
if err != nil {
return err
}
agentSummary, err := agentBuilder.GlobalTarget(name, target)
if err != nil {
return err
}
if agentSummary == nil {
return fmt.Errorf("target '%s' does not have an agents path", name)
}
oldMode := agentSummary.Mode
target.EnsureAgents().Mode = newMode
cfg.Targets[name] = target
if err := cfg.Save(); err != nil {
return err
}
ui.Success("Changed %s agent mode: %s -> %s", name, oldMode, newMode)
if newMode == "symlink" && (len(agentSummary.Include) > 0 || len(agentSummary.Exclude) > 0) {
ui.Warning("Agent include/exclude filters are ignored in symlink mode")
}
ui.Info("Run 'skillshare sync' to apply the new mode")
return nil
}
func updateTargetNaming(cfg *config.Config, name string, target config.TargetConfig, newNaming string) error {
if !config.IsValidTargetNaming(newNaming) {
return fmt.Errorf("invalid target naming '%s'. Use 'flat' or 'standard'", newNaming)
@@ -614,6 +722,15 @@ func showTargetInfo(cfg *config.Config, name string, target config.TargetConfig)
namingDisplay += " (default)"
}
agentBuilder, err := targetsummary.NewGlobalBuilder(cfg)
if err != nil {
return err
}
agentSummary, err := agentBuilder.GlobalTarget(name, target)
if err != nil {
return err
}
ui.Header(fmt.Sprintf("Target: %s", name))
fmt.Printf(" Path: %s\n", sc.Path)
fmt.Printf(" Mode: %s\n", modeDisplay)
@@ -621,6 +738,7 @@ func showTargetInfo(cfg *config.Config, name string, target config.TargetConfig)
fmt.Printf(" Status: %s\n", statusLine)
fmt.Printf(" Include: %s\n", formatFilterList(sc.Include))
fmt.Printf(" Exclude: %s\n", formatFilterList(sc.Exclude))
printTargetAgentSection(agentSummary)
return nil
}
+122
View File
@@ -0,0 +1,122 @@
package main
import (
"fmt"
"skillshare/internal/config"
"skillshare/internal/sync"
"skillshare/internal/targetsummary"
)
func applyTargetListAgentSummary(item *targetListJSONItem, summary *targetsummary.AgentSummary) {
if summary == nil {
return
}
item.AgentPath = summary.Path
item.AgentMode = summary.Mode
item.AgentInclude = append([]string(nil), summary.Include...)
item.AgentExclude = append([]string(nil), summary.Exclude...)
item.AgentLinkedCount = intPtr(summary.ManagedCount)
item.AgentExpectedCount = intPtr(summary.ExpectedCount)
}
func printTargetAgentSection(summary *targetsummary.AgentSummary) {
if summary == nil {
return
}
displayPath := summary.DisplayPath
if displayPath == "" {
displayPath = summary.Path
}
fmt.Println(" Agents:")
fmt.Printf(" Path: %s\n", displayPath)
fmt.Printf(" Mode: %s\n", summary.Mode)
fmt.Printf(" Status: %s\n", formatTargetAgentSyncSummary(summary))
if summary.Mode == "symlink" {
fmt.Println(" Filters: ignored in symlink mode")
return
}
fmt.Printf(" Include: %s\n", formatFilterList(summary.Include))
fmt.Printf(" Exclude: %s\n", formatFilterList(summary.Exclude))
}
func printTargetListPlain(items []targetTUIItem) {
for idx, item := range items {
if idx > 0 {
fmt.Println()
}
sc := item.target.SkillsConfig()
displayPath := item.displayPath
if displayPath == "" {
displayPath = sc.Path
}
fmt.Printf(" %s\n", item.name)
fmt.Println(" Skills:")
fmt.Printf(" Path: %s\n", displayPath)
fmt.Printf(" Mode: %s\n", sync.EffectiveMode(sc.Mode))
fmt.Printf(" Naming: %s\n", config.EffectiveTargetNaming(sc.TargetNaming))
fmt.Printf(" Sync: %s\n", item.skillSync)
if len(sc.Include) == 0 && len(sc.Exclude) == 0 {
fmt.Println(" No include/exclude filters")
} else {
fmt.Printf(" Include: %s\n", formatFilterList(sc.Include))
fmt.Printf(" Exclude: %s\n", formatFilterList(sc.Exclude))
}
if item.agentSummary == nil {
continue
}
agentPath := item.agentSummary.DisplayPath
if agentPath == "" {
agentPath = item.agentSummary.Path
}
fmt.Println(" Agents:")
fmt.Printf(" Path: %s\n", agentPath)
fmt.Printf(" Mode: %s\n", item.agentSummary.Mode)
fmt.Printf(" Sync: %s\n", formatTargetAgentSyncSummary(item.agentSummary))
if item.agentSummary.Mode == "symlink" {
fmt.Println(" Filters: ignored in symlink mode")
} else if len(item.agentSummary.Include) == 0 && len(item.agentSummary.Exclude) == 0 {
fmt.Println(" No agent include/exclude filters")
} else {
fmt.Printf(" Include: %s\n", formatFilterList(item.agentSummary.Include))
fmt.Printf(" Exclude: %s\n", formatFilterList(item.agentSummary.Exclude))
}
}
}
func formatTargetAgentSyncSummary(summary *targetsummary.AgentSummary) string {
if summary == nil {
return ""
}
if summary.ExpectedCount == 0 {
if summary.ManagedCount > 0 {
return fmt.Sprintf("no source agents yet (%d %s)", summary.ManagedCount, targetAgentCountLabel(summary.Mode))
}
return "no source agents yet"
}
summaryText := fmt.Sprintf("%d/%d %s", summary.ManagedCount, summary.ExpectedCount, targetAgentCountLabel(summary.Mode))
if summary.Mode == "symlink" {
return summaryText + " (directory symlink)"
}
return summaryText
}
func targetAgentCountLabel(mode string) string {
if mode == "copy" {
return "managed"
}
return "linked"
}
func intPtr(v int) *int {
return &v
}
+458
View File
@@ -0,0 +1,458 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/config"
"skillshare/internal/targetsummary"
"skillshare/internal/testutil"
)
func TestShowTargetInfo_ShowsAgentsSectionForBuiltinTarget(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
targetPath := sb.CreateTarget("claude")
writeGlobalTargetConfig(t, sb, "claude", targetPath, "")
cfg, err := config.Load()
if err != nil {
t.Fatalf("load config: %v", err)
}
agentSource := cfg.EffectiveAgentsSource()
agentFile := writeAgentFile(t, agentSource, "reviewer.md")
agentTarget := filepath.Join(sb.Home, ".claude", "agents")
linkAgentFile(t, agentTarget, "reviewer.md", agentFile)
output := stripANSIWarnings(captureStdout(t, func() {
if err := showTargetInfo(cfg, "claude", cfg.Targets["claude"]); err != nil {
t.Fatalf("showTargetInfo: %v", err)
}
}))
if !strings.Contains(output, "Agents:") {
t.Fatalf("expected agents section in output:\n%s", output)
}
if !strings.Contains(output, agentTarget) {
t.Fatalf("expected agent path %q in output:\n%s", agentTarget, output)
}
if !strings.Contains(output, "1/1 linked") {
t.Fatalf("expected linked summary in output:\n%s", output)
}
}
func TestShowTargetInfo_OmitsAgentsSectionWhenTargetHasNoAgentsPath(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
targetPath := filepath.Join(sb.Root, "custom-skills")
if err := os.MkdirAll(targetPath, 0755); err != nil {
t.Fatalf("mkdir target: %v", err)
}
writeGlobalTargetConfig(t, sb, "custom-tool", targetPath, "")
cfg, err := config.Load()
if err != nil {
t.Fatalf("load config: %v", err)
}
output := stripANSIWarnings(captureStdout(t, func() {
if err := showTargetInfo(cfg, "custom-tool", cfg.Targets["custom-tool"]); err != nil {
t.Fatalf("showTargetInfo: %v", err)
}
}))
if strings.Contains(output, "Agents:") {
t.Fatalf("did not expect agents section:\n%s", output)
}
}
func TestTargetListJSON_IncludesAgentMetadata(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
targetPath := sb.CreateTarget("claude")
writeGlobalTargetConfig(t, sb, "claude", targetPath, "")
cfg, err := config.Load()
if err != nil {
t.Fatalf("load config: %v", err)
}
agentSource := cfg.EffectiveAgentsSource()
agentFile := writeAgentFile(t, agentSource, "reviewer.md")
agentTarget := filepath.Join(sb.Home, ".claude", "agents")
linkAgentFile(t, agentTarget, "reviewer.md", agentFile)
output := captureStdout(t, func() {
if err := targetListJSON(cfg); err != nil {
t.Fatalf("targetListJSON: %v", err)
}
})
var resp struct {
Targets []targetListJSONItem `json:"targets"`
}
if err := json.Unmarshal([]byte(output), &resp); err != nil {
t.Fatalf("decode json: %v\n%s", err, output)
}
if len(resp.Targets) != 1 {
t.Fatalf("expected 1 target, got %d", len(resp.Targets))
}
target := resp.Targets[0]
if target.AgentPath != agentTarget {
t.Fatalf("agent path = %q, want %q", target.AgentPath, agentTarget)
}
if target.AgentMode != "merge" {
t.Fatalf("agent mode = %q, want merge", target.AgentMode)
}
if target.AgentLinkedCount == nil || *target.AgentLinkedCount != 1 {
t.Fatalf("agent linked = %v, want 1", target.AgentLinkedCount)
}
if target.AgentExpectedCount == nil || *target.AgentExpectedCount != 1 {
t.Fatalf("agent expected = %v, want 1", target.AgentExpectedCount)
}
}
func TestTargetList_TextOutputShowsSkillsAndAgentsSections(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
targetPath := sb.CreateTarget("claude")
writeGlobalTargetConfig(t, sb, "claude", targetPath, "")
cfg, err := config.Load()
if err != nil {
t.Fatalf("load config: %v", err)
}
agentSource := cfg.EffectiveAgentsSource()
agentFile := writeAgentFile(t, agentSource, "reviewer.md")
agentTarget := filepath.Join(sb.Home, ".claude", "agents")
linkAgentFile(t, agentTarget, "reviewer.md", agentFile)
output := stripANSIWarnings(captureStdout(t, func() {
if err := targetList(false); err != nil {
t.Fatalf("targetList: %v", err)
}
}))
for _, want := range []string{
"claude",
"Skills:",
targetPath,
"Sync:",
"Agents:",
agentTarget,
"1/1 linked",
"No include/exclude filters",
"No agent include/exclude filters",
} {
if !strings.Contains(output, want) {
t.Fatalf("expected %q in target list output:\n%s", want, output)
}
}
}
func TestRenderTargetDetail_AgentSection(t *testing.T) {
cases := []struct {
name string
item targetTUIItem
want []string
notContains []string
}{
{
name: "merge target shows builtin-like agents section",
item: targetTUIItem{
name: "cursor",
displayPath: ".cursor/skills",
skillSync: "merged (4 shared, 1 local)",
target: config.TargetConfig{
Skills: &config.ResourceTargetConfig{
Path: "/tmp/cursor/skills",
Mode: "merge",
TargetNaming: "flat",
},
},
agentSummary: &targetsummary.AgentSummary{
DisplayPath: ".cursor/agents",
Path: "/tmp/cursor/agents",
Mode: "merge",
ManagedCount: 2,
ExpectedCount: 3,
Include: []string{"team-*"},
},
},
want: []string{"Skills:", ".cursor/skills", "Sync:", "merged (4 shared, 1 local)", "Agents:", ".cursor/agents", "2/3 linked", "Agent Include:", "team-*"},
},
{
name: "copy target shows custom agents section",
item: targetTUIItem{
name: "custom",
displayPath: "/tmp/custom/skills",
skillSync: "copied (2 managed, 0 local)",
target: config.TargetConfig{
Skills: &config.ResourceTargetConfig{
Path: "/tmp/custom/skills",
Mode: "copy",
TargetNaming: "flat",
},
},
agentSummary: &targetsummary.AgentSummary{
DisplayPath: "/tmp/custom/agents",
Path: "/tmp/custom/agents",
Mode: "copy",
ManagedCount: 2,
ExpectedCount: 2,
},
},
want: []string{"Skills:", "/tmp/custom/skills", "Sync:", "copied (2 managed, 0 local)", "Agents:", "/tmp/custom/agents", "2/2 managed", "No agent include/exclude filters"},
},
{
name: "symlink agent target shows filters ignored warning",
item: targetTUIItem{
name: "claude",
displayPath: ".claude/skills",
skillSync: "merged (7 shared, 0 local)",
target: config.TargetConfig{
Skills: &config.ResourceTargetConfig{
Path: "/tmp/claude/skills",
Mode: "merge",
TargetNaming: "flat",
},
},
agentSummary: &targetsummary.AgentSummary{
DisplayPath: ".claude/agents",
Path: "/tmp/claude/agents",
Mode: "symlink",
ManagedCount: 5,
ExpectedCount: 5,
Include: []string{"team-*"},
Exclude: []string{"draft-*"},
},
},
want: []string{"Agents:", ".claude/agents", "5/5 linked (directory symlink)", "Agent include/exclude filters ignored in symlink mode"},
notContains: []string{"Agent Include:", "Agent Exclude:", "No agent include/exclude filters"},
},
{
name: "unsupported target omits agents section",
item: targetTUIItem{
name: "custom-tool",
displayPath: "/tmp/custom-tool/skills",
skillSync: "not exist (0 shared, 0 local)",
target: config.TargetConfig{
Skills: &config.ResourceTargetConfig{
Path: "/tmp/custom-tool/skills",
Mode: "merge",
TargetNaming: "flat",
},
},
},
want: []string{"Skills:", "/tmp/custom-tool/skills", "Sync:", "not exist (0 shared, 0 local)"},
notContains: []string{"Agents:", "No agent include/exclude filters"},
},
}
model := targetListTUIModel{}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rendered := stripANSIWarnings(model.renderTargetDetail(tc.item))
for _, want := range tc.want {
if !strings.Contains(rendered, want) {
t.Fatalf("expected %q in output:\n%s", want, rendered)
}
}
for _, unwanted := range tc.notContains {
if strings.Contains(rendered, unwanted) {
t.Fatalf("did not expect %q in output:\n%s", unwanted, rendered)
}
}
})
}
}
func TestTargetScopeOptions_DisablesAgentFiltersInSymlinkMode(t *testing.T) {
item := targetTUIItem{
name: "claude",
agentSummary: &targetsummary.AgentSummary{
Mode: "symlink",
},
}
options := targetScopeOptions(item, "include")
if len(options) != 2 {
t.Fatalf("expected 2 scope options, got %d", len(options))
}
if !options[0].enabled || options[0].scope != "skills" {
t.Fatalf("expected skills option enabled, got %+v", options[0])
}
if options[1].scope != "agents" || options[1].enabled {
t.Fatalf("expected agents option disabled, got %+v", options[1])
}
if options[1].disabled != "ignored in symlink mode" {
t.Fatalf("unexpected disabled reason: %+v", options[1])
}
if got := moveScopePickerCursor(options, 0, 1); got != 0 {
t.Fatalf("cursor should stay on skills when agents is disabled, got %d", got)
}
}
func TestDoSetTargetMode_Agents_GlobalAndProject(t *testing.T) {
t.Run("global", func(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
targetPath := sb.CreateTarget("claude")
writeGlobalTargetConfig(t, sb, "claude", targetPath, "")
model := targetListTUIModel{}
if _, err := model.doSetTargetMode("claude", "agents", "copy"); err != nil {
t.Fatalf("doSetTargetMode: %v", err)
}
cfg, err := config.Load()
if err != nil {
t.Fatalf("load config: %v", err)
}
target := cfg.Targets["claude"]
if got := target.AgentsConfig().Mode; got != "copy" {
t.Fatalf("agent mode = %q, want copy", got)
}
})
t.Run("project", func(t *testing.T) {
root := writeProjectTargetConfig(t, []config.ProjectTargetEntry{{Name: "claude"}})
model := targetListTUIModel{
projCfg: &config.ProjectConfig{},
cwd: root,
}
if _, err := model.doSetTargetMode("claude", "agents", "copy"); err != nil {
t.Fatalf("doSetTargetMode: %v", err)
}
cfg, err := config.LoadProject(root)
if err != nil {
t.Fatalf("load project config: %v", err)
}
if got := cfg.Targets[0].AgentsConfig().Mode; got != "copy" {
t.Fatalf("project agent mode = %q, want copy", got)
}
})
}
func TestDoAddAndRemovePattern_Agents_GlobalAndProject(t *testing.T) {
t.Run("global", func(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
targetPath := sb.CreateTarget("claude")
writeGlobalTargetConfig(t, sb, "claude", targetPath, "")
model := targetListTUIModel{}
if _, err := model.doAddPattern("claude", "agents", "include", "team-*"); err != nil {
t.Fatalf("doAddPattern: %v", err)
}
if _, err := model.doRemovePattern("claude", "agents", "include", "team-*"); err != nil {
t.Fatalf("doRemovePattern: %v", err)
}
cfg, err := config.Load()
if err != nil {
t.Fatalf("load config: %v", err)
}
target := cfg.Targets["claude"]
if got := target.AgentsConfig().Include; len(got) != 0 {
t.Fatalf("agent include = %v, want empty", got)
}
})
t.Run("project", func(t *testing.T) {
root := writeProjectTargetConfig(t, []config.ProjectTargetEntry{{Name: "claude"}})
model := targetListTUIModel{
projCfg: &config.ProjectConfig{},
cwd: root,
}
if _, err := model.doAddPattern("claude", "agents", "exclude", "draft-*"); err != nil {
t.Fatalf("doAddPattern: %v", err)
}
if _, err := model.doRemovePattern("claude", "agents", "exclude", "draft-*"); err != nil {
t.Fatalf("doRemovePattern: %v", err)
}
cfg, err := config.LoadProject(root)
if err != nil {
t.Fatalf("load project config: %v", err)
}
if got := cfg.Targets[0].AgentsConfig().Exclude; len(got) != 0 {
t.Fatalf("project agent exclude = %v, want empty", got)
}
})
}
func writeGlobalTargetConfig(t *testing.T, sb *testutil.Sandbox, name, skillsPath, agentPath string) {
t.Helper()
var b strings.Builder
b.WriteString("source: " + sb.SourcePath + "\n")
b.WriteString("mode: merge\n")
b.WriteString("targets:\n")
b.WriteString(" " + name + ":\n")
b.WriteString(" skills:\n")
b.WriteString(" path: " + skillsPath + "\n")
if agentPath != "" {
b.WriteString(" agents:\n")
b.WriteString(" path: " + agentPath + "\n")
}
sb.WriteConfig(b.String())
}
func writeAgentFile(t *testing.T, dir, name string) string {
t.Helper()
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatalf("mkdir agent source: %v", err)
}
path := filepath.Join(dir, name)
if err := os.WriteFile(path, []byte("# "+name), 0644); err != nil {
t.Fatalf("write agent file: %v", err)
}
return path
}
func linkAgentFile(t *testing.T, dir, name, source string) string {
t.Helper()
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatalf("mkdir agent target: %v", err)
}
linkPath := filepath.Join(dir, name)
if err := os.Symlink(source, linkPath); err != nil {
t.Fatalf("symlink agent: %v", err)
}
return linkPath
}
func writeProjectTargetConfig(t *testing.T, targets []config.ProjectTargetEntry) string {
t.Helper()
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, ".skillshare", "skills"), 0755); err != nil {
t.Fatalf("mkdir project skills: %v", err)
}
if err := os.MkdirAll(filepath.Join(root, ".skillshare", "agents"), 0755); err != nil {
t.Fatalf("mkdir project agents: %v", err)
}
cfg := &config.ProjectConfig{Targets: targets}
if err := cfg.Save(root); err != nil {
t.Fatalf("save project config: %v", err)
}
return root
}
+99 -8
View File
@@ -32,11 +32,26 @@ func (o filterUpdateOpts) hasUpdates() bool {
len(o.RemoveInclude) > 0 || len(o.RemoveExclude) > 0
}
type parsedTargetFilterFlags struct {
Skills filterUpdateOpts
Agents filterUpdateOpts
}
func (o parsedTargetFilterFlags) hasUpdates() bool {
return o.Skills.hasUpdates() || o.Agents.hasUpdates()
}
type parsedTargetSettingFlags struct {
SkillMode string
AgentMode string
Naming string
}
// parseFilterFlags extracts --add-include, --add-exclude, --remove-include,
// --remove-exclude flags from args. Returns the parsed opts and any
// remaining (non-filter) arguments.
func parseFilterFlags(args []string) (filterUpdateOpts, []string, error) {
var opts filterUpdateOpts
// --remove-exclude flags from args for both skills and agents.
// Returns the parsed opts and any remaining (non-filter) arguments.
func parseFilterFlags(args []string) (parsedTargetFilterFlags, []string, error) {
var opts parsedTargetFilterFlags
var rest []string
for i := 0; i < len(args); i++ {
@@ -46,25 +61,49 @@ func parseFilterFlags(args []string) (filterUpdateOpts, []string, error) {
return opts, nil, fmt.Errorf("--add-include requires a value")
}
i++
opts.AddInclude = append(opts.AddInclude, args[i])
opts.Skills.AddInclude = append(opts.Skills.AddInclude, args[i])
case "--add-exclude":
if i+1 >= len(args) {
return opts, nil, fmt.Errorf("--add-exclude requires a value")
}
i++
opts.AddExclude = append(opts.AddExclude, args[i])
opts.Skills.AddExclude = append(opts.Skills.AddExclude, args[i])
case "--remove-include":
if i+1 >= len(args) {
return opts, nil, fmt.Errorf("--remove-include requires a value")
}
i++
opts.RemoveInclude = append(opts.RemoveInclude, args[i])
opts.Skills.RemoveInclude = append(opts.Skills.RemoveInclude, args[i])
case "--remove-exclude":
if i+1 >= len(args) {
return opts, nil, fmt.Errorf("--remove-exclude requires a value")
}
i++
opts.RemoveExclude = append(opts.RemoveExclude, args[i])
opts.Skills.RemoveExclude = append(opts.Skills.RemoveExclude, args[i])
case "--add-agent-include":
if i+1 >= len(args) {
return opts, nil, fmt.Errorf("--add-agent-include requires a value")
}
i++
opts.Agents.AddInclude = append(opts.Agents.AddInclude, args[i])
case "--add-agent-exclude":
if i+1 >= len(args) {
return opts, nil, fmt.Errorf("--add-agent-exclude requires a value")
}
i++
opts.Agents.AddExclude = append(opts.Agents.AddExclude, args[i])
case "--remove-agent-include":
if i+1 >= len(args) {
return opts, nil, fmt.Errorf("--remove-agent-include requires a value")
}
i++
opts.Agents.RemoveInclude = append(opts.Agents.RemoveInclude, args[i])
case "--remove-agent-exclude":
if i+1 >= len(args) {
return opts, nil, fmt.Errorf("--remove-agent-exclude requires a value")
}
i++
opts.Agents.RemoveExclude = append(opts.Agents.RemoveExclude, args[i])
default:
rest = append(rest, args[i])
}
@@ -73,6 +112,35 @@ func parseFilterFlags(args []string) (filterUpdateOpts, []string, error) {
return opts, rest, nil
}
func parseTargetSettingFlags(args []string) (parsedTargetSettingFlags, error) {
var settings parsedTargetSettingFlags
for i := 0; i < len(args); i++ {
switch args[i] {
case "--mode", "-m":
if i+1 >= len(args) {
return settings, fmt.Errorf("--mode requires a value (merge, symlink, or copy)")
}
settings.SkillMode = args[i+1]
i++
case "--agent-mode":
if i+1 >= len(args) {
return settings, fmt.Errorf("--agent-mode requires a value (merge, symlink, or copy)")
}
settings.AgentMode = args[i+1]
i++
case "--target-naming":
if i+1 >= len(args) {
return settings, fmt.Errorf("--target-naming requires a value (flat or standard)")
}
settings.Naming = args[i+1]
i++
}
}
return settings, nil
}
// applyFilterUpdates modifies include/exclude slices according to opts.
// It validates patterns with filepath.Match, deduplicates, and returns
// a human-readable list of changes applied.
@@ -120,6 +188,29 @@ func applyFilterUpdates(include, exclude *[]string, opts filterUpdateOpts) ([]st
return changes, nil
}
func scopeFilterChanges(scope string, changes []string) []string {
if scope != "agents" {
return changes
}
scoped := make([]string, len(changes))
for i, change := range changes {
switch {
case strings.HasPrefix(change, "added include: "):
scoped[i] = strings.Replace(change, "added include: ", "added agent include: ", 1)
case strings.HasPrefix(change, "added exclude: "):
scoped[i] = strings.Replace(change, "added exclude: ", "added agent exclude: ", 1)
case strings.HasPrefix(change, "removed include: "):
scoped[i] = strings.Replace(change, "removed include: ", "removed agent include: ", 1)
case strings.HasPrefix(change, "removed exclude: "):
scoped[i] = strings.Replace(change, "removed exclude: ", "removed agent exclude: ", 1)
default:
scoped[i] = change
}
}
return scoped
}
func containsPattern(patterns []string, p string) bool {
for _, existing := range patterns {
if existing == p {
+78 -15
View File
@@ -10,14 +10,14 @@ func TestParseFilterFlags(t *testing.T) {
tests := []struct {
name string
args []string
wantOpts filterUpdateOpts
wantOpts parsedTargetFilterFlags
wantRest []string
wantErr bool
}{
{
name: "no flags",
args: []string{"--mode", "merge"},
wantOpts: filterUpdateOpts{},
wantOpts: parsedTargetFilterFlags{},
wantRest: []string{"--mode", "merge"},
},
{
@@ -28,11 +28,13 @@ func TestParseFilterFlags(t *testing.T) {
"--remove-include", "old-*",
"--remove-exclude", "test-*",
},
wantOpts: filterUpdateOpts{
AddInclude: []string{"team-*"},
AddExclude: []string{"_legacy*"},
RemoveInclude: []string{"old-*"},
RemoveExclude: []string{"test-*"},
wantOpts: parsedTargetFilterFlags{
Skills: filterUpdateOpts{
AddInclude: []string{"team-*"},
AddExclude: []string{"_legacy*"},
RemoveInclude: []string{"old-*"},
RemoveExclude: []string{"test-*"},
},
},
},
{
@@ -41,8 +43,23 @@ func TestParseFilterFlags(t *testing.T) {
"--add-include", "a-*",
"--add-include", "b-*",
},
wantOpts: filterUpdateOpts{
AddInclude: []string{"a-*", "b-*"},
wantOpts: parsedTargetFilterFlags{
Skills: filterUpdateOpts{
AddInclude: []string{"a-*", "b-*"},
},
},
},
{
name: "agent flags",
args: []string{
"--add-agent-include", "team-*",
"--remove-agent-exclude", "draft-*",
},
wantOpts: parsedTargetFilterFlags{
Agents: filterUpdateOpts{
AddInclude: []string{"team-*"},
RemoveExclude: []string{"draft-*"},
},
},
},
{
@@ -50,9 +67,15 @@ func TestParseFilterFlags(t *testing.T) {
args: []string{
"--mode", "merge",
"--add-include", "team-*",
"--add-agent-exclude", "draft-*",
},
wantOpts: filterUpdateOpts{
AddInclude: []string{"team-*"},
wantOpts: parsedTargetFilterFlags{
Skills: filterUpdateOpts{
AddInclude: []string{"team-*"},
},
Agents: filterUpdateOpts{
AddExclude: []string{"draft-*"},
},
},
wantRest: []string{"--mode", "merge"},
},
@@ -91,15 +114,39 @@ func TestParseFilterFlags(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
assertStringSlice(t, "AddInclude", opts.AddInclude, tt.wantOpts.AddInclude)
assertStringSlice(t, "AddExclude", opts.AddExclude, tt.wantOpts.AddExclude)
assertStringSlice(t, "RemoveInclude", opts.RemoveInclude, tt.wantOpts.RemoveInclude)
assertStringSlice(t, "RemoveExclude", opts.RemoveExclude, tt.wantOpts.RemoveExclude)
assertStringSlice(t, "Skills.AddInclude", opts.Skills.AddInclude, tt.wantOpts.Skills.AddInclude)
assertStringSlice(t, "Skills.AddExclude", opts.Skills.AddExclude, tt.wantOpts.Skills.AddExclude)
assertStringSlice(t, "Skills.RemoveInclude", opts.Skills.RemoveInclude, tt.wantOpts.Skills.RemoveInclude)
assertStringSlice(t, "Skills.RemoveExclude", opts.Skills.RemoveExclude, tt.wantOpts.Skills.RemoveExclude)
assertStringSlice(t, "Agents.AddInclude", opts.Agents.AddInclude, tt.wantOpts.Agents.AddInclude)
assertStringSlice(t, "Agents.AddExclude", opts.Agents.AddExclude, tt.wantOpts.Agents.AddExclude)
assertStringSlice(t, "Agents.RemoveInclude", opts.Agents.RemoveInclude, tt.wantOpts.Agents.RemoveInclude)
assertStringSlice(t, "Agents.RemoveExclude", opts.Agents.RemoveExclude, tt.wantOpts.Agents.RemoveExclude)
assertStringSlice(t, "rest", rest, tt.wantRest)
})
}
}
func TestParseTargetSettingFlags(t *testing.T) {
settings, err := parseTargetSettingFlags([]string{
"--mode", "copy",
"--agent-mode", "merge",
"--target-naming", "standard",
})
if err != nil {
t.Fatalf("parseTargetSettingFlags: %v", err)
}
if settings.SkillMode != "copy" {
t.Fatalf("SkillMode = %q, want copy", settings.SkillMode)
}
if settings.AgentMode != "merge" {
t.Fatalf("AgentMode = %q, want merge", settings.AgentMode)
}
if settings.Naming != "standard" {
t.Fatalf("Naming = %q, want standard", settings.Naming)
}
}
func TestApplyFilterUpdates(t *testing.T) {
tests := []struct {
name string
@@ -225,6 +272,22 @@ func TestFilterUpdateOpts_HasUpdates(t *testing.T) {
}
}
func TestScopeFilterChanges_Agents(t *testing.T) {
changes := scopeFilterChanges("agents", []string{
"added include: team-*",
"added exclude: draft-*",
"removed include: team-*",
"removed exclude: draft-*",
})
want := []string{
"added agent include: team-*",
"added agent exclude: draft-*",
"removed agent include: team-*",
"removed agent exclude: draft-*",
}
assertStringSlice(t, "changes", changes, want)
}
func TestFindUnknownSkillTargets_CustomTargets(t *testing.T) {
discovered := []ssync.DiscoveredSkill{
{RelPath: "skill-a", Targets: []string{"claude", "custom-tool"}},
+360 -71
View File
@@ -2,11 +2,14 @@ package main
import (
"fmt"
"path/filepath"
"sort"
"strings"
"skillshare/internal/config"
"skillshare/internal/sync"
"skillshare/internal/targetsummary"
"skillshare/internal/theme"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/spinner"
@@ -59,6 +62,7 @@ type targetListTUIModel struct {
// Mode picker overlay
showModePicker bool
modePickerTarget string // target name being edited
modePickerScope string // "skills" or "agents"
modeCursor int
// Naming picker overlay
@@ -70,6 +74,7 @@ type targetListTUIModel struct {
editingFilter bool // true when in I/E edit mode
editFilterType string // "include" or "exclude"
editFilterTarget string // target name being edited
editFilterScope string // "skills" or "agents"
editPatterns []string
editCursor int // selected pattern index
editAdding bool
@@ -79,6 +84,12 @@ type targetListTUIModel struct {
confirming bool
confirmTarget string
// Scope picker overlay for M/I/E when both skills and agents are available.
showScopePicker bool
scopePickerTarget string
scopePickerAction string // "mode", "include", "exclude"
scopePickerCursor int
// Exit-with-action (for destructive ops dispatched after TUI exit)
action string // "remove" or "" (normal quit)
@@ -86,6 +97,12 @@ type targetListTUIModel struct {
lastActionMsg string
}
type targetScopeOption struct {
scope string
enabled bool
disabled string
}
func newTargetListTUIModel(
modeLabel string,
cfg *config.Config,
@@ -96,7 +113,7 @@ func newTargetListTUIModel(
l := list.New(nil, delegate, 0, 0)
l.Title = fmt.Sprintf("Targets (%s)", modeLabel)
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
@@ -104,18 +121,18 @@ func newTargetListTUIModel(
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
fi.Placeholder = "filter by name"
ei := textinput.New()
ei.Prompt = "> pattern: "
ei.PromptStyle = tc.Cyan
ei.Cursor.Style = tc.Cyan
ei.PromptStyle = theme.Accent()
ei.Cursor.Style = theme.Accent()
ei.Placeholder = "glob pattern"
return targetListTUIModel{
@@ -152,18 +169,30 @@ func buildTargetTUIItems(isProject bool, cwd string) ([]targetTUIItem, error) {
if err != nil {
return nil, err
}
resolvedTargets, err := config.ResolveProjectTargets(cwd, projCfg)
if err != nil {
return nil, err
}
agentBuilder, err := targetsummary.NewProjectBuilder(cwd)
if err != nil {
return nil, err
}
for _, entry := range projCfg.Targets {
sc := entry.SkillsConfig()
resolved, ok := resolvedTargets[entry.Name]
if !ok {
continue
}
agentSummary, err := agentBuilder.ProjectTarget(entry)
if err != nil {
return nil, err
}
items = append(items, targetTUIItem{
name: entry.Name,
target: config.TargetConfig{
Skills: &config.ResourceTargetConfig{
Path: projectTargetDisplayPath(entry),
Mode: sc.Mode,
Include: sc.Include,
Exclude: sc.Exclude,
},
},
name: entry.Name,
target: resolved,
displayPath: projectTargetDisplayPath(entry),
skillSync: buildTargetSkillSyncSummary(resolved.SkillsConfig().Path, filepath.Join(cwd, ".skillshare", "skills"), resolved.SkillsConfig().Mode),
agentConfig: config.ResourceTargetConfig{Mode: agentSummaryMode(agentSummary), Include: agentSummaryInclude(agentSummary), Exclude: agentSummaryExclude(agentSummary)},
agentSummary: agentSummary,
})
}
} else {
@@ -171,8 +200,23 @@ func buildTargetTUIItems(isProject bool, cwd string) ([]targetTUIItem, error) {
if err != nil {
return nil, err
}
agentBuilder, err := targetsummary.NewGlobalBuilder(cfg)
if err != nil {
return nil, err
}
for name, t := range cfg.Targets {
items = append(items, targetTUIItem{name: name, target: t})
agentSummary, err := agentBuilder.GlobalTarget(name, t)
if err != nil {
return nil, err
}
items = append(items, targetTUIItem{
name: name,
target: t,
displayPath: t.SkillsConfig().Path,
skillSync: buildTargetSkillSyncSummary(t.SkillsConfig().Path, cfg.Source, t.SkillsConfig().Mode),
agentConfig: config.ResourceTargetConfig{Mode: agentSummaryMode(agentSummary), Include: agentSummaryInclude(agentSummary), Exclude: agentSummaryExclude(agentSummary)},
agentSummary: agentSummary,
})
}
}
sort.Slice(items, func(i, j int) bool {
@@ -241,6 +285,9 @@ func (m targetListTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.showModePicker {
return m.handleModePickerKey(msg)
}
if m.showScopePicker {
return m.handleScopePickerKey(msg)
}
if m.showNamingPicker {
return m.handleNamingPickerKey(msg)
}
@@ -303,6 +350,9 @@ func (m targetListTUIModel) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd)
return m, textinput.Blink
case "M":
if item, ok := m.list.SelectedItem().(targetTUIItem); ok {
if item.agentSummary != nil {
return m.openScopePicker(item, "mode")
}
return m.openModePicker(item.name, item.target)
}
return m, nil
@@ -313,11 +363,17 @@ func (m targetListTUIModel) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd)
return m, nil
case "I":
if item, ok := m.list.SelectedItem().(targetTUIItem); ok {
if item.agentSummary != nil {
return m.openScopePicker(item, "include")
}
return m.openFilterEdit(item.name, "include", item.target.SkillsConfig().Include)
}
return m, nil
case "E":
if item, ok := m.list.SelectedItem().(targetTUIItem); ok {
if item.agentSummary != nil {
return m.openScopePicker(item, "exclude")
}
return m.openFilterEdit(item.name, "exclude", item.target.SkillsConfig().Exclude)
}
return m, nil
@@ -412,10 +468,15 @@ func (m targetListTUIModel) handleConfirmKey(msg tea.KeyMsg) (tea.Model, tea.Cmd
var targetSyncModes = config.ExtraSyncModes // ["merge", "copy", "symlink"]
func (m targetListTUIModel) openModePicker(name string, target config.TargetConfig) (tea.Model, tea.Cmd) {
return m.openModePickerForScope(name, target.SkillsConfig(), "skills")
}
func (m targetListTUIModel) openModePickerForScope(name string, currentConfig config.ResourceTargetConfig, scope string) (tea.Model, tea.Cmd) {
m.showModePicker = true
m.modePickerTarget = name
m.modePickerScope = scope
m.modeCursor = 0
current := sync.EffectiveMode(target.SkillsConfig().Mode)
current := sync.EffectiveMode(currentConfig.Mode)
for i, mode := range targetSyncModes {
if mode == current {
m.modeCursor = i
@@ -445,15 +506,16 @@ func (m targetListTUIModel) handleModePickerKey(msg tea.KeyMsg) (tea.Model, tea.
m.showModePicker = false
newMode := targetSyncModes[m.modeCursor]
name := m.modePickerTarget
scope := m.modePickerScope
return m, func() tea.Msg {
msg, err := m.doSetTargetMode(name, newMode)
msg, err := m.doSetTargetMode(name, scope, newMode)
return targetListActionDoneMsg{msg: msg, err: err}
}
}
return m, nil
}
func (m targetListTUIModel) doSetTargetMode(name, newMode string) (string, error) {
func (m targetListTUIModel) doSetTargetMode(name, scope, newMode string) (string, error) {
if m.projCfg != nil {
projCfg, err := config.LoadProject(m.cwd)
if err != nil {
@@ -461,7 +523,8 @@ func (m targetListTUIModel) doSetTargetMode(name, newMode string) (string, error
}
for i, entry := range projCfg.Targets {
if entry.Name == name {
projCfg.Targets[i].EnsureSkills().Mode = newMode
targetCfg := scopeSetterProject(&projCfg.Targets[i], scope)
targetCfg.Mode = newMode
break
}
}
@@ -474,13 +537,14 @@ func (m targetListTUIModel) doSetTargetMode(name, newMode string) (string, error
return "", err
}
t := cfg.Targets[name]
t.EnsureSkills().Mode = newMode
targetCfg := scopeSetterGlobal(&t, scope)
targetCfg.Mode = newMode
cfg.Targets[name] = t
if err := cfg.Save(); err != nil {
return "", err
}
}
return fmt.Sprintf("✓ Set %s mode to %s", name, newMode), nil
return fmt.Sprintf("✓ Set %s %s mode to %s", name, scope, newMode), nil
}
// ─── Naming Picker ──────────────────────────────────────────────────
@@ -560,9 +624,14 @@ func (m targetListTUIModel) doSetTargetNaming(name, newNaming string) (string, e
// ─── Include/Exclude Edit Sub-Panel ──────────────────────────────────
func (m targetListTUIModel) openFilterEdit(name, filterType string, patterns []string) (tea.Model, tea.Cmd) {
return m.openFilterEditForScope(name, "skills", filterType, patterns)
}
func (m targetListTUIModel) openFilterEditForScope(name, scope, filterType string, patterns []string) (tea.Model, tea.Cmd) {
m.editingFilter = true
m.editFilterType = filterType
m.editFilterTarget = name
m.editFilterScope = scope
m.editPatterns = make([]string, len(patterns))
copy(m.editPatterns, patterns)
m.editCursor = 0
@@ -604,9 +673,10 @@ func (m targetListTUIModel) handleFilterEditKey(msg tea.KeyMsg) (tea.Model, tea.
m.editCursor--
}
name := m.editFilterTarget
scope := m.editFilterScope
filterType := m.editFilterType
return m, func() tea.Msg {
msg, err := m.doRemovePattern(name, filterType, pattern)
msg, err := m.doRemovePattern(name, scope, filterType, pattern)
return targetListActionDoneMsg{msg: msg, err: err}
}
}
@@ -631,9 +701,10 @@ func (m targetListTUIModel) handleFilterEditAddKey(msg tea.KeyMsg) (tea.Model, t
m.editPatterns = append(m.editPatterns, pattern)
m.editCursor = len(m.editPatterns) - 1
name := m.editFilterTarget
scope := m.editFilterScope
filterType := m.editFilterType
return m, func() tea.Msg {
msg, err := m.doAddPattern(name, filterType, pattern)
msg, err := m.doAddPattern(name, scope, filterType, pattern)
return targetListActionDoneMsg{msg: msg, err: err}
}
}
@@ -642,7 +713,7 @@ func (m targetListTUIModel) handleFilterEditAddKey(msg tea.KeyMsg) (tea.Model, t
return m, cmd
}
func (m targetListTUIModel) doAddPattern(name, filterType, pattern string) (string, error) {
func (m targetListTUIModel) doAddPattern(name, scope, filterType, pattern string) (string, error) {
if m.projCfg != nil {
projCfg, err := config.LoadProject(m.cwd)
if err != nil {
@@ -650,11 +721,11 @@ func (m targetListTUIModel) doAddPattern(name, filterType, pattern string) (stri
}
for i, entry := range projCfg.Targets {
if entry.Name == name {
sk := projCfg.Targets[i].EnsureSkills()
targetCfg := scopeSetterProject(&projCfg.Targets[i], scope)
if filterType == "include" {
sk.Include = append(sk.Include, pattern)
targetCfg.Include = append(targetCfg.Include, pattern)
} else {
sk.Exclude = append(sk.Exclude, pattern)
targetCfg.Exclude = append(targetCfg.Exclude, pattern)
}
break
}
@@ -668,21 +739,21 @@ func (m targetListTUIModel) doAddPattern(name, filterType, pattern string) (stri
return "", err
}
t := cfg.Targets[name]
sk := t.EnsureSkills()
targetCfg := scopeSetterGlobal(&t, scope)
if filterType == "include" {
sk.Include = append(sk.Include, pattern)
targetCfg.Include = append(targetCfg.Include, pattern)
} else {
sk.Exclude = append(sk.Exclude, pattern)
targetCfg.Exclude = append(targetCfg.Exclude, pattern)
}
cfg.Targets[name] = t
if err := cfg.Save(); err != nil {
return "", err
}
}
return fmt.Sprintf("✓ Added %s pattern: %s", filterType, pattern), nil
return fmt.Sprintf("✓ Added %s %s pattern: %s", scope, filterType, pattern), nil
}
func (m targetListTUIModel) doRemovePattern(name, filterType, pattern string) (string, error) {
func (m targetListTUIModel) doRemovePattern(name, scope, filterType, pattern string) (string, error) {
removeFromSlice := func(slice []string, val string) []string {
var result []string
for _, s := range slice {
@@ -700,11 +771,11 @@ func (m targetListTUIModel) doRemovePattern(name, filterType, pattern string) (s
}
for i, entry := range projCfg.Targets {
if entry.Name == name {
sk := projCfg.Targets[i].EnsureSkills()
targetCfg := scopeSetterProject(&projCfg.Targets[i], scope)
if filterType == "include" {
sk.Include = removeFromSlice(sk.Include, pattern)
targetCfg.Include = removeFromSlice(targetCfg.Include, pattern)
} else {
sk.Exclude = removeFromSlice(sk.Exclude, pattern)
targetCfg.Exclude = removeFromSlice(targetCfg.Exclude, pattern)
}
break
}
@@ -718,18 +789,18 @@ func (m targetListTUIModel) doRemovePattern(name, filterType, pattern string) (s
return "", err
}
t := cfg.Targets[name]
sk := t.EnsureSkills()
targetCfg := scopeSetterGlobal(&t, scope)
if filterType == "include" {
sk.Include = removeFromSlice(sk.Include, pattern)
targetCfg.Include = removeFromSlice(targetCfg.Include, pattern)
} else {
sk.Exclude = removeFromSlice(sk.Exclude, pattern)
targetCfg.Exclude = removeFromSlice(targetCfg.Exclude, pattern)
}
cfg.Targets[name] = t
if err := cfg.Save(); err != nil {
return "", err
}
}
return fmt.Sprintf("✓ Removed %s pattern: %s", filterType, pattern), nil
return fmt.Sprintf("✓ Removed %s %s pattern: %s", scope, filterType, pattern), nil
}
// ---- View -------------------------------------------------------------------
@@ -747,6 +818,9 @@ func (m targetListTUIModel) View() string {
if m.showModePicker {
return m.renderModePicker()
}
if m.showScopePicker {
return m.renderScopePicker()
}
if m.showNamingPicker {
return m.renderNamingPicker()
}
@@ -822,20 +896,20 @@ func (m targetListTUIModel) viewTargetVertical() string {
func renderTargetActionMsg(msg string) string {
if strings.HasPrefix(msg, "✓") {
return tc.Green.Render(msg)
return theme.Success().Render(msg)
}
if strings.HasPrefix(msg, "✗") {
return tc.Red.Render(msg)
return theme.Danger().Render(msg)
}
return tc.Yellow.Render(msg)
return theme.Warning().Render(msg)
}
func (m targetListTUIModel) renderTargetHelp(scrollInfo string) string {
helpText := "↑↓ navigate / filter Ctrl+d/u scroll M mode N naming I include E exclude R remove q quit"
helpText := "↑↓ navigate / filter Ctrl+d/u scroll M mode(sk/ag) N naming(sk) I include(sk/ag) E exclude(sk/ag) R remove q quit"
if m.filtering {
helpText = "Enter lock Esc clear q quit"
}
return tc.Help.Render(appendScrollInfo(helpText, scrollInfo))
return theme.Dim().MarginLeft(2).Render(appendScrollInfo(helpText, scrollInfo))
}
func (m targetListTUIModel) renderTargetFilterBar() string {
@@ -882,33 +956,82 @@ func (m *targetListTUIModel) syncTargetListSize() {
func (m targetListTUIModel) renderTargetDetail(item targetTUIItem) string {
var b strings.Builder
fmt.Fprintf(&b, "%s\n\n", tc.Title.Render(item.name))
fmt.Fprintf(&b, "%s\n\n", theme.Title().Render(item.name))
sc := item.target.SkillsConfig()
fmt.Fprintf(&b, "%s %s\n", tc.Dim.Render("Path:"), shortenPath(sc.Path))
fmt.Fprintf(&b, "%s %s\n", tc.Dim.Render("Mode:"), sync.EffectiveMode(sc.Mode))
fmt.Fprintf(&b, "%s %s\n", tc.Dim.Render("Naming:"), config.EffectiveTargetNaming(sc.TargetNaming))
displayPath := item.displayPath
if displayPath == "" {
displayPath = sc.Path
}
fmt.Fprintf(&b, "%s\n", theme.Dim().Render("Skills:"))
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Path:"), shortenPath(displayPath))
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Mode:"), sync.EffectiveMode(sc.Mode))
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Naming:"), config.EffectiveTargetNaming(sc.TargetNaming))
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Sync:"), item.skillSync)
if len(sc.Include) > 0 {
fmt.Fprintf(&b, "\n%s\n", tc.Dim.Render("Include:"))
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("Include:"))
for _, p := range sc.Include {
fmt.Fprintf(&b, " %s\n", p)
}
}
if len(sc.Exclude) > 0 {
fmt.Fprintf(&b, "\n%s\n", tc.Dim.Render("Exclude:"))
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("Exclude:"))
for _, p := range sc.Exclude {
fmt.Fprintf(&b, " %s\n", p)
}
}
if len(sc.Include) == 0 && len(sc.Exclude) == 0 {
fmt.Fprintf(&b, "\n%s\n", tc.Dim.Render("No include/exclude filters"))
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("No include/exclude filters"))
}
if item.agentSummary != nil {
agentPath := item.agentSummary.DisplayPath
if agentPath == "" {
agentPath = item.agentSummary.Path
}
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("Agents:"))
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Path:"), shortenPath(agentPath))
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Mode:"), item.agentSummary.Mode)
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Sync:"), formatTargetAgentSyncSummary(item.agentSummary))
if item.agentSummary.Mode == "symlink" {
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("Agent include/exclude filters ignored in symlink mode"))
} else if len(item.agentSummary.Include) > 0 {
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("Agent Include:"))
for _, p := range item.agentSummary.Include {
fmt.Fprintf(&b, " %s\n", p)
}
}
if item.agentSummary.Mode != "symlink" && len(item.agentSummary.Exclude) > 0 {
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("Agent Exclude:"))
for _, p := range item.agentSummary.Exclude {
fmt.Fprintf(&b, " %s\n", p)
}
}
if item.agentSummary.Mode != "symlink" && len(item.agentSummary.Include) == 0 && len(item.agentSummary.Exclude) == 0 {
fmt.Fprintf(&b, "\n%s\n", theme.Dim().Render("No agent include/exclude filters"))
}
}
return b.String()
}
func buildTargetSkillSyncSummary(targetPath, sourcePath, mode string) string {
switch sync.EffectiveMode(mode) {
case "copy":
status, managed, local := sync.CheckStatusCopy(targetPath)
return fmt.Sprintf("%s (%d managed, %d local)", status, managed, local)
case "merge":
status, linked, local := sync.CheckStatusMerge(targetPath, sourcePath)
return fmt.Sprintf("%s (%d shared, %d local)", status, linked, local)
default:
return sync.CheckStatus(targetPath, sourcePath).String()
}
}
// ---- Overlay renders --------------------------------------------------------
func (m targetListTUIModel) renderConfirmOverlay() string {
@@ -918,19 +1041,19 @@ func (m targetListTUIModel) renderConfirmOverlay() string {
}
cmd := fmt.Sprintf("skillshare target remove %s %s", flag, m.confirmTarget)
return fmt.Sprintf("\n %s\n\n → %s\n\n Proceed? [Y/n] ",
tc.Red.Render("Remove target "+m.confirmTarget+"?"), cmd)
theme.Danger().Render("Remove target "+m.confirmTarget+"?"), cmd)
}
func (m targetListTUIModel) renderModePicker() string {
var b strings.Builder
fmt.Fprintf(&b, "\n%s\n", tc.Title.Render("Change mode"))
fmt.Fprintf(&b, "%s %s\n\n", tc.Dim.Render("Target:"), m.modePickerTarget)
fmt.Fprintf(&b, "\n%s\n", theme.Title().Render("Change "+m.modePickerScope+" mode"))
fmt.Fprintf(&b, "%s %s\n\n", theme.Dim().Render("Target:"), m.modePickerTarget)
for i, mode := range targetSyncModes {
cursor := " "
if i == m.modeCursor {
cursor = tc.Cyan.Render(">") + " "
cursor = theme.Accent().Render(">") + " "
}
var desc string
switch mode {
@@ -942,26 +1065,59 @@ func (m targetListTUIModel) renderModePicker() string {
desc = " (directory symlink)"
}
if i == m.modeCursor {
fmt.Fprintf(&b, "%s%s%s\n", cursor, tc.Cyan.Render(mode), tc.Dim.Render(desc))
fmt.Fprintf(&b, "%s%s%s\n", cursor, theme.Accent().Render(mode), theme.Dim().Render(desc))
} else {
fmt.Fprintf(&b, "%s%s%s\n", cursor, mode, tc.Dim.Render(desc))
fmt.Fprintf(&b, "%s%s%s\n", cursor, mode, theme.Dim().Render(desc))
}
}
fmt.Fprintf(&b, "\n%s\n", tc.Help.Render("↑↓ select Enter confirm Esc cancel"))
fmt.Fprintf(&b, "\n%s\n", theme.Dim().MarginLeft(2).Render("↑↓ select Enter confirm Esc cancel"))
return b.String()
}
func (m targetListTUIModel) renderScopePicker() string {
var b strings.Builder
item, ok := m.list.SelectedItem().(targetTUIItem)
if !ok {
return ""
}
options := targetScopeOptions(item, m.scopePickerAction)
fmt.Fprintf(&b, "\n%s\n", theme.Title().Render("Choose resource"))
fmt.Fprintf(&b, "%s %s\n", theme.Dim().Render("Target:"), m.scopePickerTarget)
fmt.Fprintf(&b, "%s %s\n\n", theme.Dim().Render("Action:"), m.scopePickerAction)
for i, option := range options {
cursor := " "
if i == m.scopePickerCursor {
cursor = theme.Accent().Render(">") + " "
}
label := capitalize(option.scope)
if option.enabled {
if i == m.scopePickerCursor {
fmt.Fprintf(&b, "%s%s\n", cursor, theme.Accent().Render(label))
} else {
fmt.Fprintf(&b, "%s%s\n", cursor, label)
}
continue
}
fmt.Fprintf(&b, "%s%s%s\n", cursor, theme.Dim().Render(label), theme.Dim().Render(" ("+option.disabled+")"))
}
fmt.Fprintf(&b, "\n%s\n", theme.Dim().MarginLeft(2).Render("↑↓ select Enter confirm Esc cancel"))
return b.String()
}
func (m targetListTUIModel) renderNamingPicker() string {
var b strings.Builder
fmt.Fprintf(&b, "\n%s\n", tc.Title.Render("Change target naming"))
fmt.Fprintf(&b, "%s %s\n\n", tc.Dim.Render("Target:"), m.namingPickerTarget)
fmt.Fprintf(&b, "\n%s\n", theme.Title().Render("Change target naming"))
fmt.Fprintf(&b, "%s %s\n\n", theme.Dim().Render("Target:"), m.namingPickerTarget)
for i, naming := range config.ValidTargetNamings {
cursor := " "
if i == m.namingCursor {
cursor = tc.Cyan.Render(">") + " "
cursor = theme.Accent().Render(">") + " "
}
var desc string
switch naming {
@@ -971,13 +1127,13 @@ func (m targetListTUIModel) renderNamingPicker() string {
desc = " (SKILL.md name)"
}
if i == m.namingCursor {
fmt.Fprintf(&b, "%s%s%s\n", cursor, tc.Cyan.Render(naming), tc.Dim.Render(desc))
fmt.Fprintf(&b, "%s%s%s\n", cursor, theme.Accent().Render(naming), theme.Dim().Render(desc))
} else {
fmt.Fprintf(&b, "%s%s%s\n", cursor, naming, tc.Dim.Render(desc))
fmt.Fprintf(&b, "%s%s%s\n", cursor, naming, theme.Dim().Render(desc))
}
}
fmt.Fprintf(&b, "\n%s\n", tc.Help.Render("↑↓ select Enter confirm Esc cancel"))
fmt.Fprintf(&b, "\n%s\n", theme.Dim().MarginLeft(2).Render("↑↓ select Enter confirm Esc cancel"))
return b.String()
}
@@ -985,15 +1141,15 @@ func (m targetListTUIModel) renderFilterEditPanel() string {
var b strings.Builder
title := capitalize(m.editFilterType)
fmt.Fprintf(&b, "%s %s\n", tc.Title.Render(title+" patterns"), tc.Dim.Render("("+m.editFilterTarget+")"))
fmt.Fprintf(&b, "%s %s\n", theme.Title().Render(title+" "+m.editFilterScope+" patterns"), theme.Dim().Render("("+m.editFilterTarget+")"))
fmt.Fprintln(&b)
if len(m.editPatterns) == 0 {
fmt.Fprintf(&b, " %s\n", tc.Dim.Render("(empty)"))
fmt.Fprintf(&b, " %s\n", theme.Dim().Render("(empty)"))
} else {
for i, p := range m.editPatterns {
if i == m.editCursor {
fmt.Fprintf(&b, " %s %s\n", tc.Cyan.Render(">"), tc.Cyan.Render(p))
fmt.Fprintf(&b, " %s %s\n", theme.Accent().Render(">"), theme.Accent().Render(p))
} else {
fmt.Fprintf(&b, " %s\n", p)
}
@@ -1007,9 +1163,9 @@ func (m targetListTUIModel) renderFilterEditPanel() string {
fmt.Fprintln(&b)
if m.editAdding {
fmt.Fprintf(&b, "%s\n", tc.Help.Render("Enter confirm Esc cancel"))
fmt.Fprintf(&b, "%s\n", theme.Dim().MarginLeft(2).Render("Enter confirm Esc cancel"))
} else {
fmt.Fprintf(&b, "%s\n", tc.Help.Render("a add d delete esc back"))
fmt.Fprintf(&b, "%s\n", theme.Dim().MarginLeft(2).Render("a add d delete esc back"))
}
return b.String()
}
@@ -1067,3 +1223,136 @@ func runTargetListTUI(mode runMode, cwd string) (string, string, error) {
}
return m.action, m.confirmTarget, nil
}
func (m targetListTUIModel) openScopePicker(item targetTUIItem, action string) (tea.Model, tea.Cmd) {
m.showScopePicker = true
m.scopePickerTarget = item.name
m.scopePickerAction = action
m.scopePickerCursor = firstEnabledScopeOption(targetScopeOptions(item, action))
m.lastActionMsg = ""
return m, nil
}
func (m targetListTUIModel) handleScopePickerKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
item, ok := m.list.SelectedItem().(targetTUIItem)
if !ok {
m.showScopePicker = false
return m, nil
}
options := targetScopeOptions(item, m.scopePickerAction)
switch msg.String() {
case "q", "esc":
m.showScopePicker = false
return m, nil
case "up", "k":
m.scopePickerCursor = moveScopePickerCursor(options, m.scopePickerCursor, -1)
return m, nil
case "down", "j":
m.scopePickerCursor = moveScopePickerCursor(options, m.scopePickerCursor, 1)
return m, nil
case "enter":
if len(options) == 0 || !options[m.scopePickerCursor].enabled {
m.showScopePicker = false
m.lastActionMsg = "✗ Agents include/exclude filters are ignored in symlink mode"
return m, nil
}
m.showScopePicker = false
scope := options[m.scopePickerCursor].scope
switch m.scopePickerAction {
case "mode":
return m.openModePickerForScope(item.name, itemConfigForScope(item, scope), scope)
case "include":
return m.openFilterEditForScope(item.name, scope, "include", itemConfigForScope(item, scope).Include)
case "exclude":
return m.openFilterEditForScope(item.name, scope, "exclude", itemConfigForScope(item, scope).Exclude)
}
return m, nil
}
return m, nil
}
func targetScopeOptions(item targetTUIItem, action string) []targetScopeOption {
options := []targetScopeOption{{scope: "skills", enabled: true}}
if item.agentSummary == nil {
return options
}
option := targetScopeOption{scope: "agents", enabled: true}
if (action == "include" || action == "exclude") && item.agentSummary.Mode == "symlink" {
option.enabled = false
option.disabled = "ignored in symlink mode"
}
return append(options, option)
}
func firstEnabledScopeOption(options []targetScopeOption) int {
for i, option := range options {
if option.enabled {
return i
}
}
return 0
}
func moveScopePickerCursor(options []targetScopeOption, current, delta int) int {
if len(options) == 0 {
return 0
}
if current < 0 || current >= len(options) {
current = firstEnabledScopeOption(options)
}
next := current
for {
candidate := next + delta
if candidate < 0 || candidate >= len(options) {
return current
}
next = candidate
if options[next].enabled {
return next
}
}
}
func itemConfigForScope(item targetTUIItem, scope string) config.ResourceTargetConfig {
if scope == "agents" {
return item.agentConfig
}
return item.target.SkillsConfig()
}
func scopeSetterGlobal(target *config.TargetConfig, scope string) *config.ResourceTargetConfig {
if scope == "agents" {
return target.EnsureAgents()
}
return target.EnsureSkills()
}
func scopeSetterProject(target *config.ProjectTargetEntry, scope string) *config.ResourceTargetConfig {
if scope == "agents" {
return target.EnsureAgents()
}
return target.EnsureSkills()
}
func agentSummaryMode(summary *targetsummary.AgentSummary) string {
if summary == nil {
return ""
}
return summary.Mode
}
func agentSummaryInclude(summary *targetsummary.AgentSummary) []string {
if summary == nil {
return nil
}
return append([]string(nil), summary.Include...)
}
func agentSummaryExclude(summary *targetsummary.AgentSummary) []string {
if summary == nil {
return nil
}
return append([]string(nil), summary.Exclude...)
}
+7 -2
View File
@@ -6,6 +6,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/sync"
"skillshare/internal/targetsummary"
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
@@ -13,8 +14,12 @@ import (
// targetTUIItem wraps a target entry for the bubbles/list widget.
type targetTUIItem struct {
name string
target config.TargetConfig
name string
target config.TargetConfig
displayPath string
skillSync string
agentConfig config.ResourceTargetConfig
agentSummary *targetsummary.AgentSummary
}
func (i targetTUIItem) FilterValue() string { return i.name }
+120 -38
View File
@@ -11,6 +11,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/oplog"
"skillshare/internal/sync"
"skillshare/internal/targetsummary"
"skillshare/internal/ui"
"skillshare/internal/utils"
"skillshare/internal/validate"
@@ -277,16 +278,27 @@ func targetListProjectWithJSON(root string, jsonOutput bool) error {
})
if jsonOutput {
agentBuilder, err := targetsummary.NewProjectBuilder(root)
if err != nil {
return err
}
var items []targetListJSONItem
for _, entry := range targets {
sc := entry.SkillsConfig()
items = append(items, targetListJSONItem{
item := targetListJSONItem{
Name: entry.Name,
Path: projectTargetDisplayPath(entry),
Mode: getTargetMode(sc.Mode, ""),
Include: sc.Include,
Exclude: sc.Exclude,
})
}
agentSummary, err := agentBuilder.ProjectTarget(entry)
if err != nil {
return err
}
applyTargetListAgentSummary(&item, agentSummary)
items = append(items, item)
}
output := struct {
Targets []targetListJSONItem `json:"targets"`
@@ -294,17 +306,14 @@ func targetListProjectWithJSON(root string, jsonOutput bool) error {
return writeJSON(&output)
}
ui.Header("Configured Targets (project)")
for _, entry := range targets {
displayPath := projectTargetDisplayPath(entry)
sc := entry.SkillsConfig()
mode := sc.Mode
if mode == "" {
mode = "merge"
}
fmt.Printf(" %-12s %s (%s)\n", entry.Name, displayPath, mode)
items, err := buildTargetTUIItems(true, root)
if err != nil {
return err
}
ui.Header("Configured Targets (project)")
printTargetListPlain(items)
return nil
}
@@ -320,23 +329,9 @@ func targetInfoProject(name string, args []string, root string) error {
if err != nil {
return err
}
var newMode, newNaming string
for i := 0; i < len(remaining); i++ {
switch remaining[i] {
case "--mode", "-m":
if i+1 >= len(remaining) {
return fmt.Errorf("--mode requires a value (merge, symlink, or copy)")
}
newMode = remaining[i+1]
i++
case "--target-naming":
if i+1 >= len(remaining) {
return fmt.Errorf("--target-naming requires a value (flat or standard)")
}
newNaming = remaining[i+1]
i++
}
settings, err := parseTargetSettingFlags(remaining)
if err != nil {
return err
}
cfg, err := config.LoadProject(root)
@@ -360,13 +355,55 @@ func targetInfoProject(name string, args []string, root string) error {
if filterOpts.hasUpdates() {
start := time.Now()
entry := &cfg.Targets[targetIdx]
s := entry.EnsureSkills()
changes, fErr := applyFilterUpdates(&s.Include, &s.Exclude, filterOpts)
if fErr != nil {
return fErr
var changes []string
mutated := false
if filterOpts.Skills.hasUpdates() {
s := entry.EnsureSkills()
skillChanges, fErr := applyFilterUpdates(&s.Include, &s.Exclude, filterOpts.Skills)
if fErr != nil {
return fErr
}
changes = append(changes, skillChanges...)
mutated = true
}
if err := cfg.Save(root); err != nil {
return err
if filterOpts.Agents.hasUpdates() {
agentBuilder, buildErr := targetsummary.NewProjectBuilder(root)
if buildErr != nil {
return buildErr
}
agentSummary, buildErr := agentBuilder.ProjectTarget(*entry)
if buildErr != nil {
return buildErr
}
if agentSummary == nil {
return fmt.Errorf("target '%s' does not have an agents path", name)
}
if agentSummary.Mode == "symlink" {
return fmt.Errorf("target '%s' agent include/exclude filters are ignored in symlink mode; use --agent-mode merge or --agent-mode copy first", name)
}
ac := entry.AgentsConfig()
include := append([]string(nil), ac.Include...)
exclude := append([]string(nil), ac.Exclude...)
agentChanges, fErr := applyFilterUpdates(&include, &exclude, filterOpts.Agents)
if fErr != nil {
return fErr
}
if len(agentChanges) > 0 {
a := entry.EnsureAgents()
a.Include = include
a.Exclude = exclude
mutated = true
}
changes = append(changes, scopeFilterChanges("agents", agentChanges)...)
}
if mutated {
if err := cfg.Save(root); err != nil {
return err
}
}
for _, change := range changes {
ui.Success("%s: %s", name, change)
@@ -385,12 +422,16 @@ func targetInfoProject(name string, args []string, root string) error {
return nil
}
if newMode != "" {
return updateTargetModeProject(cfg, targetIdx, newMode, root)
if settings.SkillMode != "" {
return updateTargetModeProject(cfg, targetIdx, settings.SkillMode, root)
}
if newNaming != "" {
return updateTargetNamingProject(cfg, targetIdx, newNaming, root)
if settings.AgentMode != "" {
return updateTargetAgentModeProject(cfg, targetIdx, settings.AgentMode, root)
}
if settings.Naming != "" {
return updateTargetNamingProject(cfg, targetIdx, settings.Naming, root)
}
targets, err := config.ResolveProjectTargets(root, cfg)
@@ -405,6 +446,14 @@ func targetInfoProject(name string, args []string, root string) error {
targetEntry := cfg.Targets[targetIdx]
sourcePath := filepath.Join(root, ".skillshare", "skills")
agentBuilder, err := targetsummary.NewProjectBuilder(root)
if err != nil {
return err
}
agentSummary, err := agentBuilder.ProjectTarget(targetEntry)
if err != nil {
return err
}
sc := targetEntry.SkillsConfig()
mode := sc.Mode
@@ -439,6 +488,7 @@ func targetInfoProject(name string, args []string, root string) error {
fmt.Printf(" Include: %s\n", formatFilterList(sc.Include))
fmt.Printf(" Exclude: %s\n", formatFilterList(sc.Exclude))
printTargetAgentSection(agentSummary)
return nil
}
@@ -464,6 +514,38 @@ func updateTargetModeProject(cfg *config.ProjectConfig, idx int, newMode string,
return nil
}
func updateTargetAgentModeProject(cfg *config.ProjectConfig, idx int, newMode string, root string) error {
if newMode != "merge" && newMode != "symlink" && newMode != "copy" {
return fmt.Errorf("invalid agent mode '%s'. Use 'merge', 'symlink', or 'copy'", newMode)
}
entry := &cfg.Targets[idx]
agentBuilder, err := targetsummary.NewProjectBuilder(root)
if err != nil {
return err
}
agentSummary, err := agentBuilder.ProjectTarget(*entry)
if err != nil {
return err
}
if agentSummary == nil {
return fmt.Errorf("target '%s' does not have an agents path", entry.Name)
}
oldMode := agentSummary.Mode
entry.EnsureAgents().Mode = newMode
if err := cfg.Save(root); err != nil {
return err
}
ui.Success("Changed %s agent mode: %s -> %s", entry.Name, oldMode, newMode)
if newMode == "symlink" && (len(agentSummary.Include) > 0 || len(agentSummary.Exclude) > 0) {
ui.Warning("Agent include/exclude filters are ignored in symlink mode")
}
ui.Info("Run 'skillshare sync' to apply the new mode")
return nil
}
func updateTargetNamingProject(cfg *config.ProjectConfig, idx int, newNaming string, root string) error {
if !config.IsValidTargetNaming(newNaming) {
return fmt.Errorf("invalid target naming '%s'. Use 'flat' or 'standard'", newNaming)
+104 -36
View File
@@ -3,6 +3,7 @@ package main
import (
"fmt"
"os"
"sort"
"strings"
"time"
@@ -33,6 +34,9 @@ func cmdTrash(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare trash agents list" or "--all").
kind, rest := parseKindArgWithAll(rest)
if len(rest) == 0 {
printTrashHelp()
return nil
@@ -54,13 +58,13 @@ func cmdTrash(args []string) error {
switch sub {
case "list", "ls":
return trashList(mode, cwd, noTUI)
return trashList(mode, cwd, noTUI, kind)
case "restore":
return trashRestore(mode, cwd, filteredArgs)
return trashRestore(mode, cwd, filteredArgs, kind)
case "delete", "rm":
return trashDelete(mode, cwd, filteredArgs)
return trashDelete(mode, cwd, filteredArgs, kind)
case "empty":
return trashEmpty(mode, cwd)
return trashEmpty(mode, cwd, kind)
case "--help", "-h", "help":
printTrashHelp()
return nil
@@ -70,8 +74,56 @@ func cmdTrash(args []string) error {
}
}
func trashList(mode runMode, cwd string, noTUI bool) error {
trashBase := resolveTrashBase(mode, cwd)
func trashList(mode runMode, cwd string, noTUI bool, kind resourceKindFilter) error {
// TUI path: merge skill + agent trash when kind includes both
if shouldLaunchTUI(noTUI, nil) {
var items []trash.TrashEntry
if kind.IncludesSkills() {
skillBase := resolveTrashBase(mode, cwd, kindSkills)
for _, e := range trash.List(skillBase) {
e.Kind = "skill"
items = append(items, e)
}
}
if kind.IncludesAgents() {
agentBase := resolveTrashBase(mode, cwd, kindAgents)
for _, e := range trash.List(agentBase) {
e.Kind = "agent"
items = append(items, e)
}
}
if len(items) == 0 {
ui.Info("Trash is empty")
return nil
}
// Sort merged list by date (newest first)
sort.Slice(items, func(i, j int) bool {
return items[i].Date.After(items[j].Date)
})
modeLabel := "global"
if mode == modeProject {
modeLabel = "project"
}
skillTrashBase := resolveTrashBase(mode, cwd, kindSkills)
agentTrashBase := resolveTrashBase(mode, cwd, kindAgents)
cfgPath := resolveTrashCfgPath(mode, cwd)
destDir, err := resolveSourceDir(mode, cwd, kindSkills)
if err != nil {
return err
}
agentDestDir, err := resolveSourceDir(mode, cwd, kindAgents)
if err != nil {
return err
}
return runTrashTUI(items, skillTrashBase, agentTrashBase, destDir, agentDestDir, cfgPath, modeLabel)
}
// Plain text path (unchanged) — list single kind
trashBase := resolveTrashBase(mode, cwd, kind)
items := trash.List(trashBase)
if len(items) == 0 {
@@ -79,21 +131,6 @@ func trashList(mode runMode, cwd string, noTUI bool) error {
return nil
}
// TUI dispatch: TTY + items + TUI enabled
if shouldLaunchTUI(noTUI, nil) {
modeLabel := "global"
if mode == modeProject {
modeLabel = "project"
}
cfgPath := resolveTrashCfgPath(mode, cwd)
destDir, err := resolveSourceDir(mode, cwd)
if err != nil {
return err
}
return runTrashTUI(items, trashBase, destDir, cfgPath, modeLabel)
}
// Plain text output (--no-tui or non-TTY)
ui.Header("Trash")
for _, item := range items {
age := time.Since(item.Date)
@@ -110,7 +147,7 @@ func trashList(mode runMode, cwd string, noTUI bool) error {
return nil
}
func trashRestore(mode runMode, cwd string, args []string) error {
func trashRestore(mode runMode, cwd string, args []string, kind resourceKindFilter) error {
start := time.Now()
var name string
@@ -136,7 +173,7 @@ func trashRestore(mode runMode, cwd string, args []string) error {
cfgPath := resolveTrashCfgPath(mode, cwd)
trashBase := resolveTrashBase(mode, cwd)
trashBase := resolveTrashBase(mode, cwd, kind)
entry := trash.FindByName(trashBase, name)
if entry == nil {
cmdErr := fmt.Errorf("'%s' not found in trash", name)
@@ -144,28 +181,39 @@ func trashRestore(mode runMode, cwd string, args []string) error {
return cmdErr
}
destDir, err := resolveSourceDir(mode, cwd)
destDir, err := resolveSourceDir(mode, cwd, kind)
if err != nil {
logTrashOp(cfgPath, "restore", 0, name, start, err)
return err
}
if err := trash.Restore(entry, destDir); err != nil {
logTrashOp(cfgPath, "restore", 0, name, start, err)
return err
if kind == kindAgents {
if err := trash.RestoreAgent(entry, destDir); err != nil {
logTrashOp(cfgPath, "restore", 0, name, start, err)
return err
}
} else {
if err := trash.Restore(entry, destDir); err != nil {
logTrashOp(cfgPath, "restore", 0, name, start, err)
return err
}
}
ui.Success("Restored: %s", name)
age := time.Since(entry.Date)
ui.Info("Trashed %s ago, now back in %s", formatAge(age), destDir)
ui.SectionLabel("Next Steps")
ui.Info("Run 'skillshare sync' to update targets")
syncHint := "skillshare sync"
if kind == kindAgents {
syncHint = "skillshare sync agents"
}
ui.Info("Run '%s' to update targets", syncHint)
logTrashOp(cfgPath, "restore", 1, name, start, nil)
return nil
}
func trashDelete(mode runMode, cwd string, args []string) error {
func trashDelete(mode runMode, cwd string, args []string, kind resourceKindFilter) error {
var name string
for _, arg := range args {
switch {
@@ -187,7 +235,7 @@ func trashDelete(mode runMode, cwd string, args []string) error {
return fmt.Errorf("skill name is required")
}
trashBase := resolveTrashBase(mode, cwd)
trashBase := resolveTrashBase(mode, cwd, kind)
entry := trash.FindByName(trashBase, name)
if entry == nil {
return fmt.Errorf("'%s' not found in trash", name)
@@ -201,11 +249,11 @@ func trashDelete(mode runMode, cwd string, args []string) error {
return nil
}
func trashEmpty(mode runMode, cwd string) error {
func trashEmpty(mode runMode, cwd string, kind resourceKindFilter) error {
start := time.Now()
cfgPath := resolveTrashCfgPath(mode, cwd)
trashBase := resolveTrashBase(mode, cwd)
trashBase := resolveTrashBase(mode, cwd, kind)
items := trash.List(trashBase)
if len(items) == 0 {
@@ -238,14 +286,30 @@ func trashEmpty(mode runMode, cwd string) error {
return nil
}
func resolveTrashBase(mode runMode, cwd string) string {
func resolveTrashBase(mode runMode, cwd string, kind resourceKindFilter) string {
if kind == kindAgents {
if mode == modeProject {
return trash.ProjectAgentTrashDir(cwd)
}
return trash.AgentTrashDir()
}
if mode == modeProject {
return trash.ProjectTrashDir(cwd)
}
return trash.TrashDir()
}
func resolveSourceDir(mode runMode, cwd string) (string, error) {
func resolveSourceDir(mode runMode, cwd string, kind resourceKindFilter) (string, error) {
if kind == kindAgents {
if mode == modeProject {
return fmt.Sprintf("%s/.skillshare/agents", cwd), nil
}
cfg, err := config.Load()
if err != nil {
return "", fmt.Errorf("failed to load config: %w", err)
}
return cfg.EffectiveAgentsSource(), nil
}
if mode == modeProject {
return fmt.Sprintf("%s/.skillshare/skills", cwd), nil
}
@@ -285,7 +349,7 @@ func logTrashOp(cfgPath string, action string, count int, name string, start tim
}
func printTrashHelp() {
fmt.Println(`Usage: skillshare trash <command> [options]
fmt.Println(`Usage: skillshare trash [agents] <command> [options]
Manage uninstalled skills in the trash.
@@ -296,6 +360,7 @@ Commands:
empty Permanently delete all items from trash
Options:
--all Include both skills and agents
--no-tui Disable interactive TUI, use plain text output
--project, -p Use project-level trash
--global, -g Use global trash
@@ -307,5 +372,8 @@ Examples:
skillshare trash restore my-skill # Restore from trash
skillshare trash restore my-skill -p # Restore in project mode
skillshare trash delete my-skill # Permanently delete from trash
skillshare trash empty # Empty the trash`)
skillshare trash empty # Empty the trash
skillshare trash agents list # List trashed agents
skillshare trash agents restore tutor # Restore an agent from trash
skillshare trash --all list # List trashed skills + agents`)
}
+140 -60
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -13,6 +14,7 @@ import (
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"skillshare/internal/theme"
"skillshare/internal/trash"
)
@@ -33,9 +35,15 @@ func (i trashItem) Title() string {
if i.selected {
check = "[x]"
}
var kindBadge string
if i.entry.Kind == "agent" {
kindBadge = theme.Accent().Render("[A]") + " "
} else {
kindBadge = theme.Accent().Render("[S]") + " "
}
age := formatAge(time.Since(i.entry.Date))
size := formatBytes(i.entry.Size)
return fmt.Sprintf("%s %s (%s, %s ago)", check, i.entry.Name, size, age)
return fmt.Sprintf("%s %s%s (%s, %s ago)", check, kindBadge, i.entry.Name, size, age)
}
func (i trashItem) Description() string { return "" }
@@ -51,14 +59,16 @@ type trashOpDoneMsg struct {
// trashTUIModel is the bubbletea model for the interactive trash viewer.
type trashTUIModel struct {
list list.Model
modeLabel string // "global" or "project"
trashBase string
destDir string
cfgPath string
quitting bool
termWidth int
termHeight int
list list.Model
modeLabel string // "global" or "project"
skillTrashBase string // for reload after operations
agentTrashBase string // for reload after operations
destDir string // skill restore destination
agentDestDir string // agent restore destination
cfgPath string
quitting bool
termWidth int
termHeight int
// All items (source of truth for filter + selection)
allItems []trashItem
@@ -90,7 +100,7 @@ type trashTUIModel struct {
detailScroll int
}
func newTrashTUIModel(items []trash.TrashEntry, trashBase, destDir, cfgPath, modeLabel string) trashTUIModel {
func newTrashTUIModel(items []trash.TrashEntry, skillTrashBase, agentTrashBase, destDir, agentDestDir, cfgPath, modeLabel string) trashTUIModel {
allItems := make([]trashItem, len(items))
listItems := make([]list.Item, len(items))
for i, entry := range items {
@@ -101,7 +111,7 @@ func newTrashTUIModel(items []trash.TrashEntry, trashBase, destDir, cfgPath, mod
l := list.New(listItems, newPrefixDelegate(false), 0, 0)
l.Title = trashTUITitle(modeLabel, len(items))
l.Styles.Title = tc.ListTitle
l.Styles.Title = theme.Title()
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
@@ -110,25 +120,27 @@ func newTrashTUIModel(items []trash.TrashEntry, trashBase, destDir, cfgPath, mod
// Spinner for operations
sp := spinner.New()
sp.Spinner = spinner.Dot
sp.Style = tc.SpinnerStyle
sp.Style = theme.Accent()
// Filter text input
fi := textinput.New()
fi.Prompt = "/ "
fi.PromptStyle = tc.Filter
fi.Cursor.Style = tc.Filter
fi.PromptStyle = theme.Accent()
fi.Cursor.Style = theme.Accent()
return trashTUIModel{
list: l,
modeLabel: modeLabel,
trashBase: trashBase,
destDir: destDir,
cfgPath: cfgPath,
allItems: allItems,
matchCount: len(allItems),
filterInput: fi,
selected: make(map[int]bool),
opSpinner: sp,
list: l,
modeLabel: modeLabel,
skillTrashBase: skillTrashBase,
agentTrashBase: agentTrashBase,
destDir: destDir,
agentDestDir: agentDestDir,
cfgPath: cfgPath,
allItems: allItems,
matchCount: len(allItems),
filterInput: fi,
selected: make(map[int]bool),
opSpinner: sp,
}
}
@@ -222,12 +234,12 @@ func (m trashTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
verb := capitalize(msg.action) + "d"
switch {
case msg.err != nil && msg.count > 0:
m.lastOpMsg = tc.Green.Render(fmt.Sprintf("%s %d item(s)", verb, msg.count)) +
" " + tc.Red.Render(fmt.Sprintf("Failed: %s", msg.err))
m.lastOpMsg = theme.Success().Render(fmt.Sprintf("%s %d item(s)", verb, msg.count)) +
" " + theme.Danger().Render(fmt.Sprintf("Failed: %s", msg.err))
case msg.err != nil:
m.lastOpMsg = tc.Red.Render(fmt.Sprintf("Error: %s", msg.err))
m.lastOpMsg = theme.Danger().Render(fmt.Sprintf("Error: %s", msg.err))
default:
m.lastOpMsg = tc.Green.Render(fmt.Sprintf("%s %d item(s)", verb, msg.count))
m.lastOpMsg = theme.Success().Render(fmt.Sprintf("%s %d item(s)", verb, msg.count))
}
m.rebuildFromEntries(msg.reloadedItems)
return m, nil
@@ -492,9 +504,11 @@ func (m trashTUIModel) startOperation() (tea.Model, tea.Cmd) {
} else {
entries = m.selectedEntries()
}
trashBase := m.trashBase
destDir := m.destDir
agentDestDir := m.agentDestDir
cfgPath := m.cfgPath
skillTrashBase := m.skillTrashBase
agentTrashBase := m.agentTrashBase
cmd := func() tea.Msg {
start := time.Now()
@@ -505,8 +519,14 @@ func (m trashTUIModel) startOperation() (tea.Model, tea.Cmd) {
case "restore":
for _, entry := range entries {
e := entry // copy for closure
if err := trash.Restore(&e, destDir); err != nil {
errMsgs = append(errMsgs, fmt.Sprintf("%s: %s", entry.Name, err))
var restoreErr error
if e.Kind == "agent" {
restoreErr = trash.RestoreAgent(&e, agentDestDir)
} else {
restoreErr = trash.Restore(&e, destDir)
}
if restoreErr != nil {
errMsgs = append(errMsgs, fmt.Sprintf("%s: %s", entry.Name, restoreErr))
continue // don't stop — process remaining items
}
count++
@@ -530,8 +550,19 @@ func (m trashTUIModel) startOperation() (tea.Model, tea.Cmd) {
// Log the operation
logTrashOp(cfgPath, action, count, "", start, opErr)
// Reload items from disk
reloaded := trash.List(trashBase)
// Reload items from disk — merge skill + agent trash
var reloaded []trash.TrashEntry
for _, e := range trash.List(skillTrashBase) {
e.Kind = "skill"
reloaded = append(reloaded, e)
}
for _, e := range trash.List(agentTrashBase) {
e.Kind = "agent"
reloaded = append(reloaded, e)
}
sort.Slice(reloaded, func(i, j int) bool {
return reloaded[i].Date.After(reloaded[j].Date)
})
return trashOpDoneMsg{
action: action,
count: count,
@@ -620,7 +651,7 @@ func (m trashTUIModel) viewTrashSplit() string {
}
help := appendScrollInfo(m.trashHelpBar(), scrollInfo)
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
@@ -656,7 +687,7 @@ func (m trashTUIModel) viewTrashVertical() string {
}
help := appendScrollInfo(m.trashHelpBar(), scrollInfo)
b.WriteString(tc.Help.Render(help))
b.WriteString(theme.Dim().MarginLeft(2).Render(help))
b.WriteString("\n")
return b.String()
@@ -670,14 +701,15 @@ func (m trashTUIModel) viewConfirm() string {
verb := m.confirmAction
switch verb {
case "restore":
b.WriteString(fmt.Sprintf(" Restore %d item(s) to %s?\n\n", len(m.confirmNames), m.destDir))
b.WriteString(m.renderRestoreConfirmHeader())
b.WriteString("\n")
case "delete":
b.WriteString(" ")
b.WriteString(tc.Red.Render(fmt.Sprintf("Permanently delete %d item(s)?", len(m.confirmNames))))
b.WriteString(theme.Danger().Render(fmt.Sprintf("Permanently delete %d item(s)?", len(m.confirmNames))))
b.WriteString("\n\n")
case "empty":
b.WriteString(" ")
b.WriteString(tc.Red.Render(fmt.Sprintf("Empty trash — permanently delete ALL %d item(s)?", len(m.confirmNames))))
b.WriteString(theme.Danger().Render(fmt.Sprintf("Empty trash — permanently delete ALL %d item(s)?", len(m.confirmNames))))
b.WriteString("\n\n")
}
@@ -694,12 +726,38 @@ func (m trashTUIModel) viewConfirm() string {
}
b.WriteString("\n ")
b.WriteString(tc.Help.Render("y confirm n cancel"))
b.WriteString(theme.Dim().MarginLeft(2).Render("y confirm n cancel"))
b.WriteString("\n")
return b.String()
}
func (m trashTUIModel) renderRestoreConfirmHeader() string {
var hasSkills, hasAgents bool
for _, entry := range m.selectedEntries() {
switch entry.Kind {
case "agent":
hasAgents = true
default:
hasSkills = true
}
}
switch {
case hasSkills && hasAgents:
return fmt.Sprintf(
" Restore %d item(s)?\n\n skills -> %s\n agents -> %s\n",
len(m.confirmNames),
m.destDir,
m.agentDestDir,
)
case hasAgents:
return fmt.Sprintf(" Restore %d item(s) to %s?\n", len(m.confirmNames), m.agentDestDir)
default:
return fmt.Sprintf(" Restore %d item(s) to %s?\n", len(m.confirmNames), m.destDir)
}
}
// ---------------------------------------------------------------------------
// Rendering helpers
// ---------------------------------------------------------------------------
@@ -736,11 +794,11 @@ func (m trashTUIModel) renderTrashSummaryFooter() string {
totalSize += item.entry.Size
}
parts := []string{
tc.Emphasis.Render(formatNumber(m.matchCount)) + tc.Dim.Render("/") +
tc.Dim.Render(formatNumber(len(m.allItems))) + tc.Dim.Render(" items"),
tc.Dim.Render("Total: ") + tc.Cyan.Render(formatBytes(totalSize)),
theme.Primary().Render(formatNumber(m.matchCount)) + theme.Dim().Render("/") +
theme.Dim().Render(formatNumber(len(m.allItems))) + theme.Dim().Render(" items"),
theme.Dim().Render("Total: ") + theme.Accent().Render(formatBytes(totalSize)),
}
return tc.Help.Render(strings.Join(parts, tc.Dim.Render(" | "))) + "\n"
return theme.Dim().MarginLeft(2).Render(strings.Join(parts, theme.Dim().Render(" | "))) + "\n"
}
// renderTrashDetailPanel renders the detail section for the selected trash entry.
@@ -748,7 +806,7 @@ func (m trashTUIModel) renderTrashDetailPanel(entry trash.TrashEntry, width int)
var b strings.Builder
// Header: bold skill name
b.WriteString(tc.Title.Render(entry.Name))
b.WriteString(theme.Title().Render(entry.Name))
b.WriteString("\n\n")
// Metadata rows
@@ -756,10 +814,15 @@ func (m trashTUIModel) renderTrashDetailPanel(entry trash.TrashEntry, width int)
row := func(label, value string) {
b.WriteString(labelStyle.Render(label + ":"))
b.WriteString(" ")
b.WriteString(tc.Value.Render(value))
b.WriteString(lipgloss.NewStyle().Render(value))
b.WriteString("\n")
}
if entry.Kind == "agent" {
row("Type", theme.Accent().Render("Agent"))
} else {
row("Type", theme.Accent().Render("Skill"))
}
row("Trashed", entry.Date.Format("2006-01-02 15:04:05"))
row("Age", formatAge(time.Since(entry.Date))+" ago")
row("Size", formatBytes(entry.Size))
@@ -772,21 +835,38 @@ func (m trashTUIModel) renderTrashDetailPanel(entry trash.TrashEntry, width int)
}
row("Path", pathStr)
// SKILL.md preview — read first 15 lines
skillMD := filepath.Join(entry.Path, "SKILL.md")
if data, err := os.ReadFile(skillMD); err == nil {
lines := strings.SplitN(string(data), "\n", 16)
if len(lines) > 15 {
lines = lines[:15]
// Content preview — SKILL.md for skills, agent .md file for agents
var previewFile, previewTitle string
if entry.Kind == "agent" {
// Find the .md file inside the trash directory
if entries, readErr := os.ReadDir(entry.Path); readErr == nil {
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".md") {
previewFile = filepath.Join(entry.Path, e.Name())
previewTitle = e.Name()
break
}
}
}
preview := strings.TrimRight(strings.Join(lines, "\n"), "\n")
if preview != "" {
b.WriteString("\n")
b.WriteString(tc.Title.Render("SKILL.md"))
b.WriteString("\n")
for _, line := range strings.Split(preview, "\n") {
b.WriteString(tc.Dim.Render(line))
} else {
previewFile = filepath.Join(entry.Path, "SKILL.md")
previewTitle = "SKILL.md"
}
if previewFile != "" {
if data, err := os.ReadFile(previewFile); err == nil {
lines := strings.SplitN(string(data), "\n", 16)
if len(lines) > 15 {
lines = lines[:15]
}
preview := strings.TrimRight(strings.Join(lines, "\n"), "\n")
if preview != "" {
b.WriteString("\n")
b.WriteString(theme.Title().Render(previewTitle))
b.WriteString("\n")
for _, line := range strings.Split(preview, "\n") {
b.WriteString(theme.Dim().Render(line))
b.WriteString("\n")
}
}
}
}
@@ -799,8 +879,8 @@ func (m trashTUIModel) renderTrashDetailPanel(entry trash.TrashEntry, width int)
// ---------------------------------------------------------------------------
// runTrashTUI starts the bubbletea TUI for the trash viewer.
func runTrashTUI(items []trash.TrashEntry, trashBase, destDir, cfgPath, modeLabel string) error {
model := newTrashTUIModel(items, trashBase, destDir, cfgPath, modeLabel)
func runTrashTUI(items []trash.TrashEntry, skillTrashBase, agentTrashBase, destDir, agentDestDir, cfgPath, modeLabel string) error {
model := newTrashTUIModel(items, skillTrashBase, agentTrashBase, destDir, agentDestDir, cfgPath, modeLabel)
p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
_, err := p.Run()
return err
+46
View File
@@ -0,0 +1,46 @@
package main
import (
"strings"
"testing"
"skillshare/internal/trash"
)
func TestTrashTUIRenderRestoreConfirmHeader_UsesAgentDestination(t *testing.T) {
model := newTrashTUIModel([]trash.TrashEntry{
{Name: "tutor", Kind: "agent"},
}, "", "", "/tmp/skills", "/tmp/agents", "", "global")
model.selected[0] = true
model.selCount = 1
model.confirmAction = "restore"
model.confirmNames = []string{"tutor"}
got := model.renderRestoreConfirmHeader()
if !strings.Contains(got, "/tmp/agents") {
t.Fatalf("expected agent restore header to use agent destination, got %q", got)
}
if strings.Contains(got, "/tmp/skills") {
t.Fatalf("expected agent restore header to avoid skill destination, got %q", got)
}
}
func TestTrashTUIRenderRestoreConfirmHeader_ShowsMixedDestinations(t *testing.T) {
model := newTrashTUIModel([]trash.TrashEntry{
{Name: "demo-skill", Kind: "skill"},
{Name: "tutor", Kind: "agent"},
}, "", "", "/tmp/skills", "/tmp/agents", "", "global")
model.selected[0] = true
model.selected[1] = true
model.selCount = 2
model.confirmAction = "restore"
model.confirmNames = []string{"demo-skill", "tutor"}
got := model.renderRestoreConfirmHeader()
if !strings.Contains(got, "skills -> /tmp/skills") {
t.Fatalf("expected mixed restore header to mention skills destination, got %q", got)
}
if !strings.Contains(got, "agents -> /tmp/agents") {
t.Fatalf("expected mixed restore header to mention agent destination, got %q", got)
}
}
-149
View File
@@ -1,149 +0,0 @@
package main
import (
"strings"
"skillshare/internal/ui"
"github.com/charmbracelet/lipgloss"
)
// tuiBrandYellow is the logo yellow used for active/selected item borders across all TUIs.
const tuiBrandYellow = lipgloss.Color("#D4D93C")
// tc centralizes shared color styles used across all TUI views.
// Domain-specific structs (ac, lc) reference tc for base colors.
var tc = struct {
BrandYellow lipgloss.Color
// Semantic
Title lipgloss.Style // section headings — bold cyan
Emphasis lipgloss.Style // primary values, bright text — bright white (15)
Dim lipgloss.Style // secondary info, labels, descriptions — SGR dim
Faint lipgloss.Style // decorative chrome, borders, help — SGR dim
Cyan lipgloss.Style // emphasis, targets — cyan
Green lipgloss.Style // ok, passed
Yellow lipgloss.Style // warning
Red lipgloss.Style // error, blocked
// Detail panel
Label lipgloss.Style // row labels (width 14)
Value lipgloss.Style // default foreground
File lipgloss.Style // file names — dim
Target lipgloss.Style // target names — cyan
Separator lipgloss.Style // horizontal rules — faint
Border lipgloss.Style // panel borders — faint
// Filter & help
Filter lipgloss.Style // filter prompt/cursor — cyan
Help lipgloss.Style // help bar — faint, left margin
// List browser chrome
ListRow lipgloss.Style
ListMeta lipgloss.Style
ListRowSelected lipgloss.Style
ListMetaSelected lipgloss.Style
ListRowPrefix lipgloss.Style
ListRowPrefixSelected lipgloss.Style
BadgeLocal lipgloss.Style
BadgeRemote lipgloss.Style
BadgeDisabled lipgloss.Style
// Severity — shared across all TUIs (audit, log, etc.)
Critical lipgloss.Style // red, bold
High lipgloss.Style // orange
Medium lipgloss.Style // yellow
Low lipgloss.Style // bright blue
Info lipgloss.Style // medium gray
// List chrome
ListTitle lipgloss.Style // list title — bold cyan
SpinnerStyle lipgloss.Style // loading spinner — cyan
}{
BrandYellow: lipgloss.Color("#D4D93C"),
Title: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("6")),
Emphasis: lipgloss.NewStyle().Foreground(lipgloss.Color("15")),
Dim: lipgloss.NewStyle().Faint(true),
Faint: lipgloss.NewStyle().Faint(true),
Cyan: lipgloss.NewStyle().Foreground(lipgloss.Color("6")),
Green: lipgloss.NewStyle().Foreground(lipgloss.Color("2")),
Yellow: lipgloss.NewStyle().Foreground(lipgloss.Color("3")),
Red: lipgloss.NewStyle().Foreground(lipgloss.Color("1")),
Label: lipgloss.NewStyle().Faint(true).Width(14),
Value: lipgloss.NewStyle(),
File: lipgloss.NewStyle().Faint(true),
Target: lipgloss.NewStyle().Foreground(lipgloss.Color("6")),
Separator: lipgloss.NewStyle().Faint(true),
Border: lipgloss.NewStyle().Faint(true),
Filter: lipgloss.NewStyle().Foreground(lipgloss.Color("6")),
Help: lipgloss.NewStyle().MarginLeft(2).Faint(true),
ListRow: lipgloss.NewStyle().PaddingLeft(1),
ListMeta: lipgloss.NewStyle().PaddingLeft(1).Faint(true),
ListRowSelected: lipgloss.NewStyle().PaddingLeft(1).Foreground(lipgloss.Color("15")).Background(lipgloss.Color("237")).Bold(true),
ListMetaSelected: lipgloss.NewStyle().PaddingLeft(1).Foreground(lipgloss.Color("250")).Background(lipgloss.Color("237")),
ListRowPrefix: lipgloss.NewStyle().Foreground(lipgloss.Color("235")),
ListRowPrefixSelected: lipgloss.NewStyle().Foreground(tuiBrandYellow),
BadgeLocal: lipgloss.NewStyle().Foreground(lipgloss.Color("250")).Background(lipgloss.Color("237")).
Padding(0, 1),
BadgeRemote: lipgloss.NewStyle().Foreground(lipgloss.Color("228")).Background(lipgloss.Color("239")).
Padding(0, 1),
BadgeDisabled: lipgloss.NewStyle().Foreground(lipgloss.Color("245")).Background(lipgloss.Color("236")).
Padding(0, 1).Faint(true),
Critical: lipgloss.NewStyle().Foreground(lipgloss.Color(ui.SeverityIDCritical)).Bold(true),
High: lipgloss.NewStyle().Foreground(lipgloss.Color(ui.SeverityIDHigh)),
Medium: lipgloss.NewStyle().Foreground(lipgloss.Color(ui.SeverityIDMedium)),
Low: lipgloss.NewStyle().Foreground(lipgloss.Color(ui.SeverityIDLow)),
Info: lipgloss.NewStyle().Foreground(lipgloss.Color(ui.SeverityIDInfo)),
ListTitle: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("6")),
SpinnerStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("6")),
}
// tcSevStyle returns the severity lipgloss style from the centralized tc config.
func tcSevStyle(severity string) lipgloss.Style {
switch strings.ToUpper(severity) {
case "CRITICAL":
return tc.Critical
case "HIGH":
return tc.High
case "MEDIUM":
return tc.Medium
case "LOW":
return tc.Low
case "INFO":
return tc.Info
default:
return tc.Dim
}
}
// riskLabelStyle maps a lowercase risk label to the matching lipgloss style.
func riskLabelStyle(label string) lipgloss.Style {
switch strings.ToLower(label) {
case "clean":
return tc.Green
case "low":
return tc.Low
case "medium":
return tc.Medium
case "high":
return tc.High
case "critical":
return tc.Critical
default:
return tc.Dim
}
}
// formatRiskBadgeLipgloss returns a colored risk badge for TUI list items.
func formatRiskBadgeLipgloss(label string) string {
if label == "" {
return ""
}
return " " + riskLabelStyle(label).Render("["+label+"]")
}
+27 -1
View File
@@ -7,6 +7,7 @@ import (
"github.com/charmbracelet/lipgloss"
"skillshare/internal/config"
"skillshare/internal/theme"
"skillshare/internal/ui"
)
@@ -46,6 +47,31 @@ func appendScrollInfo(help, scrollInfo string) string {
return help
}
// formatHelpBar colorizes a help string like "Tab skills/agents ↑↓ navigate q quit".
// Each pair "key desc" is parsed: key gets HelpKey style (dim cyan), desc stays dim.
// Pairs are separated by two or more spaces.
func formatHelpBar(raw string) string {
// Split by double-space to get individual "key desc" pairs
pairs := strings.Split(raw, " ")
var parts []string
for _, pair := range pairs {
pair = strings.TrimSpace(pair)
if pair == "" {
continue
}
// Split first space: key + description
if idx := strings.IndexByte(pair, ' '); idx > 0 {
key := pair[:idx]
desc := pair[idx:]
parts = append(parts, theme.Accent().Faint(true).Render(key)+theme.Dim().MarginLeft(2).UnsetMarginLeft().Render(desc))
} else {
// Single word (e.g. just a key)
parts = append(parts, theme.Accent().Faint(true).Render(pair))
}
}
return " " + strings.Join(parts, " ")
}
// applyDetailScrollSplit applies scrolling and returns (visible content, scroll info).
func applyDetailScrollSplit(content string, detailScroll, viewHeight int) (string, string) {
lines := strings.Split(content, "\n")
@@ -102,7 +128,7 @@ func renderHorizontalSplit(leftContent, rightContent string, leftWidth, rightWid
Height(panelHeight).MaxHeight(panelHeight).
Render(leftContent)
borderStyle := tc.Border.
borderStyle := theme.Dim().
Height(panelHeight).MaxHeight(panelHeight)
borderCol := strings.Repeat("│\n", panelHeight)
borderPanel := borderStyle.Render(strings.TrimRight(borderCol, "\n"))
+57 -51
View File
@@ -23,9 +23,10 @@ import (
// uninstallOptions holds parsed arguments for uninstall command
type uninstallOptions struct {
skillNames []string // positional args (0+)
groups []string // --group/-G values (repeatable)
all bool // --all: remove ALL skills from source
skillNames []string // positional args (0+)
groups []string // --group/-G values (repeatable)
kind resourceKindFilter // set by positional filter (e.g. "uninstall agents")
all bool // --all: remove ALL skills from source
force bool
dryRun bool
jsonOutput bool
@@ -396,7 +397,7 @@ func (s uninstallTypeSummary) details() string {
}
// displayUninstallInfo shows information about the skill to be uninstalled
func displayUninstallInfo(target *uninstallTarget) {
func displayUninstallInfo(target *uninstallTarget, store *install.MetadataStore) {
if target.isTrackedRepo {
ui.Header("Uninstalling tracked repository")
ui.Info("Type: tracked repository")
@@ -411,9 +412,11 @@ func displayUninstallInfo(target *uninstallTarget) {
} else {
ui.Header("Uninstalling skill")
}
if meta, err := install.ReadMeta(target.path); err == nil && meta != nil {
ui.Info("Source: %s", meta.Source)
ui.Info("Installed: %s", meta.InstalledAt.Format("2006-01-02 15:04"))
if entry := store.Get(target.name); entry != nil {
ui.Info("Source: %s", entry.Source)
if !entry.InstalledAt.IsZero() {
ui.Info("Installed: %s", entry.InstalledAt.Format("2006-01-02 15:04"))
}
}
}
ui.Info("Name: %s", target.name)
@@ -491,9 +494,9 @@ func performUninstallQuiet(target *uninstallTarget) (typeLabel string, err error
// performUninstall moves the skill to trash (verbose single-target output).
// Note: .gitignore cleanup is handled in batch by the caller.
func performUninstall(target *uninstallTarget) error {
func performUninstall(target *uninstallTarget, store *install.MetadataStore) error {
// Read metadata before moving (for reinstall hint)
meta, _ := install.ReadMeta(target.path)
entry := store.Get(target.name)
groupSkillCount := 0
if !target.isTrackedRepo {
groupSkillCount = len(countGroupSkills(target.path))
@@ -512,8 +515,8 @@ func performUninstall(target *uninstallTarget) error {
ui.Success("Uninstalled skill: %s", target.name)
}
ui.Info("Moved to trash (7 days): %s", trashPath)
if meta != nil && meta.Source != "" {
ui.Info("Reinstall: skillshare install %s", meta.Source)
if entry != nil && entry.Source != "" {
ui.Info("Reinstall: skillshare install %s", entry.Source)
}
ui.SectionLabel("Next Steps")
ui.Info("Run 'skillshare sync' to update all targets")
@@ -549,7 +552,20 @@ func cmdUninstall(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare uninstall agents myagent").
kind, rest := parseKindArg(rest)
if mode == modeProject {
if kind == kindAgents {
agentsDir := filepath.Join(cwd, ".skillshare", "agents")
opts, _, _ := parseUninstallArgs(rest)
if opts == nil {
opts = &uninstallOptions{skillNames: rest}
}
opts.force = opts.force || opts.jsonOutput
err := cmdUninstallAgents(agentsDir, opts, config.ProjectConfigPath(cwd), trash.ProjectAgentTrashDir(cwd), start)
return err
}
err := cmdUninstallProject(rest, cwd)
logUninstallOp(config.ProjectConfigPath(cwd), uninstallOpNames(rest), 0, start, err)
return err
@@ -577,6 +593,19 @@ func cmdUninstall(args []string) error {
return fmt.Errorf("failed to load config: %w", err)
}
// Agent-only uninstall: move .md + sidecar to agent trash, then return.
if kind == kindAgents {
agentsDir := cfg.EffectiveAgentsSource()
err := cmdUninstallAgents(agentsDir, opts, config.ConfigPath(), trash.AgentTrashDir(), start)
return err
}
// Load centralized metadata store for display/reinstall hints.
skillsStore, _ := install.LoadMetadataWithMigration(cfg.Source, "")
if skillsStore == nil {
skillsStore = install.NewMetadataStore()
}
// --- Phase 1: RESOLVE ---
var targets []*uninstallTarget
seen := map[string]bool{} // dedup by path
@@ -711,7 +740,7 @@ func cmdUninstall(args []string) error {
if opts.jsonOutput {
// Skip display in JSON mode
} else if single {
displayUninstallInfo(targets[0])
displayUninstallInfo(targets[0], skillsStore)
} else {
ui.Header(fmt.Sprintf("Uninstalling %d %s", len(targets), summary.noun()))
if len(targets) > 20 {
@@ -853,8 +882,8 @@ func cmdUninstall(args []string) error {
if t.isTrackedRepo {
ui.Warning("[dry-run] would remove %s from .gitignore", t.name)
}
if meta, err := install.ReadMeta(t.path); err == nil && meta != nil && meta.Source != "" {
ui.Info("[dry-run] Reinstall: skillshare install %s", meta.Source)
if entry := skillsStore.Get(t.name); entry != nil && entry.Source != "" {
ui.Info("[dry-run] Reinstall: skillshare install %s", entry.Source)
}
}
return nil
@@ -1015,7 +1044,7 @@ func cmdUninstall(args []string) error {
}
} else {
for _, t := range targets {
if err := performUninstall(t); err != nil {
if err := performUninstall(t, skillsStore); err != nil {
failed = append(failed, fmt.Sprintf("%s: %v", t.name, err))
} else {
succeeded = append(succeeded, t)
@@ -1039,42 +1068,15 @@ func cmdUninstall(args []string) error {
}
// --- Phase 7: FINALIZE ---
// Batch-remove succeeded skills from registry
// Batch-remove succeeded skills from metadata store
if len(succeeded) > 0 {
regDir := cfg.RegistryDir
reg, regErr := config.LoadRegistry(regDir)
if regErr != nil {
ui.Warning("Failed to load registry: %v", regErr)
} else if len(reg.Skills) > 0 {
removedNames := map[string]bool{}
for _, t := range succeeded {
removedNames[t.name] = true
}
updated := make([]config.SkillEntry, 0, len(reg.Skills))
for _, s := range reg.Skills {
fullName := s.FullName()
if removedNames[fullName] {
continue
}
// When a group directory is uninstalled, also remove its member skills
memberOfRemoved := false
for name := range removedNames {
if strings.HasPrefix(fullName, name+"/") {
memberOfRemoved = true
break
}
}
if memberOfRemoved {
continue
}
updated = append(updated, s)
}
if len(updated) != len(reg.Skills) {
reg.Skills = updated
if saveErr := reg.Save(regDir); saveErr != nil {
ui.Warning("Failed to update registry after uninstall: %v", saveErr)
}
}
removedNames := map[string]bool{}
for _, t := range succeeded {
removedNames[t.name] = true
}
skillsStore.RemoveByNames(removedNames)
if saveErr := skillsStore.Save(cfg.Source); saveErr != nil {
ui.Warning("Failed to update metadata after uninstall: %v", saveErr)
}
}
@@ -1152,6 +1154,7 @@ func logUninstallOp(cfgPath string, names []string, succeeded int, start time.Ti
func printUninstallHelp() {
fmt.Println(`Usage: skillshare uninstall <name>... [options]
skillshare uninstall [agents] <name|--all> [options]
skillshare uninstall --group <group> [options]
skillshare uninstall --all [options]
@@ -1187,5 +1190,8 @@ Examples:
skillshare uninstall --group frontend -n # Preview group removal
skillshare uninstall x -G backend --force # Mix names and groups
skillshare uninstall _team-repo # Remove tracked repository
skillshare uninstall team-repo # _ prefix is optional`)
skillshare uninstall team-repo # _ prefix is optional
skillshare uninstall agents tutor # Uninstall an agent
skillshare uninstall agents --all # Uninstall all agents
skillshare uninstall agents -G demo # Uninstall all agents in demo/`)
}
+198
View File
@@ -0,0 +1,198 @@
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"skillshare/internal/install"
"skillshare/internal/oplog"
"skillshare/internal/resource"
"skillshare/internal/trash"
"skillshare/internal/ui"
)
// cmdUninstallAgents removes agents from the source directory by moving them to agent trash.
func cmdUninstallAgents(agentsDir string, opts *uninstallOptions, cfgPath string, trashBase string, start time.Time) error {
if _, err := os.Stat(agentsDir); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("agents source directory does not exist: %s", agentsDir)
}
return fmt.Errorf("cannot access agents source: %w", err)
}
// Discover all agents for resolution
discovered, discErr := resource.AgentKind{}.Discover(agentsDir)
if discErr != nil {
return fmt.Errorf("failed to discover agents: %w", discErr)
}
// Resolve targets
var targets []resource.DiscoveredResource
if opts.all {
targets = discovered
if len(targets) == 0 {
ui.Info("No agents found")
return nil
}
} else {
for _, input := range opts.skillNames {
found := false
for _, d := range discovered {
if d.Name == input || d.FlatName == input || d.RelPath == input || strings.TrimSuffix(d.RelPath, ".md") == input {
targets = append(targets, d)
found = true
break
}
}
if !found {
return fmt.Errorf("agent %q not found in %s", input, agentsDir)
}
}
// Resolve --group targets
if len(opts.groups) > 0 {
groupFiltered, err := filterDiscoveredAgentsByGroups(discovered, opts.groups, agentsDir)
if err != nil {
return err
}
if len(groupFiltered) == 0 {
return fmt.Errorf("no agents found in group(s): %s", strings.Join(opts.groups, ", "))
}
// Deduplicate against already-resolved name targets
seen := make(map[string]bool, len(targets))
for _, t := range targets {
seen[t.RelPath] = true
}
for _, d := range groupFiltered {
if !seen[d.RelPath] {
targets = append(targets, d)
}
}
}
}
if len(targets) == 0 {
return fmt.Errorf("specify agent name(s), --group, or --all")
}
// Confirmation (unless --force or --json)
if !opts.force && !opts.jsonOutput {
ui.Warning("Uninstalling %d agent(s)", len(targets))
const maxDisplay = 20
display := targets
if len(display) > maxDisplay {
display = display[:maxDisplay]
}
for _, t := range display {
fmt.Printf(" - %s\n", strings.TrimSuffix(t.RelPath, ".md"))
}
if len(targets) > maxDisplay {
fmt.Printf(" ... and %d more\n", len(targets)-maxDisplay)
}
fmt.Println()
fmt.Print("Continue? [y/N] ")
var input string
fmt.Scanln(&input)
input = strings.TrimSpace(strings.ToLower(input))
if input != "y" && input != "yes" {
ui.Info("Cancelled")
return nil
}
}
store, _ := install.LoadMetadata(agentsDir)
var removed []string
var failed []string
for _, t := range targets {
agentFile := filepath.Join(agentsDir, t.RelPath)
displayName := strings.TrimSuffix(t.RelPath, ".md")
if opts.dryRun {
ui.Info("[dry-run] Would remove agent: %s", displayName)
removed = append(removed, displayName)
continue
}
// Trash the agent file (+ legacy sidecar if it still exists)
metaName := strings.TrimSuffix(filepath.Base(t.RelPath), ".md")
legacySidecar := filepath.Join(filepath.Dir(agentFile), metaName+".skillshare-meta.json")
_, err := trash.MoveAgentToTrash(agentFile, legacySidecar, displayName, trashBase)
if err != nil {
ui.Error("Failed to remove %s: %v", displayName, err)
failed = append(failed, displayName)
continue
}
// Remove from centralized metadata store
if store != nil {
store.Remove(displayName)
}
ui.Success("Removed agent: %s", displayName)
removed = append(removed, displayName)
}
// Save store after all removals
if store != nil && len(removed) > 0 {
store.Save(agentsDir) //nolint:errcheck
}
// JSON output
if opts.jsonOutput {
output := struct {
Removed []string `json:"removed"`
Failed []string `json:"failed"`
DryRun bool `json:"dry_run"`
Duration string `json:"duration"`
}{
Removed: removed,
Failed: failed,
DryRun: opts.dryRun,
Duration: formatDuration(start),
}
var jsonErr error
if len(failed) > 0 {
jsonErr = fmt.Errorf("%d agent(s) failed to uninstall", len(failed))
}
return writeJSONResult(&output, jsonErr)
}
// Summary
if !opts.dryRun {
fmt.Println()
ui.Info("%d agent(s) removed, %d failed", len(removed), len(failed))
if len(removed) > 0 {
ui.Info("Run 'skillshare sync agents' to update targets")
}
}
// Oplog
logUninstallAgentOp(cfgPath, removed, len(removed), len(failed), opts.dryRun, start)
if len(failed) > 0 {
return fmt.Errorf("%d agent(s) failed to uninstall", len(failed))
}
return nil
}
func logUninstallAgentOp(cfgPath string, names []string, removed, failed int, dryRun bool, start time.Time) {
status := "ok"
if failed > 0 && removed > 0 {
status = "partial"
} else if failed > 0 {
status = "error"
}
e := oplog.NewEntry("uninstall", status, time.Since(start))
e.Args = map[string]any{
"resource_kind": "agent",
"names": names,
"removed": removed,
"failed": failed,
"dry_run": dryRun,
}
oplog.WriteWithLimit(cfgPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
}
+20 -41
View File
@@ -7,7 +7,6 @@ import (
"path/filepath"
"strings"
"skillshare/internal/config"
"skillshare/internal/install"
"skillshare/internal/sync"
"skillshare/internal/trash"
@@ -89,6 +88,12 @@ func cmdUninstallProject(args []string, root string) error {
sourceDir := filepath.Join(root, ".skillshare", "skills")
trashDir := trash.ProjectTrashDir(root)
// Load centralized metadata store for display/reinstall hints.
skillsStore, _ := install.LoadMetadataWithMigration(sourceDir, "")
if skillsStore == nil {
skillsStore = install.NewMetadataStore()
}
// Backward compat: ensure operational dirs are gitignored for projects created before v0.17.3.
_ = ensureProjectGitignore(root, false)
@@ -172,7 +177,7 @@ func cmdUninstallProject(args []string, root string) error {
single := len(targets) == 1
summary := summarizeUninstallTargets(targets)
if single {
displayUninstallInfo(targets[0])
displayUninstallInfo(targets[0], skillsStore)
} else {
ui.Header(fmt.Sprintf("Uninstalling %d %s", len(targets), summary.noun()))
if len(targets) > 20 {
@@ -239,8 +244,8 @@ func cmdUninstallProject(args []string, root string) error {
for _, t := range targets {
ui.Warning("[dry-run] would move to trash: %s", t.path)
ui.Warning("[dry-run] would update .skillshare/.gitignore")
if meta, err := install.ReadMeta(t.path); err == nil && meta != nil && meta.Source != "" {
ui.Info("[dry-run] Reinstall: skillshare install %s --project", meta.Source)
if entry := skillsStore.Get(t.name); entry != nil && entry.Source != "" {
ui.Info("[dry-run] Reinstall: skillshare install %s --project", entry.Source)
}
}
return nil
@@ -369,7 +374,7 @@ func cmdUninstallProject(args []string, root string) error {
}
} else {
for _, t := range targets {
meta, _ := install.ReadMeta(t.path)
entry := skillsStore.Get(t.name)
groupSkillCount := 0
if !t.isTrackedRepo {
groupSkillCount = len(countGroupSkills(t.path))
@@ -390,8 +395,8 @@ func cmdUninstallProject(args []string, root string) error {
ui.Success("Uninstalled skill: %s", t.name)
}
ui.Info("Moved to trash (7 days): %s", trashPath)
if meta != nil && meta.Source != "" {
ui.Info("Reinstall: skillshare install %s --project", meta.Source)
if entry != nil && entry.Source != "" {
ui.Info("Reinstall: skillshare install %s --project", entry.Source)
}
succeeded = append(succeeded, t)
}
@@ -409,41 +414,15 @@ func cmdUninstallProject(args []string, root string) error {
}
// --- Phase 7: FINALIZE ---
// Batch-remove succeeded skills from metadata store
if len(succeeded) > 0 {
regDir := filepath.Join(root, ".skillshare")
reg, regErr := config.LoadRegistry(regDir)
if regErr != nil {
ui.Warning("Failed to load registry: %v", regErr)
} else if len(reg.Skills) > 0 {
removedNames := map[string]bool{}
for _, t := range succeeded {
removedNames[t.name] = true
}
updated := make([]config.SkillEntry, 0, len(reg.Skills))
for _, s := range reg.Skills {
fullName := s.FullName()
if removedNames[fullName] {
continue
}
// When a group directory is uninstalled, also remove its member skills
memberOfRemoved := false
for name := range removedNames {
if strings.HasPrefix(fullName, name+"/") {
memberOfRemoved = true
break
}
}
if memberOfRemoved {
continue
}
updated = append(updated, s)
}
if len(updated) != len(reg.Skills) {
reg.Skills = updated
if saveErr := reg.Save(regDir); saveErr != nil {
ui.Warning("Failed to update registry after uninstall: %v", saveErr)
}
}
removedNames := map[string]bool{}
for _, t := range succeeded {
removedNames[t.name] = true
}
skillsStore.RemoveByNames(removedNames)
if saveErr := skillsStore.Save(sourceDir); saveErr != nil {
ui.Warning("Failed to update metadata after uninstall: %v", saveErr)
}
}
+35 -20
View File
@@ -130,6 +130,24 @@ func cmdUpdate(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare update agents")
kind, rest := parseKindArg(rest)
// Agent-only update: dispatch to correct scope
if kind == kindAgents {
if mode == modeProject {
return cmdUpdateAgentsProject(rest, cwd, start)
}
cfg, loadErr := config.Load()
if loadErr != nil {
if hasFlag(rest, "--json") {
return writeJSONError(loadErr)
}
return loadErr
}
return cmdUpdateAgents(rest, cfg, start)
}
if mode == modeProject {
// Parse opts for logging (cmdUpdateProject parses again internally)
projOpts, _, _ := parseUpdateArgs(rest)
@@ -167,24 +185,15 @@ func cmdUpdate(args []string) error {
// In JSON mode, redirect all UI output to stderr early so the
// header, step, spinner, and handler output don't corrupt stdout.
var restoreJSONUI func()
restoreJSONUIIfNeeded := func() {
if restoreJSONUI != nil {
restoreJSONUI()
restoreJSONUI = nil
}
}
if opts.jsonOutput {
restoreJSONUI = suppressUIToDevnull()
}
defer restoreJSONUIIfNeeded()
jsonUI := newJSONUISuppressor(opts.jsonOutput)
defer jsonUI.Flush()
jsonWriteError := func(err error) error {
restoreJSONUIIfNeeded()
jsonUI.Flush()
return writeJSONError(err)
}
jsonWriteResult := func(result *updateResult, cmdErr error) error {
restoreJSONUIIfNeeded()
jsonUI.Flush()
return updateOutputJSON(result, opts.dryRun, start, cmdErr)
}
@@ -200,6 +209,7 @@ func cmdUpdate(args []string) error {
// Recursive discovery for --all
scanSpinner := ui.StartSpinner("Scanning skills...")
walkRoot := utils.ResolveSymlink(cfg.Source)
metaStore, _ := install.LoadMetadataWithMigration(cfg.Source, "")
err := filepath.Walk(walkRoot, func(path string, info os.FileInfo, err error) error {
if err != nil || path == walkRoot {
return nil
@@ -226,12 +236,11 @@ func cmdUpdate(args []string) error {
// Regular skill
if !info.IsDir() && info.Name() == "SKILL.md" {
skillDir := filepath.Dir(path)
meta, metaErr := install.ReadMeta(skillDir)
if metaErr == nil && meta != nil && meta.Source != "" {
rel, _ := filepath.Rel(walkRoot, skillDir)
if rel != "." && !seen[rel] {
rel, _ := filepath.Rel(walkRoot, skillDir)
if rel != "." && !seen[rel] {
if entry := metaStore.GetByPath(rel); entry != nil && entry.Source != "" {
seen[rel] = true
targets = append(targets, updateTarget{name: rel, path: skillDir, isRepo: false, meta: meta})
targets = append(targets, updateTarget{name: rel, path: skillDir, isRepo: false, meta: entry})
}
}
}
@@ -245,6 +254,8 @@ func cmdUpdate(args []string) error {
return fmt.Errorf("failed to scan skills: %w", err)
}
} else {
// Load store once for name resolution
nameStore, _ := install.LoadMetadata(cfg.Source)
// Resolve by specific names/groups
for _, name := range opts.names {
// Glob pattern matching (e.g. "core-*", "_team-?")
@@ -268,7 +279,7 @@ func cmdUpdate(args []string) error {
continue
}
if isGroupDir(name, cfg.Source) {
if isGroupDir(name, cfg.Source, nameStore) {
groupMatches, groupErr := resolveGroupUpdatable(name, cfg.Source)
if groupErr != nil {
resolveWarnings = append(resolveWarnings, fmt.Sprintf("%s: %v", name, groupErr))
@@ -481,6 +492,7 @@ func logUpdateOp(cfgPath string, names []string, opts *updateOptions, mode strin
func printUpdateHelp() {
fmt.Println(`Usage: skillshare update <name>... [options]
skillshare update [agents] <name|--all> [options]
skillshare update --group <group> [options]
skillshare update --all [options]
@@ -528,5 +540,8 @@ Examples:
skillshare update --all -T high # Use HIGH threshold for this run
skillshare update --all --dry-run # Preview updates
skillshare update _team --force # Discard changes and update
skillshare update --all --prune # Update all + remove stale skills`)
skillshare update --all --prune # Update all + remove stale skills
skillshare update agents --all # Update all agents
skillshare update agents tutor # Update a single agent
skillshare update agents -G demo # Update all agents in demo/`)
}
+850
View File
@@ -0,0 +1,850 @@
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"skillshare/internal/check"
"skillshare/internal/config"
"skillshare/internal/install"
"skillshare/internal/oplog"
"skillshare/internal/resource"
"skillshare/internal/ui"
)
// cmdUpdateAgents handles "skillshare update agents [name|--all]".
func cmdUpdateAgents(args []string, cfg *config.Config, start time.Time) error {
jsonRequested := hasFlag(args, "--json")
opts, showHelp, parseErr := parseUpdateAgentArgs(args)
if showHelp {
printUpdateHelp()
return nil
}
if parseErr != nil {
if jsonRequested {
return writeJSONError(parseErr)
}
return parseErr
}
if opts.threshold == "" {
opts.threshold = cfg.Audit.BlockThreshold
}
jsonUI := newJSONUISuppressor(opts.jsonOutput)
defer jsonUI.Flush()
jsonWriteResult := func(items []agentUpdateItem, cmdErr error) error {
jsonUI.Flush()
return updateAgentsOutputJSON(items, opts.dryRun, start, cmdErr)
}
failJSON := func(err error) error {
if opts.jsonOutput {
jsonUI.Flush()
return writeJSONError(err)
}
return err
}
agentsDir := cfg.EffectiveAgentsSource()
if _, err := os.Stat(agentsDir); err != nil {
if os.IsNotExist(err) {
if opts.jsonOutput {
return jsonWriteResult(nil, nil)
}
ui.Info("No agents source directory (%s)", agentsDir)
return nil
}
return failJSON(fmt.Errorf("cannot access agents source: %w", err))
}
// Discover agents and check status
results := check.CheckAgents(agentsDir)
if len(results) == 0 {
if opts.jsonOutput {
return jsonWriteResult(nil, nil)
}
ui.Info("No agents found")
return nil
}
// Filter by name if specified
if len(opts.names) > 0 {
results = filterAgentCheckResults(results, opts.names)
if len(results) == 0 {
return failJSON(fmt.Errorf("no matching agents found: %s", strings.Join(opts.names, ", ")))
}
}
// Filter by group if specified
if len(opts.groups) > 0 {
var err error
results, err = filterAgentResultsByGroups(results, opts.groups, agentsDir)
if err != nil {
return failJSON(err)
}
if len(results) == 0 {
return failJSON(fmt.Errorf("no agents found in group(s): %s", strings.Join(opts.groups, ", ")))
}
}
// Only check agents that have remote sources
tracked := collectTrackedAgentResults(results)
if len(tracked) == 0 {
if opts.jsonOutput {
return jsonWriteResult(agentUpdateItemsFromCheckResults(results), nil)
}
ui.Info("No tracked agents to update (all are local)")
return nil
}
// Enrich with remote status
if !opts.jsonOutput {
sp := ui.StartSpinner(fmt.Sprintf("Checking %d agent(s) for updates...", len(tracked)))
check.EnrichAgentResultsWithRemote(tracked, func() { sp.Success("Check complete") })
} else {
check.EnrichAgentResultsWithRemote(tracked, nil)
}
mergeTrackedAgentResults(results, tracked)
// Find agents with updates available
var updatable []check.AgentCheckResult
for _, r := range tracked {
if r.Status == "update_available" {
updatable = append(updatable, r)
}
}
finalItems := agentUpdateItemsFromCheckResults(results)
if len(updatable) == 0 {
if opts.jsonOutput {
return jsonWriteResult(finalItems, nil)
}
ui.Success("All agents are up to date")
return nil
}
if !opts.jsonOutput {
ui.Header("Updating agents")
if opts.dryRun {
ui.Warning("Dry run mode - no changes will be made")
}
}
// Update agents, batching by repo URL to share git clones.
var (
updated int
failed int
updatedItems []agentUpdateItem
)
if opts.dryRun {
for _, r := range updatable {
if !opts.jsonOutput {
ui.Info(" %s: update available from %s", r.Name, r.Source)
}
}
} else {
updatedItems, updated, failed = batchUpdateAgents(agentsDir, updatable, opts, "", !opts.jsonOutput)
finalItems = mergeAgentUpdateItems(finalItems, updatedItems)
}
if !opts.jsonOutput && !opts.dryRun {
fmt.Println()
ui.Info("Agent update: %d updated, %d failed", updated, failed)
}
logUpdateAgentOp(config.ConfigPath(), len(updatable), updated, failed, opts.dryRun, start)
if opts.jsonOutput {
var cmdErr error
if failed > 0 {
cmdErr = fmt.Errorf("%d agent(s) failed to update", failed)
}
return jsonWriteResult(finalItems, cmdErr)
}
if failed > 0 {
return fmt.Errorf("%d agent(s) failed to update", failed)
}
return nil
}
// agentRepoKey groups agents by clone URL + branch + repo subdir so agents
// from the same scope share a single git clone.
type agentRepoKey struct {
cloneURL string
branch string
repoSubdir string
}
type agentUpdateItem struct {
Name string `json:"name"`
Source string `json:"source,omitempty"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
}
// batchUpdateAgents groups agents by repo URL and clones once per group.
// Agents with no RepoURL fall back to per-agent reinstallAgent.
func batchUpdateAgents(agentsDir string, agents []check.AgentCheckResult, opts *updateAgentArgs, projectRoot string, verbose bool) ([]agentUpdateItem, int, int) {
store := install.LoadMetadataOrNew(agentsDir)
trackedRepos := map[string][]check.AgentCheckResult{}
groups := map[agentRepoKey][]check.AgentCheckResult{}
var noRepo []check.AgentCheckResult
var items []agentUpdateItem
updated, failed := 0, 0
for _, r := range agents {
if r.RepoPath != "" {
trackedRepos[r.RepoPath] = append(trackedRepos[r.RepoPath], r)
continue
}
if r.RepoURL == "" {
noRepo = append(noRepo, r)
continue
}
entry := store.GetByPath(r.Name)
if entry == nil || entry.Source == "" {
noRepo = append(noRepo, r)
continue
}
source, parseErr := install.ParseSource(entry.Source)
if parseErr != nil {
noRepo = append(noRepo, r)
continue
}
repoSubdir := strings.TrimSuffix(source.Subdir, entry.Subdir)
repoSubdir = strings.TrimRight(repoSubdir, "/")
key := agentRepoKey{
cloneURL: r.RepoURL,
branch: entry.Branch,
repoSubdir: repoSubdir,
}
groups[key] = append(groups[key], r)
}
for repoPath, members := range trackedRepos {
uc := &updateContext{
sourcePath: agentsDir,
projectRoot: projectRoot,
opts: &updateOptions{
force: opts.force,
skipAudit: opts.skipAudit,
threshold: opts.threshold,
},
}
ok, _, err := updateTrackedRepoQuick(uc, repoPath)
if err != nil {
for _, m := range members {
items = append(items, agentUpdateItem{
Name: m.Name,
Source: m.Source,
Status: "failed",
Message: "tracked repo update failed",
Error: err.Error(),
})
if verbose {
ui.Error(" %s: %v", m.Name, err)
}
failed++
}
continue
}
if !ok {
for _, m := range members {
items = append(items, agentUpdateItem{
Name: m.Name,
Source: m.Source,
Status: "skipped",
Message: "up-to-date",
})
}
continue
}
for _, m := range members {
items = append(items, agentUpdateItem{
Name: m.Name,
Source: m.Source,
Status: "updated",
Message: "tracked repo updated",
})
if verbose {
ui.Success(" %s: updated", m.Name)
}
updated++
}
}
// Batch: one clone per repo group
for key, members := range groups {
source := &install.Source{
CloneURL: key.cloneURL,
Subdir: key.repoSubdir,
Branch: key.branch,
}
var discovery *install.DiscoveryResult
var discErr error
if source.HasSubdir() {
discovery, discErr = install.DiscoverFromGitSubdir(source)
} else {
discovery, discErr = install.DiscoverFromGit(source)
}
if discErr != nil {
for _, m := range members {
items = append(items, agentUpdateItem{
Name: m.Name,
Source: m.Source,
Status: "failed",
Message: "discovery failed",
Error: "discovery failed: " + discErr.Error(),
})
if verbose {
ui.Error(" %s: discovery failed: %v", m.Name, discErr)
}
failed++
}
continue
}
// Build agent name → AgentInfo lookup
agentIndex := map[string]*install.AgentInfo{}
for i, a := range discovery.Agents {
agentIndex[a.Name] = &discovery.Agents[i]
}
for _, m := range members {
agentName := filepath.Base(m.Name)
target := agentIndex[agentName]
if target == nil {
if verbose {
ui.Error(" %s: not found in repository", m.Name)
}
items = append(items, agentUpdateItem{
Name: m.Name,
Source: m.Source,
Status: "failed",
Message: "not found in repository",
Error: "not found in repository",
})
failed++
continue
}
destDir := agentsDir
if dir := filepath.Dir(m.Name); dir != "." {
destDir = filepath.Join(agentsDir, dir)
}
installOpts := install.InstallOptions{
Kind: "agent",
Force: opts.force,
Update: true,
SkipAudit: opts.skipAudit,
AuditThreshold: opts.threshold,
AuditProjectRoot: projectRoot,
SourceDir: agentsDir,
}
if _, err := install.UpdateAgentFromDiscovery(discovery, *target, destDir, installOpts); err != nil {
items = append(items, agentUpdateItem{
Name: m.Name,
Source: m.Source,
Status: "failed",
Message: "update failed",
Error: err.Error(),
})
if verbose {
ui.Error(" %s: %v", m.Name, err)
}
failed++
} else {
items = append(items, agentUpdateItem{
Name: m.Name,
Source: m.Source,
Status: "updated",
Message: "updated",
})
if verbose {
ui.Success(" %s: updated", m.Name)
}
updated++
}
}
install.CleanupDiscovery(discovery)
}
// Fallback: agents without RepoURL
for _, r := range noRepo {
if err := reinstallAgent(agentsDir, r, store, opts, projectRoot); err != nil {
items = append(items, agentUpdateItem{
Name: r.Name,
Source: r.Source,
Status: "failed",
Message: "update failed",
Error: err.Error(),
})
if verbose {
ui.Error(" %s: %v", r.Name, err)
}
failed++
} else {
items = append(items, agentUpdateItem{
Name: r.Name,
Source: r.Source,
Status: "updated",
Message: "updated",
})
if verbose {
ui.Success(" %s: updated", r.Name)
}
updated++
}
}
return items, updated, failed
}
// reinstallAgent re-installs an agent from its recorded source using
// discovery + InstallAgentFromDiscovery (single-file copy), not the
// directory-based skill installer.
// Used as fallback for agents without RepoURL in the batch path.
func reinstallAgent(agentsDir string, r check.AgentCheckResult, store *install.MetadataStore, opts *updateAgentArgs, projectRoot string) error {
entry := store.GetByPath(r.Name)
if entry == nil || entry.Source == "" {
return fmt.Errorf("no source metadata for agent %q", r.Name)
}
// Reconstruct the repo-level subdir for discovery.
source, parseErr := install.ParseSource(entry.Source)
if parseErr != nil {
return fmt.Errorf("invalid source: %w", parseErr)
}
if entry.Branch != "" {
source.Branch = entry.Branch
}
repoSubdir := strings.TrimSuffix(source.Subdir, entry.Subdir)
repoSubdir = strings.TrimRight(repoSubdir, "/")
source.Subdir = repoSubdir
// Discover agents — use subdir-scoped discovery for monorepo installs.
var discovery *install.DiscoveryResult
var discErr error
if source.HasSubdir() {
discovery, discErr = install.DiscoverFromGitSubdir(source)
} else {
discovery, discErr = install.DiscoverFromGit(source)
}
if discErr != nil {
return fmt.Errorf("discovery failed: %w", discErr)
}
defer install.CleanupDiscovery(discovery)
// Find the specific agent by name
agentName := filepath.Base(r.Name)
var targetAgent *install.AgentInfo
for i, a := range discovery.Agents {
if a.Name == agentName {
targetAgent = &discovery.Agents[i]
break
}
}
if targetAgent == nil {
return fmt.Errorf("agent %q not found in repository", agentName)
}
// For grouped agents (r.Name contains "/", e.g. "tools/reviewer"),
// reconstruct the correct destination subdirectory so the file lands
// at agents/tools/reviewer.md rather than agents/reviewer.md.
destDir := agentsDir
if dir := filepath.Dir(r.Name); dir != "." {
destDir = filepath.Join(agentsDir, dir)
}
installOpts := install.InstallOptions{
Kind: "agent",
Force: opts.force,
Update: true,
SkipAudit: opts.skipAudit,
AuditThreshold: opts.threshold,
AuditProjectRoot: projectRoot,
SourceDir: agentsDir,
}
_, installErr := install.UpdateAgentFromDiscovery(discovery, *targetAgent, destDir, installOpts)
return installErr
}
// updateAgentArgs holds parsed arguments for agent update.
type updateAgentArgs struct {
names []string
groups []string
all bool
dryRun bool
force bool
skipAudit bool
threshold string
jsonOutput bool
}
func parseUpdateAgentArgs(args []string) (*updateAgentArgs, bool, error) {
opts := &updateAgentArgs{}
for i := 0; i < len(args); i++ {
arg := args[i]
switch {
case arg == "--all" || arg == "-a":
opts.all = true
case arg == "--dry-run" || arg == "-n":
opts.dryRun = true
case arg == "--force" || arg == "-f":
opts.force = true
case arg == "--skip-audit":
opts.skipAudit = true
case arg == "--audit-threshold" || arg == "--threshold" || arg == "-T":
i++
if i >= len(args) {
return nil, false, fmt.Errorf("%s requires a value", arg)
}
threshold, err := normalizeInstallAuditThreshold(args[i])
if err != nil {
return nil, false, err
}
opts.threshold = threshold
case arg == "--json":
opts.jsonOutput = true
case arg == "--group" || arg == "-G":
i++
if i >= len(args) {
return nil, false, fmt.Errorf("--group requires a value")
}
opts.groups = append(opts.groups, args[i])
case arg == "--help" || arg == "-h":
return nil, true, nil
case strings.HasPrefix(arg, "-"):
return nil, false, fmt.Errorf("unknown option: %s", arg)
default:
opts.names = append(opts.names, arg)
}
}
if !opts.all && len(opts.names) == 0 && len(opts.groups) == 0 {
return nil, false, fmt.Errorf("specify agent name(s), --group, or --all")
}
if opts.all && (len(opts.names) > 0 || len(opts.groups) > 0) {
return nil, false, fmt.Errorf("--all cannot be used with agent names or --group")
}
return opts, false, nil
}
func collectTrackedAgentResults(results []check.AgentCheckResult) []check.AgentCheckResult {
tracked := make([]check.AgentCheckResult, 0, len(results))
for _, r := range results {
if r.Source != "" {
tracked = append(tracked, r)
}
}
return tracked
}
func mergeTrackedAgentResults(results, tracked []check.AgentCheckResult) {
indexByName := make(map[string]int, len(results))
for i, r := range results {
indexByName[r.Name] = i
}
for _, r := range tracked {
if idx, ok := indexByName[r.Name]; ok {
results[idx] = r
}
}
}
func filterAgentCheckResults(results []check.AgentCheckResult, names []string) []check.AgentCheckResult {
nameSet := make(map[string]bool, len(names))
for _, n := range names {
nameSet[n] = true
// Also index without .md suffix so "demo/tutor.md" matches "demo/tutor"
nameSet[strings.TrimSuffix(n, ".md")] = true
}
var filtered []check.AgentCheckResult
for _, r := range results {
// Match full path (e.g. "demo/code-reviewer") or basename (e.g. "code-reviewer")
if nameSet[r.Name] || nameSet[filepath.Base(r.Name)] {
filtered = append(filtered, r)
}
}
return filtered
}
// validateAgentGroups checks that each group name corresponds to a subdirectory
// under agentsDir. Returns normalized group names (trailing "/" stripped).
func validateAgentGroups(groups []string, agentsDir string) ([]string, error) {
normalized := make([]string, len(groups))
for i, group := range groups {
group = strings.TrimSuffix(group, "/")
info, err := os.Stat(filepath.Join(agentsDir, group))
if err != nil || !info.IsDir() {
return nil, fmt.Errorf("agent group %q not found in %s", group, agentsDir)
}
normalized[i] = group
}
return normalized, nil
}
func matchesAnyGroup(name string, groups []string) bool {
for _, group := range groups {
if strings.HasPrefix(name, group+"/") {
return true
}
}
return false
}
// filterAgentResultsByGroups filters agent check results to those in the given groups.
func filterAgentResultsByGroups(results []check.AgentCheckResult, groups []string, agentsDir string) ([]check.AgentCheckResult, error) {
groups, err := validateAgentGroups(groups, agentsDir)
if err != nil {
return nil, err
}
var filtered []check.AgentCheckResult
for _, r := range results {
if matchesAnyGroup(r.Name, groups) {
filtered = append(filtered, r)
}
}
return filtered, nil
}
// filterDiscoveredAgentsByGroups filters discovered agents to those in the given groups.
func filterDiscoveredAgentsByGroups(discovered []resource.DiscoveredResource, groups []string, agentsDir string) ([]resource.DiscoveredResource, error) {
groups, err := validateAgentGroups(groups, agentsDir)
if err != nil {
return nil, err
}
var filtered []resource.DiscoveredResource
for _, d := range discovered {
if matchesAnyGroup(strings.TrimSuffix(d.RelPath, ".md"), groups) {
filtered = append(filtered, d)
}
}
return filtered, nil
}
func logUpdateAgentOp(cfgPath string, total, updated, failed int, dryRun bool, start time.Time) {
status := "ok"
if failed > 0 && updated > 0 {
status = "partial"
} else if failed > 0 {
status = "error"
}
e := oplog.NewEntry("update", status, time.Since(start))
e.Args = map[string]any{
"resource_kind": "agent",
"agents_total": total,
"agents_updated": updated,
"agents_failed": failed,
"dry_run": dryRun,
}
oplog.WriteWithLimit(cfgPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
}
func agentUpdateItemsFromCheckResults(results []check.AgentCheckResult) []agentUpdateItem {
items := make([]agentUpdateItem, 0, len(results))
for _, r := range results {
item := agentUpdateItem{
Name: r.Name,
Source: r.Source,
Status: r.Status,
Message: r.Message,
}
if r.Status == "error" {
item.Error = r.Message
}
items = append(items, item)
}
return items
}
func mergeAgentUpdateItems(base, updates []agentUpdateItem) []agentUpdateItem {
if len(updates) == 0 {
return base
}
merged := append([]agentUpdateItem(nil), base...)
indexByName := make(map[string]int, len(merged))
for i, item := range merged {
indexByName[item.Name] = i
}
for _, item := range updates {
if idx, ok := indexByName[item.Name]; ok {
merged[idx] = item
continue
}
indexByName[item.Name] = len(merged)
merged = append(merged, item)
}
return merged
}
func updateAgentsOutputJSON(items []agentUpdateItem, dryRun bool, start time.Time, err error) error {
output := struct {
Agents []agentUpdateItem `json:"agents"`
DryRun bool `json:"dry_run"`
Duration string `json:"duration"`
}{
Agents: items,
DryRun: dryRun,
Duration: formatDuration(start),
}
return writeJSONResult(&output, err)
}
// cmdUpdateAgentsProject handles "skillshare update -p agents [name|--all]".
func cmdUpdateAgentsProject(args []string, projectRoot string, start time.Time) error {
jsonRequested := hasFlag(args, "--json")
opts, showHelp, parseErr := parseUpdateAgentArgs(args)
if showHelp {
printUpdateHelp()
return nil
}
if parseErr != nil {
if jsonRequested {
return writeJSONError(parseErr)
}
return parseErr
}
jsonUI := newJSONUISuppressor(opts.jsonOutput)
defer jsonUI.Flush()
jsonWriteResult := func(items []agentUpdateItem, cmdErr error) error {
jsonUI.Flush()
return updateAgentsOutputJSON(items, opts.dryRun, start, cmdErr)
}
failJSON := func(err error) error {
if opts.jsonOutput {
jsonUI.Flush()
return writeJSONError(err)
}
return err
}
if !projectConfigExists(projectRoot) {
if err := performProjectInit(projectRoot, projectInitOptions{}); err != nil {
return failJSON(err)
}
}
runtime, err := loadProjectRuntime(projectRoot)
if err != nil {
return failJSON(err)
}
if opts.threshold == "" {
opts.threshold = runtime.config.Audit.BlockThreshold
}
agentsDir := runtime.agentsSourcePath
if _, err := os.Stat(agentsDir); err != nil {
if os.IsNotExist(err) {
if opts.jsonOutput {
return jsonWriteResult(nil, nil)
}
ui.Info("No project agents directory (%s)", agentsDir)
return nil
}
return failJSON(fmt.Errorf("cannot access project agents: %w", err))
}
results := check.CheckAgents(agentsDir)
if len(results) == 0 {
if opts.jsonOutput {
return jsonWriteResult(nil, nil)
}
ui.Info("No project agents found")
return nil
}
if len(opts.names) > 0 {
results = filterAgentCheckResults(results, opts.names)
if len(results) == 0 {
return failJSON(fmt.Errorf("no matching agents found: %s", strings.Join(opts.names, ", ")))
}
}
if len(opts.groups) > 0 {
var err error
results, err = filterAgentResultsByGroups(results, opts.groups, agentsDir)
if err != nil {
return failJSON(err)
}
if len(results) == 0 {
return failJSON(fmt.Errorf("no agents found in group(s): %s", strings.Join(opts.groups, ", ")))
}
}
tracked := collectTrackedAgentResults(results)
if len(tracked) == 0 {
if opts.jsonOutput {
return jsonWriteResult(agentUpdateItemsFromCheckResults(results), nil)
}
ui.Info("No tracked project agents to update (all are local)")
return nil
}
sp := ui.StartSpinner(fmt.Sprintf("Checking %d agent(s) for updates...", len(tracked)))
check.EnrichAgentResultsWithRemote(tracked, func() { sp.Success("Check complete") })
mergeTrackedAgentResults(results, tracked)
var updatable []check.AgentCheckResult
for _, r := range tracked {
if r.Status == "update_available" {
updatable = append(updatable, r)
}
}
finalItems := agentUpdateItemsFromCheckResults(results)
if len(updatable) == 0 {
if opts.jsonOutput {
return jsonWriteResult(finalItems, nil)
}
ui.Success("All project agents are up to date")
return nil
}
ui.Header("Updating project agents")
if opts.dryRun {
ui.Warning("Dry run mode")
for _, r := range updatable {
ui.Info(" %s: update available from %s", r.Name, r.Source)
}
if opts.jsonOutput {
return jsonWriteResult(finalItems, nil)
}
return nil
}
updatedItems, updated, failed := batchUpdateAgents(agentsDir, updatable, opts, projectRoot, !opts.jsonOutput)
finalItems = mergeAgentUpdateItems(finalItems, updatedItems)
logUpdateAgentOp(config.ProjectConfigPath(projectRoot), len(updatable), updated, failed, opts.dryRun, start)
if opts.jsonOutput {
var cmdErr error
if failed > 0 {
cmdErr = fmt.Errorf("%d agent(s) failed to update", failed)
}
return jsonWriteResult(finalItems, cmdErr)
}
if failed > 0 {
return fmt.Errorf("%d agent(s) failed to update", failed)
}
return nil
}
+12 -25
View File
@@ -2,12 +2,10 @@ package main
import (
"fmt"
"path/filepath"
"strings"
"time"
"skillshare/internal/audit"
"skillshare/internal/config"
"skillshare/internal/install"
"skillshare/internal/trash"
"skillshare/internal/ui"
@@ -42,6 +40,7 @@ func (uc *updateContext) makeInstallOpts() install.InstallOptions {
Update: true,
SkipAudit: uc.opts.skipAudit,
AuditThreshold: uc.opts.threshold,
SourceDir: uc.sourcePath,
}
if uc.isProject() {
opts.AuditProjectRoot = uc.projectRoot
@@ -337,36 +336,24 @@ func pruneSkill(skillPath, name string, uc *updateContext) error {
return err
}
// pruneRegistry removes pruned skill entries from the registry.
// pruneRegistry removes pruned skill entries from the metadata store.
func pruneRegistry(prunedNames []string, uc *updateContext) {
var regDir string
if uc.isProject() {
regDir = filepath.Join(uc.projectRoot, ".skillshare")
} else {
regDir = uc.registryDir
}
reg, err := config.LoadRegistry(regDir)
if err != nil || len(reg.Skills) == 0 {
store, err := install.LoadMetadata(uc.sourcePath)
if err != nil {
return
}
removedSet := make(map[string]bool, len(prunedNames))
for _, n := range prunedNames {
removedSet[n] = true
}
updated := make([]config.SkillEntry, 0, len(reg.Skills))
for _, s := range reg.Skills {
if !removedSet[s.FullName()] {
updated = append(updated, s)
changed := false
for _, name := range prunedNames {
if store.Has(name) {
store.Remove(name)
changed = true
}
}
if len(updated) != len(reg.Skills) {
reg.Skills = updated
if saveErr := reg.Save(regDir); saveErr != nil {
ui.Warning("Failed to update registry after prune: %v", saveErr)
if changed {
if saveErr := store.Save(uc.sourcePath); saveErr != nil {
ui.Warning("Failed to update metadata after prune: %v", saveErr)
}
}
}
+12 -8
View File
@@ -216,10 +216,11 @@ func updateRegularSkill(uc *updateContext, skillName string) (updateResult, erro
skillPath := filepath.Join(uc.sourcePath, skillName)
// Read metadata to get source
meta, err := install.ReadMeta(skillPath)
if err != nil {
return updateResult{skipped: 1}, fmt.Errorf("cannot read metadata for '%s': %w", skillName, err)
store, storeErr := install.LoadMetadataWithMigration(uc.sourcePath, "")
if storeErr != nil {
return updateResult{skipped: 1}, fmt.Errorf("cannot read metadata for '%s': %w", skillName, storeErr)
}
meta := store.GetByPath(skillName)
if meta == nil || meta.Source == "" {
return updateResult{skipped: 1}, fmt.Errorf("skill '%s' has no source metadata, cannot update", skillName)
}
@@ -348,9 +349,9 @@ func updateTrackedRepoQuick(uc *updateContext, repoPath string) (bool, *audit.Re
// updateSkillFromMeta updates a skill using its metadata in batch mode.
// Output is suppressed; caller handles display via progress bar.
// If cachedMeta is non-nil it is used directly; otherwise metadata is read from disk.
// If cachedMeta is non-nil it is used directly; otherwise metadata is loaded from the store.
// Returns (updated, installResult, error).
func updateSkillFromMeta(uc *updateContext, skillPath string, cachedMeta *install.SkillMeta) (bool, *install.InstallResult, error) {
func updateSkillFromMeta(uc *updateContext, skillPath string, cachedMeta *install.MetadataEntry) (bool, *install.InstallResult, error) {
if uc.opts.dryRun {
return false, nil, nil
}
@@ -361,9 +362,12 @@ func updateSkillFromMeta(uc *updateContext, skillPath string, cachedMeta *instal
meta := cachedMeta
if meta == nil {
var readErr error
meta, readErr = install.ReadMeta(skillPath)
if readErr != nil || meta == nil || meta.Source == "" {
store, _ := install.LoadMetadataWithMigration(uc.sourcePath, "")
// GetByPath handles both full-path keys and legacy basename+group keys.
if rel, relErr := filepath.Rel(uc.sourcePath, skillPath); relErr == nil {
meta = store.GetByPath(filepath.ToSlash(rel))
}
if meta == nil || meta.Source == "" {
return false, nil, nil
}
}
+11 -9
View File
@@ -59,11 +59,13 @@ func cmdUpdateProjectBatch(sourcePath string, opts *updateOptions, projectRoot s
seen := map[string]bool{}
var resolveWarnings []string
metaStore, _ := install.LoadMetadataWithMigration(sourcePath, "")
for _, name := range opts.names {
// Check group directory first (before repo/skill lookup,
// so "feature-radar" expands to all skills rather than
// matching a single nested "feature-radar/feature-radar").
if isGroupDir(name, sourcePath) {
if isGroupDir(name, sourcePath, metaStore) {
groupMatches, groupErr := resolveGroupUpdatable(name, sourcePath)
if groupErr != nil {
resolveWarnings = append(resolveWarnings, fmt.Sprintf("%s: %v", name, groupErr))
@@ -104,11 +106,11 @@ func cmdUpdateProjectBatch(sourcePath string, opts *updateOptions, projectRoot s
// Regular skill with metadata
skillPath := filepath.Join(sourcePath, name)
if info, err := os.Stat(skillPath); err == nil && info.IsDir() {
meta, metaErr := install.ReadMeta(skillPath)
if metaErr == nil && meta != nil && meta.Source != "" {
entry := metaStore.Get(name)
if entry != nil && entry.Source != "" {
if !seen[skillPath] {
seen[skillPath] = true
targets = append(targets, updateTarget{name: name, path: skillPath, isRepo: false, meta: meta})
targets = append(targets, updateTarget{name: name, path: skillPath, isRepo: false, meta: entry})
}
continue
}
@@ -187,6 +189,7 @@ func updateAllProjectSkills(uc *updateContext) (*updateResult, error) {
scanSpinner := ui.StartSpinner("Scanning skills...")
walkRoot := utils.ResolveSymlink(uc.sourcePath)
metaStore, _ := install.LoadMetadataWithMigration(uc.sourcePath, "")
err := filepath.Walk(walkRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
@@ -213,11 +216,10 @@ func updateAllProjectSkills(uc *updateContext) (*updateResult, error) {
// Regular skill with metadata
if !info.IsDir() && info.Name() == "SKILL.md" {
skillDir := filepath.Dir(path)
meta, metaErr := install.ReadMeta(skillDir)
if metaErr == nil && meta != nil && meta.Source != "" {
rel, _ := filepath.Rel(walkRoot, skillDir)
if rel != "." {
targets = append(targets, updateTarget{name: rel, path: skillDir, isRepo: false, meta: meta})
rel, _ := filepath.Rel(walkRoot, skillDir)
if rel != "." {
if entry := metaStore.Get(rel); entry != nil && entry.Source != "" {
targets = append(targets, updateTarget{name: rel, path: skillDir, isRepo: false, meta: entry})
}
}
}
+12 -9
View File
@@ -12,10 +12,10 @@ import (
)
type updateTarget struct {
name string // relative path from source dir (display name)
path string // absolute path on disk
isRepo bool // true for tracked repos (_-prefixed git repos)
meta *install.SkillMeta // cached metadata; nil for tracked repos
name string // relative path from source dir (display name)
path string // absolute path on disk
isRepo bool // true for tracked repos (_-prefixed git repos)
meta *install.MetadataEntry // cached metadata; nil for tracked repos
}
// resolveByBasename searches nested skills and tracked repos by their
@@ -99,6 +99,9 @@ func resolveGroupUpdatable(group, sourceDir string) ([]updateTarget, error) {
return nil, fmt.Errorf("group '%s' resolves outside source directory", group)
}
// Load store once before walk (not per iteration)
store, _ := install.LoadMetadata(resolvedSourceDir)
var matches []updateTarget
if walkErr := filepath.Walk(walkRoot, func(path string, fi os.FileInfo, err error) error {
if err != nil {
@@ -122,9 +125,9 @@ func resolveGroupUpdatable(group, sourceDir string) ([]updateTarget, error) {
return filepath.SkipDir
}
// Skill with metadata (has .skillshare-meta.json)
if meta, metaErr := install.ReadMeta(path); metaErr == nil && meta != nil && meta.Source != "" {
matches = append(matches, updateTarget{name: rel, path: path, isRepo: false, meta: meta})
// Skill with metadata (centralized store)
if entry := store.GetByPath(rel); entry != nil && entry.Source != "" {
matches = append(matches, updateTarget{name: rel, path: path, isRepo: false, meta: entry})
return filepath.SkipDir
}
@@ -139,7 +142,7 @@ func resolveGroupUpdatable(group, sourceDir string) ([]updateTarget, error) {
// isGroupDir checks if a name corresponds to a group directory (a container
// for other skills). Returns false for tracked repos, skills with metadata,
// and directories that are themselves a skill (have SKILL.md).
func isGroupDir(name, sourceDir string) bool {
func isGroupDir(name, sourceDir string, store *install.MetadataStore) bool {
path := filepath.Join(sourceDir, name)
info, err := os.Stat(path)
if err != nil || !info.IsDir() {
@@ -150,7 +153,7 @@ func isGroupDir(name, sourceDir string) bool {
return false
}
// Not a skill with metadata
if meta, metaErr := install.ReadMeta(path); metaErr == nil && meta != nil && meta.Source != "" {
if entry := store.Get(name); entry != nil && entry.Source != "" {
return false
}
// Not a skill directory (has SKILL.md)
+3 -1
View File
@@ -90,7 +90,9 @@ func setupUpdatableSkill(t *testing.T, sourceDir, name string) {
dir := filepath.Join(sourceDir, name)
os.MkdirAll(dir, 0755)
os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# "+name), 0644)
install.WriteMeta(dir, &install.SkillMeta{Source: "github.com/test/" + name, Type: "github"})
store, _ := install.LoadMetadata(sourceDir)
store.Set(name, &install.MetadataEntry{Source: "github.com/test/" + name, Type: "github"})
store.Save(sourceDir)
}
func TestResolveByGlob_MatchesTrackedRepos(t *testing.T) {
+48 -11
View File
@@ -10,7 +10,7 @@ import (
)
// metadataAnalyzer cross-references SKILL.md metadata (name, description)
// against the actual git source URL from .skillshare-meta.json.
// against the actual git source URL from the centralized metadata store.
// Detects social-engineering patterns: publisher mismatch and authority claims.
// Runs at skill scope after all files are walked.
type metadataAnalyzer struct{}
@@ -20,9 +20,19 @@ func (a *metadataAnalyzer) Scope() AnalyzerScope { return ScopeSkill }
// metaJSON is a minimal subset of install.SkillMeta to avoid import cycles.
type metaJSON struct {
RepoURL string `json:"repo_url"`
RepoURL string `json:"repo_url"`
FileHashes map[string]string `json:"file_hashes"`
}
// metadataStoreJSON is a minimal subset of install.MetadataStore for reading
// the centralized .metadata.json without importing the install package.
type metadataStoreJSON struct {
Entries map[string]metaJSON `json:"entries"`
}
// metadataFileName mirrors install.MetadataFileName to avoid a circular import.
const metadataFileName = ".metadata.json"
// Rule IDs for disable support via audit-rules.yaml.
const (
rulePublisherMismatch = "publisher-mismatch"
@@ -47,7 +57,6 @@ func (a *metadataAnalyzer) Analyze(ctx *AnalyzeContext) ([]Finding, error) {
return nil, nil
}
// Read .skillshare-meta.json for source URL.
repoURL := readMetaRepoURL(ctx.SkillPath)
// Read SKILL.md frontmatter for name and description.
@@ -73,17 +82,45 @@ func (a *metadataAnalyzer) Analyze(ctx *AnalyzeContext) ([]Finding, error) {
return findings, nil
}
// readMetaRepoURL reads repo_url from .skillshare-meta.json in skillPath.
// findMetaEntry walks up parent directories of skillPath looking for the
// centralized .metadata.json store and returns the raw entry for this skill.
func findMetaEntry(skillPath string) *metaJSON {
skillName := filepath.Base(skillPath)
dir := filepath.Dir(skillPath)
for i := 0; i < 10 && dir != filepath.Dir(dir); i++ {
data, err := os.ReadFile(filepath.Join(dir, metadataFileName))
if err == nil {
var store metadataStoreJSON
if json.Unmarshal(data, &store) == nil {
if rel, relErr := filepath.Rel(dir, skillPath); relErr == nil {
key := filepath.ToSlash(rel)
if e, ok := store.Entries[key]; ok {
return &e
}
}
if e, ok := store.Entries[skillName]; ok {
return &e
}
}
}
dir = filepath.Dir(dir)
}
return nil
}
func readMetaRepoURL(skillPath string) string {
data, err := os.ReadFile(filepath.Join(skillPath, ".skillshare-meta.json"))
if err != nil {
return ""
if e := findMetaEntry(skillPath); e != nil {
return e.RepoURL
}
var m metaJSON
if json.Unmarshal(data, &m) != nil {
return ""
return ""
}
func readMetaFileHashes(skillPath string) map[string]string {
if e := findMetaEntry(skillPath); e != nil {
return e.FileHashes
}
return m.RepoURL
return nil
}
// readSkillFrontmatter extracts name and description from SKILL.md.
+53 -11
View File
@@ -246,19 +246,23 @@ func TestIsWellKnownOrg(t *testing.T) {
}
func TestMetadataAnalyzer_Integration(t *testing.T) {
// Create a temp skill directory with SKILL.md and .skillshare-meta.json
dir := t.TempDir()
// Create a nested skill directory: root/evil-skill/SKILL.md
// with centralized metadata at root/.metadata.json
root := t.TempDir()
dir := filepath.Join(root, "evil-skill")
os.MkdirAll(dir, 0755)
// Write SKILL.md claiming "from Acme Corp"
skillContent := "---\nname: evil-skill\ndescription: Official formatter from Acme Corp\n---\n# Evil\n"
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(skillContent), 0644); err != nil {
t.Fatal(err)
}
// Write meta pointing to a different org
meta := metaJSON{RepoURL: "https://github.com/evil-fork/skills.git"}
metaData, _ := json.Marshal(meta)
if err := os.WriteFile(filepath.Join(dir, ".skillshare-meta.json"), metaData, 0644); err != nil {
// Write centralized metadata in parent directory
store := metadataStoreJSON{Entries: map[string]metaJSON{
"evil-skill": {RepoURL: "https://github.com/evil-fork/skills.git"},
}}
storeData, _ := json.Marshal(store)
if err := os.WriteFile(filepath.Join(root, metadataFileName), storeData, 0644); err != nil {
t.Fatal(err)
}
@@ -298,6 +302,40 @@ func TestMetadataAnalyzer_Integration(t *testing.T) {
}
}
func TestMetadataAnalyzer_Integration_DeepNestedSkill(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "a", "b", "c", "d", "evil-skill")
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
skillContent := "---\nname: evil-skill\ndescription: Official formatter from Acme Corp\n---\n# Evil\n"
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(skillContent), 0644); err != nil {
t.Fatal(err)
}
store := metadataStoreJSON{Entries: map[string]metaJSON{
"a/b/c/d/evil-skill": {RepoURL: "https://github.com/evil-fork/skills.git"},
}}
storeData, _ := json.Marshal(store)
if err := os.WriteFile(filepath.Join(root, metadataFileName), storeData, 0644); err != nil {
t.Fatal(err)
}
a := &metadataAnalyzer{}
ctx := &AnalyzeContext{
SkillPath: dir,
DisabledIDs: map[string]bool{},
}
findings, err := a.Analyze(ctx)
if err != nil {
t.Fatal(err)
}
if len(findings) < 2 {
t.Fatalf("expected deep nested skill to resolve metadata, got %d findings", len(findings))
}
}
func TestMetadataAnalyzer_NoMeta(t *testing.T) {
// Skill without .skillshare-meta.json — should produce no findings
dir := t.TempDir()
@@ -320,14 +358,18 @@ func TestMetadataAnalyzer_NoMeta(t *testing.T) {
}
func TestMetadataAnalyzer_DisabledRules(t *testing.T) {
dir := t.TempDir()
root := t.TempDir()
dir := filepath.Join(root, "test-skill")
os.MkdirAll(dir, 0755)
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"),
[]byte("---\nname: test\ndescription: Official tool from Acme Corp\n---\n"), 0644); err != nil {
t.Fatal(err)
}
meta := metaJSON{RepoURL: "https://github.com/evil-fork/skills.git"}
metaData, _ := json.Marshal(meta)
if err := os.WriteFile(filepath.Join(dir, ".skillshare-meta.json"), metaData, 0644); err != nil {
store := metadataStoreJSON{Entries: map[string]metaJSON{
"test-skill": {RepoURL: "https://github.com/evil-fork/skills.git"},
}}
storeData, _ := json.Marshal(store)
if err := os.WriteFile(filepath.Join(root, metadataFileName), storeData, 0644); err != nil {
t.Fatal(err)
}

Some files were not shown because too many files have changed in this diff Show More