Files
skillshare/tests/integration/extras_test.go
T
Willie d78e7ce09a feat(cli): redesign init and give every command one output style (#360)
* fix(install): omit the empty audit section in dry-run

A dry-run skips the security audit, yet the single-skill path still printed
the "Audit Findings" heading with nothing under it, which reads as if the
audit ran and found an empty result.

* feat(init): ask first, confirm a summary, then write

The old init asked nine questions in three input styles and wrote files as
it went, so cancelling midway left a half-built setup, and detection created
tool folders even under --dry-run. Connecting a second machine to an
existing repo was only offered at the very end, and the built-in skill
defaulted to "no", which read as "not recommended" (#200).

init now collects every answer into a plan, shows a summary with Yes /
Change settings / Cancel, and writes nothing until confirmed. Esc cancels
cleanly. A "Connect my existing skillshare repo" path checks the repo
before writing, detects its layout, prefers the repo version of same-name
skills and keeps local-only ones for the next push. The built-in skill is
installed by default, and the first sync runs at the end so the tools work
right away. Prompts use one inline huh-based component with theme colors.

Without a terminal (CI, scripts, AI agents) init now applies the same
defaults as pressing Enter and prints each decision with the flag that
changes it, instead of silently doing less; init -p and --discover add the
detected tools. Output that is not a terminal is plain text.

BREAKING CHANGE: non-interactive `init` now enables git, installs the
built-in skill and selects every detected tool; pass --no-git, --no-skill,
--no-targets or --no-copy for the previous minimal setup. Piped or
redirected output no longer contains ANSI colors; use --json where offered
for machine-readable output.

Refs #200

* docs(init): show the new init flow and the connect-a-repo path

The getting-started page still described the old four-question wizard with
a screenshot of it, the second-machine guide never mentioned the new
"Connect my existing skillshare repo" choice, and the recipe told users to
run pull and sync after init even though init now does both.

Replace the screenshot with ones from the new flow, describe the questions,
summary and cancel behavior, and explain what connecting a repo does before
and after confirmation. The devcontainer example gains --no-git because
init without a terminal now turns git on by default.

Refs #200

* feat(devcontainer): seed fake tools and a repo with ssenv --seed

Trying init by hand needed several manual steps to fake installed AI tools
and a skills repo to connect. `ssenv create --seed` (and `ssnew --seed`)
now creates claude/codex/cursor directories with a few skills and a local
bare repo at ~/remote/skills.git, so both init paths can be tried at once.

Refs #200

* fix(ui): skip the logo on 16-color terminals and hide the cursor while it plays

`docker exec -it` sets only TERM=xterm, which reads as 16 colors: the logo
was mapped onto the terminal's own palette and its fade-in collapsed into a
few flickering cells. Below 256 colors the banner now prints only its text,
and the devcontainer sets COLORTERM=truecolor.

The visible cursor also jumped along the logo's left edge while frames
redrew in place. It is hidden during the animation and restored on exit,
including Ctrl+C.

Refs #200

* style(ui): color the question mark in prompts

The uncolored "?" before each question read like a stray character. It
now uses the accent color of the "›" cursor.

Refs #200

* fix(init): name the root git scope by what it versions

"everything" suggested plugins, MCP servers and hooks were versioned too,
but they live in config.yaml, which the root scope gitignores. The option
and summary now say "skills, agents, extras" and note that those settings
stay in each machine's config.yaml.

Refs #200

* feat(init): show --discover in the new init style

--discover still printed the old header, "agent(s)" counts and "+ name"
lists next to the new prompt. Global and project discover now share
init's answered rows (Tools, Config) and a Next line, and call the
targets "AI tools" as init's banner does.

Refs #200

* feat(init): replace the pixel logo with a SKILLSHARE wordmark

The half-block logo looked stretched on terminals with tall line height
and turned to mush when shrunk to fit. init now opens with a three-line
pixel wordmark, SKILL in blue and SHARE in gold, that lights up from left
to right, followed by the version and tagline on one dim line. The
generated logo data and its generator script are gone.

Without a terminal, without color, below 256 colors or on a narrow
terminal, the banner still prints a plain "skillshare vX" line.

Refs #200

* refactor(init): label the chosen tools "Targets"

init called them "Tools" while the rest of the CLI, the config file and
the `target` command call them targets. The answered rows and the summary
now say "Targets", the same label the other commands will use. Sentences
that describe what was detected ("Found 3 AI tools") stay as they are.

The docs tables, the First Sync steps and both init screenshots are
updated to match.

Refs #200

* feat(cli): ask yes/no questions with the inline prompt

uninstall, trash empty, extras remove, target add, collect, update,
upgrade and audit each printed their own "[y/N]:" line and parsed the
answer by hand, while init already used the inline Yes/No prompt. They
now share it: esc answers no, and a declined question prints one dim
"Cancelled. Nothing was …" line, as init's cancel now does too.

Without a terminal the prompt reads one line from stdin instead, so
piped answers such as `echo y | skillshare uninstall x` keep working.
It reads byte by byte so a second question still gets its own answer.

Refs #200

* feat(sync): report each target on one aligned row

Sync printed a ruled header, a "Backing up" block and a "name: merged
(43 linked, 0 local, 0 updated, 0 pruned)" line per target, so the
counts that changed were hard to find among zeros. It now follows the
init style: one row per target with only the non-zero counts, a single
Backup row, and a closing line with the duration. `sync --all` names
its Skills, Agents and Extras blocks and no longer explains how to set
up extras when none are configured.

The non-TTY text changes with it; `--json` stays the stable interface
for scripts. Tests match rows through the new AssertRowContains helper.

Refs #200

* feat(status): show targets as one table

Status printed each target as a header with indented skills and agents
lines full of bracketed modes and zero counts, and the audit policy as
four lines of uppercase labels. Comparing targets meant reading every
block. Each target is now one row with a skills and an agents column,
a single line names the modes in use, and audit and version take one
line each. Global and project mode share the renderer, so project
paths read relative to the project root.

Refs #200

* feat(install): report each step on one aligned row

Install printed a logo, a box-drawn tree, "Next Steps" bullets and a
separate "Audit Findings" block, so the result was hard to find. It now
uses the same rows as sync and status: Source, Audit and Install with
the destination folded to ~, then a closing line and a Next block.

Spinners write through a gate that Stop closes before clearing the line.
pterm's render goroutine checks IsActive and then writes, so a fast step
such as install --dry-run left "Copying files..." stuck in front of the
next line.

Refs #200

* feat(uninstall): confirm against one line and point at undo

Uninstall opened with a boxed header and Name/Path lines, and closed
with the trash folder path and a "Next Steps" bullet. Now one line names
the target, its folder and what it holds; the result is a single
"Uninstall x → trash, kept 7 days" row; and Next offers sync, the trash
restore command that undoes it, and the reinstall command when the
skill came from a remote source.

A batch run with --force or --dry-run no longer lists the targets twice,
since there is no question for the list to support. Mixed batches are
counted as items, not targets, which already names the AI tools.

Refs #200

* feat(update): report each skill or repo on one Update row

Update opened with an "Updating" header, the full source path and a
"0 tracked repo(s), 1 skill(s)" line, then printed a Changes box and two
success lines before "Next Steps". A single update is now an Update row
(source or commit count, time), the commits it pulled in dim text, the
Audit row, and Next. A batch ends with the audit result and one closing
line that leaves out zero counts.

Progress bars now clear themselves when they stop, like spinners, so a
finished batch no longer leaves "[3/3] ... 100% Done" behind.

Refs #200

* feat(check): list what needs attention and close with one line

Check opened with a header, the full source path and an item count,
counted skills with updates without naming them, and ended with two
"Run ..." hints. It now prints one row per repo, skill or agent that
needs attention (behind, update available, stale, failed), a closing
line that leaves out zero counts, and the update command under Next. A
single-name check is one row, like update.

Refs #200

* feat(push,pull): report commit, push and pull as aligned rows

Push and pull opened with a header and closed with "Push complete" or
"Pull complete", so they never said what they committed, where they
pushed, or what a pull brought in. Push now prints a Commit row (file
count and message) and a Push row naming the upstream branch, never the
remote URL since it can carry credentials. Pull prints a Pull row with
the commit and file counts and the commits themselves, as update does
for a tracked repository, before the sync output. Dry runs list the
changed files as ~ + - instead of raw porcelain codes, and error hints
are dim notes instead of info lines.

Refs #200

* feat(upgrade): report the CLI and the skill on one row each

Upgrade opened with the logo and printed a tree of steps per part
(current version, latest version, status) ending in "Already up to date
✓". Each part is now one row, such as "✓ CLI  v0.22.0 → v0.23.0 · 3.1s"
or "✓ Skill  v0.23.0, already up to date", with spinners that clear.
Sync is offered under Next only when the skill changed, and the star
request is a dim line at the end.

Refs #200

* feat(new): report the created skill on one row

New printed a "New Skill Created" header, the full path, and numbered
"Next steps" that told the user to edit the file and run sync. It now
prints "✓ Created  ~/…/SKILL.md", the folders a pattern added, and sync
under Next. A dry run shows the same row, a Preview section with the
template, and the dry-run line.

Refs #200

* feat(trash): list items and restores as aligned rows

The plain trash list printed each item as an info line with its size and
age in parentheses under a "Trash" header, and restore printed two
success/info lines plus a "Next Steps" label. The list is now rows of
name, size and age with one closing count, and restore is one row
naming where the item went back, with sync under Next. An item trashed
under a minute ago reads "just now" instead of "just now ago".

Refs #200

* feat(collect): list local items and results as aligned rows

Collect opened with a header, listed local items as "[target] path"
list items under a second header, then printed a third header before
the per-item results and a metric summary line. It now lists each local
item as a row (name, target, path), asks the inline confirm, prints one
row per result and closes with "Collected N skills" plus sync and,
when the source is a git repository, commit under Next.

Refs #200

* feat(hooks): show hooks and their changes as aligned rows

Hooks printed "Hooks source: <path>" as an info line, statuses through
the fixed-width Status helper, and results as sentences ending in
"Run 'skillshare hooks sync' when ready." Hooks and Agent file changes
are now rows, with conflicts marked as failures and inactive outputs as
warnings, saves and applies close with one line, and the next command
sits under Next. The list's "Pending sync" section no longer shows
entries that are already in place.

Refs #200

* feat(mcp): show servers, changes and checks as aligned rows

MCP printed "MCP source: <path>" as an info line, plan changes through
the fixed-width Status helper, results as sentences that named the next
command inline, and check summaries as "2 server(s) checked: 1
error(s)". Changes and parked servers are now rows with conflicts
marked as failures, saves and applies close with one line and Next, and
check marks each server with its findings beneath and closes with
"Checked 2 servers: 1 error". The Status helper had no callers left and
is removed.

Refs #200

* feat(plugin): show packages, plans and results as aligned rows

Plugin text output was raw "name · target · id · state" lines with
"Warning:", "Includes:" and "Revision:" prefixes, and the list walked a
map so packages came out in a different order each run. Packages,
discovered candidates, planned changes and results are now rows sorted
by name, marked by state (registered, not installed, pending, blocked,
failed), with details as dim notes and the dry-run line after a
preview. JSON output is unchanged.

Refs #200

* feat(audit): replace header and summary boxes with rows

Audit framed its context in a header box (mode, path, block rule,
policy), numbered batch results "[1/2]", printed per-skill verdicts as
"→ Aggregate risk / Block decision" lines, and closed with a Summary box
that listed every count including zeros. The context is now one title
line with a dim note, flagged skills are aligned rows with their highest
severity, the summary leaves out zero counts, and the run closes with
one line saying whether anything was blocked and by which severity,
followed by the command to see the first blocked skill's findings.

The progress bar no longer writes its final frame when stdout is not a
terminal; that frame had no newline and ran into the next line.

Refs #200

* feat(audit): show audit rules as aligned rows

The rules list was a fixed-width table framed by 90-character dividers
with a "(N rules: N enabled, N disabled)" footer, and rule changes were
sentences like "Set severity for X → HIGH". Rules are now rows keyed by
ID with a colored severity and the pattern dimmed, disabled rules dim
as a whole, the list closes with a count that names disabled rules only
when there are some, and each change is one row.

Refs #200

* feat(search): drop the logo and tree, show results as rows

Search opened with the ASCII logo, drew its progress as a ├─/└─ tree,
listed results under a column header with dividers, and ended installs
with "Run 'skillshare sync' to distribute to all targets". Results are
now aligned rows with the source, stars or risk, and the description
and tags beneath; a single install reports the same Install row as
`skillshare install`; batch installs list only failures before one Done
line; and sync and audit sit under Next. Login and rate-limit problems
name the command that fixes them. Non-terminal output no longer prints
a "name: installing..." line per skill.

Refs #200

* feat(backup): show backups and restores as rows with one closing line

Backup and restore opened with headers, announced dry runs with a
warning before doing anything, summarized with an operation box, and
followed a backup with a "Recent backups" list. Targets now back up in
name order as rows with folded paths, runs close with one Done line
(and Next restore), listings are rows keyed by timestamp or path with a
total, and dry runs end with the shared dry-run line. Cleanup reports
how many backups remain instead of a separate "Current" line.

Refs #200

* feat(help): one line per command, subcommands in each command's help

The top-level help opened with the ASCII logo and listed about 70 lines
across ten uppercase sections plus 15 examples, so it did not fit a
screen, yet it left out analyze and the common options. It now lists
each command once in six groups with the common options, and points to
`<command> --help` for subcommands. The mcp, plugin, hooks and extras
pages use the same layout and keep all their content.

A mistyped command prints one error with the closest command instead
of the whole help, a lone option such as --no-tui shows the help, and
`skillshare version` prints one line.

Refs #200

* feat(extras): show extras and their changes as rows with Next

Extras printed a header, "→ name" lines with ad-hoc colored marks
(including ✗ for targets that were only waiting for a sync), and ended
each change with a sentence naming the next command. The list now shows
each extra as a bold name over aligned target rows (! for drift or not
synced) and closes with a count and, when something is pending, Next
sync extras. Init, collect, add/remove target, mode and source changes
close with one Done line, details become notes, and dry-run collect
ends with the shared dry-run line.

Refs #200

* feat(target): show targets as sections and rows with Next

Target info and the plain list printed "Key:" lines at two indent
levels, with "(none)" for every unset filter, and remove printed
"Backing up" / "Unlinking" headers with one line per step. Info now
shows the name over Skills and Agents sections with aligned rows, the
list gives each target one row per resource with details dimmed, and
empty filters are left out. Remove reports one row per target (plus
its backups) and closes with a Done count; dry runs say what would
happen per target and end with the shared dry-run line. Skills on/off,
add and mode/naming/filter changes close with Done and Next.

Refs #200

* feat(doctor): report checks as aligned rows and end with Next

Doctor opened with the ASCII logo, split its report under divider
headers, mixed ✓/→/! lines with full paths and "(s)" counts, listed
targets in random map order, and ended with a bare warning count that
left the fix to scattered "Run:" hints. Checks now print as aligned
rows under bold sections (Environment, Targets, Extras, MCP/hooks/
plugins, Storage, Version), paths fold to ~, targets are sorted with
one row per resource, and the report closes with a Done line plus up
to three Next commands collected from the checks (sync, sync agents,
sync hooks, upgrade, ...). The --json output is unchanged.

Refs #200

* feat(hub): drop the logo and report hub changes with Done

hub index opened with the ASCII logo and a tree of spinner steps, then
repeated the result as "→ Mode / Skills / Output" lines with the full
path. It now shows one spinner that clears itself and a Done line
naming the folded output path, skill count and duration, with the
index contents as a note. hub list shows aligned rows with the default
and built-in hubs marked in dim text instead of a "*" column, and the
add, remove and default commands close with a Done line.

Refs #200

* test(install): match the shared dry-run line in online tests

The online-tagged install tests still looked for the old "dry-run"
banner, which install no longer prints since the restyle. They are
skipped by default, so the mismatch only showed under -tags online.

Refs #200

* fix(target): align remove rows on target names only

The label column was sized for "<name>-agents" so an agents backup
could fit, which left a wide gap on every row when no agents were
backed up. The agents backup row now uses the target name too and says
"agents backed up", so the column fits the names.

Refs #200

* fix(update): list each item in a batch dry run

A batch dry run only said "Would update N skills". Off a terminal the
names leaked out through the progress bar's title lines, but on a
terminal those lines clear, so the dry run never said which skills or
repos it would touch. It now prints one Update row per item, as the
single-item dry run does.

Refs #200

* fix(ui): keep the progress bar silent off a terminal

Off a terminal the bar printed "Title (0/N)", every title change and
every phase header as permanent lines, which a terminal shows only as
a frame that clears itself. Audit left a stale "Scanning skills (0/7)"
line, and scripts saw different content than a terminal. The bar now
prints nothing off a terminal, like the spinner.

Refs #200

* fix(audit): avoid a double blank line before Summary

The audit header ends with a blank line and Summary added its own, so
a clean scan with no result rows showed two blank lines in a row. The
Summary title no longer adds one; the result rows add it when present.

Refs #200

* fix(mcp): drop the blank line above "Saved the MCP source"

A save with no backup or migration notes printed a blank line with
nothing above it, so mcp add and mcp edit opened on an empty line.

Refs #200

* fix(doctor): stop repeating the extra's name in its findings

Extras findings printed "rules  rules → /home/me/.claude/rules: 1
file(s) out of sync": the row label already names the extra, the path
was not folded to ~, and the count used "file(s)". The rows now start
at the arrow, fold the path and pluralize the count. JSON details keep
the extra's name so each line still stands alone.

Refs #200

* fix(doctor): show integrity issues as rows under Integrity

Tampered skills and missing hashes printed as free "! Skill integrity:
N skill(s) ..." lines after the verified row, breaking the aligned
Environment rows. They now sit under a single Integrity row, which
turns to ! when any skill has an issue.

Refs #200

* fix(doctor): pluralize the Skillignore and Trash rows

The rows read "1 patterns, 1 skills ignored" and "1 item(s) (50 B),
oldest <1 day". They now read "1 pattern, 1 skill ignored" and "1 item,
50 B · oldest under a day". The JSON messages keep their wording, since
scripts may match on them.

Refs #200

* docs: show the restyled output of batch 3 commands

The reference pages still showed the old output of upgrade, new, trash,
collect, audit, search, backup, restore, extras, hub, target and doctor:
divider headers, arrow-prefixed lines and "(s)" plurals. The examples
now match what the commands print, in all five locales, and the doctor
check table uses the new row labels.

Refs #200

* feat(trash): let trash empty skip its confirmation with --force

Scripts had no way to empty the trash: off a terminal the confirmation
reads stdin and cancels on EOF. --force (-f) skips it, as it does for
uninstall and extras remove.

Refs #200

* fix(doctor): show source, link and target problems as rows

Missing sources, unsupported links, folders without SKILL.md, unknown
skill targets, bad include/exclude patterns and broken symlinks printed
as free "✗ Source not found: …" lines between the aligned rows. They
now use the row of the check they belong to, and broken symlinks or a
missing source add a Next suggestion.

Refs #200

* fix(ui): leave out durations that would read 0.0s

Fast commands ended with "· 0.0s", which says nothing. Every result line
now formats its time through ui.Took, which init already used for its
steps: durations under 0.05s are left out.

Refs #200

* fix(ui): print dev builds without a v prefix

Version labels were built as "v" + version everywhere, so a dev
build printed "vdev". VersionLabel adds the prefix only when the
version starts with a digit, and the logo, help header, version
command and upgrade output share it.

Refs #200

* fix: pluralize category and drop "just now ago"

The checklist status bar appended "s" to its item name and printed
"categorys". The trash TUI formatted ages with its own helper that
added "ago" after "just now". plural now handles consonant + y,
and the trash TUI uses the shared timeAgo, which makes formatAge
unused.

Refs #200

* fix(target): drop the parenthesized counts in the plain list

The plain target list printed "merged (43 shared, 0 local)" while
target info and doctor print "merged · 43 shared" with zero counts
left out. The sync summary now returns both forms from one scan, so
the TUI and --json keep their existing text and the plain list
matches the other commands.

Refs #200

* test(backup): make the agents backup test back something up

The test only synced agents, which become symlinks into the source
and are skipped by backup, so it passed without any backup being
written. It now adds a target-local agent and checks that the file
lands in the backup.

Refs #200

* refactor(cli): render every command's --help with printHelp

About forty help pages were hand-aligned raw strings with "Usage:",
"Options:" and "Examples:" headings, while hooks, mcp, plugin, extras
and the top-level help already used printHelp. They now share it, so
headings, option order (short flag first) and alignment match across
commands. Examples align on their own column so long commands no
longer push option descriptions to the right, and "--help, -h" rows
are dropped as on the converted pages.

Refs #200

* feat(enable): print enable and disable results as rows

enable/disable still used the old "Disabled: x (added to .skillignore)"
line plus a "Run skillshare sync" sentence. They now print one row per
pattern, a Next hint after a change, and the dry-run closing line,
like the other restyled commands.

Refs #200

* fix(sync): pluralize the leftover cleanup note

Project sync printed "Cleaned 1 leftover skill(s)". The note now
uses the singular or plural noun, and the sync docs show it as the
dim note it is instead of an arrow line.

Refs #200

* fix(cli): drop the arrow info lines left in install, update and sync

These commands were restyled, but about fifty messages still went
through ui.Info, which prints a leading arrow, and several said
"skill(s)" or "item(s)". Hints now print as dim notes, empty results
("No agents found") as closing lines, follow-up commands as Next,
and counts use the singular or plural noun.

Refs #200

* fix(cli): tidy small leftovers found in the recorded output

doctor printed "0 minutes ago" for a fresh backup and an ASCII arrow in
the Update row, unlike trash and upgrade, which say "just now" and
"v1.2.0 → v1.3.0". The "bring the Targets up to date" hint capitalized
a word mid-sentence, and search --list showed hub sources under the
home directory as a cut-off absolute path instead of folding it to ~.
JSON messages keep their wording.

Refs #200

* fix(search): fit a home-folded source path in the list

Folding the home directory to ~ was not enough: a typical local hub
path such as ~/.config/skillshare/skills/frontend/react is 42
characters, so the 40-character cap still cut it. Fifty characters
next to the 24-character name column stays within 80 columns.

Refs #200

* feat(list): print the plain list with rows and a closing count

The --no-tui list still used the old header with a divider and an arrow
on every skill, so it looked unlike every other restyled command. Skills
now line up in one column under their group, tracked repos use the
✓ / ! marks, and the list closes with a count split by tracked, remote
and local (zero counts left out). Project mode keeps its scope as a dim
"· project" after the title.

Global and project had copied the same plain-output code; both now call
printSkillList. The loading spinner clears itself instead of leaving a
"Loaded N skills" line.

Refs #200

* fix(cli): show help for subcommand --help instead of running it

target add/remove/list, trash list/empty and hub list/remove passed
--help through as an argument, so they ran the command, failed on a
target or hub named "--help", or rejected the flag. tui on --help even
switched the TUI on. Each now prints its command's help page.

The tui status and toggle lines also move to the row and Done style.

Refs #200

* feat(diff): print differences as rows and close with next steps

The plain diff still printed a Summary line, divider headers, arrow
hints and per-target "scanning" lines when output was not a terminal.
Each group of targets now lists one row per kind of change ("New  a,
b"), targets in sync share a single ✓ row, extras use the same rows,
and diff closes with a count and up to three commands. The suggested
sync command follows what differs: sync, sync agents, sync extras or
sync --all.

Agents no longer show as "New 1 skill", because rows name the change
rather than counting skills. "skillshare diff all", listed in the help,
failed with "target 'all' not found"; it now diffs everything, the
same as no argument.

Refs #200

* test: sync the install warning summary and gofmt two status tests

The "6 findings" wording changed in an earlier commit, but the unit
test under cmd/ still expected "6 finding(s)": scripts/test.sh and
make check only run ./internal and ./tests, so the cmd tests never ran.
Two status tests also had comment alignment gofmt rejects, which fails
make check's fmt-check.

Refs #200

* test: run the cmd unit tests in scripts/test.sh

CI runs go test ./cmd/skillshare/... ./internal/..., but the local
runner behind make test and make check only ran ./internal/..., so a
stale assertion in cmd/skillshare passed locally and would only fail
in CI.

Refs #200

* feat(cli): restyle commit and analyze output

commit and analyze were the last git and inspection commands still
printing the old header and table layouts. They now use the same rows,
Done line, and Next hints as push and pull, so a commit reads like the
commit row of push, and analyze shows each target group as a bold name
with aligned token rows instead of a boxed table.

Refs #200

* feat(log): show entries as rows and fold the log path

The plain log view still opened each section with a boxed header that
printed the absolute log path, then a TIME | CMD | STATUS table. Entries
now read like every other command: a status mark, the command, when it
ran and how long it took, with details indented beneath. The log path is
folded to ~ and moves to a dim footnote.

log --stats drops its divider and ends with one summary line. It and
the TUI stats panel said "just now ago" for a fresh entry; both now use
timeAgo, which already handles that case.

Refs #200

* feat(cli): restyle completion, ui and leftover arrow lines

completion --install, ui start/stop and a few notices still printed
arrow info lines with absolute paths. They now end with a Done line,
fold paths to ~, and give config-file lines their own bold heading so
the lines to paste read apart from the hints. The empty extras TUI now
says the same thing as extras list.

Refs #200

* feat(init): report git changes on an existing setup as rows

init --remote and init --git-root on an existing setup still printed
arrow lines with absolute paths and spinner results in a different
voice. They now print aligned Git, Remote, Pull and Git root rows like
a fresh init, end a dry run with the shared Dry run line, and give the
choices after a remote check as Next commands.

A source repo the user created before init had no fallback identity,
so on a machine without git config the follow-up commit failed and
dumped git's whole "Please tell me who you are" message. The existing
repo now gets the same local fallback a new one does.

Refs #200

* feat(doctor): warn when a newer built-in skill is published

status already compared the skillshare skill with the published one,
but doctor only printed the local version, so a run meant to find
problems called an old skill healthy. doctor now fetches the published
version alongside the CLI update check and suggests upgrade --skill.

Both commands share a semver comparison. status compared with !=, so a
skill ahead of main (a dev build) was reported as having an update.

Refs #200

* fix(cli): count batch audit warnings in words and clear progress spinners

The batch install and update audit summary still printed "2 skill(s)"
and "warning(s)" after the rest of the output switched to "1 skill" /
"2 skills". uninstall and agent update also left "Found N skills" and
"Check complete" behind, progress messages the restyle clears.

Refs #200

* fix(cli): say so when diff or analyze has no targets

With no targets configured, diff reported "No differences" and analyze
printed only its "Add -v" hint, both reading like a healthy result.
They now say no targets are configured and suggest target add, as
target list does.

Refs #200

* fix(diff): align values across target sections

Each target section sized its labels on its own, so a section with
"Local only" started its values two columns later than one with only
"New", and the list read ragged. All sections now share one width.

Refs #200

* fix(doctor): count built-in skill warnings in the summary

The skill rows (not found, missing version, newer version available)
were marked as warnings and counted by --json, but never reached the
text summary, so doctor could print "! Skill not found" and close with
"All checks passed". The all-good integration test only passed because
of this; it now installs the built-in skill it needs.

Refs #200

* fix(init): stop writing a git identity into existing repos

On a repo the user created, init stored skillshare@local in the repo
config so its one commit would work. That setting outranks --global,
so the advice we printed never took effect and later pushes went out
as skillshare@local. The commit now gets the fallback through env
vars only. The note for repos init creates names the repo-level
command that actually overrides it.

Dry runs also wrote .gitignore into existing repos while closing with
"nothing was written", and warned about --no-git when it was not
passed; both now only describe what would happen.

Refs #200

* fix(cli): tell "no targets" apart from "nothing reaches them"

diff and analyze said "No targets configured" and suggested adding one
whenever there was nothing to show, including when targets exist but
have skills turned off or no skill is meant for them.

Refs #200

* fix(log): drop the trailing separator on instant entries

Entries with no recorded duration ended in a dangling " · ". Also
removes the formatRelativeTime alias the stats restyle left unused;
its test now covers formatDurationShort directly.

Refs #200

* docs: match tui, project list and log examples to the real output

The tui and project list examples used label widths the CLI does not
print, and the plain log example claimed to show non-TTY output, which
joins each entry's details on one line.

Refs #200

* perf(version): cache the published skill version for a day

doctor and status asked GitHub for the latest skill version on every
run, adding up to 3 s when offline. They now reuse the answer for 24
hours, the same interval the CLI update check caches for. upgrade
--skill still fetches fresh and records what it got.

Refs #200

* perf(server): reuse the cached skill version on the dashboard

The version endpoint fetched the published skill version on every
call, like doctor and status did, so it now shares their 24-hour
cache. It also treated any difference as an update, offering a
"newer" skill to anyone running a local build ahead of main.

Refs #200

* test(redteam): match the restyled update --diff heading

update --diff now titles its file list "Files changed" in sentence case,
like every other section, so the check for the list looked for the old
"Files Changed" box title and failed although the list was there.

Refs #200

* test(cli): keep /tmp fixtures unfolded where HOME is /tmp

scripts/test.sh now runs the cmd unit tests, so the docker sandbox runs
them too, with HOME=/tmp. shortenPath then folds the /tmp fixtures in
four tests to ~ and their exact-path checks fail. The tests now point
the cached home elsewhere while they run.

Refs #200

* fix(init): find skills/ in a repo that holds nothing else

The check for a skills/ folder ran only when the repo root had no skill
folders, but it counted skills/ itself as one, so it never ran. A repo
with only skills/ became the source as a whole, one level too high.

Refs #200

* fix(init): keep the skills git scope for a custom source

With a remote that has no skills yet, init defaulted to versioning the
whole skillshare folder. For a --source outside that folder it holds
none of the user's skills, so the commit and every later push carried
nothing while init reported the remote as linked.

Refs #200

* test(sync): check only the Agents section for updated agents

The restyle turned the old "0 updated" check on the agent summary into
"no 'updated' anywhere", which also covered the Skills section. On
macOS the first project sync reports the skill as updated there, so
the test failed on something it was never meant to check.

Refs #200
2026-10-03 21:43:35 +08:00

1493 lines
49 KiB
Go

//go:build !online
package integration
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/testutil"
)
// TestExtras_Init_Global verifies that "extras init" creates the source directory
// and persists the extra entry in the global config.
func TestExtras_Init_Global(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Need at least a minimal config so config.Load() succeeds.
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
`)
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
result := sb.RunCLI("extras", "init", "rules", "--target", rulesTarget, "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "Created extras/rules/")
// Verify source directory was created under extras/
sourceDir := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
if _, err := os.Stat(sourceDir); os.IsNotExist(err) {
t.Errorf("expected extras source dir %s to exist", sourceDir)
}
// Verify config.yaml now contains extras section
configContent := sb.ReadFile(sb.ConfigPath)
if !strings.Contains(configContent, "extras:") {
t.Errorf("expected config to contain 'extras:', got:\n%s", configContent)
}
if !strings.Contains(configContent, "rules") {
t.Errorf("expected config to contain 'rules', got:\n%s", configContent)
}
}
// TestExtras_Init_InvalidName verifies that names with invalid characters are rejected.
func TestExtras_Init_InvalidName(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
`)
result := sb.RunCLI("extras", "init", "../bad", "--target", "/tmp/x", "-g")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "invalid")
}
// TestExtras_Init_ReservedName verifies that reserved names (e.g. "skills") are rejected.
func TestExtras_Init_ReservedName(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
`)
result := sb.RunCLI("extras", "init", "skills", "--target", "/tmp/x", "-g")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "reserved")
}
// TestExtras_List_Empty verifies that "extras list" reports nothing when no extras are configured.
func TestExtras_List_Empty(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
`)
result := sb.RunCLI("extras", "list", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "No extras configured")
}
// TestExtras_List_WithExtras verifies that "extras list" shows extra name and file count.
func TestExtras_List_WithExtras(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
// Create extras source directory with files.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding"), 0644)
os.WriteFile(filepath.Join(rulesSource, "testing.md"), []byte("# Testing"), 0644)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("extras", "list", "-g")
result.AssertSuccess(t)
// The count and extra name should be present.
result.AssertAnyOutputContains(t, "1 extra")
result.AssertAnyOutputContains(t, "rules")
// File count should be shown in the source line.
result.AssertAnyOutputContains(t, "2 files")
}
// TestExtras_Remove verifies that "extras remove --force" removes the entry from config
// while leaving source files intact.
func TestExtras_Remove(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
// Create extras source with a file.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding"), 0644)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("extras", "remove", "rules", "--force", "-g")
result.AssertSuccess(t)
// Config should no longer contain the extras entry.
configContent := sb.ReadFile(sb.ConfigPath)
if strings.Contains(configContent, "name: rules") {
t.Errorf("expected config to no longer contain 'name: rules', got:\n%s", configContent)
}
// Source files should still exist.
sourceFile := filepath.Join(rulesSource, "coding.md")
if !sb.FileExists(sourceFile) {
t.Error("source file should be preserved after remove")
}
}
// TestExtras_SyncExtras_Global verifies that "sync extras" syncs files from the
// extras source directory into the configured target.
func TestExtras_SyncExtras_Global(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Create extras source with files.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding"), 0644)
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("sync", "extras", "-g")
result.AssertSuccess(t)
result.AssertOutputContains(t, "\nExtras\n")
// Sync verb or file count should appear
result.AssertAnyOutputContains(t, "synced")
// Verify file was symlinked into target.
codingLink := filepath.Join(rulesTarget, "coding.md")
if !sb.IsSymlink(codingLink) {
t.Error("coding.md should be a symlink in target after sync")
}
}
// TestExtras_Init_Duplicate verifies that initialising an extra with an already-used
// name is rejected.
func TestExtras_Init_Duplicate(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
// Config already has an extra named "rules".
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("extras", "init", "rules", "--target", rulesTarget, "-g")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "already exists")
}
// TestExtras_Init_Force_Global verifies that "extras init --force" overwrites
// an existing extra in global mode.
func TestExtras_Init_Force_Global(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
oldTarget := filepath.Join(sb.Home, ".claude", "rules")
newTarget := filepath.Join(sb.Home, ".cursor", "rules")
os.MkdirAll(oldTarget, 0755)
os.MkdirAll(newTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
// Config already has an extra named "rules" pointing to oldTarget.
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + oldTarget + `
`)
// Re-init with --force and a different target.
result := sb.RunCLI("extras", "init", "rules", "--target", newTarget, "--force", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "Created extras/rules/")
// Config should contain the new target, not the old one.
configContent := sb.ReadFile(sb.ConfigPath)
if !strings.Contains(configContent, newTarget) {
t.Errorf("expected config to contain new target %s, got:\n%s", newTarget, configContent)
}
if strings.Contains(configContent, oldTarget) {
t.Errorf("expected config to NOT contain old target %s, got:\n%s", oldTarget, configContent)
}
}
// TestExtras_Init_Force_Project verifies that "extras init --force -p" overwrites
// an existing extra in project mode.
func TestExtras_Init_Force_Project(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
projectRoot := sb.SetupProjectDir("claude")
oldTarget := filepath.Join(projectRoot, ".claude", "rules")
newTarget := filepath.Join(projectRoot, ".claude", "prompts")
os.MkdirAll(oldTarget, 0755)
os.MkdirAll(newTarget, 0755)
// Project config already has an extra named "rules".
sb.WriteProjectConfig(projectRoot, `targets:
- claude
extras:
- name: rules
targets:
- path: `+oldTarget+`
`)
// Re-init with --force and a different target.
result := sb.RunCLIInDir(projectRoot, "extras", "init", "rules", "--target", newTarget, "--force", "-p")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "Created .skillshare/extras/rules/")
// Project config should contain the new target, not the old one.
projConfigPath := filepath.Join(projectRoot, ".skillshare", "config.yaml")
configContent := sb.ReadFile(projConfigPath)
if !strings.Contains(configContent, newTarget) {
t.Errorf("expected project config to contain new target %s, got:\n%s", newTarget, configContent)
}
if strings.Contains(configContent, oldTarget) {
t.Errorf("expected project config to NOT contain old target %s, got:\n%s", oldTarget, configContent)
}
}
// TestExtras_Init_SourceNotSupportedInProjectMode verifies that --source is
// rejected in project mode with a clear error message.
func TestExtras_Init_ProjectSourceMustBeRelative(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
projectRoot := sb.SetupProjectDir("claude")
target := filepath.Join(projectRoot, ".claude", "rules")
os.MkdirAll(target, 0755)
result := sb.RunCLIInDir(projectRoot, "extras", "init", "rules",
"--target", target,
"--source", "/some/custom/path",
"-p")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "must be relative to the project root")
}
// TestExtras_Source_Show verifies that "extras source" shows the current extras_source.
func TestExtras_Source_Show(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
customExtras := filepath.Join(sb.Home, "custom-extras")
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
extras_source: ` + customExtras + `
targets:
claude:
path: ` + claudeTarget + `
`)
result := sb.RunCLI("extras", "source", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "extras_source")
result.AssertAnyOutputContains(t, "custom-extras")
}
// TestExtras_Source_ShowDefault verifies that "extras source" shows the default
// path when extras_source is not explicitly set.
func TestExtras_Source_ShowDefault(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
`)
result := sb.RunCLI("extras", "source", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "(default)")
}
// TestExtras_Source_Set verifies that "extras source <path>" updates extras_source
// in the global config.
func TestExtras_Source_Set(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
`)
newExtras := filepath.Join(sb.Home, "new-extras")
result := sb.RunCLI("extras", "source", newExtras, "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "Set extras_source")
// Verify config was updated
configContent := sb.ReadFile(sb.ConfigPath)
if !strings.Contains(configContent, newExtras) {
t.Errorf("expected config to contain %s, got:\n%s", newExtras, configContent)
}
}
// TestExtras_Source_ProjectModeRejected verifies that "extras source -p" is rejected.
func TestExtras_Source_ProjectModeRejected(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
projectRoot := sb.SetupProjectDir("claude")
result := sb.RunCLIInDir(projectRoot, "extras", "source", "-p")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "not supported in project mode")
}
// TestExtras_Collect verifies that "extras collect" moves local (non-symlink) files
// from a target directory into the extras source and replaces them with symlinks.
func TestExtras_Collect(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Create extras source directory.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
// Create target directory with a local (non-symlink) file.
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
localFile := filepath.Join(rulesTarget, "local-rule.md")
os.WriteFile(localFile, []byte("# Local Rule"), 0644)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("extras", "collect", "rules", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "Collected")
// File should now exist in source.
sourceFile := filepath.Join(rulesSource, "local-rule.md")
if !sb.FileExists(sourceFile) {
t.Error("collected file should exist in extras source directory")
}
// Original location should now be a symlink.
if !sb.IsSymlink(localFile) {
t.Error("original file should be replaced with a symlink after collect")
}
// Symlink should point to the source file.
if got := sb.SymlinkTarget(localFile); got != sourceFile {
t.Errorf("symlink target = %q, want %q", got, sourceFile)
}
}
// TestExtras_Collect_DryRun verifies that "extras collect --dry-run" reports what
// would be collected without actually moving any files.
func TestExtras_Collect_DryRun(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Create extras source directory.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
// Create target directory with a local file.
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
localFile := filepath.Join(rulesTarget, "dry-rule.md")
os.WriteFile(localFile, []byte("# Dry Rule"), 0644)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("extras", "collect", "rules", "--dry-run", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "Would collect")
// File should NOT have been moved to source.
sourceFile := filepath.Join(rulesSource, "dry-rule.md")
if sb.FileExists(sourceFile) {
t.Error("dry run should not move file to source")
}
// Original file should still be a regular file, not a symlink.
if sb.IsSymlink(localFile) {
t.Error("dry run should not replace file with symlink")
}
}
// TestExtras_Collect_ForceCopyMode verifies that "extras collect --force" pulls
// target edits back over an existing source file, and that copy-mode targets
// keep regular files instead of becoming symlinks.
func TestExtras_Collect_ForceCopyMode(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
sourceFile := filepath.Join(rulesSource, "rule.md")
os.WriteFile(sourceFile, []byte("# Old"), 0644)
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
localFile := filepath.Join(rulesTarget, "rule.md")
os.WriteFile(localFile, []byte("# Edited in target"), 0644)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
mode: copy
`)
// Trailing slash: --from must still match the configured copy-mode target.
result := sb.RunCLI("extras", "collect", "rules", "--from", rulesTarget+"/", "--force", "-g")
result.AssertSuccess(t)
if got := sb.ReadFile(sourceFile); got != "# Edited in target" {
t.Errorf("source content = %q, want target edit", got)
}
if sb.IsSymlink(localFile) {
t.Error("copy-mode target should stay a regular file after collect")
}
}
// TestExtras_Status verifies that "status" shows extras information when extras are configured.
func TestExtras_Status(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Create extras source with files.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding"), 0644)
os.WriteFile(filepath.Join(rulesSource, "testing.md"), []byte("# Testing"), 0644)
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("status", "-g")
result.AssertSuccess(t)
// Status should show an "Extras" section.
result.AssertAnyOutputContains(t, "Extras")
// Should report file count and target path.
result.AssertRowContains(t, "rules", "~/.claude/rules 2 files")
}
// TestExtras_DiffExtras verifies that "diff" automatically shows extras that need syncing.
func TestExtras_DiffExtras(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Create extras source with a file.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
os.WriteFile(filepath.Join(rulesSource, "pending.md"), []byte("# Pending"), 0644)
// Create target directory but do NOT sync yet.
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("diff", "--no-tui", "-g")
result.AssertSuccess(t)
// Output should show the extras diff section.
result.AssertAnyOutputContains(t, "Extras")
// Should indicate file needs syncing.
result.AssertAnyOutputContains(t, "pending.md")
}
// TestExtras_SyncExtras_JSON verifies that "sync extras --json" produces valid JSON
// output with an extras array.
func TestExtras_SyncExtras_JSON(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Create extras source with a file.
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding"), 0644)
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("sync", "extras", "--json", "-g")
result.AssertSuccess(t)
// Verify JSON structure.
if !strings.Contains(result.Stdout, `"extras"`) {
t.Errorf("expected JSON to contain 'extras' key, got:\n%s", result.Stdout)
}
if !strings.Contains(result.Stdout, `"rules"`) {
t.Errorf("expected JSON to contain 'rules' entry, got:\n%s", result.Stdout)
}
if !strings.Contains(result.Stdout, `"duration"`) {
t.Errorf("expected JSON to contain 'duration' key, got:\n%s", result.Stdout)
}
}
// TestExtras_SyncAll_Project verifies that "sync --all -p" syncs both skills and extras
// in project mode.
func TestExtras_SyncAll_Project(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Set up a project directory with a claude target.
projectRoot := sb.SetupProjectDir("claude")
// Create a project skill.
sb.CreateProjectSkill(projectRoot, "proj-skill", map[string]string{
"SKILL.md": "# Project Skill",
})
// Create project extras source.
extrasSource := filepath.Join(projectRoot, ".skillshare", "extras", "rules")
os.MkdirAll(extrasSource, 0755)
os.WriteFile(filepath.Join(extrasSource, "proj-rule.md"), []byte("# Project Rule"), 0644)
// Create extras target directory.
extrasTarget := filepath.Join(projectRoot, ".claude", "rules")
os.MkdirAll(extrasTarget, 0755)
// Write project config with both skills target and extras using absolute path.
sb.WriteProjectConfig(projectRoot, `targets:
- claude
extras:
- name: rules
targets:
- path: `+extrasTarget+`
`)
result := sb.RunCLIInDir(projectRoot, "sync", "--all", "-p")
result.AssertSuccess(t)
// Verify extras were synced (symlink created in target).
ruleLink := filepath.Join(extrasTarget, "proj-rule.md")
if !sb.IsSymlink(ruleLink) {
t.Errorf("project extras should be synced as symlink after sync --all -p\nstdout: %s\nstderr: %s",
result.Stdout, result.Stderr)
}
}
// TestExtras_Doctor verifies that "doctor" reports a missing extras source directory as an error.
func TestExtras_Doctor(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
// Config references extras "rules" but we do NOT create the source directory.
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("doctor", "-g")
result.AssertSuccess(t)
// Doctor should report the missing extras source.
result.AssertAnyOutputContains(t, "rules")
result.AssertAnyOutputContains(t, "missing")
}
// TestExtras_Migration verifies that "sync extras" migrates a legacy flat extras directory
// (configDir/name/) to the new location (configDir/extras/name/).
func TestExtras_Migration(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Create the OLD-style (legacy) directory: configDir/rules/ (not extras/rules/).
configDir := filepath.Join(sb.Home, ".config", "skillshare")
legacySource := filepath.Join(configDir, "rules")
os.MkdirAll(legacySource, 0755)
os.WriteFile(filepath.Join(legacySource, "legacy.md"), []byte("# Legacy Rule"), 0644)
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("sync", "extras", "-g")
result.AssertSuccess(t)
// After migration, the new location should exist and legacy should be gone.
newSource := filepath.Join(configDir, "extras", "rules")
if _, err := os.Stat(newSource); os.IsNotExist(err) {
t.Errorf("expected migrated directory at %s to exist", newSource)
}
if _, err := os.Stat(legacySource); err == nil {
t.Errorf("expected legacy directory %s to be removed after migration", legacySource)
}
// The file should be accessible from the new location.
migratedFile := filepath.Join(newSource, "legacy.md")
if !sb.FileExists(migratedFile) {
t.Error("migrated file should exist in new extras directory")
}
// File should be synced as symlink in target.
ruleLink := filepath.Join(rulesTarget, "legacy.md")
if !sb.IsSymlink(ruleLink) {
t.Error("migrated file should be synced as symlink in target")
}
}
// TestExtras_Mode_SingleTarget verifies that "extras mode" changes the sync mode
// of an extra's target when the extra has only one target (auto-resolved).
func TestExtras_Mode_SingleTarget(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding"), 0644)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
// Change mode from merge (default) to copy
result := sb.RunCLI("extras", "rules", "--mode", "copy", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "copy")
// Verify config was updated
configContent := sb.ReadFile(sb.ConfigPath)
if !strings.Contains(configContent, "mode: copy") {
t.Errorf("expected config to contain 'mode: copy', got:\n%s", configContent)
}
}
// TestExtras_Mode_Shorthand verifies the shorthand form:
// "extras <name> --mode <mode>" (without the "mode" subcommand).
func TestExtras_Mode_Shorthand(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
// Use shorthand: extras rules --mode symlink
result := sb.RunCLI("extras", "rules", "--mode", "symlink", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "symlink")
configContent := sb.ReadFile(sb.ConfigPath)
if !strings.Contains(configContent, "mode: symlink") {
t.Errorf("expected config to contain 'mode: symlink', got:\n%s", configContent)
}
}
// TestExtras_Mode_WithTarget verifies that "extras <name> --mode" with --target
// changes the mode on a specific target when multiple targets exist.
func TestExtras_Mode_WithTarget(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget1 := filepath.Join(sb.Home, ".claude", "rules")
rulesTarget2 := filepath.Join(sb.Home, ".cursor", "rules")
os.MkdirAll(rulesTarget1, 0755)
os.MkdirAll(rulesTarget2, 0755)
rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(rulesSource, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget1 + `
- path: ` + rulesTarget2 + `
`)
// Change mode of second target only
result := sb.RunCLI("extras", "rules", "--target", rulesTarget2, "--mode", "copy", "-g")
result.AssertSuccess(t)
configContent := sb.ReadFile(sb.ConfigPath)
// The second target should have mode: copy, first should remain default (merge)
if !strings.Contains(configContent, "mode: copy") {
t.Errorf("expected config to contain 'mode: copy' for second target, got:\n%s", configContent)
}
}
// TestExtras_Mode_MultipleTargets_NoTarget verifies that "extras <name> --mode" errors
// when the extra has multiple targets and --target is not specified.
func TestExtras_Mode_MultipleTargets_NoTarget(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget1 := filepath.Join(sb.Home, ".claude", "rules")
rulesTarget2 := filepath.Join(sb.Home, ".cursor", "rules")
os.MkdirAll(rulesTarget1, 0755)
os.MkdirAll(rulesTarget2, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget1 + `
- path: ` + rulesTarget2 + `
`)
result := sb.RunCLI("extras", "rules", "--mode", "copy", "-g")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "--target")
}
// TestExtras_Mode_InvalidMode verifies that an invalid mode is rejected.
func TestExtras_Mode_InvalidMode(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
extras:
- name: rules
targets:
- path: ` + rulesTarget + `
`)
result := sb.RunCLI("extras", "rules", "--mode", "invalid", "-g")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "invalid")
}
// TestExtras_Mode_UnknownExtra verifies that mode change on non-existent extra fails.
func TestExtras_Mode_UnknownExtra(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + claudeTarget + `
`)
result := sb.RunCLI("extras", "nonexistent", "--mode", "copy", "-g")
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "not found")
}
// TestInit_WritesSourcesMap verifies that fresh "init" emits the new
// `sources:` map (v0.19.16+) with skills and agents entries, and does NOT
// write the legacy top-level source / agents_source / extras_source fields.
// The extras parent directory is provided at runtime by
// Config.EffectiveExtrasSource() — it does not need to be persisted.
func TestInit_WritesSourcesMap(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Remove config file to simulate fresh state
os.Remove(sb.ConfigPath)
// Run a fully non-interactive init
result := sb.RunCLI("init", "--no-copy", "--no-targets", "--no-git", "--no-skill")
result.AssertSuccess(t)
configContent := sb.ReadFile(sb.ConfigPath)
// New format: must contain `sources:` map with skills/agents entries.
if !strings.Contains(configContent, "sources:") {
t.Errorf("expected config to contain 'sources:' map, got:\n%s", configContent)
}
if !strings.Contains(configContent, "skills: "+sb.SourcePath) {
t.Errorf("expected sources.skills to point to %s, got:\n%s", sb.SourcePath, configContent)
}
expectedAgents := filepath.Join(filepath.Dir(sb.SourcePath), "agents")
if !strings.Contains(configContent, "agents: "+expectedAgents) {
t.Errorf("expected sources.agents to point to %s, got:\n%s", expectedAgents, configContent)
}
// Legacy fields must NOT be written by fresh init.
if strings.Contains(configContent, "\nsource:") {
t.Errorf("expected no legacy 'source:' field, got:\n%s", configContent)
}
if strings.Contains(configContent, "extras_source:") {
t.Errorf("expected no legacy 'extras_source:' field, got:\n%s", configContent)
}
if strings.Contains(configContent, "agents_source:") {
t.Errorf("expected no legacy 'agents_source:' field, got:\n%s", configContent)
}
}
// TestExtrasInit_PreservesEmptyExtrasSource verifies that "extras init" does
// NOT silently backfill the legacy extras_source field when it was absent.
// Config.EffectiveExtrasSource() handles the runtime fallback, so writing the
// derived path into the user's config would surprise them with an unexpected
// diff. The extras source directory must still be created on disk.
func TestExtrasInit_PreservesEmptyExtrasSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
// Write config WITHOUT extras_source
sb.WriteConfig(fmt.Sprintf("source: %s\ntargets:\n claude:\n path: %s",
sb.SourcePath, claudeTarget))
// Verify extras_source is absent before
configBefore := sb.ReadFile(sb.ConfigPath)
if strings.Contains(configBefore, "extras_source:") {
t.Fatalf("precondition: expected no extras_source, got:\n%s", configBefore)
}
// Run extras init
result := sb.RunCLI("extras", "init", "rules", "--target", rulesTarget, "-g")
result.AssertSuccess(t)
// Verify extras_source was NOT silently backfilled.
configAfter := sb.ReadFile(sb.ConfigPath)
if strings.Contains(configAfter, "extras_source:") {
t.Errorf("expected no extras_source backfill, got:\n%s", configAfter)
}
// But the derived extras source directory must still exist on disk so
// the new extra has somewhere to live.
expected := filepath.Join(filepath.Dir(sb.SourcePath), "extras", "rules")
if _, err := os.Stat(expected); err != nil {
t.Errorf("expected extras source directory %s to exist: %v", expected, err)
}
}
// TestExtrasInit_WithExtrasSource verifies that when extras_source is set in config,
// "extras init" creates the source dir under the custom extras_source path.
func TestExtrasInit_WithExtrasSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
customExtras := filepath.Join(sb.Home, "custom-extras")
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
sb.WriteConfig("source: " + sb.SourcePath + "\nextras_source: " + customExtras + "\ntargets:\n claude:\n path: " + claudeTarget)
result := sb.RunCLI("extras", "init", "rules", "--target", rulesTarget, "-g")
result.AssertSuccess(t)
// Source directory should be created under extras_source, not the default location.
rulesDir := filepath.Join(customExtras, "rules")
if _, err := os.Stat(rulesDir); os.IsNotExist(err) {
t.Errorf("expected extras source dir at %s\nstdout: %s\nstderr: %s", rulesDir, result.Stdout, result.Stderr)
}
// The default location should NOT have been created.
defaultDir := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
if _, err := os.Stat(defaultDir); err == nil {
t.Errorf("default extras dir %s should not exist when extras_source is set", defaultDir)
}
}
// TestExtrasInit_WithPerExtraSource verifies that --source flag writes the per-extra
// source path to config and creates the source directory at that location.
func TestExtrasInit_WithPerExtraSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
customSource := filepath.Join(sb.Home, "my-rules")
os.MkdirAll(customSource, 0o755)
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
sb.WriteConfig("source: " + sb.SourcePath + "\ntargets:\n claude:\n path: " + claudeTarget)
result := sb.RunCLI("extras", "init", "rules",
"--target", rulesTarget,
"--source", customSource,
"-g")
result.AssertSuccess(t)
// Config should contain the per-extra source path.
configContent := sb.ReadFile(sb.ConfigPath)
if !strings.Contains(configContent, customSource) {
t.Errorf("expected config to contain source %s, got:\n%s", customSource, configContent)
}
}
// TestExtrasList_SourceType verifies JSON output includes correct source_type
// for per-extra source overrides.
func TestExtrasList_SourceType(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
customSource := filepath.Join(sb.Home, "my-rules")
os.MkdirAll(customSource, 0o755)
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0o755)
sb.WriteConfig("source: " + sb.SourcePath + "\ntargets:\n claude:\n path: " + claudeTarget + "\nextras:\n - name: rules\n source: " + customSource + "\n targets:\n - path: " + rulesTarget)
result := sb.RunCLI("extras", "list", "--json", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "per-extra")
}
// TestExtrasSourcePriority verifies the 3-level source resolution priority chain:
// per-extra source > extras_source > default.
func TestExtrasSourcePriority(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
perExtra := filepath.Join(sb.Home, "per-extra-rules")
globalExtras := filepath.Join(sb.Home, "global-extras")
os.MkdirAll(perExtra, 0o755)
os.MkdirAll(filepath.Join(globalExtras, "commands"), 0o755)
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
commandsTarget := filepath.Join(sb.Home, ".claude", "commands")
os.MkdirAll(rulesTarget, 0o755)
os.MkdirAll(commandsTarget, 0o755)
sb.WriteConfig("source: " + sb.SourcePath +
"\nextras_source: " + globalExtras +
"\ntargets:\n claude:\n path: " + claudeTarget +
"\nextras:\n - name: rules\n source: " + perExtra +
"\n targets:\n - path: " + rulesTarget +
"\n - name: commands\n targets:\n - path: " + commandsTarget)
result := sb.RunCLI("extras", "list", "--json", "-g")
result.AssertSuccess(t)
// "rules" has per-extra source → source_type should be "per-extra"
result.AssertAnyOutputContains(t, "per-extra")
// "commands" falls back to extras_source → source_type should be "extras_source"
result.AssertAnyOutputContains(t, "extras_source")
}
// TestExtrasList_DefaultSourceType verifies that "extras list --json" shows
// source_type "default" when neither extras_source nor per-extra source is set.
func TestExtrasList_DefaultSourceType(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0o755)
// Create default extras source directory with a file so it reports as existing.
defaultSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
os.MkdirAll(defaultSource, 0o755)
os.WriteFile(filepath.Join(defaultSource, "coding.md"), []byte("# Coding"), 0o644)
// Config with extras but NO extras_source and NO per-extra source.
sb.WriteConfig("source: " + sb.SourcePath +
"\ntargets:\n claude:\n path: " + claudeTarget +
"\nextras:\n - name: rules\n targets:\n - path: " + rulesTarget)
result := sb.RunCLI("extras", "list", "--json", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, `"source_type"`)
result.AssertAnyOutputContains(t, `"default"`)
}
// TestExtrasSync_WithPerExtraSource verifies that sync uses the per-extra source path
// instead of the default location.
func TestExtrasSync_WithPerExtraSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
// Create a custom source directory with a file.
customSource := filepath.Join(sb.Home, "my-rules")
os.MkdirAll(customSource, 0o755)
os.WriteFile(filepath.Join(customSource, "custom.md"), []byte("# Custom Rule"), 0o644)
// Create target directory.
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0o755)
// Config with per-extra source pointing to custom location.
sb.WriteConfig("source: " + sb.SourcePath +
"\ntargets:\n claude:\n path: " + claudeTarget +
"\nextras:\n - name: rules\n source: " + customSource +
"\n targets:\n - path: " + rulesTarget)
result := sb.RunCLI("sync", "extras", "-g")
result.AssertSuccess(t)
// Verify symlink was created in target.
customLink := filepath.Join(rulesTarget, "custom.md")
if !sb.IsSymlink(customLink) {
t.Errorf("custom.md should be a symlink in target after sync\nstdout: %s\nstderr: %s",
result.Stdout, result.Stderr)
}
// Verify symlink points to the custom source, not the default.
expectedTarget := filepath.Join(customSource, "custom.md")
if got := sb.SymlinkTarget(customLink); got != expectedTarget {
t.Errorf("symlink target = %q, want %q", got, expectedTarget)
}
}
// TestExtrasSync_WithExtrasSource verifies that sync uses extras_source when set.
func TestExtrasSync_WithExtrasSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
// Create custom extras_source directory with the extra's subdirectory.
globalExtras := filepath.Join(sb.Home, "custom-extras")
rulesSource := filepath.Join(globalExtras, "rules")
os.MkdirAll(rulesSource, 0o755)
os.WriteFile(filepath.Join(rulesSource, "global-extra.md"), []byte("# Global Extra"), 0o644)
// Create target directory.
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0o755)
// Config with extras_source set (no per-extra source).
sb.WriteConfig("source: " + sb.SourcePath +
"\nextras_source: " + globalExtras +
"\ntargets:\n claude:\n path: " + claudeTarget +
"\nextras:\n - name: rules\n targets:\n - path: " + rulesTarget)
result := sb.RunCLI("sync", "extras", "-g")
result.AssertSuccess(t)
// Verify symlink was created from the extras_source location.
link := filepath.Join(rulesTarget, "global-extra.md")
if !sb.IsSymlink(link) {
t.Errorf("global-extra.md should be a symlink after sync\nstdout: %s\nstderr: %s",
result.Stdout, result.Stderr)
}
expectedTarget := filepath.Join(rulesSource, "global-extra.md")
if got := sb.SymlinkTarget(link); got != expectedTarget {
t.Errorf("symlink target = %q, want %q", got, expectedTarget)
}
}
// TestExtrasCollect_WithPerExtraSource verifies that collect moves files into
// the per-extra source directory, not the default location.
func TestExtrasCollect_WithPerExtraSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
// Create empty custom source directory.
customSource := filepath.Join(sb.Home, "my-rules")
os.MkdirAll(customSource, 0o755)
// Create target directory with a real (non-symlink) file.
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0o755)
localFile := filepath.Join(rulesTarget, "local-rule.md")
os.WriteFile(localFile, []byte("# Local Rule"), 0o644)
// Config with per-extra source.
sb.WriteConfig("source: " + sb.SourcePath +
"\ntargets:\n claude:\n path: " + claudeTarget +
"\nextras:\n - name: rules\n source: " + customSource +
"\n targets:\n - path: " + rulesTarget)
result := sb.RunCLI("extras", "collect", "rules", "-g")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "Collected")
// File should now exist in the custom source, not the default.
collectedFile := filepath.Join(customSource, "local-rule.md")
if !sb.FileExists(collectedFile) {
t.Errorf("collected file should exist in custom source %s", customSource)
}
// Default source location should NOT have the file.
defaultSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules", "local-rule.md")
if sb.FileExists(defaultSource) {
t.Error("file should NOT be collected to the default source when per-extra source is set")
}
// Original location should now be a symlink pointing to custom source.
if !sb.IsSymlink(localFile) {
t.Error("original file should be replaced with a symlink after collect")
}
if got := sb.SymlinkTarget(localFile); got != collectedFile {
t.Errorf("symlink target = %q, want %q", got, collectedFile)
}
}
// TestExtrasDoctor_WithCustomSource verifies that doctor reports the correct
// custom source path when per-extra source is configured.
func TestExtrasDoctor_WithCustomSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0o755)
// Config with per-extra source pointing to a non-existent directory.
nonExistentSource := filepath.Join(sb.Home, "does-not-exist-rules")
sb.WriteConfig("source: " + sb.SourcePath +
"\ntargets:\n claude:\n path: " + claudeTarget +
"\nextras:\n - name: rules\n source: " + nonExistentSource +
"\n targets:\n - path: " + rulesTarget)
result := sb.RunCLI("doctor", "-g")
result.AssertSuccess(t)
// Doctor should mention the custom path in its extras check.
result.AssertAnyOutputContains(t, "rules")
result.AssertAnyOutputContains(t, "missing")
}
// TestExtrasRemove_WithPerExtraSource verifies that remove works correctly
// when per-extra source is configured.
func TestExtrasRemove_WithPerExtraSource(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0o755)
// Create custom source directory with a file.
customSource := filepath.Join(sb.Home, "my-rules")
os.MkdirAll(customSource, 0o755)
os.WriteFile(filepath.Join(customSource, "coding.md"), []byte("# Coding"), 0o644)
// Config with per-extra source.
sb.WriteConfig("source: " + sb.SourcePath +
"\ntargets:\n claude:\n path: " + claudeTarget +
"\nextras:\n - name: rules\n source: " + customSource +
"\n targets:\n - path: " + rulesTarget)
result := sb.RunCLI("extras", "remove", "rules", "--force", "-g")
result.AssertSuccess(t)
// Config should no longer contain the extras entry.
configContent := sb.ReadFile(sb.ConfigPath)
if strings.Contains(configContent, "name: rules") {
t.Errorf("expected config to no longer contain 'name: rules', got:\n%s", configContent)
}
// Source files should still exist (remove only removes from config).
if !sb.FileExists(filepath.Join(customSource, "coding.md")) {
t.Error("source file in custom path should be preserved after remove")
}
}
// TestExtrasSync_SkipsMissingSourceDir verifies that "sync extras" skips an
// extra whose source directory does not exist, with a hint, instead of
// creating it.
func TestExtrasSync_SkipsMissingSourceDir(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
// Set extras_source to a non-existent directory
customExtras := filepath.Join(sb.Home, "new-extras-dir")
// Don't create it — sync should skip the extra
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
os.MkdirAll(rulesTarget, 0755)
sb.WriteConfig(fmt.Sprintf("source: %s\nextras_source: %s\ntargets:\n claude:\n path: %s\nextras:\n - name: rules\n targets:\n - path: %s",
sb.SourcePath, customExtras, claudeTarget, rulesTarget))
result := sb.RunCLI("sync", "extras", "-g")
result.AssertSuccess(t)
// Verify source dir was not created
rulesDir := filepath.Join(customExtras, "rules")
if _, err := os.Stat(rulesDir); !os.IsNotExist(err) {
t.Errorf("sync must not create source dir at %s, stat err = %v", rulesDir, err)
}
// Verify output explains the skip
result.AssertAnyOutputContains(t, "source folder not found")
result.AssertAnyOutputContains(t, "Create it to start syncing rules")
}
// TestExtrasInit_WithExtrasSource_AutoCreatesDir verifies that "extras init"
// creates the source directory under extras_source even if the extras_source
// directory itself doesn't exist yet.
func TestExtrasInit_WithExtrasSource_AutoCreatesDir(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
claudeTarget := sb.CreateTarget("claude")
rulesTarget := filepath.Join(sb.Home, ".claude", "rules")
// extras_source points to a path where parent exists but extras_source itself doesn't.
customExtras := filepath.Join(sb.Home, "brand-new-extras")
// Intentionally do NOT create customExtras — init should create it.
sb.WriteConfig("source: " + sb.SourcePath +
"\nextras_source: " + customExtras +
"\ntargets:\n claude:\n path: " + claudeTarget)
result := sb.RunCLI("extras", "init", "rules", "--target", rulesTarget, "-g")
result.AssertSuccess(t)
// The directory should have been auto-created at extras_source/rules.
rulesDir := filepath.Join(customExtras, "rules")
if _, err := os.Stat(rulesDir); os.IsNotExist(err) {
t.Errorf("expected extras source dir at %s to be auto-created\nstdout: %s\nstderr: %s",
rulesDir, result.Stdout, result.Stderr)
}
// The default location should NOT have been created.
defaultDir := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
if _, err := os.Stat(defaultDir); err == nil {
t.Errorf("default extras dir %s should not exist when extras_source is set", defaultDir)
}
}
// Identical local files are kept; only differing files need --force.
func TestExtrasSyncPreservedLocalMessage(t *testing.T) {
for _, content := range []string{"same", "different"} {
t.Run(content, func(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
source := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules")
target := filepath.Join(sb.Home, ".claude", "rules")
for _, path := range []string{source, target} {
if err := os.MkdirAll(path, 0755); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(source, "a.md"), []byte("same"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(target, "a.md"), []byte(content), 0644); err != nil {
t.Fatal(err)
}
sb.WriteConfig("source: " + sb.SourcePath + "\nextras:\n - name: rules\n targets:\n - path: " + target + "\n mode: merge\n")
result := sb.RunCLI("sync", "extras", "-g")
result.AssertSuccess(t)
if content == "same" {
result.AssertAnyOutputContains(t, "1 local preserved")
if strings.Contains(result.Stdout+result.Stderr, "use --force") {
t.Fatal(result.Stdout + result.Stderr)
}
} else {
result.AssertAnyOutputContains(t, "1 files skipped (use --force to override)")
}
if got := sb.ReadFile(filepath.Join(target, "a.md")); got != content {
t.Fatalf("local file changed: %q", got)
}
})
}
}