Merge remote-tracking branch 'origin/main' into pr-168

This commit is contained in:
Willie
2026-09-19 19:17:29 +00:00
526 changed files with 51782 additions and 35551 deletions
+5
View File
@@ -0,0 +1,5 @@
# CodeGraph data files — local to each machine, not for committing.
# Ignore everything in .codegraph/ except this file itself, so transient
# files (the database, daemon.pid, sockets, logs) never show up in git.
*
!.gitignore
+2 -2
View File
@@ -1,10 +1,10 @@
#!/usr/bin/env bash
# Devcontainer: start/stop Docusaurus.
# Usage: docs # start → http://localhost:8888
# Usage: docs # start → http://localhost:48888
# docs stop # stop
set -euo pipefail
PORT=8888
PORT=48888
PIDDIR=/tmp/dev-servers
LOGDIR=/tmp
mkdir -p "$PIDDIR"
+6 -5
View File
@@ -1,12 +1,13 @@
#!/usr/bin/env bash
# Devcontainer: launch dashboard (API backend + Vite frontend).
# Usage: ui # global mode → http://localhost:5173
# ui -p # project mode (~/demo-project) → http://localhost:5173
# Usage: ui # global mode → http://localhost:45173
# ui -p # project mode (~/demo-project) → http://localhost:45173
# ui stop # stop API + Vite
set -euo pipefail
PORT=19420
VITE_PORT=5173
# Uncommon ports so the devcontainer does not fight other projects for 5173/19420.
PORT=49420
VITE_PORT=45173
PIDDIR=/tmp/dev-servers
LOGDIR=/tmp
mkdir -p "$PIDDIR"
@@ -158,7 +159,7 @@ for p in "$(go env GOPATH)/bin/air" /go/bin/air /usr/local/go/bin/air; do
done
if [ -z "$AIR_BIN" ]; then
echo " air not found — installing..." >&2
go install github.com/air-verse/air@latest
go install github.com/air-verse/air@v1.67.1 # v1.67.2+ needs go >= 1.26
AIR_BIN="$(go env GOPATH)/bin/air"
fi
+4 -4
View File
@@ -27,12 +27,12 @@ elif [ -x /usr/local/share/nvm/current/bin/pnpm ]; then
PNPM_BIN="/usr/local/share/nvm/current/bin/pnpm"
fi
declare -A PORTS=([api]=19420 [vite]=5173 [docusaurus]=8888)
declare -A PORTS=([api]=49420 [vite]=45173 [docusaurus]=48888)
declare -A DIRS=([api]=/workspace [vite]=/workspace/ui [docusaurus]=/workspace/website)
declare -A CMDS=(
[api]="/usr/local/go/bin/go run ./cmd/skillshare ui --no-open --host 0.0.0.0 --port 19420"
[vite]="${PNPM_BIN:-pnpm} exec vite --host 0.0.0.0 --port 5173 --strictPort"
[docusaurus]="${PNPM_BIN:-pnpm} exec docusaurus start --host 0.0.0.0 --port 8888 --no-open"
[api]="/usr/local/go/bin/go run ./cmd/skillshare ui --no-open --host 0.0.0.0 --port 49420"
[vite]="${PNPM_BIN:-pnpm} exec vite --host 0.0.0.0 --port 45173 --strictPort"
[docusaurus]="${PNPM_BIN:-pnpm} exec docusaurus start --host 0.0.0.0 --port 48888 --no-open"
)
declare -A VERIFY=([api]="skillshare" [vite]="vite" [docusaurus]="docusaurus")
ALL=(vite docusaurus)
+4 -4
View File
@@ -3,11 +3,11 @@
"dockerComposeFile": "docker-compose.yml",
"service": "skillshare-devcontainer",
"workspaceFolder": "/workspace",
"forwardPorts": [5173, 19420, 8888],
"forwardPorts": [45173, 49420, 48888],
"portsAttributes": {
"5173": { "label": "Dashboard (ui)" },
"19420": { "label": "API Backend" },
"8888": { "label": "Docs (docs)" }
"45173": { "label": "Dashboard (ui)" },
"49420": { "label": "API Backend" },
"48888": { "label": "Docs (docs)" }
},
"remoteEnv": {
"PATH": "/workspace/.devcontainer/bin:/usr/local/bin:${containerEnv:PATH}",
+5 -3
View File
@@ -15,15 +15,17 @@ services:
# miss file saves. Force polling-based file watching inside the container.
CHOKIDAR_USEPOLLING: "true"
GOCACHE: /go/build-cache
SKILLSHARE_API_PORT: "49420"
GITHUB_TOKEN: ${GITHUB_TOKEN:-}
GITLAB_TOKEN: ${GITLAB_TOKEN:-}
BITBUCKET_TOKEN: ${BITBUCKET_TOKEN:-}
BITBUCKET_USERNAME: ${BITBUCKET_USERNAME:-}
SKILLSHARE_GIT_TOKEN: ${SKILLSHARE_GIT_TOKEN:-}
# Uncommon ports: 5173/8888/19420 clash with whatever else is running on the host.
ports:
- "5173:5173"
- "19420:19420"
- "8888:8888"
- "45173:45173"
- "49420:49420"
- "48888:48888"
volumes:
- ..:/workspace
# Container-local node_modules (anonymous volumes) so platform-native
+3 -3
View File
@@ -62,10 +62,10 @@ echo ""
echo "Quick start:"
echo " ss status # check current state"
echo " ss list # see all skills"
echo " ui # global-mode dashboard → :5173"
echo " ui -p # project-mode dashboard → :5173"
echo " ui # global-mode dashboard → :45173"
echo " ui -p # project-mode dashboard → :45173"
echo " ui stop # stop dashboard"
echo " docs # documentation site → :8888"
echo " docs # documentation site → :48888"
echo " docs stop # stop docs"
echo ""
echo "Private repos:"
+3 -3
View File
@@ -48,10 +48,10 @@ if [ -z "${GITHUB_TOKEN:-}" ] && command -v gh &>/dev/null; then
fi
echo "Dev servers ready:"
echo " ui # global-mode dashboard → :5173"
echo " ui -p # project-mode dashboard → :5173"
echo " ui # global-mode dashboard → :45173"
echo " ui -p # project-mode dashboard → :45173"
echo " ui stop # stop dashboard"
echo " docs # documentation site → :8888"
echo " docs # documentation site → :48888"
echo " docs stop # stop docs"
echo " ss ... # instant mode (go run, no manual rebuild)"
echo " ssenv ... # isolated HOME environments (create/use/enter/list/reset/delete)"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 476 KiB

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 433 KiB

After

Width:  |  Height:  |  Size: 347 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 401 KiB

After

Width:  |  Height:  |  Size: 534 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 520 KiB

After

Width:  |  Height:  |  Size: 625 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 577 KiB

After

Width:  |  Height:  |  Size: 500 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 768 KiB

After

Width:  |  Height:  |  Size: 727 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 361 KiB

After

Width:  |  Height:  |  Size: 347 KiB

+3
View File
@@ -54,6 +54,9 @@ ui/node_modules/
ui/dist/
internal/server/dist/
# Host verification environment (scripts/verify.sh)
.verify-home/
# Air hot-reload
tmp/
MEMORY.md
@@ -167,8 +167,8 @@ docker exec $CONTAINER ui -p
docker exec $CONTAINER ui stop
```
Dashboard accessible at `http://localhost:5173` (Vite dev server with HMR).
API backend at `http://localhost:19420`.
Dashboard accessible at `http://localhost:45173` (Vite dev server with HMR).
API backend at `http://localhost:49420`.
Logs: `/tmp/api-dev.log`, `/tmp/vite-dev.log`.
## ssenv Quick Reference
@@ -188,9 +188,9 @@ For automation (non-interactive), prefer `ssenv enter <name> -- <command>` over
| Port | Service | Notes |
|------|---------|-------|
| 5173 | Vite dev server | React dashboard with HMR |
| 19420 | Go API backend | `skillshare ui` server |
| 3000 | Docusaurus | `docs` command in devcontainer |
| 45173 | Vite dev server | React dashboard with HMR |
| 49420 | Go API backend | `skillshare ui` server |
| 48888 | Docusaurus | `docs` command in devcontainer |
## Common Mistakes to Avoid
@@ -157,7 +157,7 @@ All interactive prompts use **bubbletea** (not survey). Key components:
Color palette: cyan `Color("6")`, gray `Color("8")`, yellow `#D4D93C`.
Dispatch order: JSON output → TUI (if TTY + items + !`--no-tui`) → empty check → plain text.
Dispatch order: JSON output → TUI (if TTY + items + no `--no-tui` flag) → empty check → plain text.
### Web API Endpoint
@@ -5,285 +5,255 @@ description: >-
website (website/). Use this skill whenever you: build or modify a dashboard page
or component in ui/src/, style or layout website pages or custom CSS in website/,
create new React components for the dashboard, add pages to the dashboard, fix
visual bugs in either frontend, or need to know which design tokens, components,
or patterns to use. This skill covers color tokens, typography, component API,
page structure, accessibility, keyboard shortcuts, animations, and anti-patterns
for both frontends. Even if the user just says "fix the styling" or "add a card",
use this skill to ensure consistency.
visual bugs in either frontend, or need to know which design tokens, ss-* classes,
components, or patterns to use. Covers the two dashboard styles (Clean / Playful)
in light and dark, design tokens, the ss-* class system, component API, page
structure, accessibility, keyboard shortcuts, and anti-patterns. Even if the user
just says "fix the styling" or "add a card", use this skill to ensure consistency.
metadata:
targets: [claude, universal]
---
Enforce the skillshare design system across the two frontends. $ARGUMENTS is the file or area being worked on.
**Companion skill**: For UX design decisions beyond token/component usage — layout strategy, information hierarchy, interaction patterns, micro-copy, or when designing a new page from scratch — also invoke `/ui-ux-pro-max` for higher-level design guidance. This skill handles *what components and tokens to use*; `/ui-ux-pro-max` handles *how to design the experience*.
The project has **two distinct design systems** sharing semantic color names but with different visual treatments:
| Aspect | UI Dashboard (`ui/`) | Website (`website/`) |
|--------|---------------------|----------------------|
| Stack | React 19 + Vite + Tailwind CSS v4 | Docusaurus 3 + custom CSS |
| Font body | DM Sans | IBM Plex Sans |
| Font heading | DM Sans | Inter |
| Font mono | SFMono-Regular, Menlo | JetBrains Mono |
| Border-radius | Clean: `4px`/`8px`/`12px`/pill | Wobbly: `255px 15px 225px 15px / ...` |
| Shadows | Subtle blur: `0 1px 3px rgba(...)` | Hard offset: `4px 4px 0px 0px #2d2d2d` |
| Background | Flat `#f7f6f3` | Dot grid on `#fdfbf7` |
| Philosophy | skillshare-inspired minimal | Hand-drawn sketchy organic |
| Source of truth | `ui/src/components.css` (tokens + `ss-*` classes), `ui/src/index.css` (Tailwind mapping) | `website/src/css/custom.css` (docs), `website/src/pages/*.module.css` (homepage, features) |
| Looks | Two styles, **Clean** and **Playful**, each in light and dark | Docs: clean. Homepage: hand-drawn string board |
**This file names tokens and classes and says when to use them. It does not copy their values.** Colours, radii, fonts and shadows change; read them from the CSS when you need one.
---
## UI Dashboard (`ui/`)
Reference implementation: `ui/src/pages/LogPage.tsx`
Reference pages: `ui/src/pages/TargetsPage.tsx` (list page), `ui/src/pages/HubPage.tsx` (tabs), `ui/src/pages/ResourcesPage.tsx` (list + tiles + bulk toolbar).
> For the full human-readable style guide (design philosophy, visual rules, anti-patterns), see `references/STYLE_GUIDE.md` bundled with this skill.
> Design rules and the reasoning behind them: `references/STYLE_GUIDE.md`.
### Design Tokens
### Two styles, two modes
Defined in `ui/src/index.css` (@theme) and `ui/src/design.ts`:
Style and mode are independent, so every screen has four looks.
```ts
// ui/src/design.ts
import { radius, shadows, palette } from '../design';
| Axis | Values | How it is set |
|------|--------|---------------|
| Style | Clean, Playful (default) | `html[data-theme="playful"]`; attribute absent = Clean |
| Mode | light, dark, system | `html.dark` |
radius.sm // '4px' — badges, chips
radius.md // '8px' — cards, containers
radius.lg // '12px' — modals, panels
radius.btn // '9999px' — pill buttons (skillshare style)
radius.full // '9999px' — avatars
Set by `ui/src/context/ThemeContext.tsx`, switched in `ThemePopover.tsx`. `?theme=clean|playful|dark|light` in the URL forces one, which is handy for screenshots.
shadows.sm / .md / .lg / .hover / .active / .accent / .blue
palette.accent / .info / .success / .warning / .danger
All four looks come from CSS variables alone. A page that uses only tokens and `ss-*` classes gets all four for free; a hardcoded colour, radius or shadow breaks three of them.
- Clean: system font, 1px hairlines, soft shadows, ink-coloured primary button.
- Playful: Kalam headings, 2px ink borders, hard offset shadows, dashed separators, yellow primary, pastel accents, dot-grid background, sticky-note tiles.
- Style-only markup: `.ss-only-clean` / `.ss-only-playful` (Dashboard shows a count strip in Clean and a pin board in Playful).
### Design tokens
Defined per look at the top of `ui/src/components.css`. `ui/src/index.css` exposes them to Tailwind through `@theme inline`, so `text-ink-2`, `bg-surface`, `border-line` all follow the active look.
| Group | Tokens | Use |
|-------|--------|-----|
| Surfaces | `--bg` `--side` `--surface` `--sunken` | Page, sidebar, cards and inputs, recessed headers and footers |
| Text | `--ink` `--ink-2` `--ink-3` | Primary, secondary, tertiary and placeholder |
| Lines | `--line` `--line-2` `--line-soft` | Frames, control borders, soft dividers |
| Borders | `--sep` `--frame` `--bw` | Whole `border` values: row separator, box frame, control border width |
| Action | `--pri` `--on-pri` `--accent` `--accent-bg` `--sel` `--sel-ink` | Primary button, links and focus, selected nav and menu items |
| Status | `--ok` `--warn` `--bad`, each with `-bg` | Text or dot colour, plus its tinted background |
| Kind | `--c-skill` `--c-agent` `--c-extra` `--c-mcp` `--c-plugin` `--c-target`, each with `-bg` | Resource-kind colour, used by `.ss-cat` |
| Pastels | `--pa` `--pb` `--pc` `--pd` `--pe` | **Playful only.** Never reference outside a `[data-theme="playful"]` rule |
| Type | `--f` `--fh` `--fm` `--h1` `--h2` | Body, heading (Kalam in Playful), mono, heading shorthands |
| Shape | `--r-ctl` `--r-btn` `--r-box` `--r-tag` | Controls, buttons (pill), boxes, tags |
| Shadow | `--sh-box` `--sh-btn` `--sh-float` `--sh-dialog` | Boxes, buttons, menus and toasts, dialogs |
Tailwind names: `bg` `side` `surface` `sunken` `ink` `ink-2` `ink-3` `line` `line-2` `line-soft` `sel` `pri` `on-pri` `ok` `warn` `bad` (with `-bg`) and `link` / `link-bg` for `--accent`.
**Legacy names**: `pencil`, `pencil-light`, `paper`, `paper-warm`, `muted`, `muted-dark`, `success`, `warning`, `danger`, `blue`, `info`, `accent` still resolve as aliases for markup not yet migrated. Do not use them in new code. When you touch a line that has one, replace it:
| Legacy | Use |
|--------|-----|
| `text-pencil` | `text-ink` |
| `text-pencil-light` | `text-ink-2` |
| `text-muted-dark` | `text-ink-3` |
| `bg-paper` / `bg-paper-warm` | `bg-bg` / `bg-side` |
| `border-muted` | `border-line` |
| `text-success` / `text-warning` / `text-danger` | `text-ok` / `text-warn` / `text-bad` |
| `text-blue` / `text-info` | `text-link` |
`ui/src/design.ts` (`radius`, `shadows`, `palette`) forwards to the same variables, for inline styles only.
### The `ss-*` classes
All in `@layer components` in `ui/src/components.css`. List what exists today:
```bash
grep -o '\.ss-[a-z0-9-]*' ui/src/components.css | sort -u
```
### Color Tokens (Tailwind classes)
State and variant are short modifier classes on the same element: `.on` (selected or checked), `.sel` (selected row or tile), `.ok` `.warn` `.bad` `.inf` (tone), `.sm` `.lg` (size).
| Role | Class | When |
|------|-------|------|
| Primary text | `text-pencil` | Titles, names, values |
| Secondary | `text-pencil-light` | Descriptions, timestamps, labels |
| Tertiary | `text-muted-dark` | Hints, placeholders |
| Success | `text-success` | Passed, synced, clean |
| Warning | `text-warning` | Dirty, behind, partial |
| Danger | `text-danger` | Failed, blocked, critical |
| Info / Blue | `text-blue` | Links, info badges, repo URLs |
| Background | `bg-surface` | Cards, inputs |
| Page bg | `bg-paper` | Root background |
| Borders | `border-muted` | Default borders |
| Area | Classes |
|------|---------|
| Page | `.ss-wrap` (1080px column, 28px gap), `.ss-pgh` + `.ss-ph` (header, via `PageHeader`), `.ss-crumb`, `.ss-sec` (section heading row; `h2` inside, `.more` link on the right), `.ss-h1` `.ss-h2`, `.ss-hand` (Kalam aside) |
| Shell | `.ss-side` `.ss-wm` `.ss-nvg` `.ss-nv` `.ss-sidefoot` — `Layout.tsx` only |
| Buttons | `.ss-btn` + `.pri` `.ghost` `.dng` + `.sm` `.lg`; `.ss-ib` (30px icon button); `.ss-more` (text link) |
| Forms | `.ss-fld` (label + control + `.hp` help), `.ss-inp` (+ `.area` `.err`, `.k` key hint), `.ss-chk` (+ `.rad`), `.ss-sw` (switch), `.ss-tgl` (icon toggle), `.ss-seg` (+ `.ic` icon-only) |
| Navigation | `.ss-tabs`, `.ss-tabbar` (tabs with controls on the right), `.ss-pager`, `.ss-menu` (+ `.hv` `.dng`, `hr`, `.k`) |
| Lists | `.ss-list` (framed container), `.ss-lh` (column header), `.ss-gh` (group header), `.ss-r` (row; `.link` clickable, `.sel`, `.fold`; `.nm` name, `.nm.m` mono name), `.ss-plain` (rows without side padding), `.tr` with `--d` (tree indent) |
| Boxes | `.ss-box` (card, via `Card`), `.ss-tiles` + `.ss-tile` (grid; sticky notes in Playful), `.ss-kv` (`dl` key/value), `.ss-setrow` (settings row), `.ss-counts` (stat strip) |
| Status | `.ss-st` (dot + text; `.ok` `.warn` `.bad` `.off`, `.wrap` for long messages), `.ss-tag` (mono label; `.ok` `.warn` `.bad` `.inf`), `.ss-sev` (audit severity; `.c` `.h` `.md` `.l` `.n`), `.ss-cnt` (count) |
| Icons | `.ss-cat` (kind tile; `.skill` `.agent` `.extra` `.mcp` `.plugin` `.target`, tones, `.sm`), `.ss-at` (agent or tool logo; `.lg`), `.ss-stack` (overlapping logos) |
| Feedback | `.ss-note` (+ `.warn` `.bad` `.inf`), `.ss-empty` (via `EmptyState`), `.ss-prog`, `.ss-skel`, `.ss-toast`, `.ss-tip` |
| Overlays | `.ss-scrim` + `.ss-dlg` with `.dh` `.db` `.df` (via `DialogShell`), `.ss-bulk` (selection toolbar), `.ss-top` |
| Content | `.ss-prose` (rendered markdown), `.ss-code` (+ `.ln` `.cur`), `.ss-pre`, `.ss-ed` (editor) |
| Dashboard | `.ss-board` `.ss-pin` `.ss-pinnote` `.ss-squig` — Playful pin board |
**Rule**: Max one accent color per visual region. Don't double up — if a row has a colored dot, skip the colored badge (or vice versa).
Tailwind utilities are for layout inside these (`flex`, `gap-*`, `min-w-0`, `w-[92px]`, `truncate`). Colour, border, radius and shadow come from `ss-*` classes or token utilities.
### Typography
**Cascade gotcha**: the `ss-*` classes sit in `@layer components`, so a Tailwind utility on the same element always wins, whatever the selector specificity. Do not put `mb-*` on something `.ss-wrap` already spaces. To override an `ss-*` property from markup, use the Tailwind important prefix, as in `className="ss-r link !min-h-[56px]"`.
- Body: DM Sans (via `--font-hand`)
- `font-mono`: timestamps, file paths, durations, code, hashes
- `uppercase tracking-wider`: command names, stat labels
- Size: `text-2xl` > `text-xl` > `text-base` > `text-sm` > `text-xs`
### Page Structure (mandatory order)
Every page follows this layout:
### Page structure
```tsx
<div className="space-y-5 animate-fade-in">
<PageHeader icon={<Icon />} title="..." subtitle="..." actions={<>...</>} />
<div className="ss-wrap animate-fade-in">
<PageHeader title={t('x.title')} subtitle={t('x.subtitle')} actions={<>...</>} />
{/* Toolbar: tabs + filters */}
<div className="flex flex-wrap items-end gap-3">
<SegmentedControl ... />
<Select ... />
</div>
{/* optional: tabs, or tabs with controls on the right */}
<nav className="ss-tabs" aria-label={t('x.title')}>
<button type="button" className={on ? 'on' : ''} aria-current={on}>...</button>
</nav>
{/* Summary line or stat cards */}
<SummaryLine ... />
{error && <div className="ss-note bad"><span className="flex-1">{error.message}</span></div>}
{/* Content: table, card list, or card grid */}
{empty ? <EmptyState ... /> : <ContentArea />}
{empty ? (
<EmptyState icon={SomeIcon} title="..." description="..." action={...} />
) : (
<div className="ss-list">
<div className="ss-lh">{/* column labels; widths match the row cells */}</div>
<Link to="..." className="ss-r link">
<span className="ss-cat skill"><Puzzle size={16} /></span>
<span className="nm m min-w-0 flex-1 truncate">name</span>
<span className="w-[92px] shrink-0"><span className="ss-tag">merge</span></span>
<span className="ss-st ok">synced</span>
</Link>
</div>
)}
{/* Dialogs (rendered at bottom, portal via DialogShell) */}
<ConfirmDialog ... />
{/* a second section */}
<section>
<div className="ss-sec"><h2>Title</h2><span className="ss-cnt">12</span></div>
<div className="ss-list">...</div>
</section>
{/* dialogs last; DialogShell portals to body */}
</div>
```
### Component Library
- `.ss-wrap` spaces its children with a 28px gap. Do not add `space-y-*` or margins between them.
- A page that is one child of a wider layout, without `.ss-wrap`, still gets header spacing from `.ss-pgh`.
- `PageHeader` no longer renders `icon`; do not pass it. Use `backTo` for a sub-page of a nav item, `crumbs` for deeper trails, `mono` when the title is a resource name.
- A sub-page reached from a nav item keeps that item lit through `also` in the `Layout.tsx` nav definition (Skills stays active on `/hubs`).
| Component | File | API |
|-----------|------|-----|
| `Card` | `Card.tsx` | `variant="default\|accent\|outlined"`, `hover`, `overflow`, `tilt?`, `padding="none\|sm\|md"` — accent uses thicker border for emphasis (no stripe) |
| `Button` | `Button.tsx` | `variant="primary\|secondary\|danger\|ghost\|link"`, `size="sm\|md\|lg"`, `loading?` |
| `Badge` | `Badge.tsx` | `variant="default\|success\|warning\|danger\|info\|accent"`, `size="sm\|md"`, `dot?` |
| `PageHeader` | `PageHeader.tsx` | `icon`, `title`, `subtitle?`, `actions?`, `backTo?` (styled back arrow) |
| `EmptyState` | `EmptyState.tsx` | `icon` (LucideIcon), `title`, `description?`, `action?` |
| `ConfirmDialog` | `ConfirmDialog.tsx` | `open`, `onConfirm`, `onCancel`, `title`, `message`, `variant="default\|danger"` |
| `DialogShell` | `DialogShell.tsx` | `open`, `onClose`, `maxWidth`, `preventClose` (backdrop blur + dialog-in animation) |
| `Input` | `Input.tsx` | `label?` + standard input props (re-exports Checkbox, Select) |
| `Textarea` | `Input.tsx` | `label?` + standard textarea props |
| `Select` | `Select.tsx` | `label?`, `value`, `onChange`, `options[]`, `size="sm\|md"` |
| `Checkbox` | `Checkbox.tsx` | `label`, `checked`, `onChange`, `indeterminate?`, `disabled?`, `size="sm\|md"` |
| `Spinner` | `Spinner.tsx` | `size="sm\|md\|lg"` — use instead of `<RefreshCw className="animate-spin">` |
| `Tooltip` | `Tooltip.tsx` | `content: string`, `side="top\|bottom"` — portal-based, 200ms delay |
| `SegmentedControl` | `SegmentedControl.tsx` | `value`, `onChange`, `options[]`, `connected?`, `colorFn?` |
| `Pagination` | `Pagination.tsx` | `page`, `totalPages`, `onPageChange`, `rangeText?`, `pageSize?` |
| `StatusBadge` | `StatusBadge.tsx` | Status display |
| `Skeleton` / `PageSkeleton` | `Skeleton.tsx` | Shimmer animation loading states |
| `Toast` / `useToast` | `Toast.tsx` | `toast(message, 'success'\|'error')` — exit animation, progress bar, hover pause |
| `FilterTagInput` | `FilterTagInput.tsx` | Tag-based filter input |
| `IconButton` | `IconButton.tsx` | Icon-only button with `aria-label` |
### Components
### Stats Patterns (choose one)
Shared components in `ui/src/components/` wrap the `ss-*` classes. Use the component when one exists; write the class directly for things that have none (`.ss-list` rows, `.ss-note`, `.ss-tabs`, `.ss-st`, `.ss-tag`, `.ss-kv`).
| Pattern | When |
|---------|------|
| **Inline summary text** | 1-3 stats: `"42 ops · 3 errors · last: 2m ago"` |
| **Stat card grid** | Dashboard overview KPIs only |
| Component | Renders | API |
|-----------|---------|-----|
| `PageHeader` | `.ss-pgh` `.ss-ph` | `title`, `subtitle?`, `actions?`, `backTo?`, `crumbs?`, `mono?` |
| `Button` | `.ss-btn` | `variant="primary\|secondary\|danger\|warning\|ghost\|link"`, `size="xs\|sm\|md\|lg"`, `loading?` |
| `IconButton` | `.ss-ib` | `icon`, `label` (required, becomes `aria-label`), `size`, `variant="ghost\|danger-outline"` |
| `Card` | `.ss-box` | `padding="none\|sm\|md"`, `variant="default\|outlined"`, `hover?`, `overflow?`, `onClick?`. `tilt` and `skillCard` do nothing |
| `Badge` | `.ss-tag` | `variant="default\|success\|warning\|danger\|info"`, `size`, `dot?` |
| `KindBadge` | `.ss-tag` | `kind="skill\|agent"` |
| `EmptyState` | `.ss-empty` | `icon` (LucideIcon), `title`, `description?`, `action?` |
| `DialogShell` | `.ss-scrim` `.ss-dlg` | `open`, `onClose`, `maxWidth="sm".."7xl"`, `padding`, `preventClose?`, `ariaLabel`. Use `padding="none"` with `.dh` / `.db` / `.df` children for the standard header, body and footer |
| `ConfirmDialog` | `DialogShell` | `open`, `onConfirm`, `onCancel`, `title`, `message`, `variant="default\|danger"`, `loading?`, `wide?` |
| `Input`, `Textarea` | `.ss-fld` `.ss-inp` | `label?`, `size="sm\|md"` + native props. `Input.tsx` re-exports `Checkbox` and `Select` |
| `Select` | `.ss-inp` + `.ss-menu` | `label?`, `value`, `onChange`, `options[]` (`description?`), `size`, `prefix?` |
| `Checkbox` | `.ss-chk` | `label` (required), `checked`, `onChange`, `indeterminate?`, `hideLabel?` for row selection |
| `SegmentedControl` | `.ss-seg` | `value`, `onChange`, `options[]` (`count?`, `title?` for icon-only), `colorFn?` |
| `Pagination` | `.ss-pager` | `page`, `totalPages`, `onPageChange`, `rangeText?`, `pageSize?` |
| `Tooltip`, `TruncateTip` | `.ss-tip` | `content`, `side`, `delay`, `followCursor?` |
| `Spinner` | lucide `Loader2` | `size="sm\|md\|lg"` |
| `Skeleton`, `PageSkeleton` | shimmer | `variant="text\|card\|circle"` |
| `useToast()` | `.ss-toast` | `toast(message, 'success'\|'error'\|'warning'\|'info', { title? })` |
| `AgentIcon` | real agent logo | For targets and agents. Do not substitute a generic lucide icon |
| `CopyButton`, `CodeView`, `CodeEditor`, `MarkdownView` | `.ss-code` `.ss-prose` | Code and markdown display |
### Status Patterns (choose one per element)
Feature folders (`audit/`, `config/`, `git/`, `hub/`, `mcp/`, `plugins/`, `skill-editor/`, `sync/`, `targets/`, `tour/`) hold page-specific pieces.
| Pattern | Markup | When |
|---------|--------|------|
| Colored dot | `w-2 h-2 rounded-full` | Table rows, list items, audit findings/rules |
| Badge | `<Badge variant="...">` | Standalone labels |
### Icons
### List Patterns
lucide-react only. 14–16px inline, 16px inside `.ss-cat`, 24px in `EmptyState`. Stroke width comes from `--isw`; do not set `strokeWidth`, except the check mark inside `.ss-chk`. One icon per concept across the app: check `Layout.tsx` and neighbouring pages before picking one.
| Pattern | When |
|---------|------|
| Table | Uniform rows, sortable columns, many items |
| Card list (vertical) | Mixed content per row, expandable |
| Card grid | Visual overview, few fields per item |
### Data fetching
### Button Variants
| Variant | When |
|---------|------|
| `danger` | Permanent destructive: clear log, empty trash, delete forever |
| `secondary` | Reversible removal: uninstall, remove, restore |
| `ghost` | Cancel, clear filter, reset |
| `primary` | Positive action: save, sync, install, run |
### Separator
Always: `border-dashed border-pencil-light/30` (unified opacity, not `/20` or `/40`)
### Animations
| Context | Value |
|---------|-------|
| Card rotation | `rotate(+-0.15deg)` via `:nth-child(odd/even)` |
| Standalone accent | Max `rotate(+-0.3deg)` |
| Hover | `transition-all duration-150` |
| Page entry | `animate-fade-in` (0.2s ease-out) |
### Keyboard Shortcuts
Registered in `KeyboardShortcutsModal.tsx` and `useGlobalShortcuts.ts`:
- `?` — shortcuts modal
- `/` — focus search
- `g d/s/t/l` — go to Dashboard/Skills/Targets/Log
- `r` — refresh page
- Only fire when no `<input>` / `<textarea>` focused
- Chord timeout: 500ms
- New shortcuts must be added to `KeyboardShortcutsModal`
- Never override browser-native shortcuts (`Cmd+C`, etc.)
### Accessibility
| Concern | Requirement |
|---------|-------------|
| Focus ring | `focus:ring-2 focus:ring-blue/20` |
| Touch target | Min 44x44px |
| Color contrast | 4.5:1 (WCAG AA) |
| Icon buttons | `aria-label` required |
| Modals | `role="dialog"` + `aria-modal="true"` + `useFocusTrap` |
| Select | `role="combobox"` + `aria-expanded` + `role="listbox/option"` |
### Card Overflow Gotcha
`Card.tsx` has `overflow-hidden` by default for border-radius clipping. Absolute-positioned children (dropdowns, tooltips) get clipped. Fix: pass `overflow` prop or add `className="!overflow-visible"`.
### Data Fetching Pattern
Pages use `@tanstack/react-query`:
```tsx
const { data, isPending } = useQuery({
queryKey: queryKeys.someKey(...),
queryFn: () => api.someEndpoint(...),
const { data, error, isPending } = useQuery({
queryKey: queryKeys.someKey,
queryFn: () => api.someEndpoint(),
staleTime: staleTimes.someCategory,
});
if (isPending) return <PageSkeleton />;
```
- Query keys: `ui/src/lib/queryKeys.ts`
- API client: `ui/src/api/client.ts`
- App context: `ui/src/context/AppContext.tsx` provides `{ isProjectMode, projectRoot }`
Keys in `ui/src/lib/queryKeys.ts`, client in `ui/src/api/client.ts`, `useAppContext()` gives `{ isProjectMode, projectRoot }`. Every user-visible string goes through `useT()`; status, mode and kind labels (`merge`, `linked`, `skill`) stay in English.
### Verifying a change
Run the dev server inside the devcontainer with the `ui` command, never on the host. There Vite listens on :45173 (`make ui-dev` on a host with Go uses :5173). Screenshot the page in all four looks, at desktop width only: `?theme=clean`, `?theme=playful`, then each in dark. Look at the screenshots before reporting done. Do not run prettier in `ui/`; it has no config and rewrites whole files.
---
## Website (`website/`)
Docusaurus with hand-drawn "sketchy organic" design in `website/src/css/custom.css`.
Two separate treatments share one palette in `website/src/css/custom.css`.
### Key Differences from UI Dashboard
| Area | Files | Look |
|------|-------|------|
| Docs, navbar, footer | `src/css/custom.css` | Clean: pill buttons, solid 1px borders, soft shadows, plain underlined links, no dot grid |
| Homepage, feature map | `src/pages/index.tsx` + `index.module.css`, `features.tsx` + `features.module.css` | Hand-drawn string board: pinned notes, tape, string lines, wobbly radii, hard offset shadows, Kalam accents, slight rotation |
- **Wobbly borders**: `border-radius: var(--radius-wobbly)` (not clean px values)
- **Hard shadows**: `4px 4px 0px 0px #2d2d2d` (no blur)
- **Dot grid bg**: `radial-gradient(var(--color-muted) 1px, transparent 1px)` on body
- **Post-it yellow**: `--color-postit: #fff9c4` for highlights
- **Dashed borders everywhere**: navbar, sidebar, tables, pagination, code blocks
- **Button hover**: `transform: translate(2px, 2px)` + shadow shrinks (press-down feel)
- **Links**: wavy underline (`text-decoration-style: wavy`)
- **Dark mode**: amber/gold primary (`#e8a84c`) instead of blue
### CSS Variables
See `website/src/css/custom.css` for full list. Key additions beyond shared palette:
- `--radius-wobbly[-sm|-md|-btn]` — hand-drawn border-radius
- `--color-postit[-dark]` — yellow highlight
- `--shadow-md: 4px 4px 0px 0px #2d2d2d` — hard offset
- `--card-bg`, `--card-border`, `--install-bg` — component-specific
### Docusaurus Classes
- `.button--primary` — green bg, pencil border, hard shadow
- `.button--secondary` — dashed border, no fill
- `.markdown h2` — dashed bottom border
- `.admonition` — wobbly border-radius, left stripe
- `.menu__link--active` — post-it yellow background
- `.target-badge` — wobbly border for target grid
- Code blocks get `box-shadow: 4px 4px 0px 0px #101827`
### Homepage Components (`website/src/pages/index.tsx`)
- `CARD_ROTATIONS` array for random hand-drawn tilt
- `WavyDivider` — SVG dashed wavy line between sections
- `InstallTabs` — tabbed install commands with copy button
- Hero has hand-drawn SVG connector + underline
- Fonts: IBM Plex Sans body, Inter headings, JetBrains Mono code. Kalam appears on the homepage only.
- Palette variables keep the `--color-pencil` / `--color-paper` / `--color-postit` names here. That is current for the website; only the dashboard moved to `--ink` / `--bg`.
- `--radius-wobbly*` and the hard `--shadow-*` are defined globally but belong to the homepage modules. Do not apply them to docs chrome.
- Dark mode swaps the blue primary for amber. Check both modes.
- Docs chrome is styled by overriding Docusaurus classes (`.button--primary`, `.menu__link--active`, `.admonition`, `.table-of-contents`, `.target-badge`). Each block in `custom.css` has a titled banner comment; find the block, edit it there.
- Homepage sections are local components in `index.tsx` (`HeroSection`, `StringBoard`, `PinList`, `SyncTerminal`, `InstallTabs`, `FourMovesSection`, `FeatureMapTeaser`, `CtaSection`), styled from the CSS module.
- Mermaid diagrams use the global `handDrawn` config in `docusaurus.config.ts`: labels of one or two lines, `<br/>` for line breaks, and verify with a screenshot.
- Docs are English only. `~` inside an HTML `<code>` in MDX must be written `&#126;`.
---
## Anti-Patterns (Both Systems)
## Anti-patterns
| Don't | Do Instead |
| Don't | Do instead |
|-------|------------|
| Emojis as status icons | Colored dots, badges, or semantic icons |
| Stat cards for 1-3 values | Inline summary text |
| Left-border colored stripes (`border-l-*`) | Colored dots or badges — never use left stripe for emphasis or status |
| Stripe + badge for same status | Pick one per element |
| Mixed separator opacity (`/20`, `/40`) | Always `border-pencil-light/30` |
| `window.confirm()` | `<ConfirmDialog>` component |
| Custom empty-state markup | `<EmptyState>` component |
| Inline styles for design tokens | Use Tailwind classes or `design.ts` exports |
| `overflow-visible` on Card without `overflow` prop | Pass `overflow` prop to Card |
| Dropdowns inside `flex-wrap` title rows | Put dropdowns on their own row |
| Hardcoded hex, radius, shadow or font in a page | Token utility (`text-ink-2`) or `ss-*` class |
| Legacy names (`text-pencil-light`, `border-muted`, `text-danger`) in new code | `text-ink-2`, `border-line`, `text-bad` |
| Root `<div className="space-y-5">` | `.ss-wrap` |
| Hand-rolled dashed separators | `.ss-r` inside `.ss-list`, or `border: var(--sep)` |
| `<details>`, bare `<ul>` or `<p role="alert">` for app content | `.ss-list` rows, `.ss-note bad` |
| Playful pastels (`--pa`…`--pe`) in a shared rule | Scope to `:root[data-theme="playful"]` |
| Tilted cards | Nothing tilts in the dashboard. Rotation exists only on the website homepage |
| Dot and tag both carrying the same status | One per element: `.ss-st` for state, `.ss-tag` for a label |
| Left colour stripes (`border-l-*`) | `.ss-st`, `.ss-tag` or `.ss-note` |
| Emoji as icons | lucide, or `AgentIcon` for real tools |
| Stat cards for one to three numbers | Inline text, or `.ss-cnt` beside the heading |
| `window.confirm()` | `ConfirmDialog` |
| Custom empty-state markup | `EmptyState` |
| A small checkbox or icon as the only click target in a clickable row | Keep the hit area at 24px or more; `.ss-chk` already does this with `::after` |
| Dropdown inside a `Card` getting clipped | `overflow` prop on `Card` |
| Wording that drifts from the CLI | Use the CLI's terms: sync, target, collect, tracked, merge |
## Checklist Before Submitting
## Checklist
- [ ] Uses existing components (Card, Badge, Button, etc.) — no custom markup for solved patterns
- [ ] Page follows PageHeader → Toolbar → Summary → Content structure
- [ ] Color tokens from Tailwind (`text-pencil`, not hardcoded `#141312`)
- [ ] Separator is `border-dashed border-pencil-light/30`
- [ ] Empty states use `<EmptyState>`
- [ ] Destructive actions use `<ConfirmDialog>`
- [ ] All icon buttons have `aria-label`
- [ ] New shortcuts registered in `KeyboardShortcutsModal`
- [ ] `animate-fade-in` on root container
- [ ] Dark mode works (check both themes)
- [ ] Root is `.ss-wrap animate-fade-in`; `PageHeader` first, without `icon`
- [ ] No hardcoded colours, radii or shadows; no legacy token names added
- [ ] Shared components used where they exist; lists are `.ss-list` / `.ss-r`
- [ ] Errors are `.ss-note bad`, empty states are `EmptyState`, destructive actions go through `ConfirmDialog`
- [ ] Icon-only buttons have an accessible name; click targets are 24px or more
- [ ] Strings go through `useT()`; new shortcuts are added to `useGlobalShortcuts.ts`
- [ ] Screenshots checked in Clean and Playful, light and dark
@@ -1,178 +1,182 @@
# Skillshare Web Dashboard — Unified Style Guide
# Skillshare Web Dashboard — Style Guide
Reference implementation: `src/pages/LogPage.tsx`
The rules behind the dashboard, and why they exist. Token names, the `ss-*` class list and component APIs are in `../SKILL.md`; values are in `ui/src/components.css`.
Reference pages: `ui/src/pages/TargetsPage.tsx`, `ui/src/pages/ResourcesPage.tsx`.
---
## 1. Design Philosophy
## 1. Philosophy
- **skillshare-inspired**: whitespace over decoration, typography hierarchy over color coding
- **"Less is more"**: every visual element must earn its place — if removing it doesn't hurt comprehension, remove it
- LogPage redesign is the canonical reference: clean summary text, dashed separators, minimal color, monospace where data demands it
- **One layout, two skins.** Clean and Playful share the same markup, spacing and information hierarchy. A style changes how things are drawn, never what is on the page or where. The Dashboard pin board is the single exception, and it is marked with `.ss-only-playful`.
- **Flat.** One framed container per group of things (`.ss-list`, `.ss-box`). No card inside a card, no page made of stacked cards.
- **Typography before colour.** Hierarchy comes from size, weight and the three ink levels. Colour is for status and for resource kind, nothing else.
- **It should look made by a person.** Real tool logos (`AgentIcon`), one deliberate icon per concept, no gradient fills, no decorative icon above every heading, no emoji, no rows of identical stat cards.
- **Speak the CLI's language.** sync, target, collect, tracked, merge. The dashboard is another face of the same tool, so a label should match what the terminal prints.
- **Every element earns its place.** If removing it does not hurt comprehension, remove it.
---
## 2. Color Usage Rules
## 2. Clean and Playful
| | Clean | Playful (default) |
|-|-------|-------------------|
| Feel | Quiet, professional | Notebook, stationery |
| Headings | System font | Kalam |
| Borders | 1px hairline | 2px ink line |
| Shadows | Soft, barely there | Hard offset, no blur |
| Separators | Solid hairline | Dashed |
| Primary | Ink | Yellow with an ink border |
| Accents | None | Pastels, highlighter under the page title, dot-grid background |
| Tiles | Plain boxes | Sticky notes with tape |
Playful gets its character from line weight, hard shadows and the heading font. Nothing in the dashboard is rotated or tilted; rotation belongs to the website homepage.
Both styles ship in light and dark. Dark is not an inversion: Playful dark replaces yellow with amber and keeps pastel notes light enough for dark text, so check it rather than assuming.
---
## 3. Colour
| Role | Token | When |
|------|-------|------|
| Primary text | `text-pencil` | Titles, names, values |
| Secondary | `text-pencil-light` | Descriptions, timestamps, labels |
| Tertiary | `text-muted-dark` | Hints, placeholder text |
| Success | `text-success` | Passed, synced, clean |
| Warning | `text-warning` | Dirty, behind, partial |
| Danger | `text-danger` | Failed, blocked, critical |
| Info / Blue | `text-blue` | Links, info badge, repo URLs |
| Primary text | `ink` | Titles, names, values |
| Secondary | `ink-2` | Descriptions, subtitles |
| Tertiary | `ink-3` | Hints, placeholders, column headers, timestamps |
| Good | `ok` | Synced, passed, clean |
| Attention | `warn` | Behind, partial, dirty |
| Problem | `bad` | Failed, blocked, critical |
| Link, focus | `link` (`--accent`) | Links, focus rings, info notes |
| Kind | `--c-skill` `--c-agent` `--c-extra` `--c-mcp` `--c-target` | Resource kind, through `.ss-cat` only |
**Rule**: Max one accent color per visual region. Don't double up — if a row has a colored dot, skip the colored badge (or vice versa).
- One status signal per element: a `.ss-st` dot or a toned `.ss-tag`, not both.
- A kind colour means the same kind on every page. Do not borrow one for decoration.
- Status is never colour alone; `.ss-st` always carries text.
---
## 3. Typography
## 4. Typography
- **Body font**: DM Sans
- **Monospace** (`font-mono`): timestamps, file paths, durations, code snippets, hashes
- **Uppercase** (`uppercase tracking-wider`): command names, stat labels
- **Size hierarchy**: `text-2xl` > `text-xl` > `text-base` > `text-sm` > `text-xs`
- Body is the system font at 14px; most UI text is 13px.
- Mono (`font-mono`): resource names, paths, hashes, versions, commands, durations. `.ss-tag` is mono by design.
- Headings: `.ss-h1` for the page title (`PageHeader` does it), `.ss-h2` for section titles. Do not size headings with Tailwind text utilities, or they miss Kalam in Playful.
- Numbers are tabular already (`tnum` on `body`).
---
## 4. Layout Patterns
## 5. Layout
- **Root container**: `space-y-6 animate-fade-in` (unified across all pages)
- **Separator**: `border-dashed border-pencil-light/30` (unified — replaces any `/20`, `/40` variants)
- **Page structure**:
1. `PageHeader` — title + optional description
2. Toolbar — filters, search, actions
3. Summary — inline stats or stat card grid
4. Content — table, card list, or card grid
- Root: `.ss-wrap animate-fade-in`. 1080px column, 28px between sections.
- Order: `PageHeader` → tabs or toolbar → notes → content → dialogs.
- Spacing between sections comes from `.ss-wrap`. Spacing inside a section comes from the `ss-*` class. Reach for a Tailwind margin last.
- Toolbar: `flex flex-wrap items-center gap-3`; search first, then `SegmentedControl`, then `Select`.
- Desktop width only. The dashboard is a local tool; narrow layouts are not checked.
---
## 5. Component Usage Guidelines
## 6. Choosing a pattern
### 5.1 Stats — 2 patterns only
| Pattern | When | Example |
|---------|------|---------|
| **Inline summary text** | 1–3 stats | LogPage: "42 operations · 3 errors · last: 2 min ago" |
| **Stat card grid** | Dashboard overview only | Dashboard top-level KPIs |
Do not use stat cards for simple counts — prefer inline summary text.
### 5.2 Status — 3 patterns only
| Pattern | Markup | When |
|---------|--------|------|
| **Colored dot** | `w-2 h-2 rounded-full` | Table rows, list items, audit findings/rules |
| **Badge** | `<Badge variant="...">` | Standalone labels |
Never use left-border colored stripes (`border-l-*`) for status or emphasis — always use colored dots or badges instead.
### 5.3 Lists — choose by data shape
### Lists
| Pattern | When |
|---------|------|
| **Table** | Uniform rows, sortable columns, many items |
| **Card list** (vertical stack) | Mixed content per row, expandable detail |
| **Card grid** | Visual overview, few fields per item |
| `.ss-list` + `.ss-r` | Default. Uniform items; add `.ss-lh` when columns need labels, `.ss-gh` for groups |
| `.ss-tiles` + `.ss-tile` | The user picks by description rather than by name (Skills cards view) |
| `.ss-kv` | Properties of one thing |
| `.ss-setrow` | Settings: label and help on the left, control on the right |
### 5.4 Filters
A row that navigates is `.ss-r link`, and the whole row is the target. Controls inside it (`Checkbox`, `IconButton`, menus) must stop the click from navigating, and need a hit area of 24px or more so a near miss does not open the detail page.
- **Layout**: `flex flex-wrap items-end gap-3`
- **Order**: `[SegmentedControl tabs]` `[Select filters]` `[time range]`
- Keep filters on a single row when possible; they wrap naturally on narrow viewports.
### Status
### 5.5 Empty States
| Pattern | When |
|---------|------|
| `.ss-st` | State of a row or item |
| `.ss-tag` | A label or category (mode, kind, source), neutral unless the label itself is a status |
| `.ss-sev` | Audit severity only |
| `.ss-note` | A message about the whole page or section |
Always use the `<EmptyState>` component. Never write custom empty-state markup inline.
### Numbers
### 5.6 Buttons
One to three numbers go inline: `.ss-cnt` beside a heading, or a sentence in the subtitle. `.ss-counts` is for the Dashboard and Audit overviews only.
### Buttons
| Variant | When |
|---------|------|
| `danger` | Permanent destructive action only (clear log, empty trash, delete forever) |
| `secondary` | Reversible removal (uninstall, remove, restore) |
| `ghost` | Cancel, clear filter, reset |
| `primary` | Positive action (save, sync, install, run) |
| `primary` | The one main action of the page or dialog |
| `secondary` | Everything else, including reversible removals (uninstall, remove) |
| `danger` | Permanent destruction: empty trash, clear log, delete forever |
| `ghost` | Cancel, reset, low-emphasis toolbar actions |
| `link` | Inline action inside text or a row |
### 5.7 Dialogs
One primary per view. A destructive action always goes through `ConfirmDialog`.
### Dialogs
| Component | When |
|-----------|------|
| `ConfirmDialog` | Destructive or irreversible actions (delete, clear, overwrite) |
| `DialogShell` | Forms, multi-step flows, informational modals |
| `ConfirmDialog` | Yes or no, especially destructive |
| `DialogShell` | Forms, multi-step flows, previews. Use `padding="none"` with `.dh` / `.db` / `.df` so header, scrolling body and footer match every other dialog |
### Empty, loading, error
`EmptyState` with an action that fixes the emptiness; `PageSkeleton` while the first query is pending; `.ss-note bad` for a failed query; a toast for the result of an action.
---
## 6. Animation
## 7. Motion
| Context | Value |
|---------|-------|
| Card rotation | Alternating `rotate(±0.15deg)` via `:nth-child(odd/even)` |
| Standalone accent card | Max `rotate(±0.3deg)` |
| Hover transition | `transition-all duration-150` |
| Page entry | `animate-fade-in` (0.2s ease-out) |
| Page entry | `animate-fade-in` |
| Dialog, dropdown | `animate-dialog-in`, `animate-dropdown-in` |
| Hover and press | Built into `.ss-btn`, `.ss-ib`, `.ss-r.link`, `.ss-counts`. Add none |
| Style or mode switch | `html.theme-transitioning`, applied by `ThemeContext` |
Keep animations subtle. They should feel hand-drawn, not bouncy.
Motion confirms an interaction. Nothing animates on its own except the skeleton shimmer and the spinner.
---
## 7. Accessibility
## 8. Accessibility
| Concern | Requirement |
|---------|-------------|
| Focus ring | `focus:ring-2 focus:ring-blue/20` |
| Touch target | Min 44x44px interactive area |
| Color contrast | 4.5:1 minimum (WCAG AA) |
| Icon buttons | `aria-label` required on every icon-only button |
| Focus | The `:focus-visible` outline is built into the `ss-*` controls. Do not remove it; a custom control needs the same outline |
| Target size | 24px minimum (WCAG 2.2 SC 2.5.8). Grow the hit area with `::after` rather than the visual box |
| Contrast | 4.5:1 for text, in all four looks |
| Icon-only buttons | `IconButton` with `label`, or `aria-label` |
| Dialogs | `DialogShell` supplies `role="dialog"`, `aria-modal`, focus trap, Escape and scroll lock. Pass `ariaLabel` |
| Tabs, segments | `aria-current` on the active `.ss-tabs` item; `SegmentedControl` sets `aria-pressed` |
| Form fields | `Input`, `Textarea` and `Select` tie the label to the control. A bare `.ss-inp` needs its own `label` or `aria-label` |
| Hidden checkbox | `sr-only ss-chk-input` directly before `.ss-chk`, so the focus ring lands on the visible box |
---
## 8. Keyboard & Shortcuts UX
## 9. Keyboard
### Standard interactions
| Key | Context | Action |
|-----|---------|--------|
| `Enter` | Search / Install input | Submit form |
| `Escape` | Dialog / Modal | Close |
| `Escape` | Select dropdown | Collapse |
| `Up / Down` | Select dropdown | Navigate options |
| `Space / Enter` | Select dropdown | Select option |
| `Tab / Shift+Tab` | Inside modal | Cycle focus (`useFocusTrap`) |
| `Backspace` | FilterTagInput (empty) | Delete last tag |
### Global shortcuts
Defined in `ui/src/hooks/useGlobalShortcuts.ts`. `SHORTCUT_ENTRIES` feeds the help modal, so adding an entry there is what registers a new shortcut in the UI.
| Key | Action |
|-----|--------|
| `?` | Open keyboard shortcuts modal |
| `/` | Focus search input (if page has one) |
| `g d` | Go to Dashboard |
| `g s` | Go to Skills |
| `g t` | Go to Targets |
| `g l` | Go to Log |
| `r` | Refresh (trigger page refresh action) |
| `?` | Shortcut help |
| `/` | Focus the page's search input |
| `r` | Refresh, when the page provides a handler |
| `g` then `d` `s` `t` `l` `a` `u` | Dashboard, Skills, Targets, Log, Audit, Updates |
| `Mod+S` | Sync, except inside the code editor, where it saves |
### Rules
- Shortcuts only trigger when **no** `<input>` or `<textarea>` is focused.
- Chord shortcuts (`g` then `d`) use a **500ms timeout** reset between keys.
- All shortcut-enabled elements must have the `aria-keyshortcuts` attribute.
- New shortcuts must be registered in `KeyboardShortcutsModal`.
- **Never** override browser-native shortcuts (`Cmd+C`, `Cmd+V`, `Cmd+A`, `Cmd+Z`, etc.).
- Single-key shortcuts do not fire while focus is in an input, textarea, select or contenteditable.
- The `g` chord resets after 500ms.
- Never take a browser shortcut. `Mod+S` is the only modifier combination claimed.
- Dialogs close on Escape. `Select` supports arrows, Enter, Space and Escape.
---
## 9. Anti-Patterns
## 10. Anti-patterns
| Don't | Do instead |
|-------|------------|
| Emojis as status icons | Use colored dots, badges, or semantic icons |
| Stat cards for 1–3 values | Inline summary text |
| Left-border colored stripes (`border-l-*`) | Colored dots or badges — never use left stripes |
| Stripe + badge for same status | Pick one per element |
| Mixed separator opacity (`/20`, `/40`) | Always `border-pencil-light/30` |
| `window.confirm()` | `<ConfirmDialog>` component |
| Custom empty-state markup | `<EmptyState>` component |
The full table is at the end of `../SKILL.md`. The ones that come up most:
- Writing a page with Tailwind colour utilities and legacy token names instead of `ss-*` classes. It renders, but it misses Playful borders and shadows and drifts from every other page.
- `space-y-*` on the page root instead of `.ss-wrap`.
- A Tailwind margin on an element that `.ss-wrap` already spaces. The utility wins over `@layer components` and the gap doubles.
- A hardcoded colour that looks right in the one look you happened to test.
+277
View File
@@ -1,5 +1,282 @@
# Changelog
## [0.21.1] - 2026-09-20
### New Features
#### MCP connections
- **Turn off a global MCP server in one project** — a server in an Agent's global config loads in every project. In project mode, add an entry with the same name and mark it `disabled` to stop it loading in that project only. The Agent keeps the command or URL from its global entry.
```bash
cd my-project
skillshare mcp add company-docs --disabled --target claude --target opencode
skillshare sync mcp
```
```yaml
# .skillshare/config.yaml
mcp:
servers:
company-docs:
disabled: true
targets: [claude, opencode]
```
Works with Claude Code, OpenCode, Kilo Code, and Pi with `pi-mcp-adapter`. OpenCode, Kilo Code and Pi get a lone switch in their project file. Claude Code takes a whole entry from one scope, so Skillshare adds the name to that project's off list in `~/.claude.json`, the one the `/mcp` panel edits; a name you turned off yourself is never claimed or removed. Other clients are refused, because a lone switch would replace the server instead of turning it off. In the dashboard, open it from the project folder, choose **Add server** and pick **Off in this project**. Refs: #286.
- **Kilo Code is an MCP client** — `kilocode` joins the supported clients, in global and project scope. It uses OpenCode's format; Skillshare writes to whichever `kilo.jsonc` or `kilo.json` already exists and creates `kilo.jsonc` when there is none. Kilo ignores a project config that holds an environment reference, so `fromEnv` and `bearerToken` are refused for Kilo in project mode before anything is written. Refs: #287.
- **Claude Code local scope servers are reported** — a server added with `claude mcp add` and no `--scope` wins, whole, over one of the same name in `.mcp.json` or the user scope. In project mode the plan and the dashboard now point out such a server next to the entry it hides, with the command that removes it. The sync is not blocked.
- **Limits of each client are caught before the write** — Claude Code skips the reserved names `workspace`, `claude-in-chrome` and `computer-use`, and reads its own credentials such as `ANTHROPIC_API_KEY` as empty in a remote server's `url` and `headers`; both are now refused for Claude with a message that says what to do. The dashboard's config preview refuses the same things saving would.
#### Dashboard
- **Manual only skills are visible** — a skill with `disable-model-invocation: true` carries a **manual only** tag in the skills list, on its tile and on its detail page, matching the badge the list TUI shows after `M`. Refs: #283.
- **Add field explains each frontmatter field** — the skill editor's **Add field** menu shows what each field does under its name, instead of bare keys such as `context` and `shell`.
- **Agent icons in the MCP import picker** — the Agent dropdown in **Import from a target** shows each Agent's logo. Factory, LM Studio, Kilo Code and Claude Desktop now have their own icons.
### Bug Fixes
- **The MCP page detects Agents that have no MCP file yet** — detection looked only for the MCP file, so a fresh Claude Code install showed as not detected. An Agent's own settings folder now counts. In project mode the page listed every Agent as detected; it now lists those with a project MCP file or a global install.
- **Cline's MCP settings are found again** — Cline moved its settings to `~/.cline/data/settings/`, shared by the VS Code extension, the CLI and the SDK. Skillshare now writes there and honors `CLINE_MCP_SETTINGS_PATH`, `CLINE_DATA_DIR` and `CLINE_DIR`. The old VS Code extension path is still used while it is the only one that exists.
- **An MCP entry owned by a deleted config can be taken over** — an entry managed by a Skillshare config that was later moved or deleted stayed blocked forever as "managed by another Skillshare config". An explicit import or replace now takes it over, and the conflict names the owning file.
- **`--disabled` is refused where it does nothing** — only `mcp add` uses the flag, but the other `mcp` commands and `sync mcp` accepted it and ignored it.
- **A relative `XDG_CONFIG_HOME` is ignored for MCP paths** — as the XDG specification requires, instead of producing a path relative to the current directory.
- **Skill detail and new skill pages** — the file viewer no longer leaves a gap above it when it sticks while scrolling, and the info column beside a long `SKILL.md` stays in view.
### Breaking Changes
- **The `kilocode` skills target moved to `.kilo/skills`** — from `.kilocode/skills`, in both global and project scope, because that is the only location Kilo Code's documentation lists now. Run `skillshare sync` once to write skills to the new location.
## [0.21.0] - 2026-09-19
### New Features
#### MCP connections
- **Define an MCP server once, sync it into each Agent's own config** — a server lives in `config.yaml` (or a separate `mcp.yaml`) as a portable definition, and `sync mcp` writes it in the format each client expects: JSON, JSONC, TOML or YAML, under that client's own key. Nothing is started or proxied; Skillshare only manages the settings.
```bash
skillshare mcp add # guided: URL, command, or pasted JSON
skillshare mcp add docs --url https://example.com/mcp --target claude --target cursor
skillshare mcp import docs --from claude --sync # adopt what an Agent already has
skillshare sync mcp --dry-run # preview every file that would change
skillshare sync mcp
```
Supported clients: Claude Code, Codex, Cursor, VS Code, OpenCode, Grok CLI, Antigravity, Amp, Claude Desktop, Cline, Copilot CLI, Factory, Gemini CLI, Goose, Junie, Kiro, LM Studio, Warp, Windsurf and Pi. Global and project scope are both supported where the client has them. `skillshare mcp` without arguments opens a TUI for browsing, editing and syncing.
- **Secrets stay out of the files** — headers and environment values are written as `{fromEnv: VARIABLE}` references and rendered in each client's own reference syntax. On import, literal tokens and values carrying a URL password, such as database DSNs, are turned into references, and credential-like arguments are flagged.
- **Only entries Skillshare wrote are ever changed** — ownership is tracked per entry. An entry you wrote by hand is left alone even when it matches the source, and stays that way until you `import` it. A managed entry edited in the Agent is reported as a conflict instead of being overwritten, Agent-only fields such as timeouts survive a sync, and previews stay valid while an Agent rewrites unrelated settings in the same file.
- **Backups and restore** — every write backs up the Agent file first, keeping the newest 20 per file.
```bash
skillshare mcp restore BACKUP_ID --dry-run
skillshare mcp restore BACKUP_ID
```
- **Pasted snippets are recognised by shape** — `mcp import --file` and the add wizard pick the client format from the top-level key, so VS Code `servers` and OpenCode `mcp` snippets copied from a provider's docs import without naming a client. TOML still needs `--from`, because Codex and Grok share the format.
- **Pi through a chosen extension** — Pi has no built-in MCP support, so a server targeting Pi names the third-party package that reads the file, `pi-mcp-adapter` or `pi-mcp-extension`. Install one in Pi yourself; Skillshare only writes its configuration.
```bash
skillshare mcp add docs --url https://example.com/mcp --target pi --pi-extension pi-mcp-adapter --no-tui
```
- **`sync --all` includes MCP** — it syncs skills, agents, extras and MCP settings together, and `--json` reports the MCP plan alongside the rest.
#### Plugins
- **Install a complete plugin and choose which tools receive it** — a plugin bundles skills, hooks, MCP settings and scripts that only work together. `plugin` keeps that package intact and installs it through each Agent's own CLI, so native formats and unrelated installations are untouched.
```bash
skillshare plugin add # guided: source, plugin, targets, review
skillshare plugin add owner/repo --target claude --target codex --no-tui
skillshare plugin import review@team --from claude # adopt an existing native installation
skillshare plugin disable review --target codex # save the selection only
skillshare sync plugins --dry-run # then install or remove on sync
skillshare plugin check review
skillshare plugin update review --target claude
```
Install targets: Claude Code, Codex, Cursor, Antigravity Desktop, Antigravity CLI, GitHub Copilot CLI, Pi and OpenCode. Grok Build supports import and removal, with install and trust handled in Grok. Sources can be a local folder, `owner/repo` or an HTTPS Git URL, pinned with `--source-ref`. Plugins are synced with `sync plugins` and are not part of `sync --all`.
#### Dashboard
- **Redesigned in two styles** — the dashboard now comes in **Clean** and **Playful**, each in light and dark, switched from the theme menu. Skills and Agents are separate pages that hold their own install, search, updates and trash, and General, Backup, Log, Health, Extensions and Files are collected into one Settings page. Old routes redirect.
- **MCP page** — one row per server with its Agents as toggles. Add a server from a URL, a command, a pasted snippet or a file, or import what an installed Agent already has. Conflicts explain their cause and offer Import or Replace, backups are grouped by day with a preview before restoring, and **View what each Agent gets** shows exactly what each Agent would receive, including edits you have not saved yet. MCP settings are only served when the dashboard is opened through `localhost` or an IP address.
- **Plugins page** — one row per plugin with its Agents as toggles, the same as MCP. Expanding a row also lists the other Agents the source supports, so ticking one previews an install there. **View files** opens a read-only browser of the local copy Skillshare reviewed.
- **Hubs page** — browse a hub and install from it, or assemble your own index from installed skills, validate it and export it, all at `/hubs`. A draft can be browsed straight away, before it is hosted anywhere.
- **Filter skills and agents by target**, and a **Remote** source filter for skills from GitLab, Gitea, self-hosted and SSH sources, which previously matched no filter. Refs: #278.
- **Config editors explain themselves** — the Files tab and the audit rules editor keep a panel beside the YAML showing what the field under the cursor does and the unsaved changes. Audit rules also get a **Test** tab that runs a rule's regex against pasted lines.
- Dashboard source counts link to their pages, and plugins are counted alongside the other kinds.
#### Audit
- **Findings accepted with `--force` are remembered** — a skill that legitimately quotes attack strings, such as a security scanner or red-team notes, no longer has to be forced on every `update --all`. The accepted findings are recorded for that skill, and later updates treat the same rule matching the same text as acknowledged. Any new finding, or the same rule matching different text, still blocks. Refs: #279.
#### List TUI
- **Press `M` to make a skill manual only** — toggles `disable-model-invocation` in the selected skill's `SKILL.md`, so the skill stays installed and can be invoked by name but is no longer loaded by the model on its own. The detail panel shows a **manual only** badge. For a tracked or installed skill the TUI asks first, because the edit counts as a local change; pressing `M` again restores the file exactly. Refs: #283.
### Bug Fixes
- **`sync --dry-run agents` and `sync -g extras` no longer sync skills** — the resource kind was only recognised as the first argument, so putting a flag before it silently synced skills instead. The kind now matches in any position.
- **A mistake in the `mcp` section no longer breaks every command** — an invalid MCP setting is reported by MCP commands and the config editor, while `sync`, `install`, `list` and the dashboard keep working.
- **Web UI: saving the config keeps flow-style YAML** — a hand-written `targets: [claude, codex]` is no longer expanded into a block list on every save. Indentation is still normalised and comments are preserved.
## [0.20.29] - 2026-09-11
### Bug Fixes
- **`install -p` no longer removes the skills it just installed from `config.yaml`** — a project install driven by `config.yaml` reconciled against the metadata it had read before installing, so a skill that arrived as a plain copy — any source pointing at a subdirectory, which has no `.git` to fall back on — looked absent and its entry was pruned from the declarative list. The install itself reported success and the skill and its metadata landed correctly, but the entry was gone from `config.yaml`, which broke the `install -p && sync` flow for anyone setting the project up from a clean checkout. Metadata is now re-read from disk before reconciling, which also covers project-mode installs made through `search`. Refs: #280.
## [0.20.28] - 2026-09-09
### New Features
- **Visible `skillshare/` project directory** — repositories that treat skills as reviewable content, rather than tool state, can now use a visible `skillshare/` directory instead of the hidden `.skillshare/`.
```bash
skillshare init -p --visible # create skillshare/ instead of .skillshare/
```
Everything lives inside whichever directory is in use: `config.yaml`, `skills/`, `agents/`, `extras/`, and the operational `trash/`, `backups/` and `logs/`. Detection checks `.skillshare/config.yaml` first and `skillshare/config.yaml` second, so existing projects are unaffected and `.skillshare/` wins when both exist. `init -p` without the flag still creates `.skillshare/`. To move an existing project, run `mv .skillshare skillshare` followed by `skillshare sync -p` to repair target symlinks, and update any `sources` paths in `config.yaml` that name `.skillshare/` explicitly. Refs: #256.
### Bug Fixes
- **`.skillignore` matches again when the file uses CRLF line endings** — rules were compiled with a trailing carriage return that could never equal a path segment, so a `.skillignore` saved on Windows silently ignored nothing while `status` still reported its patterns as loaded. Editing patterns was affected the same way: existing entries were not found, adding one duplicated it, and removing one failed. A regression since v0.17.4. Refs: #275.
- **A directory symlink inside a skill no longer discards every file hash** — hashing stopped at the first entry that could not be read as a file and threw away the hashes computed so far, which left installed skills without the metadata used to detect local edits. Directory symlinks are skipped; file symlinks are still hashed, and real failures such as broken links still surface. Refs: #272.
## [0.20.27] - 2026-09-02
### New Features
- **Agents can declare which targets they belong to** — a `targets` list in an agent's frontmatter now restricts that agent to the listed tools, the same way `metadata.targets` works for skills. Agent files are copied verbatim and Claude Code, OpenCode, Cursor and Copilot read different frontmatter fields, so this lets you keep a per-tool variant of the same agent side by side. Agents without the field still sync everywhere; target aliases such as `claude-code` match `claude`. Applies to `sync agents`, the dashboard, `doctor` and the target summary. Refs: #267.
```yaml
# ~/.config/skillshare/agents/reviewer.md
---
targets: [claude]
tools: Read, Write, Bash(git log)
---
# ~/.config/skillshare/agents/reviewer-opencode.md
---
targets: [opencode]
mode: subagent
permission: { read: allow, write: allow, bash: ask }
---
```
### Bug Fixes
- **`update --all` no longer deletes a skill when the audit blocks its update** — when several skills from one repository were updated together, the existing skill directory was removed before the new content was copied in, and an audit block then cleaned up the new content as well, leaving nothing on disk and a stale metadata entry that later updates could not find. Grouped updates now stage the new content in a temporary directory, run the audit there, and only swap it into place once the audit passes, matching what `update <name>` already did. If a skill was already lost this way, `skillshare update <name> --force` reinstalls it. Refs: #271.
- **Batch updates and the web UI follow the branch a skill was installed from** — `update --all` cloned the remote default branch for skills installed with `-b <branch>`, so they were reported stale or downgraded, and `--prune` moved them to trash. The dashboard's check and update did the same, comparing against the remote HEAD instead of the installed branch. All of these now group by repository and branch and fetch from the installed branch. Refs: #268.
- **Windows drive-letter paths install as local skills** — `skillshare install D:\skills\my-skill` failed with `unrecognized source format` because only paths starting with `/`, `~`, `./` or `../` were treated as local. Drive-letter paths (`D: older`, `C:/Users/...`) and backslash-relative paths (`.\skill`) are now recognised in the CLI and the dashboard install page. Refs: #269.
- **Dashboard labels non-GitHub git sources as Remote** — skills installed from Gitea, GitLab, self-hosted or SSH sources showed a **Local** badge because only GitHub metadata types were recognised. Any non-local git source now shows **Remote**, matching `skillshare list`. Tracked repos and GitHub sources keep their existing badges. Refs: #270.
## [0.20.26] - 2026-08-27
### Bug Fixes
- **`update --force` can override the security audit again** — when an update was blocked by an audit finding, the error told you to pass `--force`, but the flag never reached the audit gate. Update stages new content in a temporary directory and had to leave its internal overwrite flag off to keep the gate active, which discarded your `--force` along with it, so a flagged update could not be applied short of `--skip-audit` — which turns scanning off entirely. `--force` now reaches the gate on every update path: regular skills, tracked repos, agents, and the web UI's Force Retry button.
```bash
skillshare update my-skill --force # apply despite audit findings
skillshare update my-skill --skip-audit # skip scanning entirely
```
Audit *scan failures* stay fail-closed regardless of `--force`: accepting findings you have seen is not the same as proceeding when the scanner could not run.
- **`install --json` no longer bypasses the security audit** — `--json` set the internal overwrite flag so installs could run non-interactively, and the audit gate read that same flag, so JSON-mode installs silently accepted content that would have been blocked interactively.
- **Grouped batch updates are covered by the audit gate** — updating several skills from a single repository inherited the same overwrite flag and skipped the block threshold.
- **Web UI: Force Retry only appears where it can help** — a failure such as `failed to remove existing skill: ... permission denied` offered a Force Retry button that retried with force and failed identically, with no hint of what would actually fix it. The button now shows for audit blocks and for pulls the server would retry with force, and is hidden elsewhere.
- **Web UI: update errors no longer quote CLI flags** — messages ending in `Use --force to override or --skip-audit to bypass scanning` were rendered verbatim in the dashboard, where there is no command line to type them into.
### Breaking Changes
- **A `--force` at install time no longer exempts later updates from the audit gate** — `--force` is a per-command decision. A skill installed with `--force` is scanned again on its next `update`, and needs `--force` (or `--skip-audit`) again to apply findings at or above the block threshold.
## [0.20.25] - 2026-08-10
### Bug Fixes
- **Batch updates no longer mark skills under target dot-directories as stale** — skills installed from subdirectories such as `.claude/skills/...` or `.codex/skills/...` were skipped by discovery during batch updates and reported as deleted upstream, which could incorrectly suggest `--prune`. Batch update now resolves the requested subdirectory directly before declaring it missing. Refs: #261.
- **Explicit target dot-directory installs discover their requested content** — commands such as `skillshare install user/repo/.claude` no longer return zero results just because `.claude` is normally excluded from repository-wide discovery. Explicitly requested roots are scanned for both skills and agents, while repository-root scans continue to skip synced target copies.
- **Project commands preserve existing projects when `config.yaml` is missing** — when `.skillshare/` already contains skills or agents but `.skillshare/config.yaml` has disappeared, project-mode commands now stop with recovery guidance instead of silently re-initializing an empty config, dropping target configuration, and leaving stale links. Fresh projects and shared repositories that intentionally gitignore `config.yaml` still initialize automatically.
- **Windows can uninstall nested skills again** — uninstalling a skill stored under a folder no longer passes Windows backslashes into the trash-name validator and fails with `trash name must not contain backslash`. Nested skill names are normalized to slash-separated paths in global and project mode without weakening traversal checks. Refs: #264.
## [0.20.24] - 2026-08-03
### Bug Fixes
- **Gemini CLI and Antigravity are separate targets again** — `gemini` had been folded into `antigravity` as an alias, but the two runtimes read different global skill directories, so one of them was always pointed at the wrong path. Antigravity now resolves to `~/.gemini/config/skills` (global) and `.agents/skills` (project); `gemini` is a target of its own resolving to `~/.gemini/skills` and `.gemini/skills`, with `~/.agents/skills` and `.agents/skills` still scanned as fallbacks. Aliases: `gemini-cli` for Gemini CLI, `antigravity-cli` for Antigravity. Refs: #255.
```bash
skillshare target add gemini # Gemini CLI
skillshare target add antigravity # Antigravity
skillshare sync
```
Antigravity's skill scanner also skips symlinked skill directories entirely — silently on macOS and Linux, and as `Incorrect function` on Windows. The troubleshooting docs now cover this along with its two workarounds: switch the target to `copy` mode, or point Antigravity at your skillshare source directory via its Skill Custom Paths setting.
- **`doctor`'s symlink compatibility hint is deterministic** — the hint chose its example target by iterating a map, so the same config produced a different suggestion on each run, and it could name a target whose runtime handles symlinks fine — telling users to switch something that was not broken. The example is now drawn only from the targets known to skip symlinked skill directories, in a fixed order. The sync docs are also corrected: the hint is printed by `doctor`, not `sync`.
### Breaking Changes
- **`gemini` no longer resolves to the Antigravity target** — configs that used `gemini` (or `gemini-cli`) to reach Antigravity now sync to Gemini CLI's own directory instead. Use `antigravity` for Antigravity. Existing `antigravity` targets change global path from `~/.gemini/skills` to `~/.gemini/config/skills`; run `skillshare sync` after upgrading.
## [0.20.23] - 2026-07-30
### New Features
- **`list --status` filters enabled or disabled entries outside the TUI** — the enabled/disabled filter previously existed only inside the list TUI (`s` key, `status:` search tag), so scripts had to know that `disabled` is omitted for enabled entries and filter the JSON themselves. `--status` combines with the pattern and `--type` using AND semantics, and works in project mode and for agents.
```bash
skillshare list --status disabled
skillshare list --status enabled --json
```
`--status all` is the default and produces output identical to omitting the flag. Refs: #244.
### Bug Fixes
- **Backups no longer copy your source, and old snapshots are pruned automatically** — pre-sync backups followed merge-mode skill symlinks and copied the resolved content, so every snapshot duplicated the source directory, including files kept out of Git but still present on disk such as model weights, `.venv`, and browser profiles. Retention only ran when `backup --cleanup` was invoked by hand, so nothing removed the accumulating snapshots; backup directories could reach hundreds of gigabytes until `sync` failed with `no space left on device`. Snapshots now capture only local target content, and the existing retention policy (10 snapshots, 30 days, 500 MB) runs after every automatic backup. Refs: #252.
- **`backup --cleanup` keeps the newest snapshot when it exceeds the size cap** — a single snapshot larger than the 500 MB cap previously removed every backup including the most recent one, leaving no restore point at all.
- **Backup previews and cleanup now agree** — `backup --cleanup --dry-run` no longer reports that it will delete an oversized newest snapshot when the actual cleanup keeps it. Retention also counts only snapshots that remain after cleanup, avoiding unnecessary deletion of older snapshots that still fit.
- **Failed backups are discarded instead of appearing as restore points** — if a file cannot be copied, the partial snapshot is removed and cannot consume the newest retention slot. Automatic cleanup failures are now shown as warnings instead of being silently ignored.
- **Targets holding only symlinks no longer produce empty snapshots** — an empty restore point consumed a retention slot and evicted older snapshots that did have content.
- **`doctor` handles linked target directories correctly** — in project symlink mode the valid link `../.skillshare/skills` was reported as pointing to the wrong location, because relative links were resolved against the current working directory instead of the link's parent. Symlink-mode targets no longer report every source skill as a duplicate target-local copy, while copy-mode targets reached through a symlink still report real duplicate copies. Refs: #251.
### Breaking Changes
- **Backups capture local target content only** — merge-mode skill symlinks are skipped, so restoring a target recovers its local skills and then needs `skillshare sync` to recreate symlinks for synced skills. Copy-mode targets are unaffected because they hold real files. The documented backup location is also corrected to `~/.local/share/skillshare/backups/` (the XDG data directory), which had been listed under `~/.config` in some places.
## [0.20.22] - 2026-07-21
### New Features
- **Grok CLI target** — added xAI's Grok CLI as a built-in target, syncing skills to `~/.grok/skills` (global) and `.grok/skills` (project), with legacy fallback to `~/.agents/skills`. Aliases: `xai`, `grok-cli`.
```bash
skillshare target add grok
skillshare sync
```
### Bug Fixes
- **`collect --json` no longer forces overwrites** — JSON mode previously implied `--force`, silently overwriting existing skills and agents in the source. It now still skips confirmation prompts but keeps the overwrite guard, so existing resources are preserved unless `--force` is passed.
- **`uninstall --json` no longer bypasses the uncommitted-changes guard** — JSON mode previously implied `--force`, removing tracked skills that had uncommitted changes without warning. Dirty repositories now return a structured error unless `--force` is passed.
- **Batch uninstall explains all-dirty failures** — uninstalling multiple tracked skills where every repository has uncommitted changes now reports why nothing was removed instead of failing without explanation.
- **Editing a skill's source no longer rewrites the source directory's Git remote** — in the dashboard, changing a nested skill's source URL could overwrite the `origin` of the skills source directory itself when that directory is a Git repository (for example, backed by Git Sync). Source edits now only affect a tracked skill's own repository.
- **Freshly installed skills show their correct source instead of "Local"** — after installing a skill from the dashboard, the resource now immediately shows its GitHub source and type, rather than appearing as a local skill with an empty source until the server was restarted.
## [0.20.21] - 2026-06-29
### Bug Fixes
- **Copy-mode sync respects file ignore patterns** — `sync` in `copy` mode now skips configured `ignore:` artifacts, plus default `.DS_Store`, `.git/`, and `__pycache__/` files, across CLI sync, diff, and dashboard sync/diff paths. This prevents ignored cache and build artifacts from being copied into targets or changing copy-mode checksums.
- **Global sync uses the default skills source when source is omitted** — global configs that only define targets now work with `skillshare sync --global`, using the default `~/.config/skillshare/skills` source instead of failing with `source path is empty`. Refs: #238.
## [0.20.20] - 2026-06-19
### Bug Fixes
+21 -1
View File
@@ -1,4 +1,4 @@
.PHONY: help build build-meta build-windows run test test-unit test-int test-docker test-docker-online test-redteam test-redteam-signal test-redteam-rules-signal playground playground-down devc devc-up devc-down devc-restart devc-reset devc-status dev-docker dev-docker-down docker-build docker-build-multiarch lint fmt fmt-check check install clean ui-install ui-build ui-dev build-all
.PHONY: help build build-meta build-windows run test test-unit test-int test-docker test-docker-online test-redteam test-redteam-signal test-redteam-rules-signal playground playground-down devc devc-up devc-down devc-restart devc-reset devc-status dev-docker dev-docker-down docker-build docker-build-multiarch lint fmt fmt-check check install clean ui-install ui-build ui-dev build-all verify verify-shell verify-down verify-status verify-reset
help:
@echo "Common tasks:"
@@ -20,6 +20,11 @@ help:
@echo " make devc-restart # restart devcontainer"
@echo " make devc-reset # full reset (remove volumes)"
@echo " make devc-status # show devcontainer status"
@echo " make verify # host verify env: real AI CLIs, throwaway config"
@echo " make verify-shell # enter the verify env shell"
@echo " make verify-down # stop the verify dashboard"
@echo " make verify-status # show verify env paths and state"
@echo " make verify-reset # delete the throwaway HOME"
@echo " make lint # go vet"
@echo " make fmt # format Go files"
@echo " make check # fmt-check + lint + test"
@@ -98,6 +103,21 @@ devc-reset:
devc-status:
./scripts/devc.sh status
verify:
./scripts/verify.sh up
verify-shell:
./scripts/verify.sh shell
verify-down:
./scripts/verify.sh down
verify-status:
./scripts/verify.sh status
verify-reset:
./scripts/verify.sh reset
dev-docker:
docker compose -f docker-compose.sandbox.yml --profile dev watch
+59 -4
View File
@@ -40,7 +40,7 @@
</p>
> [!NOTE]
> **Latest**: [v0.20.0](https://github.com/runkids/skillshare/releases/tag/v0.20.0) — choose what `commit`/`push`/`pull` version with **git_root scope** (skills, agents, extras, or all together in one repo); extras **extension transforms** convert Markdown to native formats (Gemini TOML commands, Codex TOML agents) during sync. [All releases →](https://github.com/runkids/skillshare/releases)
> **Latest**: [v0.21.0](https://github.com/runkids/skillshare/releases/tag/v0.21.0) — define **MCP connections** once and sync them into each Agent's native config; install and sync **complete plugins** across Claude, Codex, Cursor and more; and a **redesigned web dashboard** with Clean and Playful styles. [All releases →](https://github.com/runkids/skillshare/releases)
## Why skillshare
@@ -52,6 +52,8 @@ skillshare fixes this:
- **One source, every agent** — sync to Claude, Cursor, Codex & 60+ 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)
- **MCP connections** — define a server once, sync it into each Agent's own config format with [`sync mcp`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp)
- **Complete plugins** — keep a plugin's skills, hooks and MCP settings together and choose which tools receive it with [`plugin`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-plugins)
- **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
- **Team-ready** — project skills in `.skillshare/`, org-wide skills via tracked repos
@@ -186,17 +188,40 @@ skillshare init -p && skillshare sync
```bash
skillshare sync agents # sync agents only
skillshare sync --all # sync skills + agents + extras together
skillshare sync --all # sync skills + agents + extras + MCP together
```
**Extras** —manage rules, commands, prompts & more
```bash
skillshare extras init rules # create a "rules" extra
skillshare sync --all # sync skills + extras together
skillshare sync --all # sync skills + agents + extras + MCP together
skillshare extras collect rules # collect local files back to source
```
**MCP connections** —configure once for Claude Code, Codex, Cursor, VS Code, OpenCode and more
```bash
skillshare mcp add # guided URL or JSON setup
skillshare sync mcp --dry-run # preview native configuration changes
skillshare sync mcp # apply connection settings
```
Keep definitions in `config.yaml` or reference a separate `mcp.yaml`.
See [MCP setup](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp)
for examples, environment references and importing existing connections.
**Plugins** —install a complete plugin and pick which tools receive it
```bash
skillshare plugin add # guided: source, plugin, targets, review
skillshare plugin add owner/repo --target claude --target codex --no-tui
skillshare sync plugins --dry-run # plugins sync separately from sync --all
```
Existing native installations can be adopted with `plugin import`.
See [Manage plugins across tools](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-plugins).
**Shell completion** —tab-complete commands, flags, and subcommands
```bash
@@ -289,6 +314,36 @@ Thanks to everyone who helped shape skillshare.
<a href="https://github.com/rhysmcneill"><img src="https://github.com/rhysmcneill.png" width="50" style="border-radius:50%" alt="rhysmcneill"></a>
<a href="https://github.com/druellan"><img src="https://github.com/druellan.png" width="50" style="border-radius:50%" alt="druellan"></a>
<a href="https://github.com/12britz"><img src="https://github.com/12britz.png" width="50" style="border-radius:50%" alt="12britz"></a>
<a href="https://github.com/askpatrickw"><img src="https://github.com/askpatrickw.png" width="50" style="border-radius:50%" alt="askpatrickw"></a>
<a href="https://github.com/Almost42"><img src="https://github.com/Almost42.png" width="50" style="border-radius:50%" alt="Almost42"></a>
<a href="https://github.com/Brett-Best"><img src="https://github.com/Brett-Best.png" width="50" style="border-radius:50%" alt="Brett-Best"></a>
<a href="https://github.com/isCopyman"><img src="https://github.com/isCopyman.png" width="50" style="border-radius:50%" alt="isCopyman"></a>
<a href="https://github.com/svob"><img src="https://github.com/svob.png" width="50" style="border-radius:50%" alt="svob"></a>
<a href="https://github.com/michal-grzelak"><img src="https://github.com/michal-grzelak.png" width="50" style="border-radius:50%" alt="michal-grzelak"></a>
<a href="https://github.com/shikbupt"><img src="https://github.com/shikbupt.png" width="50" style="border-radius:50%" alt="shikbupt"></a>
<a href="https://github.com/LeoYeAI"><img src="https://github.com/LeoYeAI.png" width="50" style="border-radius:50%" alt="LeoYeAI"></a>
<a href="https://github.com/TIR44"><img src="https://github.com/TIR44.png" width="50" style="border-radius:50%" alt="TIR44"></a>
<a href="https://github.com/Ajaymamtora"><img src="https://github.com/Ajaymamtora.png" width="50" style="border-radius:50%" alt="Ajaymamtora"></a>
<a href="https://github.com/vishaldialpad"><img src="https://github.com/vishaldialpad.png" width="50" style="border-radius:50%" alt="vishaldialpad"></a>
<a href="https://github.com/kankan0829"><img src="https://github.com/kankan0829.png" width="50" style="border-radius:50%" alt="kankan0829"></a>
<a href="https://github.com/dnabb"><img src="https://github.com/dnabb.png" width="50" style="border-radius:50%" alt="dnabb"></a>
<a href="https://github.com/thinhngotony"><img src="https://github.com/thinhngotony.png" width="50" style="border-radius:50%" alt="thinhngotony"></a>
<a href="https://github.com/skaurus"><img src="https://github.com/skaurus.png" width="50" style="border-radius:50%" alt="skaurus"></a>
<a href="https://github.com/jamesbraza"><img src="https://github.com/jamesbraza.png" width="50" style="border-radius:50%" alt="jamesbraza"></a>
<a href="https://github.com/2BAB"><img src="https://github.com/2BAB.png" width="50" style="border-radius:50%" alt="2BAB"></a>
<a href="https://github.com/zdlldz"><img src="https://github.com/zdlldz.png" width="50" style="border-radius:50%" alt="zdlldz"></a>
<a href="https://github.com/elstiaan"><img src="https://github.com/elstiaan.png" width="50" style="border-radius:50%" alt="elstiaan"></a>
<a href="https://github.com/EriaWalker"><img src="https://github.com/EriaWalker.png" width="50" style="border-radius:50%" alt="EriaWalker"></a>
<a href="https://github.com/FaintFlower"><img src="https://github.com/FaintFlower.png" width="50" style="border-radius:50%" alt="FaintFlower"></a>
<a href="https://github.com/yantinglin21"><img src="https://github.com/yantinglin21.png" width="50" style="border-radius:50%" alt="yantinglin21"></a>
<a href="https://github.com/chung1912"><img src="https://github.com/chung1912.png" width="50" style="border-radius:50%" alt="chung1912"></a>
<a href="https://github.com/r-fynn"><img src="https://github.com/r-fynn.png" width="50" style="border-radius:50%" alt="r-fynn"></a>
<a href="https://github.com/cescox"><img src="https://github.com/cescox.png" width="50" style="border-radius:50%" alt="cescox"></a>
<a href="https://github.com/hhdebb"><img src="https://github.com/hhdebb.png" width="50" style="border-radius:50%" alt="hhdebb"></a>
<a href="https://github.com/Snurppa"><img src="https://github.com/Snurppa.png" width="50" style="border-radius:50%" alt="Snurppa"></a>
<a href="https://github.com/s0undt3ch"><img src="https://github.com/s0undt3ch.png" width="50" style="border-radius:50%" alt="s0undt3ch"></a>
<a href="https://github.com/danscheer"><img src="https://github.com/danscheer.png" width="50" style="border-radius:50%" alt="danscheer"></a>
<a href="https://github.com/7zq12lvm-b"><img src="https://github.com/7zq12lvm-b.png" width="50" style="border-radius:50%" alt="7zq12lvm-b"></a>
---
@@ -296,7 +351,7 @@ If you find skillshare useful, consider giving it a ⭐
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=runkids/skillshare&type=date&legend=top-left)](https://www.star-history.com/#runkids/skillshare&type=date&legend=top-left)
[![Star History Chart](https://star-history.dera.page/svg?repos=runkids/skillshare&type=date&legend=top-left)](https://star-history.dera.page/#runkids/skillshare&type=date&legend=top-left)
---
+136
View File
@@ -0,0 +1,136 @@
# Hub Builder E2E Runbook
Verify author drafts, portable export, and installation by a separate recipient.
**Origin**: Hub builder — skills-only authoring without hand-editing JSON.
## Scope
- Import, save, reload, optimistic revision checks, and local-source export blockers.
- Preserve extension fields and duplicate display names.
- Export a v1 index without author paths; search and install it in another ssenv.
- The recipient installation downloads the public built-in skill from GitHub.
## Environment
Run inside the devcontainer in a fresh `ssenv` created with `--init`.
When invoking mdproof from an active ssenv, unset inherited `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_STATE_HOME`, `XDG_CACHE_HOME`, and `SKILLSHARE_CONFIG` for mdproof so its per-runbook HOME isolation also controls configuration.
The test creates and deletes its own recipient environment and stops its own API server.
It does not publish a Hub or modify the normal development configuration.
## Steps
### 1. Author, export, and consume a Hub
```bash
python3 - <<'PY'
import json, os, pathlib, signal, socket, subprocess, time, urllib.request, urllib.error
home = pathlib.Path.home()
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
base = f'http://127.0.0.1:{port}/api/hub/drafts'
log = open(home / 'hub-builder-server.log', 'w')
server = subprocess.Popen(['ss', 'ui', '-g', '--no-open', '--port', str(port)], stdout=log, stderr=log, start_new_session=True)
recipient = 'hub-recipient-' + str(os.getpid())
recipient_created = False
def request(method, suffix='', data=None, status=200):
body = None if data is None else json.dumps(data).encode()
req = urllib.request.Request(base + suffix, data=body, method=method, headers={'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(req) as response:
assert response.status == status
return json.load(response)
except urllib.error.HTTPError as error:
assert error.code == status, (error.code, error.read().decode())
return None
try:
for attempt in range(120):
try:
request('GET')
break
except urllib.error.URLError:
if server.poll() is not None:
raise RuntimeError('API server exited; inspect hub-builder-server.log')
time.sleep(0.25)
else:
raise RuntimeError('API server did not start')
source = 'github.com/runkids/skillshare/skills/skillshare'
imported = request('POST', '/import', {
'schemaVersion': 1, 'sourcePath': str(home / 'author-only'), 'extension': {'kept': True},
'skills': [
{'name': 'Shared skill', 'source': source, 'futureField': 42},
{'name': 'Shared skill', 'source': 'local/notes'}
]
})
draft = imported['draft']
assert len(draft['entries']) == 2
assert draft['entries'][0]['id'] != draft['entries'][1]['id']
path = '/' + draft['id']
assert any(p['code'] == 'local_source' for p in imported['problems'])
request('POST', path + '/export', {'revision': draft['revision']}, 400)
old = json.loads(json.dumps(draft))
draft['entries'] = [draft['entries'][0]]
saved = request('PUT', path, draft)
request('PUT', path, old, 409)
restored = request('GET', path)
assert restored['draft'] == saved['draft']
exported = request('POST', path + '/export', {'revision': saved['draft']['revision']})
assert exported['schemaVersion'] == 1 and 'sourcePath' not in exported
assert exported['extension']['kept'] and exported['skills'][0]['futureField'] == 42
assert 'revision' not in exported and 'entries' not in exported
print('PASS: drafts, blockers, revisions, extension fields, and portable export')
subprocess.run(['ssenv', 'create', recipient], check=True)
recipient_created = True
subprocess.run(['ssenv', 'enter', recipient, '--', 'ss', 'init', '-g', '--all-targets', '--no-git', '--no-skill'], check=True)
payload = json.dumps(exported)
consumer = r'''
import json, pathlib, subprocess, sys
path = pathlib.Path.home() / 'skillshare-hub.json'
path.write_text(sys.argv[1])
rows = json.loads(subprocess.check_output(['ss', 'search', '--hub', str(path), '--json']))
assert len(rows) == 1 and rows[0]['Name'] == 'Shared skill'
subprocess.run(['ss', 'install', rows[0]['Source'], '--name', 'hub-builder-received', '-g'], check=True)
assert (pathlib.Path.home() / '.config/skillshare/skills/hub-builder-received/SKILL.md').is_file()
print('PASS: separate recipient searched and installed exported source')
'''
subprocess.run(['ssenv', 'enter', recipient, '--', 'python3', '-c', consumer, payload], check=True)
request('DELETE', path + '?revision=' + saved['draft']['revision'])
request('GET', path, status=404)
print('PASS: draft deleted without removing installed skills')
finally:
os.killpg(server.pid, signal.SIGTERM)
server.wait(timeout=10)
log.close()
if recipient_created:
subprocess.run(['ssenv', 'delete', recipient, '--force'], check=True)
PY
```
Expected:
- exit_code: 0
- PASS: drafts, blockers, revisions, extension fields, and portable export
- PASS: separate recipient searched and installed exported source
- PASS: draft deleted without removing installed skills
## Browser Verification
Against an isolated author dashboard:
1. Open **Skills → My Hubs**, create a draft, select both a local skill and a remote skill.
2. Save; the local entry remains visible and export is blocked.
3. Edit a field and navigate away; cancel the discard dialog and confirm edits remain.
4. Remove the local entry, save, download, and inspect `skillshare-hub.json`.
5. Reload the page and reopen the saved draft.
6. Open the same draft in another tab; save there, then verify an older save gets a conflict without discarding edits.
7. Import an exported index; confirm custom fields and optional selectors survive.
8. Confirm the delete dialog can be cancelled, then delete the test draft.
## Pass Criteria
The automated step passes, and browser verification confirms editing, navigation protection, export, and deletion.
+235
View File
@@ -0,0 +1,235 @@
# CLI E2E Runbook: Portable MCP Configuration
## Scope
Verify inline and external declarations, global/project destinations, preview,
idempotence, removal, import/adoption, conflict protection and entry restoration.
No server is launched and all endpoints are inert example URLs.
## Environment
Run inside the devcontainer with a fresh ssenv HOME. Each step creates its own
config directory under the isolated HOME. Use the newly built `ss` binary.
Do not run these steps against a real Agent configuration.
## Steps
### Step 1: Inline lifecycle with preview and removal
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-inline.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
printf 'targets: {}\n' > "$SKILLSHARE_CONFIG"
ss mcp add e2e-inline --url https://example.com/mcp --target claude -g >/dev/null
ss sync mcp --dry-run --json -g | jq -e '.changes[0].action == "add"' >/dev/null
ss sync mcp --json -g > "$MCP_CASE/applied.json"
jq -e '.applied | length == 1' "$MCP_CASE/applied.json" >/dev/null
ss sync mcp --json -g | jq -e '.applied == [] and .plan.changes[0].action == "unchanged"' >/dev/null
ss mcp remove e2e-inline --sync -g >/dev/null
ss mcp list --json -g
```
Expected:
- exit_code: 0
- jq: .changes == []
- jq: .blocked == false
### Step 2: External source edits and missing-file protection
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-external.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
printf 'sources:\n mcp: ./mcp.yaml\nmcp:\n targets: [claude]\n' > "$SKILLSHARE_CONFIG"
printf 'servers: {}\n' > "$MCP_CASE/mcp.yaml"
cp "$SKILLSHARE_CONFIG" "$MCP_CASE/config.before"
ss mcp add e2e-external --url https://example.com/external --sync -g >/dev/null
cmp "$SKILLSHARE_CONFIG" "$MCP_CASE/config.before"
cp "$HOME/.claude.json" "$MCP_CASE/native.before"
mv "$MCP_CASE/mcp.yaml" "$MCP_CASE/mcp.saved"
if ss sync mcp -g > "$MCP_CASE/error" 2>&1; then exit 1; fi
cmp "$HOME/.claude.json" "$MCP_CASE/native.before"
mv "$MCP_CASE/mcp.saved" "$MCP_CASE/mcp.yaml"
ss mcp list --json -g
```
Expected:
- exit_code: 0
- jq: .blocked == false
- jq: .changes[0].action == "unchanged"
### Step 3: Import refusal, explicit replace, save-only and later drift conflict
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-import.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
export CLAUDE_CONFIG_DIR="$MCP_CASE/client"
mkdir -p "$CLAUDE_CONFIG_DIR"
printf 'targets: {}\n' > "$SKILLSHARE_CONFIG"
printf '{"mcpServers":{"imported":{"command":"example-mcp","env":{"API_TOKEN":"literal-secret"}}},"personal":true}\n' > "$CLAUDE_CONFIG_DIR/.claude.json"
cp "$CLAUDE_CONFIG_DIR/.claude.json" "$MCP_CASE/before"
if ss mcp import imported --from claude --target claude -g > "$MCP_CASE/refused" 2>&1; then exit 1; fi
cmp "$CLAUDE_CONFIG_DIR/.claude.json" "$MCP_CASE/before"
ss mcp import imported --from claude --target claude --replace -g >/dev/null
cmp "$CLAUDE_CONFIG_DIR/.claude.json" "$MCP_CASE/before"
ss sync mcp -g >/dev/null
sed -i 's/example-mcp/changed-mcp/' "$CLAUDE_CONFIG_DIR/.claude.json"
if ss sync mcp -g > "$MCP_CASE/error" 2>&1; then exit 1; fi
ss mcp list --json -g
```
Expected:
- exit_code: 0
- jq: .blocked == true
- jq: .changes[0].action == "conflict"
### Step 4: Project native destinations and restore
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-project.XXXXXX")
mkdir -p "$MCP_CASE/.skillshare"
printf 'targets: []\n' > "$MCP_CASE/.skillshare/config.yaml"
cd "$MCP_CASE"
ss mcp add project-docs --url https://example.com/project --target claude --target codex --sync -p >/dev/null
test -f .mcp.json
test -f .codex/config.toml
ss mcp remove project-docs --sync --json -p > removal.json
MCP_BACKUP=$(jq -r '.backupIds[0]' removal.json)
ss mcp restore "$MCP_BACKUP" --dry-run --json -p | jq -e '.blocked == false' >/dev/null
ss mcp restore "$MCP_BACKUP" --json -p
```
Expected:
- exit_code: 0
- jq: .applied | length == 1
- jq: .plan.changes[0].action == "restore"
### Step 5: OpenCode, Grok and Antigravity project sync
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-extra-clients.XXXXXX")
mkdir -p "$MCP_CASE/.skillshare"
printf 'targets: []\n' > "$MCP_CASE/.skillshare/config.yaml"
cd "$MCP_CASE"
printf '{\n// keep\n"model":"example"\n}\n' > opencode.jsonc
ss mcp add company-docs --url https://example.com/mcp --target opencode --target grok --target antigravity --sync -p >/dev/null
test ! -f opencode.json
grep -q '// keep' opencode.jsonc
grep -q 'remote' opencode.jsonc
grep -q 'mcp_servers.company-docs' .grok/config.toml
jq -e '.mcpServers["company-docs"].serverUrl == "https://example.com/mcp"' .agents/mcp_config.json >/dev/null
ss mcp remove company-docs --sync --json -p > removal.json
MCP_BACKUP=$(jq -r '.backupIds[0]' removal.json)
ss mcp restore "$MCP_BACKUP" --json -p
```
Expected:
- exit_code: 0
- jq: .applied | length == 1
- jq: .plan.changes[0].action == "restore"
### Step 6: Agent-specific fields survive and a pulled change converges
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-converge.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
export CODEX_HOME="$MCP_CASE/codex"
mkdir -p "$CODEX_HOME"
printf 'targets: {}\n' > "$SKILLSHARE_CONFIG"
printf '[mcp_servers.docs]\nurl = "https://example.com/mcp"\nstartup_timeout_sec = 30\n' > "$CODEX_HOME/config.toml"
ss mcp import docs --from codex --target codex --sync -g >/dev/null
ss mcp add docs --url https://changed.example/mcp --target codex --replace --sync -g >/dev/null
grep -q 'startup_timeout_sec = 30' "$CODEX_HOME/config.toml"
sed -i 's/changed.example/pulled.example/' "$SKILLSHARE_CONFIG" "$CODEX_HOME/config.toml"
ss mcp list --json -g
```
Expected:
- exit_code: 0
- jq: .blocked == false
- jq: .changes[0].action == "unchanged"
### Step 7: Expanded project clients and Goose YAML import
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-expanded.XXXXXX")
mkdir -p "$MCP_CASE/.skillshare"
printf 'targets: []\n' > "$MCP_CASE/.skillshare/config.yaml"
cd "$MCP_CASE"
ss mcp add browser --target amp --target copilot --target factory --target gemini --target junie --target kiro --target warp --sync -p -- npx -y @playwright/mcp@latest >/dev/null
jq -e '."amp.mcpServers".browser.command == "npx"' .amp/settings.json >/dev/null
jq -e '.mcpServers.browser.type == "local" and .mcpServers.browser.tools == ["*"]' .github/mcp.json >/dev/null
ss sync mcp --json -p | jq -e '.applied == [] and (.plan.changes | length == 7)' >/dev/null
ss mcp add remote --url https://example.com/mcp --target gemini --sync -p >/dev/null
jq -e '.mcpServers.remote.httpUrl == "https://example.com/mcp" and .mcpServers.remote.url == null' .gemini/settings.json >/dev/null
printf 'extensions:\n imported:\n type: stdio\n name: imported\n enabled: true\n cmd: echo\n args: [ready]\n' > goose.yaml
ss mcp import imported --from goose --file goose.yaml --target amp --sync -p >/dev/null
jq -e '."amp.mcpServers".imported.command == "echo"' .amp/settings.json >/dev/null
ss mcp list --json -p
```
Expected:
- exit_code: 0
- jq: .blocked == false
- jq: .changes | length == 9
### Step 8: Scripted editing and TUI opt-out
```bash
set -eu
MCP_CASE=$(mktemp -d "$HOME/mcp-edit.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
printf 'targets: {}\n' > "$SKILLSHARE_CONFIG"
ss mcp add editable --url https://example.com/mcp --target claude --no-tui -g >/dev/null
ss mcp edit editable --url https://updated.example/mcp --no-tui -g >/dev/null
grep -q 'updated.example' "$SKILLSHARE_CONFIG"
ss mcp edit editable --url https://preview.example/mcp --dry-run --json -g >/dev/null
! grep -q 'preview.example' "$SKILLSHARE_CONFIG"
ss mcp edit editable --no-tui -g -- echo ready >/dev/null
! grep -q 'url:' "$SKILLSHARE_CONFIG"
ss mcp --no-tui -g >/dev/null
ss mcp --json -g
```
Expected:
- exit_code: 0
- jq: .blocked == false
- jq: .changes[0].name == "editable"
## Pass Criteria
All eight steps pass. Core Go tests additionally cover multi-file recovery,
stale revisions, Agent-specific fields, credential references and foreign ownership.
TUI model tests cover search shortcuts, hidden credentials, edit cancellation and
batch import cancellation. In a real terminal, also verify `mcp` search/detail,
edit and remove previews, multi-selection import, and the client/backup picker.
### Pi extension selection and output
Inside a fresh ssenv HOME (do not install or launch either Pi extension):
```bash
set -eu
PI_CASE=$(mktemp -d "$HOME/mcp-pi.XXXXXX")
export SKILLSHARE_CONFIG="$PI_CASE/config.yaml"
printf 'targets: {}\n' > "$SKILLSHARE_CONFIG"
ss mcp add pi-docs --target pi --pi-extension pi-mcp-extension --url https://example.com/mcp --no-tui -g
ss sync mcp --dry-run --json -g | jq -e '.changes[] | select(.target == "pi" and .action == "add")'
ss sync mcp -g
jq -e '.mcpServers["pi-docs"].transport == "streamable-http"' "$HOME/.pi/agent/mcp.json"
ss sync mcp --dry-run --json -g | jq -e '.changes[] | select(.target == "pi" and .action == "unchanged")'
ss mcp edit pi-docs --pi-extension pi-mcp-adapter --no-tui -g
ss sync mcp -g
jq -e '.mcpServers["pi-docs"] | has("transport") | not' "$HOME/.pi/agent/mcp.json"
ss mcp remove pi-docs --sync --no-tui -g
```
**Expected:** explicit extension choice is saved, extension output includes transport,
adapter output omits it, the second sync is unchanged, and removal affects only
the managed entry. No MCP server or Pi package is installed or executed.
+119
View File
@@ -0,0 +1,119 @@
# CLI E2E Runbook: Native plugin lifecycle
Validate complete plugin management and sync selection without touching real user installs.
**Origin**: Plugin support — shared CLI/TUI/UI service and native adapters.
## Scope
- Source discovery, preview cancellation, stale preview rejection, partial failure/retry.
- Claude and Codex native install, exclusion, reinstallation, removal.
- Claude native update and project-scoped install/removal.
- Native enabled state is independent of Skillshare sync selection.
## Environment
Run in the devcontainer. The Go fixtures create isolated HOME, XDG, CODEX_HOME,
and CLAUDE_CONFIG_DIR directories and remove them through `t.TempDir` cleanup.
They contain only a greeting skill, with no hooks or MCP servers.
The optional native suite requires Claude Code 2.1.276 and Codex CLI 0.154.0 on
PATH. For local validation these may be installed under
`/tmp/skillshare-plugin-native-tools`, not globally. It deliberately skips unless
`SKILLSHARE_PLUGIN_NATIVE_E2E=1` is set; a skipped native suite is not a pass.
## Steps
### 1. Core contracts and CLI/API routing
```bash
cd /workspace
go test ./internal/plugin ./cmd/skillshare ./internal/server -run 'TestPluginOptions|TestPluginAPI|TestSyncSelection|TestDiscoverPreserves|TestNativeInventory|TestPreviewCancel|TestProjectCodex' -count=1
```
**Expected**:
- Exit code 0.
- All three packages pass.
### 2. Real native lifecycle
```bash
cd /workspace
export PATH=/tmp/skillshare-plugin-native-tools/node_modules/.bin:$PATH
codex --version
claude --version
SKILLSHARE_PLUGIN_NATIVE_E2E=1 go test ./internal/plugin -run TestPluginNativeLifecycle -count=1 -v
```
**Expected**:
- Exit code 0.
- `--- PASS: TestPluginNativeLifecycle`
- No changes outside the tests' temporary homes and fixture directories.
### 3. Frontend contracts
```bash
cd /workspace/ui
pnpm exec vitest run src/pages/PluginsPage.test.tsx src/i18n/i18n.test.ts
```
**Expected**:
- Exit code 0.
- Sync checkbox remains independent of native enabled state.
- Applying sync requires a preview; partial results stay visible.
### 4. Additional target lifecycle
```bash
cd /workspace
go test ./internal/plugin -run 'TestAdditionalPlugin|TestLocalPlugin|TestAntigravity|TestOpenCode|TestPiFiltered' -count=1
PATH=/tmp/skillshare-plugin-extra-tools/node_modules/.bin:$PATH SKILLSHARE_PLUGIN_EXTRA_E2E=1 go test ./internal/plugin -run TestAdditionalNativeLifecycle -count=1 -v
cd ui
pnpm exec vitest run src/components/plugins/PluginAddDialog.test.tsx
```
**Expected**:
- Whole Cursor/Antigravity bundles survive add/update/reselection; local edits are preserved.
- Antigravity project sync does not touch global paths; `agy` alias resolves correctly.
- Pi 0.85.1 real install/remove normalizes native relative source paths.
- OpenCode 1.18.31 registration lifecycle preserves unrelated JSONC entries/comments.
- OpenCode v2 is fixture-tested only; no claim of tested v2 runtime loading.
- UI lists all six targets, with no Gemini CLI target; project restrictions apply.
- Native runs use temporary HOME/XDG/PI_CODING_AGENT_DIR; no model calls.
## Pass Criteria
All steps pass, including the opt-in native test (not skipped). Installing source
files is not evidence that an Agent has loaded a skill or trusted a hook; those
runtime activation claims are outside this test.
### 5. Source compatibility and new native target
```bash
cd /workspace
go test ./internal/plugin -run 'TestSource|TestUnsafe|TestManifest|TestBrokenCatalog|TestExplicitOpenCode|TestOpenCodeProject|TestNativePackage|TestFailedUpdate|TestDroidPluginTargetNotSupported' -count=1
PATH=/tmp/skillshare-plugin-clients/node_modules/.bin:$PATH SKILLSHARE_PLUGIN_EXPANDED_E2E=1 go test ./internal/plugin -run TestExpandedNativeLifecycle -count=1 -v
```
**Expected**:
- Safe internal file/directory links survive snapshots; unsafe links are rejected.
- Multiple catalogs and per-target metadata preserve valid formats.
- Copilot CLI 1.0.86 completes add, deselect/sync, reselect/sync, update, and removal
in temporary HOME. A skipped native test is not a pass.
- Antigravity CLI uses `agy`, separate from the desktop alias. Native 1.2.6
install/list/remove was checked separately with isolated HOME/XDG directories.
- Kimi/Hermes/Devin remain discovery-only. Grok install/update requires native trust.
- Factory Droid is not offered as a plugin target.
- OpenCode project imported update never runs a global native command.
- A failed native update restores the previous managed source snapshot.
### 6. Dashboard compatibility
```bash
cd /workspace/ui
pnpm exec vitest run src/components/plugins/PluginAddDialog.test.tsx src/pages/PluginsPage.test.tsx src/i18n/i18n.test.ts
```
Check Clean and Playful in light/dark: advanced source options, per-target reasons,
registered/loading-unverified state, and identical Antigravity Desktop/CLI logos.
+4 -2
View File
@@ -319,15 +319,17 @@ func planBackupCleanup(backups []backup.BackupInfo, cfg backup.CleanupConfig, no
}
size := backup.Size(backupInfo.Path)
totalSize += size
if cfg.MaxSizeMB > 0 && totalSize > cfg.MaxSizeMB*1024*1024 {
if !shouldRemove && cfg.MaxSizeMB > 0 && i > 0 &&
totalSize+size > cfg.MaxSizeMB*1024*1024 {
shouldRemove = true
}
if shouldRemove {
removed++
removedSize += size
continue
}
totalSize += size
}
return removed, removedSize
+2 -3
View File
@@ -2,7 +2,6 @@ package main
import (
"fmt"
"path/filepath"
"skillshare/internal/backup"
"skillshare/internal/config"
@@ -11,7 +10,7 @@ import (
// 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/.
// In project mode, backups are stored under <project-dir>/backups/.
func createAgentBackup(mode runMode, cwd, targetName string, dryRun bool) error {
backupDir, targets, err := resolveAgentBackupContext(mode, cwd)
if err != nil {
@@ -153,6 +152,6 @@ func resolveProjectAgentBackupContext(cwd string) (string, []agentTarget, error)
}
}
backupDir := filepath.Join(cwd, ".skillshare", "backups")
backupDir := backup.ProjectBackupDir(cwd)
return backupDir, targets, nil
}
+63
View File
@@ -0,0 +1,63 @@
package main
import (
"os"
"path/filepath"
"testing"
"time"
"skillshare/internal/backup"
)
func TestPlanBackupCleanup_OverSizeCapKeepsNewestBackup(t *testing.T) {
backupPath := filepath.Join(t.TempDir(), "2026-07-30_00-00-00")
if err := os.MkdirAll(filepath.Join(backupPath, "claude"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(backupPath, "claude", "big.bin"), make([]byte, 2<<20), 0644); err != nil {
t.Fatal(err)
}
backups := []backup.BackupInfo{{
Timestamp: "2026-07-30_00-00-00",
Path: backupPath,
Date: time.Now(),
}}
removed, freed := planBackupCleanup(backups, backup.CleanupConfig{MaxSizeMB: 1}, time.Now())
if removed != 0 {
t.Errorf("removed = %d, want 0", removed)
}
if freed != 0 {
t.Errorf("freed = %d, want 0", freed)
}
}
func TestPlanBackupCleanup_SizeCapCountsOnlyRetainedBackups(t *testing.T) {
root := t.TempDir()
sizes := []int{400 << 10, 700 << 10, 400 << 10}
backups := make([]backup.BackupInfo, 0, len(sizes))
for i, size := range sizes {
path := filepath.Join(root, time.Now().Add(-time.Duration(i)*time.Hour).Format("2006-01-02_15-04-05"))
if err := os.MkdirAll(filepath.Join(path, "claude"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(path, "claude", "payload.bin"), make([]byte, size), 0644); err != nil {
t.Fatal(err)
}
backups = append(backups, backup.BackupInfo{
Timestamp: filepath.Base(path),
Path: path,
Date: time.Now().Add(-time.Duration(i) * time.Hour),
})
}
removed, freed := planBackupCleanup(backups, backup.CleanupConfig{MaxSizeMB: 1}, time.Now())
if removed != 1 {
t.Errorf("removed = %d, want 1", removed)
}
if freed != int64(sizes[1]) {
t.Errorf("freed = %d, want %d", freed, sizes[1])
}
}
+3 -2
View File
@@ -616,10 +616,11 @@ func resolveSkillStatuses(
}
}
// Fetch remote tree hashes once per URL (nil on error → fallback)
// Fetch remote tree hashes once per URL+branch (nil on error → fallback)
var remoteTreeHashes map[string]string
if len(subdirs) > 0 {
remoteTreeHashes = check.FetchRemoteTreeHashes(url)
repoURL, branch := splitURLBranch(url)
remoteTreeHashes = check.FetchRemoteTreeHashesForRef(repoURL, branch)
}
for i, it := range items {
+1 -4
View File
@@ -65,9 +65,6 @@ func parseCollectOptions(args []string) collectOptions {
}
}
}
if opts.jsonOutput {
opts.force = true
}
return opts
}
@@ -181,7 +178,7 @@ func runCollectPlan(plan collectPlan, opts collectOptions, start time.Time, scop
return summary, nil
}
if !opts.force {
if !opts.force && !opts.jsonOutput {
if !confirmCollect(label) {
ui.Info("Cancelled")
return summary, nil
+4 -4
View File
@@ -40,13 +40,13 @@ func cmdCommit(args []string) error {
ui.Header("Committing local changes")
spinner := ui.StartSpinner("Checking repository...")
source, ok := resolveGitRoot(cfg, spinner)
if !ok {
return nil // Mismatch guidance already displayed
source, err := resolveGitRoot(cfg, spinner)
if err != nil {
return err
}
if err := checkGitWorktree(source, spinner); err != nil {
return nil // Error already displayed
return err
}
if sweep := rootScopeSafetySweep(cfg, source, opts.dryRun); sweep.hasNotice() {
+16 -3
View File
@@ -14,7 +14,7 @@ _skillshare() {
cword=$COMP_CWORD
fi
local commands="init install uninstall list search sync status diff backup restore collect pull push commit doctor target upgrade update check new trash analyze audit hub log ui tui extras enable disable completion version help"
local commands="init install uninstall list search sync mcp plugin status diff backup restore collect pull push commit doctor target upgrade update check new trash analyze audit hub log ui tui extras enable disable completion version help"
local global_flags="--project -p --global -g"
@@ -31,8 +31,9 @@ _skillshare() {
local init_flags="--source -s --remote --copy-from -c --no-copy --targets -t --all-targets --no-targets --mode -m --git --no-git --skill --no-skill --discover -d --select --subdir --dry-run -n --help -h"
local install_flags="--source -s --name --force -f --update -u --dry-run -n --skip-audit --audit-verbose --audit-threshold --threshold -T --branch -b --track -t --kind --agent -a --skill --exclude --into --all --yes -y --json --help -h"
local uninstall_flags="--all --force -f --dry-run -n --json --group -G --help -h"
local list_flags="--verbose -v --json -j --no-tui --type -t --sort -s --all --help -h"
local list_flags="--verbose -v --json -j --no-tui --type -t --status --sort -s --all --help -h"
local sync_flags="--all --dry-run -n --force -f --json --help -h"
local mcp_flags="--pi-extension --url --target --from --file --sync --replace --revision --dry-run -n --json --help -h"
local diff_flags="--no-tui --patch --stat --json --help -h"
local backup_flags="--list -l --cleanup -c --dry-run -n --target -t --help -h"
local restore_flags="--from -f --force --dry-run -n --no-tui --help -h"
@@ -67,6 +68,16 @@ _skillshare() {
local cmd="${words[1]}"
if [[ "${cmd}" == plugin && ( "${prev}" == --target || "${prev}" == --from ) ]]; then
COMPREPLY=($(compgen -W "claude codex cursor antigravity agy antigravity-cli copilot grok kimi hermes devin pi opencode" -- "${cur}"))
return
fi
if [[ "${cmd}" == mcp && "${prev}" == --pi-extension ]]; then
COMPREPLY=($(compgen -W "pi-mcp-adapter pi-mcp-extension" -- "${cur}"))
return
fi
# Handle subcommands (cword == 2)
if [[ ${cword} -eq 2 ]]; then
case "${cmd}" in
@@ -99,7 +110,7 @@ _skillshare() {
return
;;
sync)
COMPREPLY=($(compgen -W "agents extras ${sync_flags} ${global_flags}" -- "${cur}"))
COMPREPLY=($(compgen -W "agents extras mcp plugins ${sync_flags} ${global_flags}" -- "${cur}"))
return
;;
list)
@@ -151,6 +162,8 @@ _skillshare() {
uninstall) COMPREPLY=($(compgen -W "${uninstall_flags} ${global_flags}" -- "${cur}")) ;;
list) COMPREPLY=($(compgen -W "${list_flags} ${global_flags}" -- "${cur}")) ;;
sync) COMPREPLY=($(compgen -W "${sync_flags} ${global_flags}" -- "${cur}")) ;;
plugin) COMPREPLY=($(compgen -W "add discover import list inspect sync check update enable disable remove --target --from --plugin --name --source-ref --entry --revision --dry-run --json --no-tui ${global_flags}" -- "${cur}")) ;;
mcp) COMPREPLY=($(compgen -W "add import list remove restore ${mcp_flags} ${global_flags}" -- "${cur}")) ;;
status) COMPREPLY=($(compgen -W "${global_flags}" -- "${cur}")) ;;
diff) COMPREPLY=($(compgen -W "${diff_flags} ${global_flags}" -- "${cur}")) ;;
backup) COMPREPLY=($(compgen -W "${backup_flags} ${global_flags}" -- "${cur}")) ;;
+18 -2
View File
@@ -29,7 +29,22 @@ complete -c skillshare -n __fish_skillshare_no_subcommand -a install -d 'Install
complete -c skillshare -n __fish_skillshare_no_subcommand -a uninstall -d 'Remove skills/agents from source directory'
complete -c skillshare -n __fish_skillshare_no_subcommand -a list -d 'List installed skills'
complete -c skillshare -n __fish_skillshare_no_subcommand -a search -d 'Search or browse GitHub for skills'
complete -c skillshare -n __fish_skillshare_no_subcommand -a sync -d 'Sync skills/agents/extras to targets'
complete -c skillshare -n __fish_skillshare_no_subcommand -a sync -d 'Sync skills/agents/extras/MCP to targets'
complete -c skillshare -n __fish_skillshare_no_subcommand -a plugin -d 'Manage complete native plugins'
complete -c skillshare -n '__fish_skillshare_using_command plugin' -a 'add discover import list inspect sync check update enable disable remove'
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l target -r -a 'claude codex cursor antigravity agy antigravity-cli copilot grok kimi hermes devin pi opencode' -d 'Plugin target'
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l from -r -a 'claude codex cursor antigravity agy antigravity-cli copilot grok kimi hermes devin pi opencode' -d 'Plugin target'
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l plugin -r
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l name -r
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l source-ref -r
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l entry -r
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l revision -r
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l dry-run
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l json
complete -c skillshare -n '__fish_skillshare_using_command plugin' -l no-tui
complete -c skillshare -n __fish_skillshare_no_subcommand -a mcp -d 'Manage MCP connections'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l pi-extension -r -a 'pi-mcp-adapter pi-mcp-extension' -d 'MCP extension installed in Pi'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -a 'add import list remove restore'
complete -c skillshare -n __fish_skillshare_no_subcommand -a status -d 'Show status of all targets'
complete -c skillshare -n __fish_skillshare_no_subcommand -a diff -d 'Show differences between source and targets'
complete -c skillshare -n __fish_skillshare_no_subcommand -a backup -d 'Create backup of targets'
@@ -117,12 +132,13 @@ complete -c skillshare -n '__fish_skillshare_using_command list' -l verbose -s v
complete -c skillshare -n '__fish_skillshare_using_command list' -l json -s j -d 'JSON output'
complete -c skillshare -n '__fish_skillshare_using_command list' -l no-tui -d 'Skip interactive TUI'
complete -c skillshare -n '__fish_skillshare_using_command list' -l type -s t -r -a 'tracked local github' -d 'Filter by type'
complete -c skillshare -n '__fish_skillshare_using_command list' -l status -r -a 'all enabled disabled' -d 'Filter by status'
complete -c skillshare -n '__fish_skillshare_using_command list' -l sort -s s -r -a 'name newest oldest' -d 'Sort by'
complete -c skillshare -n '__fish_skillshare_using_command list' -l all -d 'List skills + agents'
complete -c skillshare -n '__fish_skillshare_using_command list' -l help -s h -d 'Show help'
# sync
complete -c skillshare -n '__fish_skillshare_using_command sync' -a 'agents extras' -d 'Sync scope'
complete -c skillshare -n '__fish_skillshare_using_command sync' -a 'agents extras mcp plugins' -d 'Sync scope'
complete -c skillshare -n '__fish_skillshare_using_command sync' -l all -d 'Sync skills + agents + extras'
complete -c skillshare -n '__fish_skillshare_using_command sync' -l dry-run -s n -d 'Preview changes'
complete -c skillshare -n '__fish_skillshare_using_command sync' -l force -s f -d 'Force sync'
+54 -2
View File
@@ -9,7 +9,9 @@ def "nu-complete skillshare commands" [] {
{ value: "uninstall", description: "Remove skills/agents from source directory" }
{ value: "list", description: "List installed skills" }
{ value: "search", description: "Search or browse GitHub for skills" }
{ value: "sync", description: "Sync skills/agents/extras to targets" }
{ value: "sync", description: "Sync skills/agents/extras/MCP to targets" }
{ value: "plugin", description: "Manage complete native plugins" }
{ value: "mcp", description: "Manage MCP connections" }
{ value: "status", description: "Show status of all targets" }
{ value: "diff", description: "Show differences between source and targets" }
{ value: "backup", description: "Create backup of targets" }
@@ -40,6 +42,51 @@ def "nu-complete skillshare commands" [] {
]
}
def "nu-complete skillshare plugin" [] {
[add discover import list inspect sync check update enable disable remove]
}
def "nu-complete skillshare plugin-target" [] {
[claude codex cursor antigravity agy antigravity-cli copilot grok kimi hermes devin pi opencode]
}
export extern "skillshare mcp" [
command?: string
name?: string
--pi-extension: string # pi-mcp-adapter or pi-mcp-extension
--target: string
--from: string
--url: string
--file: string
--revision: string
--sync
--replace
--dry-run(-n)
--json
--no-tui
--project(-p)
--global(-g)
--help(-h)
]
export extern "skillshare plugin" [
command?: string@"nu-complete skillshare plugin"
value?: string
--target: string@"nu-complete skillshare plugin-target"
--from: string@"nu-complete skillshare plugin-target"
--plugin: string
--name: string
--source-ref: string
--entry: string
--revision: string
--dry-run(-n)
--json
--no-tui
--global(-g)
--project(-p)
--help(-h)
]
def "nu-complete skillshare target" [] {
[
{ value: "add", description: "Add a target" }
@@ -131,6 +178,10 @@ def "nu-complete skillshare list-sort" [] {
["name" "newest" "oldest"]
}
def "nu-complete skillshare list-status" [] {
["all" "enabled" "disabled"]
}
# Main command
export extern "skillshare" [
command?: string@"nu-complete skillshare commands"
@@ -209,6 +260,7 @@ export extern "skillshare list" [
--json(-j) # JSON output
--no-tui # Skip interactive TUI
--type(-t): string@"nu-complete skillshare list-type"
--status: string@"nu-complete skillshare list-status"
--sort(-s): string@"nu-complete skillshare list-sort"
--all # List skills + agents
--project(-p) # Use project-level config
@@ -218,7 +270,7 @@ export extern "skillshare list" [
# Sync
export extern "skillshare sync" [
scope?: string # agents, extras
scope?: string # agents, extras, mcp, plugins
--all # Sync skills + agents + extras
--dry-run(-n) # Preview changes
--force(-f) # Force sync
+28 -2
View File
@@ -12,7 +12,9 @@ $_skillshareCompleter = {
@{ Name = 'uninstall'; Desc = 'Remove skills/agents from source directory' }
@{ Name = 'list'; Desc = 'List installed skills' }
@{ Name = 'search'; Desc = 'Search or browse GitHub for skills' }
@{ Name = 'sync'; Desc = 'Sync skills/agents/extras to targets' }
@{ Name = 'sync'; Desc = 'Sync skills/agents/extras/MCP to targets' }
@{ Name = 'plugin'; Desc = 'Manage complete native plugins' }
@{ Name = 'mcp'; Desc = 'Manage MCP connections' }
@{ Name = 'status'; Desc = 'Show status of all targets' }
@{ Name = 'diff'; Desc = 'Show differences between source and targets' }
@{ Name = 'backup'; Desc = 'Create backup of targets' }
@@ -41,6 +43,19 @@ $_skillshareCompleter = {
@{ Name = 'version'; Desc = 'Show version' }
@{ Name = 'help'; Desc = 'Show help' }
)
'plugin' = @(
@{ Name = 'add'; Desc = 'Plugin add' }
@{ Name = 'discover'; Desc = 'Plugin discover' }
@{ Name = 'import'; Desc = 'Plugin import' }
@{ Name = 'list'; Desc = 'Plugin list' }
@{ Name = 'inspect'; Desc = 'Plugin inspect' }
@{ Name = 'sync'; Desc = 'Plugin sync' }
@{ Name = 'check'; Desc = 'Plugin check' }
@{ Name = 'update'; Desc = 'Plugin update' }
@{ Name = 'enable'; Desc = 'Plugin enable' }
@{ Name = 'disable'; Desc = 'Plugin disable' }
@{ Name = 'remove'; Desc = 'Plugin remove' }
)
'target' = @(
@{ Name = 'add'; Desc = 'Add a target' }
@{ Name = 'remove'; Desc = 'Unlink target and restore skills' }
@@ -90,7 +105,7 @@ $_skillshareCompleter = {
'init' = '--source', '-s', '--remote', '--copy-from', '-c', '--no-copy', '--targets', '-t', '--all-targets', '--no-targets', '--mode', '-m', '--git', '--no-git', '--skill', '--no-skill', '--discover', '-d', '--select', '--subdir', '--dry-run', '-n', '--help', '-h', '--project', '-p', '--global', '-g'
'install' = '--source', '-s', '--name', '--force', '-f', '--update', '-u', '--dry-run', '-n', '--skip-audit', '--audit-verbose', '--audit-threshold', '--threshold', '-T', '--branch', '-b', '--track', '-t', '--kind', '--agent', '-a', '--skill', '--exclude', '--into', '--all', '--yes', '-y', '--json', '--help', '-h', '--project', '-p', '--global', '-g'
'uninstall' = '--all', '--force', '-f', '--dry-run', '-n', '--json', '--group', '-G', '--help', '-h', '--project', '-p', '--global', '-g'
'list' = '--verbose', '-v', '--json', '-j', '--no-tui', '--type', '-t', '--sort', '-s', '--all', '--help', '-h', '--project', '-p', '--global', '-g'
'list' = '--verbose', '-v', '--json', '-j', '--no-tui', '--type', '-t', '--status', '--sort', '-s', '--all', '--help', '-h', '--project', '-p', '--global', '-g'
'sync' = '--all', '--dry-run', '-n', '--force', '-f', '--json', '--help', '-h', '--project', '-p', '--global', '-g'
'diff' = '--no-tui', '--patch', '--stat', '--json', '--help', '-h', '--project', '-p', '--global', '-g'
'backup' = '--list', '-l', '--cleanup', '-c', '--dry-run', '-n', '--target', '-t', '--help', '-h', '--project', '-p', '--global', '-g'
@@ -112,6 +127,8 @@ $_skillshareCompleter = {
'enable' = '--dry-run', '-n', '--help', '-h', '--project', '-p', '--global', '-g'
'disable' = '--dry-run', '-n', '--help', '-h', '--project', '-p', '--global', '-g'
'analyze' = '--no-tui', '--json', '--help', '-h', '--project', '-p', '--global', '-g'
'mcp' = '--pi-extension', '--target', '--from', '--url', '--file', '--sync', '--replace', '--revision', '--dry-run', '--json', '--no-tui', '--help', '--project', '--global'
'plugin' = '--target', '--from', '--plugin', '--name', '--source-ref', '--entry', '--revision', '--dry-run', '--json', '--no-tui', '--help', '--project', '--global'
'extras' = '--help', '-h', '--project', '-p', '--global', '-g'
'completion' = '--install', '--help', '-h'
}
@@ -120,6 +137,15 @@ $_skillshareCompleter = {
$cmd = if ($elements.Count -gt 1) { $elements[1] } else { '' }
$subcmd = if ($elements.Count -gt 2) { $elements[2] } else { '' }
$previousIndex = $elements.Count - 1
if ($wordToComplete -ne '') { $previousIndex-- }
if ($cmd -eq 'plugin' -and $previousIndex -ge 0 -and $elements[$previousIndex] -in @('--target', '--from')) {
@('claude', 'codex', 'cursor', 'antigravity', 'agy', 'antigravity-cli', 'copilot', 'grok', 'kimi', 'hermes', 'devin', 'pi', 'opencode') | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
return
}
# Complete subcommands
if ($elements.Count -le 2 -or ($elements.Count -eq 2 -and $wordToComplete -ne '')) {
$key = if ($elements.Count -le 1 -or ($elements.Count -eq 2 -and $wordToComplete -ne '')) { '' } else { $cmd }
+38 -2
View File
@@ -10,7 +10,9 @@ _skillshare() {
'uninstall:Remove skills/agents from source directory'
'list:List installed skills'
'search:Search or browse GitHub for skills'
'sync:Sync skills/agents/extras to targets'
'sync:Sync skills/agents/extras/MCP to targets'
'plugin:Manage complete native plugins'
'mcp:Manage MCP connections'
'status:Show status of all targets'
'diff:Show differences between source and targets'
'backup:Create backup of targets'
@@ -86,6 +88,39 @@ _skillshare() {
'--help[Show help]' \
'-h[Show help]'
;;
mcp)
_arguments \
'1:command:(add edit import list remove restore)' \
'--pi-extension[MCP extension installed in Pi]:extension:(pi-mcp-adapter pi-mcp-extension)' \
'--target[Receiving client]:target:' \
'--from[Import client]:target:' \
'--url[MCP endpoint]:url:' \
'--file[Import file]:file:_files' \
'--sync[Sync after saving]' \
'--replace[Replace an existing entry]' \
'--revision[Preview revision]:revision:' \
'--dry-run[Preview changes]' \
'--json[JSON output]' \
'--no-tui[Disable interactive menus]' \
$global_flags \
'--help[Show help]'
;;
plugin)
_arguments \
'1:command:(add discover import list inspect sync check update enable disable remove)' \
'--target[Receiving target]:target:(claude codex cursor antigravity agy antigravity-cli copilot grok kimi hermes devin pi opencode)' \
'--from[Import target]:target:(claude codex cursor antigravity agy antigravity-cli copilot grok kimi hermes devin pi opencode)' \
'--plugin[Source plugin]:name:' \
'--name[Logical package name]:name:' \
'--source-ref[Git branch, tag or commit]:ref:' \
'--entry[OpenCode entry path]:path:' \
'--revision[Preview revision]:revision:' \
'--dry-run[Preview changes]' \
'--json[JSON output]' \
'--no-tui[Disable interactive menus]' \
$global_flags \
'--help[Show help]'
;;
install)
_arguments \
'1:source:_files' \
@@ -145,6 +180,7 @@ _skillshare() {
'--no-tui[Skip interactive TUI]' \
'--type[Filter by type]:type:(tracked local github)' \
'-t[Filter by type]:type:(tracked local github)' \
'--status[Filter by status]:status:(all enabled disabled)' \
'--sort[Sort by]:order:(name newest oldest)' \
'-s[Sort by]:order:(name newest oldest)' \
'--all[List skills + agents]' \
@@ -154,7 +190,7 @@ _skillshare() {
;;
sync)
_arguments \
'1:scope:(agents extras)' \
'1:scope:(agents extras mcp plugins)' \
'--all[Sync skills + agents + extras]' \
'--dry-run[Preview changes]' \
'-n[Preview changes]' \
+6 -6
View File
@@ -460,7 +460,7 @@ func cmdDiffGlobal(targetName string, kind resourceKindFilter, opts diffRenderOp
defer wg.Done()
defer func() { <-sem }()
progress.startTarget(fe.name)
r := collectTargetDiff(fe.name, fe.target, cfg.EffectiveSkillsSource(), fe.mode, fe.filtered, progress)
r := collectTargetDiff(fe.name, fe.target, cfg.EffectiveSkillsSource(), fe.mode, fe.filtered, sync.EffectiveFileIgnorePatterns(cfg.Ignore), progress)
progress.doneTarget(fe.name, r)
results[idx] = r
}(i, fe)
@@ -557,7 +557,7 @@ func diffOutputJSONWithExtras(results []targetDiffResult, extrasResults []extraD
return writeJSON(&o)
}
func collectTargetDiff(name string, target config.TargetConfig, source, mode string, filtered []sync.DiscoveredSkill, dp *diffProgress) targetDiffResult {
func collectTargetDiff(name string, target config.TargetConfig, source, mode string, filtered []sync.DiscoveredSkill, ignorePatterns []string, dp *diffProgress) targetDiffResult {
sc := target.SkillsConfig()
r := targetDiffResult{
name: name,
@@ -600,7 +600,7 @@ func collectTargetDiff(name string, target config.TargetConfig, source, mode str
if mode == "copy" {
manifest, _ := sync.ReadManifest(sc.Path)
collectCopyDiff(&r, name, sc.Path, resolution.Skills, sourceSkills, legacyNames, manifest, dp)
collectCopyDiff(&r, name, sc.Path, resolution.Skills, sourceSkills, legacyNames, manifest, ignorePatterns, dp)
} else {
// Merge mode (instant)
collectMergeDiff(&r, sc.Path, sourceSkills, sourceMap, legacyNames)
@@ -637,7 +637,7 @@ func collectSymlinkDiff(r *targetDiffResult, targetPath, source string) {
}
}
func collectCopyDiff(r *targetDiffResult, targetName, targetPath string, filtered []sync.ResolvedTargetSkill, sourceSkills map[string]bool, legacyNames map[string]sync.ResolvedTargetSkill, manifest *sync.Manifest, dp *diffProgress) {
func collectCopyDiff(r *targetDiffResult, targetName, targetPath string, filtered []sync.ResolvedTargetSkill, sourceSkills map[string]bool, legacyNames map[string]sync.ResolvedTargetSkill, manifest *sync.Manifest, ignorePatterns []string, dp *diffProgress) {
for _, resolved := range filtered {
skill := resolved.Skill
dp.update(targetName, resolved.TargetName)
@@ -674,11 +674,11 @@ func collectCopyDiff(r *targetDiffResult, targetName, targetPath string, filtere
}
// mtime fast-path
oldMtime := manifest.Mtimes[resolved.TargetName]
currentMtime, mtimeErr := sync.DirMaxMtime(skill.SourcePath)
currentMtime, mtimeErr := sync.DirMaxMtimeWithIgnore(skill.SourcePath, ignorePatterns)
if mtimeErr == nil && oldMtime > 0 && currentMtime == oldMtime {
continue
}
srcChecksum, err := sync.DirChecksum(skill.SourcePath)
srcChecksum, err := sync.DirChecksumWithIgnore(skill.SourcePath, ignorePatterns)
if err != nil {
r.items = append(r.items, copyDiffEntry{action: "modify", name: resolved.TargetName, reason: "cannot compute checksum", isSync: true, srcDir: srcDir, dstDir: dstDir})
continue
+2 -4
View File
@@ -14,10 +14,8 @@ import (
// 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
}
if err := ensureProjectConfig(root); err != nil {
return err
}
rt, err := loadProjectRuntime(root)
+4 -5
View File
@@ -14,10 +14,8 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR
if kind == kindAgents {
return diffProjectAgents(root, targetName, opts, start)
}
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
runtime, err := loadProjectRuntime(root)
@@ -99,6 +97,7 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR
}
results := make([]targetDiffResult, len(resolved))
ignorePatterns := sync.EffectiveFileIgnorePatterns(runtime.config.Ignore)
sem := make(chan struct{}, 8)
var wg gosync.WaitGroup
for i, rt := range resolved {
@@ -108,7 +107,7 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR
defer wg.Done()
defer func() { <-sem }()
progress.startTarget(rt.name)
r := collectTargetDiff(rt.name, rt.target, runtime.sourcePath, rt.mode, rt.filtered, progress)
r := collectTargetDiff(rt.name, rt.target, runtime.sourcePath, rt.mode, rt.filtered, ignorePatterns, progress)
progress.doneTarget(rt.name, r)
results[idx] = r
}(i, rt)
+13 -6
View File
@@ -487,7 +487,7 @@ func checkTargets(cfg *config.Config, result *doctorResult, isProject bool) map[
result.addWarning()
}
targetIssues := checkTargetIssues(target, cfg.EffectiveSkillsSource())
targetIssues := checkTargetIssues(target, cfg.EffectiveSkillsSource(), mode)
// Target name header
fmt.Printf("%s%s%s\n", ui.Bold, name, ui.Reset)
@@ -519,7 +519,7 @@ func checkTargets(cfg *config.Config, result *doctorResult, isProject bool) map[
return cache
}
func checkTargetIssues(target config.TargetConfig, source string) []string {
func checkTargetIssues(target config.TargetConfig, source, mode string) []string {
sc := target.SkillsConfig()
var targetIssues []string
@@ -537,12 +537,13 @@ func checkTargetIssues(target config.TargetConfig, source string) []string {
return targetIssues
}
// Check if it's a symlink
if info.Mode()&os.ModeSymlink != 0 {
// Check if it's a symlink. Relative links must resolve against the link's
// parent directory, not the current working directory.
if mode == "symlink" && info.Mode()&os.ModeSymlink != 0 {
link, _ := os.Readlink(sc.Path)
absLink, _ := filepath.Abs(link)
absLink, err := utils.ResolveLinkTarget(sc.Path)
absSource, _ := filepath.Abs(source)
if !utils.PathsEqual(absLink, absSource) {
if err != nil || !utils.PathsEqual(absLink, absSource) {
targetIssues = append(targetIssues, fmt.Sprintf("symlink points to wrong location: %s", link))
}
}
@@ -1014,6 +1015,12 @@ func checkDuplicateSkills(cfg *config.Config, result *doctorResult, discovered [
continue
}
// The target dir is itself a link (symlink mode after sync), so its
// entries are the source itself, not target-local copies.
if mode == "symlink" && utils.IsSymlinkOrJunction(sc.Path) {
continue
}
resolution, err := sync.ResolveTargetSkillsForTarget(name, target.SkillsConfig(), discovered)
if err != nil {
continue
+1 -1
View File
@@ -36,7 +36,7 @@ func checkAgentTargetInline(name string, target config.TargetConfig, builtinAgen
fmt.Sprintf("Agent target %s: invalid filter: %v", name, filterErr), nil)
return
}
agentCount := len(filtered)
agentCount := len(sync.FilterAgentsByTarget(filtered, name))
// Build details for JSON output
var details []string
@@ -0,0 +1,180 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
func writeSkill(t *testing.T, dir, name string) {
t.Helper()
skillDir := filepath.Join(dir, name)
if err := os.MkdirAll(skillDir, 0755); err != nil {
t.Fatal(err)
}
body := "---\nname: " + name + "\ndescription: Fixture skill.\n---\n\n# " + name + "\n"
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(body), 0644); err != nil {
t.Fatal(err)
}
}
func TestEnsureProjectConfig_AlreadyInitialized(t *testing.T) {
for _, dirName := range []string{".skillshare", "skillshare"} {
t.Run(dirName, func(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, dirName)
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("targets: []\n"), 0644); err != nil {
t.Fatal(err)
}
if err := ensureProjectConfig(root); err != nil {
t.Errorf("ensureProjectConfig() = %v, want nil", err)
}
})
}
}
// A repository with no project directory at all still bootstraps, which is the
// documented behaviour of the project commands.
func TestEnsureProjectConfig_NoProjectStillInitializes(t *testing.T) {
root := t.TempDir()
if err := ensureProjectConfig(root); err != nil {
t.Fatalf("ensureProjectConfig() = %v, want nil", err)
}
if _, err := os.Stat(filepath.Join(root, ".skillshare", "config.yaml")); err != nil {
t.Errorf("no config created for a fresh repository: %v", err)
}
}
// The --config local shared skills repo gitignores config.yaml, so a fresh
// clone legitimately has content but no config and must still regenerate one.
func TestEnsureProjectConfig_SharedRepoStillRepairs(t *testing.T) {
for _, dirName := range []string{".skillshare", "skillshare"} {
t.Run(dirName, func(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, dirName)
writeSkill(t, filepath.Join(dir, "skills"), "shared-skill")
if err := os.WriteFile(filepath.Join(dir, ".gitignore"), []byte("config.yaml\n"), 0644); err != nil {
t.Fatal(err)
}
if err := ensureProjectConfig(root); err != nil {
t.Fatalf("ensureProjectConfig() = %v, want nil for the shared-repo flow", err)
}
if _, err := os.Stat(filepath.Join(dir, "config.yaml")); err != nil {
t.Errorf("shared-repo repair did not write a config: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, "skills", "shared-skill", "SKILL.md")); err != nil {
t.Errorf("shared skill was disturbed: %v", err)
}
})
}
}
// A visible shared repo whose skills and agents were never committed clones
// with nothing but the tracked .gitignore, because git drops empty directories.
// The repair must still target that directory instead of starting a hidden one
// alongside it.
func TestEnsureProjectConfig_FreshCloneOfVisibleSharedRepo(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "skillshare")
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ".gitignore"), []byte("logs\ntrash\nbackups\nconfig.yaml\n"), 0644); err != nil {
t.Fatal(err)
}
if err := ensureProjectConfig(root); err != nil {
t.Fatalf("ensureProjectConfig() = %v, want nil for a freshly cloned shared repository", err)
}
if _, err := os.Stat(filepath.Join(dir, "config.yaml")); err != nil {
t.Errorf("no config written to the visible project directory: %v", err)
}
if _, err := os.Stat(filepath.Join(root, ".skillshare")); !os.IsNotExist(err) {
t.Error("repair created a hidden project directory next to the visible one")
}
}
// The guarded case: a project directory that already holds content, whose
// config.yaml is simply missing and is not gitignored. Re-initializing would
// replace it with an empty config and silently drop every configured target.
func TestEnsureProjectConfig_RefusesToDiscardExistingProject(t *testing.T) {
for _, dirName := range []string{".skillshare", "skillshare"} {
t.Run(dirName, func(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, dirName)
writeSkill(t, filepath.Join(dir, "skills"), "demo")
err := ensureProjectConfig(root)
if err == nil {
t.Fatal("ensureProjectConfig() = nil, want an error for a content-bearing project without a config")
}
if !strings.Contains(err.Error(), dirName) {
t.Errorf("error %q does not name the project directory", err)
}
if !strings.Contains(err.Error(), "init -p") {
t.Errorf("error %q does not point at 'init -p'", err)
}
if _, statErr := os.Stat(filepath.Join(dir, "config.yaml")); !os.IsNotExist(statErr) {
t.Error("a config was written over an existing project")
}
if _, statErr := os.Stat(filepath.Join(dir, "skills", "demo", "SKILL.md")); statErr != nil {
t.Errorf("existing skill was disturbed: %v", statErr)
}
})
}
}
// An empty project directory has nothing to lose, so it repairs silently as
// before.
func TestEnsureProjectConfig_EmptyProjectDirRepairs(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, ".skillshare")
if err := os.MkdirAll(filepath.Join(dir, "skills"), 0755); err != nil {
t.Fatal(err)
}
if err := ensureProjectConfig(root); err != nil {
t.Fatalf("ensureProjectConfig() = %v, want nil for an empty project directory", err)
}
if _, err := os.Stat(filepath.Join(dir, "config.yaml")); err != nil {
t.Errorf("empty project directory was not repaired: %v", err)
}
}
// Regression guard for the reported data loss, at the command level.
func TestCmdStatusProject_DoesNotDiscardExistingProject(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, ".skillshare")
writeSkill(t, filepath.Join(dir, "skills"), "demo")
if err := cmdStatusProject(root); err == nil {
t.Fatal("cmdStatusProject() = nil, want an error for a content-bearing project without a config")
}
if _, err := os.Stat(filepath.Join(dir, "config.yaml")); !os.IsNotExist(err) {
t.Error("status wrote a fresh config over an existing project")
}
if _, err := os.Stat(filepath.Join(dir, "skills", "demo", "SKILL.md")); err != nil {
t.Errorf("existing skill was disturbed: %v", err)
}
}
// Agents alone are enough to make a project worth protecting.
func TestEnsureProjectConfig_RefusesWhenOnlyAgentsExist(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, ".skillshare")
writeSkill(t, filepath.Join(dir, "agents"), "demo-agent")
if err := ensureProjectConfig(root); err == nil {
t.Fatal("ensureProjectConfig() = nil, want an error for a project holding only agents")
}
if _, err := os.Stat(filepath.Join(dir, "config.yaml")); !os.IsNotExist(err) {
t.Error("a config was written over an existing project")
}
}
+5 -5
View File
@@ -21,12 +21,12 @@ func hasGitDir(dir string) bool {
//
// Option (a) mismatch handling: if the configured scope has no repo directly at
// its directory but another scope's directory does, the user changed git_root
// without relocating the repo. We print guidance and return ok=false so the
// without relocating the repo. We print guidance and return an error so the
// caller aborts. When no stray repo is found we return the resolved directory and
// let the caller's existing repo check emit the standard "not a git repository"
// guidance (this also preserves the legacy case of a skills source nested inside
// an unrelated parent git repo).
func resolveGitRoot(cfg *config.Config, spinner *ui.Spinner) (string, bool) {
func resolveGitRoot(cfg *config.Config, spinner *ui.Spinner) (string, error) {
// Reject an unknown git_root before resolving: ScopeDir silently falls back
// to the skills scope for any unrecognized value, which would make
// commit/push/pull operate on the wrong repository without warning.
@@ -34,7 +34,7 @@ func resolveGitRoot(cfg *config.Config, spinner *ui.Spinner) (string, bool) {
spinner.Fail("Invalid git_root")
ui.Info(" git_root %q is not a valid scope", cfg.GitRoot)
ui.Info(" valid values: %s (or leave empty for skills)", strings.Join(config.ValidGitRoots, ", "))
return "", false
return "", fmt.Errorf("invalid git_root %q", cfg.GitRoot)
}
root := cfg.EffectiveGitRoot()
@@ -50,9 +50,9 @@ func resolveGitRoot(cfg *config.Config, spinner *ui.Spinner) (string, bool) {
ui.Info(" - skillshare init --git-root %s (start a fresh repo at the configured scope)", configured)
ui.Info(" - mv \"%s/.git\" \"%s/.git\" (move the existing repo over, keeps history)", dir, root)
ui.Info(" - set 'git_root: %s' in %s (keep using the existing repo)", scope, config.ConfigPath())
return "", false
return "", fmt.Errorf("git root mismatch (see guidance above)")
}
return root, true
return root, nil
}
// rootSweepResult reports what the root-scope safety sweep changed or found.
+3 -2
View File
@@ -483,8 +483,9 @@ func performFreshInit(opts *initOptions, home string) error {
Mode: mode,
Targets: targets,
Ignore: []string{
"**/.DS_Store",
"**/.git/**",
".DS_Store",
".git/",
"__pycache__/",
},
Audit: config.AuditConfig{
BlockThreshold: "CRITICAL",
+43 -22
View File
@@ -8,6 +8,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/install"
"skillshare/internal/projectdir"
"skillshare/internal/ui"
)
@@ -18,6 +19,7 @@ type projectInitOptions struct {
selectArg string // Non-interactive selection for --discover
mode string // default mode for new targets: merge|copy|symlink
configMode string // "local" to gitignore config.yaml (shared skills repo)
visible bool // create a visible skillshare/ directory instead of .skillshare/
}
type detectedProjectTarget struct {
@@ -40,6 +42,7 @@ func printProjectInitUsage() {
fmt.Println(" --mode, -m <mode> Set sync mode (merge, copy, symlink; default: merge).")
fmt.Println(" With --discover, applies only to newly added targets")
fmt.Println(" --config local Gitignore config.yaml (each developer manages own targets)")
fmt.Println(" --visible Create a visible skillshare/ directory instead of .skillshare/")
fmt.Println(" --dry-run, -n Preview without making changes")
fmt.Println(" --help, -h Show this help")
fmt.Println()
@@ -47,6 +50,7 @@ func printProjectInitUsage() {
fmt.Println(" skillshare init -p")
fmt.Println(" skillshare init -p --targets claude,cursor --mode copy")
fmt.Println(" skillshare init -p --discover --select cursor --mode copy")
fmt.Println(" skillshare init -p --visible")
}
func parseProjectInitArgs(args []string) (projectInitOptions, bool, error) {
@@ -56,6 +60,8 @@ func parseProjectInitArgs(args []string) (projectInitOptions, bool, error) {
switch {
case arg == "--dry-run" || arg == "-n":
opts.dryRun = true
case arg == "--visible":
opts.visible = true
case arg == "--help" || arg == "-h":
return opts, true, nil
case arg == "--discover" || arg == "-d":
@@ -123,8 +129,17 @@ func cmdInitProject(args []string) error {
}
func performProjectInit(root string, opts projectInitOptions) error {
projectDir := filepath.Join(root, ".skillshare")
configPath := config.ProjectConfigPath(root)
// An already-initialized or partially-initialized project keeps its own
// directory; only a brand new project honours --visible.
projectDir, existing := projectdir.Find(root)
if !existing {
projectDir, existing = projectdir.FindPartial(root)
}
if !existing {
projectDir = filepath.Join(root, projectdir.Name(opts.visible))
}
dirName := filepath.Base(projectDir)
configPath := filepath.Join(projectDir, projectdir.ConfigFileName)
partialInitRepair := false
if info, err := os.Stat(projectDir); err == nil {
if !info.IsDir() {
@@ -146,7 +161,7 @@ func performProjectInit(root string, opts projectInitOptions) error {
sharedRepoFlow := false
if partialInitRepair {
gitignored, err := isConfigGitignored(root)
gitignored, err := isConfigGitignored(projectDir)
if err != nil {
ui.Warning("Could not check for shared repo config: %v", err)
}
@@ -210,29 +225,34 @@ func performProjectInit(root string, opts projectInitOptions) error {
if opts.dryRun {
ui.Header("Dry run complete (project)")
ui.Info("Would create .skillshare/skills/")
ui.Info("Would create %s/skills/", dirName)
ui.Info("Would write config: %s", configPath)
return nil
}
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(projectDir, "skills"), 0755); err != nil {
return fmt.Errorf("failed to create %s/skills: %w", dirName, 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 := os.MkdirAll(filepath.Join(projectDir, "agents"), 0755); err != nil {
return fmt.Errorf("failed to create %s/agents: %w", dirName, err)
}
if err := ensureProjectGitignore(root, opts.configMode == "local"); err != nil {
if err := ensureProjectGitignore(projectDir, opts.configMode == "local"); err != nil {
return err
}
cfg := &config.ProjectConfig{
Targets: selected,
Ignore: []string{
".DS_Store",
".git/",
"__pycache__/",
},
Audit: config.AuditConfig{
BlockThreshold: "CRITICAL",
},
}
if err := cfg.Save(root); err != nil {
if err := cfg.SaveIn(projectDir); err != nil {
return err
}
@@ -240,16 +260,16 @@ func performProjectInit(root string, opts projectInitOptions) error {
return err
}
ui.Success("Created .skillshare/config.yaml")
ui.Success("Created .skillshare/skills/")
ui.Success("Created %s/%s", dirName, projectdir.ConfigFileName)
ui.Success("Created %s/skills/", dirName)
if !sharedRepoFlow {
ui.Success("Added %d target(s)", len(selected))
}
fmt.Println()
ui.Header("Initialized successfully (project)")
ui.Success("Source: .skillshare/skills/")
ui.Success("Config: %s", config.ProjectConfigPath(root))
ui.Success("Source: %s/skills/", dirName)
ui.Success("Config: %s", configPath)
if opts.configMode == "local" {
ui.Success("Config gitignored (each developer manages own targets)")
}
@@ -538,25 +558,26 @@ func findGroupedTarget(targets []detectedProjectTarget, name string) *detectedPr
return nil
}
// isConfigGitignored checks if config.yaml is gitignored in .skillshare/.gitignore,
// indicating this is a shared skills repo where each developer manages their own config.
func isConfigGitignored(root string) (bool, error) {
path := filepath.Join(root, ".skillshare", ".gitignore")
// isConfigGitignored checks if config.yaml is gitignored in the project
// directory's .gitignore, indicating this is a shared skills repo where each
// developer manages their own config.
func isConfigGitignored(projectDir string) (bool, error) {
path := filepath.Join(projectDir, ".gitignore")
return install.GitignoreContains(path, "config.yaml")
}
func ensureProjectGitignore(root string, gitignoreConfig bool) error {
gitignoreDir := filepath.Join(root, ".skillshare")
func ensureProjectGitignore(gitignoreDir string, gitignoreConfig bool) error {
dirName := filepath.Base(gitignoreDir)
gitignorePath := filepath.Join(gitignoreDir, ".gitignore")
if _, err := os.Stat(gitignorePath); os.IsNotExist(err) {
if err := os.WriteFile(gitignorePath, []byte(""), 0644); err != nil {
return fmt.Errorf("failed to create .skillshare/.gitignore: %w", err)
return fmt.Errorf("failed to create %s/.gitignore: %w", dirName, err)
}
}
// Always ignore operational directories to avoid committing noise.
if err := install.UpdateGitIgnoreBatch(gitignoreDir, []string{"logs", "trash", "backups"}); err != nil {
return fmt.Errorf("failed to update .skillshare/.gitignore: %w", err)
return fmt.Errorf("failed to update %s/.gitignore: %w", dirName, err)
}
// --config local: gitignore config.yaml so each developer manages own targets.
+82
View File
@@ -0,0 +1,82 @@
package main
import (
"os"
"path/filepath"
"testing"
)
func TestParseProjectInitArgs_Visible(t *testing.T) {
opts, showHelp, err := parseProjectInitArgs([]string{"--visible"})
if err != nil {
t.Fatalf("parseProjectInitArgs failed: %v", err)
}
if showHelp {
t.Fatal("--visible should not request help")
}
if !opts.visible {
t.Error("opts.visible = false, want true")
}
opts, _, err = parseProjectInitArgs([]string{"--targets", "claude"})
if err != nil {
t.Fatalf("parseProjectInitArgs failed: %v", err)
}
if opts.visible {
t.Error("opts.visible = true without --visible")
}
}
func TestPerformProjectInit_Visible(t *testing.T) {
root := t.TempDir()
if err := performProjectInit(root, projectInitOptions{visible: true, targets: []string{"claude"}}); err != nil {
t.Fatalf("performProjectInit failed: %v", err)
}
dir := filepath.Join(root, "skillshare")
for _, sub := range []string{"config.yaml", "skills", "agents", ".gitignore"} {
if _, err := os.Stat(filepath.Join(dir, sub)); err != nil {
t.Errorf("missing %s in visible project directory: %v", sub, err)
}
}
if _, err := os.Stat(filepath.Join(root, ".skillshare")); !os.IsNotExist(err) {
t.Error("--visible also created a hidden .skillshare directory")
}
if !projectConfigExists(root) {
t.Error("visible project not detected by projectConfigExists")
}
}
func TestPerformProjectInit_DefaultStaysHidden(t *testing.T) {
root := t.TempDir()
if err := performProjectInit(root, projectInitOptions{targets: []string{"claude"}}); err != nil {
t.Fatalf("performProjectInit failed: %v", err)
}
if _, err := os.Stat(filepath.Join(root, ".skillshare", "config.yaml")); err != nil {
t.Errorf("default init did not create .skillshare/config.yaml: %v", err)
}
if _, err := os.Stat(filepath.Join(root, "skillshare")); !os.IsNotExist(err) {
t.Error("default init created a visible skillshare directory")
}
}
// A second init must report the existing project rather than creating the other
// layout alongside it.
func TestPerformProjectInit_VisibleProjectIsAlreadyInitialized(t *testing.T) {
root := t.TempDir()
if err := performProjectInit(root, projectInitOptions{visible: true, targets: []string{"claude"}}); err != nil {
t.Fatalf("performProjectInit failed: %v", err)
}
err := performProjectInit(root, projectInitOptions{targets: []string{"claude"}})
if err == nil {
t.Fatal("re-init of a visible project succeeded, want already-initialized error")
}
if _, statErr := os.Stat(filepath.Join(root, ".skillshare")); !os.IsNotExist(statErr) {
t.Error("re-init created a hidden directory next to the visible project")
}
}
+2
View File
@@ -67,6 +67,7 @@ func parseInstallArgs(args []string) (*installArgs, bool, error) {
result.opts.Name = args[i]
case arg == "--force" || arg == "-f":
result.opts.Force = true
result.opts.AuditOverride = true
case arg == "--update" || arg == "-u":
result.opts.Update = true
case arg == "--dry-run" || arg == "-n":
@@ -217,6 +218,7 @@ func applyInstallJSONDefaults(parsed *installArgs) {
if !parsed.jsonOutput {
return
}
// Force only: --json must not silently override the audit gate.
parsed.opts.Force = true
if !parsed.opts.HasSkillFilter() && !parsed.opts.HasAgentFilter() {
parsed.opts.All = true
+2 -15
View File
@@ -31,10 +31,8 @@ func cmdInstallProjectParsed(parsed *installArgs, root string) (installLogSummar
summary.Into = parsed.opts.Into
summary.SkipAudit = parsed.opts.SkipAudit
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return summary, err
}
if err := ensureProjectConfig(root); err != nil {
return summary, err
}
runtime, err := loadProjectRuntime(root)
@@ -78,10 +76,6 @@ func cmdInstallProjectParsed(parsed *installArgs, root string) (installLogSummar
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
@@ -97,13 +91,6 @@ func cmdInstallProjectParsed(parsed *installArgs, root string) (installLogSummar
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)
}
+4
View File
@@ -40,9 +40,13 @@ func TestConfigFromProjectRuntime_IncludesAzureHosts(t *testing.T) {
config: &config.ProjectConfig{
GitLabHosts: []string{"gitlab.corp.com"},
AzureHosts: []string{"azuredevops.corp.com"},
Ignore: []string{"tmp/"},
},
}
cfg := configFromProjectRuntime(runtime)
if len(cfg.Ignore) != 1 || cfg.Ignore[0] != "tmp/" {
t.Fatalf("configFromProjectRuntime dropped Ignore: %v", cfg.Ignore)
}
opts := parseOptsFromConfig(cfg)
source, err := install.ParseSourceWithOptions(
"https://azuredevops.corp.com/Org/Project/_git/Repo", opts)
+79 -16
View File
@@ -28,6 +28,7 @@ type listOptions struct {
Pattern string // positional search pattern (case-insensitive)
TypeFilter string // --type: "tracked", "local", "github"
SortBy string // --sort: "name" (default), "newest", "oldest"
Status listStatusFilter
}
// validTypeFilters lists accepted values for --type.
@@ -44,6 +45,23 @@ var validSortOptions = map[string]bool{
"oldest": true,
}
// validStatusFilters maps accepted --status values to their typed filter.
var validStatusFilters = map[string]listStatusFilter{
"all": statusFilterAll,
"enabled": statusFilterEnabled,
"disabled": statusFilterDisabled,
}
// parseStatusFilter validates a --status value and normalizes it.
func parseStatusFilter(raw string) (listStatusFilter, error) {
v := strings.ToLower(raw)
status, ok := validStatusFilters[v]
if !ok {
return statusFilterAll, fmt.Errorf("invalid status %q: must be all, enabled, or disabled", raw)
}
return status, nil
}
// parseListArgs parses list command arguments into listOptions.
func parseListArgs(args []string) (listOptions, error) {
var opts listOptions
@@ -103,6 +121,22 @@ func parseListArgs(args []string) (listOptions, error) {
return opts, fmt.Errorf("invalid sort %q: must be name, newest, or oldest", v)
}
opts.SortBy = v
case arg == "--status":
i++
if i >= len(args) {
return opts, fmt.Errorf("--status requires a value (all, enabled, disabled)")
}
v, err := parseStatusFilter(args[i])
if err != nil {
return opts, err
}
opts.Status = v
case strings.HasPrefix(arg, "--status="):
v, err := parseStatusFilter(strings.TrimPrefix(arg, "--status="))
if err != nil {
return opts, err
}
opts.Status = v
case strings.HasPrefix(arg, "-"):
return opts, fmt.Errorf("unknown option: %s", arg)
default:
@@ -117,16 +151,22 @@ func parseListArgs(args []string) (listOptions, error) {
return opts, nil
}
// filterSkillEntries filters skills by pattern and type.
// filterSkillEntries filters skills by pattern, type, and status.
// Pattern matches case-insensitively against Name, RelPath, and Source.
func filterSkillEntries(skills []skillEntry, pattern, typeFilter string) []skillEntry {
if pattern == "" && typeFilter == "" {
// Status uses statusFilterAll for no filter; filters combine with AND.
func filterSkillEntries(skills []skillEntry, pattern, typeFilter string, status listStatusFilter) []skillEntry {
if pattern == "" && typeFilter == "" && status == statusFilterAll {
return skills
}
pat := strings.ToLower(pattern)
var result []skillEntry
for _, s := range skills {
// Status filter
if status != statusFilterAll && s.Disabled != (status == statusFilterDisabled) {
continue
}
// Type filter
if typeFilter != "" {
switch typeFilter {
@@ -162,6 +202,29 @@ func filterSkillEntries(skills []skillEntry, pattern, typeFilter string) []skill
return result
}
// statusNote returns a " (status: enabled)" suffix for footers and messages,
// or "" when no status filter is active.
func statusNote(status listStatusFilter) string {
if status == statusFilterAll {
return ""
}
return fmt.Sprintf(" (status: %s)", status.String())
}
// noMatchMessage builds the "no results" message for the active filter set.
func noMatchMessage(resourceLabel string, opts listOptions) string {
switch {
case opts.Pattern != "" && opts.TypeFilter != "":
return fmt.Sprintf("No %s matching %q (type: %s)%s", resourceLabel, opts.Pattern, opts.TypeFilter, statusNote(opts.Status))
case opts.Pattern != "":
return fmt.Sprintf("No %s matching %q%s", resourceLabel, opts.Pattern, statusNote(opts.Status))
case opts.TypeFilter != "":
return fmt.Sprintf("No %s matching type %q%s", resourceLabel, opts.TypeFilter, statusNote(opts.Status))
default:
return fmt.Sprintf("No %s matching status %q", resourceLabel, opts.Status.String())
}
}
// sortSkillEntries sorts skills by the given criteria.
func sortSkillEntries(skills []skillEntry, sortBy string) {
switch sortBy {
@@ -608,14 +671,16 @@ func cmdList(args []string) error {
allEntries = append(allEntries, buildSkillEntries(discovered)...)
allEntries = append(allEntries, discoverAndBuildAgentEntries(cfg.EffectiveAgentsSource())...)
total := len(allEntries)
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
// Status is NOT filtered here — the TUI needs both enabled and
// disabled entries loaded so the `s` key can restore them.
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, statusFilterAll)
// 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, skillKind, err := runListTUI(loadFn, "global", cfg.EffectiveSkillsSource(), cfg.EffectiveAgentsSource(), cfg.Targets, kind)
action, skillName, skillKind, err := runListTUI(loadFn, "global", cfg.EffectiveSkillsSource(), cfg.EffectiveAgentsSource(), cfg.Targets, kind, opts.Status)
if err != nil {
return err
}
@@ -688,10 +753,10 @@ func cmdList(args []string) error {
sp.Success(fmt.Sprintf("Loaded %d %s", len(allEntries), resourceLabel))
}
totalCount := len(allEntries)
hasFilter := opts.Pattern != "" || opts.TypeFilter != ""
hasFilter := opts.Pattern != "" || opts.TypeFilter != "" || opts.Status != statusFilterAll
// Apply filter and sort
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, opts.Status)
// Always sort so the TUI and plain-text renderers see contiguous
// top-level groups (tracked → named locals → standalone).
sortSkillEntries(allEntries, opts.SortBy)
@@ -711,13 +776,7 @@ func cmdList(args []string) error {
}
if hasFilter && len(allEntries) == 0 {
if opts.Pattern != "" && opts.TypeFilter != "" {
ui.Info("No %s matching %q (type: %s)", resourceLabel, opts.Pattern, opts.TypeFilter)
} else if opts.Pattern != "" {
ui.Info("No %s matching %q", resourceLabel, opts.Pattern)
} else {
ui.Info("No %s matching type %q", resourceLabel, opts.TypeFilter)
}
ui.Info("%s", noMatchMessage(resourceLabel, opts))
return nil
}
@@ -746,9 +805,9 @@ func cmdList(args []string) error {
if hasFilter && len(allEntries) > 0 {
fmt.Println()
if opts.Pattern != "" {
ui.Info("%d of %d %s matching %q", len(allEntries), totalCount, resourceLabel, opts.Pattern)
ui.Info("%d of %d %s matching %q%s", len(allEntries), totalCount, resourceLabel, opts.Pattern, statusNote(opts.Status))
} else {
ui.Info("%d of %d %s", len(allEntries), totalCount, resourceLabel)
ui.Info("%d of %d %s%s", len(allEntries), totalCount, resourceLabel, statusNote(opts.Status))
}
} else if !opts.Verbose && len(allEntries) > 0 {
fmt.Println()
@@ -820,6 +879,7 @@ func printListHelp() {
List all installed skills in the source directory.
An optional pattern filters skills by name, path, or source (case-insensitive).
The default view (--status all) includes entries marked disabled.
Options:
--all List both skills and agents
@@ -827,6 +887,7 @@ Options:
--json, -j Output as JSON (useful for CI/scripts)
--no-tui Disable interactive TUI, use plain text output
--type, -t <type> Filter by type: tracked, local, github
--status <status> Filter by status: all (default), enabled, disabled
--sort, -s <order> Sort order: name (default), newest, oldest
--project, -p Use project-level config in current directory
--global, -g Use global config (~/.config/skillshare)
@@ -836,6 +897,8 @@ Examples:
skillshare list
skillshare list react
skillshare list --type local
skillshare list --status disabled
skillshare list --status enabled --json
skillshare list react --type github --sort newest
skillshare list --json | jq '.[].name'
skillshare list --verbose
+11 -17
View File
@@ -11,10 +11,8 @@ import (
)
func cmdListProject(root string, opts listOptions, kind resourceKindFilter) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
projCfg, err := config.LoadProject(root)
@@ -52,11 +50,13 @@ func cmdListProject(root string, opts listOptions, kind resourceKindFilter) erro
allEntries = append(allEntries, buildSkillEntries(discovered)...)
allEntries = append(allEntries, discoverAndBuildAgentEntries(agentsSource)...)
total := len(allEntries)
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
// Status is NOT filtered here — the TUI needs both enabled and
// disabled entries loaded so the `s` key can restore them.
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, statusFilterAll)
sortSkillEntries(allEntries, sortBy)
return listLoadResult{skills: toSkillItems(allEntries), totalCount: total}
}
action, skillName, skillKind, err := runListTUI(loadFn, "project", skillsSource, agentsSource, targets, kind)
action, skillName, skillKind, err := runListTUI(loadFn, "project", skillsSource, agentsSource, targets, kind, opts.Status)
if err != nil {
return err
}
@@ -122,10 +122,10 @@ func cmdListProject(root string, opts listOptions, kind resourceKindFilter) erro
sp.Success(fmt.Sprintf("Loaded %d %s", len(allEntries), resourceLabel))
}
totalCount := len(allEntries)
hasFilter := opts.Pattern != "" || opts.TypeFilter != ""
hasFilter := opts.Pattern != "" || opts.TypeFilter != "" || opts.Status != statusFilterAll
// Apply filter and sort
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter)
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, opts.Status)
sortBy := opts.SortBy
if sortBy == "" {
sortBy = "name" // project mode default
@@ -147,13 +147,7 @@ func cmdListProject(root string, opts listOptions, kind resourceKindFilter) erro
}
if hasFilter && len(allEntries) == 0 {
if opts.Pattern != "" && opts.TypeFilter != "" {
ui.Info("No %s matching %q (type: %s)", resourceLabel, opts.Pattern, opts.TypeFilter)
} else if opts.Pattern != "" {
ui.Info("No %s matching %q", resourceLabel, opts.Pattern)
} else {
ui.Info("No %s matching type %q", resourceLabel, opts.TypeFilter)
}
ui.Info("%s", noMatchMessage(resourceLabel, opts))
return nil
}
@@ -182,9 +176,9 @@ func cmdListProject(root string, opts listOptions, kind resourceKindFilter) erro
if hasFilter && len(allEntries) > 0 {
fmt.Println()
if opts.Pattern != "" {
ui.Info("%d of %d %s matching %q", len(allEntries), totalCount, resourceLabel, opts.Pattern)
ui.Info("%d of %d %s matching %q%s", len(allEntries), totalCount, resourceLabel, opts.Pattern, statusNote(opts.Status))
} else {
ui.Info("%d of %d %s", len(allEntries), totalCount, resourceLabel)
ui.Info("%d of %d %s%s", len(allEntries), totalCount, resourceLabel, statusNote(opts.Status))
}
} else {
fmt.Println()
+134
View File
@@ -0,0 +1,134 @@
package main
import "testing"
func TestParseListArgs_Status(t *testing.T) {
tests := []struct {
name string
args []string
want listStatusFilter
}{
{"space form", []string{"--status", "enabled"}, statusFilterEnabled},
{"equals form", []string{"--status=disabled"}, statusFilterDisabled},
{"case insensitive", []string{"--status", "DISABLED"}, statusFilterDisabled},
{"all", []string{"--status", "all"}, statusFilterAll},
{"all equals form", []string{"--status=ALL"}, statusFilterAll},
{"absent", []string{}, statusFilterAll},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
opts, err := parseListArgs(tc.args)
if err != nil {
t.Fatalf("parseListArgs(%v) error = %v", tc.args, err)
}
if opts.Status != tc.want {
t.Errorf("Status = %q, want %q", opts.Status, tc.want)
}
})
}
}
func TestParseListArgs_StatusErrors(t *testing.T) {
for _, args := range [][]string{
{"--status"}, // missing value
{"--status", "bogus"}, // invalid value
{"--status="}, // empty value
{"--status=off"}, // invalid value, equals form
} {
if _, err := parseListArgs(args); err == nil {
t.Errorf("parseListArgs(%v) = nil error, want error", args)
}
}
}
func TestParseListArgs_StatusCombinesWithOtherFilters(t *testing.T) {
opts, err := parseListArgs([]string{"react", "--type", "local", "--status", "disabled", "--sort", "newest"})
if err != nil {
t.Fatalf("parseListArgs error = %v", err)
}
if opts.Pattern != "react" || opts.TypeFilter != "local" || opts.Status != statusFilterDisabled || opts.SortBy != "newest" {
t.Errorf("got %+v, want pattern=react type=local status=disabled sort=newest", opts)
}
}
func TestFilterSkillEntries_Status(t *testing.T) {
entries := []skillEntry{
{Name: "on-a", RelPath: "on-a"},
{Name: "off-a", RelPath: "off-a", Disabled: true},
{Name: "on-b", RelPath: "on-b"},
}
tests := []struct {
status listStatusFilter
want []string
}{
{statusFilterAll, []string{"on-a", "off-a", "on-b"}},
{statusFilterEnabled, []string{"on-a", "on-b"}},
{statusFilterDisabled, []string{"off-a"}},
}
for _, tc := range tests {
got := filterSkillEntries(entries, "", "", tc.status)
if len(got) != len(tc.want) {
t.Fatalf("status %q: got %d entries, want %d", tc.status, len(got), len(tc.want))
}
for i, name := range tc.want {
if got[i].Name != name {
t.Errorf("status %q: entry %d = %q, want %q", tc.status, i, got[i].Name, name)
}
}
}
}
func TestFilterSkillEntries_StatusAndPatternAreAND(t *testing.T) {
entries := []skillEntry{
{Name: "react-on", RelPath: "react-on"},
{Name: "react-off", RelPath: "react-off", Disabled: true},
{Name: "vue-off", RelPath: "vue-off", Disabled: true},
}
got := filterSkillEntries(entries, "react", "", statusFilterDisabled)
if len(got) != 1 || got[0].Name != "react-off" {
t.Fatalf("got %+v, want only react-off", got)
}
}
func TestNoMatchMessage_StatusOnly(t *testing.T) {
got := noMatchMessage("skills", listOptions{Status: statusFilterDisabled})
want := `No skills matching status "disabled"`
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestNoMatchMessage_StatusWithOtherFilters(t *testing.T) {
got := noMatchMessage("agents", listOptions{Pattern: "react", Status: statusFilterEnabled})
want := `No agents matching "react" (status: enabled)`
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestListStatusFilterString(t *testing.T) {
tests := []struct {
status listStatusFilter
want string
}{
{statusFilterAll, "all"},
{statusFilterEnabled, "enabled"},
{statusFilterDisabled, "disabled"},
}
for _, tc := range tests {
if got := tc.status.String(); got != tc.want {
t.Errorf("%v.String() = %q, want %q", tc.status, got, tc.want)
}
}
}
// The `s` key cycles All → Enabled → Disabled → All from whatever --status
// seeded, so an initial filter never traps the user.
func TestStatusFilterCyclesBackToAll(t *testing.T) {
s := statusFilterDisabled
if next := (s + 1) % 3; next != statusFilterAll {
t.Errorf("cycling from Disabled = %v, want All", next)
}
}
+94 -13
View File
@@ -43,6 +43,18 @@ const (
statusFilterDisabled // show only disabled
)
// String returns the CLI representation of the status filter.
func (s listStatusFilter) String() string {
switch s {
case statusFilterEnabled:
return "enabled"
case statusFilterDisabled:
return "disabled"
default:
return "all"
}
}
// label returns the display name shown in the status chip.
func (s listStatusFilter) label() string {
switch s {
@@ -88,6 +100,9 @@ type detailData struct {
License string
Files []string
SyncedTargets []string
// ModelInvocationOff mirrors disable-model-invocation: the skill stays installed and
// user-invocable, but the model no longer loads it on its own.
ModelInvocationOff bool
}
// listTUIModel is the bubbletea model for the interactive skill list.
@@ -130,7 +145,8 @@ type listTUIModel struct {
// In-TUI confirmation overlay
confirming bool // true when confirmation overlay is shown
confirmAction string // "audit", "update", "uninstall"
confirmAction string // "audit", "update", "uninstall", or confirmModelInvocation
confirmNote string // consequence shown by the in-place confirmations
confirmSkill string // skill name for confirmation display
confirmKind string // "skill" or "agent"
@@ -415,12 +431,13 @@ func (m listTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.confirming {
switch msg.String() {
case "y", "Y", "enter":
if m.confirmAction == confirmModelInvocation {
m.clearConfirm()
return m.toggleModelInvocation()
}
return m.quitWithAction(m.confirmAction)
case "n", "N", "esc", "q":
m.confirming = false
m.confirmAction = ""
m.confirmSkill = ""
m.confirmKind = ""
m.clearConfirm()
return m, nil
}
return m, nil
@@ -501,6 +518,8 @@ func (m listTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m.enterConfirm("uninstall")
case "E":
return m.toggleDisabled()
case "M":
return m.pressModelInvocation()
}
}
@@ -604,6 +623,58 @@ func (m listTUIModel) toggleDisabled() (tea.Model, tea.Cmd) {
}
// quitWithAction sets the action on the selected skill and exits the TUI.
const (
modelInvocationKey = "disable-model-invocation"
confirmModelInvocation = "model-invocation"
)
func (m *listTUIModel) clearConfirm() {
m.confirming = false
m.confirmAction = ""
m.confirmSkill = ""
m.confirmKind = ""
m.confirmNote = ""
}
// pressModelInvocation handles M. Unlike E, which only touches the ignore file beside the
// skill, this edits SKILL.md itself — so when upstream owns that file it says what that costs
// before writing. Turning the flag back off restores the file and needs no warning.
func (m listTUIModel) pressModelInvocation() (tea.Model, tea.Cmd) {
item, ok := m.list.SelectedItem().(skillItem)
if !ok || item.entry.Kind == "agent" { // agent harnesses do not read this key
return m, nil
}
e := item.entry
if m.getDetailData(e).ModelInvocationOff || (e.RepoName == "" && e.Source == "") {
return m.toggleModelInvocation()
}
m.confirming = true
m.confirmAction = confirmModelInvocation
m.confirmSkill = e.RelPath
m.confirmKind = e.Kind
if e.RepoName != "" {
m.confirmNote = "This edits SKILL.md inside a tracked repo. 'skillshare update' skips\n repos with local changes until you press M again to restore the file."
} else {
m.confirmNote = "This edits an installed SKILL.md. The next 'skillshare update' reinstalls\n the skill and drops the change."
}
return m, nil
}
// toggleModelInvocation flips disable-model-invocation in the selected skill's SKILL.md.
func (m listTUIModel) toggleModelInvocation() (tea.Model, tea.Cmd) {
item, ok := m.list.SelectedItem().(skillItem)
if !ok {
return m, nil
}
skillMD := filepath.Join(m.sourcePath, item.entry.RelPath, "SKILL.md")
if _, err := utils.ToggleFrontmatterFlag(skillMD, modelInvocationKey); err != nil {
return m, nil
}
delete(m.detailCache, item.entry.RelPath) // the chip re-reads the file
return m, nil
}
func (m listTUIModel) quitWithAction(action string) (tea.Model, tea.Cmd) {
if _, ok := m.list.SelectedItem().(skillItem); ok {
m.action = action
@@ -637,6 +708,10 @@ func (m listTUIModel) View() string {
if m.confirmKind == "agent" {
kindArg = "agents "
}
if m.confirmAction == confirmModelInvocation {
return fmt.Sprintf("\n %s\n\n %s\n\n Proceed? [Y/n] ",
theme.Warning().Render("Make "+m.confirmSkill+" manual only?"), m.confirmNote)
}
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] ",
@@ -789,7 +864,7 @@ func (m listTUIModel) viewSplit() string {
b.WriteString(m.renderFilterBar())
b.WriteString(m.renderSummaryFooter())
b.WriteString("\n")
helpText := "Tab skills/agents s status ↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable X uninstall q quit"
helpText := "Tab skills/agents s status ↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable M manual only X uninstall q quit"
if m.filtering {
helpText = "t:type g:group r:repo k:kind Enter lock Esc clear q quit"
}
@@ -830,7 +905,7 @@ func (m listTUIModel) viewVertical() string {
b.WriteString(m.renderSummaryFooter())
b.WriteString("\n")
helpText := "Tab skills/agents s status ↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable X uninstall q quit"
helpText := "Tab skills/agents s status ↑↓ navigate ←→ page / filter Ctrl+d/u detail Enter view A audit U update E enable/disable M manual only X uninstall q quit"
if m.filtering {
helpText = "t:type g:group r:repo k:kind Enter lock Esc clear q quit"
}
@@ -953,13 +1028,14 @@ func (m listTUIModel) getDetailData(e skillEntry) *detailData {
skillMD := filepath.Join(skillDir, "SKILL.md")
// Single file open for both description and license
fm := utils.ParseFrontmatterFields(skillMD, []string{"description", "license"})
fm := utils.ParseFrontmatterFields(skillMD, []string{"description", "license", modelInvocationKey})
d := &detailData{
Description: fm["description"],
License: fm["license"],
Files: listSkillFiles(skillDir),
SyncedTargets: m.findSyncedTargets(e),
Description: fm["description"],
License: fm["license"],
Files: listSkillFiles(skillDir),
SyncedTargets: m.findSyncedTargets(e),
ModelInvocationOff: strings.EqualFold(fm[modelInvocationKey], "true"),
}
m.detailCache[key] = d
return d
@@ -1071,6 +1147,9 @@ func renderDetailHeader(e skillEntry, d *detailData, width int) string {
// Line 2: Compact metadata — status · date · targets on one line
var metaParts []string
metaParts = append(metaParts, detailStatusBits(e))
if d.ModelInvocationOff {
metaParts = append(metaParts, theme.Warning().Render("manual only"))
}
if e.InstalledAt != "" {
metaParts = append(metaParts, theme.Dim().Render(e.InstalledAt))
}
@@ -1162,9 +1241,11 @@ 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).
// initialStatus seeds the status chip; the `s` key still cycles from there.
// 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) {
func runListTUI(loadFn listLoadFn, modeLabel, sourcePath, agentsSourcePath string, targets map[string]config.TargetConfig, initialKind resourceKindFilter, initialStatus listStatusFilter) (string, string, string, error) {
model := newListTUIModel(loadFn, nil, 0, modeLabel, sourcePath, agentsSourcePath, targets, initialKind)
model.statusFilter = initialStatus
p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
finalModel, err := p.Run()
if err != nil {
@@ -0,0 +1,117 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
)
const flagLine = "disable-model-invocation: true"
// modelInvocationTUI builds a one-item list TUI over a real SKILL.md and returns its path.
func modelInvocationTUI(t *testing.T, entry skillEntry, skillMD string) (listTUIModel, string) {
t.Helper()
source := t.TempDir()
path := filepath.Join(source, entry.RelPath, "SKILL.md")
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(skillMD), 0644); err != nil {
t.Fatal(err)
}
m := newListTUIModel(nil, []skillItem{{entry: entry}}, 1, "global", source, "", nil, kindAll)
return m, path
}
func pressKey(t *testing.T, m listTUIModel, key string) listTUIModel {
t.Helper()
next, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(key)})
return next.(listTUIModel)
}
func skillMDHasFlag(t *testing.T, path string) bool {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return strings.Contains(string(data), flagLine)
}
func TestModelInvocationKey_LocalSkillTogglesDirectly(t *testing.T) {
m, path := modelInvocationTUI(t, skillEntry{Name: "mine", RelPath: "mine"}, "---\nname: mine\n---\n# Body\n")
m = pressKey(t, m, "M")
if m.confirming {
t.Error("a local skill is yours to edit, so M should not ask")
}
if !skillMDHasFlag(t, path) {
t.Error("SKILL.md should carry the flag after M")
}
}
func TestModelInvocationKey_TrackedSkillAsksFirst(t *testing.T) {
m, path := modelInvocationTUI(t, skillEntry{Name: "theirs", RelPath: "_team/theirs", RepoName: "_team"}, "---\nname: theirs\n---\n# Body\n")
m = pressKey(t, m, "M")
if !m.confirming {
t.Fatal("editing a tracked repo blocks its updates, so M should ask")
}
if skillMDHasFlag(t, path) {
t.Fatal("SKILL.md must stay untouched until confirmed")
}
m = pressKey(t, m, "y")
if m.confirming {
t.Error("confirming should close the prompt and stay in the TUI")
}
if !skillMDHasFlag(t, path) {
t.Error("SKILL.md should carry the flag after confirming")
}
}
func TestModelInvocationKey_TurningBackOnNeverAsks(t *testing.T) {
m, path := modelInvocationTUI(t, skillEntry{Name: "theirs", RelPath: "_team/theirs", RepoName: "_team"}, "---\nname: theirs\n"+flagLine+"\n---\n# Body\n")
m = pressKey(t, m, "M")
if m.confirming {
t.Error("removing the flag restores the file, so there is nothing to warn about")
}
if skillMDHasFlag(t, path) {
t.Error("the flag should be gone")
}
}
func TestModelInvocationKey_IgnoresAgents(t *testing.T) {
agents := t.TempDir()
path := filepath.Join(agents, "helper.md")
orig := "---\nname: helper\n---\n# Agent\n"
os.WriteFile(path, []byte(orig), 0644)
entry := skillEntry{Name: "helper", RelPath: "helper.md", Kind: "agent"}
m := newListTUIModel(nil, []skillItem{{entry: entry}}, 1, "global", t.TempDir(), agents, nil, kindAll)
m = pressKey(t, m, "M")
got, _ := os.ReadFile(path)
if m.confirming || string(got) != orig {
t.Error("agents do not read this key, so M should do nothing")
}
}
func TestRenderDetailHeader_ShowsManualOnlyChip(t *testing.T) {
e := skillEntry{Name: "mine", RelPath: "mine"}
off := renderDetailHeader(e, &detailData{ModelInvocationOff: true}, 60)
on := renderDetailHeader(e, &detailData{}, 60)
if !strings.Contains(off, "manual only") || strings.Contains(on, "manual only") {
t.Errorf("chip should appear only while model invocation is off\n off: %q\n on: %q", off, on)
}
}
+9 -1
View File
@@ -11,7 +11,9 @@ import (
"skillshare/internal/config"
"skillshare/internal/oplog"
"skillshare/internal/projectdir"
"skillshare/internal/ui"
"skillshare/internal/utils"
)
func cmdLog(args []string) error {
@@ -264,7 +266,13 @@ func runLogStats(configPath string, auditOnly bool, f oplog.Filter) error {
}
func isProjectLogConfig(configPath string) bool {
return filepath.Base(filepath.Dir(configPath)) == ".skillshare"
configDir := filepath.Dir(configPath)
if !projectdir.IsName(filepath.Base(configDir)) {
return false
}
// The visible project directory shares its name with the global config
// directory, so exclude the global location by full path.
return !utils.PathsEqual(configDir, config.BaseDir())
}
// runLogTUIDispatch launches the interactive TUI with async log loading.
+32 -2
View File
@@ -47,6 +47,8 @@ var commands = map[string]func([]string) error{
"__ui-restart": cmdUIRestart,
"tui": cmdTUIToggle,
"extras": cmdExtras,
"mcp": cmdMCP,
"plugin": cmdPlugin,
"enable": cmdEnable,
"disable": cmdDisable,
"completion": cmdCompletion,
@@ -214,7 +216,7 @@ func printUsage() {
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", "[agents] [--all]", "Sync skills/agents/extras to targets")
cmd("sync", "[scope] [--all]", "Sync skills/agents/extras/MCP to targets")
cmd("status", "", "Show status of all targets")
fmt.Println()
@@ -254,6 +256,32 @@ func printUsage() {
cmd("extras", "collect <name>", "Collect local files into extras source")
fmt.Println()
// Plugins
fmt.Println("PLUGIN MANAGEMENT")
cmd("plugin list", "", "Browse plugins and native installation state (TUI)")
cmd("plugin discover", "<source>", "Inspect plugins in a directory or Git repository")
cmd("plugin add", "[source]", "Install a complete plugin (guided in a terminal)")
cmd("plugin import", "[native-id]", "Adopt a native install with --from <target>")
cmd("plugin inspect", "<name>", "Show a managed plugin and its target bindings")
cmd("plugin sync", "[name]", "Apply sync selection using native clients")
cmd("plugin check", "[name]", "Check source changes without applying")
cmd("plugin update", "[name]", "Update supported targets from reviewed sources")
cmd("plugin enable", "[name]", "Select targets for the next plugin sync")
cmd("plugin disable", "[name]", "Deselect targets; next sync removes their installs")
cmd("plugin remove", "[name]", "Uninstall managed plugins and remove definitions")
cmd("sync plugins", "[name]", "Alias for plugin sync; excluded from sync --all")
fmt.Println()
// MCP
fmt.Println("MCP")
cmd("mcp add", "[name]", "Add a connection (guided, --url or -- command)")
cmd("mcp edit", "[name]", "Change an endpoint, command or its clients")
cmd("mcp import", "[name]", "Import from a client (--from) or file (--file)")
cmd("mcp list", "", "Browse connections and per-client sync status")
cmd("mcp remove", "[name]", "Remove a connection from the source")
cmd("mcp restore", "[id]", "Restore client entries from a backup")
fmt.Println()
// Git Remote
fmt.Println("GIT REMOTE")
cmd("commit", "", "Create local git commit without pushing")
@@ -285,7 +313,9 @@ func printUsage() {
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 sync --all # Sync skills + agents + extras + MCP")
fmt.Println(" skillshare plugin # Open the plugin manager")
fmt.Println(" skillshare sync plugins --dry-run --json # Preview plugin changes")
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")
+255
View File
@@ -0,0 +1,255 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
"skillshare/internal/mcp"
"skillshare/internal/oplog"
"skillshare/internal/ui"
)
type mcpOptions struct {
name, url, from, file, revision, piExtension string
targets []string
command []string
sync, dryRun, json, replace, noTUI, disabled bool
}
func parseMCPOptions(args []string) (mcpOptions, error) {
var o mcpOptions
for i := 0; i < len(args); i++ {
switch a := args[i]; a {
case "--":
o.command = args[i+1:]
return o, nil
case "--url", "--target", "--from", "--file", "--revision", "--pi-extension":
if i+1 == len(args) {
return o, fmt.Errorf("%s requires a value", a)
}
i++
value := args[i]
switch a {
case "--pi-extension":
o.piExtension = value
case "--url":
o.url = value
case "--target":
o.targets = append(o.targets, value)
case "--from":
o.from = value
case "--file":
o.file = value
case "--revision":
o.revision = value
}
case "--sync":
o.sync = true
case "--dry-run", "-n":
o.dryRun = true
case "--json":
o.json = true
case "--no-tui":
o.noTUI = true
case "--replace":
o.replace = true
case "--disabled":
o.disabled = true
default:
if strings.HasPrefix(a, "-") || o.name != "" {
return o, fmt.Errorf("unknown MCP argument %q", a)
}
o.name = a
}
}
return o, nil
}
func cmdMCP(args []string) (resultErr error) {
defer func() {
if errors.Is(resultErr, errMCPCancelled) {
resultErr = nil
}
}()
helpArgs := args
for i, arg := range args {
if arg == "--" {
helpArgs = args[:i]
break
}
}
if wantsHelp(helpArgs) {
printMCPHelp()
return nil
}
if len(args) == 0 || strings.HasPrefix(args[0], "-") {
args = append([]string{"list"}, args...)
}
sub, args := args[0], args[1:]
service, rest, err := mcpContext(args)
if err != nil {
return err
}
o, err := parseMCPOptions(rest)
if err != nil {
return err
}
if o.disabled && sub != "add" {
return fmt.Errorf("--disabled only applies to mcp add")
}
start := time.Now()
switch sub {
case "list":
if mcpInteractive(o) && !o.dryRun {
return runMCPManager(service)
}
p, err := service.Preview()
if err != nil {
return err
}
return printMCPPlan(p, o.json)
case "add":
return runMCPAdd(service, o)
case "edit":
return runMCPEdit(service, o)
case "import":
return runMCPImport(service, o)
case "remove":
if mcpInteractive(o) {
return mcpRemoveWizard(service, o, terminalMCPPrompts{})
}
if o.name == "" {
return fmt.Errorf("usage: skillshare mcp remove <name> [--sync]")
}
return finishMCPMutation(service, mcp.Mutation{Name: o.name, Remove: true}, o, start)
case "restore":
return runMCPRestore(service, o, terminalMCPPrompts{})
default:
return fmt.Errorf("unknown MCP command %q; run skillshare mcp --help", sub)
}
}
func cmdSyncMCP(args []string) error {
if wantsHelp(args) {
printMCPHelp()
return nil
}
service, rest, err := mcpContext(args)
if err != nil {
return err
}
o, err := parseMCPOptions(rest)
if err != nil {
return err
}
if o.piExtension != "" || o.name != "" || o.url != "" || o.from != "" || o.file != "" || len(o.command) > 0 || len(o.targets) > 0 || o.replace || o.sync || o.disabled {
return fmt.Errorf("sync mcp accepts only --dry-run, --json, --revision and scope flags")
}
if o.dryRun {
p, err := service.Preview()
if err != nil {
return err
}
if err := printMCPPlan(p, o.json); err != nil {
return err
}
if p.Blocked {
return fmt.Errorf("MCP conflicts found; no files changed")
}
return nil
}
start := time.Now()
result, err := service.Apply(o.revision)
logMCPOp(service.ConfigPath, "sync mcp", start, err)
if result != nil {
if outputErr := printMCPResult(result, o.json); outputErr != nil {
return outputErr
}
}
return err
}
func printMCPPlan(p *mcp.Plan, asJSON bool) error {
if asJSON {
return json.NewEncoder(os.Stdout).Encode(p)
}
ui.Info("MCP source: %s", p.SourcePath)
for _, c := range p.Changes {
detail := c.Target
if c.Message != "" {
detail += " — " + c.Message
}
ui.Status(c.Name, c.Action, detail)
}
if len(p.Changes) == 0 {
ui.Info("No MCP servers configured. Run 'skillshare mcp add' to get started.")
}
return nil
}
func printMCPResult(result *mcp.Result, asJSON bool) error {
if asJSON {
return json.NewEncoder(os.Stdout).Encode(result)
}
if result.Plan != nil {
if err := printMCPPlan(result.Plan, false); err != nil {
return err
}
}
for _, id := range result.BackupIDs {
ui.Info("Backup: %s", id)
}
if result.Plan == nil {
ui.Success("MCP source saved. Run 'skillshare sync mcp' when ready.")
} else if !result.Plan.Blocked {
ui.Success("MCP files applied: %d. Reload your Agent after synchronization and complete any required login.", len(result.Applied))
}
return nil
}
func logMCPOp(path, command string, start time.Time, err error) {
if logErr := oplog.Write(path, oplog.OpsFile, oplog.NewEntry(command, statusFromErr(err), time.Since(start))); logErr != nil {
fmt.Fprintln(os.Stderr, "Warning: could not write MCP operation log")
}
}
func printMCPHelp() {
fmt.Println(`Usage: skillshare mcp [command] [options]
Commands:
add [name] Guided setup, or --url URL / -- command args...
edit [name] Interactive editor, or update --url / --target / -- command
import [name] Import --from <client> or --file <JSON/TOML/YAML file>
list Browse connections and per-client sync status (default)
remove [name] Select and remove a source entry; optionally sync removal
restore [id] Browse backups, preview and restore Agent entries
Options:
--pi-extension <package> pi-mcp-adapter or pi-mcp-extension (requires installation in Pi)
--target <client> Receiving client; repeat for multiple clients
--from <client> Native client ID (see mcp documentation for destinations)
--file <path> Native configuration file to import
--url <url> Streamable HTTP endpoint
--disabled Project mode: turn off a server from the Agent's global config
(add NAME --disabled --target opencode; claude, opencode, kilocode, pi)
--sync Save and synchronize (non-interactive default: save only)
--replace Replace an existing source entry; on import, also rewrite
the imported client's entry when it differs
--dry-run, -n Preview without writing
--json Machine-readable, credential-free sync results
--no-tui Disable interactive menus (also honors tui: false)
--revision <id> Require the matching preview revision
--global, -g Global configuration
--project, -p Project configuration
With no command, opens the MCP manager in a terminal; otherwise prints status.
Manager keys: / search, Enter details, a add, i import, e edit, x remove,
s sync, b backups, r refresh, q quit.
JSON and non-TTY output never open a TUI. Scripted edits require a name.
Sync: skillshare sync mcp [--dry-run] [--json] [--no-tui] [-g|-p]
Import does not start MCP servers or copy OAuth credentials.`)
}
+42
View File
@@ -0,0 +1,42 @@
package main
import (
"os"
"skillshare/internal/config"
"skillshare/internal/mcp"
)
func mcpContext(args []string) (*mcp.Service, []string, error) {
// Do not interpret flags belonging to a spawned server after --.
var command []string
for i, arg := range args {
if arg == "--" {
command = args[i:]
args = args[:i]
break
}
}
mode, rest, err := parseModeArgs(args)
if err != nil {
return nil, nil, err
}
rest = append(rest, command...)
cwd, err := os.Getwd()
if err != nil {
return nil, nil, err
}
if mode == modeAuto {
mode = modeGlobal
if projectConfigExists(cwd) {
mode = modeProject
}
}
service := &mcp.Service{ConfigPath: config.ConfigPath(), StateDir: config.StateDir(), ConfigDirs: mcp.ConfigDirsFromEnv()}
if mode == modeProject {
service.ConfigPath = config.ProjectConfigPath(cwd)
service.ProjectRoot = cwd
}
applyModeLabel(mode)
return service, rest, nil
}
+273
View File
@@ -0,0 +1,273 @@
package main
import (
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"time"
"skillshare/internal/mcp"
)
func runMCPEdit(service *mcp.Service, o mcpOptions) error {
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return err
}
interactive := mcpInteractive(o)
if o.name == "" && !interactive {
return fmt.Errorf("usage: skillshare mcp edit <name> --url URL, --target CLIENT or -- command args; omit options in a terminal for the editor")
}
prompts := terminalMCPPrompts{}
name, err := chooseMCPServer(source, o.name, "Edit which MCP server?", prompts)
if err != nil {
return err
}
server := source.Servers[name]
if o.url != "" && len(o.command) > 0 {
return fmt.Errorf("choose either --url or -- command args")
}
if o.piExtension != "" || o.url != "" || len(o.command) > 0 || o.targets != nil {
server = patchMCPServer(server, o)
if err := source.CheckUnchanged(); err != nil {
return err
}
o.replace = true
return finishMCPMutation(service, mcp.Mutation{Name: name, Server: &server, Replace: true}, o, time.Now())
}
if !interactive {
return fmt.Errorf("provide --url, --target or -- command args with --no-tui/--json; omit --no-tui for the editor")
}
server, err = editMCPDraft(service, name, server, source.Targets, prompts)
if err != nil {
return err
}
if err := source.CheckUnchanged(); err != nil {
return err
}
return reviewMCPMutations(service, []mcp.Mutation{{Name: name, Server: &server, Replace: true}}, o, prompts)
}
func patchMCPServer(server mcp.Server, o mcpOptions) mcp.Server {
if o.piExtension != "" {
server.PiExtension = o.piExtension
}
if o.url != "" || len(o.command) > 0 {
// A connection makes this a server of its own, no longer a switch for a global one.
server.Disabled = false
}
if o.url != "" {
server.Command = ""
server.Args = nil
server.Env = nil
server.URL = o.url
server.Transport = ""
}
if len(o.command) > 0 {
server.URL = ""
server.Headers = nil
server.BearerToken = nil
server.Command = o.command[0]
server.Args = o.command[1:]
server.Transport = ""
}
if o.targets != nil {
server.Targets = slices.Clone(o.targets)
}
return server
}
func editMCPDraft(service *mcp.Service, name string, server mcp.Server, defaults []string, prompts mcpPrompts) (mcp.Server, error) {
// Edits are a private draft; Esc anywhere leaves the source untouched.
server.Env, server.Headers = maps.Clone(server.Env), maps.Clone(server.Headers)
for {
targets := server.Targets
if targets == nil {
targets = defaults
}
items := []checklistItemData{
{label: "Connection", desc: mcpConnectionSummary(server)},
{label: "Arguments", desc: "Local command arguments, one per line or a JSON array"},
{label: "Environment variables", desc: fmt.Sprintf("%d variables (values hidden)", len(server.Env))},
{label: "HTTP headers", desc: fmt.Sprintf("%d headers (values hidden)", len(server.Headers))},
{label: "Bearer token", desc: "Environment variable name only"},
{label: "Targets", desc: strings.Join(targets, ", ")},
{label: "Review changes", desc: "Preview before saving"},
{label: "Pi extension", desc: server.PiExtension},
}
selected, err := chooseMCP(prompts, checklistConfig{title: "Edit MCP: " + name, header: "Esc cancels this draft without saving.", items: items, singleSelect: true})
if err != nil {
return server, err
}
switch selected[0] {
case 0:
kind, err := chooseMCP(prompts, checklistConfig{title: "Connection type", items: []checklistItemData{{label: "Local command (stdio)", preSelected: server.Command != ""}, {label: "Remote URL (Streamable HTTP)", preSelected: server.URL != ""}}, singleSelect: true})
if err != nil {
return server, err
}
if kind[0] == 0 {
command, err := prompts.text("Executable only (for example npx); edit arguments separately", server.Command)
if err != nil {
return server, err
}
if command == "" {
continue
}
server.URL, server.Command, server.Transport = "", command, ""
server.Headers, server.BearerToken = nil, nil
} else {
url, err := prompts.text("MCP URL (https://…/mcp)", server.URL)
if err != nil {
return server, err
}
if url == "" {
continue
}
server = patchMCPServer(server, mcpOptions{url: url})
}
case 1:
if server.Command == "" {
fmt.Println("Arguments apply to local commands. Change the connection type first.")
continue
}
initial, _ := json.Marshal(server.Args)
if server.Args == nil {
initial = []byte("[]")
}
text, err := prompts.text("Arguments: one per line, or a JSON array; empty clears all arguments", string(initial))
if err != nil {
return server, err
}
args, err := parseMCPArgumentInput(text)
if err != nil {
fmt.Println(err)
continue
}
server.Args = args
case 2:
if server.Command == "" {
fmt.Println("Environment variables apply to local commands.")
continue
}
server.Env, err = editMCPValues("Environment variables", server.Env, prompts)
case 3:
if server.URL == "" {
fmt.Println("HTTP headers apply to remote URLs.")
continue
}
server.Headers, err = editMCPValues("HTTP headers", server.Headers, prompts)
case 4:
if server.URL == "" {
fmt.Println("Bearer tokens apply to remote URLs.")
continue
}
initial := ""
if server.BearerToken != nil {
initial = server.BearerToken.FromEnv
}
var name string
name, err = prompts.text("Bearer token environment variable (for example MCP_TOKEN); empty removes it", initial)
if name == "" {
server.BearerToken = nil
} else {
server.BearerToken = &mcp.Value{FromEnv: name}
}
case 5:
servers := []mcp.Server{server}
server.Targets, err = chooseMCPTargets(service, servers, targets, prompts)
server.PiExtension = servers[0].PiExtension
case 7:
server.PiExtension, err = choosePiExtension(server.PiExtension, prompts)
case 6:
if err := server.Validate(name); err != nil {
fmt.Println(err)
continue
}
return server, nil
}
if err != nil {
return server, err
}
}
}
func parseMCPArgumentInput(text string) ([]string, error) {
if text == "" {
return nil, nil
}
if strings.HasPrefix(strings.TrimSpace(text), "[") {
var args []string
if err := json.Unmarshal([]byte(text), &args); err != nil {
return nil, fmt.Errorf("arguments must be a JSON array of strings or one literal argument per line")
}
return args, nil
}
return strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n"), nil
}
func editMCPValues(title string, values map[string]mcp.Value, prompts mcpPrompts) (map[string]mcp.Value, error) {
values = maps.Clone(values)
if values == nil {
values = map[string]mcp.Value{}
}
for {
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
slices.Sort(keys)
items := []checklistItemData{{label: "Done"}, {label: "Add variable/header"}}
for _, key := range keys {
items = append(items, checklistItemData{label: key, desc: "Edit or remove (value hidden)"})
}
selected, err := chooseMCP(prompts, checklistConfig{title: title, items: items, singleSelect: true})
if err != nil {
return values, err
}
if selected[0] == 0 {
return values, nil
}
key := ""
if selected[0] >= 2 {
key = keys[selected[0]-2]
} else {
key, err = prompts.text("Variable/header name", "")
if err != nil {
return values, err
}
if key == "" {
continue
}
if _, exists := values[key]; exists {
fmt.Println("That name already exists; select it to edit.")
continue
}
}
kind, err := chooseMCP(prompts, checklistConfig{title: key + ": value source", items: []checklistItemData{{label: "Environment reference", desc: "Recommended for credentials; only the variable name is saved"}, {label: "Literal value", desc: "For non-secret values only"}, {label: "Remove"}}, singleSelect: true})
if err != nil {
return values, err
}
if kind[0] == 2 {
delete(values, key)
continue
}
initial, label := values[key].FromEnv, "Environment variable name (not its secret value)"
if kind[0] == 1 {
initial, label = values[key].Literal, "Literal non-secret value"
}
text, err := prompts.text(label, initial)
if err != nil {
return values, err
}
if kind[0] == 0 {
if text == "" {
continue
}
values[key] = mcp.Value{FromEnv: text}
} else {
values[key] = mcp.Value{Literal: text}
}
}
}
+160
View File
@@ -0,0 +1,160 @@
package main
import (
"encoding/json"
"fmt"
"os"
"slices"
"strings"
"time"
"skillshare/internal/mcp"
)
func runMCPAdd(service *mcp.Service, o mcpOptions) error {
if o.disabled && (o.name == "" || o.url != "" || len(o.command) > 0) {
return fmt.Errorf("--disabled takes a name and --target only: it turns off a server the Agent already has")
}
if o.name == "" || o.url == "" && len(o.command) == 0 && !o.disabled {
if !mcpInteractive(o) {
return fmt.Errorf("provide a name and --url URL or -- command args; run without flags in a terminal for guided setup")
}
return mcpAddWizard(service, o)
}
server := mcp.Server{URL: o.url, Targets: o.targets, PiExtension: o.piExtension, Disabled: o.disabled}
if len(o.command) > 0 {
server.Command, server.Args = o.command[0], o.command[1:]
}
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return err
}
if _, exists := source.Servers[o.name]; exists && !o.replace {
return fmt.Errorf("MCP %s already exists; use --replace to explicitly replace its source definition", o.name)
}
return finishMCPMutation(service, mcp.Mutation{Name: o.name, Server: &server}, o, time.Now())
}
func finishMCPMutation(service *mcp.Service, mutation mcp.Mutation, o mcpOptions, start time.Time) error {
mutation.Replace = o.replace
if o.dryRun {
p, err := service.PreviewMutation(mutation)
if err != nil {
return err
}
if err := printMCPPlan(p, o.json); err != nil {
return err
}
if p.Blocked {
return fmt.Errorf("MCP conflicts found; no files changed")
}
return nil
}
result, err := service.Mutate(mutation, o.revision, o.sync)
logMCPOp(service.ConfigPath, "mcp configure", start, err)
if result != nil {
if outputErr := printMCPResult(result, o.json); outputErr != nil {
return outputErr
}
}
return err
}
func runMCPImport(service *mcp.Service, o mcpOptions) error {
if o.from == "" && o.file == "" {
if !mcpInteractive(o) {
return fmt.Errorf("import requires --from <client> or --file <path>")
}
items := mcpTargetItems(service, nil)
selected, err := runChecklistTUI(checklistConfig{title: "Import MCP from which Agent?", singleSelect: true, items: items})
if err != nil {
return err
}
if len(selected) == 0 {
return nil
}
o.from = items[selected[0]].label
}
var candidates []mcp.Candidate
var err error
if o.file != "" {
data, readErr := os.ReadFile(o.file)
if readErr != nil {
return readErr
}
format := o.from
if format == "" && strings.HasSuffix(o.file, ".toml") {
format = "codex"
}
candidates, err = mcp.Import(format, data, o.name)
} else {
candidates, err = service.ImportClient(o.from)
}
if err != nil {
return err
}
if o.name == "" {
if !mcpInteractive(o) {
return json.NewEncoder(os.Stdout).Encode(candidates)
}
return mcpBatchImportWizard(service, candidates, o, terminalMCPPrompts{})
}
for _, c := range candidates {
if c.Name != o.name {
continue
}
if len(c.Problems) > 0 {
return fmt.Errorf("cannot import %s: %s", c.Name, strings.Join(c.Problems, "; "))
}
if len(c.Warnings) > 0 && !o.json {
for _, w := range c.Warnings {
fmt.Println(w)
}
}
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return err
}
if _, exists := source.Servers[c.Name]; exists && !o.replace {
return fmt.Errorf("MCP source entry exists; use --replace")
}
c.Server.Targets = o.targets
c.Server.PiExtension = o.piExtension
selectedTargets := c.Server.Targets
if selectedTargets == nil {
selectedTargets = source.Targets
}
mutation, err := mcpImportMutation(service, c, selectedTargets, o)
if err != nil {
return err
}
return finishMCPMutation(service, mutation, o, time.Now())
}
return fmt.Errorf("MCP server %q not found in import", o.name)
}
// mcpImportMutation adopts the imported client's own entry when it already
// matches and rewrites it only with --replace: a converted entry (a literal
// token becoming an environment reference) would otherwise silently change an
// Agent that works today.
func mcpImportMutation(service *mcp.Service, c mcp.Candidate, targets []string, o mcpOptions) (mcp.Mutation, error) {
mutation := mcp.Mutation{Name: c.Name, Server: &c.Server, Replace: o.replace}
if c.From == "" || !slices.Contains(targets, c.From) {
return mutation, nil
}
if o.replace {
mutation.Resolutions = []mcp.Resolution{{Target: c.From, Name: c.Name, Action: "replace"}}
return mutation, nil
}
mutation.Resolutions = []mcp.Resolution{{Target: c.From, Name: c.Name, Action: "adopt"}}
p, err := service.PreviewMutation(mutation)
if err != nil {
return mutation, err
}
for _, change := range p.Changes {
if change.Target == c.From && change.Name == c.Name && change.Action == "conflict" {
return mutation, fmt.Errorf("%s already has %s with different settings, such as a literal token that import turned into an environment reference; set any reported variables, then rerun with --replace to rewrite it, or leave %s out of --target", c.From, c.Name, c.From)
}
}
return mutation, nil
}
+68
View File
@@ -0,0 +1,68 @@
package main
import (
"fmt"
"strings"
"skillshare/internal/mcp"
)
func mcpBatchImportWizard(service *mcp.Service, candidates []mcp.Candidate, o mcpOptions, prompts mcpPrompts) error {
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return err
}
eligible := []mcp.Candidate{}
items := []checklistItemData{}
for _, candidate := range candidates {
if len(candidate.Problems) > 0 {
fmt.Printf("Skipped %s: %s\n", candidate.Name, strings.Join(candidate.Problems, "; "))
continue
}
if _, exists := source.Servers[candidate.Name]; exists && !o.replace {
fmt.Printf("Skipped %s: already in source (use --replace to replace it)\n", candidate.Name)
continue
}
eligible = append(eligible, candidate)
items = append(items, checklistItemData{label: candidate.Name, desc: mcpConnectionSummary(candidate.Server)})
}
if len(items) == 0 {
return fmt.Errorf("no new importable MCP servers")
}
selected, err := chooseMCP(prompts, checklistConfig{title: "Choose MCP servers to import", header: "Space toggles · a selects all · Enter continues · Esc cancels", items: items, itemName: "server"})
if err != nil {
return err
}
servers := make([]mcp.Server, 0, len(selected))
for _, i := range selected {
server := eligible[i].Server
server.PiExtension = o.piExtension
servers = append(servers, server)
}
initial := o.targets
if initial == nil {
initial = source.Targets
}
targets, err := chooseMCPTargets(service, servers, initial, prompts)
if err != nil {
return err
}
mutations := make([]mcp.Mutation, 0, len(selected))
for position, i := range selected {
candidate := eligible[i]
candidate.Server.PiExtension = servers[position].PiExtension
for _, warning := range candidate.Warnings {
fmt.Printf("%s: %s\n", candidate.Name, warning)
}
candidate.Server.Targets = targets
mutation, err := mcpImportMutation(service, candidate, targets, o)
if err != nil {
return err
}
mutations = append(mutations, mutation)
}
if err := source.CheckUnchanged(); err != nil {
return err
}
return reviewMCPMutations(service, mutations, o, prompts)
}
+301
View File
@@ -0,0 +1,301 @@
package main
import (
"errors"
"fmt"
"os"
"slices"
"strconv"
"strings"
"time"
"golang.org/x/term"
"skillshare/internal/mcp"
)
var errMCPCancelled = errors.New("MCP operation cancelled; no changes saved")
// The same opt-out and terminal rules as skills, plus stdin for input prompts.
func mcpInteractive(o mcpOptions) bool {
return !o.json && shouldLaunchTUI(o.noTUI, nil) && term.IsTerminal(int(os.Stdin.Fd()))
}
type mcpPrompts interface {
choose(checklistConfig) ([]int, error)
text(title, initial string) (string, error)
review(string, *mcp.Plan) error
}
type terminalMCPPrompts struct{}
func (terminalMCPPrompts) choose(c checklistConfig) ([]int, error) { return runChecklistTUI(c) }
func (terminalMCPPrompts) text(title, initial string) (string, error) {
return promptMCPText(title, initial)
}
func chooseMCP(p mcpPrompts, c checklistConfig) ([]int, error) {
selected, err := p.choose(c)
if err != nil {
return nil, err
}
if len(selected) == 0 {
return nil, errMCPCancelled
}
return selected, nil
}
func mcpServerNames(source *mcp.Source) []string {
names := make([]string, 0, len(source.Servers))
for name := range source.Servers {
names = append(names, name)
}
slices.Sort(names)
return names
}
func chooseMCPServer(source *mcp.Source, name, title string, p mcpPrompts) (string, error) {
if name != "" {
if _, ok := source.Servers[name]; !ok {
return "", fmt.Errorf("MCP server %q not found", name)
}
return name, nil
}
names := mcpServerNames(source)
if len(names) == 0 {
return "", fmt.Errorf("no MCP servers configured; run skillshare mcp add")
}
items := make([]checklistItemData, len(names))
for i, name := range names {
items[i] = checklistItemData{label: name, desc: mcpConnectionSummary(source.Servers[name])}
}
selected, err := chooseMCP(p, checklistConfig{title: title, header: "Source: " + source.Path, items: items, singleSelect: true, itemName: "server"})
if err != nil {
return "", err
}
return names[selected[0]], nil
}
func chooseMCPTargets(service *mcp.Service, servers []mcp.Server, initial []string, p mcpPrompts) ([]string, error) {
items := mcpTargetItems(service, nil)
available := items[:0]
for _, item := range items {
compatible := true
for _, server := range servers {
if item.label == "pi" && server.PiExtension == "" {
server.PiExtension = "pi-mcp-adapter"
}
if _, err := mcp.Render(item.label, server); err != nil {
compatible = false
break
}
}
if compatible {
item.preSelected = slices.Contains(initial, item.label)
available = append(available, item)
}
}
if len(available) == 0 {
return nil, fmt.Errorf("no compatible MCP clients in this scope")
}
selected, err := chooseMCP(p, checklistConfig{title: "Which Agents should receive these connections?", header: "Only clients compatible with every selected server are shown.", items: available, itemName: "target"})
if err != nil {
return nil, err
}
targets := make([]string, 0, len(selected))
for _, i := range selected {
targets = append(targets, available[i].label)
}
if slices.Contains(targets, "pi") {
initial := ""
for _, server := range servers {
if server.PiExtension != "" {
initial = server.PiExtension
break
}
}
extension, err := choosePiExtension(initial, p)
if err != nil {
return nil, err
}
for i := range servers {
servers[i].PiExtension = extension
if _, err := mcp.Render("pi", servers[i]); err != nil {
return nil, err
}
}
}
return targets, nil
}
func reviewMCPMutations(service *mcp.Service, mutations []mcp.Mutation, o mcpOptions, prompts mcpPrompts) error {
p, err := service.PreviewMutations(mutations)
if err != nil {
return err
}
if o.revision != "" && o.revision != p.Revision {
return fmt.Errorf("MCP configuration changed since preview; preview again")
}
if err := printMCPPlan(p, o.json); err != nil {
return err
}
if o.dryRun {
if p.Blocked {
return fmt.Errorf("MCP conflicts found; no files changed")
}
return nil
}
var summary strings.Builder
for _, mutation := range mutations {
action := "Save"
if mutation.Remove {
action = "Remove"
}
fmt.Fprintf(&summary, "%s source server: %s\n", action, mutation.Name)
}
if err := prompts.review(summary.String(), p); err != nil {
return err
}
choices := []checklistItemData{{label: "Save only", desc: "Update the source; leave Agent files unchanged"}}
if p.Blocked {
for _, mutation := range mutations {
if len(mutation.Resolutions) > 0 {
return fmt.Errorf("resolve MCP conflicts before importing; no settings saved")
}
}
} else {
choices = append([]checklistItemData{{label: "Save and sync", desc: "Apply the previewed changes to Agent files"}}, choices...)
}
selected, err := chooseMCP(prompts, checklistConfig{title: "Review complete — save these MCP changes?", items: choices, singleSelect: true})
if err != nil {
return err
}
sync := !p.Blocked && selected[0] == 0
start := time.Now()
result, err := service.MutateBatch(mutations, p.Revision, sync)
logMCPOp(service.ConfigPath, "mcp configure", start, err)
if result != nil {
if outputErr := printMCPResult(result, false); outputErr != nil {
return outputErr
}
}
return err
}
func mcpRemoveWizard(service *mcp.Service, o mcpOptions, prompts mcpPrompts) error {
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return err
}
name, err := chooseMCPServer(source, o.name, "Remove which MCP server?", prompts)
if err != nil {
return err
}
if err := source.CheckUnchanged(); err != nil {
return err
}
fmt.Printf("Remove %s from the source. Sync also removes its managed Agent entries.\n", name)
return reviewMCPMutations(service, []mcp.Mutation{{Name: name, Remove: true}}, o, prompts)
}
func mcpBackupLabel(b mcp.BackupInfo) string {
stamp, _, _ := strings.Cut(b.ID, "-")
if nanos, err := strconv.ParseInt(stamp, 10, 64); err == nil {
return time.Unix(0, nanos).Local().Format("2006-01-02 15:04:05") + " · " + b.ID
}
return b.ID
}
func runMCPRestore(service *mcp.Service, o mcpOptions, prompts mcpPrompts) error {
interactive := mcpInteractive(o)
if o.name == "" {
if !interactive {
return fmt.Errorf("usage: skillshare mcp restore <id> [--dry-run]; omit the ID in an interactive terminal to browse backups")
}
backups, err := service.Backups()
if err != nil {
return err
}
if len(backups) == 0 {
return fmt.Errorf("no MCP backups for this configuration")
}
targets := []string{}
for _, b := range backups {
if !slices.Contains(targets, b.Target) {
targets = append(targets, b.Target)
}
}
slices.Sort(targets)
items := make([]checklistItemData, len(targets))
for i, target := range targets {
items[i] = checklistItemData{label: target}
}
selected, err := chooseMCP(prompts, checklistConfig{title: "Restore backups for which Agent?", items: items, singleSelect: true})
if err != nil {
return err
}
versions := []mcp.BackupInfo{}
items = nil
for _, b := range backups {
if b.Target == targets[selected[0]] {
versions = append(versions, b)
items = append(items, checklistItemData{label: mcpBackupLabel(b), desc: b.Path})
}
}
selected, err = chooseMCP(prompts, checklistConfig{title: "Choose an MCP backup (newest first)", items: items, singleSelect: true})
if err != nil {
return err
}
o.name = versions[selected[0]].ID
}
p, err := service.PreviewRestore(o.name)
if err != nil {
return err
}
if o.revision != "" && o.revision != p.Revision {
return fmt.Errorf("MCP configuration changed since preview; preview again")
}
if o.dryRun || interactive {
if err := printMCPPlan(p, o.json); err != nil {
return err
}
}
if p.Blocked {
return fmt.Errorf("MCP restore conflicts found; no files changed")
}
if o.dryRun {
return nil
}
if interactive {
if err := prompts.review("Restore backup: "+o.name, p); err != nil {
return err
}
_, err := chooseMCP(prompts, checklistConfig{title: "Restore the previewed Agent entries?", header: "The source definition stays unchanged. Esc cancels.", items: []checklistItemData{{label: "Restore backup", desc: o.name}}, singleSelect: true})
if err != nil {
return err
}
}
start := time.Now()
result, err := service.Restore(o.name, p.Revision)
logMCPOp(service.ConfigPath, "mcp restore", start, err)
if result != nil {
if outputErr := printMCPResult(result, o.json); outputErr != nil {
return outputErr
}
}
return err
}
func choosePiExtension(initial string, p mcpPrompts) (string, error) {
packages := []string{"pi-mcp-adapter", "pi-mcp-extension"}
items := []checklistItemData{
{label: packages[0], desc: "On-demand tools; supports environment-backed headers", preSelected: initial == packages[0]},
{label: packages[1], desc: "Direct tools; start with /mcp:start <server>; no header interpolation", preSelected: initial == packages[1]},
}
selected, err := chooseMCP(p, checklistConfig{title: "Which MCP extension do you use in Pi?", header: "Install ONE with pi install npm:<package>. Sync only writes config; it does not install or verify the extension. Docs: https://pi.dev/packages/pi-mcp-adapter and https://pi.dev/packages/pi-mcp-extension", items: items, singleSelect: true, itemName: "extension"})
if err != nil {
return "", err
}
return packages[selected[0]], nil
}
+273
View File
@@ -0,0 +1,273 @@
package main
import (
"errors"
"fmt"
"net/url"
"slices"
"strings"
"time"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"skillshare/internal/mcp"
"skillshare/internal/theme"
)
type mcpListItem struct {
name, description, detail string
}
func (i mcpListItem) Title() string { return i.name }
func (i mcpListItem) Description() string { return i.description }
func (i mcpListItem) FilterValue() string { return i.name + " " + i.description }
// Lists never expose arguments or credential values, including URL queries.
func mcpConnectionSummary(server mcp.Server) string {
if server.Disabled {
return "off in this project"
}
if server.Command != "" {
return "stdio · " + server.Command
}
u, err := url.Parse(server.URL)
if err != nil {
return "http"
}
u.User, u.RawQuery, u.Fragment = nil, "", ""
return "http · " + u.String()
}
func mcpListItems(source *mcp.Source, plan *mcp.Plan) []list.Item {
items := []list.Item{}
for _, name := range mcpServerNames(source) {
server := source.Servers[name]
targets := server.Targets
if targets == nil {
targets = source.Targets
}
status := []string{}
if plan != nil {
for _, change := range plan.Changes {
if change.Name == name {
status = append(status, change.Target+": "+change.Action)
}
}
}
if len(status) == 0 {
status = []string{"not synchronized / no preview"}
}
description := mcpConnectionSummary(server) + " · " + strings.Join(targets, ", ") + " · " + strings.Join(status, "; ")
var detail strings.Builder
fmt.Fprintf(&detail, "%s\n\n%s\nArguments: %d (values hidden)\nTargets: %s\n\nSync status\n%s\n", name, mcpConnectionSummary(server), len(server.Args), strings.Join(targets, ", "), strings.Join(status, "\n"))
for _, group := range []struct {
title string
values map[string]mcp.Value
}{{"Environment", server.Env}, {"Headers", server.Headers}} {
keys := make([]string, 0, len(group.values))
for key := range group.values {
keys = append(keys, key)
}
slices.Sort(keys)
if len(keys) > 0 {
fmt.Fprintf(&detail, "\n%s (values hidden)\n%s\n", group.title, strings.Join(keys, "\n"))
}
}
if server.BearerToken != nil {
detail.WriteString("\nBearer token: environment reference (value hidden)\n")
}
fmt.Fprintf(&detail, "\nSource: %s", source.Path)
items = append(items, mcpListItem{name: name, description: description, detail: detail.String()})
}
return items
}
type mcpListModel struct {
list list.Model
viewport viewport.Model
width, height int
showDetail bool
action, name, notice string
}
func newMCPListModel(source *mcp.Source, plan *mcp.Plan, scope, notice string) mcpListModel {
l := list.New(mcpListItems(source, plan), newPrefixDelegate(true), 80, 18)
l.Title = "MCP connections (" + scope + ")"
l.Styles.Title = theme.Title()
l.SetShowHelp(false)
l.SetStatusBarItemName("server", "servers")
applyTUIFilterStyle(&l)
return mcpListModel{list: l, viewport: viewport.New(76, 18), width: 80, height: 24, notice: notice}
}
func (m mcpListModel) Init() tea.Cmd { return nil }
func (m mcpListModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
m.list.SetSize(msg.Width, max(5, msg.Height-5))
m.viewport.Width, m.viewport.Height = max(10, msg.Width-4), max(3, msg.Height-5)
if item, ok := m.list.SelectedItem().(mcpListItem); ok {
m.viewport.SetContent(hardWrapContent(item.detail, m.viewport.Width))
}
return m, nil
case tea.KeyMsg:
if m.showDetail {
if msg.String() == "esc" || msg.String() == "enter" {
m.showDetail = false
return m, nil
}
if msg.String() == "q" || msg.String() == "ctrl+c" {
return m, tea.Quit
}
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
if m.list.FilterState() == list.Filtering {
break
}
switch msg.String() {
case "q", "ctrl+c":
return m, tea.Quit
case "esc":
if m.list.FilterState() == list.FilterApplied {
m.list.ResetFilter()
return m, nil
}
return m, tea.Quit
case "enter":
if item, ok := m.list.SelectedItem().(mcpListItem); ok {
m.showDetail = true
m.viewport.SetContent(hardWrapContent(item.detail, m.viewport.Width))
m.viewport.GotoTop()
}
return m, nil
case "a", "A":
m.action = "add"
case "i", "I":
m.action = "import"
case "e", "E":
m.action = "edit"
case "x", "X":
m.action = "remove"
case "s":
m.action = "sync"
case "b":
m.action = "restore"
case "r":
m.action = "refresh"
}
if m.action != "" {
if item, ok := m.list.SelectedItem().(mcpListItem); ok {
m.name = item.name
}
if (m.action == "edit" || m.action == "remove") && m.name == "" {
m.action = ""
return m, nil
}
return m, tea.Quit
}
}
var cmd tea.Cmd
m.list, cmd = m.list.Update(msg)
return m, cmd
}
func (m mcpListModel) View() string {
if m.showDetail {
return "\n" + m.viewport.View() + "\n" + formatHelpBar("↑↓ scroll Esc back q quit")
}
notice := m.notice
if len(m.list.Items()) == 0 {
notice = "No MCP servers. Press a to add or i to import."
}
return m.list.View() + "\n" + theme.Dim().Render(hardWrapContent(notice, max(10, m.width-4))) + "\n" + formatHelpBar("/ search Enter details a add i import e edit x remove") + "\n" + formatHelpBar("s sync b backups r refresh q quit")
}
func runMCPManager(service *mcp.Service) error {
notice := ""
for {
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return err
}
plan, previewErr := service.Preview()
if previewErr != nil {
notice = previewErr.Error()
}
scope := "global"
if service.ProjectRoot != "" {
scope = "project"
}
model := newMCPListModel(source, plan, scope, notice)
result, err := tea.NewProgram(model, tea.WithAltScreen()).Run()
if err != nil {
return err
}
m := result.(mcpListModel)
if m.action == "" {
return nil
}
prompts := terminalMCPPrompts{}
switch m.action {
case "add":
err = runMCPAdd(service, mcpOptions{})
case "import":
err = runMCPImport(service, mcpOptions{})
case "edit":
err = runMCPEdit(service, mcpOptions{name: m.name})
case "remove":
err = mcpRemoveWizard(service, mcpOptions{name: m.name}, prompts)
case "restore":
err = runMCPRestore(service, mcpOptions{}, prompts)
case "sync":
err = mcpSyncWizard(service, prompts)
}
notice = ""
if errors.Is(err, errMCPCancelled) {
notice = "Cancelled; no draft changes saved."
} else if err != nil {
notice = err.Error()
}
}
}
func mcpSyncWizard(service *mcp.Service, prompts mcpPrompts) error {
p, err := service.Preview()
if err != nil {
return err
}
if err := printMCPPlan(p, false); err != nil {
return err
}
if p.Blocked {
return fmt.Errorf("MCP conflicts found; import the affected entries before syncing")
}
pending := false
for _, change := range p.Changes {
pending = pending || change.Action != "unchanged"
}
if !pending {
return nil
}
if err := prompts.review("Sync managed Agent entries", p); err != nil {
return err
}
_, err = chooseMCP(prompts, checklistConfig{title: "Apply these MCP changes?", items: []checklistItemData{{label: "Sync now", desc: "Only managed Agent entries will be changed; Esc cancels"}}, singleSelect: true})
if err != nil {
return err
}
start := time.Now()
result, err := service.Apply(p.Revision)
logMCPOp(service.ConfigPath, "sync mcp", start, err)
if result != nil {
if outputErr := printMCPResult(result, false); outputErr != nil {
return outputErr
}
}
return err
}
+56
View File
@@ -0,0 +1,56 @@
package main
import (
"skillshare/internal/mcp"
"testing"
)
func TestMCPPiCLI(t *testing.T) {
s := mcpTUIService(t)
o, err := parseMCPOptions([]string{"docs", "--target", "pi", "--pi-extension", "pi-mcp-extension", "--url", "https://example.com/mcp", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err = runMCPAdd(s, o); err != nil {
t.Fatal(err)
}
source, err := mcp.LoadSource(s.ConfigPath)
if err != nil || source.Servers["docs"].PiExtension != "pi-mcp-extension" {
t.Fatalf("%+v %v", source, err)
}
o, err = parseMCPOptions([]string{"docs", "--pi-extension", "pi-mcp-adapter", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err = runMCPEdit(s, o); err != nil {
t.Fatal(err)
}
source, err = mcp.LoadSource(s.ConfigPath)
if err != nil || source.Servers["docs"].PiExtension != "pi-mcp-adapter" {
t.Fatalf("%+v %v", source, err)
}
}
type piPrompts struct{ scriptedMCPPrompts }
func (p *piPrompts) choose(c checklistConfig) ([]int, error) {
for i, item := range c.items {
if item.label == "pi" || item.label == "pi-mcp-extension" {
return []int{i}, nil
}
}
return nil, errMCPCancelled
}
func TestMCPPiTUI(t *testing.T) {
s := mcpTUIService(t)
servers := []mcp.Server{{Command: "echo"}, {URL: "https://example.com/mcp"}}
targets, err := chooseMCPTargets(s, servers, nil, &piPrompts{})
if err != nil || len(targets) != 1 || targets[0] != "pi" {
t.Fatalf("%v %v", targets, err)
}
for _, server := range servers {
if server.PiExtension != "pi-mcp-extension" {
t.Fatal("extension selection lost")
}
}
}
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/textarea"
tea "github.com/charmbracelet/bubbletea"
"skillshare/internal/mcp"
)
type mcpInput struct {
title string
input textarea.Model
cancelled bool
}
func (m mcpInput) Init() tea.Cmd { return textarea.Blink }
func (m mcpInput) View() string {
return m.title + "\n" + m.input.View() + "\nCtrl+D: continue · Esc: cancel\n"
}
func (m mcpInput) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if key, ok := msg.(tea.KeyMsg); ok {
switch key.String() {
case "ctrl+d":
return m, tea.Quit
case "esc", "ctrl+c":
m.cancelled = true
return m, tea.Quit
}
}
var cmd tea.Cmd
m.input, cmd = m.input.Update(msg)
return m, cmd
}
func promptMCPText(title, initial string) (string, error) {
input := textarea.New()
input.SetWidth(76)
input.SetHeight(6)
input.CharLimit = 1024 * 1024
input.SetValue(initial)
input.Focus()
result, err := tea.NewProgram(mcpInput{title: title, input: input}).Run()
if err != nil {
return "", err
}
m := result.(mcpInput)
if m.cancelled {
return "", errMCPCancelled
}
return strings.TrimSpace(m.input.Value()), nil
}
func mcpTargetItems(service *mcp.Service, server *mcp.Server) []checklistItemData {
items := []checklistItemData{}
paths := service.ClientPaths()
for _, name := range mcp.Targets {
if paths[name] == "" {
continue
}
if server != nil {
if _, err := mcp.Render(name, *server); err != nil {
continue
}
}
items = append(items, checklistItemData{label: name})
}
return items
}
func mcpAddWizard(service *mcp.Service, o mcpOptions) error {
input, err := promptMCPText("Paste an MCP URL or server JSON (nothing will be executed)", o.url)
if err != nil {
return err
}
name := o.name
if name == "" {
name, err = promptMCPText("Choose a name for this MCP", "")
if err != nil {
return err
}
}
candidate := mcp.Candidate{Name: name, Server: mcp.Server{URL: input}}
if strings.HasPrefix(input, "{") {
candidates, err := mcp.Import("", []byte(input), name)
if err != nil {
return err
}
if len(candidates) != 1 {
return fmt.Errorf("paste one server at a time, or use mcp import --file to select a server")
}
candidate = candidates[0]
}
return mcpCandidateWizard(service, candidate, o)
}
func mcpCandidateWizard(service *mcp.Service, c mcp.Candidate, o mcpOptions) error {
if len(c.Problems) > 0 {
return fmt.Errorf("cannot import: %s", strings.Join(c.Problems, "; "))
}
for _, warning := range c.Warnings {
fmt.Println(warning)
}
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return err
}
initial := o.targets
if initial == nil {
initial = source.Targets
}
prompts := terminalMCPPrompts{}
c.Server.PiExtension = o.piExtension
servers := []mcp.Server{c.Server}
c.Server.Targets, err = chooseMCPTargets(service, servers, initial, prompts)
c.Server.PiExtension = servers[0].PiExtension
if err != nil {
return err
}
mutation, err := mcpImportMutation(service, c, c.Server.Targets, o)
if err != nil {
return err
}
if err := source.CheckUnchanged(); err != nil {
return err
}
return reviewMCPMutations(service, []mcp.Mutation{mutation}, o, prompts)
}
+67
View File
@@ -0,0 +1,67 @@
package main
import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"skillshare/internal/mcp"
)
type mcpReviewModel struct {
viewport viewport.Model
content string
accepted bool
}
func (m mcpReviewModel) Init() tea.Cmd { return nil }
func (m mcpReviewModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.viewport.Width, m.viewport.Height = max(10, msg.Width-4), max(3, msg.Height-4)
m.viewport.SetContent(hardWrapContent(m.content, m.viewport.Width))
return m, nil
case tea.KeyMsg:
switch msg.String() {
case "enter":
m.accepted = true
return m, tea.Quit
case "esc", "q", "ctrl+c":
return m, tea.Quit
}
}
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
func (m mcpReviewModel) View() string {
return "MCP change preview\n\n" + m.viewport.View() + "\n" + formatHelpBar("↑↓ scroll Enter continue Esc cancel")
}
func (terminalMCPPrompts) review(summary string, plan *mcp.Plan) error {
var content strings.Builder
fmt.Fprintf(&content, "%s\n\nSource: %s\n", summary, plan.SourcePath)
if plan.Blocked {
content.WriteString("\nConflicts found. Agent files cannot be synced.\n")
}
for _, change := range plan.Changes {
fmt.Fprintf(&content, "\n%s · %s · %s\n %s\n", change.Target, change.Name, change.Action, change.Path)
if change.Message != "" {
fmt.Fprintf(&content, " %s\n", change.Message)
}
}
m := mcpReviewModel{viewport: viewport.New(76, 20), content: content.String()}
m.viewport.SetContent(hardWrapContent(m.content, m.viewport.Width))
result, err := tea.NewProgram(m, tea.WithAltScreen()).Run()
if err != nil {
return err
}
if !result.(mcpReviewModel).accepted {
return errMCPCancelled
}
return nil
}
+164
View File
@@ -0,0 +1,164 @@
package main
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"skillshare/internal/mcp"
)
type scriptedMCPPrompts struct {
choices [][]int
texts []string
}
func (*scriptedMCPPrompts) review(string, *mcp.Plan) error { return nil }
func TestMCPReviewRequiresExplicitContinue(t *testing.T) {
for _, key := range []tea.KeyType{tea.KeyEsc, tea.KeyCtrlC, tea.KeyEnter} {
m := mcpReviewModel{viewport: viewport.New(76, 20), content: "Remove source server: docs"}
resized, _ := m.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
if !strings.Contains(resized.View(), "Remove source server: docs") {
t.Fatal("preview missing from terminal")
}
result, cmd := resized.Update(tea.KeyMsg{Type: key})
if cmd == nil || result.(mcpReviewModel).accepted != (key == tea.KeyEnter) {
t.Fatalf("unexpected preview decision for %v", key)
}
}
}
func (p *scriptedMCPPrompts) choose(checklistConfig) ([]int, error) {
if len(p.choices) == 0 {
return nil, errMCPCancelled
}
choice := p.choices[0]
p.choices = p.choices[1:]
return choice, nil
}
func (p *scriptedMCPPrompts) text(string, string) (string, error) {
if len(p.texts) == 0 {
return "", errMCPCancelled
}
value := p.texts[0]
p.texts = p.texts[1:]
return value, nil
}
func mcpTUIService(t *testing.T) *mcp.Service {
t.Helper()
home := t.TempDir()
s := &mcp.Service{ConfigPath: filepath.Join(home, "config.yaml"), Home: home, StateDir: filepath.Join(home, "state"), Platform: "linux"}
if err := os.WriteFile(s.ConfigPath, []byte("mcp: {targets: [claude], servers: {}}\n"), 0600); err != nil {
t.Fatal(err)
}
return s
}
func TestMCPListKeysAndPrivateDetails(t *testing.T) {
source := &mcp.Source{Targets: []string{"claude"}, Servers: map[string]mcp.Server{"docs": {URL: "https://example.com/mcp?token=hidden-query", Headers: map[string]mcp.Value{"Authorization": {Literal: "hidden-secret"}}}}}
m := newMCPListModel(source, nil, "global", "")
for _, key := range []string{"a", "i", "e", "x", "s", "b", "r"} {
updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(key)})
if cmd == nil || updated.(mcpListModel).action == "" {
t.Errorf("missing shortcut %s", key)
}
}
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
detail := updated.(mcpListModel)
if !detail.showDetail || strings.Contains(detail.View(), "hidden-") {
t.Fatalf("unsafe or missing details: %s", detail.View())
}
updated, _ = detail.Update(tea.KeyMsg{Type: tea.KeyEsc})
if updated.(mcpListModel).showDetail {
t.Fatal("Escape did not return to list")
}
m.list.SetFilterState(list.Filtering)
updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("a")})
if updated.(mcpListModel).action != "" {
t.Fatal("typing search triggered add")
}
}
func TestMCPEditDraftDoesNotMutateOriginal(t *testing.T) {
s := mcpTUIService(t)
original := mcp.Server{Command: "echo", Env: map[string]mcp.Value{"TEAM": {Literal: "before"}}}
prompts := &scriptedMCPPrompts{choices: [][]int{{2}, {2}, {1}, {0}, {6}}, texts: []string{"after"}}
draft, err := editMCPDraft(s, "docs", original, []string{"claude"}, prompts)
if err != nil {
t.Fatal(err)
}
if original.Env["TEAM"].Literal != "before" || draft.Env["TEAM"].Literal != "after" {
t.Fatal("editor mutated input or lost edit")
}
_, err = editMCPDraft(s, "docs", original, nil, &scriptedMCPPrompts{choices: [][]int{{0}, {0}}})
if !errors.Is(err, errMCPCancelled) {
t.Fatalf("cancel: %v", err)
}
}
func TestMCPBatchImportCancelAndSaveOnly(t *testing.T) {
for _, save := range []bool{false, true} {
s := mcpTUIService(t)
before, _ := os.ReadFile(s.ConfigPath)
candidates := []mcp.Candidate{{Name: "one", Server: mcp.Server{Command: "echo"}}, {Name: "two", Server: mcp.Server{URL: "https://example.com/mcp"}}}
prompts := &scriptedMCPPrompts{choices: [][]int{{0, 1}, {0}}}
if save {
prompts.choices = append(prompts.choices, []int{1})
}
err := mcpBatchImportWizard(s, candidates, mcpOptions{}, prompts)
if save {
if err != nil {
t.Fatal(err)
}
source, err := mcp.LoadSource(s.ConfigPath)
if err != nil || len(source.Servers) != 2 {
t.Fatalf("batch: %+v %v", source, err)
}
} else {
if !errors.Is(err, errMCPCancelled) {
t.Fatal(err)
}
after, _ := os.ReadFile(s.ConfigPath)
if string(after) != string(before) {
t.Fatal("cancel saved partial batch")
}
}
if _, err := os.Stat(filepath.Join(s.Home, ".claude.json")); !os.IsNotExist(err) {
t.Fatal("save-only/cancel wrote Agent config")
}
}
}
func TestMCPReviewDryRunNeverPromptsOrWrites(t *testing.T) {
s := mcpTUIService(t)
before, _ := os.ReadFile(s.ConfigPath)
server := mcp.Server{Command: "echo", Targets: []string{"claude"}}
err := reviewMCPMutations(s, []mcp.Mutation{{Name: "one", Server: &server}}, mcpOptions{dryRun: true}, &scriptedMCPPrompts{})
if err != nil {
t.Fatal(err)
}
after, _ := os.ReadFile(s.ConfigPath)
if string(before) != string(after) {
t.Fatal("dry-run wrote source")
}
}
func TestMCPArgumentsPreserveLiterals(t *testing.T) {
for _, input := range []string{"--workspace\nMy Documents", `["--workspace", "My Documents", ""]`} {
args, err := parseMCPArgumentInput(input)
if err != nil || len(args) < 2 || args[1] != "My Documents" {
t.Fatalf("%q: %v %v", input, args, err)
}
}
if _, err := parseMCPArgumentInput(`[3]`); err == nil {
t.Fatal("numeric argument accepted")
}
}
+49 -2
View File
@@ -4,7 +4,9 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"skillshare/internal/projectdir"
"skillshare/internal/ui"
)
@@ -56,6 +58,51 @@ func modeString(mode runMode) string {
}
func projectConfigExists(root string) bool {
_, err := os.Stat(filepath.Join(root, ".skillshare", "config.yaml"))
return err == nil
_, ok := projectdir.Find(root)
return ok
}
// ensureProjectConfig initializes a project when that is safe, and reports the
// case where initializing would discard an existing project instead.
//
// Auto-init is intentional in two situations and both are preserved: a
// repository with no project directory at all, and the shared skills repo
// produced by 'init -p --config local', which gitignores config.yaml so every
// developer regenerates their own.
//
// The case in between used to be silent. A project directory that already holds
// skills or agents, whose config.yaml is simply gone, was re-initialized into an
// empty config — dropping every configured target, leaving stale target links,
// and exiting 0.
func ensureProjectConfig(root string) error {
if projectConfigExists(root) {
return nil
}
if dir, ok := projectdir.FindPartial(root); ok {
gitignored, err := isConfigGitignored(dir)
if (err != nil || !gitignored) && projectDirHasContent(dir) {
return fmt.Errorf(
"%s/ in %s holds skills or agents but has no %s\n"+
"Restore it from version control, or run 'skillshare init -p' to write a new one",
filepath.Base(dir), root, projectdir.ConfigFileName)
}
}
return performProjectInit(root, projectInitOptions{})
}
// projectDirHasContent reports whether the project directory holds authored
// skills or agents that a regenerated config would no longer describe.
func projectDirHasContent(dir string) bool {
for _, name := range []string{"skills", "agents"} {
entries, err := os.ReadDir(filepath.Join(dir, name))
if err != nil {
continue
}
for _, entry := range entries {
if !strings.HasPrefix(entry.Name(), ".") {
return true
}
}
}
return false
}
+12 -4
View File
@@ -28,12 +28,20 @@ func modeHintCommand(targetName string, projectMode bool) string {
return fmt.Sprintf("skillshare target %s --mode copy && skillshare sync", targetName)
}
// symlinkIncompatTargets lists targets whose runtimes are known to skip
// symlinked skill directories. Order doubles as the hint's example priority,
// which also keeps the output deterministic (ranging a map would not).
var symlinkIncompatTargets = []string{"cursor", "antigravity", "copilot", "opencode"}
func printSymlinkCompatHint(targets map[string]config.TargetConfig, defaultMode string, projectMode bool) {
// Find any target that uses a non-copy mode (merge or symlink).
// Pick the highest-priority known-incompatible target still on a non-copy mode.
var exampleTarget string
for name, target := range targets {
mode := effectiveSyncMode(target.SkillsConfig().Mode, defaultMode)
if mode != "copy" {
for _, name := range symlinkIncompatTargets {
target, ok := targets[name]
if !ok {
continue
}
if effectiveSyncMode(target.SkillsConfig().Mode, defaultMode) != "copy" {
exampleTarget = name
break
}
+269
View File
@@ -0,0 +1,269 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/oplog"
"skillshare/internal/plugin"
)
type pluginOptions struct {
request plugin.Request
json, dryRun, noTUI bool
revision string
}
func parsePluginOptions(args []string) (pluginOptions, error) {
o := pluginOptions{request: plugin.Request{Action: "list"}}
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
o.request.Action = args[0]
args = args[1:]
}
positional := ""
for i := 0; i < len(args); i++ {
a := args[i]
switch a {
case "--json":
o.json = true
case "--dry-run", "-n":
o.dryRun = true
case "--no-tui":
o.noTUI = true
case "--target", "--from", "--plugin", "--name", "--revision", "--source-ref", "--entry":
if i+1 == len(args) {
return o, fmt.Errorf("%s requires a value", a)
}
i++
v := args[i]
if v == "" || strings.HasPrefix(v, "--") {
return o, fmt.Errorf("%s requires a value", a)
}
switch a {
case "--target":
o.request.Targets = append(o.request.Targets, plugin.NormalizeTarget(v))
case "--from":
o.request.From = plugin.NormalizeTarget(v)
case "--plugin":
o.request.Plugin = v
case "--name":
o.request.Name = v
case "--entry":
o.request.Entry = v
case "--source-ref":
o.request.SourceRef = v
case "--revision":
o.revision = v
}
default:
if strings.HasPrefix(a, "-") || positional != "" {
return o, fmt.Errorf("unknown plugin argument %q", a)
}
positional = a
}
}
switch o.request.Action {
case "add", "discover":
o.request.Source = positional
case "import":
o.request.Plugin = positional
case "list", "sync", "check", "inspect", "remove", "update", "enable", "disable":
if positional != "" {
if o.request.Name != "" {
return o, fmt.Errorf("specify one package name")
}
o.request.Name = positional
}
default:
return o, fmt.Errorf("unknown plugin command %q; run skillshare plugin --help", o.request.Action)
}
return o, nil
}
func pluginContext(args []string) (*plugin.Service, []string, error) {
mode, rest, err := parseModeArgs(args)
if err != nil {
return nil, nil, err
}
cwd, err := os.Getwd()
if err != nil {
return nil, nil, err
}
if mode == modeAuto {
mode = modeGlobal
if projectConfigExists(cwd) {
mode = modeProject
}
}
s := &plugin.Service{ConfigPath: config.ConfigPath(), StateDir: config.StateDir()}
if mode == modeProject {
s.ConfigPath = config.ProjectConfigPath(cwd)
s.ProjectRoot = cwd
}
applyModeLabel(mode)
return s, rest, nil
}
func cmdPlugin(args []string) (resultErr error) {
defer func() {
if errors.Is(resultErr, errMCPCancelled) {
resultErr = nil
}
}()
if wantsHelp(args) {
printPluginHelp()
return nil
}
s, rest, err := pluginContext(args)
if err != nil {
return err
}
o, err := parsePluginOptions(rest)
if err != nil {
return err
}
interactive := mcpInteractive(mcpOptions{json: o.json, noTUI: o.noTUI})
if interactive && !o.dryRun {
if o.request.Action == "list" {
return runPluginManager(s)
}
if o.request.Action == "add" || o.request.Action == "import" || o.request.Action == "remove" || o.request.Action == "update" || o.request.Action == "enable" || o.request.Action == "disable" || o.request.Action == "sync" {
return pluginWizard(s, o)
}
}
return executePlugin(s, o)
}
func executePlugin(s *plugin.Service, o pluginOptions) error {
ctx := context.Background()
r := o.request
switch r.Action {
case "discover":
d, err := plugin.DiscoverOptions(ctx, r.Source, r.SourceRef, r.Entry)
if err != nil {
return err
}
if o.json {
return json.NewEncoder(os.Stdout).Encode(d)
}
for _, warning := range d.Warnings {
fmt.Println("Warning:", warning)
}
for _, c := range d.Candidates {
fmt.Printf("%s · %s · %s\n", c.Name, strings.Join(c.Targets, ", "), strings.Join(c.Components, ", "))
if c.Problem != "" {
fmt.Println(c.Problem)
}
}
return nil
case "list", "inspect":
inventory, err := s.Inventory(ctx)
if err != nil {
return err
}
if r.Name != "" {
p, ok := inventory.Packages[r.Name]
if !ok {
return fmt.Errorf("plugin package %q not found", r.Name)
}
inventory.Packages = map[string]plugin.Package{r.Name: p}
}
if o.json {
return json.NewEncoder(os.Stdout).Encode(inventory)
}
if len(inventory.Packages) == 0 {
fmt.Println("No plugins managed yet. Run 'skillshare plugin add' or 'skillshare plugin import'.")
}
for name, p := range inventory.Packages {
for _, target := range plugin.Targets {
if b, ok := p.Bindings[target]; ok {
state := "not installed"
for _, h := range inventory.Hosts {
if h.Target != target {
continue
}
if h.Error != "" {
state = h.Error
}
for _, i := range h.Installed {
if i.ID == b.ID {
state = "registered (loading unverified)"
if i.EnabledKnown && !i.Enabled {
state = "disabled"
}
}
}
}
if b.Pending != "" {
state = "pending " + b.Pending
}
fmt.Printf("%s · %s · %s · %s\n", name, target, b.ID, state)
}
}
}
for _, h := range inventory.Hosts {
if h.Error != "" {
fmt.Printf("%s: %s\n", h.Target, h.Error)
}
}
return nil
}
p, err := s.Preview(ctx, r)
if err != nil {
return err
}
if o.revision != "" && o.revision != p.Revision {
return fmt.Errorf("plugin state changed; preview again")
}
if o.dryRun || r.Action == "check" {
if o.json {
err = json.NewEncoder(os.Stdout).Encode(p)
} else {
printPluginPlan(p)
}
if err != nil {
return err
}
if p.Blocked {
return fmt.Errorf("plugin changes are blocked")
}
return nil
}
start := time.Now()
result, err := s.Apply(ctx, r, p.Revision)
entry := oplog.NewEntry("plugin "+r.Action, statusFromErr(err), time.Since(start))
if logErr := oplog.Write(s.ConfigPath, oplog.OpsFile, entry); logErr != nil {
fmt.Fprintln(os.Stderr, "Warning: could not write plugin operation log")
}
if result != nil {
if o.json {
if outErr := json.NewEncoder(os.Stdout).Encode(result); outErr != nil {
return outErr
}
} else {
for _, r := range result.Results {
fmt.Printf("%s · %s · %s\n%s\n", r.Name, r.Target, r.Status, r.Message)
}
}
}
return err
}
func printPluginPlan(p *plugin.Plan) {
for _, c := range p.Changes {
fmt.Printf("%s · %s · %s · %s\n", c.Name, c.Target, c.Action, c.ID)
if len(c.Components) > 0 {
fmt.Println("Includes:", strings.Join(c.Components, ", "))
}
if c.Message != "" {
fmt.Println(c.Message)
}
}
fmt.Println("Revision:", p.Revision)
}
+48
View File
@@ -0,0 +1,48 @@
package main
import "fmt"
func printPluginHelp() {
fmt.Println(`Usage: skillshare plugin [command] [options]
Commands:
list Browse managed plugins (default; TUI in a terminal)
add [source] Choose a plugin from a directory or HTTPS Git repository
discover <source> Inspect source candidates without installing
import [native-id] Adopt an existing native install with --from
inspect <name> Show bindings and native installation state
sync [name] Install missing bindings or retry pending operations
check [name] Check source content for changes (read-only)
update [name] Review and update supported targets
enable / disable [name] Select / deselect managed targets for the next sync
remove [name] Uninstall managed bindings; retain shared marketplaces
Options:
--target <target> Receiving client (repeat to select several)
--plugin <name> Select one plugin from a marketplace
--name <name> Logical Skillshare package name
--from <target> Import from this native client in the selected scope
--dry-run, -n Preview without writing config or Agent state
--source-ref <ref> Git branch, tag or commit (discover/add/update)
--entry <path> Explicit OpenCode JS/TS entry (discover/add)
--revision <id> Require the matching preview before applying
--json Machine-readable output, no interactive prompts
--no-tui Plain output, no interactive prompts
--global, -g Global configuration (native user scope)
--project, -p Project configuration (supported targets only)
Targets: claude, codex, cursor, antigravity (desktop; alias: agy),
antigravity-cli, copilot, grok, pi, opencode
Discovery only: kimi, hermes, devin (native automation not yet verified)
Grok requires native trust: install there first, then import.
Project targets: claude, antigravity, pi, opencode
Cursor/Antigravity sync whole local folders; OpenCode syncs registrations.
Pi project operations require native project trust.
Sync alias: skillshare sync plugins [name] [--dry-run] [--json]
Plugins are not included in sync --all. Complete plugin trees stay together.
Codex project installation and native updates are not supported here.
Enable/disable saves sync selection only; run sync to install/remove the target.
Authentication, hook trust and command-source approval remain in the native client.
Use check before update. Import does not reinstall or change enabled state.`)
}
+22
View File
@@ -0,0 +1,22 @@
package main
import "testing"
func TestPluginOptions(t *testing.T) {
o, err := parsePluginOptions([]string{"add", "owner/repo", "--plugin", "demo", "--target", "claude", "--target", "codex", "--json"})
if err != nil || o.request.Source != "owner/repo" || len(o.request.Targets) != 2 || !o.json {
t.Fatalf("%+v %v", o, err)
}
for _, args := range [][]string{{"unknown"}, {"add", "source", "--target"}, {"remove", "a", "b"}, {"list", "--oops"}} {
if _, err := parsePluginOptions(args); err == nil {
t.Fatalf("accepted %v", args)
}
}
}
func TestPluginAntigravityAlias(t *testing.T) {
o, err := parsePluginOptions([]string{"add", "./demo", "--target", "agy", "--no-tui"})
if err != nil || o.request.Targets[0] != "antigravity" {
t.Fatalf("alias: %+v %v", o, err)
}
}
+232
View File
@@ -0,0 +1,232 @@
package main
import (
"context"
"fmt"
"slices"
"strings"
"skillshare/internal/plugin"
)
func pluginChoose(title string, items []checklistItemData, multiple bool, kinds ...string) ([]int, error) {
kind := "plugin"
if len(kinds) > 0 {
kind = kinds[0]
}
selected, err := runChecklistTUI(checklistConfig{title: title, items: items, singleSelect: !multiple, itemName: kind})
if err == nil && len(selected) == 0 {
return nil, errMCPCancelled
}
return selected, err
}
func runPluginManager(s *plugin.Service) error {
for {
if err := executePlugin(s, pluginOptions{request: plugin.Request{Action: "list"}, noTUI: true}); err != nil {
return err
}
actions := []string{"add", "import", "inspect", "sync", "check", "update", "enable", "disable", "remove"}
labels := []string{"Add a plugin", "Import an existing install", "Inspect a plugin", "Sync / retry pending operations", "Check for source updates", "Update a plugin", "Include a target in sync", "Exclude a target from sync", "Remove a plugin"}
items := make([]checklistItemData, len(actions))
for i, label := range labels {
items[i] = checklistItemData{label: label}
}
selected, err := pluginChoose("Plugins · Esc to close", items, false, "action")
if err != nil {
return err
}
if err := pluginWizard(s, pluginOptions{request: plugin.Request{Action: actions[selected[0]]}}); err != nil {
if err == errMCPCancelled {
continue
}
fmt.Println(err)
}
}
}
func pluginWizard(s *plugin.Service, o pluginOptions) error {
ctx := context.Background()
r := o.request
switch r.Action {
case "add":
if r.Source == "" {
v, err := promptMCPText("1/3 · Paste a GitHub repository or local plugin directory", "")
if err != nil {
return err
}
r.Source = v
}
d, err := plugin.DiscoverOptions(ctx, r.Source, r.SourceRef, r.Entry)
if err != nil {
return err
}
candidates := []plugin.Candidate{}
items := []checklistItemData{}
for _, c := range d.Candidates {
if c.Problem == "" {
candidates = append(candidates, c)
items = append(items, checklistItemData{label: c.Name, desc: c.Description + " · " + strings.Join(c.Components, ", ")})
}
}
if len(candidates) == 0 {
return fmt.Errorf("no locally packaged plugins in this source; install external catalog entries with their native client and import them")
}
var chosen *plugin.Candidate
for _, c := range candidates {
if c.Name == r.Plugin {
cc := c
chosen = &cc
}
}
if chosen == nil {
idx, err := pluginChoose("Choose a plugin", items, false)
if err != nil {
return err
}
chosen = &candidates[idx[0]]
}
r.Plugin = chosen.Name
if len(r.Targets) == 0 {
items = nil
targets := []string{}
for _, definition := range plugin.TargetDefinitions() {
target := definition.Target
if !slices.Contains(chosen.Targets, target) || !slices.Contains(definition.Operations, "add") {
continue
}
if s.ProjectRoot != "" && !plugin.ProjectSupported(target) {
continue
}
targets = append(targets, target)
items = append(items, checklistItemData{label: definition.Label, desc: strings.Join(chosen.TargetInfo[target].Components, ", ")})
}
if len(items) == 0 {
return fmt.Errorf("no compatible native clients in this scope")
}
idx, err := pluginChoose("2/3 · Which tools should receive this plugin?", items, true, "target")
if err != nil {
return err
}
for _, i := range idx {
r.Targets = append(r.Targets, targets[i])
}
}
case "import":
inventory, err := s.Inventory(ctx)
if err != nil {
return err
}
type selection struct{ target, id string }
choices := []selection{}
items := []checklistItemData{}
for _, h := range inventory.Hosts {
supported := false
for _, definition := range inventory.TargetDefinitions {
if definition.Target == h.Target && slices.Contains(definition.Operations, "import") {
supported = true
}
}
if !supported || h.Error != "" {
continue
}
if r.From != "" && r.From != h.Target {
continue
}
for _, i := range h.Installed {
if i.Filtered {
continue
}
if r.Plugin != "" && r.Plugin != i.ID {
continue
}
choices = append(choices, selection{h.Target, i.ID})
items = append(items, checklistItemData{label: i.ID, desc: h.Target + " · " + i.Version})
}
}
if len(items) == 0 {
return fmt.Errorf("no native installations found in this scope; check that the client is installed and signed in")
}
idx, err := pluginChoose("Import without reinstalling", items, false)
if err != nil {
return err
}
r.From = choices[idx[0]].target
r.Plugin = choices[idx[0]].id
default:
if r.Name == "" && r.Action != "sync" && r.Action != "check" {
inventory, err := s.Inventory(ctx)
if err != nil {
return err
}
names := []string{}
for name := range inventory.Packages {
names = append(names, name)
}
slices.Sort(names)
if len(names) == 0 {
return fmt.Errorf("no managed plugins; add or import one first")
}
items := make([]checklistItemData, len(names))
for i, name := range names {
items[i] = checklistItemData{label: name}
}
idx, err := pluginChoose("Choose a plugin", items, false)
if err != nil {
return err
}
r.Name = names[idx[0]]
}
}
o.request = r
if len(r.Targets) == 0 && (r.Action == "enable" || r.Action == "disable" || r.Action == "update" || r.Action == "remove") {
inventory, err := s.Inventory(ctx)
if err != nil {
return err
}
targets := []string{}
items := []checklistItemData{}
for _, definition := range inventory.TargetDefinitions {
target := definition.Target
if !slices.Contains(definition.Operations, r.Action) {
continue
}
if b, ok := inventory.Packages[r.Name].Bindings[target]; ok {
targets = append(targets, target)
items = append(items, checklistItemData{label: definition.Label, desc: b.ID})
}
}
if len(items) == 0 {
return fmt.Errorf("no managed targets support %s; inspect plugin capabilities and use the native client", r.Action)
}
selected, err := pluginChoose("Which targets?", items, true, "target")
if err != nil {
return err
}
for _, i := range selected {
r.Targets = append(r.Targets, targets[i])
}
o.request = r
}
o.noTUI = true
if r.Action == "inspect" || r.Action == "check" {
return executePlugin(s, o)
}
p, err := s.Preview(ctx, r)
if err != nil {
return err
}
printPluginPlan(p)
if p.Blocked {
return fmt.Errorf("resolve blocked targets before continuing")
}
if len(p.Changes) == 0 {
return nil
}
_, err = pluginChoose("3/3 · Apply these changes? Esc cancels", []checklistItemData{{label: "Apply", desc: "Use native plugin management; login and hook trust remain in each Agent"}}, false)
if err != nil {
return err
}
o.revision = p.Revision
return executePlugin(s, o)
}
+1
View File
@@ -56,6 +56,7 @@ func configFromProjectRuntime(r *projectRuntime) *config.Config {
return &config.Config{
Source: r.sourcePath,
AgentsSource: r.agentsSourcePath,
Ignore: r.config.Ignore,
GitLabHosts: r.config.GitLabHosts,
AzureHosts: r.config.AzureHosts,
}
+7
View File
@@ -2,8 +2,15 @@ package main
import (
"skillshare/internal/config"
"skillshare/internal/install"
)
func reconcileProjectRemoteSkills(runtime *projectRuntime) error {
// Installs write .metadata.json directly, so the store loaded before the
// install is stale. Reconciling with it prunes config entries for skills it
// never saw (#280) — always reload from disk first.
if fresh, err := install.LoadMetadata(runtime.sourcePath); err == nil {
runtime.skillsStore = fresh
}
return config.ReconcileProjectSkills(runtime.root, runtime.config, runtime.skillsStore, runtime.sourcePath)
}
+34 -142
View File
@@ -14,13 +14,6 @@ import (
"skillshare/internal/ui"
)
type firstPullOutcome int
const (
firstPullNoop firstPullOutcome = iota
firstPullApplied
)
func cmdPull(args []string) error {
if wantsHelp(args) {
printPullHelp()
@@ -65,14 +58,14 @@ func pullFromRemote(cfg *config.Config, dryRun, force bool) error {
pullStart := time.Now()
spinner := ui.StartSpinner("Checking repository...")
source, ok := resolveGitRoot(cfg, spinner)
if !ok {
return nil // Mismatch guidance already displayed
source, err := resolveGitRoot(cfg, spinner)
if err != nil {
return err
}
// Check if source is a git repo with a configured remote
if err := checkGitRepo(source, spinner); err != nil {
return nil
return err
}
// Check for uncommitted changes
@@ -88,7 +81,7 @@ func pullFromRemote(cfg *config.Config, dryRun, force bool) error {
spinner.Fail("Local changes detected")
ui.Info(" Run: skillshare push")
ui.Info(" Or: cd %s && git stash -u", source)
return nil
return fmt.Errorf("local changes must be pushed or stashed before pulling")
}
if dryRun {
@@ -100,13 +93,23 @@ func pullFromRemote(cfg *config.Config, dryRun, force bool) error {
return nil
}
// First pull (no upstream): fetch + reset to remote branch, then set
// upstream. This mirrors tryPullAfterRemoteSetup() in init.go and avoids
// merge conflicts between the local init commit and remote history.
// Subsequent pulls: normal git pull.
// First pull (no upstream): fetch, then merge or reset onto the remote
// default branch and set upstream (see gitops.FirstPull). Subsequent pulls:
// normal git pull.
authEnv := gitops.AuthEnvForRepo(source)
if !gitops.HasUpstream(source) {
if _, err := firstPull(source, authEnv, force, spinner); err != nil {
spinner.Update("Fetching from remote...")
if _, err := gitops.FirstPull(source, force); errors.Is(err, gitops.ErrNoRemoteBranches) {
spinner.Warn("Remote has no branches yet")
ui.Info(" Push your skills first: skillshare push")
} else if err != nil {
spinner.Fail("Pull failed")
if errors.Is(err, gitops.ErrMergeFailed) {
ui.Info(" Resolve manually: cd %s && git merge --allow-unrelated-histories <remote branch>", source)
ui.Info(" Or force-pull: skillshare pull --force (replaces local with remote)")
} else if !isAuthError(err.Error()) {
hintGitRemoteError(err.Error()) // auth guidance is already part of err
}
return err
}
} else {
@@ -129,135 +132,24 @@ func pullFromRemote(cfg *config.Config, dryRun, force bool) error {
spinner.Stop()
ui.SuccessMsg("Pull complete (%.1fs)", time.Since(pullStart).Seconds())
// Sync to all targets (always global — pull operates on the global source)
// Sync what the pulled scope holds (always global — pull operates on the
// global source).
fmt.Println()
switch cfg.GitRoot {
case "agents":
return cmdSync([]string{"agents", "--global"})
case "extras":
return cmdSync([]string{"extras", "--global"})
case "root":
if err := cmdSync([]string{"--global"}); err != nil {
return err
}
fmt.Println()
return cmdSync([]string{"agents", "--global"})
}
return cmdSync([]string{"--global"})
}
// firstPull handles the initial pull when no upstream tracking exists.
// Fetches remote, then decides based on local/remote content:
// - Remote has branches but no skills + local has skills:
// merge unrelated histories (preserve local skills, import remote files)
// - Both have skills + no --force: attempt merge (fail on conflict)
// - Both have skills + --force: reset to remote (discard local)
// - Local has no skills, or --force: reset to remote
func firstPull(sourcePath string, authEnv []string, force bool, spinner *ui.Spinner) (firstPullOutcome, error) {
spinner.Update("Fetching from remote...")
fetchCmd := exec.Command("git", "fetch", "origin")
fetchCmd.Dir = sourcePath
if len(authEnv) > 0 {
fetchCmd.Env = append(os.Environ(), authEnv...)
}
if output, err := fetchCmd.CombinedOutput(); err != nil {
spinner.Fail("Fetch failed")
outStr := string(output)
fmt.Print(outStr)
hintGitRemoteError(outStr)
return firstPullNoop, fmt.Errorf("fetch failed: %w", err)
}
remoteBranch, err := gitops.GetRemoteDefaultBranch(sourcePath)
if err != nil {
if errors.Is(err, gitops.ErrNoRemoteBranches) {
spinner.Warn("Remote has no branches yet")
ui.Info(" Push your skills first: skillshare push")
return firstPullNoop, nil
}
spinner.Fail("Failed to detect remote default branch")
return firstPullNoop, fmt.Errorf("failed to detect remote default branch: %w", err)
}
// Check if remote actually has skill directories
hasRemoteSkills, err := gitops.HasRemoteSkillDirs(sourcePath, remoteBranch)
if err != nil {
spinner.Fail("Failed to inspect remote skills")
return firstPullNoop, fmt.Errorf("failed to inspect remote skills: %w", err)
}
// Check if local has skill directories
hasLocalSkills, err := gitops.HasLocalSkillDirs(sourcePath)
if err != nil {
spinner.Fail("Failed to inspect local skills")
return firstPullNoop, fmt.Errorf("failed to inspect local skills: %w", err)
}
if !hasRemoteSkills {
// Remote has history/files but no skills.
// If local has skills, merge histories so later push/pull won't hit
// unrelated-history errors.
if hasLocalSkills && !force {
if err := mergeRemoteHistory(sourcePath, remoteBranch, spinner); err != nil {
return firstPullNoop, err
}
setUpstream(sourcePath, remoteBranch)
return firstPullApplied, nil
}
// Local has no skills (or --force): align to remote history directly.
if err := resetToRemote(sourcePath, remoteBranch, spinner); err != nil {
return firstPullNoop, err
}
setUpstream(sourcePath, remoteBranch)
return firstPullApplied, nil
}
if hasLocalSkills && !force {
// Both have skills — try merge; on conflict, guide the user.
if err := mergeRemoteHistory(sourcePath, remoteBranch, spinner); err != nil {
ui.Info(" Or force-pull: skillshare pull --force (replaces local with remote)")
return firstPullNoop, err
}
setUpstream(sourcePath, remoteBranch)
return firstPullApplied, nil
}
// Safe to reset: either local has no skills, or --force was used
if err := resetToRemote(sourcePath, remoteBranch, spinner); err != nil {
return firstPullNoop, err
}
setUpstream(sourcePath, remoteBranch)
return firstPullApplied, nil
}
func setUpstream(sourcePath, remoteBranch string) {
localBranch, _ := gitops.GetCurrentBranch(sourcePath)
if localBranch == "" {
localBranch = "main"
}
trackCmd := exec.Command("git", "branch", "--set-upstream-to=origin/"+remoteBranch, localBranch)
trackCmd.Dir = sourcePath
trackCmd.Run() // best-effort
}
func mergeRemoteHistory(sourcePath, remoteBranch string, spinner *ui.Spinner) error {
spinner.Update("Merging remote history...")
mergeCmd := exec.Command("git", "-c", "merge.ff=false", "merge", "--allow-unrelated-histories", "--no-edit", "origin/"+remoteBranch)
mergeCmd.Dir = sourcePath
if output, err := mergeCmd.CombinedOutput(); err != nil {
spinner.Fail("Failed to merge remote history")
fmt.Print(string(output))
abortCmd := exec.Command("git", "merge", "--abort")
abortCmd.Dir = sourcePath
abortCmd.Run() // best-effort cleanup
ui.Info(" Resolve manually: cd %s && git merge --allow-unrelated-histories origin/%s", sourcePath, remoteBranch)
return fmt.Errorf("merge failed: %w", err)
}
return nil
}
func resetToRemote(sourcePath, remoteBranch string, spinner *ui.Spinner) error {
spinner.Update("Pulling skills from remote...")
resetCmd := exec.Command("git", "reset", "--hard", "origin/"+remoteBranch)
resetCmd.Dir = sourcePath
if output, err := resetCmd.CombinedOutput(); err != nil {
spinner.Fail("Failed to pull from remote")
fmt.Print(string(output))
return fmt.Errorf("reset failed: %w", err)
}
return nil
}
func printPullHelp() {
fmt.Println(`Usage: skillshare pull [options]
+18 -63
View File
@@ -136,26 +136,7 @@ func gitPush(sourcePath string, spinner *ui.Spinner) error {
spinner.Update("Pushing to remote...")
authEnv := gitops.AuthEnvForRepo(sourcePath)
args := []string{"push"}
localBranch, err := gitops.GetCurrentBranch(sourcePath)
if err != nil {
localBranch = "main"
}
if !gitops.HasUpstream(sourcePath) {
remoteBranch := detectRemoteDefaultBranchForPush(sourcePath, authEnv)
if remoteBranch != "" && remoteBranch != localBranch {
args = append(args, "-u", "origin", localBranch+":"+remoteBranch)
} else {
args = append(args, "-u", "origin", localBranch)
}
} else if remoteName, upstreamBranch := upstreamTrackingBranch(sourcePath); remoteName != "" && upstreamBranch != "" && upstreamBranch != localBranch {
// push.default=simple refuses pushing when upstream branch name differs
// from local branch name. Push explicitly to tracked upstream branch.
args = []string{"push", remoteName, "HEAD:" + upstreamBranch}
}
cmd := exec.Command("git", args...)
cmd := exec.Command("git", gitops.PushArgs(sourcePath, authEnv)...)
cmd.Dir = sourcePath
cmd.Env = append(os.Environ(), "LC_ALL=C")
if len(authEnv) > 0 {
@@ -177,39 +158,7 @@ func gitPush(sourcePath string, spinner *ui.Spinner) error {
return nil
}
func upstreamTrackingBranch(sourcePath string) (remoteName, branch string) {
cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")
cmd.Dir = sourcePath
out, err := cmd.Output()
if err != nil {
return "", ""
}
ref := strings.TrimSpace(string(out))
parts := strings.SplitN(ref, "/", 2)
if len(parts) != 2 {
return "", ""
}
return parts[0], parts[1]
}
func detectRemoteDefaultBranchForPush(sourcePath string, authEnv []string) string {
fetchCmd := exec.Command("git", "fetch", "origin")
fetchCmd.Dir = sourcePath
if len(authEnv) > 0 {
fetchCmd.Env = append(os.Environ(), authEnv...)
}
if err := fetchCmd.Run(); err != nil {
return ""
}
branch, err := gitops.GetRemoteDefaultBranch(sourcePath)
if err != nil {
return ""
}
return branch
}
func cmdPush(args []string) error {
func cmdPush(args []string) (err error) {
if wantsHelp(args) {
printPushHelp()
return nil
@@ -223,17 +172,28 @@ func cmdPush(args []string) error {
return fmt.Errorf("config not found: run 'skillshare init' first")
}
if !opts.dryRun {
defer func() {
e := oplog.NewEntry("push", statusFromErr(err), time.Since(start))
e.Args = map[string]any{"message": opts.message}
if err != nil {
e.Message = err.Error()
}
oplog.WriteWithLimit(config.ConfigPath(), oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
}()
}
ui.Header("Pushing to remote")
spinner := ui.StartSpinner("Checking repository...")
source, ok := resolveGitRoot(cfg, spinner)
if !ok {
return nil // Mismatch guidance already displayed
source, err := resolveGitRoot(cfg, spinner)
if err != nil {
return err
}
if err := checkGitRepo(source, spinner); err != nil {
return nil // Error already displayed
return err
}
if sweep := rootScopeSafetySweep(cfg, source, opts.dryRun); sweep.hasNotice() {
@@ -277,16 +237,11 @@ func cmdPush(args []string) error {
}
if err := gitPush(source, spinner); err != nil {
return nil // Error already displayed
return err
}
spinner.Stop()
ui.SuccessMsg("Push complete (%.1fs)", time.Since(start).Seconds())
e := oplog.NewEntry("push", "ok", time.Since(start))
e.Args = map[string]any{"message": opts.message}
oplog.WriteWithLimit(config.ConfigPath(), oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
return nil
}
+2 -5
View File
@@ -441,11 +441,8 @@ func installFromSearchResultProject(result search.SearchResult, cwd string) (err
logInstallOp(config.ProjectConfigPath(cwd), []string{result.Source}, start, err, logSummary)
}()
// Auto-init project if not yet initialized
if !projectConfigExists(cwd) {
if err := performProjectInit(cwd, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(cwd); err != nil {
return err
}
runtime, err := loadProjectRuntime(cwd)
+7 -12
View File
@@ -381,13 +381,10 @@ func collectSearchInstallProject(result search.SearchResult, cwd string, onProgr
source: result.Source,
}
// Auto-init project if not yet initialized
if !projectConfigExists(cwd) {
if err := performProjectInit(cwd, projectInitOptions{}); err != nil {
r.status = "failed"
r.detail = fmt.Sprintf("project init: %v", err)
return r
}
if err := ensureProjectConfig(cwd); err != nil {
r.status = "failed"
r.detail = fmt.Sprintf("project config: %v", err)
return r
}
runtime, err := loadProjectRuntime(cwd)
@@ -588,13 +585,11 @@ func batchInstallFromSearchWithProgress(selected []search.SearchResult, mode run
}
// resolveBatchSourceDir returns the skill source directory for the given mode.
// For project mode, it also ensures project config is initialized.
// For project mode, it requires an initialized project config.
func resolveBatchSourceDir(mode runMode, cfg *config.Config, cwd string) (string, error) {
if mode == modeProject {
if !projectConfigExists(cwd) {
if err := performProjectInit(cwd, projectInitOptions{}); err != nil {
return "", fmt.Errorf("project init: %w", err)
}
if err := ensureProjectConfig(cwd); err != nil {
return "", fmt.Errorf("project config: %w", err)
}
runtime, err := loadProjectRuntime(cwd)
if err != nil {
+4 -8
View File
@@ -16,10 +16,8 @@ import (
)
func cmdStatusProject(root string) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
runtime, err := loadProjectRuntime(root)
@@ -55,10 +53,8 @@ func cmdStatusProject(root string) error {
}
func cmdStatusProjectJSON(root string) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return writeJSONError(err)
}
if err := ensureProjectConfig(root); err != nil {
return writeJSONError(err)
}
runtime, err := loadProjectRuntime(root)
+146 -31
View File
@@ -4,11 +4,13 @@ import (
"fmt"
"io"
"os"
"slices"
"strings"
"time"
"skillshare/internal/backup"
"skillshare/internal/config"
"skillshare/internal/mcp"
"skillshare/internal/oplog"
"skillshare/internal/skillignore"
"skillshare/internal/sync"
@@ -39,6 +41,7 @@ type syncJSONOutput struct {
Details []syncJSONTargetDetail `json:"details"`
Extras []syncExtrasJSONEntry `json:"extras,omitempty"`
ContextCost *contextCostJSON `json:"context_cost,omitempty"`
MCP *mcp.Result `json:"mcp,omitempty"`
}
type syncJSONTargetDetail struct {
@@ -57,14 +60,21 @@ type syncModeStats struct {
}
func cmdSync(args []string) error {
if i := slices.Index(args, "plugins"); i >= 0 {
return cmdPlugin(append([]string{"sync"}, slices.Delete(slices.Clone(args), i, i+1)...))
}
// "mcp" is a subcommand in any position, e.g. "sync -g --dry-run mcp".
if i := slices.Index(args, "mcp"); i >= 0 {
return cmdSyncMCP(slices.Delete(slices.Clone(args), i, i+1))
}
if wantsHelp(args) {
printSyncHelp()
return nil
}
// Subcommand: sync extras
if len(args) > 0 && args[0] == "extras" {
return cmdSyncExtras(args[1:])
// Subcommand: sync extras, also after flags, e.g. "sync -g extras".
if i := slices.Index(args, "extras"); i >= 0 {
return cmdSyncExtras(slices.Delete(slices.Clone(args), i, i+1))
}
// Extract --all flag before mode parsing
@@ -101,11 +111,92 @@ func cmdSync(args []string) error {
applyModeLabel(mode)
// Extract kind filter (e.g. "skillshare sync agents").
// Extract kind filter (e.g. "skillshare sync agents"). Sync flags take no
// values, so the kind may also follow them: "sync --dry-run agents".
if i := slices.IndexFunc(rest, func(arg string) bool {
_, remaining := parseKindArg([]string{arg})
return len(remaining) == 0
}); i > 0 {
rest = append([]string{rest[i]}, slices.Delete(slices.Clone(rest), i, i+1)...)
}
kind, rest := parseKindArg(rest)
dryRun, force, jsonOutput, quiet := parseSyncFlags(rest)
var mcpResult *mcp.Result
var mcpService *mcp.Service
if hasAll {
preflightErr := func(err error) error {
if jsonOutput {
return writeJSONError(err)
}
return err
}
// Loading can migrate legacy skill/extras configuration. Complete that
// existing normalization before fingerprinting the MCP source.
if mode == modeProject {
_, err = config.LoadProject(cwd)
} else {
_, err = config.Load()
}
if err != nil {
return preflightErr(err)
}
scope := "-g"
if mode == modeProject {
scope = "-p"
}
mcpService, _, err = mcpContext([]string{scope})
if err != nil {
return preflightErr(err)
}
plan, planErr := mcpService.Preview()
if planErr != nil {
return preflightErr(fmt.Errorf("MCP preflight: %w", planErr))
}
mcpResult = &mcp.Result{Plan: plan, Applied: []string{}, BackupIDs: []string{}}
if plan.Blocked {
err = fmt.Errorf("MCP conflicts found; no resources synchronized")
if jsonOutput {
// Changes are credential-free and tell scripts which entries conflict.
return writeJSONResult(map[string]any{"error": err.Error(), "mcp": mcpResult}, err)
}
_ = printMCPPlan(plan, false)
return err
}
}
finishMCP := func(previous error) error {
if !hasAll {
return previous
}
if previous != nil {
// Keep MCP untouched after a resource failure; drop the preflight plan
// so JSON output does not look processed.
mcpResult = nil
if !jsonOutput {
ui.Warning("MCP settings were not applied because resource sync failed")
}
return previous
}
if len(mcpResult.Plan.Changes) == 0 {
return nil
}
var applyErr error
if !dryRun {
// Skills sync ran after the preflight; plan again under the MCP lock so
// unrelated config writes cannot fail the run with a stale revision.
mcpResult, applyErr = mcpService.Apply("")
logMCPOp(mcpService.ConfigPath, "sync mcp", start, applyErr)
}
if !jsonOutput && !quiet && mcpResult != nil {
_ = printMCPPlan(mcpResult.Plan, false)
for _, id := range mcpResult.BackupIDs {
ui.Info("MCP backup: %s", id)
}
}
return applyErr
}
prevDiagOutput := sync.DiagOutput
if jsonOutput {
sync.DiagOutput = io.Discard
@@ -141,6 +232,7 @@ func cmdSync(args []string) error {
}
if jsonOutput {
err = finishMCP(err)
if hasAll {
projCfg, loadErr := config.LoadProject(cwd)
if loadErr == nil && len(projCfg.Extras) > 0 {
@@ -148,12 +240,12 @@ func cmdSync(args []string) error {
extrasEntries := runExtrasSyncEntries(projCfg.Extras, func(extra config.ExtraConfig) string {
return config.ExtrasSourceDirProject(projCfg.EffectiveExtrasSource(cwd), extra.Name)
}, dryRun, force, cwd, agentPaths)
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost, extrasEntries)
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost, mcpResult, extrasEntries)
}
}
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost)
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost, mcpResult)
}
return err
return finishMCP(err)
}
cfg, err := config.Load()
@@ -226,9 +318,9 @@ func cmdSync(args []string) error {
var results []syncTargetResult
var failedTargets int
if jsonOutput {
results, failedTargets = runParallelSyncQuiet(entries, cfg.EffectiveSkillsSource(), discoveredSkills, dryRun, force, "")
results, failedTargets = runParallelSyncQuiet(entries, cfg.EffectiveSkillsSource(), discoveredSkills, sync.EffectiveFileIgnorePatterns(cfg.Ignore), dryRun, force, "")
} else {
results, failedTargets = runParallelSync(entries, cfg.EffectiveSkillsSource(), discoveredSkills, dryRun, force, "")
results, failedTargets = runParallelSync(entries, cfg.EffectiveSkillsSource(), discoveredSkills, sync.EffectiveFileIgnorePatterns(cfg.Ignore), dryRun, force, "")
}
var syncErr error
@@ -289,7 +381,15 @@ func cmdSync(args []string) error {
Force: force,
}, start, syncErr)
// Agents are included in --all in both human-readable and JSON output.
if kind == kindAll || hasAll {
if _, agentErr := syncAgentsGlobal(cfg, dryRun, force, jsonOutput, start); agentErr != nil && syncErr == nil {
syncErr = agentErr
}
}
if jsonOutput {
syncErr = finishMCP(syncErr)
var ctxCost *contextCostJSON
if analyzeErr == nil && len(analyzeEntries) > 0 {
ctxCost = buildContextCostJSON(analyzeEntries, cfg.ContextBudget)
@@ -299,16 +399,9 @@ func cmdSync(args []string) error {
extrasEntries := runExtrasSyncEntries(cfg.Extras, func(extra config.ExtraConfig) string {
return config.ResolveExtrasSourceDir(extra, cfg.EffectiveExtrasSource(), cfg.EffectiveSkillsSource())
}, dryRun, force, "", agentPaths)
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost, extrasEntries)
}
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost)
}
// 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
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost, mcpResult, extrasEntries)
}
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost, mcpResult)
}
if hasAll {
@@ -317,7 +410,7 @@ func cmdSync(args []string) error {
}
}
return syncErr
return finishMCP(syncErr)
}
func parseSyncFlags(args []string) (dryRun, force, jsonOutput, quiet bool) {
@@ -405,7 +498,7 @@ func printIgnoredSkills(stats *skillignore.IgnoreStats) {
// syncOutputJSON converts sync results to JSON and writes to stdout.
// extras is optional and included when --all is used.
func syncOutputJSON(results []syncTargetResult, dryRun bool, start time.Time, iStats *skillignore.IgnoreStats, syncErr error, ctxCost *contextCostJSON, extras ...[]syncExtrasJSONEntry) error {
func syncOutputJSON(results []syncTargetResult, dryRun bool, start time.Time, iStats *skillignore.IgnoreStats, syncErr error, ctxCost *contextCostJSON, mcpResult *mcp.Result, extras ...[]syncExtrasJSONEntry) error {
var totals syncModeStats
var details []syncJSONTargetDetail
for _, r := range results {
@@ -443,10 +536,19 @@ func syncOutputJSON(results []syncTargetResult, dryRun bool, start time.Time, iS
output.Extras = extras[0]
}
output.ContextCost = ctxCost
output.MCP = mcpResult
return writeJSONResult(&output, syncErr)
}
func backupTargetsBeforeSync(cfg *config.Config) {
// Pre-sync backups are automatic, so retention must be too — otherwise
// every sync adds a snapshot that nothing ever removes.
defer func() {
if _, err := backup.Cleanup(backup.DefaultCleanupConfig()); err != nil {
ui.Warning("Failed to clean up old backups: %v", err)
}
}()
backedUp := false
for name, target := range cfg.Targets {
backupPath, err := backup.Create(name, target.SkillsConfig().Path)
@@ -463,7 +565,11 @@ func backupTargetsBeforeSync(cfg *config.Config) {
// Also backup agent targets if any exist.
backupDir, agentTargets, err := resolveGlobalAgentBackupContextFromCfg(cfg)
if err != nil || len(agentTargets) == 0 {
if err != nil {
ui.Warning("Failed to resolve agent backup targets: %v", err)
return
}
if len(agentTargets) == 0 {
return
}
for _, at := range agentTargets {
@@ -496,7 +602,7 @@ func syncTarget(name string, target config.TargetConfig, cfg *config.Config, dry
case "merge":
return syncMergeMode(name, target, cfg.EffectiveSkillsSource(), dryRun, force)
case "copy":
return syncCopyMode(name, target, cfg.EffectiveSkillsSource(), dryRun, force)
return syncCopyMode(name, target, cfg.EffectiveSkillsSource(), sync.EffectiveFileIgnorePatterns(cfg.Ignore), dryRun, force)
default:
return syncSymlinkMode(name, target, cfg.EffectiveSkillsSource(), dryRun, force)
}
@@ -521,7 +627,7 @@ func syncTargetWithSkillsStats(name string, target config.TargetConfig, cfg *con
case "merge":
return syncMergeModeWithSkills(name, target, cfg.EffectiveSkillsSource(), skills, dryRun, force)
case "copy":
return syncCopyModeWithSkills(name, target, cfg.EffectiveSkillsSource(), skills, dryRun, force)
return syncCopyModeWithSkills(name, target, cfg.EffectiveSkillsSource(), skills, sync.EffectiveFileIgnorePatterns(cfg.Ignore), dryRun, force)
default:
err := syncSymlinkMode(name, target, cfg.EffectiveSkillsSource(), dryRun, force)
return syncModeStats{}, err
@@ -606,9 +712,9 @@ func reportMergeResult(name string, target config.TargetConfig, result *sync.Mer
}
}
func syncCopyMode(name string, target config.TargetConfig, source string, dryRun, force bool) error {
func syncCopyMode(name string, target config.TargetConfig, source string, ignorePatterns []string, dryRun, force bool) error {
sc := target.SkillsConfig()
result, err := sync.SyncTargetCopy(name, target, source, dryRun, force)
result, err := sync.SyncTargetCopyWithOptions(name, target, source, dryRun, force, sync.CopyOptions{IgnorePatterns: ignorePatterns})
if err != nil {
return err
}
@@ -622,14 +728,14 @@ func syncCopyMode(name string, target config.TargetConfig, source string, dryRun
return nil
}
func syncCopyModeWithSkills(name string, target config.TargetConfig, source string, skills []sync.DiscoveredSkill, dryRun, force bool) (syncModeStats, error) {
func syncCopyModeWithSkills(name string, target config.TargetConfig, source string, skills []sync.DiscoveredSkill, ignorePatterns []string, dryRun, force bool) (syncModeStats, error) {
// Copy mode is slow (checksum + file copy per skill) — show a spinner with progress
spinner := ui.StartSpinner(fmt.Sprintf("%s: copying skills", name))
onProgress := func(cur, total int, skill string) {
spinner.Update(fmt.Sprintf("%s: %d/%d %s", name, cur, total, skill))
}
result, err := sync.SyncTargetCopyWithSkills(name, target, skills, source, dryRun, force, onProgress)
result, err := sync.SyncTargetCopyWithSkillsOptions(name, target, skills, source, dryRun, force, onProgress, sync.CopyOptions{IgnorePatterns: ignorePatterns})
if err != nil {
spinner.Fail(fmt.Sprintf("%s: copy failed", name))
return syncModeStats{}, err
@@ -837,12 +943,12 @@ func syncSymlinkMode(name string, target config.TargetConfig, source string, dry
}
func printSyncHelp() {
fmt.Println(`Usage: skillshare sync [agents] [options]
fmt.Println(`Usage: skillshare sync [agents|extras|mcp|plugins] [options]
Sync skills from source to all configured targets.
Options:
--all Sync skills, agents, and extras
--all Sync skills, agents, extras, and MCP
--dry-run, -n Preview changes without applying
--force, -f Force sync (overwrite local changes)
--json Output results as JSON
@@ -852,12 +958,21 @@ Options:
--help, -h Show this help
Subcommands:
agents Sync only agents
plugins [name] Apply plugin sync selection (see: skillshare plugin --help)
mcp Sync only MCP settings (no --force; conflicts require review)
extras Sync only extras (see: skillshare sync extras --help)
Examples:
skillshare sync Sync skills to all targets
skillshare sync --dry-run Preview sync changes
skillshare sync --all Sync skills, agents, and extras
skillshare sync --all Sync skills, agents, extras, and MCP
skillshare sync -p Sync project-level skills
skillshare sync agents Sync agents only`)
skillshare sync agents Sync agents only
skillshare sync plugins Apply selected plugin installations/removals
skillshare sync plugins --dry-run --json Preview plugin changes
Plugins are not included in --all. Plugin sync uses its own options;
--force and --quiet do not apply. Enable/disable saves selection only;
run sync plugins to install selected targets or uninstall deselected targets.`)
}
+19 -2
View File
@@ -55,7 +55,17 @@ func syncAgentsGlobal(cfg *config.Config, dryRun, force, jsonOutput bool, start
// Backup agent targets before sync (non-dry-run only).
if !dryRun && !jsonOutput {
backupDir, agentTargets, _ := resolveGlobalAgentBackupContextFromCfg(cfg)
backupDir, agentTargets, backupErr := resolveGlobalAgentBackupContextFromCfg(cfg)
if backupErr != nil {
ui.Warning("Failed to resolve agent backup targets: %v", backupErr)
agentTargets = nil
} else {
defer func() {
if _, err := backup.CleanupInDir(backupDir, backup.DefaultCleanupConfig()); err != nil {
ui.Warning("Failed to clean up old agent backups: %v", err)
}
}()
}
backedUp := false
for _, at := range agentTargets {
entryName := at.name + "-agents"
@@ -97,6 +107,7 @@ func syncAgentsGlobal(cfg *config.Config, dryRun, force, jsonOutput bool, start
syncErr = fmt.Errorf("some agent targets failed to sync")
continue
}
filtered = sync.FilterAgentsByTarget(filtered, name)
stats, targetErr := syncAgentTarget(name, agentPath, ac.Mode, filtered, agentsSource, dryRun, force, jsonOutput, "")
if targetErr != nil {
syncErr = fmt.Errorf("some agent targets failed to sync")
@@ -182,7 +193,12 @@ func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start
// Backup agent targets before sync (non-dry-run only).
if !dryRun && !jsonOutput {
backupDir := filepath.Join(projectRoot, ".skillshare", "backups")
backupDir := backup.ProjectBackupDir(projectRoot)
defer func() {
if _, err := backup.CleanupInDir(backupDir, backup.DefaultCleanupConfig()); err != nil {
ui.Warning("Failed to clean up old project agent backups: %v", err)
}
}()
backedUp := false
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
@@ -225,6 +241,7 @@ func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start
syncErr = fmt.Errorf("some agent targets failed to sync")
continue
}
filtered = sync.FilterAgentsByTarget(filtered, entry.Name)
stats, targetErr := syncAgentTarget(entry.Name, agentPath, ac.Mode, filtered, agentsSource, dryRun, force, jsonOutput, projectRoot)
if targetErr != nil {
syncErr = fmt.Errorf("some agent targets failed to sync")
+10 -10
View File
@@ -179,7 +179,7 @@ type syncTargetEntry struct {
// collectSyncResult runs sync for one target and returns a result struct.
// Does NOT print any UI output — all output data is captured in the result.
func collectSyncResult(name string, target config.TargetConfig, source, mode string, skills []sync.DiscoveredSkill, dryRun, force bool, progress *syncProgress, projectRoot string) syncTargetResult {
func collectSyncResult(name string, target config.TargetConfig, source, mode string, skills []sync.DiscoveredSkill, ignorePatterns []string, dryRun, force bool, progress *syncProgress, projectRoot string) syncTargetResult {
sc := target.SkillsConfig()
r := syncTargetResult{
name: name,
@@ -192,7 +192,7 @@ func collectSyncResult(name string, target config.TargetConfig, source, mode str
case "merge":
collectMergeSyncResult(&r, name, target, source, skills, dryRun, force, projectRoot)
case "copy":
collectCopySyncResult(&r, name, target, source, skills, dryRun, force, progress)
collectCopySyncResult(&r, name, target, source, skills, ignorePatterns, dryRun, force, progress)
default:
collectSymlinkSyncResult(&r, name, target, source, dryRun, force, projectRoot)
}
@@ -251,14 +251,14 @@ func collectMergeSyncResult(r *syncTargetResult, name string, target config.Targ
}
}
func collectCopySyncResult(r *syncTargetResult, name string, target config.TargetConfig, source string, skills []sync.DiscoveredSkill, dryRun, force bool, progress *syncProgress) {
func collectCopySyncResult(r *syncTargetResult, name string, target config.TargetConfig, source string, skills []sync.DiscoveredSkill, ignorePatterns []string, dryRun, force bool, progress *syncProgress) {
onProgress := func(cur, total int, skill string) {
if progress != nil {
progress.updateTarget(name, fmt.Sprintf("%d/%d %s", cur, total, skill))
}
}
result, err := sync.SyncTargetCopyWithSkills(name, target, skills, source, dryRun, force, onProgress)
result, err := sync.SyncTargetCopyWithSkillsOptions(name, target, skills, source, dryRun, force, onProgress, sync.CopyOptions{IgnorePatterns: ignorePatterns})
if err != nil {
r.errMsg = err.Error()
return
@@ -372,13 +372,13 @@ func renderSyncResults(results []syncTargetResult) {
// Targets sharing the same resolved path are grouped and run sequentially within one
// goroutine to avoid race conditions (e.g., two targets trying to create the same symlink).
// Returns results (indexed by position) and count of failed targets.
func runParallelSync(entries []syncTargetEntry, source string, skills []sync.DiscoveredSkill, dryRun, force bool, projectRoot string) ([]syncTargetResult, int) {
func runParallelSync(entries []syncTargetEntry, source string, skills []sync.DiscoveredSkill, ignorePatterns []string, dryRun, force bool, projectRoot string) ([]syncTargetResult, int) {
names := make([]string, len(entries))
for i, e := range entries {
names[i] = e.name
}
progress := newSyncProgress(names)
results, failedTargets := runParallelSyncCore(entries, source, skills, dryRun, force, progress, projectRoot)
results, failedTargets := runParallelSyncCore(entries, source, skills, ignorePatterns, dryRun, force, progress, projectRoot)
progress.stop()
renderSyncResults(results)
return results, failedTargets
@@ -386,13 +386,13 @@ func runParallelSync(entries []syncTargetEntry, source string, skills []sync.Dis
// runParallelSyncQuiet executes sync for multiple targets without any UI output.
// Used for --json mode where only structured output should go to stdout.
func runParallelSyncQuiet(entries []syncTargetEntry, source string, skills []sync.DiscoveredSkill, dryRun, force bool, projectRoot string) ([]syncTargetResult, int) {
return runParallelSyncCore(entries, source, skills, dryRun, force, nil, projectRoot)
func runParallelSyncQuiet(entries []syncTargetEntry, source string, skills []sync.DiscoveredSkill, ignorePatterns []string, dryRun, force bool, projectRoot string) ([]syncTargetResult, int) {
return runParallelSyncCore(entries, source, skills, ignorePatterns, dryRun, force, nil, projectRoot)
}
// runParallelSyncCore is the shared implementation for parallel sync.
// When progress is nil, no UI output is produced (quiet/JSON mode).
func runParallelSyncCore(entries []syncTargetEntry, source string, skills []sync.DiscoveredSkill, dryRun, force bool, progress *syncProgress, projectRoot string) ([]syncTargetResult, int) {
func runParallelSyncCore(entries []syncTargetEntry, source string, skills []sync.DiscoveredSkill, ignorePatterns []string, dryRun, force bool, progress *syncProgress, projectRoot string) ([]syncTargetResult, int) {
type indexedEntry struct {
idx int
entry syncTargetEntry
@@ -422,7 +422,7 @@ func runParallelSyncCore(entries []syncTargetEntry, source string, skills []sync
if progress != nil {
progress.startTarget(m.entry.name)
}
r := collectSyncResult(m.entry.name, m.entry.target, source, m.entry.mode, skills, dryRun, force, progress, projectRoot)
r := collectSyncResult(m.entry.name, m.entry.target, source, m.entry.mode, skills, ignorePatterns, dryRun, force, progress, projectRoot)
if progress != nil {
progress.doneTarget(m.entry.name, r)
}
+5 -6
View File
@@ -20,10 +20,8 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog
ProjectScope: true,
}
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return stats, nil, nil, nil, err
}
if err := ensureProjectConfig(root); err != nil {
return stats, nil, nil, nil, err
}
runtime, err := loadProjectRuntime(root)
@@ -95,10 +93,11 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLog
var results []syncTargetResult
var failedTargets int
ignorePatterns := sync.EffectiveFileIgnorePatterns(runtime.config.Ignore)
if jsonOutput {
results, failedTargets = runParallelSyncQuiet(entries, runtime.sourcePath, discoveredSkills, dryRun, force, root)
results, failedTargets = runParallelSyncQuiet(entries, runtime.sourcePath, discoveredSkills, ignorePatterns, dryRun, force, root)
} else {
results, failedTargets = runParallelSync(entries, runtime.sourcePath, discoveredSkills, dryRun, force, root)
results, failedTargets = runParallelSync(entries, runtime.sourcePath, discoveredSkills, ignorePatterns, dryRun, force, root)
}
failedTargets += notFoundCount
+8 -16
View File
@@ -31,10 +31,8 @@ func targetAddProject(args []string, root string) error {
return fmt.Errorf("invalid target name: %w", err)
}
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
knownPath := ""
@@ -128,10 +126,8 @@ func targetRemoveProject(args []string, root string) error {
return err
}
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
cfg, err := config.LoadProject(root)
@@ -259,10 +255,8 @@ func targetListProject(root string) error {
}
func targetListProjectWithJSON(root string, jsonOutput bool) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
if jsonOutput {
@@ -293,10 +287,8 @@ func targetListProjectWithJSON(root string, jsonOutput bool) error {
}
func targetInfoProject(name string, args []string, root string) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
// Parse filter flags first, pass remaining to mode parsing
+31 -11
View File
@@ -110,6 +110,19 @@ func topLevelDir(relPath string) string {
return parts[0]
}
// normalizeUninstallName converts OS-native separators to the slash-separated
// logical names used by metadata and trash entries.
func normalizeUninstallName(name string) string {
return normalizeUninstallNameForSeparator(name, os.PathSeparator)
}
func normalizeUninstallNameForSeparator(name string, separator uint8) string {
if separator == '/' {
return name
}
return strings.ReplaceAll(name, string(separator), "/")
}
// looksLikeShellGlob detects when positional args appear to be shell-expanded
// file names rather than real skill names. Heuristic: ≥3 warnings, warnings ≥50%
// of names, and ≥2 names contain a dot (file extension characteristic).
@@ -131,6 +144,7 @@ func looksLikeShellGlob(names []string, warnings []string) bool {
// to "frontend/react/react-best-practices").
func resolveUninstallTarget(skillName string, cfg *config.Config) (*uninstallTarget, error) {
skillName = strings.TrimRight(strings.TrimSpace(skillName), `/\`)
skillName = normalizeUninstallName(skillName)
if skillName == "" || skillName == "." {
return nil, fmt.Errorf("invalid skill name: %q", skillName)
}
@@ -197,6 +211,7 @@ func resolveUninstallByGlob(pattern string, cfg *config.Config) ([]*uninstallTar
// Returns uninstallTargets for each skill found.
func resolveGroupSkills(group, sourceDir string) ([]*uninstallTarget, error) {
group = strings.TrimRight(strings.TrimSpace(group), `/\`)
group = normalizeUninstallName(group)
if group == "" || group == "." {
return nil, fmt.Errorf("invalid group name: %q", group)
}
@@ -239,7 +254,7 @@ func resolveGroupSkills(group, sourceDir string) ([]*uninstallTarget, error) {
rel, relErr := filepath.Rel(resolvedSourceDir, path)
if relErr == nil && !strings.HasPrefix(rel, "..") {
targets = append(targets, &uninstallTarget{
name: rel,
name: normalizeUninstallName(rel),
path: path,
isTrackedRepo: isRepo,
})
@@ -278,7 +293,7 @@ func resolveNestedSkillDir(sourceDir, name string) (string, error) {
}
if info.Name() == name || info.Name() == "_"+name {
if rel, relErr := filepath.Rel(walkRoot, path); relErr == nil && rel != "." {
matches = append(matches, rel)
matches = append(matches, normalizeUninstallName(rel))
}
return filepath.SkipDir
}
@@ -584,11 +599,6 @@ func cmdUninstall(args []string) error {
return parseErr
}
// --json implies --force (skip confirmation prompts)
if opts.jsonOutput {
opts.force = true
}
cfg, err := config.Load()
if err != nil {
if opts.jsonOutput {
@@ -599,6 +609,7 @@ func cmdUninstall(args []string) error {
// Agent-only uninstall: move .md + sidecar to agent trash, then return.
if kind == kindAgents {
opts.force = opts.force || opts.jsonOutput
agentsDir := cfg.EffectiveAgentsSource()
err := cmdUninstallAgents(agentsDir, opts, config.ConfigPath(), trash.AgentTrashDir(), start)
return err
@@ -841,11 +852,17 @@ func cmdUninstall(args []string) error {
// Repo is dirty
if !opts.force {
if single {
dirtyErr := fmt.Errorf("uncommitted changes detected, use --force to override")
if opts.jsonOutput {
return writeJSONError(dirtyErr)
}
ui.Error("Repository has uncommitted changes!")
ui.Info("Use --force to uninstall anyway, or commit/stash your changes first")
return fmt.Errorf("uncommitted changes detected, use --force to override")
return dirtyErr
}
if !opts.jsonOutput {
ui.StepSkip(t.name, "uncommitted changes, use --force")
}
ui.StepSkip(t.name, "uncommitted changes, use --force")
continue
}
if !opts.jsonOutput {
@@ -864,6 +881,9 @@ func cmdUninstall(args []string) error {
if len(targets) == 0 {
preflightErr := fmt.Errorf("no skills to uninstall after pre-flight checks")
if preflightSkipped > 0 {
preflightErr = fmt.Errorf("%d tracked repo%s skipped due to uncommitted changes; use --force to override", preflightSkipped, pluralS(preflightSkipped))
}
if opts.jsonOutput {
return writeJSONError(preflightErr)
}
@@ -893,7 +913,7 @@ func cmdUninstall(args []string) error {
return nil
}
if !opts.force {
if !opts.force && !opts.jsonOutput {
if single {
confirmed, err := confirmUninstall(targets[0])
if err != nil {
@@ -1178,7 +1198,7 @@ Options:
--group, -G <name> Remove all skills in a group (prefix match, repeatable)
--force, -f Skip confirmation and ignore uncommitted changes
--dry-run, -n Preview without making changes
--json Output results as JSON (implies --force)
--json Global mode: output JSON and skip confirmation
--project, -p Use project-level config in current directory
--global, -g Use global config (~/.config/skillshare)
--help, -h Show this help
+3 -4
View File
@@ -18,6 +18,7 @@ import (
// within a project's .skillshare/skills directory.
func resolveProjectUninstallTarget(skillName, sourceDir string) (*uninstallTarget, error) {
skillName = strings.TrimRight(strings.TrimSpace(skillName), `/\`)
skillName = normalizeUninstallName(skillName)
if skillName == "" || skillName == "." {
return nil, fmt.Errorf("invalid skill name: %q", skillName)
}
@@ -80,10 +81,8 @@ func cmdUninstallProject(args []string, root string) error {
return err
}
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
}
if err := ensureProjectConfig(root); err != nil {
return err
}
projectCfg, loadErr := config.LoadProject(root)
+14
View File
@@ -9,6 +9,20 @@ import (
"skillshare/internal/install"
)
func TestNormalizeUninstallName_WindowsNestedPath(t *testing.T) {
got := normalizeUninstallNameForSeparator(`coding\_skill`, '\\')
if got != "coding/_skill" {
t.Fatalf("normalizeUninstallNameForSeparator() = %q, want %q", got, "coding/_skill")
}
}
func TestNormalizeUninstallName_UnixPreservesLiteralBackslash(t *testing.T) {
got := normalizeUninstallNameForSeparator(`coding\_skill`, '/')
if got != `coding\_skill` {
t.Fatalf("normalizeUninstallNameForSeparator() = %q, want %q", got, `coding\_skill`)
}
}
// --- resolveUninstallByGlob tests ---
func TestResolveUninstallByGlob_MatchesDirs(t *testing.T) {
+4 -3
View File
@@ -536,8 +536,9 @@ For regular skills: reinstalls from stored source metadata
If a positional name matches a group directory (not a repo or skill), it is
automatically expanded to all updatable skills in that group.
Safety: Tracked repos with uncommitted changes are skipped by default.
Use --force to discard local changes and update.
Safety: Tracked repos with uncommitted changes are skipped by default, and
updates with audit findings at/above the block threshold are rolled back.
Use --force to override both; --skip-audit skips scanning entirely.
Arguments:
name... Skill name(s) or tracked repo name(s)
@@ -546,7 +547,7 @@ Arguments:
Options:
--all, -a Update all tracked repos + skills with metadata
--group, -G <name> Update all updatable skills in a group (repeatable)
--force, -f Discard local changes and force update
--force, -f Discard local changes and proceed despite audit findings
--dry-run, -n Preview without making changes
--skip-audit Skip post-update security audit
--audit-threshold, --threshold, -T <t>
+4 -4
View File
@@ -345,6 +345,7 @@ func batchUpdateAgents(agentsDir string, agents []check.AgentCheckResult, opts *
installOpts := install.InstallOptions{
Kind: "agent",
Force: opts.force,
AuditOverride: opts.force,
Update: true,
SkipAudit: opts.skipAudit,
AuditThreshold: opts.threshold,
@@ -470,6 +471,7 @@ func reinstallAgent(agentsDir string, r check.AgentCheckResult, store *install.M
installOpts := install.InstallOptions{
Kind: "agent",
Force: opts.force,
AuditOverride: opts.force,
Update: true,
SkipAudit: opts.skipAudit,
AuditThreshold: opts.threshold,
@@ -735,10 +737,8 @@ func cmdUpdateAgentsProject(args []string, projectRoot string, start time.Time)
return err
}
if !projectConfigExists(projectRoot) {
if err := performProjectInit(projectRoot, projectInitOptions{}); err != nil {
return failJSON(err)
}
if err := ensureProjectConfig(projectRoot); err != nil {
return failJSON(err)
}
runtime, err := loadProjectRuntime(projectRoot)
+8 -3
View File
@@ -38,6 +38,7 @@ func (uc *updateContext) auditScanFn() auditScanFunc {
func (uc *updateContext) makeInstallOpts() install.InstallOptions {
opts := install.InstallOptions{
Force: true,
AuditOverride: uc.opts.force,
Update: true,
SkipAudit: uc.opts.skipAudit,
AuditThreshold: uc.opts.threshold,
@@ -75,7 +76,10 @@ func executeBatchUpdate(uc *updateContext, targets []updateTarget) (updateResult
continue
}
if t.meta != nil && t.meta.RepoURL != "" {
repoGroups[t.meta.RepoURL] = append(repoGroups[t.meta.RepoURL], t)
// Group by URL+branch: skills installed from a non-default branch
// must be re-fetched from that branch, not the remote HEAD.
key := urlBranchKey(t.meta.RepoURL, t.meta.Branch)
repoGroups[key] = append(repoGroups[key], t)
} else {
standaloneSkills = append(standaloneSkills, t)
}
@@ -149,7 +153,8 @@ func executeBatchUpdate(uc *updateContext, targets []updateTarget) (updateResult
progressBar.SetHeader(ui.FormatPhaseHeader(phaseCurrent, phaseTotal, "Updating %d grouped skill(s) from %d repo(s)...", groupedCount, len(repoGroups)))
}
}
for repoURL, groupTargets := range repoGroups {
for groupKey, groupTargets := range repoGroups {
repoURL, branch := splitURLBranch(groupKey)
if uc.opts.dryRun {
for _, t := range groupTargets {
progressBar.UpdateTitle(fmt.Sprintf("Updating %s", t.name))
@@ -187,7 +192,7 @@ func executeBatchUpdate(uc *updateContext, targets []updateTarget) (updateResult
}
}
batchResult, err := install.UpdateSkillsFromRepo(repoURL, skillTargetMap, batchOpts)
batchResult, err := install.UpdateSkillsFromRepo(repoURL, branch, skillTargetMap, batchOpts)
if err != nil {
for _, t := range groupTargets {
progressBar.UpdateTitle(fmt.Sprintf("Failed %s: %v", t.name, err))
+27 -4
View File
@@ -16,6 +16,19 @@ import (
"skillshare/internal/ui"
)
// recordAcceptedFindings persists the findings the user just overrode so
// later updates stop blocking on them.
func recordAcceptedFindings(sourceDir, repoPath string, result *audit.Result, threshold string) {
n, err := install.RecordAcceptedFindings(sourceDir, repoPath, result, threshold)
if err != nil {
ui.Warning("Failed to record accepted findings: %v", err)
return
}
if n > 0 {
ui.Info("Recorded %d accepted finding(s); future updates won't block on them", n)
}
}
// auditScanFunc abstracts the audit scan call so the same gate logic
// can be used for both global mode (audit.ScanSkill) and project mode
// (audit.ScanSkillForProject with a captured projectRoot).
@@ -27,7 +40,7 @@ type auditScanFunc func(repoPath string) (*audit.Result, error)
// - Non-TTY mode: automatically resets to beforeHash and returns error.
//
// Returns the audit result (may be nil if skipped or on error) and any error.
func auditGateAfterPull(repoPath, beforeHash string, skipAudit bool, threshold string, scanFn auditScanFunc) (*audit.Result, error) {
func auditGateAfterPull(sourceDir, repoPath, beforeHash string, skipAudit, force bool, threshold string, scanFn auditScanFunc) (*audit.Result, error) {
if skipAudit {
return nil, nil
}
@@ -48,17 +61,26 @@ func auditGateAfterPull(repoPath, beforeHash string, skipAudit bool, threshold s
return nil, fmt.Errorf("security audit failed: %v — rolled back (use --skip-audit to bypass): %w", err, audit.ErrBlocked)
}
if n := install.ApplyAcceptedFindings(sourceDir, repoPath, result); n > 0 {
ui.Info("%d previously accepted finding(s) skipped", n)
}
if !result.HasSeverityAtOrAbove(normalizedThreshold) {
return result, nil
}
// Show findings
for _, f := range result.Findings {
if audit.SeverityRank(f.Severity) <= audit.SeverityRank(normalizedThreshold) {
if !f.Acknowledged && audit.SeverityRank(f.Severity) <= audit.SeverityRank(normalizedThreshold) {
ui.Warning("[%s] %s (%s:%d)", f.Severity, f.Message, f.File, f.Line)
}
}
if force {
ui.Warning("Findings at/above %s; proceeding due to --force", normalizedThreshold)
recordAcceptedFindings(sourceDir, repoPath, result, normalizedThreshold)
return result, nil
}
if ui.IsTTY() {
fmt.Printf("\n Security findings at %s or above detected.\n", normalizedThreshold)
fmt.Printf(" Apply anyway? [y/N]: ")
@@ -66,6 +88,7 @@ func auditGateAfterPull(repoPath, beforeHash string, skipAudit bool, threshold s
answer, _ := reader.ReadString('\n')
answer = strings.TrimSpace(strings.ToLower(answer))
if answer == "y" || answer == "yes" {
recordAcceptedFindings(sourceDir, repoPath, result, normalizedThreshold)
return result, nil
}
// User declined → rollback
@@ -202,7 +225,7 @@ func updateTrackedRepo(uc *updateContext, repoName string) (updateResult, error)
// Post-pull audit gate
scanFn := uc.auditScanFn()
if _, err := auditGateAfterPull(repoPath, info.BeforeHash, uc.opts.skipAudit, uc.opts.threshold, scanFn); err != nil {
if _, err := auditGateAfterPull(uc.sourcePath, repoPath, info.BeforeHash, uc.opts.skipAudit, uc.opts.force, uc.opts.threshold, scanFn); err != nil {
return updateResult{securityFailed: 1}, err
}
@@ -347,7 +370,7 @@ func updateTrackedRepoQuick(uc *updateContext, repoPath string) (bool, *audit.Re
}
// Post-pull audit gate
auditResult, auditErr := auditGateAfterPull(repoPath, info.BeforeHash, uc.opts.skipAudit, uc.opts.threshold, uc.auditScanFn())
auditResult, auditErr := auditGateAfterPull(uc.sourcePath, repoPath, info.BeforeHash, uc.opts.skipAudit, uc.opts.force, uc.opts.threshold, uc.auditScanFn())
if auditErr != nil {
return false, auditResult, auditErr
}
+2 -4
View File
@@ -26,10 +26,8 @@ func cmdUpdateProject(args []string, root string) (*updateResult, error) {
opts.all = true
}
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return nil, err
}
if err := ensureProjectConfig(root); err != nil {
return nil, err
}
runtime, err := loadProjectRuntime(root)
+2 -1
View File
@@ -26,7 +26,8 @@ RUN apt-get update \
&& rm -rf /var/lib/apt/lists/*
# Install Go development tools
RUN go install github.com/air-verse/air@latest \
# air pinned: v1.67.2+ requires go >= 1.26, image runs GO_VERSION with GOTOOLCHAIN=local
RUN go install github.com/air-verse/air@v1.67.1 \
&& go install github.com/go-delve/delve/cmd/dlv@latest
# Copy node runtime from ui-builder stage (for devcontainer / interactive use)
+4
View File
@@ -8,9 +8,12 @@ require (
github.com/charmbracelet/glamour v0.10.0
github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834
github.com/charmbracelet/x/ansi v0.11.6
github.com/gofrs/flock v0.12.1
github.com/mattn/go-runewidth v0.0.19
github.com/pelletier/go-toml/v2 v2.2.4
github.com/pterm/pterm v0.12.82
github.com/sergi/go-diff v1.4.0
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a
golang.org/x/sys v0.38.0
golang.org/x/term v0.32.0
gopkg.in/yaml.v3 v3.0.1
@@ -46,6 +49,7 @@ require (
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.16.0 // indirect
github.com/sahilm/fuzzy v0.1.1 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yuin/goldmark v1.7.8 // indirect
+18 -4
View File
@@ -6,6 +6,8 @@ atomicgo.dev/keyboard v0.2.9 h1:tOsIid3nlPLZ3lwgG8KZMp/SFmr7P0ssEN5JUsm78K8=
atomicgo.dev/keyboard v0.2.9/go.mod h1:BC4w9g00XkxH/f1HXhW2sXmJFOCWbKn9xrOunSFtExQ=
atomicgo.dev/schedule v0.1.0 h1:nTthAbhZS5YZmgYbb2+DH8uQIZcTlIrd4eYr3UQxEjs=
atomicgo.dev/schedule v0.1.0/go.mod h1:xeUa3oAkiuHYh8bKiQBRojqAMq3PXXbJujjb0hw8pEU=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/MarvinJWendt/testza v0.1.0/go.mod h1:7AxNvlfeHP7Z/hDQ5JtE3OKYT3XFUeLCDE2DQninSqs=
github.com/MarvinJWendt/testza v0.2.1/go.mod h1:God7bhG8n6uQxwdScay+gjm9/LnO4D3kkcZX4hv9Rp8=
github.com/MarvinJWendt/testza v0.2.8/go.mod h1:nwIcjmr0Zz+Rcwfh3/4UhBp7ePKVhuBExvZqnKYWlII=
@@ -66,6 +68,10 @@ github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxK
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E=
github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ=
github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
@@ -79,8 +85,9 @@ github.com/klauspost/cpuid/v2 v2.0.10/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuOb
github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c=
github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU=
github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
@@ -108,6 +115,8 @@ github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pterm/pterm v0.12.27/go.mod h1:PhQ89w4i95rhgE+xedAoqous6K9X+r6aSOI2eFF7DZI=
@@ -123,6 +132,8 @@ github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
@@ -132,8 +143,10 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a h1:SJy1Pu0eH1C29XwJucQo73FrleVK6t4kYz4NVhp34Yw=
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a/go.mod h1:DFSS3NAGHthKo1gTlmEcSBiZrRJXi28rLNd/1udP1c8=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
@@ -193,8 +206,9 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
+57
View File
@@ -0,0 +1,57 @@
package audit
import (
"crypto/sha256"
"encoding/hex"
"strings"
)
// AcceptKey returns a stable key for acknowledging a finding across updates.
// Unlike Fingerprint it omits the line number, so an accepted finding survives
// edits elsewhere in the file. A different rule, file, or matched text yields
// a new key and blocks again.
func AcceptKey(f Finding) string {
raw := strings.Join([]string{
f.RuleID, f.Pattern, f.Analyzer, f.File, normalizeSnippet(f.Snippet),
}, "|")
h := sha256.Sum256([]byte(strings.ToLower(raw)))
return hex.EncodeToString(h[:])
}
// MarkAcknowledged flags findings whose AcceptKey is in keys. Acknowledged
// findings stay in the result for display but no longer count toward blocking.
// Returns the number of findings marked.
func (r *Result) MarkAcknowledged(keys []string) int {
if r == nil || len(keys) == 0 {
return 0
}
set := make(map[string]bool, len(keys))
for _, k := range keys {
set[k] = true
}
n := 0
for i := range r.Findings {
if set[AcceptKey(r.Findings[i])] {
r.Findings[i].Acknowledged = true
n++
}
}
return n
}
// AcceptKeysAtOrAbove returns keys for unacknowledged findings at or above
// threshold — the set a --force override accepts.
func (r *Result) AcceptKeysAtOrAbove(threshold string) []string {
normalized, err := NormalizeThreshold(threshold)
if err != nil {
normalized = DefaultThreshold()
}
cutoff := SeverityRank(normalized)
var keys []string
for _, f := range r.Findings {
if !f.Acknowledged && SeverityRank(f.Severity) <= cutoff {
keys = append(keys, AcceptKey(f))
}
}
return keys
}
+46
View File
@@ -0,0 +1,46 @@
package audit
import "testing"
func TestAcceptKey_IgnoresLineNumber(t *testing.T) {
a := Finding{RuleID: "prompt-injection-0", Pattern: "prompt-injection", File: "SKILL.md", Line: 5, Snippet: "Ignore previous instructions"}
b := a
b.Line = 42
if AcceptKey(a) != AcceptKey(b) {
t.Error("line number must not change the accept key")
}
b.Snippet = "SYSTEM: override"
if AcceptKey(a) == AcceptKey(b) {
t.Error("different snippet must change the accept key")
}
}
func TestResult_MarkAcknowledged_SkipsBlocking(t *testing.T) {
r := &Result{Findings: []Finding{
{Severity: SeverityCritical, Pattern: "prompt-injection", File: "SKILL.md", Snippet: "Ignore previous instructions"},
}}
keys := r.AcceptKeysAtOrAbove(SeverityCritical)
if len(keys) != 1 {
t.Fatalf("want 1 accept key, got %d", len(keys))
}
if n := r.MarkAcknowledged(keys); n != 1 {
t.Fatalf("want 1 marked, got %d", n)
}
if r.HasSeverityAtOrAbove(SeverityCritical) {
t.Error("acknowledged finding must not block")
}
if len(r.AcceptKeysAtOrAbove(SeverityCritical)) != 0 {
t.Error("acknowledged finding must not be re-accepted")
}
}
func TestResult_MarkAcknowledged_NewFindingStillBlocks(t *testing.T) {
r := &Result{Findings: []Finding{
{Severity: SeverityCritical, Pattern: "prompt-injection", File: "SKILL.md", Snippet: "Ignore previous instructions"},
{Severity: SeverityCritical, Pattern: "prompt-injection", File: "SKILL.md", Snippet: "SYSTEM: override"},
}}
r.MarkAcknowledged([]string{AcceptKey(r.Findings[0])})
if !r.HasSeverityAtOrAbove(SeverityCritical) {
t.Error("unacknowledged finding must still block")
}
}
+9 -5
View File
@@ -120,11 +120,12 @@ type Finding struct {
Snippet string `json:"snippet"` // trimmed matched line (no truncation)
// Phase 2 fields — analyzer traceability and deduplication.
RuleID string `json:"ruleId,omitempty"` // stable rule identifier
Analyzer string `json:"analyzer,omitempty"` // static|dataflow|tier|integrity|structure|cross-skill
Category string `json:"category,omitempty"` // injection|exfiltration|credential|obfuscation|...
Confidence float64 `json:"confidence,omitempty"` // 0~1
Fingerprint string `json:"fingerprint,omitempty"` // sha256 stable hash for deduplication
RuleID string `json:"ruleId,omitempty"` // stable rule identifier
Analyzer string `json:"analyzer,omitempty"` // static|dataflow|tier|integrity|structure|cross-skill
Category string `json:"category,omitempty"` // injection|exfiltration|credential|obfuscation|...
Confidence float64 `json:"confidence,omitempty"` // 0~1
Fingerprint string `json:"fingerprint,omitempty"` // sha256 stable hash for deduplication
Acknowledged bool `json:"acknowledged,omitempty"` // previously accepted via --force; excluded from blocking
}
// Result holds all findings for a single skill.
@@ -166,6 +167,9 @@ func (r *Result) HasSeverityAtOrAbove(threshold string) bool {
}
cutoff := SeverityRank(normalized)
for _, f := range r.Findings {
if f.Acknowledged {
continue
}
if SeverityRank(f.Severity) <= cutoff {
return true
}

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