feat: native hooks, MCP tool policy and Pi built-in MCP (v0.23.0) (#304)

* feat(hooks): manage native hooks across agents

Add global and project hook management for ten coding agents with native
format adapters, explicit ownership, revision-guarded synchronization and
selective backup/restore. Preserve unrelated native configuration and leave
hook execution and trust decisions with each agent.

Expose CLI commands and completions alongside dashboard import, editing,
native preview, target/project views, synchronization and backups. Localize
messages and document the workflows across supported locales.

Validation: devcontainer make check, full dashboard Vitest suite,
TypeScript/Vite build, scoped ESLint, isolated CLI lifecycle and real UI
acceptance. Native agent hook execution was not tested.

* feat(mcp)!: sync Pi only through its built-in MCP

Pi could be synced through three different mechanisms (built-in MCP,
pi-mcp-adapter, or the extension file), chosen per server. Mixing them
inside one scope was an error users hit easily, and the adapter and
extension files drifted from what Pi itself reads. Pi's built-in MCP
now covers what the other modes offered, so every Pi server is written
to ~/.pi/agent/mcp.json or <project>/.pi/mcp.json.

Existing setups migrate on the next sync: entries Skillshare wrote to
mcp-adapter.json are removed through the ownership ledger, extension
entries are rewritten in place, and hand-written entries stay put.
piExtension and piOptionsPrune still load (with a notice) so old
configs keep working, and are dropped on the next save. directTools is
kept but no longer rendered, since only the adapter reads it.

Pruning unchanged fields Skillshare wrote earlier is now always on,
the per-project off switch no longer applies to Pi, and the removed
--pi-extension and --pi-options-prune flags explain the change instead
of failing as unknown. Import still reads mcp-adapter.json read-only so
servers kept only there can be brought over.

BREAKING CHANGE: --pi-extension and --pi-options-prune were removed;
Pi servers are always synced to Pi's built-in MCP file.

* fix(mcp): load Pi switches and adapter options left from before 0.23.0

Phase 1 made Pi sync only through its built-in MCP, which left two
upgrade paths broken or misleading:

- A project entry with disabled: true that selected Pi used to work in
  adapter mode, but now fails every sync with "pi cannot turn off".
  Loading now takes pi (and Pi accounts) out of such an entry with a
  notice; an entry left with no targets stays and turns nothing off, so
  an explicit empty list is now valid for a switch. Saving a new switch
  for pi still fails.
- piOptions keys that only pi-mcp-adapter reads (lifecycle, idleTimeout,
  approveTools, ...) were copied into Pi's built-in mcp.json, where
  nothing reads them. Loading drops them with a notice naming each key,
  and saving new ones is refused. Keys neither Pi nor the adapter
  documents still pass through. includeTools/excludeTools are left for
  the tool policy change, which converts them.

Both changes rewrite the YAML node on load, like the phase 1 legacy
fields, so the next save persists them.

* feat(mcp): portable tool policy per server

Users need one place to say which of a server's tools the model sees,
instead of Pi-only adapter options that Pi's built-in MCP no longer
reads. A server's tools{expose, allow, deny} is rendered per Agent:
Pi gets exposure and an ordered toolExposure, Codex gets
enabled_tools/disabled_tools, Copilot gets its tools list. Parts an
Agent cannot hold (OpenCode and Kilo have no per-server field) are
named in the plan and by mcp check rather than dropped silently.

directTools and the adapter's includeTools/excludeTools are converted
on load and on import, so existing configs keep their behavior; the
--direct-tools flag is removed with a pointer to the new flags.
check --live now reports tool names so the dashboard can suggest them.

Refs #140

* feat(ui): drop the Pi mode, prune switch and Direct tools from MCP

Since 0.23.0 Pi syncs only through its built-in MCP and the API no longer
returns piExtension, so the server dialog showed an empty "Pi MCP mode"
select, links to pi-mcp-adapter and pi-mcp-extension, a prune switch the
backend ignores and adapter-only Direct tools. Toggling Pi also opened a
mode setup that no longer exists, and Pi was still offered as an Agent
that can turn a global server off per project, which the backend refuses.

Pi now shows only tool exposure, its other settings and one link to
Pi's MCP docs. The import dialog still sends piExtension, but only to
pick between Pi's mcp.json and the legacy mcp-adapter.json, which the
listed path already tells apart. Settings the config still carries from
before 0.23.0 are explained once on the MCP page from the source's
notices, worded in the dashboard's language.

* fix(ui): clarify hook takeover and localize MCP actions

Identify global and project hooks in sync previews, show full takeover guidance, and link project conflicts to their Hooks tab. Translate MCP pending actions using the existing locale keys.

* feat(mcp): name unapplied tool policy parts in the render preview

The dashboard's server editor needs to say which Agents cannot follow
part of a tool policy before the server is saved. The plan's notices
only cover saved servers, so each rendered target now carries the gaps
from toolPolicyGaps instead of the UI re-implementing the per-Agent rules.

Refs #140

* feat(ui): edit the portable MCP tool policy in the dashboard

Saving a server from the edit dialog rebuilt it from the form and
dropped its tools policy. The draft now carries tools, and a Tools
section edits exposure, allow and deny for every Agent at once. Tool
names can be loaded on demand from the saved server through the live
check, and each selected Agent that does not apply a part is named from
the backend's render preview.

Pi's other settings flag the adapter-only keys and the exposure fields
that Tools now owns, so the form refuses what the backend refuses with
a message that points to Tools. Rows show a short policy marker, and the
plan's tool policy notices are localized on the MCP page.

Refs #140

* feat(mcp): save the config without retired settings on sync

Notices about settings 0.23.0 retired (piExtension, piOptionsPrune,
adapter-only piOptions, Pi switch entries, directTools/includeTools/
excludeTools) only went away when the user happened to save MCP settings.
Sync never rewrote the source, so most users kept seeing them.

Loading already converts those settings in memory, so a sync now writes
the converted config back (global, per project, external source, CLI and
dashboard), after keeping the previous content in the file history.
Dry runs write nothing, and a failed save is reported after the Agent
files are applied. The plan carries `migrates`, so the dashboard's sync
runs MCP even when no Agent file changes.

The CLI notices are one short line per kind with each server named
once, and a sync prints the file it updated with its backup. The
dashboard no longer shows these notices: sync handles them with nothing
for the user to do, and tool policy gaps stay in the server dialog.

* fix(ui): catch MCP tool policy mistakes before saving

The empty "Other Pi settings" box showed a toolExposure example even
while Tools had a setting. That example is exactly what the dialog
refuses in that state, so it read as a saved value that went unflagged.
The example now leaves toolExposure out while Tools is set.

A Deny list that removes every tool Allow keeps was only refused by the
server, in English with raw field names. The Tools section now says so
in the user's language and disables Save; the server check stays.

* fix(ui): move Pi settings help into info tooltips

The Pi block stacked four lines of help under the exposure select, one
of them in raw config words (entry, toolExposure), which pushed the
fields apart. The help now sits behind keyboard-focusable info icons:
one on a new "Pi settings" heading, which keeps the official docs link
beside it since a tooltip cannot hold a link, and one on the exposure
label with a shorter, plain explanation. The line saying Tools sets the
exposure stays, because it explains why the select is locked.

* docs(mcp): describe Pi built-in only and the tool policy

0.23.0 dropped the Pi modes, the prune switch and directTools, and added a
portable tools policy (#140, #143). The MCP reference still told users to
pick pi-mcp-adapter and pass flags that now fail, and said nothing about
what the first sync does to an old config or which Agents apply which part
of a tool policy.

The reference now covers the tools field and flags with a per-Agent table
linked to each Agent's docs, the dashboard Tools section, Pi's built-in
files and options, and an upgrade section: what the first sync converts,
which adapter entries it removes, the config save with its migrate backup,
and what replaces each removed flag. The how-to, dashboard and backup pages
follow.

* docs(skill): teach the built-in skill the Pi and tool policy changes

Agents using the skill would still pass --pi-extension and --direct-tools,
which fail since 0.23.0, and would not know the tools policy or what a sync
does to a 0.22 Pi config. The MCP reference now matches the CLI; the
description is unchanged and stays within its size limit.

* test(mcp): cover Pi migration and the tool policy in the runbook

The runbook still exercised pi-mcp-extension, pi-mcp-adapter and
--pi-options-prune, all removed in 0.23.0. New steps check Pi built-in
cleanup, the first-sync conversion of a 0.22 config with its migrate
backup and untouched hand-written adapter entries, the removed-flag
messages, and what each Agent receives from one tool policy.

* docs(wiki): record the 0.23.0 MCP Pi and tool policy milestone

Keeps the design decisions and evidence limits of #140 and #143 (the
ledger-driven migration, the migrate backup, per-Agent translation rules)
where later work can find them without reading five phase reports.

* docs(i18n): mirror the Pi built-in and tool policy docs in four locales

The zh-Hant, zh-Hans, ja and ko MCP pages still described the removed Pi
modes and flags, and linked to anchors that no longer exist in English.
They now carry the tool policy, Pi, and upgrade sections with the English
anchors and dashboard labels taken from each locale's UI strings.

* feat(mcp): probe an unsaved server definition for the dashboard

Loading tools in the server dialog could only probe the saved config, so
editing a URL and clicking load tested the old address and surfaced a raw
"connection refused" for a server the user was already fixing. A new server
could not load tools at all until saved.

POST /api/mcp/probe runs the existing live probe on the definition in the
request, resolving env and header references as the saved-server check does,
and never saves or syncs. Failures carry an error kind (connect, timeout,
auth, protocol, command, unknown) so the dashboard can explain them in the
user's language and keep the raw text as detail.

* fix(ui): load MCP tools with the dialog's current settings

The Tools section now probes the connection as the form describes it, so
an edited URL or command is what gets tested and a new server can load its
tools before saving. Probe failures read as short localized messages with
the raw error behind Details instead of the probe's English text.

Loaded names are dropped when the connection fields change, since they may
no longer be this server's tools; editing Allow or Deny keeps them.

* docs(mcp): say Load tools probes the dialog's current settings

The MCP and UI references said the button starts the saved server and that
a new server must be saved first, which is no longer true.

* feat(ui): pick MCP tools from a loaded checklist

Typing exact tool names into allow/deny chip inputs made users guess
names the server already knows. The Tools section now loads the
server's tool list and lets users tick which tools the model gets;
unticking writes the exact name to deny, re-ticking removes it (and
adds it to a non-empty allow list), and rows removed by a deny
wildcard are locked with the rule named in a tooltip.

Wildcard and unlisted rules stay editable as chips in the same box,
and an outcome summary tells users which agents honor the list,
which honor it only partly, and which cannot filter tools at all, so
nobody assumes a filter applies where it does not.

* refactor(mcp): drop tools.expose in favor of Pi's own exposure

tools.expose only ever meant something to Pi, yet it sat in the
cross-Agent tool policy, locked Pi's exposure select whenever a policy
was set, and produced an "expose" gap for every other Agent. Pi's
exposure mode now lives only in piOptions.exposure: it can sit next to
a tool policy (only toolExposure still conflicts, since the policy
writes it), allowed tools inherit it, and pi-mcp-adapter's directTools
migrates to it. The flag and field were never released, so they are
removed without a shim.

The dashboard now describes a policy in plain words ("2 tools
excluded") instead of the old "2 denied" shorthand, shows Pi's
exposure on the server list in words, hints that Enter adds a rule,
and no longer leaves "{}" behind when an exposure is set and then
cleared.

* fix(hooks): make import a takeover and plans say what changes

A hands-on trial showed several rough edges in hooks management:

- Importing one per-event candidate such as claude-stop merged every event
  of the file into the entry, so unrelated hooks became managed.
- An imported hook then conflicted on the next sync as an "identical
  unmanaged hook" until --replace, although importing it was the takeover.
- Narrowing an entry was reported as "remove" of the whole file although
  only one event left it, and plans gave no event-level detail.
- A misspelled event such as Stopp was accepted silently and would never run.
- Rewriting a compact settings.json produced half compact, half indented
  JSON and left an empty hooks key Skillshare itself had added.

A name that matches a candidate now picks only that candidate. Saving an
import (Mutation.adopt) records the identical native registrations as the
entry's own even without sync, so the next sync adopts them in place; edits
made outside Skillshare afterwards still conflict. Changes carry added,
updated and removed events, and "remove" is reserved for an entry that leaves
the file. A per-Agent catalog of documented events, from each Agent's
official hooks reference, drives advisory plan warnings and is served at
GET /api/hooks/catalog. JSON edits keep the file's compact or indented style
and drop a hooks key once Skillshare empties the one it created.

* style(ui): keep clean theme switches and picked cards black and white

The clean theme is black-and-white only, so its on switches and picked
cards use ink instead of the green ok and blue accent colors. The playful
theme keeps its own colors.

* feat(hooks): return full file texts from the hooks preview

The dashboard can only show which Agent files a hooks change touches, not
what changes inside them. POST /api/hooks/preview now also returns files[]:
each native file the plan would change, with its current text and the exact
text sync would write, taken from the same plan apply writes from. Other
plan responses stay unchanged, and the route keeps the localhost-only guard.

* feat(hooks): manage Antigravity and Antigravity CLI hooks

Antigravity and its CLI (agy) are skills targets, but their hooks could
not be managed. Both read the same files, ~/.gemini/config/hooks.json and a
project's .agents/hooks.json, so they are one hooks Agent with
antigravity-cli and agy as aliases.

Antigravity's hooks.json maps hook names to blocks of events rather than
one event map. Each Skillshare hook becomes one block named after it, held
as a single owned element, so ownership, adoption, conflicts and restore
work as for the other Agents. Keeping the block's own name lets an import
take the block over in place; a same-named block Skillshare does not own is
a conflict until it is imported or replaced. Disabled blocks are not offered
for import, and edits keep the file's compact or indented style.

The event catalog lists the documented events (seconds timeouts), import
problems are no longer cleared before validation, and the schema and docs
cover the new Agent.

* fix(hooks): replace an edited registration in place

Acceptance found that --replace on a registration Skillshare owned but
someone edited outside appended a second copy: the edited one stayed in the
file, now unmanaged, next to the replacement. When the element at the
record's last written position is owned by no one, replace now overwrites it
there, for both an edit with --replace and 'hooks sync NAME --replace'.

Writing into a one-line array such as "Stop": [{...}] also mixed one-line
and indented layouts; elements written there now stay on that line. Import
candidate lists print an explanation shared by several rows once instead of
on every row.

* feat(ui): rebuild the hooks page around targets, the catalog and real diffs

Editing a hook meant typing event names from memory, repeating each
target by hand and saving JSON the dashboard could not check, and the
preview only listed actions without showing what would change in a
file. The backend now publishes each target's documented events and the
full before/after text of every file a preview touches, so the UI can
guide the whole flow instead of trusting free text.

- Event fields pick from the catalog with descriptions, and show the
  tool filter and timeout unit only where the target has them.
- An empty target tab offers to copy another target's commands, mapping
  events to their closest equivalent and converting timeout units, and
  says when an event has no counterpart.
- Native JSON gets completion, formatting and linting with the line and
  a suggested event, and never drops invalid text when switching back to
  fields; Cmd/Ctrl+S saves without syncing and Esc asks before
  discarding edits.
- The preview shows one card per file with event-level changes and a
  folded line diff that marks the user's own hooks as untouched.
- Import preloads each target's unmanaged hooks, saves only the checked
  ones with adopt so sync does not duplicate them, and keeps pasting as
  a secondary path.
- Antigravity joins the managed targets, the wording says targets
  throughout, and the remove dialog no longer contradicts itself.

* fix(hooks): keep key order and separators when replacing an element

Replacing a registration in place re-encoded it from a Go map, so its keys
came out sorted, and on a one-line array it was minimized without the
spaces the line used: [{"hooks": [{"type": "command", ...}]}] turned into
[{"hooks":[{"command":...,"type":"command"}]}]. The whole line then showed
as changed and read as a rewrite of the user's style.

A replaced element now keeps the replaced one's key order at every depth,
with new keys at the end, and elements written on a one-line array use the
line's own spacing after colons and commas.

* feat(hooks): stop managing a hook while keeping its entries

Removing a hook from the source always queued the removal of its native
entries on the next sync, so there was no way to hand a synced or adopted
hook back to the user. MCP already has this as `remove --keep-files`.

`hooks remove NAME --keep-files` (and `unmanage` in the API mutation)
removes the entry and forgets its ownership records in that scope, so sync
neither removes nor updates what it wrote; the entries show up as unmanaged
and importable again. It is rejected with --sync, like MCP.

The dashboard remove dialog adds "Stop managing" and now says what each
choice does to the target files, including that "Remove from source only"
still deletes the entries on the next sync. Its backup note is neutral and
the dialog is wider to fit the diff.

* fix(mcp): warn that Pi's built-in MCP needs Pi 0.99.0 and no old extension

The first sync after upgrading moves Pi servers off pi-mcp-adapter and
pi-mcp-extension into Pi's mcp.json. A user still on Pi before 0.99.0
silently loses every server, because older Pi does not read that file, and
Pi's docs say an installed extension that registers /mcp replaces the
built-in MCP. Nothing told them either.

The plan now adds one notice, shown by preview, sync and --json, when it
removes an entry Skillshare wrote to mcp-adapter.json, rewrites an owned
entry in pi-mcp-extension's format (the transport field), or the config
still has settings only the extensions read. The ledger check covers a
config that owns adapter entries without saying piExtension.

* docs(mcp): say what Pi needs before the first 0.23.0 sync

The upgrade section described how the config changes but not the two
things a user must do in Pi: run Pi 0.99.0 or later, and remove
pi-mcp-adapter or pi-mcp-extension, which Pi's docs say replace the
built-in MCP. It now shows the sync warning, lists every dropped adapter
option, and says a disabled entry no longer turns a server off for Pi in
that project. The import paragraph claimed sync never changes
mcp-adapter.json; it removes the entries it wrote there.

* fix(ui): make hook diffs, editors and the hooks rail readable

Supervisor and user trial of the rebuilt hooks page found diffs that
read as "we will touch your hook", an editor too small for real hooks,
and text cut short in the rail.

- Diffs: removed lines red and added lines green through new diff theme
  tokens (the one colour exception in the clean theme), removals before
  additions, lines differing only by a trailing comma or whitespace kept
  as context, long lines wrapped, and the "left as is" marker on its own
  line. An adopt-only card says the file is unchanged.
- Editors: native JSON and code editors expand over the dialog and back
  as the same editor, so lint, completion, format, the error count and
  Cmd/Ctrl+S keep working; Esc closes completion first. The invalid-JSON
  explanation sits above the editor.
- Dialogs are 880px like MCP's.
- Main page: full target paths wrap under the name with no inner scroll
  box, the sync card shows the target file, empty descriptions are
  hidden, the unmanaged note avoids an orphaned character, and the row
  menu uses a hooks-specific "each target" label.
- Import names follow the CLI (<target>-<event>) or a script's basename.

* feat(ui): show MCP plan notices before a sync

The API returned the plan's notices, but no dashboard view showed them, so
dashboard users never saw that the 0.23.0 sync rewrites their config or
that Pi's built-in MCP needs Pi 0.99.0 and no old extension. The MCP sync
dialog and the Sync page now list them, translated through mcp.notice.*
keys; a notice the UI does not know is shown as the server sent it.

* fix(install): default CLI installs to the user-local bin directory

Use ~/.local/bin so ordinary script installs and upgrades do not require administrator access. Preserve INSTALL_DIR overrides and existing installations, verify the installed binary directly, and show PATH setup only when needed.

Add offline installer regressions and align installation guidance across all five documentation locales, including automation PATH setup.

Validation: seven offline installer cases, make check in the devcontainer, all five website locale builds, and AI context checks passed.

* fix(ui): let stop managing succeed and open the source config from the header

Stop managing sent a mutation whose plan differs from the removal preview the
dialog had loaded, because the server forgets the ownership records first, so
the revision never matched and every attempt failed as stale. Both the hooks
and MCP remove dialogs now preview that mutation before saving it; it writes no
target file, so there is no diff to review. Its toast also says the entries
stay in the files instead of "Removed".

The source path line under the lists took space most people never read. A
config.yaml button in the page header now shows the full path on hover and
opens the Config page editor; a separate sources.mcp file has no editor there,
so that case copies the path instead.

The Pi chip on a server row no longer mentions other Pi settings.

* test(server): replay the dashboard's hooks and MCP requests against the handlers

UI tests mock the API with one fixed revision, so a dialog that saves with a
revision from the wrong preview passed every vitest while "Stop managing"
failed in real use. These tests send the exact mutation JSON and preview
revision each dialog uses (remove, stop managing, edit, toggle, takeover,
import/adopt, restore, global and project sync) in global, hooks.projects
or mcp.projects, and project-mode scopes, and pin that hooks refuses an
unmanage saved with the removal preview's revision.

* fix(ui): show comma-only line changes in the hooks diff

A line that only gained or lost a trailing comma was shown as unchanged
with its new text, so the preview hid a real byte change to the file.
Lines still align ignoring the comma, so an added sibling does not shift
unrelated lines, but a differing pair now shows as removed and added,
removals first within each change. The user's own event keeps its
"left as is" note on the new line.

* fix(hooks): name the events a Copilot hook file changes

Copilot keeps each hook in its own file, so its plan changes carried no
events and the preview card showed only the action while every other
Agent listed "+ SessionStart" and the like. The planner now compares the
file's hooks map before and after the write and reports added, updated
and removed events the same way shared files do.

* feat(ui): open config.yaml at the section the header button came from

The config.yaml button on the Hooks and MCP pages opened the editor at
the top, leaving the user to scroll for the part that page manages. It
now links to /config?section=hooks or ?section=mcp, and the Config page
puts the cursor on that top-level key and scrolls it into view once the
file is loaded. A config without the key opens at the top as before.

* fix(ui): say what hooks and MCP dialogs will really do

Trying hooks across eight targets showed several places where the
dashboard hid or misstated the outcome:

- Remove and sync writes every pending change of the scope, but the
  hooks and MCP remove dialogs only named the removed entry; they now
  name the other hooks or servers that go out with it.
- With more than three targets, each remove choice spelled out every
  target; it now gives the count.
- Preview cards shrank to their header in a long list and hid the diff.
- A hook's summary listed SessionStart and sessionStart as separate rows
  with no hint of which target runs which; rows now merge case-only
  differences and show their targets' icons.
- Save and sync used the same toast as a plain save.
- The copy panel promised the closest events even when a target had
  none; it now says those events must be picked by hand.
- The Hooks rail's expandable target rows had no accessible name.

* fix(ui): pair hooks diff lines only at the same indentation

Diff lines were aligned ignoring leading whitespace, so appending an
event paired the file's closing braces with braces inside the new block.
Once differing pairs show as removed and added, that turned one comma
change into a run of removed closing braces. Only the trailing comma is
ignored now, so the diff shows the comma pair and the added lines.

* fix(ui): explain each hook removal choice on its own button

The three consequence lines sat in the dialog body, away from the buttons
they describe, and made the dialog long when a hook reached many targets.
Each explanation now shows as a tooltip on its footer button, on hover and
keyboard focus, and is wired through aria-describedby for screen readers.

Tooltip placed button-anchored tips that did not fit below using the
cursor offset, so a two-line tip covered the buttons; it now flips above
the anchor. It also shows nothing without content, which lets the dialog
keep its buttons mounted while the preview loads.

The CJK strings dropped the space between the target text and the
particle, which read as "8 個目標 的".

* fix(hooks): delete the files and folders a removed hook leaves empty

Syncing a hook to an Agent whose hooks file did not exist, then removing
it, left shells behind: `{}` in Claude, Codex, Gemini, Qwen, Droid and
Antigravity files, `{"version":1}` for Cursor, and empty folders such as
~/.copilot/hooks and ~/.pi/agent/extensions. They look like user
configuration and confuse the next import or review.

The ledger now records the shared files Skillshare created and the
folders it made for its outputs. When removal leaves a created file with
nothing but that skeleton, the plan deletes it and says so, and the file
diff shows the deletion. Files and folders that existed before, settings
or comments the user added, and non-empty folders all stay. Apply checks
the skeleton again, so settings added after the preview keep the file.

* fix(hooks): note Copilot's folder trust and use Pi's current package

Running Copilot CLI against a synced project showed that .github/hooks
is skipped until the folder is in trustedFolders, while COPILOT_HOME
hooks run anyway; the Copilot note was the only command Agent note that
did not mention trust. Pi's extension docs now import ExtensionAPI from
@earendil-works/pi-coding-agent, so the hook template follows them. The
old name still loads because the import is type-only, but editors no
longer resolve its types.

* test(hooks): run synced hooks in real Agent CLIs

Unit tests only prove Skillshare writes the native files we believe are
right. This runbook syncs a marker-writing hook for each Agent, starts
the real CLI once per scope with a throwaway HOME and fake credentials,
and checks the markers, so a format or location mistake shows up as a
missing marker. Antigravity and Cursor check credentials before any hook
runs; the runbook lists how to confirm them by hand.

* fix(hooks): write the hooks section in block style

yaml.v3 encodes an empty mapping as flow `{}`, and entries added to it
inherit that style, so the first hook saved after the section was emptied
landed on one unreadable line in config.yaml. The section is now expanded
before it is written, like the MCP section, which also unfolds entries an
earlier save left on one line.

* fix(ui): let Beautify unfold nested one-line YAML

Beautify kept flow collections as written, so a hooks or MCP section
squeezed onto one line stayed that way and the button reported nothing to
change. It now expands flow collections that nest others, and everything
inside them, while short lists such as `targets: [claude, codex]` stay on
one line. Saving still keeps the user's flow style.

* fix(ui): show hook targets once and light them up per event

Each event line repeated its own row of target icons under the header's
icons, and two rows of logos stacked on the right read as clutter. The
header now shows the targets as one overlapping stack, and hovering an
event line fades the targets it does not run on. Screen readers still hear
each line's targets.

* fix(ui): document the hooks section in the config editor

The field panel labelled every key under hooks as an unknown field, which
suggested the section was a mistake. It now explains hooks, its entries,
bindings, events, code, files and projects like the MCP keys.

* docs(hooks): describe the config editor and Copilot folder trust

The hooks page now writes its section in block style, opens the config
editor at hooks:, and the field panel and Beautify understand the
section; none of that was documented. Running Copilot CLI also showed that
project hooks in .github/hooks load only in a trusted folder, which the
destinations section did not say.

* docs(changelog): add 0.23.0 entry

Records native hooks, the MCP tool policy, the dashboard work around both,
and the Pi built-in MCP breaking changes, so users upgrading from 0.22.2
know what moves on their first sync.

* fix(server): validate hooks when the config editor saves

The config editor kept the hooks section as an opaque node and never ran
the hooks checks, so a malformed binding saved successfully and then broke
the Hooks page and `sync --all` until the YAML was repaired by hand. A
project config could also gain `hooks.projects`, which only the global
config may hold. Saving now rejects both with the same message sync gives.

* fix(hooks): keep an Antigravity block's name when importing it

An Antigravity hook is the named block in hooks.json. Importing one under
another name, through `hooks import --from agy NAME` or a renamed row in the
dashboard, planned a new block and left the original unmanaged, so both
ran. Such a takeover is now a conflict that asks for the block's own name,
and the import dialog keeps that name fixed for Antigravity rows.
This commit is contained in:
Willie
2026-10-01 02:24:24 +08:00
committed by GitHub
parent de0f14f35b
commit c327a26e30
333 changed files with 24714 additions and 3321 deletions
+61
View File
@@ -1,5 +1,66 @@
# Changelog
## [0.23.0] - 2026-10-01
### New Features
#### Hooks
- **Manage native hooks** — `skillshare hooks` keeps named hooks in `hooks.entries` and writes them into each Agent's own hook configuration: Claude Code, Codex, Gemini CLI, Copilot CLI, Cursor, Factory Droid, Qwen Code, Antigravity (and its CLI, `agy`), Pi, Amp and OpenCode, in global and project scope. Each binding keeps that Agent's own event names and format; Skillshare does not translate between Agents. Sync previews every file it changes, keeps your other settings and hooks, reports a hook you edited by hand as a conflict, and backs files up before writing. It never runs a hook or changes an Agent's trust.
```bash
skillshare hooks add check --file ./check.yaml
skillshare hooks sync --dry-run
skillshare hooks sync
skillshare sync --all # now includes hooks
```
- **Import the hooks you already have** — `hooks import --from AGENT` lists that Agent's existing hooks. Saving one takes over those registrations in place, so the next sync does not add a duplicate.
```bash
skillshare hooks import --from claude
```
- **Disable, stop managing and restore** — `hooks disable` keeps the definition and removes it from the Agents on the next sync. `hooks remove --keep-files` stops managing a hook and leaves its entries in the Agent files as yours; `hooks import` offers them again. `hooks restore` brings back a backup of an Agent file without touching unrelated later edits.
```bash
skillshare hooks disable check --sync
skillshare hooks remove check --keep-files
skillshare hooks restore BACKUP_ID --dry-run
```
- **Project hooks from the global config** — `hooks.projects` holds hooks for other project folders, so one sync from the global config reaches each of them.
- **Removal cleans up after itself** — removing a hook deletes a hook file Skillshare created once nothing else is left in it, together with the folders it created that are now empty. Files and folders that existed before, and anything you added, stay.
#### MCP
- **Tool policy per server** — `tools.allow` and `tools.deny` say which of a server's tools reach the model. Write them once; sync translates them into Pi's `toolExposure`, Codex's `enabled_tools` and `disabled_tools`, and Copilot's `tools`. Parts an Agent cannot hold, such as the whole policy for OpenCode and Kilo Code, are named in the sync plan and by `mcp check` instead of being dropped.
```bash
skillshare mcp add github --target pi --target codex --tools-allow 'get_*,search_code' --tools-deny get_secret -- github-mcp
skillshare mcp edit github --tools-allow '' # clear the allow list
```
#### Dashboard
- **Hooks page** — add and edit hooks by picking each target's documented events, copy commands from another target's tab, or edit the native JSON with completion and checks. Every sync shows a diff of each file it changes. Import lists each target's hooks that Skillshare does not manage yet. Hooks also appear on target and project pages, on the Sync page and in **Settings → Backups**.
- **Clear remove choices** — removing a hook offers **Remove and sync**, **Remove from source only** and **Stop managing**; hovering or focusing a button explains what it does to the target files. In the hook and MCP remove dialogs, **Remove and sync** names the other pending hooks or servers that go out with it.
- **Tools in the MCP server dialog** — load a server's tool list with the dialog's current settings, even before saving, and tick the tools the model gets. The dialog says which selected Agents follow the policy fully, partly or not at all.
- **Plan notices before an MCP sync** — the MCP sync dialog and the Sync page list the plan's notices, such as Pi's built-in MCP needing Pi 0.99.0, before you sync.
- **Open config.yaml at the right place** — the **config.yaml** button in the Hooks and MCP page headers opens **Settings → Files** at the `hooks:` or `mcp:` section. The field panel there explains every `hooks` key.
### Bug Fixes
- **Script installs no longer need administrator access** — `install.sh` now installs to `~/.local/bin` by default and prints PATH setup only when that folder is not on your PATH. `INSTALL_DIR` still overrides the location, and an existing installation is upgraded where it is.
- **Stop managing an MCP server works in the dashboard** — **Stop managing** in the MCP remove dialog always failed with a "changed since preview" error. It now succeeds, and its message says the entries stay in the Agent files.
- **Beautify unfolds one-line YAML** — in **Settings → Files**, **Beautify** left a section squeezed onto one line, such as `servers: {docs: {url: …}}`, unchanged and said there was nothing to tidy. It now unfolds nested one-line sections; short lists such as `targets: [claude, codex]` stay on one line.
### Breaking Changes
#### Pi MCP
- **Pi uses only its built-in MCP** — Skillshare now writes Pi's servers only to Pi's own `mcp.json` (`~/.pi/agent/mcp.json`, or `.pi/mcp.json` in a project). It no longer writes for `pi-mcp-adapter` or `pi-mcp-extension`, and the `piExtension` choice is gone. The first sync after upgrading moves your servers: entries Skillshare wrote to `mcp-adapter.json` are removed and written to `mcp.json`, and `pi-mcp-extension` entries are rewritten in place. Entries you added to `mcp-adapter.json` yourself are left alone, and `mcp import --from pi` still reads them.
- **Needs Pi 0.99.0 or later** — Pi added its built-in MCP in 0.99.0. On older Pi the moved servers stop loading until you update Pi. Skillshare does not check Pi's version; the sync that moves servers prints a warning.
- **Remove the old extension from Pi** — if `pi-mcp-adapter` or `pi-mcp-extension` is still installed in Pi, uninstall it. Pi's docs say an installed extension that registers `/mcp` replaces the built-in MCP, and `pi-mcp-adapter` 3.0.0 and later no longer read `mcp.json`.
- **Adapter-only server options are dropped** — Pi's built-in MCP does not read these `piOptions` fields, so the next sync removes them from your config: `approveTools`, `auth`, `bearerToken`, `bearerTokenEnv`, `bearerTokenStore`, `caFile`, `debug`, `exposeResources`, `idleTimeout`, `inheritEnv`, `lifecycle`, `protocolVersion`, `requestHeadersCommand`, `requestTimeoutMs`, `searchKeywords`, `socket`, `tasks`, `toolPrefix`, `trace`.
- **No per-project off switch for Pi** — Pi cannot turn off one global server in one project. The next sync removes `pi` from the targets of `disabled` entries, so that server is on again in that project. To keep a server off for Pi, set `piOptions: {enabled: false}` on a complete entry.
- **`directTools` becomes Pi's exposure** — `directTools: true` becomes `piOptions.exposure: direct`, `"search"` becomes `deferred`, and a list of tool names becomes `piOptions.toolExposure` with those tools `direct`. `mcp.directTools` and a project's default are copied into each Pi server that sets none. `piOptions.includeTools` / `excludeTools` become `tools.allow` / `tools.deny`.
- **Removed flags** — `--pi-extension`, `--direct-tools` and `--pi-options-prune` now fail with a message saying what to use. Use `--pi-options '{"exposure":"direct"}'` or `--pi-options '{"toolExposure":{"TOOL":"direct"}}'` instead of `--direct-tools`. Sync always removes unchanged Pi fields Skillshare wrote earlier, so `--pi-options-prune` is no longer needed.
- **Your config is updated on the first sync** — the old config still loads, and `sync mcp --dry-run` names each retired setting. The first `sync mcp`, `sync --all` or dashboard sync saves `config.yaml` (or the `sources.mcp` file) without them, keeping the previous version in the file history.
## [0.22.2] - 2026-09-30
### New Features
+13 -2
View File
@@ -59,6 +59,7 @@ skillshare はこの問題を解決します。
- **skills だけではない** — [extras](https://skillshare.runkids.cc/docs/reference/targets/configuration#extras) で rules、commands、prompts などファイルベースのリソースを管理
- **MCP 接続** — サーバーの定義は一度だけ。[`sync mcp`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp) が各 Agent 固有の設定形式に書き込みます
- **plugin 一式** — plugin の skills、hooks、MCP 設定をまとめたまま、[`plugin`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-plugins) でインストール先のツールを選択
- **ネイティブ hooks** — Agent ごとの event 設定や extension コードを管理。プレビュー、有効/無効、復元に対応。 [hooks](https://skillshare.runkids.cc/docs/reference/commands/hooks)
- **どこからでもインストール** — GitHub、GitLab、Bitbucket、Azure DevOps、Gitea、CNB、またはセルフホストの Git
- **セキュリティ機能を内蔵** — 使う前に、prompt injection やデータ流出につながる内容がないか skills を監査
- **チームで使える** — プロジェクトの skills は `.skillshare/` に、組織共通の skills は tracked repo で配布
@@ -120,6 +121,8 @@ skillshare はこの問題を解決します。
curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh
```
スクリプトはデフォルトで `~/.local/bin` にインストールするため、通常のインストールと更新に `sudo` は不要です。インストーラーが PATH 設定の案内を表示した場合のみ、その案内に従ってから `skillshare` を実行してください。今後のターミナルでも使えるよう、案内された行を shell 設定ファイル(`~/.zshrc` や `~/.bashrc` など)に追加できます。別の場所には `INSTALL_DIR` を指定できます。
### Windows PowerShell
```powershell
@@ -193,14 +196,14 @@ skillshare init -p && skillshare sync
```bash
skillshare sync agents # agents だけを同期
skillshare sync --all # skills、agents、extras、MCP をまとめて同期
skillshare sync --all # skills、agents、extras、MCP、hooks をまとめて同期
```
**Extras** — rules、commands、prompts などを管理
```bash
skillshare extras init rules # "rules" という extra を作成
skillshare sync --all # skills、agents、extras、MCP をまとめて同期
skillshare sync --all # skills、agents、extras、MCP、hooks をまとめて同期
skillshare extras collect rules # ローカルのファイルをソースに取り込む
```
@@ -215,6 +218,14 @@ skillshare sync mcp # 接続設定を適用
定義は `config.yaml` に書くか、別の `mcp.yaml` を参照できます。
設定例、環境変数の参照、既存の接続のインポートは [MCP の設定](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp)を参照してください。
hook を実行せずにネイティブ hooks を管理:
```bash
skillshare hooks add check --file ./check.yaml
skillshare hooks sync --dry-run
skillshare hooks sync
```
**Plugins** — plugin 一式をインストールし、インストール先のツールを選択
```bash
+13 -2
View File
@@ -59,6 +59,7 @@ skillshare가 이 문제를 해결합니다.
- **skills 그 이상** — [extras](https://skillshare.runkids.cc/docs/reference/targets/configuration#extras)로 rules, commands, prompts 등 파일 기반 리소스를 관리
- **MCP 연결** — 서버는 한 번만 정의하고, [`sync mcp`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp)로 각 Agent 고유의 설정 형식에 기록
- **완전한 plugin** — plugin의 skills, hooks, MCP 설정을 한 묶음으로 유지하고, [`plugin`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-plugins)으로 설치할 도구를 선택
- **네이티브 hooks** — Agent별 event 설정과 extension 코드를 관리하고 미리보기, 활성화/비활성화, 복원을 지원합니다. [hooks](https://skillshare.runkids.cc/docs/reference/commands/hooks)
- **어디서든 설치** — GitHub, GitLab, Bitbucket, Azure DevOps, Gitea, CNB 또는 자체 호스팅 Git
- **내장 보안 기능** — 사용하기 전에 skills에 prompt injection이나 데이터 유출 위험이 있는지 감사
- **팀에 적합** — 프로젝트 skills는 `.skillshare/`에, 조직 공용 skills는 tracked repo로 배포
@@ -120,6 +121,8 @@ skillshare가 이 문제를 해결합니다.
curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh
```
스크립트는 기본적으로 `~/.local/bin`에 설치하므로 일반적인 설치와 업데이트에는 `sudo`가 필요하지 않습니다. 설치 프로그램이 PATH 설정 안내를 표시할 때만 안내에 따라 설정한 후 `skillshare`를 실행하세요. 이후 터미널에서도 사용할 수 있도록 안내된 명령을 shell 설정 파일(예: `~/.zshrc` 또는 `~/.bashrc`)에 추가할 수 있습니다. 다른 설치 위치는 `INSTALL_DIR`로 지정할 수 있습니다.
### Windows PowerShell
```powershell
@@ -193,14 +196,14 @@ skillshare init -p && skillshare sync
```bash
skillshare sync agents # agents만 동기화
skillshare sync --all # skills, agents, extras, MCP를 함께 동기화
skillshare sync --all # skills, agents, extras, MCP, hooks를 함께 동기화
```
**Extras** — rules, commands, prompts 등을 관리
```bash
skillshare extras init rules # "rules"라는 extra 생성
skillshare sync --all # skills, agents, extras, MCP를 함께 동기화
skillshare sync --all # skills, agents, extras, MCP, hooks를 함께 동기화
skillshare extras collect rules # 로컬 파일을 소스로 다시 수집
```
@@ -215,6 +218,14 @@ skillshare sync mcp # 연결 설정 적용
정의는 `config.yaml`에 두거나 별도의 `mcp.yaml`을 참조할 수 있습니다.
예시, 환경 변수 참조, 기존 연결 가져오기는 [MCP 설정](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp)을 참고하세요.
hook을 실행하지 않고 네이티브 hooks 관리:
```bash
skillshare hooks add check --file ./check.yaml
skillshare hooks sync --dry-run
skillshare hooks sync
```
**Plugins** — 완전한 plugin을 설치하고, 설치할 도구를 선택
```bash
+13 -2
View File
@@ -59,6 +59,7 @@ skillshare 解决这个问题:
- **不只是 skills** — 用 [extras](https://skillshare.runkids.cc/docs/reference/targets/configuration#extras) 管理 rules、commands、prompts 和任何基于文件的资源
- **MCP 连接** — 服务器只定义一次,用 [`sync mcp`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp) 写入每个 Agent 自己的配置格式
- **完整 plugin** — plugin 的 skills、hooks 和 MCP 设置保持完整,用 [`plugin`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-plugins) 选择哪些工具要安装
- **原生 hooks** — 管理各 Agent 的 event 配置或 extension 代码,支持预览、启用/停用与恢复。 [hooks](https://skillshare.runkids.cc/docs/reference/commands/hooks)
- **从任何地方安装** — GitHub、GitLab、Bitbucket、Azure DevOps、Gitea、CNB,或任何自托管的 Git
- **内置安全检查** — 使用前先审计 skills 是否含有 prompt injection 或数据外泄的内容
- **适合团队** — 项目的 skills 放在 `.skillshare/`,组织共用的 skills 通过 tracked repo 发布
@@ -120,6 +121,8 @@ skillshare 解决这个问题:
curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh
```
脚本默认安装到 `~/.local/bin`,正常安装与更新不需要 `sudo`。只有安装器显示 PATH 设置提示时,才需要按提示设置后再运行 `skillshare`。可把提示的命令加入 shell 配置文件(例如 `~/.zshrc` 或 `~/.bashrc`),让之后打开的终端也能使用。可用 `INSTALL_DIR` 指定其他安装位置。
### Windows PowerShell
```powershell
@@ -193,14 +196,14 @@ skillshare init -p && skillshare sync
```bash
skillshare sync agents # 只同步 agents
skillshare sync --all # skills、agents、extras、MCP 一起同步
skillshare sync --all # skills、agents、extras、MCP、hooks 一起同步
```
**Extras** — 管理 rules、commands、prompts 等资源
```bash
skillshare extras init rules # 创建名为 "rules" 的 extra
skillshare sync --all # skills、agents、extras、MCP 一起同步
skillshare sync --all # skills、agents、extras、MCP、hooks 一起同步
skillshare extras collect rules # 把本地文件收回来源
```
@@ -215,6 +218,14 @@ skillshare sync mcp # 应用连接设置
定义可以放在 `config.yaml`,或另外引用一个 `mcp.yaml`。
示例、环境变量引用,以及导入已有连接的方式,请见 [MCP 配置](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp)。
管理原生 hooks,管理操作不执行 hook:
```bash
skillshare hooks add check --file ./check.yaml
skillshare hooks sync --dry-run
skillshare hooks sync
```
**Plugins** — 安装完整的 plugin,并选择哪些工具要安装
```bash
+13 -2
View File
@@ -59,6 +59,7 @@ skillshare 解決這個問題:
- **不只是 skills** — 用 [extras](https://skillshare.runkids.cc/docs/reference/targets/configuration#extras) 管理 rules、commands、prompts 和任何以檔案為主的資源
- **MCP 連線** — 伺服器只定義一次,用 [`sync mcp`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp) 寫進每個 Agent 自己的設定格式
- **完整 plugin** — plugin 的 skills、hooks 和 MCP 設定保持完整,用 [`plugin`](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-plugins) 選擇哪些工具要安裝
- **原生 hooks** — 管理各 Agent 的 event 設定或 extension 程式碼,支援預覽、啟用/停用與復原。 [hooks](https://skillshare.runkids.cc/docs/reference/commands/hooks)
- **從任何地方安裝** — GitHub、GitLab、Bitbucket、Azure DevOps、Gitea、CNB,或任何自架的 Git
- **內建安全檢查** — 使用前先稽核 skills 是否含有 prompt injection 或資料外洩的內容
- **適合團隊** — 專案的 skills 放在 `.skillshare/`,組織共用的 skills 透過 tracked repo 發布
@@ -120,6 +121,8 @@ skillshare 解決這個問題:
curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh
```
腳本預設安裝到 `~/.local/bin`,正常安裝與更新不需要 `sudo`。只有安裝器顯示 PATH 設定提示時,才需要依提示設定後再執行 `skillshare`。可把提示的指令加入 shell 設定檔(例如 `~/.zshrc` 或 `~/.bashrc`),讓之後開啟的終端機也能使用。可用 `INSTALL_DIR` 指定其他安裝位置。
### Windows PowerShell
```powershell
@@ -193,14 +196,14 @@ skillshare init -p && skillshare sync
```bash
skillshare sync agents # 只同步 agents
skillshare sync --all # skills、agents、extras、MCP 一起同步
skillshare sync --all # skills、agents、extras、MCP、hooks 一起同步
```
**Extras** — 管理 rules、commands、prompts 等資源
```bash
skillshare extras init rules # 建立名為 "rules" 的 extra
skillshare sync --all # skills、agents、extras、MCP 一起同步
skillshare sync --all # skills、agents、extras、MCP、hooks 一起同步
skillshare extras collect rules # 把本機檔案收回來源
```
@@ -215,6 +218,14 @@ skillshare sync mcp # 套用連線設定
定義可以放在 `config.yaml`,或另外引用一個 `mcp.yaml`。
範例、環境變數引用,以及匯入既有連線的方式,請見 [MCP 設定](https://skillshare.runkids.cc/docs/how-to/daily-tasks/sharing-mcp)。
管理原生 hooks,管理操作不執行 hook:
```bash
skillshare hooks add check --file ./check.yaml
skillshare hooks sync --dry-run
skillshare hooks sync
```
**Plugins** — 安裝完整的 plugin,並選擇哪些工具要安裝
```bash
+13 -2
View File
@@ -60,6 +60,7 @@ skillshare fixes this:
- **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)
- **Native hooks** — manage each Agent’s event configuration or extension code, with preview, enable/disable and recovery. [hooks](https://skillshare.runkids.cc/docs/reference/commands/hooks)
- **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
@@ -121,6 +122,8 @@ skillshare fixes this:
curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh
```
The script installs to `~/.local/bin` by default, so normal installs and updates do not need `sudo`. If the installer prints PATH setup instructions, follow them before running `skillshare`. Add the suggested line to your shell config (such as `~/.zshrc` or `~/.bashrc`) for future terminals. Set `INSTALL_DIR` to use another location.
### Windows PowerShell
```powershell
@@ -194,14 +197,14 @@ skillshare init -p && skillshare sync
```bash
skillshare sync agents # sync agents only
skillshare sync --all # sync skills + agents + extras + MCP together
skillshare sync --all # sync skills + agents + extras + MCP + hooks together
```
**Extras** —manage rules, commands, prompts & more
```bash
skillshare extras init rules # create a "rules" extra
skillshare sync --all # sync skills + agents + extras + MCP together
skillshare sync --all # sync skills + agents + extras + MCP + hooks together
skillshare extras collect rules # collect local files back to source
```
@@ -217,6 +220,14 @@ 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.
Manage native hooks without executing them:
```bash
skillshare hooks add check --file ./check.yaml
skillshare hooks sync --dry-run
skillshare hooks sync
```
**Plugins** —install a complete plugin and pick which tools receive it
```bash
+246
View File
@@ -0,0 +1,246 @@
# CLI E2E Runbook: Hooks Fire in Real Agents
## Scope
Prove that the native files `skillshare hooks` writes are loaded and run by the
real Agents, not only that they match the shape the unit tests expect. Every hook
writes a marker file and nothing else. Each Agent runs once per scope with a
throwaway HOME and fake credentials: it starts a session, runs its hooks, then
fails at the model call. No login, real Agent configuration or trust store is used.
Covered by firing here: Claude Code, Codex, Gemini CLI, Qwen Code, Copilot CLI,
Factory Droid, OpenCode, Amp (plugin load only) and Pi, in project and global scope.
Antigravity and Cursor check credentials before any hook runs; see
[Agents that need a login](#agents-that-need-a-login).
## Environment
Run inside the devcontainer with a fresh ssenv HOME and network access (the first
step downloads Agent CLIs into `/tmp/hooks-agents`). Fixtures live in
`/workspace/tmp/hooks-e2e-<target>` (gitignored, each its own Git root) and
`/tmp/hooks-e2e-*`. Helper: `scripts/hooks/real-agents.sh`.
```sh
CONTAINER=$(docker compose -f .devcontainer/docker-compose.yml ps -q skillshare-devcontainer)
docker exec "$CONTAINER" ssenv create hooks-real-agents --init
docker exec "$CONTAINER" /workspace/.devcontainer/ensure-mdproof.sh
docker exec "$CONTAINER" ssenv enter hooks-real-agents -- \
mdproof --report json /workspace/ai_docs/tests/hooks_real_agents_runbook.md
```
Trust gates are satisfied only inside the throwaway HOME or with per-run flags:
Codex gets a `trust_level = "trusted"` entry in its temporary `CODEX_HOME` plus
`--dangerously-bypass-hook-trust`, Copilot a `trustedFolders` entry in its temporary
`COPILOT_HOME`, Gemini `GEMINI_CLI_TRUST_WORKSPACE=true`, and Pi `--approve`.
Without these, project hooks are skipped by design.
## Agents that need a login
These run manually on a machine where the Agent is already logged in. Generate
the fixture in the devcontainer with the host path as the marker directory, run
the Agent from that directory on the host, then check for `.hook-fired-*`:
```sh
HOST_TMP="$PWD/tmp" # on the host, from the repository root
docker exec "$CONTAINER" ssenv enter hooks-real-agents -- \
bash /workspace/scripts/hooks/real-agents.sh project antigravity "$HOST_TMP/hooks-e2e-antigravity"
cd tmp/hooks-e2e-antigravity && agy -p "reply ok"; ls -A | grep hook-fired
```
- **Antigravity (`agy`)**: project hooks in `.agents/hooks.json` load only after
the folder is trusted in an interactive session, which is stored persistently;
global hooks live in the real `~/.gemini/config/hooks.json`. With a throwaway
HOME, `agy -p` asks for Google OAuth before any hook runs.
- **Cursor (`cursor-agent`)**: it validates `CURSOR_API_KEY` before the session
starts, and project hooks need a trusted workspace.
- **Claude Code and Pi** can also be confirmed on the host: `claude -p "reply ok"`
(print mode skips the workspace trust dialog) and `pi -p --approve --no-session
"reply ok"` (`--approve` trusts project files for that run only).
- **Codex on the host**: project hooks need a persisted `trust_level` in the real
`~/.codex/config.toml`; `-c` overrides do not mark a project trusted.
## Steps
### Step 1: Build and install Agent CLIs
```bash
cd /workspace && make build >/dev/null
bash /workspace/scripts/hooks/real-agents.sh clean
bash /workspace/scripts/hooks/real-agents.sh install
```
Expected:
- exit_code: 0
- regex: claude \d+\.
- regex: codex codex-cli \d+\.
- regex: copilot GitHub Copilot CLI \d+\.
- regex: pi \d+\.
- regex: droid \d+\.
### Step 2: Claude Code runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project claude >/dev/null
P=$(bash "$S" fire claude project)
bash "$S" global claude >/dev/null
G=$(bash "$S" fire claude global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("SessionStart")) != null and (.global | index("SessionStart")) != null
- jq: (.project | index("UserPromptSubmit")) != null and (.global | index("UserPromptSubmit")) != null
### Step 3: Codex runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project codex >/dev/null
P=$(bash "$S" fire codex project)
bash "$S" global codex >/dev/null
G=$(bash "$S" fire codex global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("SessionStart")) != null and (.global | index("SessionStart")) != null
- jq: (.project | index("UserPromptSubmit")) != null and (.global | index("UserPromptSubmit")) != null
### Step 4: Gemini CLI runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project gemini >/dev/null
P=$(bash "$S" fire gemini project)
bash "$S" global gemini >/dev/null
G=$(bash "$S" fire gemini global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("SessionStart")) != null and (.global | index("SessionStart")) != null
- jq: (.project | index("BeforeAgent")) != null and (.global | index("BeforeAgent")) != null
### Step 5: Qwen Code runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project qwen >/dev/null
P=$(bash "$S" fire qwen project)
bash "$S" global qwen >/dev/null
G=$(bash "$S" fire qwen global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("SessionStart")) != null and (.global | index("SessionStart")) != null
- jq: (.project | index("UserPromptSubmit")) != null and (.global | index("UserPromptSubmit")) != null
### Step 6: GitHub Copilot CLI runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project copilot >/dev/null
P=$(bash "$S" fire copilot project)
bash "$S" global copilot >/dev/null
G=$(bash "$S" fire copilot global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("sessionStart")) != null and (.global | index("sessionStart")) != null
- jq: (.project | index("userPromptSubmitted")) != null and (.global | index("userPromptSubmitted")) != null
### Step 7: Factory Droid runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project droid >/dev/null
P=$(bash "$S" fire droid project)
bash "$S" global droid >/dev/null
G=$(bash "$S" fire droid global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("SessionStart")) != null and (.global | index("SessionStart")) != null
### Step 8: OpenCode runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project opencode >/dev/null
P=$(bash "$S" fire opencode project)
bash "$S" global opencode >/dev/null
G=$(bash "$S" fire opencode global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("load")) != null and (.global | index("load")) != null
- jq: (.project | index("session.created")) != null and (.global | index("session.created")) != null
### Step 9: Amp runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project amp >/dev/null
P=$(bash "$S" fire amp project)
bash "$S" global amp >/dev/null
G=$(bash "$S" fire amp global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("load")) != null and (.global | index("load")) != null
### Step 10: Pi runs project and global hooks
```bash
set -e
S=/workspace/scripts/hooks/real-agents.sh
bash "$S" project pi >/dev/null
P=$(bash "$S" fire pi project)
bash "$S" global pi >/dev/null
G=$(bash "$S" fire pi global)
printf '%s\n%s\n' "$P" "$G" | jq -sc '{project: .[0].markers, global: .[1].markers}'
```
Expected:
- exit_code: 0
- jq: (.project | index("load")) != null and (.global | index("load")) != null
- jq: (.project | index("session_start")) != null and (.global | index("session_start")) != null
### Step 11: Clean up
```bash
bash /workspace/scripts/hooks/real-agents.sh clean
find /workspace/tmp /tmp -maxdepth 1 -name 'hooks-e2e-*' | wc -l
```
Expected:
- exit_code: 0
- jq: . == 0
## Pass Criteria
Steps 1 to 11 pass: every listed marker exists for both scopes. Amp's
`session.start` needs a login, so only plugin loading is proven there. Remove
the ssenv afterwards with `ssenv delete hooks-real-agents --force`.
+146 -54
View File
@@ -3,7 +3,8 @@
## Scope
Verify inline and external declarations, global/project destinations, preview,
idempotence, removal, import/adoption, conflict protection and entry restoration.
idempotence, removal, import/adoption, conflict protection, entry restoration,
Pi built-in MCP and its 0.22 migration, and the per-Agent tool policy.
No server is launched and all endpoints are inert example URLs.
## Environment
@@ -202,67 +203,158 @@ Expected:
- 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-adapter.json"
jq -e '.mcpServers | has("pi-docs") | 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 and moves from `mcp.json` to `mcp-adapter.json`, the second
sync is unchanged, and removal affects only
the managed entry. No MCP server or Pi package is installed or executed.
### Pi built-in MCP (0.99.0+) and cleared options
### Step 9: Pi built-in MCP and cleared options
```bash
set -eu
mkdir -p "$HOME/.config/skillshare/skills"
MCP_CASE=$(mktemp -d "$HOME/mcp-pi-builtin.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
export PI_CODING_AGENT_DIR="$MCP_CASE/pi"
printf 'targets: {}\n' > "$SKILLSHARE_CONFIG"
ss mcp add docs --target pi --pi-extension builtin --url https://example.com/mcp \
--pi-options '{"exposure":"deferred","timeout":120,"toolExposure":{"get_*":"direct","*":"hidden"},"custom":{"flag":true}}' --no-tui -g
ss sync mcp --dry-run --json -g | jq -e '.blocked == false and (.changes[0].fields.added | length > 0)'
ss sync mcp -g
jq -e '.mcpServers.docs.exposure == "deferred" and .mcpServers.docs.transport == null' "$PI_CODING_AGENT_DIR/mcp.json"
ss mcp import --from pi --dry-run --json -g
ss mcp edit docs --pi-options '{}' --no-tui -g
ss sync mcp -g
jq -e '.mcpServers.docs.custom.flag == true' "$PI_CODING_AGENT_DIR/mcp.json"
# Re-manage the fields before testing explicit removal.
ss mcp edit docs --pi-options '{"exposure":"deferred","timeout":120}' --no-tui -g
ss sync mcp -g
ss mcp edit docs --pi-options '{}' --pi-options-prune --no-tui -g
ss sync mcp -g
jq -e '.mcpServers.docs.exposure == null and .mcpServers.docs.timeout == null and .mcpServers.docs.custom.flag == true' "$PI_CODING_AGENT_DIR/mcp.json"
ss mcp add docs --target pi --url https://example.com/mcp \
--pi-options '{"exposure":"deferred","timeout":120,"custom":{"flag":true}}' --no-tui -g >/dev/null
ss sync mcp -g >/dev/null
jq -e '.mcpServers.docs.exposure == "deferred" and .mcpServers.docs.transport == null' "$PI_CODING_AGENT_DIR/mcp.json" >/dev/null
test ! -e "$PI_CODING_AGENT_DIR/mcp-adapter.json"
ss mcp edit docs --pi-options '{"custom":{"flag":true}}' --no-tui -g >/dev/null
ss sync mcp -g >/dev/null
jq -e '.mcpServers.docs.exposure == null and .mcpServers.docs.timeout == null and .mcpServers.docs.custom.flag == true' "$PI_CODING_AGENT_DIR/mcp.json" >/dev/null
ss sync mcp --dry-run --json -g
```
Expected:
- exit_code: 0
- Global destination is `<PI_CODING_AGENT_DIR>/mcp.json`; project mode uses `.pi/mcp.json`.
- Import keeps Pi-only fields. Clearing preserves values by default, explicit prune removes only owned unchanged fields.
- No server is launched, no OAuth login or project trust is granted.
- jq: .blocked == false
- jq: .changes[0].action == "unchanged"
### Step 10: A 0.22 Pi config converts on the first sync
The owned `mcp-adapter.json` entry of a real 0.22 sync needs a 0.22 ledger; Go tests
(`TestPiAdapterServerMovesToBuiltin`, `TestMCPPiAdapterServerSyncsToBuiltin`) cover its
removal. This step covers the config, the notices, the backup and a hand-written
adapter entry.
```bash
set -eu
mkdir -p "$HOME/.config/skillshare/skills"
MCP_CASE=$(mktemp -d "$HOME/mcp-pi-migrate.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
export PI_CODING_AGENT_DIR="$MCP_CASE/pi"
mkdir -p "$PI_CODING_AGENT_DIR"
printf '{"mcpServers":{"mine":{"command":"my-mcp"}}}\n' > "$PI_CODING_AGENT_DIR/mcp-adapter.json"
cp "$PI_CODING_AGENT_DIR/mcp-adapter.json" "$MCP_CASE/adapter.before"
cat > "$SKILLSHARE_CONFIG" <<'YAML'
targets: {}
mcp:
directTools: search
servers:
docs:
url: https://example.com/mcp
targets: [pi]
piExtension: pi-mcp-adapter
piOptionsPrune: true
piOptions:
lifecycle: lazy
excludeTools: [delete_repo]
lister:
command: lister-mcp
targets: [pi]
piExtension: builtin
directTools: [list_items]
YAML
cp "$SKILLSHARE_CONFIG" "$MCP_CASE/config.before"
ss sync mcp --dry-run --json -g > "$MCP_CASE/plan.json"
jq -e '.migrates == true and (.notices | length == 5)' "$MCP_CASE/plan.json" >/dev/null
jq -e '.notices[-1] | startswith("Pi'"'"'s built-in MCP needs Pi 0.99.0 or later")' "$MCP_CASE/plan.json" >/dev/null
jq -e '.notices[0] == "Pi now uses its built-in MCP; the next sync updates the config: docs, lister"' "$MCP_CASE/plan.json" >/dev/null
cmp "$SKILLSHARE_CONFIG" "$MCP_CASE/config.before"
ss sync mcp -g > "$MCP_CASE/sync.out"
grep -q 'Updated config.yaml for 0.23.0 (backup: ' "$MCP_CASE/sync.out"
! grep -Eq 'piExtension|piOptionsPrune|directTools|lifecycle|excludeTools' "$SKILLSHARE_CONFIG"
jq -e '.mcpServers.docs.exposure == "deferred" and .mcpServers.docs.toolExposure.delete_repo == "hidden"' "$PI_CODING_AGENT_DIR/mcp.json" >/dev/null
jq -e '.mcpServers.lister.toolExposure.list_items == "direct"' "$PI_CODING_AGENT_DIR/mcp.json" >/dev/null
cmp "$PI_CODING_AGENT_DIR/mcp-adapter.json" "$MCP_CASE/adapter.before"
ss backup files show "$SKILLSHARE_CONFIG" -g | grep -q 'history/migrate'
ss mcp import --from pi --json -g | jq -e 'any(.[]; .name == "mine")' >/dev/null
ss sync mcp --dry-run --json -g
```
Expected:
- exit_code: 0
- jq: .notices == null
- jq: .migrates == null
- jq: .changes | length == 2
### Step 11: Removed Pi flags explain the change
```bash
set -eu
mkdir -p "$HOME/.config/skillshare/skills"
MCP_CASE=$(mktemp -d "$HOME/mcp-pi-flags.XXXXXX")
export SKILLSHARE_CONFIG="$MCP_CASE/config.yaml"
export PI_CODING_AGENT_DIR="$MCP_CASE/pi"
printf 'targets: {}\n' > "$SKILLSHARE_CONFIG"
ss mcp add docs --url https://example.com/mcp --target pi --no-tui -g >/dev/null
for flag in '--pi-extension builtin' '--pi-options-prune' '--direct-tools true'; do
if ss mcp edit docs $flag --no-tui -g > "$MCP_CASE/out" 2>&1; then exit 1; fi
grep -q 'was removed in 0.23.0' "$MCP_CASE/out"
done
grep -q '"exposure":"direct"' "$MCP_CASE/out"
ss mcp list --json -g
```
Expected:
- exit_code: 0
- jq: .blocked == false
### Step 12: Tool policy per Agent
```bash
set -eu
mkdir -p "$HOME/.config/skillshare/skills"
unset SKILLSHARE_CONFIG PI_CODING_AGENT_DIR
MCP_CASE=$(mktemp -d "$HOME/mcp-tools.XXXXXX")
mkdir -p "$MCP_CASE/.skillshare"
printf 'targets: []\n' > "$MCP_CASE/.skillshare/config.yaml"
cd "$MCP_CASE"
ss mcp add github --target pi --target codex --target copilot --target opencode \
--pi-options '{"exposure":"deferred"}' --tools-allow 'get_*,search_code' --tools-deny get_secret --no-tui -p -- github-mcp >/dev/null
ss sync mcp --dry-run --json -p > plan.json
jq -e '.notices == ["tool policy not applied for codex: allow patterns (github)", "tool policy not applied for copilot: allow patterns, deny (github)", "tool policy not applied for opencode: allow, deny (github)"]' plan.json >/dev/null
ss sync mcp -p >/dev/null
jq -e '.mcpServers.github.exposure == "deferred" and (.mcpServers.github.toolExposure | keys_unsorted) == ["get_secret", "get_*", "search_code", "*"]' .pi/mcp.json >/dev/null
grep -q "disabled_tools = \['get_secret'\]" .codex/config.toml
! grep -q enabled_tools .codex/config.toml
jq -e '.mcpServers.github.tools == ["*"]' .github/mcp.json >/dev/null
jq -e '.mcp.github | has("tools") | not' opencode.json >/dev/null
# github-mcp is not installed, so check exits 1 for the missing command.
ss mcp check github --json --no-dns -p > check.json || test $? -eq 1
jq -e '[.servers[].findings[] | select(.check == "tools") | .target] == ["codex", "copilot", "opencode"]' check.json >/dev/null
ss mcp edit github --tools-allow 'search_code,list_issues' --tools-deny '' --no-tui -p >/dev/null
ss sync mcp -p >/dev/null
grep -q "enabled_tools = \['search_code', 'list_issues'\]" .codex/config.toml
jq -e '.mcpServers.github.tools == ["search_code", "list_issues"]' .github/mcp.json >/dev/null
ss mcp edit github --tools-allow '' --no-tui -p >/dev/null
ss sync mcp -p >/dev/null
! grep -q _tools .codex/config.toml
if ss mcp edit github --tools-allow x --tools-deny x --no-tui -p > err 2>&1; then exit 1; fi
grep -q 'tools.deny removes every tool tools.allow keeps' err
printf '[mcp_servers.imp]\ncommand = "imp-mcp"\nenabled_tools = ["a"]\n' > imp.toml
ss mcp import imp --file imp.toml --from codex --target codex --no-tui -p >/dev/null
grep -A6 ' imp:' .skillshare/config.yaml | grep -q -- '- a'
ss sync mcp --dry-run --json -p
```
Expected:
- exit_code: 0
- jq: .blocked == false
- jq: .notices == null
## Pass Criteria
All twelve 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.
+5 -13
View File
@@ -14,7 +14,7 @@ _skillshare() {
cword=$COMP_CWORD
fi
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 commands="init install uninstall list search sync mcp hooks 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"
@@ -36,8 +36,9 @@ _skillshare() {
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 --status --sort -s --all --help -h"
local sync_flags="--all --dry-run -n --force -f --json --quiet -q --help -h"
local mcp_flags="--pi-extension --direct-tools --pi-options --pi-options-prune --url --target --from --file --sync --replace --disabled --keep-files --revision --dry-run -n --json --no-tui --no-dns --live --timeout --help -h"
local mcp_flags="--tools-allow --tools-deny --pi-options --url --target --from --file --sync --replace --disabled --keep-files --revision --dry-run -n --json --no-tui --no-dns --live --timeout --help -h"
local status_flags="--json --help -h"
local hooks_flags="--file --from --sync --replace --keep-files --revision --dry-run -n --json --help -h"
local diff_flags="--no-tui --patch --stat --json --help -h"
local backup_flags="--list -l --cleanup -c --delete --all --dry-run -n --target -t --help -h"
local backup_files_restore_flags="--unlink --dry-run -n --help -h"
@@ -88,16 +89,6 @@ _skillshare() {
return
fi
if [[ "${cmd}" == mcp && "${prev}" == --pi-extension ]]; then
COMPREPLY=($(compgen -W "builtin pi-mcp-adapter pi-mcp-extension" -- "${cur}"))
return
fi
if [[ "${cmd}" == mcp && "${prev}" == --direct-tools ]]; then
COMPREPLY=($(compgen -W "true false search" -- "${cur}"))
return
fi
# Handle subcommands (cword == 2)
if [[ ${cword} -eq 2 ]]; then
case "${cmd}" in
@@ -130,7 +121,7 @@ _skillshare() {
return
;;
sync)
COMPREPLY=($(compgen -W "agents extras mcp plugins ${sync_flags} ${global_flags}" -- "${cur}"))
COMPREPLY=($(compgen -W "agents extras mcp hooks plugins ${sync_flags} ${global_flags}" -- "${cur}"))
return
;;
list)
@@ -240,6 +231,7 @@ _skillshare() {
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 -n --json --no-tui --help -h ${global_flags}" -- "${cur}")) ;;
mcp) COMPREPLY=($(compgen -W "add check edit import list remove restore ${mcp_flags} ${global_flags}" -- "${cur}")) ;;
status) COMPREPLY=($(compgen -W "${status_flags} ${global_flags}" -- "${cur}")) ;;
hooks) COMPREPLY=($(compgen -W "add disable edit enable import list remove restore sync ${hooks_flags} ${global_flags}" -- "${cur}")) ;;
diff) COMPREPLY=($(compgen -W "${diff_flags} ${global_flags}" -- "${cur}")) ;;
backup) COMPREPLY=($(compgen -W "${backup_flags} ${global_flags}" -- "${cur}")) ;;
restore) COMPREPLY=($(compgen -W "${restore_flags} ${global_flags}" -- "${cur}")) ;;
+14 -5
View File
@@ -44,10 +44,9 @@ 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_using_command plugin' -l help -s h
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 'builtin pi-mcp-adapter pi-mcp-extension' -d 'Pi MCP mode'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l direct-tools -r -a 'true false search' -d 'pi-mcp-adapter direct tools, or tool names separated by commas'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l pi-options -r -d 'builtin or adapter: other per-server fields as JSON'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l pi-options-prune -d 'Remove only owned unchanged Pi fields (=false disables)'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l tools-allow -r -d 'Only these tools, comma-separated; empty clears'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l tools-deny -r -d 'Never these tools, comma-separated; empty clears'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l pi-options -r -d 'Other Pi built-in per-server fields as JSON'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l no-dns -d 'Skip host lookups'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l live -d 'check: start or call each server'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l timeout -r -d 'check --live: per-server timeout'
@@ -65,6 +64,16 @@ complete -c skillshare -n '__fish_skillshare_using_command mcp' -l json -d 'JSON
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l no-tui -d 'Disable interactive menus'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l help -s h -d 'Show help'
complete -c skillshare -n '__fish_skillshare_using_command mcp' -a 'add check edit import list remove restore'
complete -c skillshare -n __fish_skillshare_no_subcommand -a hooks -d 'Manage Agent hooks'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -a 'add disable edit enable import list remove restore sync'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -l file -r -F -d 'Entry or native file'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -l from -r -d 'Import Agent'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -l sync -d 'Sync after saving'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -l replace -d 'Replace an existing entry'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -l keep-files -d 'remove: leave Agent entries as they are'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -l revision -r -d 'Preview revision'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -s n -l dry-run -d 'Preview changes'
complete -c skillshare -n '__fish_skillshare_using_command hooks' -l json -d 'JSON output'
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'
@@ -161,7 +170,7 @@ complete -c skillshare -n '__fish_skillshare_using_command list' -l all -d 'List
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 mcp plugins' -d 'Sync scope'
complete -c skillshare -n '__fish_skillshare_using_command sync' -a 'agents extras mcp hooks 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'
+25 -5
View File
@@ -12,6 +12,7 @@ def "nu-complete skillshare commands" [] {
{ value: "sync", description: "Sync skills/agents/extras/MCP to targets" }
{ value: "plugin", description: "Manage complete native plugins" }
{ value: "mcp", description: "Manage MCP connections" }
{ value: "hooks", description: "Manage Agent hooks" }
{ value: "status", description: "Show status of all targets" }
{ value: "diff", description: "Show differences between source and targets" }
{ value: "backup", description: "Create backup of targets" }
@@ -50,6 +51,10 @@ def "nu-complete skillshare mcp" [] {
[add check edit import list remove restore]
}
def "nu-complete skillshare hooks" [] {
[add disable edit enable import list remove restore sync]
}
def "nu-complete skillshare plugin-target" [] {
[claude codex cursor antigravity agy antigravity-cli copilot grok kimi hermes devin pi opencode]
}
@@ -57,10 +62,9 @@ def "nu-complete skillshare plugin-target" [] {
export extern "skillshare mcp" [
command?: string@"nu-complete skillshare mcp"
name?: string
--pi-extension: string # builtin, pi-mcp-adapter or pi-mcp-extension
--direct-tools: string # pi-mcp-adapter only: true, false, search or tool names
--pi-options: string # builtin or adapter: other per-server fields as JSON
--pi-options-prune # Remove only owned unchanged Pi fields
--tools-allow: string # Only these tools, comma-separated, * matches any characters; empty clears
--tools-deny: string # Never these tools, comma-separated, * matches any characters; empty clears
--pi-options: string # Other Pi built-in per-server fields as JSON
--target: string
--from: string
--url: string
@@ -81,6 +85,22 @@ export extern "skillshare mcp" [
--help(-h)
]
export extern "skillshare hooks" [
command?: string@"nu-complete skillshare hooks"
name?: string
--file: string # Entry or native file
--from: string # Import Agent
--revision: string
--sync
--replace
--keep-files # remove: leave Agent entries as they are
--dry-run(-n)
--json
--project(-p)
--global(-g)
--help(-h)
]
export extern "skillshare plugin" [
command?: string@"nu-complete skillshare plugin"
value?: string
@@ -194,7 +214,7 @@ def "nu-complete skillshare ui" [] {
}
def "nu-complete skillshare sync-scope" [] {
["agents" "extras" "mcp" "plugins"]
["agents" "extras" "mcp" "hooks" "plugins"]
}
def "nu-complete skillshare kind" [] {
+15 -1
View File
@@ -15,6 +15,7 @@ $_skillshareCompleter = {
@{ Name = 'sync'; Desc = 'Sync skills/agents/extras/MCP to targets' }
@{ Name = 'plugin'; Desc = 'Manage complete native plugins' }
@{ Name = 'mcp'; Desc = 'Manage MCP connections' }
@{ Name = 'hooks'; Desc = 'Manage Agent hooks' }
@{ Name = 'status'; Desc = 'Show status of all targets' }
@{ Name = 'diff'; Desc = 'Show differences between source and targets' }
@{ Name = 'backup'; Desc = 'Create backup of targets' }
@@ -52,6 +53,17 @@ $_skillshareCompleter = {
@{ Name = 'remove'; Desc = 'MCP remove' }
@{ Name = 'restore'; Desc = 'MCP restore' }
)
'hooks' = @(
@{ Name = 'add'; Desc = 'Hooks add' }
@{ Name = 'disable'; Desc = 'Hooks disable' }
@{ Name = 'edit'; Desc = 'Hooks edit' }
@{ Name = 'enable'; Desc = 'Hooks enable' }
@{ Name = 'import'; Desc = 'Hooks import' }
@{ Name = 'list'; Desc = 'Hooks list' }
@{ Name = 'remove'; Desc = 'Hooks remove' }
@{ Name = 'restore'; Desc = 'Hooks restore' }
@{ Name = 'sync'; Desc = 'Hooks sync' }
)
'plugin' = @(
@{ Name = 'add'; Desc = 'Plugin add' }
@{ Name = 'discover'; Desc = 'Plugin discover' }
@@ -126,6 +138,7 @@ $_skillshareCompleter = {
@{ Name = 'agents'; Desc = 'Sync agents' }
@{ Name = 'extras'; Desc = 'Sync extras' }
@{ Name = 'mcp'; Desc = 'Sync MCP connections' }
@{ Name = 'hooks'; Desc = 'Sync hooks' }
@{ Name = 'plugins'; Desc = 'Sync plugins' }
)
'list' = @(
@@ -181,13 +194,14 @@ $_skillshareCompleter = {
'enable' = '--dry-run', '-n', '--kind', '--help', '-h', '--project', '-p', '--global', '-g'
'disable' = '--dry-run', '-n', '--kind', '--help', '-h', '--project', '-p', '--global', '-g'
'analyze' = '--verbose', '-v', '--filter', '--no-tui', '--json', '--help', '-h', '--project', '-p', '--global', '-g'
'mcp' = '--pi-extension', '--direct-tools', '--pi-options', '--pi-options-prune', '--target', '--from', '--url', '--file', '--sync', '--replace', '--disabled', '--keep-files', '--revision', '--dry-run', '-n', '--json', '--no-dns', '--live', '--timeout', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
'mcp' = '--tools-allow', '--tools-deny', '--pi-options', '--target', '--from', '--url', '--file', '--sync', '--replace', '--disabled', '--keep-files', '--revision', '--dry-run', '-n', '--json', '--no-dns', '--live', '--timeout', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
'plugin' = '--target', '--from', '--plugin', '--name', '--source-ref', '--entry', '--revision', '--dry-run', '-n', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
'extras' = '--mode', '--target', '--source', '--file', '--as', '--flatten', '--no-flatten', '--add-target', '--remove-target', '--prune', '--from', '--dry-run', '--force', '-f', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
'status' = '--json', '--help', '-h', '--project', '-p', '--global', '-g'
'new' = '--pattern', '-P', '--dry-run', '-n', '--help', '-h', '--project', '-p', '--global', '-g'
'search' = '--json', '--list', '-l', '--hub', '--limit', '-n', '--help', '-h', '--project', '-p', '--global', '-g'
'tui' = '--help', '-h'
'hooks' = '--file', '--from', '--sync', '--replace', '--keep-files', '--revision', '--dry-run', '-n', '--json', '--help', '-h', '--project', '-p', '--global', '-g'
'completion' = '--install', '--help', '-h'
}
+20 -5
View File
@@ -13,6 +13,7 @@ _skillshare() {
'sync:Sync skills/agents/extras/MCP to targets'
'plugin:Manage complete native plugins'
'mcp:Manage MCP connections'
'hooks:Manage Agent hooks'
'status:Show status of all targets'
'diff:Show differences between source and targets'
'backup:Create backup of targets'
@@ -94,10 +95,9 @@ _skillshare() {
mcp)
_arguments \
'1:command:(add check edit import list remove restore)' \
'--pi-extension[Pi MCP mode]:extension:(builtin pi-mcp-adapter pi-mcp-extension)' \
'--direct-tools[pi-mcp-adapter direct tools: true, false, search or tool names]:value:(true false search)' \
'--pi-options[builtin or adapter: other per-server fields as JSON]:json:' \
'--pi-options-prune[Remove only owned unchanged Pi fields]' \
'--tools-allow[Only these tools, comma-separated, * matches any characters; empty clears]:tools:' \
'--tools-deny[Never these tools, comma-separated, * matches any characters; empty clears]:tools:' \
'--pi-options[Other Pi built-in per-server fields as JSON]:json:' \
'--target[Receiving client]:target:' \
'--from[Import client]:target:' \
'--url[MCP endpoint]:url:' \
@@ -118,6 +118,21 @@ _skillshare() {
'--help[Show help]' \
'-h[Show help]'
;;
hooks)
_arguments \
'1:command:(add disable edit enable import list remove restore sync)' \
'--file[Entry or native file]:file:_files' \
'--from[Import Agent]:agent:' \
'--sync[Sync after saving]' \
'--replace[Replace an existing entry]' \
'--keep-files[remove: leave Agent entries as they are]' \
'--revision[Preview revision]:revision:' \
'--dry-run[Preview changes]' \
'-n[Preview changes]' \
'--json[JSON output]' \
$global_flags \
'--help[Show help]'
;;
plugin)
_arguments \
'1:command:(add discover import list inspect sync check update enable disable remove)' \
@@ -205,7 +220,7 @@ _skillshare() {
;;
sync)
_arguments \
'1:scope:(agents extras mcp plugins)' \
'1:scope:(agents extras mcp hooks plugins)' \
'--all[Sync skills + agents + extras]' \
'--dry-run[Preview changes]' \
'-n[Preview changes]' \
+202
View File
@@ -0,0 +1,202 @@
package main
import (
"errors"
"fmt"
"os"
"strings"
"skillshare/internal/config"
"skillshare/internal/hooks"
)
type hooksOptions struct {
name, file, from, revision string
sync, dryRun, json, replace bool
keepFiles bool
}
func parseHooksOptions(args []string) (hooksOptions, error) {
var o hooksOptions
for i := 0; i < len(args); i++ {
switch a := args[i]; a {
case "--file", "--from", "--revision":
if i+1 == len(args) {
return o, fmt.Errorf("%s requires a value", a)
}
i++
switch a {
case "--file":
o.file = args[i]
case "--from":
o.from = args[i]
case "--revision":
o.revision = args[i]
}
case "--sync":
o.sync = true
case "--dry-run", "-n":
o.dryRun = true
case "--json":
o.json = true
case "--replace":
o.replace = true
case "--keep-files":
o.keepFiles = true
default:
if strings.HasPrefix(a, "-") || o.name != "" {
return o, fmt.Errorf("unknown hooks argument %q", a)
}
o.name = a
}
}
return o, nil
}
func hooksContext(args []string) (*hooks.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
}
}
service := &hooks.Service{ConfigPath: config.ConfigPath(), StateDir: config.StateDir(), ConfigDirs: hooks.ConfigDirsFromEnv()}
if mode == modeProject {
service.ConfigPath = config.ProjectConfigPath(cwd)
service.ProjectRoot = cwd
}
applyModeLabel(mode)
return service, rest, nil
}
func cmdHooks(args []string) error {
if wantsHelp(args) {
printHooksHelp()
return nil
}
if len(args) == 0 || strings.HasPrefix(args[0], "-") {
args = append([]string{"list"}, args...)
}
sub, args := args[0], args[1:]
service, rest, err := hooksContext(args)
if err != nil {
return err
}
o, err := parseHooksOptions(rest)
if err != nil {
return err
}
if err := checkHooksFlags(sub, o); err != nil {
return err
}
return hooksJSONError(runHooks(service, sub, o), o)
}
// cmdSyncHooks is "skillshare sync hooks", the same as "skillshare hooks sync".
func cmdSyncHooks(args []string) error {
if wantsHelp(args) {
printHooksHelp()
return nil
}
service, rest, err := hooksContext(args)
if err != nil {
return err
}
o, err := parseHooksOptions(rest)
if err != nil {
return err
}
if o.name != "" || o.file != "" || o.from != "" || o.sync || o.replace || o.keepFiles {
return fmt.Errorf("sync hooks accepts only --dry-run, --json, --revision and scope flags; use 'skillshare hooks sync <name> --replace' to take over conflicts")
}
return hooksJSONError(runHooks(service, "sync", o), o)
}
// hooksJSONError keeps --json failures machine-readable.
func hooksJSONError(err error, o hooksOptions) error {
var silent *jsonSilentError
if err != nil && o.json && !errors.As(err, &silent) {
return writeJSONError(err)
}
return err
}
// checkHooksFlags rejects flags a subcommand would otherwise ignore silently.
func checkHooksFlags(sub string, o hooksOptions) error {
allowed := map[string]string{
"list": "",
"add": "name file sync replace",
"edit": "name file sync replace",
"import": "name file from sync replace",
"enable": "name sync replace",
"disable": "name sync replace",
"remove": "name sync replace",
"sync": "name replace",
"restore": "name",
}
spec, ok := allowed[sub]
if !ok {
return fmt.Errorf("unknown hooks command %q; run skillshare hooks --help", sub)
}
used := map[string]bool{"name": o.name != "", "file": o.file != "", "from": o.from != "", "sync": o.sync, "replace": o.replace}
for flag, set := range used {
if set && !strings.Contains(" "+spec+" ", " "+flag+" ") {
if flag == "name" {
return fmt.Errorf("hooks %s takes no name", sub)
}
return fmt.Errorf("--%s does not apply to hooks %s", flag, sub)
}
}
if o.keepFiles && (sub != "remove" || o.sync) {
return fmt.Errorf("--keep-files only applies to hooks remove without --sync: it leaves Agent files as they are")
}
if sub == "sync" && o.name != "" && !o.replace {
return fmt.Errorf("hooks sync takes a name only with --replace, to take over that hook's conflicting Agent entries")
}
if sub == "list" && (o.dryRun || o.revision != "") {
return fmt.Errorf("hooks list accepts only --json and scope flags")
}
return nil
}
func printHooksHelp() {
fmt.Println(`Usage: skillshare hooks [command] [options]
Commands:
list Show hook entries, their Agents and sync status (default)
add <name> Add an entry from --file (Entry JSON or YAML)
edit <name> Replace an existing entry's definition from --file
import Read native hooks with --from <agent> (or --file <native file>);
list candidates, or save one with a name
enable <name> Publish a disabled entry again on the next sync
disable <name> Keep the definition; the next sync removes its owned outputs
remove <name> Delete the entry; the next sync prunes its owned outputs,
or stop managing it and keep its Agent entries (--keep-files)
sync [name] Write hooks to each Agent's native configuration; with a name
and --replace, take over that hook's conflicting Agent entries
restore <id> Preview and restore an Agent file from a hooks backup
Options:
--file <path> Entry document for add/edit, or native file for import
--from <agent> Agent to import from, such as claude or codex
--sync Save and synchronize (default: save the source only)
--replace Replace an existing entry, or take over its conflicting
Agent entries (unmanaged duplicates or outside edits)
--keep-files remove only: stop managing the hook; its Agent entries stay
--dry-run, -n Preview without writing
--json Machine-readable output
--revision <id> Require the matching preview revision
--global, -g Global configuration
--project, -p Project configuration
Sync alias: skillshare sync hooks [--dry-run] [--json] [-g|-p]; sync --all includes hooks.
Import reads configuration and code only; it never runs hook commands.`)
}
+363
View File
@@ -0,0 +1,363 @@
package main
import (
"fmt"
"maps"
"os"
"slices"
"strings"
"time"
"skillshare/internal/hooks"
"skillshare/internal/oplog"
"skillshare/internal/ui"
)
func runHooks(service *hooks.Service, sub string, o hooksOptions) error {
switch sub {
case "list":
return runHooksList(service, o)
case "add", "edit":
return runHooksSave(service, sub, o)
case "import":
return runHooksImport(service, o)
case "enable", "disable":
return runHooksToggle(service, sub == "enable", o)
case "remove":
if o.name == "" {
return fmt.Errorf("usage: skillshare hooks remove <name> [--sync | --keep-files]")
}
if _, err := hooksEntry(service, o.name); err != nil {
return err
}
return finishHooksMutation(service, "hooks remove", hooks.Mutation{Name: o.name, Remove: true, Replace: o.replace, Unmanage: o.keepFiles}, o)
case "sync":
o.sync = true
// A name only scopes --replace; the sync itself covers every entry.
return finishHooksMutation(service, "hooks sync", hooks.Mutation{Name: o.name, Replace: o.replace}, o)
case "restore":
return runHooksRestore(service, o)
}
return fmt.Errorf("unknown hooks command %q; run skillshare hooks --help", sub)
}
func runHooksList(service *hooks.Service, o hooksOptions) error {
inv, err := service.List()
if err != nil {
return err
}
if o.json {
return writeJSON(inv)
}
ui.Info("Hooks source: %s", inv.Source.Path)
for _, name := range slices.Sorted(maps.Keys(inv.Source.Entries)) {
entry := inv.Source.Entries[name]
state := "enabled"
if entry.Enabled != nil && !*entry.Enabled {
state = "disabled"
}
agents := strings.Join(slices.Sorted(maps.Keys(entry.Bindings)), ", ")
if agents == "" {
agents = "no Agents"
}
ui.Status(name, state, agents)
}
if len(inv.Source.Entries) == 0 {
ui.Info("No hooks configured. Run 'skillshare hooks add <name> --file <entry.yaml>' to get started.")
}
for _, u := range inv.Unmanaged {
ui.Status(u.Target, "not managed", u.Path+": "+strings.Join(u.Names, ", "))
}
if inv.PreviewError != "" {
ui.Warning("Sync preview failed: %s", inv.PreviewError)
} else if inv.Plan != nil && len(inv.Plan.Changes) > 0 {
ui.Info("Pending sync changes:")
printHooksChanges(inv.Plan)
}
return nil
}
func runHooksSave(service *hooks.Service, sub string, o hooksOptions) error {
if o.name == "" || o.file == "" {
return fmt.Errorf("usage: skillshare hooks %s <name> --file <entry.json|entry.yaml> [--sync]", sub)
}
data, err := os.ReadFile(o.file)
if err != nil {
return err
}
entry, err := hooks.ParseEntry(data)
if err != nil {
return fmt.Errorf("%s: %w", o.file, err)
}
_, lookupErr := hooksEntry(service, o.name)
switch {
case sub == "edit" && lookupErr != nil:
return lookupErr
case sub == "add" && lookupErr == nil && !o.replace:
return fmt.Errorf("hook %s already exists; use 'skillshare hooks edit %s --file %s' or --replace", o.name, o.name, o.file)
}
return finishHooksMutation(service, "hooks "+sub, hooks.Mutation{Name: o.name, Entry: &entry, Replace: o.replace}, o)
}
func runHooksToggle(service *hooks.Service, enabled bool, o hooksOptions) error {
command := "hooks disable"
if enabled {
command = "hooks enable"
}
if o.name == "" {
return fmt.Errorf("usage: skillshare %s <name> [--sync]", command)
}
entry, err := hooksEntry(service, o.name)
if err != nil {
return err
}
entry.Enabled = &enabled
return finishHooksMutation(service, command, hooks.Mutation{Name: o.name, Entry: &entry, Replace: o.replace}, o)
}
func runHooksImport(service *hooks.Service, o hooksOptions) error {
if o.from == "" {
return fmt.Errorf("usage: skillshare hooks import --from <agent> [--file <native file>] [name] [--dry-run]")
}
request := hooks.ImportRequest{From: o.from, Name: o.name}
if o.file != "" {
data, err := os.ReadFile(o.file)
if err != nil {
return err
}
request.Content = string(data)
}
candidates, err := service.Import(request)
if err != nil {
return err
}
if o.name == "" {
return printHooksCandidates(candidates, o.json)
}
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 !o.json {
for _, w := range c.Warnings {
ui.Warning("%s", w)
}
}
if _, err := hooksEntry(service, c.Name); err == nil && !o.replace {
return fmt.Errorf("hook %s already exists; use --replace to overwrite its definition", c.Name)
}
// Importing takes over the registrations it read, so they are not reported as
// unmanaged duplicates on the next sync.
return finishHooksMutation(service, "hooks import", hooks.Mutation{Name: c.Name, Entry: &c.Entry, Replace: o.replace, Adopt: true}, o)
}
return fmt.Errorf("hook %q not found in %s", o.name, o.from)
}
func runHooksRestore(service *hooks.Service, o hooksOptions) error {
if o.name == "" {
return fmt.Errorf("usage: skillshare hooks restore <backup-id> [--dry-run]; 'skillshare hooks list --json' shows backups")
}
p, err := service.PreviewRestore(o.name)
if err != nil {
return err
}
o.sync = true
if err := checkHooksPreview(p, o); err != nil || o.dryRun {
return err
}
start := time.Now()
result, err := service.Restore(o.name, p.Revision)
logHooksOp(service.ConfigPath, "hooks restore", start, err)
return printHooksResult(result, err, o)
}
// finishHooksMutation previews first and applies with that preview's revision, so
// native files edited in between are reported instead of being overwritten.
func finishHooksMutation(service *hooks.Service, command string, mutation hooks.Mutation, o hooksOptions) error {
p, err := service.PreviewMutation(mutation)
if err != nil {
return err
}
if err := checkHooksPreview(p, o); err != nil || o.dryRun {
return err
}
start := time.Now()
result, err := service.Mutate(mutation, p.Revision, o.sync)
logHooksOp(service.ConfigPath, command, start, err)
return printHooksResult(result, err, o)
}
// applyHooksSync previews the whole source and applies with that revision, so sync
// --all never writes past a conflict that appeared after its preflight.
func applyHooksSync(service *hooks.Service, start time.Time) (*hooks.Result, error) {
p, err := service.Preview()
if err != nil {
return nil, err
}
result := &hooks.Result{Plan: p, Applied: []string{}, BackupIDs: []string{}}
if p.Blocked {
err = hooks.ErrConflict
} else {
result, err = service.Mutate(hooks.Mutation{}, p.Revision, true)
}
logHooksOp(service.ConfigPath, "sync hooks", start, err)
return result, err
}
// checkHooksPreview prints a dry-run or blocked plan and enforces --revision. Conflicts
// block only writes to Agent files; saving the source alone always proceeds.
func checkHooksPreview(p *hooks.Plan, o hooksOptions) error {
if o.revision != "" && o.revision != p.Revision {
return hooks.ErrStaleRevision
}
blocked := error(nil)
if o.sync && p.Blocked {
blocked = hooks.ErrConflict
}
if !o.dryRun && blocked == nil {
return nil
}
if o.json {
return writeJSONResult(p, blocked)
}
printHooksPlan(p)
return blocked
}
func hooksEntry(service *hooks.Service, name string) (hooks.Entry, error) {
inv, err := service.List()
if err != nil {
return hooks.Entry{}, err
}
entry, ok := inv.Source.Entries[name]
if !ok {
return entry, fmt.Errorf("hook %s not found; run 'skillshare hooks list'", name)
}
return entry, nil
}
func printHooksPlan(p *hooks.Plan) {
ui.Info("Hooks source: %s", p.SourcePath)
printHooksChanges(p)
if len(p.Changes) == 0 {
ui.Info("No hook changes.")
}
}
func printHooksChanges(p *hooks.Plan) {
home, _ := os.UserHomeDir()
conflicts := []string{}
for _, c := range p.Changes {
detail := c.Target + " " + hooksDisplayPath(c.Path, home)
if c.Events != nil {
detail += " " + hooksEventDetail(c.Events)
}
if c.Message != "" {
detail += " — " + c.Message
}
ui.Status(c.Name, c.Action, detail)
if c.Action == "conflict" && c.Name != "" && c.Root == "" && !slices.Contains(conflicts, c.Name) {
conflicts = append(conflicts, c.Name)
}
}
for _, w := range p.Warnings {
ui.Warning("%s", w)
}
for _, name := range conflicts {
ui.Info("To take over %s's conflicting Agent entries: skillshare hooks sync %s --replace", name, name)
}
}
// hooksDisplayPath shortens a path under the home directory to ~/...
func hooksDisplayPath(path, home string) string {
if home != "" && strings.HasPrefix(path, home+string(os.PathSeparator)) {
return "~" + path[len(home):]
}
return path
}
// hooksEventDetail renders events added (+), updated (~) and removed (−).
func hooksEventDetail(e *hooks.EventChanges) string {
var parts []string
for _, group := range []struct {
mark string
events []string
}{{"+", e.Added}, {"~", e.Updated}, {"−", e.Removed}} {
if len(group.events) > 0 {
parts = append(parts, group.mark+" "+strings.Join(group.events, ", "))
}
}
return strings.Join(parts, " ")
}
func printHooksResult(result *hooks.Result, err error, o hooksOptions) error {
if o.json {
if result == nil {
return err
}
return writeJSONResult(result, err)
}
if result != nil {
if result.Plan != nil {
printHooksPlan(result.Plan)
}
for _, id := range result.BackupIDs {
ui.Info("Backup: %s", id)
}
if err == nil && !o.sync {
ui.Success("Hooks source saved. Run 'skillshare hooks sync' when ready.")
} else if err == nil {
ui.Success("Hook files applied: %d. Restart or reload the Agent to load them.", len(result.Applied))
}
}
return err
}
func printHooksCandidates(candidates []hooks.Candidate, asJSON bool) error {
if asJSON {
return writeJSON(candidates)
}
// A warning several candidates share is printed once, after the rows.
seen := map[string]int{}
for _, c := range candidates {
for _, w := range c.Warnings {
seen[w]++
}
}
var shared []string
for _, c := range candidates {
var own []string
for _, w := range c.Warnings {
if seen[w] > 1 {
if !slices.Contains(shared, w) {
shared = append(shared, w)
}
continue
}
own = append(own, w)
}
if len(c.Problems) > 0 {
ui.Status(c.Name, "blocked", strings.Join(c.Problems, "; "))
} else {
ui.Status(c.Name, "importable", strings.Join(own, "; "))
}
}
for _, w := range shared {
ui.Info("%s%s", strings.ToUpper(w[:1]), w[1:]+".")
}
if len(candidates) == 0 {
ui.Info("No hooks found to import.")
} else {
ui.Info("Import one with 'skillshare hooks import --from <agent> <name>' (add --dry-run to preview).")
}
return nil
}
func logHooksOp(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 hooks operation log")
}
}
+14
View File
@@ -48,6 +48,7 @@ var commands = map[string]func([]string) error{
"tui": cmdTUIToggle,
"extras": cmdExtras,
"mcp": cmdMCP,
"hooks": cmdHooks,
"plugin": cmdPlugin,
"enable": cmdEnable,
"disable": cmdDisable,
@@ -284,6 +285,19 @@ func printUsage() {
cmd("mcp restore", "[id]", "Restore client entries from a backup")
fmt.Println()
// Hooks
fmt.Println("HOOKS")
cmd("hooks list", "", "Show hook entries and per-Agent sync status")
cmd("hooks add", "<name> --file <path>", "Add a hook entry from JSON or YAML")
cmd("hooks edit", "<name> --file <path>", "Replace a hook entry's definition")
cmd("hooks import", "--from <agent> [name]", "Import native hooks without running them")
cmd("hooks enable", "<name>", "Publish a disabled hook on the next sync")
cmd("hooks disable", "<name>", "Keep a hook but unpublish it on the next sync")
cmd("hooks remove", "<name>", "Remove a hook entry from the source")
cmd("hooks sync", "", "Write hooks to Agent configuration")
cmd("hooks restore", "<id>", "Restore Agent hook files from a backup")
fmt.Println()
// Git Remote
fmt.Println("GIT REMOTE")
cmd("commit", "", "Create local git commit without pushing")
+68 -37
View File
@@ -6,8 +6,8 @@ import (
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
@@ -17,47 +17,51 @@ import (
)
type mcpOptions struct {
name, url, from, file, revision, piExtension string
// directTools is nil unless --direct-tools was given.
directTools any
name, url, from, file, revision string
// toolsAllow and toolsDeny are nil unless their --tools-* flag was given; an empty
// value clears that part of the tool policy.
toolsAllow, toolsDeny *string
// piOptions is nil unless --pi-options was given.
piOptions mcp.PiOptions
targets []string
command []string
sync, dryRun, json, replace, noTUI, disabled bool
keepFiles bool
piOptionsPrune bool
piOptionsPruneSet bool
}
// removedMCPFlags were Pi settings until 0.23.0. Naming one says what replaced it rather
// than calling the flag unknown.
var removedMCPFlags = map[string]string{
"--pi-extension": "--pi-extension was removed in 0.23.0: Pi always uses its built-in MCP (~/.pi/agent/mcp.json or .pi/mcp.json); drop the flag",
"--pi-options-prune": "--pi-options-prune was removed in 0.23.0: sync always removes Pi fields Skillshare wrote earlier that are unchanged; drop the flag",
"--direct-tools": "--direct-tools was removed in 0.23.0: use --pi-options '{\"exposure\":\"direct\"}' for every tool, or --pi-options '{\"toolExposure\":{\"TOOL\":\"direct\"}}' for single tools in Pi",
}
func parseMCPOptions(args []string) (mcpOptions, error) {
var o mcpOptions
for i := 0; i < len(args); i++ {
flag, _, _ := strings.Cut(args[i], "=")
if message, removed := removedMCPFlags[flag]; removed {
return o, errors.New(message)
}
switch a := args[i]; a {
case "--":
o.command = args[i+1:]
i = len(args)
case "--url", "--target", "--from", "--file", "--revision", "--pi-extension", "--direct-tools", "--pi-options":
case "--url", "--target", "--from", "--file", "--revision", "--tools-allow", "--tools-deny", "--pi-options":
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 "--direct-tools":
switch value {
case "true", "false":
o.directTools = value == "true"
case "search":
o.directTools = value
default:
o.directTools = strings.Split(value, ",")
}
case "--tools-allow":
o.toolsAllow = &value
case "--tools-deny":
o.toolsDeny = &value
case "--pi-options":
if err := json.Unmarshal([]byte(value), &o.piOptions); err != nil || o.piOptions == nil {
return o, fmt.Errorf("--pi-options takes a JSON object, such as '{\"excludeTools\":[\"delete_*\"]}'")
return o, fmt.Errorf("--pi-options takes a JSON object, such as '{\"timeout\":30}'")
}
case "--url":
o.url = value
@@ -82,21 +86,9 @@ func parseMCPOptions(args []string) (mcpOptions, error) {
o.replace = true
case "--disabled":
o.disabled = true
case "--pi-options-prune":
o.piOptionsPrune = true
o.piOptionsPruneSet = true
case "--keep-files":
o.keepFiles = true
default:
if value, found := strings.CutPrefix(a, "--pi-options-prune="); found {
var err error
o.piOptionsPrune, err = strconv.ParseBool(value)
if err != nil {
return o, fmt.Errorf("--pi-options-prune takes true or false")
}
o.piOptionsPruneSet = true
continue
}
if strings.HasPrefix(a, "-") || o.name != "" {
return o, fmt.Errorf("unknown MCP argument %q", a)
}
@@ -113,6 +105,32 @@ func parseMCPOptions(args []string) (mcpOptions, error) {
return o, nil
}
// toolFlags reports whether any --tools-* flag was given.
func (o mcpOptions) toolFlags() bool {
return o.toolsAllow != nil || o.toolsDeny != nil
}
// applyToolFlags sets the parts of a tool policy that --tools-* flags name. Lists are
// comma-separated; an empty value clears the part.
func (o mcpOptions) applyToolFlags(t mcp.ToolPolicy) mcp.ToolPolicy {
list := func(value string) []string {
var tools []string
for _, tool := range strings.Split(value, ",") {
if tool = strings.TrimSpace(tool); tool != "" {
tools = append(tools, tool)
}
}
return tools
}
if o.toolsAllow != nil {
t.Allow = list(*o.toolsAllow)
}
if o.toolsDeny != nil {
t.Deny = list(*o.toolsDeny)
}
return t
}
func cmdMCP(args []string) (resultErr error) {
defer func() {
if errors.Is(resultErr, errMCPCancelled) {
@@ -215,7 +233,7 @@ func cmdSyncMCP(args []string) error {
if err != nil {
return err
}
if o.piOptionsPruneSet || o.piOptionsPrune || o.piOptions != nil || o.directTools != nil || o.piExtension != "" || o.name != "" || o.url != "" || o.from != "" || o.file != "" || len(o.command) > 0 || o.targets != nil || o.replace || o.sync || o.disabled || o.keepFiles {
if o.piOptions != nil || o.toolFlags() || o.name != "" || o.url != "" || o.from != "" || o.file != "" || len(o.command) > 0 || o.targets != nil || o.replace || o.sync || o.disabled || o.keepFiles {
return fmt.Errorf("sync mcp accepts only --dry-run, --json, --revision and scope flags")
}
if o.dryRun {
@@ -273,6 +291,9 @@ func printMCPPlan(p *mcp.Plan, asJSON bool) error {
return json.NewEncoder(os.Stdout).Encode(p)
}
ui.Info("MCP source: %s", p.SourcePath)
for _, notice := range p.Notices {
ui.Warning("%s", notice)
}
// mcp.projects puts one server into several roots; name the file only then.
seen := map[string]int{}
for _, c := range p.Changes {
@@ -306,6 +327,7 @@ func printMCPResult(result *mcp.Result, asJSON bool) error {
for _, id := range result.BackupIDs {
ui.Info("Backup: %s", id)
}
printMCPMigrated(result)
if result.Plan == nil {
ui.Success("MCP source saved. Run 'skillshare sync mcp' when ready.")
} else if !result.Plan.Blocked {
@@ -314,6 +336,13 @@ func printMCPResult(result *mcp.Result, asJSON bool) error {
return nil
}
// printMCPMigrated says the sync also saved the config without the settings 0.23.0 retired.
func printMCPMigrated(result *mcp.Result) {
for _, file := range result.Migrated {
ui.Info("Updated %s for 0.23.0 (backup: %s)", filepath.Base(file.Path), file.Backup)
}
}
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")
@@ -335,17 +364,19 @@ Commands:
restore [id] Browse backups, preview and restore Agent entries
Options:
--pi-extension <mode> builtin (Pi >= 0.99.0; default for a new server), pi-mcp-adapter or pi-mcp-extension
--direct-tools <value> pi-mcp-adapter only: true, false, search, or tool names separated by commas
--pi-options <json> builtin or adapter: other per-server fields as a JSON object
--pi-options-prune Remove cleared Pi fields only if owned and unchanged (=false disables)
--tools-allow <tools> Only these tools, separated by commas; * matches any
characters ("" clears)
--tools-deny <tools> Never these tools, separated by commas; beats allow
("" clears). The plan names each Agent that cannot hold
a part of the tool policy
--pi-options <json> Other Pi built-in per-server fields as a JSON object
--target <client> Receiving client; repeat for multiple clients, or none to keep
the server in Skillshare without writing it to any Agent
--from <client> Native client ID or account target (see mcp documentation)
--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)
(add NAME --disabled --target opencode; claude, opencode, kilocode)
--sync Save and synchronize (non-interactive default: save only)
--keep-files remove only: stop managing the server; its Agent entries stay
and sync no longer removes or updates them
+8 -1
View File
@@ -5,8 +5,15 @@ import (
"skillshare/internal/config"
"skillshare/internal/mcp"
syncpkg "skillshare/internal/sync"
)
// backupMCPSource keeps a config's content in the file history before a sync saves it
// without the MCP settings 0.23.0 retired.
func backupMCPSource(path string) (string, error) {
return syncpkg.StoreBackup(path, syncpkg.BackupReasonMigrate)
}
func mcpContext(args []string) (*mcp.Service, []string, error) {
// Do not interpret flags belonging to a spawned server after --.
var command []string
@@ -32,7 +39,7 @@ func mcpContext(args []string) (*mcp.Service, []string, error) {
mode = modeProject
}
}
service := &mcp.Service{ConfigPath: config.ConfigPath(), StateDir: config.StateDir(), ConfigDirs: mcp.ConfigDirsFromEnv()}
service := &mcp.Service{ConfigPath: config.ConfigPath(), StateDir: config.StateDir(), ConfigDirs: mcp.ConfigDirsFromEnv(), BackupSource: backupMCPSource}
if mode == modeProject {
service.ConfigPath = config.ProjectConfigPath(cwd)
service.ProjectRoot = cwd
+35 -17
View File
@@ -29,7 +29,7 @@ func runMCPEdit(service *mcp.Service, o mcpOptions) error {
if o.url != "" && len(o.command) > 0 {
return fmt.Errorf("choose either --url or -- command args")
}
if o.piExtension != "" || o.directTools != nil || o.piOptions != nil || o.piOptionsPruneSet || o.piOptionsPrune || o.url != "" || len(o.command) > 0 || o.targets != nil {
if o.toolFlags() || o.piOptions != nil || o.url != "" || len(o.command) > 0 || o.targets != nil {
server = patchMCPServer(server, o)
if err := source.CheckUnchanged(); err != nil {
return err
@@ -38,7 +38,7 @@ func runMCPEdit(service *mcp.Service, o mcpOptions) error {
return finishMCPMutation(service, mcp.Mutation{Name: name, Server: &server, Replace: true}, o, time.Now())
}
if !interactive {
return fmt.Errorf("provide --url, --target, --pi-extension, --direct-tools, --pi-options or -- command args with --no-tui/--json; omit --no-tui for the editor")
return fmt.Errorf("provide --url, --target, --tools-allow, --tools-deny, --pi-options 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 {
@@ -51,15 +51,7 @@ func runMCPEdit(service *mcp.Service, o mcpOptions) error {
}
func patchMCPServer(server mcp.Server, o mcpOptions) mcp.Server {
if o.piExtension != "" {
server.PiExtension = o.piExtension
}
if o.directTools != nil {
server.DirectTools = o.directTools
}
if o.piOptionsPruneSet || o.piOptionsPrune {
server.PiOptionsPrune = o.piOptionsPrune
}
server.Tools = o.applyToolFlags(server.Tools)
if o.piOptions != nil {
server.PiOptions = o.piOptions
}
@@ -102,9 +94,9 @@ func editMCPDraft(service *mcp.Service, name string, server mcp.Server, defaults
{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: "Tools", desc: mcpToolsSummary(server.Tools)},
{label: "Targets", desc: mcpTargetSummary(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 {
@@ -184,12 +176,10 @@ func editMCPDraft(service *mcp.Service, name string, server mcp.Server, defaults
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)
server.Tools, err = editMCPTools(server.Tools, prompts)
case 6:
server.Targets, err = chooseMCPTargets(service, []mcp.Server{server}, targets, prompts)
case 7:
if err := server.Validate(name); err != nil {
fmt.Println(err)
continue
@@ -202,6 +192,34 @@ func editMCPDraft(service *mcp.Service, name string, server mcp.Server, defaults
}
}
func mcpToolsSummary(tools mcp.ToolPolicy) string {
if tools.IsZero() {
return "Every tool, as each Agent shows it by default"
}
var parts []string
if len(tools.Allow) > 0 {
parts = append(parts, "only "+strings.Join(tools.Allow, ", "))
}
if len(tools.Deny) > 0 {
parts = append(parts, "never "+strings.Join(tools.Deny, ", "))
}
return strings.Join(parts, "; ")
}
// editMCPTools asks for the tool policy the --tools-* flags set: the allowed and the denied
// tools.
func editMCPTools(tools mcp.ToolPolicy, prompts mcpPrompts) (mcp.ToolPolicy, error) {
allow, err := prompts.text("Allowed tools, separated by commas; * matches any characters; empty allows every tool", strings.Join(tools.Allow, ","))
if err != nil {
return tools, err
}
deny, err := prompts.text("Denied tools, separated by commas; they win over allowed ones; empty denies none", strings.Join(tools.Deny, ","))
if err != nil {
return tools, err
}
return mcpOptions{toolsAllow: &allow, toolsDeny: &deny}.applyToolFlags(mcp.ToolPolicy{}), nil
}
func parseMCPArgumentInput(text string) ([]string, error) {
if text == "" {
return nil, nil
+4 -31
View File
@@ -21,7 +21,7 @@ func runMCPAdd(service *mcp.Service, o mcpOptions) error {
}
return mcpAddWizard(service, o)
}
server := mcp.Server{URL: o.url, Targets: o.targets, PiExtension: o.piExtension, DirectTools: o.directTools, PiOptions: o.piOptions, PiOptionsPrune: o.piOptionsPrune, Disabled: o.disabled}
server := mcp.Server{URL: o.url, Targets: o.targets, Tools: o.applyToolFlags(mcp.ToolPolicy{}), PiOptions: o.piOptions, Disabled: o.disabled}
if len(o.command) > 0 {
server.Command, server.Args = o.command[0], o.command[1:]
}
@@ -32,10 +32,6 @@ func runMCPAdd(service *mcp.Service, o mcpOptions) error {
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)
}
// A switch-only entry takes the mode of the server it turns off.
if !server.Disabled {
source.DefaultPiExtension(&server)
}
return finishMCPMutation(service, mcp.Mutation{Name: o.name, Server: &server}, o, time.Now())
}
@@ -94,29 +90,9 @@ func runMCPImport(service *mcp.Service, o mcpOptions) error {
if format == "" && strings.HasSuffix(o.file, ".toml") {
format = "codex"
}
if o.piExtension != "" && o.from == "" {
if format == "" {
format = mcp.DetectImportFormat(data)
}
if format != "pi" {
return fmt.Errorf("--pi-extension requires Pi input when --from is omitted; detected %s", format)
}
}
if format == "pi" && o.piExtension != "" {
candidates, err = mcp.ImportPi(data, o.name, o.piExtension)
} else {
candidates, err = mcp.Import(format, data, o.name)
}
candidates, err = mcp.Import(format, data, o.name)
} else {
format, formatErr := service.ImportFormat(o.from)
if formatErr != nil {
return formatErr
}
mode := ""
if format == "pi" {
mode = o.piExtension
}
candidates, err = service.ImportClientMode(o.from, mode)
candidates, err = service.ImportClient(o.from)
}
if err != nil {
return err
@@ -147,10 +123,7 @@ func runMCPImport(service *mcp.Service, o mcpOptions) error {
return fmt.Errorf("MCP source entry exists; use --replace")
}
c.Server.Targets = o.targets
if o.piExtension != "" {
c.Server.PiExtension = o.piExtension
}
source.DefaultPiExtension(&c.Server)
c.Server.Tools = o.applyToolFlags(c.Server.Tools)
selectedTargets := c.Server.Targets
if selectedTargets == nil {
selectedTargets = source.Targets
+2 -7
View File
@@ -35,11 +35,7 @@ func mcpBatchImportWizard(service *mcp.Service, candidates []mcp.Candidate, o mc
}
servers := make([]mcp.Server, 0, len(selected))
for _, i := range selected {
server := eligible[i].Server
if o.piExtension != "" {
server.PiExtension = o.piExtension
}
servers = append(servers, server)
servers = append(servers, eligible[i].Server)
}
initial := o.targets
if initial == nil {
@@ -50,9 +46,8 @@ func mcpBatchImportWizard(service *mcp.Service, candidates []mcp.Candidate, o mc
return err
}
mutations := make([]mcp.Mutation, 0, len(selected))
for position, i := range selected {
for _, 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)
}
-40
View File
@@ -82,9 +82,6 @@ func chooseMCPTargets(service *mcp.Service, servers []mcp.Server, initial []stri
for _, item := range items {
compatible := true
for _, server := range servers {
if item.label == "pi" && server.PiExtension == "" {
server.PiExtension = "builtin"
}
if _, err := mcp.Render(item.label, server); err != nil {
compatible = false
break
@@ -110,26 +107,6 @@ func chooseMCPTargets(service *mcp.Service, servers []mcp.Server, initial []stri
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
}
@@ -305,20 +282,3 @@ func runMCPRestore(service *mcp.Service, o mcpOptions, prompts mcpPrompts) error
}
return err
}
func choosePiExtension(initial string, p mcpPrompts) (string, error) {
packages := []string{"builtin", "pi-mcp-adapter", "pi-mcp-extension"}
if initial == "" {
initial = "builtin"
}
items := []checklistItemData{
{label: packages[0], desc: "Pi >= 0.99.0; built-in MCP and codemode; manage with /mcp", preSelected: initial == packages[0]},
{label: packages[1], desc: "On-demand proxy tools; manage with /mcp-adapter", preSelected: initial == packages[1]},
{label: packages[2], desc: "Direct tools; start with /mcp:start <server>", preSelected: initial == packages[2]},
}
selected, err := chooseMCP(p, checklistConfig{title: "Which MCP mode do you use in Pi?", header: "Built-in requires Pi >= 0.99.0. Third-party packages need installation. Sync writes configuration only.", items: items, singleSelect: true, itemName: "mode"})
if err != nil {
return "", err
}
return packages[selected[0]], nil
}
+65 -185
View File
@@ -3,178 +3,79 @@ package main
import (
"os"
"path/filepath"
"reflect"
"skillshare/internal/mcp"
"slices"
"strings"
"testing"
)
func TestMCPPiImportAutodetectedFileUsesSelectedMode(t *testing.T) {
for _, mode := range []string{"builtin", "pi-mcp-adapter", "pi-mcp-extension"} {
t.Run(mode, func(t *testing.T) {
s := mcpTUIService(t)
path := filepath.Join(s.Home, "export.json")
if err := os.WriteFile(path, []byte(`{"mcpServers":{"a":{"command":"c","exposure":"direct"}}}`), 0600); err != nil {
t.Fatal(err)
}
o, err := parseMCPOptions([]string{"a", "--file", path, "--pi-extension", mode, "--target", "claude", "--no-tui"})
if err != nil {
t.Fatal(err)
}
output := captureStdout(t, func() { err = runMCPImport(s, o) })
if err != nil {
t.Fatal(err)
}
source, err := mcp.LoadSource(s.ConfigPath)
if err != nil || source.Servers["a"].PiExtension != mode {
t.Fatalf("%+v %v", source, err)
}
if mode == "pi-mcp-extension" && (len(source.Servers["a"].PiOptions) != 0 || !strings.Contains(output, "Agent-specific field not imported: exposure")) {
t.Fatalf("extension options or warning: %+v %s", source.Servers["a"], output)
}
if mode == "pi-mcp-adapter" && !strings.Contains(output, "Pi built-in field") {
t.Fatalf("adapter mode silently accepted exposure: %s", output)
}
})
// The flags that chose Pi's MCP mode and opted in to pruning were removed in 0.23.0; naming
// one says what happens now instead of calling it unknown.
func TestMCPRemovedPiFlags(t *testing.T) {
for _, args := range [][]string{
{"docs", "--pi-extension", "builtin"},
{"docs", "--pi-extension=pi-mcp-adapter"},
{"docs", "--pi-options-prune"},
{"docs", "--pi-options-prune=false"},
{"docs", "--direct-tools", "true"},
} {
flag, _, _ := strings.Cut(args[1], "=")
if _, err := parseMCPOptions(args); err == nil || !strings.Contains(err.Error(), flag+" was removed in 0.23.0") {
t.Errorf("%v: %v", args, err)
}
}
if o, err := parseMCPOptions([]string{"docs", "--", "server", "--pi-extension"}); err != nil || len(o.command) != 2 {
t.Fatalf("a command argument is not a flag: %+v %v", o, err)
}
}
func TestMCPPiImportAutodetectedFileRejectsOtherFormats(t *testing.T) {
s := mcpTUIService(t)
path := filepath.Join(s.Home, "gemini.json")
if err := os.WriteFile(path, []byte(`{"mcpServers":{"a":{"httpUrl":"https://example.com/mcp"}}}`), 0600); err != nil {
t.Fatal(err)
}
o, err := parseMCPOptions([]string{"a", "--file", path, "--pi-extension", "builtin", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err = runMCPImport(s, o); err == nil || !strings.Contains(err.Error(), "detected gemini") {
t.Fatalf("non-Pi input accepted: %v", err)
}
source, err := mcp.LoadSource(s.ConfigPath)
if err != nil || source.Servers["a"].Command != "" || source.Servers["a"].URL != "" {
t.Fatalf("source changed: %+v %v", source, err)
}
}
func TestMCPPiImportSelectsModeFile(t *testing.T) {
for _, mode := range []string{"builtin", "pi-mcp-adapter", "pi-mcp-extension"} {
t.Run(mode, func(t *testing.T) {
s := mcpTUIService(t)
dir := filepath.Join(s.Home, ".pi", "agent")
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
for file, entry := range map[string]string{"mcp.json": `{"command":"native"}`, "mcp-adapter.json": `{"command":"adapter","directTools":true}`} {
if err := os.WriteFile(filepath.Join(dir, file), []byte(`{"mcpServers":{"docs":`+entry+`}}`), 0600); err != nil {
t.Fatal(err)
}
}
o, err := parseMCPOptions([]string{"docs", "--from", "pi", "--pi-extension", mode, "--target", "claude", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err := runMCPImport(s, o); err != nil {
t.Fatal(err)
}
source, err := mcp.LoadSource(s.ConfigPath)
want := "native"
if mode == "pi-mcp-adapter" {
want = "adapter"
}
if err != nil || source.Servers["docs"].Command != want || source.Servers["docs"].PiExtension != mode {
t.Fatalf("%+v %v", source, err)
}
})
}
}
func TestMCPPiPruneCanBeDisabled(t *testing.T) {
s := mcpTUIService(t)
o, err := parseMCPOptions([]string{"docs", "--target", "pi", "--pi-extension", "builtin", "--pi-options-prune", "--url", "https://example.com/mcp", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err = runMCPAdd(s, o); err != nil {
t.Fatal(err)
}
o, err = parseMCPOptions([]string{"docs", "--pi-options-prune=false", "--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"].PiOptionsPrune {
t.Fatalf("%+v %v", source, err)
}
}
func TestMCPPiImportExportedExtensionFile(t *testing.T) {
func TestMCPPiImportFile(t *testing.T) {
s := mcpTUIService(t)
path := filepath.Join(s.Home, "export.json")
if err := os.WriteFile(path, []byte(`{"mcpServers":{"docs":{"command":"docs","lifecycle":"eager"}}}`), 0600); err != nil {
if err := os.WriteFile(path, []byte(`{"mcpServers":{"a":{"command":"c","exposure":"direct"}}}`), 0600); err != nil {
t.Fatal(err)
}
o, err := parseMCPOptions([]string{"docs", "--from", "pi", "--file", path, "--pi-extension", "pi-mcp-extension", "--target", "claude", "--no-tui"})
o, err := parseMCPOptions([]string{"a", "--file", path, "--target", "claude", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err = runMCPImport(s, o); err != nil {
if err := runMCPImport(s, o); err != nil {
t.Fatal(err)
}
source, err := mcp.LoadSource(s.ConfigPath)
if err != nil || source.Servers["docs"].PiExtension != "pi-mcp-extension" || source.Servers["docs"].PiOptions != nil {
if err != nil || source.Servers["a"].PiOptions["exposure"] != "direct" || !source.Servers["a"].Tools.IsZero() {
t.Fatalf("%+v %v", source, err)
}
}
func TestMCPImportFromOtherAgentCanChoosePiMode(t *testing.T) {
// Servers written by hand into pi-mcp-adapter's file can still be imported.
func TestMCPPiImportReadsAdapterFile(t *testing.T) {
s := mcpTUIService(t)
if err := os.WriteFile(filepath.Join(s.Home, ".claude.json"), []byte(`{"mcpServers":{"docs":{"command":"docs"}}}`), 0600); err != nil {
dir := filepath.Join(s.Home, ".pi", "agent")
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
o, err := parseMCPOptions([]string{"docs", "--from", "claude", "--pi-extension", "builtin", "--target", "pi", "--no-tui"})
if err := os.WriteFile(filepath.Join(dir, "mcp-adapter.json"), []byte(`{"mcpServers":{"docs":{"command":"adapter","excludeTools":["delete_*"]}}}`), 0600); err != nil {
t.Fatal(err)
}
o, err := parseMCPOptions([]string{"docs", "--from", "pi", "--target", "claude", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err = runMCPImport(s, o); err != nil {
if err := runMCPImport(s, o); err != nil {
t.Fatal(err)
}
}
func TestMCPAddDefaultsPiToBuiltin(t *testing.T) {
for _, tc := range []struct {
name, want string
args []string
}{
{"explicit target", "builtin", []string{"--target", "pi"}},
{"inherited target", "builtin", nil},
{"chosen mode kept", "pi-mcp-adapter", []string{"--target", "pi", "--pi-extension", "pi-mcp-adapter"}},
{"no Pi", "", []string{"--target", "claude"}},
} {
t.Run(tc.name, func(t *testing.T) {
s := mcpTUIService(t)
if err := os.WriteFile(s.ConfigPath, []byte("mcp: {targets: [pi], servers: {}}\n"), 0600); err != nil {
t.Fatal(err)
}
o, err := parseMCPOptions(append([]string{"docs", "--url", "https://example.com/mcp", "--no-tui"}, tc.args...))
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 != tc.want {
t.Fatalf("%+v %v", source.Servers["docs"], err)
}
})
source, err := mcp.LoadSource(s.ConfigPath)
if err != nil || source.Servers["docs"].Command != "adapter" || !slices.Equal(source.Servers["docs"].Tools.Deny, []string{"delete_*"}) {
t.Fatalf("%+v %v", source, err)
}
if data, _ := os.ReadFile(filepath.Join(dir, "mcp-adapter.json")); !strings.Contains(string(data), `"adapter"`) {
t.Fatalf("adapter file changed: %s", data)
}
}
func TestMCPImportIntoPiDefaultsToBuiltin(t *testing.T) {
func TestMCPImportIntoPi(t *testing.T) {
s := mcpTUIService(t)
if err := os.WriteFile(filepath.Join(s.Home, ".claude.json"), []byte(`{"mcpServers":{"docs":{"command":"docs"}}}`), 0600); err != nil {
t.Fatal(err)
@@ -186,35 +87,8 @@ func TestMCPImportIntoPiDefaultsToBuiltin(t *testing.T) {
if err = runMCPImport(s, o); err != nil {
t.Fatal(err)
}
source, err := mcp.LoadSource(s.ConfigPath)
if err != nil || source.Servers["docs"].PiExtension != "builtin" {
t.Fatalf("%+v %v", source.Servers["docs"], err)
}
}
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)
if data, err := os.ReadFile(s.ConfigPath); err != nil || strings.Contains(string(data), "piExtension") {
t.Fatalf("%s %v", data, err)
}
}
@@ -222,7 +96,7 @@ 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" {
if item.label == "pi" {
return []int{i}, nil
}
}
@@ -235,16 +109,11 @@ func TestMCPPiTUI(t *testing.T) {
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")
}
}
}
func TestMCPDirectToolsFlag(t *testing.T) {
func TestMCPToolsFlags(t *testing.T) {
s := mcpTUIService(t)
run := func(handler func(*mcp.Service, mcpOptions) error, args ...string) any {
run := func(handler func(*mcp.Service, mcpOptions) error, args ...string) mcp.ToolPolicy {
t.Helper()
o, err := parseMCPOptions(append(args, "--no-tui"))
if err != nil {
@@ -257,16 +126,27 @@ func TestMCPDirectToolsFlag(t *testing.T) {
if err != nil {
t.Fatal(err)
}
return source.Servers["tools"].DirectTools
return source.Servers["tools"].Tools
}
if got := run(runMCPAdd, "tools", "--target", "pi", "--pi-extension", "pi-mcp-adapter", "--direct-tools", "true", "--url", "https://example.com/mcp"); got != true {
t.Fatalf("add: %v", got)
got := run(runMCPAdd, "tools", "--target", "pi", "--tools-allow", "search_*, get_issue", "--url", "https://example.com/mcp")
if want := (mcp.ToolPolicy{Allow: []string{"search_*", "get_issue"}}); !reflect.DeepEqual(got, want) {
t.Fatalf("add: %+v", got)
}
if got, ok := run(runMCPEdit, "tools", "--direct-tools", "search_docs,fetch").([]any); !ok || len(got) != 2 || got[1] != "fetch" {
t.Fatalf("edit to a list: %v", got)
// Each flag sets its own part; the others stay.
got = run(runMCPEdit, "tools", "--tools-deny", "delete_*")
if want := (mcp.ToolPolicy{Allow: []string{"search_*", "get_issue"}, Deny: []string{"delete_*"}}); !reflect.DeepEqual(got, want) {
t.Fatalf("edit deny: %+v", got)
}
if got := run(runMCPEdit, "tools", "--direct-tools", "search"); got != "search" {
t.Fatalf("edit to search: %v", got)
// An empty value clears that part.
if got = run(runMCPEdit, "tools", "--tools-allow", "", "--tools-deny", ""); !got.IsZero() {
t.Fatalf("clear: %+v", got)
}
o, err := parseMCPOptions([]string{"tools", "--tools-allow", "get?", "--no-tui"})
if err != nil {
t.Fatal(err)
}
if err := runMCPEdit(s, o); err == nil || !strings.Contains(err.Error(), "tools.allow") {
t.Fatalf("invalid tool name: %v", err)
}
}
@@ -287,10 +167,10 @@ func TestMCPPiOptionsFlag(t *testing.T) {
}
return source.Servers["tools"].PiOptions
}
if got := run(runMCPAdd, "tools", "--target", "pi", "--pi-extension", "pi-mcp-adapter", "--pi-options", `{"excludeTools":["*emulator*"]}`, "--url", "https://example.com/mcp"); len(got) != 1 {
if got := run(runMCPAdd, "tools", "--target", "pi", "--pi-options", `{"retries":3}`, "--url", "https://example.com/mcp"); len(got) != 1 {
t.Fatalf("add: %v", got)
}
if got := run(runMCPEdit, "tools", "--pi-options", `{"approveTools":["delete_*"]}`); len(got) != 1 || got["approveTools"] == nil {
if got := run(runMCPEdit, "tools", "--pi-options", `{"timeout":30}`); len(got) != 1 || got["timeout"] == nil {
t.Fatalf("edit replaces the options: %v", got)
}
if got := run(runMCPEdit, "tools", "--pi-options", `{}`); len(got) != 0 {
+1 -6
View File
@@ -126,12 +126,7 @@ func mcpCandidateWizard(service *mcp.Service, c mcp.Candidate, o mcpOptions) err
initial = source.Targets
}
prompts := terminalMCPPrompts{}
if o.piExtension != "" {
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
c.Server.Targets, err = chooseMCPTargets(service, []mcp.Server{c.Server}, initial, prompts)
if err != nil {
return err
}
+1 -1
View File
@@ -90,7 +90,7 @@ func TestMCPListKeysAndPrivateDetails(t *testing.T) {
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"}}
prompts := &scriptedMCPPrompts{choices: [][]int{{2}, {2}, {1}, {0}, {7}}, texts: []string{"after"}}
draft, err := editMCPDraft(s, "docs", original, []string{"claude"}, prompts)
if err != nil {
t.Fatal(err)
+72 -17
View File
@@ -11,6 +11,7 @@ import (
"skillshare/internal/backup"
"skillshare/internal/config"
"skillshare/internal/hooks"
"skillshare/internal/mcp"
"skillshare/internal/oplog"
"skillshare/internal/skillignore"
@@ -43,6 +44,7 @@ type syncJSONOutput struct {
Extras []syncExtrasJSONEntry `json:"extras,omitempty"`
ContextCost *contextCostJSON `json:"context_cost,omitempty"`
MCP *mcp.Result `json:"mcp,omitempty"`
Hooks *hooks.Result `json:"hooks,omitempty"`
}
type syncJSONTargetDetail struct {
@@ -70,6 +72,9 @@ func cmdSync(args []string) error {
if i := slices.Index(args, "mcp"); i >= 0 {
return cmdSyncMCP(slices.Delete(slices.Clone(args), i, i+1))
}
if i := slices.Index(args, "hooks"); i >= 0 {
return cmdSyncHooks(slices.Delete(slices.Clone(args), i, i+1))
}
if wantsHelp(args) {
printSyncHelp()
return nil
@@ -122,6 +127,8 @@ func cmdSync(args []string) error {
var mcpResult *mcp.Result
var mcpService *mcp.Service
var hooksResult *hooks.Result
var hooksService *hooks.Service
if hasAll {
preflightErr := func(err error) error {
if jsonOutput {
@@ -161,11 +168,25 @@ func cmdSync(args []string) error {
_ = printMCPPlan(plan, false)
return err
}
hooksService, _, err = hooksContext([]string{scope})
if err != nil {
return preflightErr(err)
}
hooksPlan, planErr := hooksService.Preview()
if planErr != nil {
return preflightErr(fmt.Errorf("hooks preflight: %w", planErr))
}
hooksResult = &hooks.Result{Plan: hooksPlan, Applied: []string{}, BackupIDs: []string{}}
if hooksPlan.Blocked {
err = fmt.Errorf("hooks conflicts found; no resources synchronized")
if jsonOutput {
return writeJSONResult(map[string]any{"error": err.Error(), "hooks": hooksResult}, err)
}
printHooksPlan(hooksPlan)
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.
@@ -175,7 +196,7 @@ func cmdSync(args []string) error {
}
return previous
}
if len(mcpResult.Plan.Changes) == 0 {
if len(mcpResult.Plan.Changes) == 0 && !mcpResult.Plan.Migrates {
return nil
}
var applyErr error
@@ -190,9 +211,41 @@ func cmdSync(args []string) error {
for _, id := range mcpResult.BackupIDs {
ui.Info("MCP backup: %s", id)
}
printMCPMigrated(mcpResult)
}
return applyErr
}
finishHooks := func(previous error) error {
if previous != nil {
hooksResult = nil
if !jsonOutput {
ui.Warning("Hooks were not applied because an earlier sync step failed")
}
return previous
}
if len(hooksResult.Plan.Changes) == 0 {
return nil
}
var applyErr error
if !dryRun {
// Resources synced after the preflight: preview again and apply that revision.
hooksResult, applyErr = applyHooksSync(hooksService, start)
}
if !jsonOutput && !quiet && hooksResult != nil {
printHooksPlan(hooksResult.Plan)
for _, id := range hooksResult.BackupIDs {
ui.Info("Hooks backup: %s", id)
}
}
return applyErr
}
// finishNative applies MCP, then hooks, only after every resource synced.
finishNative := func(previous error) error {
if !hasAll {
return previous
}
return finishHooks(finishMCP(previous))
}
prevDiagOutput := sync.DiagOutput
if jsonOutput {
@@ -222,7 +275,7 @@ func cmdSync(args []string) error {
logSyncOp(config.ProjectConfigPath(cwd), stats, start, err)
if jsonOutput {
err = finishMCP(err)
err = finishNative(err)
if hasAll {
projCfg, loadErr := config.LoadProject(cwd)
if loadErr == nil && len(projCfg.Extras) > 0 {
@@ -233,12 +286,12 @@ func cmdSync(args []string) error {
if err == nil {
err = extrasErr
}
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost, mcpResult, extrasEntries)
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost, mcpResult, hooksResult, extrasEntries)
}
}
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost, mcpResult)
return syncOutputJSON(results, dryRun, start, projIgnoreStats, err, projCtxCost, mcpResult, hooksResult)
}
err = finishMCP(err)
err = finishNative(err)
if hasAll {
// Run project extras sync after project skills sync (text mode)
if extrasErr := cmdSyncExtras(append([]string{"-p"}, rest...)); extrasErr != nil {
@@ -415,7 +468,7 @@ func cmdSync(args []string) error {
logSyncOp(config.ConfigPath(), logStats, start, syncErr)
if jsonOutput {
syncErr = finishMCP(syncErr)
syncErr = finishNative(syncErr)
var ctxCost *contextCostJSON
if analyzeErr == nil && len(analyzeEntries) > 0 {
ctxCost = buildContextCostJSON(analyzeEntries, cfg.ContextBudget)
@@ -428,9 +481,9 @@ func cmdSync(args []string) error {
if syncErr == nil {
syncErr = extrasErr
}
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost, mcpResult, extrasEntries)
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost, mcpResult, hooksResult, extrasEntries)
}
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost, mcpResult)
return syncOutputJSON(results, dryRun, start, ignoreStats, syncErr, ctxCost, mcpResult, hooksResult)
}
var extrasErr error
@@ -440,8 +493,8 @@ func cmdSync(args []string) error {
}
}
// An extras failure fails the run but, as in JSON mode, does not hold back MCP.
if err := finishMCP(syncErr); err != nil {
// An extras failure fails the run but, as in JSON mode, does not hold back MCP or hooks.
if err := finishNative(syncErr); err != nil {
return err
}
return extrasErr
@@ -572,7 +625,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, mcpResult *mcp.Result, extras ...[]syncExtrasJSONEntry) error {
func syncOutputJSON(results []syncTargetResult, dryRun bool, start time.Time, iStats *skillignore.IgnoreStats, syncErr error, ctxCost *contextCostJSON, mcpResult *mcp.Result, hooksResult *hooks.Result, extras ...[]syncExtrasJSONEntry) error {
var totals syncModeStats
var details []syncJSONTargetDetail
for _, r := range results {
@@ -613,6 +666,7 @@ func syncOutputJSON(results []syncTargetResult, dryRun bool, start time.Time, iS
}
output.ContextCost = ctxCost
output.MCP = mcpResult
output.Hooks = hooksResult
return writeJSONResult(&output, syncErr)
}
@@ -748,12 +802,12 @@ func reportCollisions(skills []sync.DiscoveredSkill, targets map[string]config.T
}
func printSyncHelp() {
fmt.Println(`Usage: skillshare sync [agents|extras|mcp|plugins] [options]
fmt.Println(`Usage: skillshare sync [agents|extras|mcp|hooks|plugins] [options]
Sync skills from source to all configured targets.
Options:
--all Sync skills, agents, extras, and MCP
--all Sync skills, agents, extras, MCP and hooks
--dry-run, -n Preview changes without applying
--force, -f Force sync (overwrite local changes)
--json Output results as JSON
@@ -766,12 +820,13 @@ 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)
hooks Sync only hooks (same as skillshare hooks sync)
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, extras, and MCP
skillshare sync --all Sync skills, agents, extras, MCP and hooks
skillshare sync -p Sync project-level skills
skillshare sync agents Sync agents only
skillshare sync plugins Apply selected plugin installations/removals
+23 -14
View File
@@ -4,7 +4,7 @@ set -e
REPO="runkids/skillshare"
BINARY_NAME="skillshare"
if [ -z "${INSTALL_DIR}" ]; then
INSTALL_DIR="/usr/local/bin"
INSTALL_DIR="$HOME/.local/bin"
fi
# Colors (if terminal supports it)
@@ -84,30 +84,39 @@ install() {
fi
# Install
mkdir -p "$INSTALL_DIR"
chmod +x "$TMP_DIR/$BINARY_NAME"
if [ -w "$INSTALL_DIR" ]; then
mv "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/"
else
warn "Need sudo to install to $INSTALL_DIR"
sudo mv "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/"
fi
chmod +x "$INSTALL_DIR/$BINARY_NAME"
}
# Verify installation
verify() {
if command -v "$BINARY_NAME" >/dev/null 2>&1; then
info ""
info "Successfully installed skillshare to $INSTALL_DIR/$BINARY_NAME"
info ""
"$BINARY_NAME" version
info ""
info "Get started:"
info " skillshare init"
info " skillshare --help"
else
warn "Installed but '$BINARY_NAME' not in PATH. Add $INSTALL_DIR to your PATH."
info ""
info "Successfully installed skillshare to $INSTALL_DIR/$BINARY_NAME"
info ""
"$INSTALL_DIR/$BINARY_NAME" version
ACTIVE_BINARY=$(command -v "$BINARY_NAME" || true)
if [ "$ACTIVE_BINARY" != "$INSTALL_DIR/$BINARY_NAME" ]; then
if [ -n "$ACTIVE_BINARY" ]; then
warn "$ACTIVE_BINARY takes precedence over the newly installed binary."
else
warn "Installed but '$BINARY_NAME' not in PATH."
fi
info "Use the new installation in this terminal:"
printf ' export PATH="%s:$PATH"\n' "$INSTALL_DIR"
info "Add that line to your shell config (e.g., ~/.zshrc or ~/.bashrc) for future terminals."
fi
info ""
info "Get started:"
info " skillshare init"
info " skillshare --help"
}
main() {
+1
View File
@@ -315,6 +315,7 @@ type GlobalSources struct {
// Config holds the application configuration
type Config struct {
Plugins yaml.Node `yaml:"plugins,omitempty"`
Hooks yaml.Node `yaml:"hooks,omitempty"`
MCP *MCPConfig `yaml:"mcp,omitempty"`
Source string `yaml:"source,omitempty"`
AgentsSource string `yaml:"agents_source,omitempty"`
+1 -8
View File
@@ -1,7 +1,6 @@
package config
import (
"bytes"
"fmt"
"slices"
@@ -119,14 +118,8 @@ func ValidateMCP(cfg *MCPConfig, external string, accounts ...string) error {
if cfg.Servers.Kind != yaml.MappingNode {
return fmt.Errorf("mcp.servers must be a mapping")
}
data, err := yaml.Marshal(cfg.Servers)
servers, err := mcp.ParseServers(cfg.Servers)
if err != nil {
return err
}
var servers map[string]mcp.Server
d := yaml.NewDecoder(bytes.NewReader(data))
d.KnownFields(true)
if err := d.Decode(&servers); err != nil {
return fmt.Errorf("invalid MCP server fields")
}
for name, server := range servers {
+16
View File
@@ -22,3 +22,19 @@ func TestPluginConfigPreservedByResourceConfig(t *testing.T) {
}
}
}
func TestHooksConfigPreservedByResourceConfig(t *testing.T) {
raw := []byte("hooks:\n entries:\n guard:\n enabled: false\n bindings:\n pi:\n code: |\n export default function (pi) {}\n")
for _, cfg := range []any{&Config{}, &ProjectConfig{}} {
if err := yaml.Unmarshal(raw, cfg); err != nil {
t.Fatal(err)
}
data, err := yaml.Marshal(cfg)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "enabled: false") || !strings.Contains(string(data), "export default function (pi) {}") {
t.Fatalf("hooks config lost: %s", data)
}
}
}
+1
View File
@@ -292,6 +292,7 @@ func ProjectDir(projectRoot string) string {
// ProjectConfig holds project-level config (<project-dir>/config.yaml).
type ProjectConfig struct {
Plugins yaml.Node `yaml:"plugins,omitempty"`
Hooks yaml.Node `yaml:"hooks,omitempty"`
MCP *MCPConfig `yaml:"mcp,omitempty"`
Sources ProjectSources `yaml:"sources,omitempty"`
Targets []ProjectTargetEntry `yaml:"targets"`
+1
View File
@@ -158,6 +158,7 @@ func TestSchemaFiles_ValidJSON(t *testing.T) {
{"schemas/config.schema.json", "Skillshare Global Configuration"},
{"schemas/project-config.schema.json", "Skillshare Project Configuration"},
{"schemas/mcp.schema.json", "Skillshare MCP Source"},
{"schemas/hooks.schema.json", "Skillshare Hooks"},
}
for _, tt := range tests {
+353
View File
@@ -0,0 +1,353 @@
package hooks
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
)
// Every command Agent receives its elements exactly as supplied: matchers and fields
// Skillshare has no setting for survive the round trip into the native file.
func TestAdapters_NativePayloadPreservedExactly(t *testing.T) {
payloads := map[string]string{
"claude": `{"PreToolUse":[{"matcher":"Bash|Edit","hooks":[{"type":"command","command":"x","timeout":5,"statusMessage":"s","async":true}]},{"hooks":[{"type":"http","url":"https://example.test/h"}]}]}`,
"codex": `{"PreToolUse":[{"matcher":"^shell$","hooks":[{"type":"command","command":"x","commandWindows":"y","additionalContextLimit":10}]}]}`,
"gemini": `{"BeforeTool":[{"matcher":"write_.*","sequential":true,"hooks":[{"type":"command","command":"x","name":"n","timeout":60000,"description":"d"}]}]}`,
"qwen": `{"PreToolUse":[{"matcher":"Shell","sequential":false,"hooks":[{"type":"command","command":"x","env":{"A":"1"},"shell":"bash"}]}]}`,
"droid": `{"PreToolUse":[{"matcher":"Execute","commandRegex":"^git ","hooks":[{"type":"command","command":"x","timeout":60}]}]}`,
"cursor": `{"beforeShellExecution":[{"command":"x","matcher":"git","timeout":10,"loop_limit":3,"failClosed":true}]}`,
"copilot": `{"preToolUse":[{"bash":"x","powershell":"y","matcher":"bash","cwd":"scripts","env":{"A":"1"},"timeoutSec":30}]}`,
}
for target, raw := range payloads {
t.Run(target, func(t *testing.T) {
e := newEnv(t)
var events map[string]any
must(t, json.Unmarshal([]byte(raw), &events))
save(t, e.service, Mutation{Name: "demo", Entry: &Entry{Bindings: map[string]Binding{target: {Events: events}}}})
var got map[string]any
switch target {
case "copilot":
var doc struct {
Hooks map[string]any `json:"hooks"`
}
must(t, json.Unmarshal([]byte(read(t, filepath.Join(e.home, ".copilot", "hooks", "skillshare-demo.json"))), &doc))
got = doc.Hooks
default:
path := e.service.Paths()[target]
got = map[string]any{}
for event, items := range readEvents(t, path, target != "droid") {
got[event] = items
}
}
if !reflect.DeepEqual(got, events) {
t.Fatalf("payload changed:\nwant %v\ngot %v", events, got)
}
})
}
}
func readEvents(t *testing.T, path string, wrapped bool) map[string]any {
out := map[string]any{}
for event, items := range events(t, path, wrapped) {
out[event] = items
}
return out
}
// Copilot handlers are flat and take bash, powershell, command, or exec with args,
// with type optional; http and prompt handlers need no command.
func TestCopilot_OfficialHandlerShapesAccepted(t *testing.T) {
valid := []string{
`{"bash":"x"}`,
`{"type":"command","powershell":"x"}`,
`{"command":"x","timeoutSec":5}`,
`{"exec":"node","args":["hook.js"]}`,
`{"type":"http","url":"https://example.test/hook"}`,
`{"bash":"x","matcher":"bash"}`,
`{"bash":"x","powershell":"y","command":"z"}`,
}
for _, handler := range valid {
doc := `{"bindings":{"copilot":{"events":{"preToolUse":[` + handler + `]}}}}`
if _, err := ParseEntry([]byte(doc)); err != nil {
t.Errorf("%s rejected: %v", handler, err)
}
}
for _, handler := range []string{
`{"type":"command"}`, `{"type":"script","bash":"x"}`, `{"args":["x"]}`,
`{"exec":"node","bash":"x"}`, `{"exec":"node","command":"x"}`, `{"bash":"x","args":["y"]}`,
`{"exec":"node","args":"hook.js"}`, `{"type":"http"}`, `{"type":"http","url":"ftp://x"}`,
`{"type":"http","url":"http://example.test"}`, `{"type":"prompt"}`, `{"bash":"x","timeoutSec":-1}`,
} {
doc := `{"bindings":{"copilot":{"events":{"preToolUse":[` + handler + `]}}}}`
if _, err := ParseEntry([]byte(doc)); err == nil {
t.Errorf("%s accepted", handler)
}
}
// Prompt hooks are sessionStart only; plain http is allowed outside the
// permission-granting events.
for doc, ok := range map[string]bool{
`{"bindings":{"copilot":{"events":{"sessionStart":[{"type":"prompt","prompt":"/status"}]}}}}`: true,
`{"bindings":{"copilot":{"events":{"preToolUse":[{"type":"prompt","prompt":"x"}]}}}}`: false,
`{"bindings":{"copilot":{"events":{"postToolUse":[{"type":"http","url":"http://localhost:8080/h"}]}}}}`: true,
`{"bindings":{"copilot":{"events":{"postToolUse":[{"type":"http","url":"http://h.test","allowedEnvVars":["TOKEN"]}]}}}}`: false,
} {
if _, err := ParseEntry([]byte(doc)); (err == nil) != ok {
t.Errorf("%s: accepted=%v, want %v (%v)", doc, err == nil, ok, err)
}
}
// PascalCase is Copilot's VS Code compatible form and stays as written.
if _, err := ParseEntry([]byte(`{"bindings":{"copilot":{"events":{"PreToolUse":[{"bash":"x"}]}}}}`)); err != nil {
t.Fatalf("PascalCase Copilot event rejected: %v", err)
}
}
// A user's identical copy inserted before or after Skillshare's makes identity ambiguous:
// the nearest old index would pick the user's copy, so update, disable and remove all
// conflict and never touch the file; replace releases ownership without writing.
func TestLedger_IdenticalCopyInsertedBeforeOrAfterIsAmbiguous(t *testing.T) {
group := `{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard","timeout":5}]}`
for name, layout := range map[string]string{
"before": `{"hooks":{"PreToolUse":[` + group + `,` + group + `]}}`,
"after": `{"hooks":{"PreToolUse":[` + group + `,{"hooks":[{"type":"command","command":"echo other"}]},` + group + `]}}`,
} {
t.Run(name, func(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)}) // owned at index 0
write(t, path, layout)
off := *entry(t, claudeEntry)
disabled := false
off.Enabled = &disabled
for label, m := range map[string]Mutation{
"disable": {Name: "guard", Entry: &off},
"remove": {Name: "guard", Remove: true},
"update": {Name: "guard", Entry: entry(t, strings.Replace(claudeEntry, "echo guard", "echo v2", 1))},
} {
p, err := e.service.PreviewMutation(m)
must(t, err)
if !p.Blocked {
t.Fatalf("%s: ambiguous identical copies must conflict: %s", label, actions(p))
}
if _, err := e.service.Mutate(m, p.Revision, true); !errors.Is(err, ErrConflict) {
t.Fatalf("%s: want ErrConflict, got %v", label, err)
}
}
if read(t, path) != layout {
t.Fatal("a refused sync must leave the file byte for byte")
}
inv, err := e.service.List()
must(t, err)
if inv.Unmanaged[0].Names[0] != "PreToolUse" {
t.Fatalf("ambiguous copies are not claimed as owned: %+v", inv.Unmanaged)
}
save(t, e.service, Mutation{Name: "guard", Remove: true, Replace: true})
if read(t, path) != layout {
t.Fatal("release must not write")
}
})
}
}
// Identical copies all owned by records stay resolvable, and removing one leaves the other.
func TestLedger_OwnedIdenticalCopiesResolve(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
two := `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"x"}]},{"hooks":[{"type":"command","command":"x"}]}]}}}}`
save(t, e.service, Mutation{Name: "a", Entry: entry(t, two)})
save(t, e.service, Mutation{Name: "b", Entry: entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]}}}}`)})
if n := len(events(t, path, true)["Stop"]); n != 3 {
t.Fatalf("three owned copies expected, got %d", n)
}
save(t, e.service, Mutation{Name: "a", Remove: true})
if n := len(events(t, path, true)["Stop"]); n != 1 {
t.Fatalf("b's copy must remain: %d", n)
}
p, err := e.service.Preview()
must(t, err)
if p.Blocked || actions(p) != "claude:b:unchanged" {
t.Fatalf("remaining copy stays owned: %s", actions(p))
}
}
// Reordering keeps ownership: the owned element is found by record and content,
// not by its old index.
func TestLedger_ReorderedElementsKeepOwnership(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, `{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo mine"}]}]}}`)
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
var doc map[string]map[string][]any
must(t, json.Unmarshal([]byte(read(t, path)), &doc))
items := doc["hooks"]["PreToolUse"]
items[0], items[1] = items[1], items[0]
data, _ := json.Marshal(doc)
write(t, path, string(data))
save(t, e.service, Mutation{Name: "guard", Remove: true})
got := events(t, path, true)["PreToolUse"]
if len(got) != 1 || !strings.Contains(mustJSON(got[0]), "echo mine") {
t.Fatalf("remove after reorder must prune only the owned group: %v", got)
}
}
func mustJSON(v any) string {
data, _ := json.Marshal(v)
return string(data)
}
// A nonempty revision guards a source-only save exactly like a sync.
func TestMutate_SourceOnlySaveWithRevisionRejectsDrift(t *testing.T) {
for name, drift := range map[string]func(e *env){
"native hooks": func(e *env) {
write(t, filepath.Join(e.home, ".claude", "settings.json"), `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]}}`)
},
"config": func(e *env) { write(t, e.config, "targets: {}\n# edited\n") },
"ownership": func(e *env) { write(t, e.service.statePath(), `{"version":1,"records":{}}`+"\n") },
} {
t.Run(name, func(t *testing.T) {
e := newEnv(t)
m := Mutation{Name: "guard", Entry: entry(t, claudeEntry)}
p, err := e.service.PreviewMutation(m)
must(t, err)
drift(e)
if _, err := e.service.Mutate(m, p.Revision, false); !errors.Is(err, ErrStaleRevision) {
t.Fatalf("want ErrStaleRevision, got %v", err)
}
if source, _ := LoadSource(e.config); source != nil && len(source.Entries) != 0 {
t.Fatal("a stale save must not write the source")
}
})
}
}
// A symlinked Agent folder inside a project would send writes outside the project.
func TestSync_ProjectAncestorSymlinkRejected(t *testing.T) {
e := newEnv(t)
root := filepath.Join(filepath.Dir(e.home), "repo")
project := e.project(root)
outside := filepath.Join(filepath.Dir(e.home), "outside")
must(t, os.MkdirAll(outside, 0755))
must(t, os.Symlink(outside, filepath.Join(root, ".pi")))
_, err := project.PreviewMutation(Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"pi":`+adapterEntry["pi"]+`}}`)})
if err == nil || !strings.Contains(err.Error(), "symlink") {
t.Fatalf("want symlink refusal, got %v", err)
}
if entries, _ := os.ReadDir(outside); len(entries) != 0 {
t.Fatal("nothing may be written outside the project")
}
}
// A crash after the journal but before the native write leaves ownership untouched.
func TestRecovery_InterruptedBeforeWriteKeepsOwnership(t *testing.T) {
e := newEnv(t)
m := Mutation{Name: "guard", Entry: entry(t, claudeEntry)}
source, replace, adopt, err := e.service.draft(m)
must(t, err)
must(t, source.save())
p, err := e.service.previewSource(source, replace, adopt)
must(t, err)
f := p.files[0]
must(t, writeJSONFile(e.service.journalPath(), journal{Path: f.path, After: digest(f.after), State: p.state}))
plan, err := e.service.Preview()
must(t, err)
if !strings.Contains(actions(plan), "claude:guard:add") {
t.Fatalf("an unwritten file must still be pending: %s", actions(plan))
}
sync(t, e.service)
if exists(e.service.journalPath()) || len(events(t, f.path, true)["PreToolUse"]) != 1 {
t.Fatal("recovery then sync must write exactly once")
}
}
// Droid reads settings.json hooks only while hooks.json is absent. Those hooks are what
// Droid runs, so import offers them, the conflict says how to resolve it, and inventory
// lists them only while they are active.
func TestDroid_InlineHooksImportResolveFlow(t *testing.T) {
e := newEnv(t)
settings := filepath.Join(e.home, ".factory", "settings.json")
write(t, settings, `{"model":"x","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo inline"}]}]}}`)
candidates, err := e.service.Import(ImportRequest{From: "droid", Name: "inline"})
must(t, err)
if len(candidates) != 1 || candidates[0].Entry.Bindings["droid"].Events["Stop"] == nil || len(candidates[0].Warnings) == 0 {
t.Fatalf("import must offer the active settings.json hooks with guidance: %+v", candidates)
}
m := Mutation{Name: "inline", Entry: &candidates[0].Entry}
p, err := e.service.PreviewMutation(m)
must(t, err)
if !p.Blocked || !strings.Contains(p.Changes[0].Message, settings) {
t.Fatalf("conflict must name the settings file to clean up: %+v", p.Changes)
}
// Save the definition, then the user removes the inline hooks and syncs.
_, err = e.service.Mutate(m, p.Revision, false)
must(t, err)
write(t, settings, `{"model":"x"}`)
sync(t, e.service)
if n := len(events(t, filepath.Join(e.home, ".factory", "hooks.json"), false)["Stop"]); n != 1 {
t.Fatalf("hooks.json must hold the imported hook: %d", n)
}
// With hooks.json present, settings.json hooks are inert and not listed as active.
write(t, settings, `{"model":"x","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo ignored"}]}]}}`)
inv, err := e.service.List()
must(t, err)
for _, u := range inv.Unmanaged {
if u.Path == settings {
t.Fatalf("Droid ignores settings.json hooks while hooks.json exists: %+v", u)
}
}
// The legacy .factory/hooks/hooks.json still loads and is disclosed.
legacy := filepath.Join(e.home, ".factory", "hooks", "hooks.json")
write(t, legacy, `{"SessionStart":[{"hooks":[{"type":"command","command":"echo legacy"}]}]}`)
inv, err = e.service.List()
must(t, err)
found := false
for _, u := range inv.Unmanaged {
found = found || u.Path == legacy && strings.Join(u.Names, ",") == "SessionStart"
}
if !found {
t.Fatalf("legacy Droid hooks file must be disclosed: %+v", inv.Unmanaged)
}
// Pasted settings.json content, with its hooks wrapper, imports too.
c, err := e.service.Import(ImportRequest{From: "droid", Content: `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]}}`})
must(t, err)
if len(c) != 1 || c[0].Entry.Bindings["droid"].Events["Stop"] == nil {
t.Fatalf("wrapped Droid content: %+v", c)
}
}
// Restore validates the whole path, not only the leaf: a parent folder swapped for a
// symlink is refused whether the file there still exists or has to be recreated.
func TestRestore_SymlinkedParentRefusedForExistingAndMissingLeaf(t *testing.T) {
for _, leaf := range []string{"existing", "missing"} {
t.Run(leaf, func(t *testing.T) {
e := newEnv(t)
m := Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"pi":`+adapterEntry["pi"]+`}}`)}
r := save(t, e.service, m)
if leaf == "missing" {
r = save(t, e.service, Mutation{Name: "demo", Remove: true}) // restoring recreates the file
}
dir := filepath.Join(e.home, ".pi", "agent", "extensions")
outside := filepath.Join(e.home, "outside")
must(t, os.MkdirAll(outside, 0755))
if leaf == "existing" {
must(t, os.Rename(filepath.Join(dir, "skillshare-demo.ts"), filepath.Join(outside, "skillshare-demo.ts")))
}
must(t, os.RemoveAll(dir))
must(t, os.MkdirAll(filepath.Dir(dir), 0755)) // removal pruned the folders it created
must(t, os.Symlink(outside, dir))
before, _ := os.ReadDir(outside)
if _, err := e.service.PreviewRestore(r.BackupIDs[0]); err == nil || !strings.Contains(err.Error(), "symlink") {
t.Fatalf("preview restore: want symlink refusal, got %v", err)
}
if _, err := e.service.Restore(r.BackupIDs[0], ""); err == nil {
t.Fatal("restore must refuse")
}
after, _ := os.ReadDir(outside)
if len(after) != len(before) {
t.Fatal("nothing may be written through the symlink")
}
})
}
}
+176
View File
@@ -0,0 +1,176 @@
package hooks
import (
"encoding/json"
"path/filepath"
"slices"
"strings"
"testing"
)
// adapterEntry is one valid binding per Agent, in that Agent's own native shape.
var adapterEntry = map[string]string{
"claude": `{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo claude","timeout":5}]}]}}`,
"codex": `{"events":{"PreToolUse":[{"matcher":"shell","hooks":[{"type":"command","command":"echo codex","timeout":5}]}]}}`,
"gemini": `{"events":{"BeforeTool":[{"matcher":"run_shell_command","hooks":[{"type":"command","command":"echo gemini","timeout":5000}]}]}}`,
"qwen": `{"events":{"PreToolUse":[{"matcher":"Shell","hooks":[{"type":"command","command":"echo qwen"}]}]}}`,
"droid": `{"events":{"PreToolUse":[{"matcher":"Execute","hooks":[{"type":"command","command":"echo droid"}]}]}}`,
"cursor": `{"events":{"beforeShellExecution":[{"command":"./hooks/skillshare/demo/guard.sh"}]},"files":{"guard.sh":"#!/bin/sh\necho cursor\n"}}`,
"copilot": `{"events":{"preToolUse":[{"type":"command","bash":"echo copilot","timeoutSec":10}]}}`,
"antigravity": `{"events":{"PreToolUse":[{"matcher":"run_command","hooks":[{"type":"command","command":"echo agy","timeout":10}]}],"Stop":[{"command":"echo stop"}]}}`,
"pi": `{"code":"export default function (pi) {\n pi.on(\"tool_call\", async () => {});\n}\n"}`,
"amp": `{"code":"export default function (amp) {\n amp.on(\"tool.call\", async () => ({ action: \"allow\" }));\n}\n"}`,
"opencode": `{"code":"export const Demo = async () => ({\n \"tool.execute.before\": async () => {},\n})\n"}`,
}
func TestAdapters_GlobalPathsAndNativeShape(t *testing.T) {
want := map[string]string{
"claude": ".claude/settings.json", "codex": ".codex/hooks.json", "gemini": ".gemini/settings.json",
"qwen": ".qwen/settings.json", "droid": ".factory/hooks.json", "cursor": ".cursor/hooks.json",
"copilot": ".copilot/hooks/skillshare-demo.json", "pi": ".pi/agent/extensions/skillshare-demo.ts",
"amp": ".config/amp/plugins/skillshare-demo.ts", "opencode": ".config/opencode/plugins/skillshare-demo.ts",
"antigravity": ".gemini/config/hooks.json",
}
for target, binding := range adapterEntry {
t.Run(target, func(t *testing.T) {
e := newEnv(t)
save(t, e.service, Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"`+target+`":`+binding+`}}`)})
path := filepath.Join(e.home, want[target])
content := read(t, path)
var b Binding
must(t, json.Unmarshal([]byte(binding), &b))
switch target {
case "pi", "amp", "opencode":
if content != b.Code {
t.Fatalf("code must be written verbatim, got %q", content)
}
case "antigravity":
var doc map[string]map[string]any
must(t, json.Unmarshal([]byte(content), &doc))
if len(doc) != 1 || doc["demo"]["PreToolUse"] == nil || doc["demo"]["Stop"] == nil {
t.Fatalf("antigravity writes one block named after the hook: %s", content)
}
case "copilot":
var doc map[string]any
must(t, json.Unmarshal([]byte(content), &doc))
if doc["version"] != float64(1) || doc["hooks"].(map[string]any)["preToolUse"] == nil {
t.Fatalf("copilot file: %s", content)
}
default:
got := events(t, path, target != "droid")
for event := range b.Events {
if len(got[event]) != 1 {
t.Fatalf("%s missing %s: %s", path, event, content)
}
}
if target == "cursor" && !strings.Contains(content, `"version": 1`) {
t.Fatalf("cursor hooks.json needs version 1: %s", content)
}
}
if target == "cursor" {
script := filepath.Join(e.home, ".cursor", "hooks", "skillshare", "demo", "guard.sh")
if read(t, script) != "#!/bin/sh\necho cursor\n" {
t.Fatal("script file not written")
}
}
p, err := e.service.Preview()
must(t, err)
for _, c := range p.Changes {
if c.Action != "unchanged" {
t.Fatalf("second sync must be idempotent: %s", actions(p))
}
}
})
}
}
func TestAdapters_ProjectPathsNeverFallBackToGlobal(t *testing.T) {
want := map[string]string{
"claude": ".claude/settings.json", "codex": ".codex/hooks.json", "gemini": ".gemini/settings.json",
"qwen": ".qwen/settings.json", "droid": ".factory/hooks.json", "cursor": ".cursor/hooks.json",
"copilot": ".github/hooks/skillshare-demo.json", "pi": ".pi/extensions/skillshare-demo.ts",
"amp": ".amp/plugins/skillshare-demo.ts", "opencode": ".opencode/plugins/skillshare-demo.ts",
"antigravity": ".agents/hooks.json",
}
e := newEnv(t)
root := filepath.Join(filepath.Dir(e.home), "repo")
project := e.project(root)
project.ConfigDirs = map[string]string{"claude": filepath.Join(e.home, "elsewhere"), "xdg": filepath.Join(e.home, "xdg")}
var bindings []string
for target, binding := range adapterEntry {
bindings = append(bindings, `"`+target+`":`+binding)
}
save(t, project, Mutation{Name: "demo", Entry: entry(t, `{"bindings":{`+strings.Join(bindings, ",")+`}}`)})
for target, rel := range want {
if !exists(filepath.Join(root, rel)) {
t.Errorf("%s: %s not written", target, rel)
}
}
if exists(filepath.Join(e.home, ".claude")) || exists(filepath.Join(e.home, "elsewhere")) {
t.Fatal("project sync wrote a global path")
}
}
func TestAdapters_ConfigDirOverrides(t *testing.T) {
e := newEnv(t)
dir := filepath.Join(e.home, "custom-claude")
e.service.ConfigDirs = map[string]string{"claude": dir, "pi": filepath.Join(e.home, "pi-home"), "xdg": filepath.Join(e.home, "xdg")}
paths := e.service.Paths()
if paths["claude"] != filepath.Join(dir, "settings.json") || paths["pi"] != filepath.Join(e.home, "pi-home", "extensions") || paths["opencode"] != filepath.Join(e.home, "xdg", "opencode", "plugins") {
t.Fatalf("overrides ignored: %v", paths)
}
}
func TestParseEntry_ValidatesNativeShape(t *testing.T) {
bad := map[string]string{
"unknown agent": `{"bindings":{"kiro":{"events":{}}}}`,
"code on command": `{"bindings":{"claude":{"code":"x"}}}`,
"events on code": `{"bindings":{"pi":{"events":{"x":[]}}}}`,
"missing hooks array": `{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash"}]}}}}`,
"cursor pascal case": `{"bindings":{"cursor":{"events":{"BeforeShellExecution":[{"command":"x"}]}}}}`,
"copilot no command": `{"bindings":{"copilot":{"events":{"preToolUse":[{"type":"command"}]}}}}`,
"traversal file": `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]},"files":{"../x.sh":"x"}}}}`,
"nested file": `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]},"files":{"a/x.sh":"x"}}}}`,
"unknown field": `{"bindings":{},"runtime":"node"}`,
"negative timeout": `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"x","timeout":-1}]}]}}}}`,
"alias and canonical": `{"bindings":{"droid":` + adapterEntry["droid"] + `,"factory":` + adapterEntry["droid"] + `}}`,
"empty event array": `{"bindings":{"claude":{"events":{"Stop":[]}}}}`,
"code agent no code": `{"bindings":{"amp":{}}}`,
"yaml unknown binding": "bindings:\n claude:\n command: echo\n",
}
for name, doc := range bad {
if _, err := ParseEntry([]byte(doc)); err == nil {
t.Errorf("%s: accepted %s", name, doc)
}
}
e, err := ParseEntry([]byte("bindings:\n factory:\n events:\n Stop:\n - hooks:\n - type: command\n command: echo hi\n timeout: 5\n"))
must(t, err)
if _, ok := e.Bindings["droid"]; !ok {
t.Fatal("factory alias must resolve to droid")
}
if e.Bindings["droid"].Events["Stop"].([]any)[0].(map[string]any)["hooks"].([]any)[0].(map[string]any)["timeout"] != float64(5) {
t.Fatal("YAML events must take their JSON shape")
}
}
func TestCopilotFileChangesNameTheirEvents(t *testing.T) {
e := newEnv(t)
start := `{"bindings":{"copilot":{"events":{"sessionStart":[{"type":"command","bash":"echo a"}]}}}}`
p, err := e.service.PreviewMutation(Mutation{Name: "demo", Entry: entry(t, start)})
must(t, err)
if len(p.Changes) != 1 || p.Changes[0].Events == nil || !slices.Equal(p.Changes[0].Events.Added, []string{"sessionStart"}) {
t.Fatalf("add: %+v", p.Changes)
}
save(t, e.service, Mutation{Name: "demo", Entry: entry(t, start)})
next := `{"bindings":{"copilot":{"events":{"sessionStart":[{"type":"command","bash":"echo b"}],"preToolUse":[{"type":"command","bash":"echo c"}]}}}}`
p, err = e.service.PreviewMutation(Mutation{Name: "demo", Entry: entry(t, next)})
must(t, err)
if ev := p.Changes[0].Events; ev == nil || !slices.Equal(ev.Added, []string{"preToolUse"}) || !slices.Equal(ev.Updated, []string{"sessionStart"}) {
t.Fatalf("update: %+v", p.Changes[0].Events)
}
p, err = e.service.PreviewMutation(Mutation{Name: "demo", Remove: true})
must(t, err)
if ev := p.Changes[0].Events; p.Changes[0].Action != "remove" || ev == nil || !slices.Equal(ev.Removed, []string{"sessionStart"}) {
t.Fatalf("remove: %+v", p.Changes[0])
}
}
+73
View File
@@ -0,0 +1,73 @@
package hooks
import (
"path/filepath"
"strings"
"testing"
)
const agyNative = `{"lint":{"PostToolUse":[{"matcher":"run_command","hooks":[{"command":"./lint.sh","timeout":10}]}]},"off":{"enabled":false,"Stop":[{"command":"echo off"}]},"mine":{"Stop":[{"command":"echo mine"}]}}`
func TestAntigravity_ImportTakesOverNamedBlockInPlace(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".gemini", "config", "hooks.json")
write(t, path, agyNative)
candidates, err := e.service.Import(ImportRequest{From: "agy"})
must(t, err)
got := map[string]int{}
for _, c := range candidates {
got[c.Name] = len(c.Problems)
}
if len(got) != 3 || got["lint"] != 0 || got["off"] != 1 {
t.Fatalf("one candidate per block, disabled blocks blocked: %+v", candidates)
}
c := importOne(t, e.service, "antigravity-cli", "lint")
m := Mutation{Name: "lint", Entry: &c.Entry, Adopt: true}
p, err := e.service.PreviewMutation(m)
must(t, err)
if p.Blocked || actions(p) != "antigravity:lint:adopt" {
t.Fatalf("import preview: %s", actions(p))
}
save(t, e.service, m)
if read(t, path) != agyNative {
t.Fatalf("taking over a block must not rewrite the file:\n%s", read(t, path))
}
save(t, e.service, Mutation{Name: "lint", Remove: true})
if got := read(t, path); strings.Contains(got, `"lint"`) || !strings.Contains(got, `"mine"`) || !strings.Contains(got, `"enabled":false`) {
t.Fatalf("remove prunes only the owned block:\n%s", got)
}
}
func TestAntigravity_ImportUnderAnotherNameIsAConflict(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".gemini", "config", "hooks.json")
write(t, path, agyNative)
c := importOne(t, e.service, "agy", "lint")
p, err := e.service.PreviewMutation(Mutation{Name: "renamed", Entry: &c.Entry, Adopt: true})
must(t, err)
if !p.Blocked || actions(p) != "antigravity:renamed:conflict" {
t.Fatalf("a renamed takeover would leave the original block running beside a copy: %s", actions(p))
}
}
func TestAntigravity_SameNamedUnmanagedBlockIsAConflict(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".gemini", "config", "hooks.json")
write(t, path, agyNative)
m := Mutation{Name: "mine", Entry: entry(t, `{"bindings":{"antigravity":{"events":{"Stop":[{"command":"echo other"}]}}}}`)}
p, err := e.service.PreviewMutation(m)
must(t, err)
if !p.Blocked {
t.Fatalf("a different block with the same name is a conflict: %s", actions(p))
}
m.Replace = true
p, err = e.service.PreviewMutation(m)
must(t, err)
if c := p.Changes[0]; c.Action != "update" || strings.Join(c.Events.Updated, ",") != "Stop" {
t.Fatalf("replace takes the block over: %+v %+v", c, c.Events)
}
save(t, e.service, m)
if got := read(t, path); strings.Count(got, `"mine"`) != 1 || !strings.Contains(got, "echo other") {
t.Fatalf("the block is replaced in place:\n%s", got)
}
}
+830
View File
@@ -0,0 +1,830 @@
package hooks
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
// keepBackups bounds the backups kept per native file; every write adds one.
const keepBackups = 20
var backupID = regexp.MustCompile(`^[0-9]+-[a-f0-9]{8}$`)
// ErrUnknownProject is returned for a root hooks.projects does not declare.
var ErrUnknownProject = errors.New("unknown hooks project")
type journal struct {
Path string `json:"path"`
After string `json:"after"` // digest of the written file, "" for a removal
State ledger `json:"state"`
}
type backupRecord struct {
ID string `json:"id"`
Owner string `json:"owner"`
Target string `json:"target"`
Path string `json:"path"`
Root string `json:"root,omitempty"`
Kind string `json:"kind"`
// Ops are the element edits of a shared file, with the values before and after.
Ops []elementOp `json:"ops,omitempty"`
// Before and After are a whole file's contents; nil means absent.
Before *string `json:"before,omitempty"`
After *string `json:"after,omitempty"`
// Ownership of the moved records before and after the write; nil means none.
OwnedBefore map[string]*record `json:"ownedBefore"`
OwnedAfter map[string]*record `json:"ownedAfter"`
}
func atomicWrite(path string, data []byte, mode os.FileMode) error {
if _, _, _, err := safeRead(path); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
file, err := os.CreateTemp(filepath.Dir(path), ".hooks-write-*")
if err != nil {
return err
}
defer os.Remove(file.Name())
if err = file.Chmod(mode); err == nil {
_, err = file.Write(data)
}
if err == nil {
err = file.Sync()
}
closeErr := file.Close()
if err != nil {
return err
}
if closeErr != nil {
return closeErr
}
return os.Rename(file.Name(), path)
}
func writeJSONFile(path string, value any) error {
data, err := json.MarshalIndent(value, "", " ")
if err != nil {
return err
}
return atomicWrite(path, append(data, '\n'), 0600)
}
func (s *Service) journalPath() string { return filepath.Join(s.stateDir(), "pending.json") }
// readPending returns an interrupted write's journal and whether its native file was
// written, in which case recovery records the journal's ownership.
func (s *Service) readPending() (*journal, bool, error) {
data, exists, _, err := safeRead(s.journalPath())
if err != nil || !exists {
return nil, false, err
}
var pending journal
if json.Unmarshal(data, &pending) != nil || pending.Path == "" || pending.State.Version != 1 || pending.State.Records == nil {
return nil, false, fmt.Errorf("hooks recovery journal is invalid; manual recovery required")
}
current, exists, _, err := safeRead(pending.Path)
if err != nil {
return nil, false, err
}
if pending.After == "" {
return &pending, !exists, nil
}
return &pending, exists && digest(current) == pending.After, nil
}
func (s *Service) recoverPending() error {
pending, written, err := s.readPending()
if err != nil || pending == nil {
return err
}
if written {
if err := writeJSONFile(s.statePath(), pending.State); err != nil {
return err
}
}
// Otherwise the write did not happen, or the file changed again; ownership hashes
// flag any output that no longer matches, so the journal is obsolete.
return os.Remove(s.journalPath())
}
// draft applies a mutation to a fresh source and returns the entries it may replace
// and the entries that adopt their identical unmanaged registrations.
func (s *Service) draft(m Mutation) (*Source, map[string]bool, map[string]bool, error) {
source, err := LoadSource(s.ConfigPath)
if err != nil {
return nil, nil, nil, err
}
if m.Adopt && (m.Entry == nil || m.Name == "") {
return nil, nil, nil, fmt.Errorf("adopt takes a hook name and entry")
}
if m.Entry != nil && m.Remove {
return nil, nil, nil, fmt.Errorf("cannot save and remove the same hook")
}
if m.Unmanage && (!m.Remove || m.Name == "") {
return nil, nil, nil, fmt.Errorf("stop managing applies only to removing a named hook")
}
if (m.Entry != nil || m.Remove || m.Replace) && m.Name == "" && m.Project == "" {
return nil, nil, nil, fmt.Errorf("hook name is required")
}
root := ""
entries := source.Entries
if m.Project != "" {
if s.ProjectRoot != "" {
return nil, nil, nil, fmt.Errorf("hooks.projects belongs in the global config")
}
if root, err = projectRoot(m.Project); err != nil {
return nil, nil, nil, err
}
project, exists := source.Projects[root]
if _, known := source.projectKeys[root]; !known {
source.projectKeys[root] = m.Project
}
switch {
case m.Remove && m.Name == "":
if !exists {
return nil, nil, nil, fmt.Errorf("%w: %s", ErrUnknownProject, m.Project)
}
delete(source.Projects, root)
source.touchedProjects[root] = true
return source, nil, nil, nil
case m.Name == "" && m.Entry == nil:
if !exists {
source.Projects[root] = Project{Entries: map[string]Entry{}}
source.touchedProjects[root] = true
}
return source, nil, nil, nil
}
if project.Entries == nil {
project.Entries = map[string]Entry{}
}
source.Projects[root] = project
entries = project.Entries
source.touchedProjects[root] = true
}
replace, adopt := map[string]bool{}, map[string]bool{}
if m.Replace {
replace[root+"\x00"+m.Name] = true
}
if m.Adopt {
adopt[root+"\x00"+m.Name] = true
}
switch {
case m.Remove:
if _, ok := entries[m.Name]; !ok {
return nil, nil, nil, fmt.Errorf("hook %q not found", m.Name)
}
delete(entries, m.Name)
if m.Unmanage {
source.unmanaged[root+"\x00"+m.Name] = true
}
case m.Entry != nil:
entry := *m.Entry
if err := entry.normalize(); err != nil {
return nil, nil, nil, err
}
if err := entry.Validate(m.Name); err != nil {
return nil, nil, nil, err
}
entries[m.Name] = entry
}
if m.Project == "" && (m.Remove || m.Entry != nil) {
source.touched[m.Name] = true
}
return source, replace, adopt, nil
}
// PreviewMutation does not persist a draft or claim ownership.
func (s *Service) PreviewMutation(m Mutation) (*Plan, error) {
source, replace, adopt, err := s.draft(m)
if err != nil {
return nil, err
}
return s.previewSource(source, replace, adopt)
}
// Mutate validates before saving. With sync, it refuses to save when native outputs
// conflict, then saves the source and applies the plan. Without sync, it saves the
// source only, even when native sync would be blocked.
func (s *Service) Mutate(m Mutation, revision string, sync bool) (*Result, error) {
if m.Unmanage && sync {
return nil, fmt.Errorf("stop managing keeps target files as they are, so it cannot be combined with sync")
}
lock, err := s.lock()
if err != nil {
return nil, err
}
defer lock.Unlock()
if err := s.recoverPending(); err != nil {
return nil, err
}
source, replace, adopt, err := s.draft(m)
if err != nil {
return nil, err
}
if !sync && revision == "" && !m.Adopt {
// Saving the source alone needs only definitions every scope can render; a
// blocked or unreadable native file must not stop it.
if _, err := s.render(source); err != nil {
return nil, err
}
if err := source.save(); err != nil {
return nil, err
}
if err := s.forgetUnmanaged(source); err != nil {
return nil, err
}
return &Result{Applied: []string{}, BackupIDs: []string{}}, nil
}
p, err := s.previewSource(source, replace, adopt)
if err != nil {
return nil, err
}
if revision != "" && revision != p.Revision {
return nil, ErrStaleRevision
}
// A project mutation syncs only its own root; pending global or other-project
// changes, and their conflicts, wait for their own sync.
var scope *string
if m.Project != "" {
root, err := projectRoot(m.Project)
if err != nil {
return nil, err
}
scope = &root
}
if sync && p.blockedIn(scope) {
return &Result{Plan: p, Applied: []string{}, BackupIDs: []string{}}, ErrConflict
}
if err := source.save(); err != nil {
return nil, err
}
if !sync {
if err := s.recordAdopted(p); err != nil {
return nil, fmt.Errorf("source saved; recording the imported registrations failed: %w", err)
}
if err := s.forgetUnmanaged(source); err != nil {
return nil, err
}
return &Result{Plan: p, Applied: []string{}, BackupIDs: []string{}}, nil
}
// The plan was computed from the draft, which is now the saved source.
result, err := s.applyScoped(p, scope)
if err != nil && len(source.touched)+len(source.touchedProjects) > 0 {
return result, fmt.Errorf("source saved; synchronization incomplete: %w", err)
}
return result, err
}
// recordAdopted claims the registrations an import adopts without syncing, so the
// next sync adopts them in place instead of reporting a conflict.
func (s *Service) recordAdopted(p *Plan) error {
if len(p.adopted) == 0 {
return nil
}
state, _, err := s.loadLedger()
if err != nil {
return err
}
for _, key := range p.adopted {
r := p.state.Records[key]
r.Adopted = true
state.Records[key] = r
}
return writeJSONFile(s.statePath(), state)
}
// forgetUnmanaged drops the ownership records of the hooks a draft stops managing, so
// sync neither updates nor removes what they wrote.
func (s *Service) forgetUnmanaged(source *Source) error {
if len(source.unmanaged) == 0 {
return nil
}
state, _, err := s.loadLedger()
if err != nil {
return err
}
source.forget(state)
if err := writeJSONFile(s.statePath(), state); err != nil {
return fmt.Errorf("source saved; forgetting the hook's registrations failed: %w", err)
}
return nil
}
// forget deletes the records of the hooks this draft stops managing.
func (source *Source) forget(state ledger) {
for key, r := range state.Records {
if r.Owner == source.ConfigPath && source.unmanaged[r.Root+"\x00"+r.Entry] {
delete(state.Records, key)
}
}
}
// ApplyProject applies only one hooks.projects root's changes. The revision still
// covers the whole plan, so any change anywhere asks for a new preview.
func (s *Service) ApplyProject(revision, root string) (*Result, error) {
if revision == "" {
return nil, fmt.Errorf("preview the hooks changes before syncing a project")
}
lock, err := s.lock()
if err != nil {
return nil, err
}
defer lock.Unlock()
if err := s.recoverPending(); err != nil {
return nil, err
}
p, err := s.Preview()
if err != nil {
return nil, err
}
root = filepath.Clean(root)
if _, ok := p.source.Projects[root]; !ok {
return nil, fmt.Errorf("%w: %s", ErrUnknownProject, root)
}
if revision != p.Revision {
return nil, ErrStaleRevision
}
return s.applyScoped(p, &root)
}
// blockedIn reports a conflict among the plan's changes, or with root set only among
// that root's changes.
func (p *Plan) blockedIn(root *string) bool {
if root == nil {
return p.Blocked
}
for _, c := range p.Changes {
if c.Action == "conflict" && c.Root == *root {
return true
}
}
return false
}
// applyScoped writes the plan's files, or with root set only that root's files, with
// a backup and recovery journal per file.
func (s *Service) applyScoped(p *Plan, root *string) (*Result, error) {
result := &Result{Plan: p, Applied: []string{}, BackupIDs: []string{}}
inScope := func(r string) bool { return root == nil || r == *root }
if p.blockedIn(root) {
return result, ErrConflict
}
if err := p.source.checkUnchanged(); err != nil {
return result, err
}
state, stateBytes, err := s.loadLedger()
if err != nil {
return result, err
}
if !bytes.Equal(stateBytes, p.stateBytes) {
return result, fmt.Errorf("hooks ownership changed: %w", ErrStaleRevision)
}
// Check every file before the first write, and each again at its write.
for _, f := range p.files {
if inScope(f.root) {
if _, _, _, _, err := f.refresh(); err != nil {
return result, err
}
}
}
for _, f := range p.files {
if !inScope(f.root) || !f.changed() {
continue
}
data, exists, mode, doc, err := f.refresh()
if err != nil {
return result, err
}
after, remove := f.write, f.remove
if f.kind == kindJSON {
// Edit the file as it is now, keeping settings the Agent wrote since the preview.
if after, _, err = doc.edit(f.ops, nil, f.created); err != nil {
return result, fmt.Errorf("%s: %w", f.path, err)
}
// Settings added since the preview keep a file the plan deletes.
remove = f.remove && skeleton(f.target, after)
}
id := fmt.Sprintf("%d-%s", time.Now().UnixNano(), digest([]byte(f.path))[:8])
backup := backupRecord{ID: id, Owner: p.source.ConfigPath, Target: f.target, Path: f.path, Root: f.root, Kind: f.kind, Ops: f.ops, OwnedBefore: map[string]*record{}, OwnedAfter: map[string]*record{}}
if f.kind == kindFile {
if exists {
before := string(data)
backup.Before = &before
}
if !remove {
text := string(after)
backup.After = &text
}
}
for _, key := range f.keys {
if r, ok := state.Records[key]; ok {
backup.OwnedBefore[key] = &r
}
if r, ok := p.state.Records[key]; ok {
backup.OwnedAfter[key] = &r
state.Records[key] = r
} else {
delete(state.Records, key)
}
}
if err := writeJSONFile(filepath.Join(s.stateDir(), "backups", id+".json"), backup); err != nil {
return result, fmt.Errorf("hooks backup failed: %w", err)
}
if f.kind == kindJSON {
if p.state.Created[f.path] {
if state.Created == nil {
state.Created = map[string]bool{}
}
state.Created[f.path] = true
} else {
delete(state.Created, f.path)
}
switch {
case remove:
delete(state.NewFiles, f.path)
case !exists:
if state.NewFiles == nil {
state.NewFiles = map[string]bool{}
}
state.NewFiles[f.path] = true
}
}
if !remove {
for _, dir := range missingDirs(filepath.Dir(f.path)) {
if state.Dirs == nil {
state.Dirs = map[string]bool{}
}
state.Dirs[dir] = true
}
}
pending := journal{Path: f.path, State: state}
if !remove {
pending.After = digest(after)
}
if err := writeJSONFile(s.journalPath(), pending); err != nil {
return result, err
}
if remove {
err = os.Remove(f.path)
if err == nil {
pruneEmptyDirs(filepath.Dir(f.path))
pruneCreatedDirs(state.Dirs, filepath.Dir(f.path))
}
} else {
err = atomicWrite(f.path, after, mode)
}
if err != nil {
_ = os.Remove(s.journalPath())
return result, fmt.Errorf("hooks write failed for %s: %w", f.path, err)
}
result.Applied = append(result.Applied, f.path)
result.BackupIDs = append(result.BackupIDs, id)
if err := writeJSONFile(s.statePath(), state); err != nil {
return result, fmt.Errorf("hooks file written but ownership update failed; retry sync to recover: %w", err)
}
if err := os.Remove(s.journalPath()); err != nil {
return result, err
}
s.pruneBackups(f.path)
}
// Records that moved without a write, such as an adoption or a refreshed index.
final := ledger{Version: 1, Records: map[string]record{}, Created: state.Created, NewFiles: state.NewFiles, Dirs: state.Dirs}
for key, r := range state.Records {
if !inScope(r.Root) {
final.Records[key] = r
}
}
for key, r := range p.state.Records {
if inScope(r.Root) {
final.Records[key] = r
}
}
finalBytes, _ := json.Marshal(final)
currentBytes, _ := json.Marshal(state)
if !bytes.Equal(finalBytes, currentBytes) {
if err := writeJSONFile(s.statePath(), final); err != nil {
return result, err
}
}
return result, nil
}
// pruneEmptyDirs removes an entry's script folder and hooks/skillshare once empty.
func pruneEmptyDirs(dir string) {
for range 2 {
if filepath.Base(filepath.Dir(dir)) != "skillshare" && filepath.Base(dir) != "skillshare" {
return
}
if os.Remove(dir) != nil { // fails unless empty
return
}
dir = filepath.Dir(dir)
}
}
// missingDirs lists dir and each missing parent, nearest first: what MkdirAll creates.
func missingDirs(dir string) []string {
var out []string
for {
if _, err := os.Lstat(dir); !os.IsNotExist(err) {
return out
}
out = append(out, dir)
parent := filepath.Dir(dir)
if parent == dir {
return out
}
dir = parent
}
}
// pruneCreatedDirs removes dir and its parents while Skillshare created them and they
// are empty, stopping at a folder that existed before or still holds anything.
func pruneCreatedDirs(created map[string]bool, dir string) {
for created[dir] {
if err := os.Remove(dir); err != nil && !os.IsNotExist(err) {
return
}
delete(created, dir)
dir = filepath.Dir(dir)
}
}
// Backups lists this config's backups, newest first, without their contents.
func (s *Service) Backups() ([]Backup, error) {
owner, err := filepath.Abs(s.ConfigPath)
if err != nil {
return nil, err
}
records, err := s.backupRecords()
if err != nil {
return nil, err
}
out := []Backup{}
for _, r := range records {
if r.Owner == owner {
out = append(out, Backup{ID: r.ID, Target: r.Target, Path: r.Path, Time: backupTime(r.ID)})
}
}
return out, nil
}
func backupTime(id string) string {
stamp, _, _ := strings.Cut(id, "-")
n, err := strconv.ParseInt(stamp, 10, 64)
if err != nil {
return ""
}
return time.Unix(0, n).UTC().Format(time.RFC3339)
}
// backupRecords returns backups newest first; unreadable ones are skipped.
func (s *Service) backupRecords() ([]backupRecord, error) {
dir := filepath.Join(s.stateDir(), "backups")
entries, err := os.ReadDir(dir)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, err
}
var records []backupRecord
for i := len(entries) - 1; i >= 0; i-- {
name := entries[i].Name()
data, _, _, err := safeRead(filepath.Join(dir, name))
var r backupRecord
if err != nil || json.Unmarshal(data, &r) != nil || !backupID.MatchString(r.ID) || r.ID+".json" != name {
continue
}
records = append(records, r)
}
return records, nil
}
// pruneBackups keeps the newest backups of one native file; best effort.
func (s *Service) pruneBackups(path string) {
dir := filepath.Join(s.stateDir(), "backups")
entries, _ := os.ReadDir(dir)
suffix := "-" + digest([]byte(path))[:8] + ".json"
kept := 0
for i := len(entries) - 1; i >= 0; i-- {
if name := entries[i].Name(); strings.HasSuffix(name, suffix) {
if kept++; kept > keepBackups {
_ = os.Remove(filepath.Join(dir, name))
}
}
}
}
// PreviewRestore reverts only what one backed-up write changed. Outputs changed
// after the backup are conflicts; unrelated later changes are kept.
func (s *Service) PreviewRestore(id string) (*Plan, error) {
if !backupID.MatchString(id) {
return nil, fmt.Errorf("invalid hooks backup ID")
}
data, exists, _, err := safeRead(filepath.Join(s.stateDir(), "backups", id+".json"))
if err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("hooks backup not found")
}
var b backupRecord
if json.Unmarshal(data, &b) != nil || b.ID != id {
return nil, fmt.Errorf("invalid hooks backup")
}
source, err := LoadSource(s.ConfigPath)
if err != nil {
return nil, err
}
if b.Owner != source.ConfigPath {
return nil, fmt.Errorf("backup belongs to another config or scope")
}
state, stateBytes, err := s.loadLedger()
if err != nil {
return nil, err
}
p := &Plan{SourcePath: source.ConfigPath, Changes: []Change{}, Warnings: []string{}, source: source, stateBytes: stateBytes, state: ledger{Version: 1, Records: map[string]record{}, Created: state.Created}}
for k, r := range state.Records {
p.state.Records[k] = r
}
base, err := s.base(b.Target, b.Root)
if err != nil {
return nil, err
}
if err := checkPath(base, b.Path); err != nil {
return nil, err
}
current, exists, mode, err := safeRead(b.Path)
if err != nil {
return nil, err
}
f := &filePlan{path: b.Path, target: b.Target, root: b.Root, base: base, kind: b.Kind, before: current, exists: exists, mode: mode}
change := Change{Target: b.Target, Path: b.Path, Root: b.Root, Action: "restore"}
conflict := func(message string) {
change.Action, change.Message = "conflict", message
p.Blocked = true
}
sameRecord := func(key string, want *record) bool {
r, ok := state.Records[key]
if want == nil {
return !ok
}
return ok && r.Owner == want.Owner && r.Hash == want.Hash && r.Event == want.Event && r.Path == want.Path
}
restoreOwnership := func(key string) {
if r := b.OwnedBefore[key]; r != nil {
p.state.Records[key] = *r
} else {
delete(p.state.Records, key)
}
f.keys = append(f.keys, key)
}
if b.Kind == kindFile {
f.section = ""
if exists {
f.section = digest(current)
}
if mode == 0 {
f.mode = 0644
}
for key := range b.OwnedAfter {
change.Name = b.OwnedAfter[key].Entry
}
for key := range b.OwnedBefore {
change.Name = b.OwnedBefore[key].Entry
}
afterMatches := b.After == nil && !exists || b.After != nil && exists && string(current) == *b.After
owned := true
for key, r := range b.OwnedAfter {
owned = owned && sameRecord(key, r)
}
if !afterMatches || !owned {
conflict("file changed after the backup; restore would overwrite newer changes")
} else {
for _, key := range sortedKeys(mergeKeys(b.OwnedBefore, b.OwnedAfter)) {
restoreOwnership(key)
}
if b.Before == nil {
f.remove = true
} else {
f.write = []byte(*b.Before)
}
}
} else {
doc, err := parseNative(b.Target, current)
if err != nil {
return nil, fmt.Errorf("%s: %w", b.Path, err)
}
f.section = doc.sectionDigest()
if mode == 0 {
f.mode = 0644
}
// Locate against every current record of the file: identical copies resolve only
// when all of them are accounted for. sameRecord below ties these to the backup.
current := map[string]record{}
for key, r := range state.Records {
if r.Path == b.Path && r.Event != "" {
current[key] = r
}
}
located := locate(doc, current)
for _, op := range b.Ops {
if r := b.OwnedAfter[op.Key]; r != nil {
change.Name = r.Entry
} else if r := b.OwnedBefore[op.Key]; r != nil {
change.Name = r.Entry
}
if !sameRecord(op.Key, b.OwnedAfter[op.Key]) {
conflict("hook changed after the backup; restore would overwrite newer changes")
break
}
switch {
case op.Value == nil: // the write removed it: add it back
f.ops = append(f.ops, elementOp{Key: op.Key, Event: op.Event, Index: -1, Value: op.Before})
default:
i, ok := located[op.Key]
if !ok {
conflict("hook changed after the backup; restore would overwrite newer changes")
break
}
undo := elementOp{Key: op.Key, Event: op.Event, Index: i, Before: doc.events[op.Event][i]}
if op.Index >= 0 { // an update: put the old value back
undo.Value = op.Before
}
f.ops = append(f.ops, undo)
}
if change.Action == "conflict" {
break
}
restoreOwnership(op.Key)
}
if !p.Blocked {
after, positions, err := doc.edit(f.ops, nil, false)
if err != nil {
return nil, err
}
f.after = after
for key, i := range positions {
if r, ok := p.state.Records[key]; ok {
r.Index = i
p.state.Records[key] = r
}
}
}
}
if p.Blocked {
f.ops, f.write, f.remove, f.keys = nil, nil, false, nil
p.state = ledger{Version: 1, Records: state.Records, Created: state.Created}
}
p.Changes = append(p.Changes, change)
p.files = []*filePlan{f}
p.Revision = digest([]byte(id + f.section + digest(stateBytes) + digest(source.bytes)))
return p, nil
}
func mergeKeys[T any](a, b map[string]T) map[string]bool {
out := map[string]bool{}
for k := range a {
out[k] = true
}
for k := range b {
out[k] = true
}
return out
}
// Restore creates a new backup before reverting. The source is unchanged, so a
// later sync may reapply it.
func (s *Service) Restore(id, revision string) (*Result, error) {
lock, err := s.lock()
if err != nil {
return nil, err
}
defer lock.Unlock()
if err := s.recoverPending(); err != nil {
return nil, err
}
p, err := s.PreviewRestore(id)
if err != nil {
return nil, err
}
if revision != "" && p.Revision != revision {
return nil, ErrStaleRevision
}
if p.Blocked {
return &Result{Plan: p, Applied: []string{}, BackupIDs: []string{}}, ErrConflict
}
return s.applyScoped(p, nil)
}
+206
View File
@@ -0,0 +1,206 @@
package hooks
import (
"fmt"
"slices"
)
// CatalogEvent is one native event an Agent documents.
type CatalogEvent struct {
Name string `json:"name"`
Description string `json:"description"`
// Matcher reports whether the event's registrations take a matcher.
Matcher bool `json:"matcher"`
}
// AgentCatalog is a command Agent's documented events and the unit of its timeout field.
type AgentCatalog struct {
Events []CatalogEvent `json:"events"`
TimeoutUnit string `json:"timeoutUnit"` // seconds or milliseconds
// aliases are other spellings the Agent documents for its events.
aliases []string
}
func ev(name string, matcher bool, description string) CatalogEvent {
return CatalogEvent{Name: name, Description: description, Matcher: matcher}
}
// Catalog lists the native events of each command Agent, taken from its official hooks
// reference (accessed 2026-09-30). Agents add events over time, so an unknown name is
// a warning, never an error. Code Agents (pi, amp, opencode) have no event map.
var Catalog = map[string]AgentCatalog{
// https://code.claude.com/docs/en/hooks
"claude": {TimeoutUnit: "seconds", Events: []CatalogEvent{
ev("SessionStart", true, "A session starts or resumes."),
ev("Setup", true, "Runs on --init-only, or --init/--maintenance in non-interactive mode."),
ev("UserPromptSubmit", false, "A prompt is submitted, before Claude processes it."),
ev("UserPromptExpansion", true, "A typed command expands into a prompt; can block it."),
ev("PreToolUse", true, "Before a tool call runs; can block it."),
ev("PermissionRequest", true, "A tool call needs a permission decision."),
ev("PermissionDenied", true, "Auto mode denied a tool call."),
ev("PostToolUse", true, "After a tool call succeeds."),
ev("PostToolUseFailure", true, "After a tool call fails."),
ev("PostToolBatch", false, "After a batch of parallel tool calls resolves."),
ev("Notification", true, "Claude Code sends a notification."),
ev("MessageDisplay", false, "While assistant message text is displayed."),
ev("SubagentStart", true, "A subagent is spawned."),
ev("SubagentStop", true, "A subagent finishes."),
ev("TaskCreated", false, "A task is created."),
ev("TaskCompleted", false, "A task is marked completed."),
ev("Stop", false, "Claude finishes responding."),
ev("StopFailure", true, "A turn ends because of an API error."),
ev("TeammateIdle", false, "An agent-team teammate is about to go idle."),
ev("InstructionsLoaded", true, "CLAUDE.md or a rules file is loaded into context."),
ev("ConfigChange", true, "A config file changes during a session."),
ev("CwdChanged", false, "The working directory changes."),
ev("DirectoryAdded", true, "A working directory is added mid-session."),
ev("FileChanged", true, "A watched file changes on disk."),
ev("WorktreeCreate", false, "A worktree is being created."),
ev("WorktreeRemove", false, "A worktree is being removed."),
ev("PreCompact", true, "Before context compaction."),
ev("PostCompact", true, "After context compaction completes."),
ev("PreModelSwitch", true, "Before a requested model switch; can block it."),
ev("PostModelSwitch", true, "After the session's model changes."),
ev("Elicitation", true, "An MCP server requests user input."),
ev("ElicitationResult", true, "The user answered an MCP elicitation."),
ev("SessionEnd", true, "A session terminates."),
}},
// https://learn.chatgpt.com/docs/hooks
"codex": {TimeoutUnit: "seconds", Events: []CatalogEvent{
ev("SessionStart", true, "A session starts; can add context."),
ev("SessionEnd", true, "A session ends; for cleanup."),
ev("SubagentStart", true, "Before a subagent starts; can add context."),
ev("PreToolUse", true, "Before a tool call; can block, allow or rewrite input."),
ev("PermissionRequest", true, "An approval prompt; can allow or deny."),
ev("PostToolUse", true, "After a tool completes; can block the result or add feedback."),
ev("PreCompact", true, "Before compaction; can prevent it."),
ev("PostCompact", true, "After compaction completes."),
ev("UserPromptSubmit", false, "A prompt is submitted; can block it."),
ev("SubagentStop", true, "A subagent finishes."),
ev("Stop", false, "A turn stops; can force continuation."),
ev("Interrupt", false, "The user interrupts an active turn."),
}},
// https://geminicli.com/docs/hooks/reference/
"gemini": {TimeoutUnit: "milliseconds", Events: []CatalogEvent{
ev("BeforeTool", true, "Before a tool call; can validate arguments or block it."),
ev("AfterTool", true, "After a tool call; can audit or filter output."),
ev("BeforeAgent", false, "After a prompt is submitted, before the agent plans."),
ev("AfterAgent", false, "Once per turn after the final model response."),
ev("BeforeModel", false, "Before a request is sent to the model."),
ev("BeforeToolSelection", false, "Before the model picks tools; can filter them."),
ev("AfterModel", false, "After each model response chunk; allows redaction."),
ev("SessionStart", false, "On startup, resume or /clear."),
ev("SessionEnd", false, "The CLI exits or the session is cleared."),
ev("Notification", false, "The CLI emits a system alert."),
ev("PreCompress", false, "Before history is summarized."),
}},
// https://docs.github.com/en/copilot/reference/hooks-reference
"copilot": {TimeoutUnit: "seconds", aliases: []string{"PreToolUse", "PostToolUse", "PermissionRequest", "PreCompact"}, Events: []CatalogEvent{
ev("sessionStart", false, "A new or resumed session begins."),
ev("sessionEnd", false, "The session terminates."),
ev("userPromptSubmitted", false, "The user submits a prompt."),
ev("userPromptTransformed", false, "After the prompt is transformed, before the model gets it."),
ev("preToolUse", true, "Before a tool runs; can allow, deny or modify it."),
ev("postToolUse", true, "After a tool succeeds."),
ev("postToolUseFailure", false, "After a tool fails."),
ev("preCompact", true, "Before context compaction."),
ev("agentStop", false, "The main agent finishes a turn."),
ev("subagentStart", true, "Before a subagent is spawned."),
ev("subagentStop", false, "A subagent completes."),
ev("errorOccurred", false, "An error occurs during execution."),
ev("notification", true, "The CLI emits a notification."),
ev("permissionRequest", true, "Before the permission service decides."),
}},
// https://cursor.com/docs/hooks
"cursor": {TimeoutUnit: "seconds", Events: []CatalogEvent{
ev("sessionStart", false, "A conversation begins; can inject environment and context."),
ev("sessionEnd", false, "A conversation ends."),
ev("preToolUse", true, "Before any tool runs."),
ev("postToolUse", true, "After a tool succeeds."),
ev("postToolUseFailure", true, "A tool fails, times out or is denied."),
ev("subagentStart", true, "Before a subagent spawns; can allow or deny it."),
ev("subagentStop", true, "A subagent completes."),
ev("beforeShellExecution", true, "Before a shell command runs."),
ev("afterShellExecution", true, "After a shell command runs."),
ev("beforeMCPExecution", true, "Before an MCP tool call."),
ev("afterMCPExecution", false, "After an MCP tool call completes."),
ev("beforeReadFile", true, "Before the agent reads a file."),
ev("afterFileEdit", true, "After the agent edits a file."),
ev("beforeSubmitPrompt", true, "Before the prompt is sent; can block it."),
ev("preCompact", false, "Before compaction; observational only."),
ev("stop", true, "The agent loop ends; can submit a follow-up."),
ev("afterAgentResponse", true, "After an assistant message completes."),
ev("afterAgentThought", true, "After a thinking block completes."),
ev("beforeTabFileRead", true, "Before Tab reads a file."),
ev("afterTabFileEdit", true, "After Tab edits a file."),
ev("workspaceOpen", false, "A workspace opens or its folder changes."),
}},
// https://docs.factory.com/harness/hooks
"droid": {TimeoutUnit: "seconds", Events: []CatalogEvent{
ev("PreToolUse", true, "After tool parameters are built, before the tool runs."),
ev("PostToolUse", true, "Right after a tool completes."),
ev("UserPromptSubmit", false, "Before Droid processes a submitted prompt."),
ev("Notification", false, "Droid sends a notification."),
ev("Stop", false, "The main Droid is about to finish responding."),
ev("SubagentStop", false, "A sub-droid launched by Task finishes."),
ev("PreCompact", false, "Before manual or automatic compaction."),
ev("SessionStart", false, "On start, resume, clear or after compaction."),
ev("SessionEnd", false, "A session ends."),
}},
// https://antigravity.google/docs/hooks (the IDE and CLI tabs list the same events)
"antigravity": {TimeoutUnit: "seconds", Events: []CatalogEvent{
ev("PreToolUse", true, "Before a tool runs."),
ev("PostToolUse", true, "After a tool completes."),
ev("PreInvocation", false, "Before the model is called."),
ev("PostInvocation", false, "Right after each model invocation completes."),
ev("Stop", false, "Execution terminates."),
}},
// https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/
"qwen": {TimeoutUnit: "seconds", Events: []CatalogEvent{
ev("PreToolUse", true, "Before a tool runs; for permission checks and input validation."),
ev("PostToolUse", true, "After a tool succeeds; can add context."),
ev("PostToolUseFailure", true, "A tool execution fails."),
ev("PostToolBatch", false, "Once after all tool calls in a batch resolve."),
ev("UserPromptSubmit", false, "Before the model call; can validate or enrich the prompt."),
ev("UserPromptExpansion", true, "A slash command expands into a prompt."),
ev("SessionStart", true, "A new session starts."),
ev("SessionEnd", true, "A session ends."),
ev("SessionDelete", false, "A session is permanently deleted."),
ev("MessageDisplay", false, "Repeatedly while the reply streams."),
ev("Stop", false, "Before Qwen concludes its response."),
ev("StopFailure", true, "Instead of Stop, on an API error or loop detection."),
ev("SubagentStart", true, "A subagent starts."),
ev("SubagentStop", true, "A subagent finishes."),
ev("PreCompact", true, "Before conversation compaction."),
ev("PostCompact", true, "After compaction succeeds."),
ev("Notification", true, "A notification is sent."),
ev("PermissionRequest", true, "A permission dialog is shown."),
ev("PermissionDenied", true, "The auto-mode classifier blocks a tool call."),
ev("TodoCreated", false, "A todo item is created."),
ev("TodoCompleted", false, "A todo item is completed."),
ev("InstructionsLoaded", true, "A context file is loaded into the system prompt."),
}},
}
// knownEvent reports whether the Agent documents the event; Agents without a catalog
// know every name.
func knownEvent(target, event string) bool {
c, ok := Catalog[target]
if !ok {
return true
}
return slices.Contains(c.aliases, event) || slices.ContainsFunc(c.Events, func(e CatalogEvent) bool { return e.Name == event })
}
// EventWarnings names the events of an entry its Agents do not document.
func EventWarnings(name string, e Entry) []string {
var out []string
for _, target := range sortedKeys(e.Bindings) {
for _, event := range sortedKeys(e.Bindings[target].Events) {
if !knownEvent(target, event) {
out = append(out, fmt.Sprintf("hook %s: %s does not document the event %q; check its spelling", name, target, event))
}
}
}
return out
}
+40
View File
@@ -0,0 +1,40 @@
package hooks
import (
"strings"
"testing"
)
func TestCatalog_CoversEveryCommandAgent(t *testing.T) {
for _, target := range Targets {
c, ok := Catalog[target.Name]
if target.Kind == KindCode {
if ok {
t.Fatalf("%s is a code Agent and has no event catalog", target.Name)
}
continue
}
if !ok || len(c.Events) == 0 || (c.TimeoutUnit != "seconds" && c.TimeoutUnit != "milliseconds") {
t.Fatalf("%s catalog: %+v", target.Name, c)
}
for _, event := range c.Events {
if !eventName.MatchString(event.Name) || event.Description == "" {
t.Fatalf("%s event: %+v", target.Name, event)
}
}
}
}
func TestPlan_UnknownEventWarnsWithoutBlocking(t *testing.T) {
e := newEnv(t)
typo := entry(t, `{"bindings":{"claude":{"events":{"Stopp":[{"hooks":[{"type":"command","command":"echo"}]}]}},"codex":{"events":{"Stop":[{"hooks":[{"type":"command","command":"echo"}]}]}},"pi":{"code":"export default function () {}"}}}`)
p, err := e.service.PreviewMutation(Mutation{Name: "typo", Entry: typo})
must(t, err)
if p.Blocked || len(p.Warnings) != 1 || !strings.Contains(p.Warnings[0], `"Stopp"`) || !strings.Contains(p.Warnings[0], "claude") {
t.Fatalf("warnings: %v blocked=%t", p.Warnings, p.Blocked)
}
// Copilot's documented PascalCase aliases are known events.
if w := EventWarnings("c", Entry{Bindings: map[string]Binding{"copilot": {Events: map[string]any{"PreToolUse": []any{}, "sessionStart": []any{}}}}}); len(w) != 0 {
t.Fatalf("copilot aliases: %v", w)
}
}
+99
View File
@@ -0,0 +1,99 @@
package hooks
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
// allAgents is one entry that binds every Agent.
func allAgents(t *testing.T) *Entry {
t.Helper()
var bindings []string
for _, target := range sortedKeys(adapterEntry) {
bindings = append(bindings, `"`+target+`":`+adapterEntry[target])
}
return entry(t, `{"bindings":{`+strings.Join(bindings, ",")+`}}`)
}
func entries(t *testing.T, dir string) []string {
t.Helper()
list, err := os.ReadDir(dir)
must(t, err)
var names []string
for _, e := range list {
names = append(names, e.Name())
}
return names
}
// A file Skillshare created is deleted once removing the last hook leaves only what
// Skillshare put there, and so are the directories it created; the preview shows
// each deletion as a file whose new text is empty.
func TestRemove_DeletesFilesAndFoldersSkillshareCreated(t *testing.T) {
e := newEnv(t)
save(t, e.service, Mutation{Name: "demo", Entry: allAgents(t)})
p, err := e.service.PreviewMutation(Mutation{Name: "demo", Remove: true})
must(t, err)
shared := 0
for _, f := range p.Files() {
if f.After != "" {
t.Errorf("%s: remove must delete the created file, got %q", f.Path, f.After)
}
if strings.HasSuffix(f.Path, ".json") && !strings.Contains(f.Path, "copilot") {
shared++
}
}
if shared != 7 {
t.Fatalf("every created shared hooks file must be a delete in the preview, got %d: %+v", shared, p.Files())
}
save(t, e.service, Mutation{Name: "demo", Remove: true})
if left := entries(t, e.home); len(left) != 0 {
t.Fatalf("created files and folders must be gone, left %v", left)
}
}
func TestRemove_ProjectDeletesOnlyWhatSkillshareCreated(t *testing.T) {
e := newEnv(t)
root := t.TempDir()
s := e.project(root)
save(t, s, Mutation{Name: "demo", Entry: allAgents(t)})
save(t, s, Mutation{Name: "demo", Remove: true})
if left := entries(t, root); !slices.Equal(left, []string{".skillshare"}) {
t.Fatalf("project must be back to its own config only, left %v", left)
}
}
// Anything the user owns stays: a file or folder that existed before, and a created
// file that gained other settings or a comment.
func TestRemove_KeepsWhatTheUserOwns(t *testing.T) {
e := newEnv(t)
gemini := filepath.Join(e.home, ".gemini", "settings.json")
write(t, gemini, "{}\n")
must(t, os.MkdirAll(filepath.Join(e.home, ".cursor"), 0755))
both := entry(t, `{"bindings":{"claude":`+adapterEntry["claude"]+`,"gemini":`+adapterEntry["gemini"]+`,"cursor":{"events":{"stop":[{"command":"echo stop"}]}},"codex":`+adapterEntry["codex"]+`}}`)
save(t, e.service, Mutation{Name: "demo", Entry: both})
claude := filepath.Join(e.home, ".claude", "settings.json")
write(t, claude, strings.Replace(read(t, claude), "{", `{"theme": "dark",`, 1))
codex := filepath.Join(e.home, ".codex", "hooks.json")
write(t, codex, "// mine\n"+read(t, codex))
save(t, e.service, Mutation{Name: "demo", Remove: true})
if got := read(t, gemini); got != "{}\n" {
t.Errorf("a file that existed before must stay, got %q", got)
}
if got := read(t, claude); !strings.Contains(got, `"theme"`) || strings.Contains(got, "hooks") {
t.Errorf("a created file with user settings keeps them and loses only the hooks: %q", got)
}
if got := read(t, codex); !strings.Contains(got, "// mine") {
t.Errorf("a created file with a user comment must stay: %q", got)
}
if _, err := os.Stat(filepath.Join(e.home, ".cursor", "hooks.json")); !os.IsNotExist(err) {
t.Errorf("the created Cursor file must be deleted: %v", err)
}
if _, err := os.Stat(filepath.Join(e.home, ".cursor")); err != nil {
t.Errorf("a folder that existed before must stay: %v", err)
}
}
+132
View File
@@ -0,0 +1,132 @@
package hooks
import (
"os"
"path/filepath"
"strings"
"testing"
)
func fingerprint(t *testing.T, s *Service) *Plan {
t.Helper()
p, err := s.Preview()
must(t, err)
if p.Fingerprint == "" {
t.Fatal("every plan needs a fingerprint")
}
return p
}
func TestFingerprint_DeterministicIncludingEmptyPlans(t *testing.T) {
e := newEnv(t)
if fingerprint(t, e.service).Fingerprint != fingerprint(t, e.service).Fingerprint {
t.Fatal("an empty plan's fingerprint must be deterministic")
}
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
if fingerprint(t, e.service).Fingerprint != fingerprint(t, e.service).Fingerprint {
t.Fatal("a noop plan's fingerprint must be deterministic")
}
}
// A pending change edited again keeps the same actions; only the fingerprint shows
// the content the user reviewed is no longer what sync would write.
func TestFingerprint_SameActionsChangedContent(t *testing.T) {
cases := map[string][2]string{
"command": {claudeEntry, strings.Replace(claudeEntry, "echo guard", "echo other", 1)},
"code": {
`{"bindings":{"opencode":{"code":"export const A = async () => ({})\n"}}}`,
`{"bindings":{"opencode":{"code":"export const B = async () => ({})\n"}}}`,
},
"script": {
`{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"run.sh"}]}]},"files":{"run.sh":"echo a\n"}}}}`,
`{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"run.sh"}]}]},"files":{"run.sh":"echo b\n"}}}}`,
},
}
for name, docs := range cases {
t.Run(name, func(t *testing.T) {
e := newEnv(t)
_, err := e.service.Mutate(Mutation{Name: "guard", Entry: entry(t, docs[0])}, "", false)
must(t, err)
before := fingerprint(t, e.service)
_, err = e.service.Mutate(Mutation{Name: "guard", Entry: entry(t, docs[1])}, "", false)
must(t, err)
after := fingerprint(t, e.service)
if actions(before) != actions(after) {
t.Fatalf("fixture must keep the actions: %s vs %s", actions(before), actions(after))
}
if before.Fingerprint == after.Fingerprint {
t.Fatal("changed content must change the fingerprint")
}
})
}
}
func TestFingerprint_TracksHooksSourceNativeAndOwnership(t *testing.T) {
e := newEnv(t)
settings := filepath.Join(e.home, ".claude", "settings.json")
write(t, settings, `{"model":"x","hooks":{}}`)
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
base := fingerprint(t, e.service)
// Unrelated Skillshare configuration changes the revision only.
config := read(t, e.config)
write(t, e.config, strings.Replace(config, "targets: {}", "targets:\n claude:\n path: /elsewhere", 1))
p := fingerprint(t, e.service)
if p.Revision == base.Revision || p.Fingerprint != base.Fingerprint {
t.Fatalf("unrelated config: revision must change, fingerprint must not")
}
// Unrelated settings in the same native file leave it unchanged.
write(t, settings, strings.Replace(read(t, settings), `"model":"x"`, `"model":"y","mcpServers":{"a":{"command":"a"}}`, 1))
if fingerprint(t, e.service).Fingerprint != base.Fingerprint {
t.Fatal("unrelated native settings must not change the fingerprint")
}
changed := map[string]func(){
"disabled": func() {
disabled := entry(t, claudeEntry)
off := false
disabled.Enabled = &off
_, err := e.service.Mutate(Mutation{Name: "guard", Entry: disabled}, "", false)
must(t, err)
},
"native hooks": func() {
write(t, settings, strings.Replace(read(t, settings), `"hooks":{`, `"hooks":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}],`, 1))
},
"ownership": func() { must(t, os.Remove(e.service.statePath())) },
}
for name, change := range changed {
t.Run(name, func(t *testing.T) {
restore := map[string]string{e.config: read(t, e.config), settings: read(t, settings), e.service.statePath(): read(t, e.service.statePath())}
defer func() {
for path, content := range restore {
write(t, path, content)
}
}()
change()
if fingerprint(t, e.service).Fingerprint == base.Fingerprint {
t.Fatal("a hooks-relevant change must change the fingerprint")
}
})
}
}
func TestFingerprint_TracksReplaceAndDroidGuard(t *testing.T) {
e := newEnv(t)
write(t, filepath.Join(e.home, ".claude", "settings.json"), `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard","timeout":5}]}]}}`)
keep, err := e.service.PreviewMutation(Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
must(t, err)
take, err := e.service.PreviewMutation(Mutation{Name: "guard", Entry: entry(t, claudeEntry), Replace: true})
must(t, err)
if keep.Fingerprint == take.Fingerprint {
t.Fatal("replacement semantics must change the fingerprint")
}
droid := `{"bindings":{"droid":{"events":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]}}}}`
_, err = e.service.Mutate(Mutation{Name: "d", Entry: entry(t, droid)}, "", false)
must(t, err)
open := fingerprint(t, e.service)
write(t, filepath.Join(e.home, ".factory", "settings.json"), `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"y"}]}]}}`)
if fingerprint(t, e.service).Fingerprint == open.Fingerprint {
t.Fatal("the Droid inline-hooks guard must change the fingerprint")
}
}
+112
View File
@@ -0,0 +1,112 @@
package hooks
import (
"path/filepath"
"strings"
"testing"
)
const stopEntry = `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"echo stop"}]}]}}}}`
func TestSync_CompactFileStaysCompact(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, `{"model":"opus","hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"g"}]}]}}`)
save(t, e.service, Mutation{Name: "stop", Entry: entry(t, stopEntry)})
want := `{"model":"opus","hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"g"}]}],"Stop":[{"hooks":[{"command":"echo stop","type":"command"}]}]}}` + "\n"
if got := read(t, path); got != want {
t.Fatalf("added:\n%s", got)
}
save(t, e.service, Mutation{Name: "stop", Remove: true})
if got := read(t, path); got != `{"model":"opus","hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"g"}]}]}}`+"\n" {
t.Fatalf("removed:\n%s", got)
}
}
func TestSync_EmptiedHooksKeyFollowsWhoCreatedIt(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, "{\n \"model\": \"opus\"\n}\n")
save(t, e.service, Mutation{Name: "stop", Entry: entry(t, stopEntry)})
if got := read(t, path); !strings.Contains(got, "\n \"hooks\": {\n \"Stop\": [\n {\n") {
t.Fatalf("indentation must follow the file:\n%s", got)
}
save(t, e.service, Mutation{Name: "stop", Remove: true})
if got := read(t, path); got != "{\n \"model\": \"opus\"\n}\n" {
t.Fatalf("Skillshare created hooks, so it removes the emptied key:\n%q", got)
}
write(t, path, `{"model":"opus","hooks":{}}`)
save(t, e.service, Mutation{Name: "stop", Entry: entry(t, stopEntry)})
save(t, e.service, Mutation{Name: "stop", Remove: true})
if got := read(t, path); got != `{"model":"opus","hooks":{}}`+"\n" {
t.Fatalf("a hooks key the user had stays:\n%q", got)
}
}
func TestPlanFiles_AfterIsWhatSyncWrites(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, `{"model":"opus"}`)
m := Mutation{Name: "stop", Entry: entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"echo stop"}]}]}},"opencode":{"code":"export default {}\n"}}}`)}
p, err := e.service.PreviewMutation(m)
must(t, err)
files := p.Files()
if len(files) != 2 || files[0].Before != `{"model":"opus"}` || files[1].Before != "" {
t.Fatalf("files: %+v", files)
}
save(t, e.service, m)
for _, f := range files {
if got := read(t, f.Path); got != f.After {
t.Fatalf("%s: preview after differs from the written file:\n%q\n%q", f.Target, f.After, got)
}
}
p, err = e.service.Preview()
must(t, err)
if len(p.Files()) != 0 {
t.Fatalf("unchanged files are skipped: %+v", p.Files())
}
}
func TestSync_OneLineArraysStayOnOneLine(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, "{\n \"hooks\": {\n \"Stop\": [{\"hooks\": [{\"type\": \"command\", \"command\": \"mine\"}]}]\n }\n}\n")
save(t, e.service, Mutation{Name: "stop", Entry: entry(t, stopEntry)})
want := "{\n \"hooks\": {\n \"Stop\": [{\"hooks\": [{\"type\": \"command\", \"command\": \"mine\"}]}, {\"hooks\": [{\"command\": \"echo stop\", \"type\": \"command\"}]}]\n }\n}\n"
if got := read(t, path); got != want {
t.Fatalf("appended:\n%s", got)
}
}
// An element replaced in place keeps its key order and the separators of the line it is on.
func TestSync_ReplacedElementKeepsKeyOrderAndSpacing(t *testing.T) {
for _, tc := range []struct{ name, file string }{
{"spaced", "{\n \"hooks\": {\n \"Stop\": [{\"hooks\": [{\"type\": \"command\", \"command\": \"chime\", \"timeout\": 5}]}]\n }\n}\n"},
{"compact", `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"chime","timeout":5}]}]}}` + "\n"},
} {
t.Run(tc.name, func(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, tc.file)
c := importOne(t, e.service, "claude", "claude-stop")
save(t, e.service, Mutation{Name: c.Name, Entry: &c.Entry, Adopt: true})
save(t, e.service, Mutation{Name: c.Name, Entry: entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"chime","timeout":10}]}]}}}}`)})
if got, want := read(t, path), strings.Replace(tc.file, "5}", "10}", 1); got != want {
t.Fatalf("replaced:\n%s\nwant:\n%s", got, want)
}
})
}
}
func TestSave_EntriesAddedToAnEmptiedSectionAreBlockStyle(t *testing.T) {
e := newEnv(t)
// An emptied section, plus an entry already squeezed onto one line by the earlier bug.
write(t, e.config, "targets: {}\nhooks:\n entries: {old: {bindings: {}}}\n")
if _, err := e.service.Mutate(Mutation{Name: "stop", Entry: entry(t, stopEntry)}, "", false); err != nil {
t.Fatal(err)
}
if got := read(t, e.config); strings.Contains(got, "entries: {") || strings.Contains(got, "old: {") || !strings.Contains(got, "\n stop:\n") {
t.Fatalf("entries not written in block style:\n%s", got)
}
}
+106
View File
@@ -0,0 +1,106 @@
package hooks
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/tailscale/hujson"
)
type env struct {
t *testing.T
home string
config string
service *Service
}
// newEnv is a global scope with an isolated home, state and config.
func newEnv(t *testing.T) *env {
t.Helper()
dir := t.TempDir()
home := filepath.Join(dir, "home")
config := filepath.Join(dir, "skillshare", "config.yaml")
must(t, os.MkdirAll(home, 0755))
write(t, config, "targets: {}\n")
return &env{t: t, home: home, config: config, service: &Service{ConfigPath: config, Home: home, StateDir: filepath.Join(dir, "state"), ConfigDirs: map[string]string{}}}
}
// project is a project scope sharing e's state directory.
func (e *env) project(root string) *Service {
config := filepath.Join(root, ".skillshare", "config.yaml")
write(e.t, config, "targets: []\n")
return &Service{ConfigPath: config, ProjectRoot: root, Home: e.home, StateDir: e.service.StateDir}
}
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
func write(t *testing.T, path, content string) {
t.Helper()
must(t, os.MkdirAll(filepath.Dir(path), 0755))
must(t, os.WriteFile(path, []byte(content), 0644))
}
func read(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
must(t, err)
return string(data)
}
func entry(t *testing.T, doc string) *Entry {
t.Helper()
e, err := ParseEntry([]byte(doc))
must(t, err)
return &e
}
// save previews then saves a mutation with sync, as the CLI does.
func save(t *testing.T, s *Service, m Mutation) *Result {
t.Helper()
p, err := s.PreviewMutation(m)
must(t, err)
r, err := s.Mutate(m, p.Revision, true)
if err != nil {
t.Fatalf("mutate: %v (changes %+v)", err, p.Changes)
}
return r
}
func sync(t *testing.T, s *Service) *Result { return save(t, s, Mutation{}) }
func actions(p *Plan) string {
var out []string
for _, c := range p.Changes {
out = append(out, c.Target+":"+c.Name+":"+c.Action)
}
return strings.Join(out, ",")
}
// events decodes a shared hooks file's event map.
func events(t *testing.T, path string, wrapped bool) map[string][]any {
t.Helper()
v, err := hujson.Parse([]byte(read(t, path)))
must(t, err)
v.Standardize()
var doc map[string]any
must(t, json.Unmarshal(v.Pack(), &doc))
section := doc
if wrapped {
section, _ = doc["hooks"].(map[string]any)
}
out := map[string][]any{}
for k, v := range section {
out[k], _ = v.([]any)
}
return out
}
const claudeEntry = `{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard","timeout":5}]}]}}}}`
+467
View File
@@ -0,0 +1,467 @@
package hooks
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/pelletier/go-toml/v2"
)
// List reads the source, ownership and native files without writing. A plan that
// cannot be computed is reported in PreviewError so the rest stays visible.
func (s *Service) List() (*Inventory, error) {
source, err := LoadSource(s.ConfigPath)
if err != nil {
return nil, err
}
inv := &Inventory{
Source: SourceInfo{Path: source.ConfigPath, ConfigPath: source.ConfigPath, Entries: source.Entries, Projects: source.Projects},
Targets: Targets,
Paths: s.Paths(),
Unmanaged: []Unmanaged{},
ProjectConfigs: []string{},
ProjectPaths: map[string]map[string]string{},
}
if inv.Plan, err = s.previewSource(source, nil, nil); err != nil {
inv.Plan, inv.PreviewError = nil, err.Error()
}
if inv.Backups, err = s.Backups(); err != nil {
return nil, err
}
state, _, err := s.loadLedger()
if err != nil {
return nil, err
}
inv.Unmanaged = append(inv.Unmanaged, s.unmanaged(state)...)
for _, root := range sortedKeys(source.Projects) {
if ownConfig(root) {
inv.ProjectConfigs = append(inv.ProjectConfigs, root)
continue
}
scoped := s.scoped(root)
inv.ProjectPaths[root] = scoped.Paths()
inv.Unmanaged = append(inv.Unmanaged, scoped.unmanaged(state)...)
}
return inv, nil
}
// unmanaged lists native hooks in this scope that no Skillshare config owns, plus
// additional sources Skillshare reads but never edits.
func (s *Service) unmanaged(state ledger) []Unmanaged {
var out []Unmanaged
add := func(target, path string, names []string) {
if len(names) > 0 {
out = append(out, Unmanaged{Target: target, Path: path, Names: names})
}
}
for _, t := range Targets {
path, err := s.nativePath(t.Name)
if err != nil {
continue
}
switch {
case t.Kind == KindCode || t.Name == "copilot":
add(t.Name, path, s.unownedFiles(t.Name, path, state))
default:
doc, _, err := s.readDoc(t.Name, path)
if err != nil || doc == nil {
continue
}
add(t.Name, path, unownedEvents(doc, path, state))
}
}
dir := func(target string) string { d, _ := s.configDir(target); return d }
if names := codexInlineEvents(filepath.Join(dir("codex"), "config.toml")); len(names) > 0 {
add("codex", filepath.Join(dir("codex"), "config.toml"), names)
}
// Droid runs settings.json hooks only while hooks.json is absent; its legacy
// hooks/hooks.json always loads.
if !exists(filepath.Join(dir("droid"), "hooks.json")) {
if inline, _ := droidInlineHooks(filepath.Join(dir("droid"), "settings.json")); len(inline) > 0 {
add("droid", filepath.Join(dir("droid"), "settings.json"), sortedKeys(inline))
}
}
legacy := filepath.Join(dir("droid"), "hooks", "hooks.json")
if doc, _, err := s.readDoc("droid", legacy); err == nil && doc != nil {
add("droid", legacy, sortedKeys(doc.events))
}
if s.ProjectRoot != "" {
local := filepath.Join(dir("claude"), "settings.local.json")
if doc, _, err := s.readDoc("claude", local); err == nil && doc != nil {
add("claude", local, sortedKeys(doc.events))
}
}
return out
}
func (s *Service) readDoc(target, path string) (*nativeDoc, bool, error) {
data, exists, _, err := safeRead(path)
if err != nil || !exists {
return nil, exists, err
}
doc, err := parseNative(target, data)
return doc, true, err
}
// unownedEvents names events holding elements no record locates.
func unownedEvents(doc *nativeDoc, path string, state ledger) []string {
records := map[string]record{}
for key, r := range state.Records {
if r.Path == path && r.Event != "" {
records[key] = r
}
}
owned := map[string]int{}
for key := range locate(doc, records) {
owned[records[key].Event]++
}
var names []string
for _, event := range sortedKeys(doc.events) {
if len(doc.events[event]) > owned[event] {
names = append(names, event)
}
}
return names
}
// unownedFiles lists hook files in a Copilot hooks folder or a code Agent's plugin
// folder that no Skillshare config owns.
func (s *Service) unownedFiles(target, dir string, state ledger) []string {
entries, err := os.ReadDir(dir)
if err != nil {
return nil
}
var names []string
for _, e := range entries {
name := e.Name()
ext := filepath.Ext(name)
if e.IsDir() || !(target == "copilot" && ext == ".json" || target != "copilot" && (ext == ".ts" || ext == ".js")) {
continue
}
if _, owned := state.Records[fileKey(filepath.Join(dir, name))]; !owned {
names = append(names, name)
}
}
return names
}
// codexInlineEvents names the [hooks] events inline in Codex's config.toml.
func codexInlineEvents(path string) []string {
data, exists, _, err := safeRead(path)
if err != nil || !exists {
return nil
}
var doc struct {
Hooks map[string]any `toml:"hooks"`
}
if toml.Unmarshal(data, &doc) != nil {
return nil
}
return sortedKeys(doc.Hooks)
}
var nonName = regexp.MustCompile(`[^A-Za-z0-9_.-]+`)
// candidateName turns an event or file name into a hook name.
func candidateName(parts ...string) string {
name := strings.Trim(nonName.ReplaceAllString(strings.Join(parts, "-"), "-"), "-.")
if len(name) > 128 {
name = name[:128]
}
return strings.ToLower(name)
}
// Import reads native hooks without executing them. Without Content it reads the
// Agent's files in scope and offers only hooks no Skillshare config owns. A Name that
// matches a candidate picks that one; any other Name merges everything found into one
// candidate.
func (s *Service) Import(req ImportRequest) ([]Candidate, error) {
target := canonicalTarget(req.From)
def, ok := targetDef(target)
if !ok {
return nil, fmt.Errorf("unsupported hooks Agent %q", req.From)
}
scope := s
if req.Root != "" {
if s.ProjectRoot != "" {
return nil, fmt.Errorf("hooks.projects belongs in the global config")
}
source, err := LoadSource(s.ConfigPath)
if err != nil {
return nil, err
}
root, err := projectRoot(req.Root)
if err != nil {
return nil, err
}
if _, ok := source.Projects[root]; !ok {
return nil, fmt.Errorf("%w: %s", ErrUnknownProject, req.Root)
}
scope = s.scoped(root)
}
state, _, err := s.loadLedger()
if err != nil {
return nil, err
}
found := []Candidate{}
switch {
case def.Kind == KindCode:
found, err = scope.importCode(target, req, state)
case target == "copilot":
found, err = scope.importCopilot(req, state)
default:
found, err = scope.importShared(target, req, state)
}
if err != nil {
return nil, err
}
shared := def.Kind == KindCommand && target != "copilot"
picked := []Candidate{}
for _, c := range found {
if c.Name == req.Name {
picked = append(picked, c)
}
}
if req.Name != "" && (len(picked) > 0 || req.Content == "" && !shared) {
// Candidates are per event or per file; a name picks one of them.
found = picked
} else if req.Name != "" && len(found) > 1 {
merged := Entry{Bindings: map[string]Binding{}}
var warnings []string
for _, c := range found {
b := c.Entry.Bindings[target]
m := merged.Bindings[target]
if m.Events == nil {
m.Events = map[string]any{}
}
for event, items := range b.Events {
existing, _ := m.Events[event].([]any)
m.Events[event] = append(existing, items.([]any)...)
}
merged.Bindings[target] = m
warnings = append(warnings, c.Warnings...)
}
found = []Candidate{{Name: req.Name, Entry: merged, Warnings: dedupe(warnings)}}
} else if req.Name != "" && len(found) == 1 {
found[0].Name = req.Name
}
for i := range found {
if found[i].Problems == nil {
found[i].Problems = []string{}
}
if found[i].Warnings == nil {
found[i].Warnings = []string{}
}
if err := found[i].Entry.Validate(found[i].Name); err != nil {
found[i].Problems = append(found[i].Problems, err.Error())
}
}
return found, nil
}
func exists(path string) bool {
_, err := os.Lstat(path)
return err == nil
}
func dedupe(items []string) []string {
seen := map[string]bool{}
out := []string{}
for _, item := range items {
if !seen[item] {
seen[item] = true
out = append(out, item)
}
}
return out
}
const adoptWarning = "saving the import takes over the existing registrations in place; sync leaves them as they are instead of adding duplicates"
func (s *Service) importShared(target string, req ImportRequest, state ledger) ([]Candidate, error) {
path, err := s.nativePath(target)
if err != nil {
return nil, err
}
var doc *nativeDoc
var warnings []string
if req.Content != "" {
if doc, err = parseNative(target, []byte(req.Content)); err != nil && target == "droid" {
// Pasted from settings.json, where Droid's hooks sit under "hooks".
doc, err = parseNative("claude", []byte(req.Content))
}
if err != nil {
return nil, err
}
state = ledger{Records: map[string]record{}} // pasted content has no owners
} else if settings := filepath.Join(filepath.Dir(path), "settings.json"); target == "droid" && !exists(path) {
// Without hooks.json, the hooks Droid runs are the inline ones in settings.json.
if err := checkPath(s.baseOrDir(target), settings); err != nil {
return nil, err
}
if doc, _, err = s.readDoc("claude", settings); err != nil {
return nil, fmt.Errorf("%s: %w", settings, err)
}
if doc == nil {
return []Candidate{}, nil
}
state = ledger{Records: map[string]record{}}
warnings = []string{"Droid runs these from " + settings + " only while hooks.json is absent; after saving, remove the hooks key from " + settings + " and sync to move them into hooks.json"}
} else {
if err := checkPath(s.baseOrDir(target), path); err != nil {
return nil, err
}
if doc, _, err = s.readDoc(target, path); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if doc == nil {
return []Candidate{}, nil
}
}
records := map[string]record{}
for key, r := range state.Records {
if r.Path == path && r.Event != "" {
records[key] = r
}
}
owned := map[string]map[int]bool{}
for key, i := range locate(doc, records) {
event := records[key].Event
if owned[event] == nil {
owned[event] = map[int]bool{}
}
owned[event][i] = true
}
out := []Candidate{}
for _, event := range sortedKeys(doc.events) {
var items []any
for i, item := range doc.events[event] {
if !owned[event][i] {
items = append(items, item)
}
}
if len(items) == 0 {
continue
}
c := Candidate{Name: candidateName(target, event), Entry: Entry{Bindings: map[string]Binding{target: {Events: map[string]any{event: items}}}}}
switch {
case warnings != nil:
c.Warnings = warnings
case req.Content == "":
c.Warnings = []string{adoptWarning}
}
if target == "antigravity" {
c = antigravityCandidate(event, items[0].(map[string]any), c.Warnings)
}
out = append(out, c)
}
return out, nil
}
// antigravityCandidate offers one named block. The hook keeps the block's name, so
// saving the import takes that block over in place.
func antigravityCandidate(name string, block map[string]any, warnings []string) Candidate {
events := map[string]any{}
for event, value := range block {
if event != "enabled" {
events[event] = value
}
}
c := Candidate{Name: name, Entry: Entry{Bindings: map[string]Binding{"antigravity": {Events: events}}}, Warnings: warnings}
if !entryName.MatchString(name) {
c.Name = candidateName(name)
c.Warnings = []string{fmt.Sprintf("%q is not a valid hook name, so the import is written as %q next to it; remove the original afterwards", name, c.Name)}
}
if _, disabled := block["enabled"]; disabled {
c.Problems = []string{"this hook is disabled in Antigravity (enabled: false); enable it there to import it"}
}
return c
}
func (s *Service) baseOrDir(target string) string {
if s.ProjectRoot != "" {
return s.ProjectRoot
}
dir, _ := s.configDir(target)
return dir
}
func (s *Service) importCopilot(req ImportRequest, state ledger) ([]Candidate, error) {
parse := func(name string, data []byte) (Candidate, error) {
var doc struct {
Version any `json:"version"`
Hooks map[string]any `json:"hooks"`
}
if err := json.Unmarshal(data, &doc); err != nil || doc.Version != float64(1) {
return Candidate{}, fmt.Errorf("%s: Copilot hooks files need version 1 and a hooks object", name)
}
return Candidate{Name: name, Entry: Entry{Bindings: map[string]Binding{"copilot": {Events: doc.Hooks}}}}, nil
}
if req.Content != "" {
c, err := parse("copilot-hooks", []byte(req.Content))
if err != nil {
return nil, err
}
return []Candidate{c}, nil
}
dir, err := s.nativePath("copilot")
if err != nil {
return nil, err
}
out := []Candidate{}
for _, file := range s.unownedFiles("copilot", dir, state) {
path := filepath.Join(dir, file)
if err := checkPath(s.baseOrDir("copilot"), path); err != nil {
return nil, err
}
data, _, _, err := safeRead(path)
if err != nil {
return nil, err
}
c, err := parse(candidateName(strings.TrimSuffix(strings.TrimPrefix(file, "skillshare-"), ".json")), data)
if err != nil {
out = append(out, Candidate{Name: candidateName(strings.TrimSuffix(file, ".json")), Entry: Entry{Bindings: map[string]Binding{}}, Problems: []string{err.Error()}})
continue
}
c.Warnings = []string{fmt.Sprintf("%s keeps loading; remove it after syncing so Copilot does not run these hooks twice", path)}
out = append(out, c)
}
return out, nil
}
func (s *Service) importCode(target string, req ImportRequest, state ledger) ([]Candidate, error) {
if req.Content != "" {
name := req.Name
if name == "" {
name = candidateName(target, "plugin")
}
return []Candidate{{Name: name, Entry: Entry{Bindings: map[string]Binding{target: {Code: req.Content}}}}}, nil
}
dir, err := s.nativePath(target)
if err != nil {
return nil, err
}
out := []Candidate{}
for _, file := range s.unownedFiles(target, dir, state) {
path := filepath.Join(dir, file)
if err := checkPath(s.baseOrDir(target), path); err != nil {
return nil, err
}
data, _, _, err := safeRead(path)
if err != nil {
return nil, err
}
name := candidateName(strings.TrimSuffix(strings.TrimPrefix(file, "skillshare-"), filepath.Ext(file)))
c := Candidate{Name: name, Entry: Entry{Bindings: map[string]Binding{target: {Code: string(data)}}}}
c.Warnings = []string{fmt.Sprintf("%s keeps loading; remove it after syncing so the plugin does not run twice", path)}
if filepath.Ext(file) == ".js" {
c.Warnings = append(c.Warnings, "Skillshare writes code as a .ts file; plain JavaScript is valid TypeScript for the loader, but check any CommonJS syntax")
}
out = append(out, c)
}
return out, nil
}
+415
View File
@@ -0,0 +1,415 @@
package hooks
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
const userSettings = `{
// user's own comment
"model": "opus",
"hooks": {
"PreToolUse": [
{"matcher": "Edit", "hooks": [{"type": "command", "command": "echo mine"}]}
],
"Stop": [{"hooks": [{"type": "command", "command": "echo stop"}]}]
},
"permissions": {"allow": ["Bash(ls)"]}
}
`
func TestSync_PreservesUnrelatedSettingsCommentsAndOrder(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, userSettings)
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
got := read(t, path)
for _, keep := range []string{"// user's own comment", `"model": "opus"`, `"permissions": {"allow": ["Bash(ls)"]}`, `{"matcher": "Edit", "hooks": [{"type": "command", "command": "echo mine"}]}`, `"Stop": [{"hooks": [{"type": "command", "command": "echo stop"}]}]`} {
if !strings.Contains(got, keep) {
t.Fatalf("lost %q:\n%s", keep, got)
}
}
pre := events(t, path, true)["PreToolUse"]
if len(pre) != 2 || !strings.Contains(got, "echo guard") || strings.Index(got, "echo mine") > strings.Index(got, "echo guard") {
t.Fatalf("owned group must be appended after the user's:\n%s", got)
}
// Disable removes only the owned group; the definition stays.
disabled := *entry(t, claudeEntry)
off := false
disabled.Enabled = &off
save(t, e.service, Mutation{Name: "guard", Entry: &disabled})
if got := read(t, path); got != userSettings {
t.Fatalf("disable must restore the user's file byte for byte:\n%s", got)
}
source, err := LoadSource(e.config)
must(t, err)
if source.Entries["guard"].IsEnabled() {
t.Fatal("definition must stay, disabled")
}
// Re-enable republishes; remove prunes.
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
if !strings.Contains(read(t, path), "echo guard") {
t.Fatal("re-enable must republish")
}
save(t, e.service, Mutation{Name: "guard", Remove: true})
if got := read(t, path); got != userSettings {
t.Fatalf("remove must prune only the owned group:\n%s", got)
}
}
func TestSync_IdenticalUnmanagedGroupIsConflictUntilReplace(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard","timeout":5}]}]}}`)
m := Mutation{Name: "guard", Entry: entry(t, claudeEntry)}
p, err := e.service.PreviewMutation(m)
must(t, err)
if !p.Blocked || !strings.Contains(actions(p), "conflict") {
t.Fatalf("equality alone must not adopt: %s", actions(p))
}
if _, err := e.service.Mutate(m, p.Revision, true); !errors.Is(err, ErrConflict) {
t.Fatalf("sync must refuse conflicts, got %v", err)
}
if _, err := LoadSource(e.config); err != nil {
t.Fatal(err)
}
if source, _ := LoadSource(e.config); len(source.Entries) != 0 {
t.Fatal("a refused sync must not save the source")
}
m.Replace = true
save(t, e.service, m)
if n := len(events(t, path, true)["PreToolUse"]); n != 1 {
t.Fatalf("replace must take over in place, not duplicate: %d groups", n)
}
// Now owned: removing prunes it.
save(t, e.service, Mutation{Name: "guard", Remove: true})
if n := len(events(t, path, true)["PreToolUse"]); n != 0 {
t.Fatalf("adopted group must be pruned on remove: %d", n)
}
}
func TestSync_ExternallyEditedOutputIsNeverOverwritten(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
edited := strings.Replace(read(t, path), "echo guard", "echo edited", 1)
write(t, path, edited)
for name, m := range map[string]Mutation{
"update": {Name: "guard", Entry: entry(t, strings.Replace(claudeEntry, "echo guard", "echo v2", 1))},
"remove": {Name: "guard", Remove: true},
"disable": {Name: "guard", Entry: func() *Entry { x := *entry(t, claudeEntry); f := false; x.Enabled = &f; return &x }()},
} {
p, err := e.service.PreviewMutation(m)
must(t, err)
if !p.Blocked {
t.Fatalf("%s: edited output must conflict: %s", name, actions(p))
}
}
// Replace on remove releases ownership and leaves the user's edit.
save(t, e.service, Mutation{Name: "guard", Remove: true, Replace: true})
if read(t, path) != edited {
t.Fatal("released output must stay as the user edited it")
}
p, err := e.service.Preview()
must(t, err)
if len(p.Changes) != 0 {
t.Fatalf("released output is the user's: %s", actions(p))
}
}
func TestSync_WholeFilesRespectUnmanagedAndEditedFiles(t *testing.T) {
e := newEnv(t)
ts := filepath.Join(e.home, ".pi", "agent", "extensions", "skillshare-demo.ts")
write(t, ts, "// the user's own file\n")
m := Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"pi":`+adapterEntry["pi"]+`}}`)}
p, err := e.service.PreviewMutation(m)
must(t, err)
if !p.Blocked {
t.Fatal("an unmanaged file at an output path must conflict")
}
m.Replace = true
save(t, e.service, m)
backups, err := e.service.Backups()
must(t, err)
if len(backups) != 1 {
t.Fatalf("overwrite needs a backup: %v", backups)
}
write(t, ts, "// edited later\n")
p, err = e.service.PreviewMutation(Mutation{Name: "demo", Remove: true})
must(t, err)
if !p.Blocked {
t.Fatal("an edited owned file must not be removed")
}
}
func TestSync_ScriptFilesArePrunedWithTheirFolder(t *testing.T) {
e := newEnv(t)
save(t, e.service, Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"cursor":`+adapterEntry["cursor"]+`}}`)})
script := filepath.Join(e.home, ".cursor", "hooks", "skillshare", "demo", "guard.sh")
info, err := os.Stat(script)
must(t, err)
if info.Mode().Perm()&0100 == 0 {
t.Fatal("scripts must be executable")
}
save(t, e.service, Mutation{Name: "demo", Remove: true})
if exists(filepath.Join(e.home, ".cursor", "hooks", "skillshare")) {
t.Fatal("empty script folders must be pruned")
}
if exists(filepath.Join(e.home, ".cursor")) {
t.Fatal("the hooks.json and folders Skillshare created go with the last hook")
}
}
func TestSync_EmptyBindingsKeepsDefinitionWithoutPublishing(t *testing.T) {
e := newEnv(t)
save(t, e.service, Mutation{Name: "idea", Entry: entry(t, `{"description":"later","bindings":{}}`)})
source, err := LoadSource(e.config)
must(t, err)
if _, ok := source.Entries["idea"]; !ok {
t.Fatal("definition must be saved")
}
if exists(filepath.Join(e.home, ".claude")) {
t.Fatal("empty bindings must publish nothing")
}
}
func TestMutate_StaleRevisionAndExternalConfigEdit(t *testing.T) {
e := newEnv(t)
m := Mutation{Name: "guard", Entry: entry(t, claudeEntry)}
p, err := e.service.PreviewMutation(m)
must(t, err)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo new"}]}]}}`)
if _, err := e.service.Mutate(m, p.Revision, true); !errors.Is(err, ErrStaleRevision) {
t.Fatalf("native hooks edited after preview: want ErrStaleRevision, got %v", err)
}
p, err = e.service.PreviewMutation(m)
must(t, err)
write(t, e.config, "targets: {}\n# edited\n")
if _, err := e.service.Mutate(m, p.Revision, true); !errors.Is(err, ErrStaleRevision) {
t.Fatalf("config edited after preview: want ErrStaleRevision, got %v", err)
}
// Unrelated settings the Agent rewrites between preview and apply are kept.
p, err = e.service.PreviewMutation(m)
must(t, err)
write(t, path, `{"theme":"dark","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo new"}]}]}}`)
if _, err := e.service.Mutate(m, p.Revision, true); err != nil {
t.Fatalf("unrelated setting change must not be stale: %v", err)
}
if !strings.Contains(read(t, path), `"theme":"dark"`) {
t.Fatal("setting written after preview was lost")
}
}
func TestSync_RejectsMalformedAndUnsafeDestinations(t *testing.T) {
cases := map[string]func(e *env){
"malformed": func(e *env) { write(t, filepath.Join(e.home, ".claude", "settings.json"), `{"hooks":`) },
"duplicate key": func(e *env) { write(t, filepath.Join(e.home, ".claude", "settings.json"), `{"hooks":{},"hooks":{}}`) },
"event not array": func(e *env) { write(t, filepath.Join(e.home, ".claude", "settings.json"), `{"hooks":{"Stop":{}}}`) },
"symlinked file": func(e *env) {
target := filepath.Join(e.home, "dotfiles", "settings.json")
write(t, target, "{}")
must(t, os.MkdirAll(filepath.Join(e.home, ".claude"), 0755))
must(t, os.Symlink(target, filepath.Join(e.home, ".claude", "settings.json")))
},
"symlinked script dir": func(e *env) {
must(t, os.MkdirAll(filepath.Join(e.home, "outside"), 0755))
must(t, os.MkdirAll(filepath.Join(e.home, ".claude", "hooks"), 0755))
must(t, os.Symlink(filepath.Join(e.home, "outside"), filepath.Join(e.home, ".claude", "hooks", "skillshare")))
},
}
for name, setup := range cases {
t.Run(name, func(t *testing.T) {
e := newEnv(t)
setup(e)
doc := `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]},"files":{"a.sh":"echo"}}}}`
if _, err := e.service.PreviewMutation(Mutation{Name: "demo", Entry: entry(t, doc)}); err == nil {
t.Fatal("preview must fail closed")
}
})
}
}
func TestSync_CrossConfigOwnershipIsRespected(t *testing.T) {
e := newEnv(t)
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
other := *e.service
other.ConfigPath = filepath.Join(filepath.Dir(e.config), "other.yaml")
write(t, other.ConfigPath, "targets: {}\n")
p, err := other.PreviewMutation(Mutation{Name: "guard", Entry: entry(t, claudeEntry), Replace: true})
must(t, err)
if !p.Blocked || !strings.Contains(p.Changes[0].Message, "another Skillshare config") {
t.Fatalf("replace must not take another live config's hook: %+v", p.Changes)
}
// The other config's sync never prunes what this config owns.
sync(t, &other)
if n := len(events(t, filepath.Join(e.home, ".claude", "settings.json"), true)["PreToolUse"]); n != 1 {
t.Fatalf("other config removed a hook it does not own: %d", n)
}
// Once the owner is gone, an explicit replace may take over.
must(t, os.Remove(e.config))
save(t, &other, Mutation{Name: "guard", Entry: entry(t, claudeEntry), Replace: true})
if n := len(events(t, filepath.Join(e.home, ".claude", "settings.json"), true)["PreToolUse"]); n != 1 {
t.Fatalf("takeover must not duplicate: %d", n)
}
}
func TestSync_DroidNeverShadowsInlineSettingsHooks(t *testing.T) {
e := newEnv(t)
write(t, filepath.Join(e.home, ".factory", "settings.json"), `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo inline"}]}]}}`)
p, err := e.service.PreviewMutation(Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"droid":`+adapterEntry["droid"]+`}}`)})
must(t, err)
if !p.Blocked {
t.Fatal("creating hooks.json would silently stop Droid reading settings.json hooks")
}
inv, err := e.service.List()
must(t, err)
found := false
for _, u := range inv.Unmanaged {
found = found || u.Target == "droid" && strings.HasSuffix(u.Path, "settings.json")
}
if !found {
t.Fatalf("inline Droid hooks must be disclosed: %+v", inv.Unmanaged)
}
}
func TestRecovery_InterruptedWriteRecordsOwnership(t *testing.T) {
e := newEnv(t)
m := Mutation{Name: "guard", Entry: entry(t, claudeEntry)}
p, err := e.service.PreviewMutation(m)
must(t, err)
source, replace, adopt, err := e.service.draft(m)
must(t, err)
must(t, source.save())
p, err = e.service.previewSource(source, replace, adopt)
must(t, err)
// Simulate a crash after the native write and before the ledger update.
f := p.files[0]
must(t, writeJSONFile(e.service.journalPath(), journal{Path: f.path, After: digest(f.after), State: p.state}))
must(t, atomicWrite(f.path, f.after, 0644))
plan, err := e.service.Preview()
must(t, err)
if plan.Blocked || !strings.Contains(actions(plan), "unchanged") {
t.Fatalf("preview must read recovered ownership: %s", actions(plan))
}
sync(t, e.service)
if exists(e.service.journalPath()) {
t.Fatal("journal must be cleared by the next operation")
}
save(t, e.service, Mutation{Name: "guard", Remove: true})
if n := len(events(t, f.path, true)["PreToolUse"]); n != 0 {
t.Fatal("recovered ownership must allow pruning")
}
}
func TestRestore_RevertsOnlyThatWriteAndKeepsLaterChanges(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, userSettings)
r := save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
id := r.BackupIDs[0]
// A later, unrelated user change.
write(t, path, strings.Replace(read(t, path), `"model": "opus"`, `"model": "sonnet"`, 1))
p, err := e.service.PreviewRestore(id)
must(t, err)
if p.Blocked {
t.Fatalf("restore blocked: %+v", p.Changes)
}
_, err = e.service.Restore(id, p.Revision)
must(t, err)
got := read(t, path)
if strings.Contains(got, "echo guard") || !strings.Contains(got, `"model": "sonnet"`) || !strings.Contains(got, "echo mine") {
t.Fatalf("restore must undo only its write:\n%s", got)
}
// Ownership went back too: a sync republishes rather than conflicting.
sync(t, e.service)
if !strings.Contains(read(t, path), "echo guard") {
t.Fatal("sync after restore must republish the source")
}
// A backup whose output was edited since is a conflict.
backups, err := e.service.Backups()
must(t, err)
latest := backups[0].ID
write(t, path, strings.Replace(read(t, path), "echo guard", "echo tampered", 1))
p, err = e.service.PreviewRestore(latest)
must(t, err)
if !p.Blocked {
t.Fatal("restore must not overwrite newer changes")
}
if _, err := e.service.Restore(latest, p.Revision); !errors.Is(err, ErrConflict) {
t.Fatalf("want ErrConflict, got %v", err)
}
}
func TestRestore_WholeFileAndOwnershipScope(t *testing.T) {
e := newEnv(t)
ts := filepath.Join(e.home, ".config", "amp", "plugins", "skillshare-demo.ts")
r := save(t, e.service, Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"amp":`+adapterEntry["amp"]+`}}`)})
other := *e.service
other.ConfigPath = filepath.Join(filepath.Dir(e.config), "other.yaml")
write(t, other.ConfigPath, "targets: {}\n")
if _, err := other.PreviewRestore(r.BackupIDs[0]); err == nil {
t.Fatal("another config must not restore this config's backup")
}
if _, err := e.service.PreviewRestore("../../x"); err == nil {
t.Fatal("backup IDs must not traverse")
}
p, err := e.service.PreviewRestore(r.BackupIDs[0])
must(t, err)
_, err = e.service.Restore(r.BackupIDs[0], p.Revision)
must(t, err)
if exists(ts) {
t.Fatal("restoring a creation removes the file")
}
}
func TestMutate_SourceOnlySaveIgnoresBlockedNativeFiles(t *testing.T) {
e := newEnv(t)
write(t, filepath.Join(e.home, ".claude", "settings.json"), `{"hooks":`)
if _, err := e.service.Mutate(Mutation{Name: "guard", Entry: entry(t, claudeEntry)}, "", false); err != nil {
t.Fatalf("saving the definition must not need a readable native file: %v", err)
}
source, err := LoadSource(e.config)
must(t, err)
if _, ok := source.Entries["guard"]; !ok {
t.Fatal("definition not saved")
}
if _, err := e.service.Mutate(Mutation{}, "", true); err == nil {
t.Fatal("sync must still fail closed on the malformed file")
}
}
func TestSource_CodeRoundTripsVerbatimThroughYAML(t *testing.T) {
e := newEnv(t)
code := "export default function (pi) {\n\tpi.on(\"x\", () => {}); \n}\n\n// tail "
save(t, e.service, Mutation{Name: "demo", Entry: &Entry{Bindings: map[string]Binding{"pi": {Code: code}}}})
source, err := LoadSource(e.config)
must(t, err)
if source.Entries["demo"].Bindings["pi"].Code != code {
t.Fatalf("code changed through config.yaml: %q", source.Entries["demo"].Bindings["pi"].Code)
}
if read(t, filepath.Join(e.home, ".pi", "agent", "extensions", "skillshare-demo.ts")) != code {
t.Fatal("code changed on its way to Pi")
}
}
func TestMutate_ReplayedRevisionIsStale(t *testing.T) {
e := newEnv(t)
m := Mutation{Name: "guard", Entry: entry(t, claudeEntry)}
p, err := e.service.PreviewMutation(m)
must(t, err)
_, err = e.service.Mutate(m, p.Revision, true)
must(t, err)
if _, err := e.service.Mutate(m, p.Revision, true); !errors.Is(err, ErrStaleRevision) {
t.Fatalf("a replayed preview must be refused, got %v", err)
}
if n := len(events(t, filepath.Join(e.home, ".claude", "settings.json"), true)["PreToolUse"]); n != 1 {
t.Fatalf("replay must not duplicate: %d", n)
}
}
+399
View File
@@ -0,0 +1,399 @@
// Package hooks manages Agent hook declarations and their native configuration.
// It never executes hook commands or extension code and never changes native trust.
package hooks
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"path/filepath"
"regexp"
"slices"
"strings"
"gopkg.in/yaml.v3"
)
// Entry is one named hook under hooks.entries.
type Entry struct {
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Enabled defaults to true. A disabled entry keeps its definition and publishes nothing.
Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
// Bindings are keyed by canonical Agent name. An empty map publishes nothing.
Bindings map[string]Binding `yaml:"bindings" json:"bindings"`
}
// Project is what a project's own config would hold under hooks, declared in the
// global config under hooks.projects so one sync reaches every root.
type Project struct {
Entries map[string]Entry `yaml:"entries" json:"entries"`
}
// Binding is what one Agent receives. Command Agents use Events and Files, code Agents Code.
type Binding struct {
// Events is the Agent's own event map, written without translation.
Events map[string]any `yaml:"events,omitempty" json:"events,omitempty"`
// Code is one standalone native TypeScript/JavaScript extension or plugin.
Code string `yaml:"code,omitempty" json:"code,omitempty"`
// Files are script files written to <Agent config dir>/hooks/skillshare/<entry>/.
Files map[string]string `yaml:"files,omitempty" json:"files,omitempty"`
}
// IsEnabled reports the effective enabled state.
func (e Entry) IsEnabled() bool { return e.Enabled == nil || *e.Enabled }
// Target kinds.
const (
KindCommand = "command"
KindCode = "code"
)
// TargetDef describes one supported Agent.
type TargetDef struct {
Name string `json:"name"`
Kind string `json:"kind"`
// Note is static loading and trust guidance; Skillshare never infers loaded state.
Note string `json:"note"`
}
// Targets are the supported Agents in display order.
var Targets = []TargetDef{
{Name: "claude", Kind: KindCommand, Note: "Claude Code runs settings.json hooks only after the workspace trust dialog is accepted; /hooks lists them read-only."},
{Name: "codex", Kind: KindCommand, Note: "Codex loads hooks.json together with inline [hooks] in config.toml, which Skillshare leaves untouched and lists as an additional source. Review and trust each new or changed hook in /hooks; project hooks load only when the project's .codex folder is trusted."},
{Name: "gemini", Kind: KindCommand, Note: "Gemini CLI reads hooks from settings.json. Project hooks are fingerprinted and warn until trusted again after any change; manage them with /hooks panel."},
{Name: "copilot", Kind: KindCommand, Note: "GitHub Copilot loads every JSON file in its hooks folder (COPILOT_HOME/hooks, or .github/hooks in a project, which loads only in a trusted folder). Skillshare writes one skillshare-<entry>.json per hook."},
{Name: "cursor", Kind: KindCommand, Note: "Cursor reads hooks.json (version 1, lowerCamelCase events) and reloads it when it changes; project hooks need a trusted workspace."},
{Name: "droid", Kind: KindCommand, Note: "Factory Droid reads hooks.json, and settings.json hooks only while hooks.json is absent, so Skillshare never creates hooks.json over inline hooks. Droid snapshots hooks at startup; review changes in /hooks."},
{Name: "qwen", Kind: KindCommand, Note: "Qwen Code reads hooks from settings.json; project hooks load only in trusted folders. Opening /hooks reloads the definitions."},
{Name: "antigravity", Kind: KindCommand, Note: "Antigravity and its CLI (agy) share hooks.json: ~/.gemini/config/hooks.json globally and .agents/hooks.json in a project, where hooks load only in a trusted folder. Each hook is a named block; Skillshare writes one block per hook, named after it. The CLI can also read hooks from ~/.gemini/antigravity-cli/settings.json, which Skillshare leaves untouched."},
{Name: "pi", Kind: KindCode, Note: "Pi discovers extensions at startup; project extensions load only after project trust is granted. The code must use the extension API of your installed Pi version."},
{Name: "amp", Kind: KindCode, Note: "Amp runs plugins from its plugins folder with Bun; run 'plugins: reload' after sync. The code must use your Amp version's plugin API."},
{Name: "opencode", Kind: KindCode, Note: "OpenCode loads plugins from its plugins folder. v1 plugins are named exports and v2 plugins export default Plugin.define(...); Skillshare writes your code as given and never converts between them."},
}
// targetAliases are accepted spellings of canonical Agent names.
var targetAliases = map[string]string{"factory": "droid", "antigravity-cli": "antigravity", "agy": "antigravity"}
func targetDef(name string) (TargetDef, bool) {
for _, t := range Targets {
if t.Name == name {
return t, true
}
}
return TargetDef{}, false
}
// canonicalTarget resolves aliases; unknown names are returned unchanged.
func canonicalTarget(name string) string {
if alias, ok := targetAliases[name]; ok {
return alias
}
return name
}
var (
entryName = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$`)
fileName = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$`)
eventName = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]*$`)
)
// Errors that the HTTP layer maps to 409.
var (
ErrStaleRevision = errors.New("hooks configuration changed since preview; preview again")
ErrConflict = errors.New("hooks conflicts found; no files changed")
)
// ParseEntry reads one Entry from a JSON or YAML document and validates it.
func ParseEntry(data []byte) (Entry, error) {
var entry Entry
trimmed := bytes.TrimSpace(data)
if len(trimmed) > 0 && trimmed[0] == '{' {
d := json.NewDecoder(bytes.NewReader(trimmed))
d.DisallowUnknownFields()
if err := d.Decode(&entry); err != nil {
return Entry{}, fmt.Errorf("invalid hook entry JSON: %w", err)
}
if d.Decode(new(any)) != io.EOF {
return Entry{}, fmt.Errorf("hook entry must contain one JSON document")
}
} else {
d := yaml.NewDecoder(bytes.NewReader(trimmed))
d.KnownFields(true)
if err := d.Decode(&entry); err != nil {
return Entry{}, fmt.Errorf("invalid hook entry YAML: %w", err)
}
if d.Decode(new(yaml.Node)) != io.EOF {
return Entry{}, fmt.Errorf("hook entry must contain one YAML document")
}
}
if err := entry.normalize(); err != nil {
return Entry{}, err
}
return entry, entry.Validate("entry")
}
// normalize resolves aliases and gives events their JSON shape, so YAML integers and
// maps compare and hash the same as JSON ones.
func (e *Entry) normalize() error {
if e.Bindings == nil {
e.Bindings = map[string]Binding{}
}
bindings := map[string]Binding{}
for name, b := range e.Bindings {
canonical := canonicalTarget(name)
if _, dup := bindings[canonical]; dup {
return fmt.Errorf("duplicate binding for %s", canonical)
}
if b.Events != nil {
data, err := json.Marshal(b.Events)
if err != nil {
return fmt.Errorf("%s events: %w", canonical, err)
}
b.Events = map[string]any{}
if err := json.Unmarshal(data, &b.Events); err != nil {
return err
}
}
bindings[canonical] = b
}
e.Bindings = bindings
return nil
}
// Validate checks an entry against each Agent's native schema without executing it.
func (e Entry) Validate(name string) error {
if !entryName.MatchString(name) {
return fmt.Errorf("invalid hook name %q: use letters, digits, dots, underscores or hyphens", name)
}
for _, target := range sortedKeys(e.Bindings) {
def, ok := targetDef(target)
if !ok {
return fmt.Errorf("hook %s: unsupported Agent %q", name, target)
}
b := e.Bindings[target]
if def.Kind == KindCode {
if len(b.Events) > 0 || len(b.Files) > 0 {
return fmt.Errorf("hook %s: %s takes code only, not events or files", name, target)
}
if strings.TrimSpace(b.Code) == "" {
return fmt.Errorf("hook %s: %s requires code", name, target)
}
continue
}
if b.Code != "" {
return fmt.Errorf("hook %s: %s takes events, not code", name, target)
}
if len(b.Events) == 0 {
return fmt.Errorf("hook %s: %s requires at least one event", name, target)
}
if err := validateEvents(target, b.Events); err != nil {
return fmt.Errorf("hook %s: %s: %w", name, target, err)
}
for file := range b.Files {
if !fileName.MatchString(file) || !filepath.IsLocal(file) {
return fmt.Errorf("hook %s: %s: file %q must be a plain file name", name, target, file)
}
}
}
return nil
}
// validateEvents checks the structure every Agent documents, leaving event names,
// matchers, timeouts and payloads exactly as the Agent defines them.
func validateEvents(target string, events map[string]any) error {
for _, event := range sortedKeys(events) {
if !eventName.MatchString(event) {
return fmt.Errorf("invalid event name %q", event)
}
if target == "cursor" && (event[0] < 'a' || event[0] > 'z') {
return fmt.Errorf("event %q: Cursor uses lowerCamelCase event names", event)
}
items, ok := events[event].([]any)
if !ok || len(items) == 0 {
return fmt.Errorf("event %s must be a non-empty array", event)
}
for i, item := range items {
obj, ok := item.(map[string]any)
if !ok {
return fmt.Errorf("event %s[%d] must be an object", event, i)
}
if err := validateElement(target, event, obj); err != nil {
return fmt.Errorf("event %s[%d]: %w", event, i, err)
}
}
}
return nil
}
func validateElement(target, event string, obj map[string]any) error {
switch target {
case "cursor":
if kind, set := obj["type"]; set && kind != "command" && kind != "prompt" {
return fmt.Errorf("type must be command or prompt")
}
if obj["type"] == "prompt" {
return requireString(obj, "prompt")
}
return requireString(obj, "command")
case "copilot":
return validateCopilot(event, obj)
case "antigravity":
return validateAntigravity(obj)
}
// Matcher groups: Claude, Codex, Gemini, Qwen and Droid.
if matcher, set := obj["matcher"]; set {
if _, ok := matcher.(string); !ok {
return fmt.Errorf("matcher must be a string")
}
}
handlers, ok := obj["hooks"].([]any)
if !ok || len(handlers) == 0 {
return fmt.Errorf("requires a non-empty hooks array")
}
for i, h := range handlers {
handler, ok := h.(map[string]any)
if !ok {
return fmt.Errorf("hooks[%d] must be an object", i)
}
if err := requireString(handler, "type"); err != nil {
return fmt.Errorf("hooks[%d]: %w", i, err)
}
if handler["type"] == "command" {
if err := requireString(handler, "command"); err != nil {
return fmt.Errorf("hooks[%d]: %w", i, err)
}
}
if timeout, set := handler["timeout"]; set {
if n, ok := timeout.(float64); !ok || n <= 0 {
return fmt.Errorf("hooks[%d]: timeout must be a positive number", i)
}
}
}
return nil
}
// validateAntigravity checks a matcher group (PreToolUse, PostToolUse) or, for the other
// events, a handler listed directly under the event. type defaults to command.
func validateAntigravity(obj map[string]any) error {
handlers := []any{obj}
if _, grouped := obj["hooks"]; grouped {
if matcher, set := obj["matcher"]; set {
if _, ok := matcher.(string); !ok {
return fmt.Errorf("matcher must be a string")
}
}
list, ok := obj["hooks"].([]any)
if !ok || len(list) == 0 {
return fmt.Errorf("requires a non-empty hooks array")
}
handlers = list
}
for i, h := range handlers {
handler, ok := h.(map[string]any)
if !ok {
return fmt.Errorf("hooks[%d] must be an object", i)
}
if kind, set := handler["type"]; set && kind != "command" {
return fmt.Errorf("hooks[%d]: type must be command", i)
}
if err := requireString(handler, "command"); err != nil {
return fmt.Errorf("hooks[%d]: %w", i, err)
}
if timeout, set := handler["timeout"]; set {
if n, ok := timeout.(float64); !ok || n <= 0 {
return fmt.Errorf("hooks[%d]: timeout must be a positive number", i)
}
}
}
return nil
}
// validateCopilot checks the required fields and exclusive forms of Copilot's flat
// handlers, leaving every field as written.
func validateCopilot(event string, obj map[string]any) error {
for _, key := range []string{"timeoutSec", "timeout"} {
if value, set := obj[key]; set {
if n, ok := value.(float64); !ok || n <= 0 {
return fmt.Errorf("%s must be a positive number", key)
}
}
}
switch obj["type"] {
case "http":
if err := requireString(obj, "url"); err != nil {
return err
}
u, err := url.Parse(obj["url"].(string))
if err != nil || u.Host == "" || u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("url must be an http:// or https:// URL")
}
_, envVars := obj["allowedEnvVars"]
if u.Scheme != "https" && (envVars || event == "preToolUse" || event == "permissionRequest" || event == "PreToolUse" || event == "PermissionRequest") {
return fmt.Errorf("url must use https:// here")
}
return nil
case "prompt":
if !strings.EqualFold(event, "sessionStart") {
return fmt.Errorf("prompt hooks are only supported on sessionStart")
}
return requireString(obj, "prompt")
case nil, "command":
default:
return fmt.Errorf("type must be command, http or prompt")
}
shell := false
for _, key := range []string{"bash", "powershell", "command"} {
if _, set := obj[key]; set {
if err := requireString(obj, key); err != nil {
return err
}
shell = true
}
}
if _, set := obj["exec"]; set {
if shell {
return fmt.Errorf("exec cannot be combined with bash, powershell or command")
}
if err := requireString(obj, "exec"); err != nil {
return err
}
if args, set := obj["args"]; set {
list, ok := args.([]any)
for _, arg := range list {
if _, isString := arg.(string); !isString {
ok = false
}
}
if !ok {
return fmt.Errorf("args must be an array of strings")
}
}
return nil
}
if _, set := obj["args"]; set {
return fmt.Errorf("args are passed to exec only")
}
if !shell {
return fmt.Errorf("requires bash, powershell, command or exec")
}
return nil
}
func requireString(obj map[string]any, key string) error {
if s, ok := obj[key].(string); !ok || strings.TrimSpace(s) == "" {
return fmt.Errorf("%s must be a non-empty string", key)
}
return nil
}
func sortedKeys[T any](m map[string]T) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
slices.Sort(keys)
return keys
}
+505
View File
@@ -0,0 +1,505 @@
package hooks
import (
"bytes"
"encoding/json"
"fmt"
"os"
"regexp"
"sort"
"strings"
"github.com/tailscale/hujson"
)
// nativeDoc is one shared hooks file of a command Agent: Claude, Gemini and Qwen
// settings.json, Codex and Cursor hooks.json under "hooks", and Droid's hooks.json,
// whose top level is the event map. Antigravity's hooks.json maps hook names to
// blocks of events; each block is held as the only element of an "event" named after
// it, so the same ownership rules apply to whole blocks. Edits touch only the event
// arrays or blocks they change, so comments, order and every other setting keep
// their bytes.
type nativeDoc struct {
target string
data []byte
value hujson.Value
// events holds each event's elements in their JSON shape, in file order.
events map[string][]any
// hasSection reports an existing event map: a "hooks" key, or Droid's whole file.
hasSection bool
}
// skeleton reports a shared file left with only what Skillshare writes into a new one:
// an empty object, or Cursor's version header. A comment or trailing comma is the
// user's, and strict JSON rejects both.
func skeleton(target string, data []byte) bool {
var doc map[string]any
if json.Unmarshal(data, &doc) != nil || doc == nil {
return false
}
if target == "cursor" && doc["version"] == float64(1) {
delete(doc, "version")
}
return len(doc) == 0
}
// wrapped reports whether the event map sits under a "hooks" key.
func wrapped(target string) bool { return target != "droid" && target != "antigravity" }
func uniqueJSON(v *hujson.Value) error {
switch value := v.Value.(type) {
case *hujson.Object:
seen := map[string]bool{}
for i := range value.Members {
name := literalString(value.Members[i].Name)
if seen[name] {
return fmt.Errorf("duplicate JSON property %q", name)
}
seen[name] = true
if err := uniqueJSON(&value.Members[i].Value); err != nil {
return err
}
}
case *hujson.Array:
for i := range value.Elements {
if err := uniqueJSON(&value.Elements[i]); err != nil {
return err
}
}
}
return nil
}
func literalString(v hujson.Value) string {
if lit, ok := v.Value.(hujson.Literal); ok {
return lit.String()
}
return ""
}
// parseNative fails closed on malformed files, duplicate properties and event
// values that are not arrays; the file is then never edited.
func parseNative(target string, data []byte) (*nativeDoc, error) {
n := &nativeDoc{target: target, data: data, events: map[string][]any{}}
if len(bytes.TrimSpace(data)) == 0 {
data = []byte("{}\n")
n.data = data
}
var err error
if n.value, err = hujson.Parse(data); err != nil {
return nil, fmt.Errorf("invalid JSON/JSONC; file was not changed")
}
if err := uniqueJSON(&n.value); err != nil {
return nil, err
}
standard := n.value.Clone()
standard.Standardize()
var document map[string]any
if err := json.Unmarshal(standard.Pack(), &document); err != nil || document == nil {
return nil, fmt.Errorf("configuration must be a JSON object")
}
if target == "cursor" {
if version, ok := document["version"]; ok && version != float64(1) {
return nil, fmt.Errorf("unsupported Cursor hooks version %v; only version 1 is supported", version)
}
}
if target == "antigravity" {
n.hasSection = true
for name, raw := range document {
block, ok := raw.(map[string]any)
if !ok {
return nil, fmt.Errorf("hook %q must be an object", name)
}
// enabled defaults to true, so an explicit true is the same block.
if block["enabled"] == true {
delete(block, "enabled")
}
n.events[name] = []any{block}
}
return n, nil
}
section := document
n.hasSection = true
if wrapped(target) {
raw, ok := document["hooks"]
if !ok {
n.hasSection = false
return n, nil
}
if section, ok = raw.(map[string]any); !ok {
return nil, fmt.Errorf("hooks must be an object")
}
}
for event, raw := range section {
items, ok := raw.([]any)
if !ok {
return nil, fmt.Errorf("hooks event %q must be an array", event)
}
n.events[event] = items
}
return n, nil
}
// elementHash identifies element content; ownership is never inferred from it alone.
func elementHash(v any) string {
data, _ := json.Marshal(v)
return digest(data)
}
// sectionDigest identifies only the hooks, so an Agent may rewrite its other
// settings between preview and apply.
func (n *nativeDoc) sectionDigest() string {
data, _ := json.Marshal(n.events)
return digest(data)
}
// elementOp changes one array element. Index is the element's position in the file
// as read; -1 appends. A nil Value removes the element at Index.
type elementOp struct {
Key string `json:"key"`
Event string `json:"event"`
Index int `json:"index"`
Value any `json:"value,omitempty"`
Before any `json:"before,omitempty"`
}
// edit applies ops and returns the new bytes plus the final index of each op key
// and each tracked key (event -> original index -> key). With drop, a hooks key the
// edit leaves empty is removed. The output keeps the file's style: a single-line file
// stays compact, an indented one keeps its indent unit. It fails when an op no longer
// fits the file, which callers have already ruled out by comparing section digests.
func (n *nativeDoc) edit(ops []elementOp, track map[string]map[int]string, drop bool) ([]byte, map[string]int, error) {
positions := map[string]int{}
if len(ops) == 0 {
return append([]byte(nil), n.data...), positions, nil
}
v := n.value.Clone()
root, ok := v.Value.(*hujson.Object)
if !ok {
return nil, nil, fmt.Errorf("configuration must be a JSON object")
}
indent := detectIndent(root)
fresh := len(root.Members) == 0
compact := !fresh && !bytes.Contains(bytes.TrimSpace(n.data), []byte("\n"))
if n.target == "antigravity" {
if err := n.editBlocks(root, ops, indent, positions); err != nil {
return nil, nil, err
}
return n.finish(&v, root, fresh, compact, positions)
}
section := root
depth := 1
if wrapped(n.target) {
if n.target == "cursor" && member(root, "version") == nil {
addMember(root, "version", hujson.Value{Value: hujson.Int(1)}, indent)
}
m := member(root, "hooks")
if m == nil {
m = addMember(root, "hooks", hujson.Value{Value: &hujson.Object{}}, indent)
}
if section, ok = m.Value.Value.(*hujson.Object); !ok {
return nil, nil, fmt.Errorf("hooks must be an object")
}
depth = 2
}
byEvent := map[string][]elementOp{}
for _, op := range ops {
byEvent[op.Event] = append(byEvent[op.Event], op)
}
for _, event := range sortedKeys(byEvent) {
m := member(section, event)
if m == nil {
m = addMember(section, event, hujson.Value{Value: &hujson.Array{}}, strings.Repeat(indent, depth))
}
arr, ok := m.Value.Value.(*hujson.Array)
if !ok {
return nil, nil, fmt.Errorf("hooks event %q must be an array", event)
}
// ids follow each original element through the edit to its final index.
ids := make([]string, len(arr.Elements))
for i, key := range track[event] {
if i < len(ids) {
ids[i] = key
}
}
// A one-line array keeps its elements on that line, with the line's own separators.
line := hujson.Value{Value: arr}.Pack()
inline := len(arr.Elements) > 0 && !bytes.Contains(line, []byte("\n"))
colon, comma := separators(line)
// like is the element being replaced, whose key order the new one keeps.
layout := func(v any, like *hujson.Value) (hujson.Value, error) {
value, err := formatted(v, indent, depth+1)
if err != nil {
return value, err
}
if like != nil {
keepKeyOrder(&value, *like)
}
if inline {
value.Minimize()
spaceOut(&value, colon, comma)
}
return value, nil
}
removed := map[int]bool{}
var appended []elementOp
for _, op := range byEvent[event] {
switch {
case op.Index < 0:
appended = append(appended, op)
case op.Index >= len(arr.Elements):
return nil, nil, fmt.Errorf("hooks event %q changed; preview again", event)
case op.Value == nil:
removed[op.Index] = true
default:
value, err := layout(op.Value, &arr.Elements[op.Index])
if err != nil {
return nil, nil, err
}
value.BeforeExtra = arr.Elements[op.Index].BeforeExtra
arr.Elements[op.Index] = value
ids[op.Index] = op.Key
}
}
var kept []hujson.Value
var keptIDs []string
for i, element := range arr.Elements {
if !removed[i] {
kept = append(kept, element)
keptIDs = append(keptIDs, ids[i])
}
}
for _, op := range appended {
value, err := layout(op.Value, nil)
if err != nil {
return nil, nil, err
}
value.BeforeExtra = hujson.Extra("\n" + strings.Repeat(indent, depth+1))
if inline {
value.BeforeExtra = hujson.Extra(" ")
}
kept = append(kept, value)
keptIDs = append(keptIDs, op.Key)
}
if len(kept) == 0 && len(arr.Elements) > 0 {
// Skillshare removed the last element, so it drops the event it emptied.
removeMember(section, event)
continue
}
arr.Elements = kept
if len(appended) > 0 && !inline && !bytes.Contains(arr.AfterExtra, []byte("\n")) {
arr.AfterExtra = hujson.Extra("\n" + strings.Repeat(indent, depth))
}
for i, id := range keptIDs {
if id != "" {
positions[id] = i
}
}
}
switch {
case len(section.Members) == 0 && drop && section != root:
removeMember(root, "hooks")
case len(section.Members) == 0:
section.AfterExtra = nil
case !bytes.Contains(section.AfterExtra, []byte("\n")):
section.AfterExtra = hujson.Extra("\n" + strings.Repeat(indent, depth-1))
}
return n.finish(&v, root, fresh, compact, positions)
}
// finish lays out the edited document in the file's style and checks it parses.
func (n *nativeDoc) finish(v *hujson.Value, root *hujson.Object, fresh, compact bool, positions map[string]int) ([]byte, map[string]int, error) {
if len(root.Members) == 0 {
root.AfterExtra = nil
} else if fresh || !bytes.Contains(root.AfterExtra, []byte("\n")) {
root.AfterExtra = hujson.Extra("\n")
}
if compact {
v.Minimize()
}
out := v.Pack()
if !bytes.HasSuffix(out, []byte("\n")) {
out = append(out, '\n')
}
if _, err := parseNative(n.target, out); err != nil {
return nil, nil, fmt.Errorf("cannot safely edit hooks: %w", err)
}
return out, positions, nil
}
// editBlocks adds, replaces or removes Antigravity's named blocks, one per op.
func (n *nativeDoc) editBlocks(root *hujson.Object, ops []elementOp, indent string, positions map[string]int) error {
for _, op := range ops {
m := member(root, op.Event)
switch {
case op.Value == nil:
removeMember(root, op.Event)
continue
case op.Index < 0 && m != nil, op.Index >= 0 && m == nil:
return fmt.Errorf("hook %q changed; preview again", op.Event)
}
value, err := formatted(op.Value, indent, 1)
if err != nil {
return err
}
if m == nil {
addMember(root, op.Event, value, indent)
} else {
value.BeforeExtra = m.Value.BeforeExtra
m.Value = value
}
positions[op.Key] = 0
}
return nil
}
func member(obj *hujson.Object, name string) *hujson.ObjectMember {
for i := range obj.Members {
if literalString(obj.Members[i].Name) == name {
return &obj.Members[i]
}
}
return nil
}
func addMember(obj *hujson.Object, name string, value hujson.Value, indent string) *hujson.ObjectMember {
key := hujson.Value{BeforeExtra: hujson.Extra("\n" + indent), Value: hujson.String(name)}
value.BeforeExtra = hujson.Extra(" ")
obj.Members = append(obj.Members, hujson.ObjectMember{Name: key, Value: value})
return &obj.Members[len(obj.Members)-1]
}
func removeMember(obj *hujson.Object, name string) {
for i := range obj.Members {
if literalString(obj.Members[i].Name) == name {
obj.Members = append(obj.Members[:i], obj.Members[i+1:]...)
return
}
}
}
// detectIndent reuses the file's indent unit, two spaces for a new file.
func detectIndent(root *hujson.Object) string {
if len(root.Members) > 0 {
before := string(root.Members[0].Name.BeforeExtra)
if i := strings.LastIndex(before, "\n"); i >= 0 {
if ws := before[i+1:]; ws != "" && strings.TrimLeft(ws, " \t") == "" {
return ws
}
}
}
return " "
}
// separators reports whether a one-line JSON text puts a space after its colons
// and after its commas. Without any comma, commas follow the colons.
func separators(line []byte) (colon, comma bool) {
colon = colonSpace.Match(line)
comma = colon
if bytes.Contains(line, []byte(",")) {
comma = commaSpace.Match(line)
}
return colon, comma
}
var (
colonSpace = regexp.MustCompile(`"\s*:[ \t]`)
commaSpace = regexp.MustCompile(`,[ \t]`)
)
// spaceOut puts single spaces after the colons and commas of a minimized value.
func spaceOut(v *hujson.Value, colon, comma bool) {
after := func(on bool) hujson.Extra {
if on {
return hujson.Extra(" ")
}
return nil
}
switch value := v.Value.(type) {
case *hujson.Object:
for i := range value.Members {
m := &value.Members[i]
if i > 0 {
m.Name.BeforeExtra = after(comma)
}
m.Value.BeforeExtra = after(colon)
spaceOut(&m.Value, colon, comma)
}
case *hujson.Array:
for i := range value.Elements {
if i > 0 {
value.Elements[i].BeforeExtra = after(comma)
}
spaceOut(&value.Elements[i], colon, comma)
}
}
}
// keepKeyOrder orders v's object keys as they are in like, at every depth;
// keys like does not have follow in their own order.
func keepKeyOrder(v *hujson.Value, like hujson.Value) {
switch value := v.Value.(type) {
case *hujson.Object:
old, ok := like.Value.(*hujson.Object)
if !ok || len(value.Members) == 0 {
return
}
rank := map[string]int{}
for i, m := range old.Members {
rank[literalString(m.Name)] = i
}
pos := func(m hujson.ObjectMember) int {
if i, ok := rank[literalString(m.Name)]; ok {
return i
}
return len(old.Members)
}
// Every member but the first carries the same layout, so moving whole members keeps it.
first := value.Members[0].Name.BeforeExtra
sort.SliceStable(value.Members, func(i, j int) bool { return pos(value.Members[i]) < pos(value.Members[j]) })
for i := range value.Members {
value.Members[i].Name.BeforeExtra = first
if j, ok := rank[literalString(value.Members[i].Name)]; ok {
keepKeyOrder(&value.Members[i].Value, old.Members[j].Value)
}
}
case *hujson.Array:
old, ok := like.Value.(*hujson.Array)
if !ok {
return
}
for i := range value.Elements {
if i < len(old.Elements) {
keepKeyOrder(&value.Elements[i], old.Elements[i])
}
}
}
}
// formatted encodes a value laid out at depth, so written elements stay readable.
func formatted(value any, indent string, depth int) (hujson.Value, error) {
var text bytes.Buffer
encoder := json.NewEncoder(&text)
encoder.SetEscapeHTML(false)
encoder.SetIndent(strings.Repeat(indent, depth), indent)
if err := encoder.Encode(value); err != nil {
return hujson.Value{}, err
}
return hujson.Parse(bytes.TrimSpace(text.Bytes()))
}
// safeRead refuses symlinks and non-regular files at native destinations.
func safeRead(path string) ([]byte, bool, os.FileMode, error) {
info, err := os.Lstat(path)
if os.IsNotExist(err) {
return nil, false, 0, nil
}
if err != nil {
return nil, false, 0, err
}
if !info.Mode().IsRegular() {
return nil, false, 0, fmt.Errorf("hooks file must be a regular file, not a symlink or directory: %s", path)
}
data, err := os.ReadFile(path)
return data, true, info.Mode().Perm(), err
}
+937
View File
@@ -0,0 +1,937 @@
package hooks
import (
"encoding/json"
"fmt"
"maps"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"skillshare/internal/projectdir"
)
// record is Skillshare's ownership of one native output, kept outside native files.
// An array element is identified by this record plus its content hash, with the last
// written index only breaking ties between identical elements; neither index nor
// equality alone ever claims an element.
type record struct {
Owner string `json:"owner"`
Target string `json:"target"`
Path string `json:"path"`
Root string `json:"root,omitempty"`
Entry string `json:"entry"`
Event string `json:"event,omitempty"`
Ordinal int `json:"ordinal,omitempty"`
Index int `json:"index,omitempty"`
// Peers is how many identical elements the event held when Skillshare last wrote or
// synced it. A different count now means a copy was added or deleted and nobody can
// tell whose, so the record no longer locates any of them.
Peers int `json:"peers,omitempty"`
Hash string `json:"hash"`
// Adopted marks a registration an import claimed without syncing; the next sync
// reports it as adopted once, then as unchanged.
Adopted bool `json:"adopted,omitempty"`
}
type ledger struct {
Version int `json:"version"`
Records map[string]record `json:"records"`
// Created are shared files whose hooks key Skillshare added, so it removes the key
// again when it removes the last hook there.
Created map[string]bool `json:"created,omitempty"`
// NewFiles are shared files that did not exist before Skillshare wrote them, so
// it deletes them once they hold nothing but what Skillshare put there.
NewFiles map[string]bool `json:"newFiles,omitempty"`
// Dirs are folders Skillshare created for its files, removed again once empty.
Dirs map[string]bool `json:"dirs,omitempty"`
}
func elementKey(owner, root, path, event, entry string, ordinal int) string {
return digest(fmt.Appendf(nil, "element\x00%s\x00%s\x00%s\x00%s\x00%s\x00%d", owner, root, path, event, entry, ordinal))
}
// fileKey is one whole file; a path has at most one owner.
func fileKey(path string) string { return digest([]byte("file\x00" + path)) }
// ownerGone reports a missing owning config, the one case where it can never
// release its outputs and an explicit replace may take them over.
func ownerGone(path string) bool {
_, err := os.Lstat(path)
return os.IsNotExist(err)
}
const (
kindJSON = "json"
kindFile = "file"
)
type filePlan struct {
path, target, root string
// base is where no symlink may redirect the write; apply checks it again.
base string
kind string
before, after []byte
exists bool
mode os.FileMode
// section identifies what apply rechecks: the hooks of a shared file, or a whole file.
section string
ops []elementOp
// write is a whole file's new content; remove deletes it.
write []byte
remove bool
// keys are the ledger records this file's changes move.
keys []string
// created drops the hooks key once the edit empties it, because Skillshare added it.
created bool
}
func (f *filePlan) changed() bool {
if f.kind == kindJSON {
return len(f.ops) > 0
}
return f.write != nil || f.remove
}
type wantElement struct {
target, path, root, entry, event string
ordinal int
value any
}
type wantFile struct {
target, path, root, entry string
content []byte
mode os.FileMode
}
type desired struct {
elements map[string][]wantElement // by path
targets map[string]string // path -> target
roots map[string]string // path -> root
files map[string]wantFile
notes []Change
}
func (s *Service) scoped(root string) *Service {
c := *s
c.ProjectRoot = root
return &c
}
// ownConfig reports a root with its own Skillshare config, which the global config
// cannot manage.
func ownConfig(root string) bool {
_, ok := projectdir.Find(root)
return ok
}
// render builds every native output the source asks for. A global source's projects
// land in the same plan, so one revision and one owner cover every root.
func (s *Service) render(source *Source) (*desired, error) {
d := &desired{elements: map[string][]wantElement{}, targets: map[string]string{}, roots: map[string]string{}, files: map[string]wantFile{}}
if s.ProjectRoot != "" && len(source.Projects) > 0 {
return nil, fmt.Errorf("hooks.projects belongs in the global config")
}
if err := s.renderScope(d, "", source.Entries); err != nil {
return nil, err
}
for _, root := range sortedKeys(source.Projects) {
if ownConfig(root) {
d.notes = append(d.notes, Change{Path: root, Root: root, Action: "conflict", Message: "project has its own Skillshare config; manage its hooks there with -p"})
continue
}
if err := s.scoped(root).renderScope(d, root, source.Projects[root].Entries); err != nil {
return nil, err
}
}
return d, nil
}
func (s *Service) renderScope(d *desired, root string, entries map[string]Entry) error {
addFile := func(f wantFile) error {
if _, dup := d.files[f.path]; dup {
return fmt.Errorf("two hooks write %s", f.path)
}
d.files[f.path] = f
return nil
}
for _, name := range sortedKeys(entries) {
entry := entries[name]
if !entry.IsEnabled() {
continue
}
for _, target := range sortedKeys(entry.Bindings) {
b := entry.Bindings[target]
def, _ := targetDef(target)
if def.Kind == KindCode || target == "copilot" {
path, err := s.codePath(target, name)
if err != nil {
return err
}
content := []byte(b.Code)
if target == "copilot" {
data, err := json.MarshalIndent(map[string]any{"version": 1, "hooks": b.Events}, "", " ")
if err != nil {
return err
}
content = append(data, '\n')
}
if err := addFile(wantFile{target: target, path: path, root: root, entry: name, content: content, mode: 0644}); err != nil {
return err
}
} else {
path, err := s.nativePath(target)
if err != nil {
return err
}
d.targets[path], d.roots[path] = target, root
if target == "antigravity" {
// One named block per hook, holding its whole event map.
d.elements[path] = append(d.elements[path], wantElement{target: target, path: path, root: root, entry: name, event: name, value: b.Events})
continue
}
for _, event := range sortedKeys(b.Events) {
for i, value := range b.Events[event].([]any) {
d.elements[path] = append(d.elements[path], wantElement{target: target, path: path, root: root, entry: name, event: event, ordinal: i, value: value})
}
}
}
if len(b.Files) == 0 {
continue
}
dir, err := s.scriptDir(target, name)
if err != nil {
return err
}
for _, file := range sortedKeys(b.Files) {
if err := addFile(wantFile{target: target, path: filepath.Join(dir, file), root: root, entry: name, content: []byte(b.Files[file]), mode: 0755}); err != nil {
return err
}
}
}
}
return nil
}
// base is the directory below which no symlink may redirect a write.
func (s *Service) base(target, root string) (string, error) {
if root != "" {
return root, nil
}
if s.ProjectRoot != "" {
return s.ProjectRoot, nil
}
return s.configDir(target)
}
// checkPath rejects symlinks between base and path, so a link can never send a
// write outside the Agent's folder or the project. base itself may be a link.
func checkPath(base, path string) error {
rel, err := filepath.Rel(base, path)
if err != nil || !filepath.IsLocal(rel) {
return fmt.Errorf("hooks path %s is outside %s", path, base)
}
current := base
for _, part := range strings.Split(rel, string(filepath.Separator)) {
current = filepath.Join(current, part)
info, err := os.Lstat(current)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("refusing to write through symlink %s", current)
}
}
return nil
}
func (s *Service) loadLedger() (ledger, []byte, error) {
state := ledger{Version: 1, Records: map[string]record{}}
pending, written, err := s.readPending()
if err != nil {
return state, nil, err
}
if written {
data, err := json.MarshalIndent(pending.State, "", " ")
return pending.State, append(data, '\n'), err
}
data, exists, _, err := safeRead(s.statePath())
if err != nil {
return state, nil, err
}
if exists {
if json.Unmarshal(data, &state) != nil || state.Version != 1 || state.Records == nil {
return state, nil, fmt.Errorf("hooks ownership state is invalid; restore a backup or import hooks again")
}
}
return state, data, nil
}
// locate finds each record's element: same event, same content hash, never two records
// on one element. Identical elements are resolved only while their number matches both
// the records holding that content and the count at the last write or sync; any copy
// added or removed since makes identity ambiguous, so none of them is located and the
// plan reports a conflict instead of guessing by position. The last written index only
// orders records among identical elements that all belong to Skillshare.
func locate(doc *nativeDoc, records map[string]record) map[string]int {
found := map[string]int{}
taken := map[string]map[int]bool{}
keys := sortedKeys(records)
slices.SortStableFunc(keys, func(a, b string) int { return records[a].Index - records[b].Index })
hashes := map[string][]string{}
counts := map[string]int{}
for event, items := range doc.events {
for _, item := range items {
h := elementHash(item)
hashes[event] = append(hashes[event], h)
counts[event+"\x00"+h]++
}
}
holders := map[string]int{}
for _, r := range records {
holders[r.Event+"\x00"+r.Hash]++
}
for _, key := range keys {
r := records[key]
group := r.Event + "\x00" + r.Hash
if counts[group] != holders[group] || r.Peers != 0 && counts[group] != r.Peers {
continue
}
best := -1
for i, h := range hashes[r.Event] {
if h != r.Hash || taken[r.Event][i] {
continue
}
if best < 0 || abs(i-r.Index) < abs(best-r.Index) {
best = i
}
}
if best >= 0 {
if taken[r.Event] == nil {
taken[r.Event] = map[int]bool{}
}
taken[r.Event][best] = true
found[key] = best
}
}
return found
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
type planner struct {
s *Service
source *Source
p *Plan
replace map[string]bool // root + "\x00" + entry
adopt map[string]bool // root + "\x00" + entry
changes map[string]*Change
order []string
// events is each change's event detail: event -> added, updated or removed.
events map[string]map[string]string
}
func changeKey(target, path, root, entry string) string {
return target + "\x00" + path + "\x00" + root + "\x00" + entry
}
// event records what one change does to one event; "updated" wins over the others.
func (pl *planner) event(target, path, root, entry, event, kind string) {
key := changeKey(target, path, root, entry)
if pl.events[key] == nil {
pl.events[key] = map[string]string{}
}
if pl.events[key][event] != "updated" {
pl.events[key][event] = kind
}
}
func (pl *planner) eventChanges(key string) *EventChanges {
events := pl.events[key]
if len(events) == 0 {
return nil
}
out := &EventChanges{}
for _, event := range sortedKeys(events) {
switch events[event] {
case "added":
out.Added = append(out.Added, event)
case "removed":
out.Removed = append(out.Removed, event)
default:
out.Updated = append(out.Updated, event)
}
}
return out
}
// keeps reports an action after which the entry still has registrations in the file.
func keeps(action string) bool {
return action == "add" || action == "update" || action == "unchanged" || action == "adopt"
}
func (pl *planner) note(target, path, root, entry, action, message string) {
key := changeKey(target, path, root, entry)
c, ok := pl.changes[key]
if !ok {
c = &Change{Target: target, Path: path, Name: entry, Root: root, Action: action, Message: message}
pl.changes[key] = c
pl.order = append(pl.order, key)
return
}
rank := map[string]int{"unchanged": 0, "adopt": 1, "release": 2, "add": 3, "remove": 3, "update": 4, "conflict": 5}
// An entry that leaves some events but keeps others in the file updates it; remove
// means it leaves the file entirely.
switch {
case action == c.Action:
case action == "remove" && keeps(c.Action) || c.Action == "remove" && keeps(action):
if c.Action != "update" {
c.Action, c.Message = "update", ""
}
case rank[action] > rank[c.Action] && action != "remove":
c.Action, c.Message = action, message
}
}
// Preview reads source, ownership and native files without writing.
func (s *Service) Preview() (*Plan, error) {
source, err := LoadSource(s.ConfigPath)
if err != nil {
return nil, err
}
return s.previewSource(source, nil, nil)
}
// previewSource plans a sync; replace and adopt are root + "\x00" + entry sets.
func (s *Service) previewSource(source *Source, replace, adopt map[string]bool) (*Plan, error) {
state, stateBytes, err := s.loadLedger()
if err != nil {
return nil, err
}
// A hook the draft stops managing already plans as the user's own.
source.forget(state)
d, err := s.render(source)
if err != nil {
return nil, err
}
p := &Plan{SourcePath: source.ConfigPath, Changes: []Change{}, Warnings: []string{}, source: source, stateBytes: stateBytes, state: ledger{Version: 1, Records: maps.Clone(state.Records), Created: maps.Clone(state.Created), NewFiles: maps.Clone(state.NewFiles), Dirs: maps.Clone(state.Dirs)}}
pl := &planner{s: s, source: source, p: p, replace: replace, adopt: adopt, changes: map[string]*Change{}, events: map[string]map[string]string{}}
for _, name := range sortedKeys(source.Entries) {
p.Warnings = append(p.Warnings, EventWarnings(name, source.Entries[name])...)
}
for _, root := range sortedKeys(source.Projects) {
entries := source.Projects[root].Entries
for _, name := range sortedKeys(entries) {
p.Warnings = append(p.Warnings, EventWarnings(name, entries[name])...)
}
}
owner := source.ConfigPath
// A file the source no longer writes still needs a plan, to remove what it left there.
for _, r := range state.Records {
if r.Owner != owner {
continue
}
if r.Event != "" {
if _, ok := d.targets[r.Path]; !ok {
d.targets[r.Path], d.roots[r.Path] = r.Target, r.Root
}
} else if _, ok := d.files[r.Path]; !ok {
d.files[r.Path] = wantFile{target: r.Target, path: r.Path, root: r.Root, entry: r.Entry}
}
}
proposal, _ := json.Marshal(struct {
Entries map[string]Entry
Projects map[string]Project
Replace []string
}{source.Entries, source.Projects, sortedKeys(replace)})
revision := digest(source.bytes) + digest(stateBytes) + digest(proposal)
owned, _ := json.Marshal(state)
fingerprint := digest(proposal) + digest(owned)
for _, note := range d.notes {
p.Changes = append(p.Changes, note)
p.Blocked = true
}
for _, path := range sortedKeys(d.targets) {
f, err := pl.planShared(path, d.targets[path], d.roots[path], d.elements[path], state)
if err != nil {
return nil, err
}
revision += path + f.section
p.files = append(p.files, f)
}
for _, path := range sortedKeys(d.files) {
f, err := pl.planFile(d.files[path], state)
if err != nil {
return nil, err
}
revision += path + f.section
p.files = append(p.files, f)
}
for _, f := range p.files {
fingerprint += fmt.Sprintf("%s\x00%s\x00%t\x00%s\n", f.path, f.kind, f.exists, f.section)
}
for _, key := range pl.order {
c := pl.changes[key]
c.Events = pl.eventChanges(key)
if c.Action == "conflict" {
p.Blocked = true
}
p.Changes = append(p.Changes, *c)
}
p.Revision = digest([]byte(revision))
changes, _ := json.Marshal(p.Changes)
p.Fingerprint = digest([]byte(fmt.Sprintf("%s%s\x00%t\x00%s", fingerprint, source.ConfigPath, p.Blocked, digest(changes))))
return p, nil
}
func (pl *planner) replaces(root, entry string) bool { return pl.replace[root+"\x00"+entry] }
func (pl *planner) adopts(root, entry string) bool { return pl.adopt[root+"\x00"+entry] }
func (pl *planner) planShared(path, target, root string, want []wantElement, state ledger) (*filePlan, error) {
s, p, owner := pl.s, pl.p, pl.source.ConfigPath
base, err := s.base(target, root)
if err != nil {
return nil, err
}
if err := checkPath(base, path); err != nil {
return nil, err
}
data, exists, mode, err := safeRead(path)
if err != nil {
return nil, err
}
doc, err := parseNative(target, data)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if mode == 0 {
mode = 0644
}
f := &filePlan{path: path, target: target, root: root, base: base, kind: kindJSON, before: data, exists: exists, mode: mode, section: doc.sectionDigest()}
if target == "droid" && !exists && len(want) > 0 {
settings := filepath.Join(filepath.Dir(path), "settings.json")
if inline, _ := droidInlineHooks(settings); len(inline) > 0 {
pl.note(target, path, root, want[0].entry, "conflict", "Droid runs the hooks in "+settings+" only while hooks.json is absent, so creating hooks.json would silently stop them; import them from droid, remove the hooks key from "+settings+", then sync")
}
}
all := map[string]record{}
for key, r := range state.Records {
if r.Path == path && r.Event != "" {
all[key] = r
}
}
located := locate(doc, all)
taken := map[string]map[int]string{} // event -> index -> key
for key, i := range located {
r := all[key]
if taken[r.Event] == nil {
taken[r.Event] = map[int]string{}
}
taken[r.Event][i] = key
}
track := map[string]map[int]string{}
keep := func(event string, i int, key string) {
if track[event] == nil {
track[event] = map[int]string{}
}
track[event][i] = key
}
// prior and wantEvents are each entry's events in this file before and after.
prior, wantEvents := map[string]map[string]bool{}, map[string]map[string]bool{}
mark := func(sets map[string]map[string]bool, root, entry, event string) {
k := root + "\x00" + entry
if sets[k] == nil {
sets[k] = map[string]bool{}
}
sets[k][event] = true
}
for _, r := range all {
if r.Owner == owner {
mark(prior, r.Root, r.Entry, r.Event)
}
}
for _, w := range want {
mark(wantEvents, w.root, w.entry, w.event)
}
// touch records the events one element change adds, updates or removes; before is
// nil for an addition and after nil for a removal.
touch := func(root, entry, event string, before, after any) {
if target == "antigravity" {
// The element is a whole block: compare the events inside it.
old, _ := before.(map[string]any)
next, _ := after.(map[string]any)
for _, e := range sortedKeys(mergeKeys(old, next)) {
_, had := old[e]
_, has := next[e]
switch {
case !had:
pl.event(target, path, root, entry, e, "added")
case !has:
pl.event(target, path, root, entry, e, "removed")
case elementHash(old[e]) != elementHash(next[e]):
pl.event(target, path, root, entry, e, "updated")
}
}
return
}
k, kind := root+"\x00"+entry, "updated"
switch {
case after == nil && !wantEvents[k][event]:
kind = "removed"
case after != nil && !prior[k][event]:
kind = "added"
}
pl.event(target, path, root, entry, event, kind)
}
wanted := map[string]bool{}
for _, w := range want {
key := elementKey(owner, w.root, path, w.event, w.entry, w.ordinal)
wanted[key] = true
wantHash := elementHash(w.value)
next := record{Owner: owner, Target: target, Path: path, Root: w.root, Entry: w.entry, Event: w.event, Ordinal: w.ordinal, Hash: wantHash}
items := doc.events[w.event]
if r, has := state.Records[key]; has {
if i, ok := located[key]; ok {
if r.Hash == wantHash {
next.Index = i
p.state.Records[key] = next
keep(w.event, i, key)
action := "unchanged"
if r.Adopted {
action = "adopt"
}
pl.note(target, path, w.root, w.entry, action, "")
} else {
f.ops = append(f.ops, elementOp{Key: key, Event: w.event, Index: i, Value: w.value, Before: items[i]})
p.state.Records[key] = next
touch(w.root, w.entry, w.event, items[i], w.value)
pl.note(target, path, w.root, w.entry, "update", "")
}
continue
}
if !pl.replaces(w.root, w.entry) {
pl.note(target, path, w.root, w.entry, "conflict", "a hook Skillshare wrote was changed or removed outside Skillshare; import it or explicitly replace it")
continue
}
op := elementOp{Key: key, Event: w.event, Index: -1, Value: w.value}
if i := r.Index; i < len(items) && taken[w.event][i] == "" {
// The edited registration sits where Skillshare last wrote it and no one
// owns it: replace it in place rather than adding a second one. For
// Antigravity that place is the block's name.
op.Index, op.Before = i, items[i]
if taken[w.event] == nil {
taken[w.event] = map[int]string{}
}
taken[w.event][i] = key
} else if target == "antigravity" && len(items) > 0 {
pl.note(target, path, w.root, w.entry, "conflict", "a hook with this name is managed by another Skillshare config")
continue
}
f.ops = append(f.ops, op)
p.state.Records[key] = next
touch(w.root, w.entry, w.event, op.Before, w.value)
pl.note(target, path, w.root, w.entry, "update", "replacing a registration changed outside Skillshare")
continue
}
identical, other := -1, ""
for i, item := range items {
if elementHash(item) != wantHash {
continue
}
if holder, held := taken[w.event][i]; held {
if all[holder].Owner != owner && other == "" {
other = holder
}
continue
}
identical = i
break
}
switch {
case identical >= 0 && !pl.replaces(w.root, w.entry) && !pl.adopts(w.root, w.entry):
pl.note(target, path, w.root, w.entry, "conflict", "an identical hook exists that Skillshare does not manage; import it or explicitly replace it")
case identical >= 0:
if pl.adopts(w.root, w.entry) {
p.adopted = append(p.adopted, key)
}
if taken[w.event] == nil {
taken[w.event] = map[int]string{}
}
taken[w.event][identical] = key
next.Index = identical
p.state.Records[key] = next
keep(w.event, identical, key)
pl.note(target, path, w.root, w.entry, "adopt", "")
case other != "" && !(ownerGone(all[other].Owner) && pl.replaces(w.root, w.entry)):
pl.note(target, path, w.root, w.entry, "conflict", "an identical hook is managed by another Skillshare config: "+all[other].Owner)
case other != "":
i := located[other]
delete(p.state.Records, other)
taken[w.event][i] = key
next.Index = i
p.state.Records[key] = next
keep(w.event, i, key)
pl.note(target, path, w.root, w.entry, "adopt", "taking over a hook left by a removed Skillshare config")
case target == "antigravity" && len(items) > 0 && other == "" && !pl.replaces(w.root, w.entry) && !pl.adopts(w.root, w.entry):
pl.note(target, path, w.root, w.entry, "conflict", "a hook with this name exists that Skillshare does not manage; import it or explicitly replace it")
case target == "antigravity" && len(items) > 0 && other == "":
if _, held := taken[w.event][0]; held {
pl.note(target, path, w.root, w.entry, "conflict", "a hook with this name is managed by another Skillshare config")
continue
}
// Importing or replacing takes over the block of the same name in place.
f.ops = append(f.ops, elementOp{Key: key, Event: w.event, Index: 0, Value: w.value, Before: items[0]})
p.state.Records[key] = next
touch(w.root, w.entry, w.event, items[0], w.value)
pl.note(target, path, w.root, w.entry, "update", "replacing a hook Skillshare did not write")
case target == "antigravity" && pl.adopts(w.root, w.entry):
// An Antigravity hook is the block of that name. Taking over a block under
// another name would add a second block and leave the original running.
pl.note(target, path, w.root, w.entry, "conflict", "Antigravity names each hook after its block; import it under the block's own name")
default:
f.ops = append(f.ops, elementOp{Key: key, Event: w.event, Index: -1, Value: w.value})
p.state.Records[key] = next
touch(w.root, w.entry, w.event, nil, w.value)
pl.note(target, path, w.root, w.entry, "add", "")
}
}
for _, key := range sortedKeys(all) {
r := all[key]
if r.Owner != owner || wanted[key] {
continue
}
if i, ok := located[key]; ok {
f.ops = append(f.ops, elementOp{Key: key, Event: r.Event, Index: i, Before: doc.events[r.Event][i]})
delete(p.state.Records, key)
touch(r.Root, r.Entry, r.Event, doc.events[r.Event][i], nil)
pl.note(target, path, r.Root, r.Entry, "remove", "")
continue
}
if pl.replaces(r.Root, r.Entry) {
delete(p.state.Records, key)
pl.note(target, path, r.Root, r.Entry, "release", "left in place; Skillshare no longer manages it")
continue
}
pl.note(target, path, r.Root, r.Entry, "conflict", "a hook Skillshare wrote was changed or removed outside Skillshare, so it is not removed; explicitly replace to stop managing it")
}
f.created = p.state.Created[path] || !doc.hasSection && slices.ContainsFunc(f.ops, func(op elementOp) bool { return op.Value != nil })
after, positions, err := doc.edit(f.ops, track, f.created)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
f.after = after
if len(f.ops) > 0 && p.state.NewFiles[path] && skeleton(target, after) {
f.remove, f.after = true, nil
for _, key := range pl.order {
if c := pl.changes[key]; c.Path == path && c.Action == "remove" {
c.Message = "deletes the file: Skillshare created it and nothing else is left"
}
}
}
for _, op := range f.ops {
f.keys = append(f.keys, op.Key)
}
for key, i := range positions {
if r, ok := p.state.Records[key]; ok {
r.Index = i
p.state.Records[key] = r
}
}
written, err := parseNative(target, after)
if err != nil {
return nil, err
}
if len(f.ops) > 0 {
if f.created && written.hasSection {
if p.state.Created == nil {
p.state.Created = map[string]bool{}
}
p.state.Created[path] = true
} else {
delete(p.state.Created, path)
}
}
counts := map[string]int{}
for event, items := range written.events {
for _, item := range items {
counts[event+"\x00"+elementHash(item)]++
}
}
for key, r := range p.state.Records {
if r.Owner == owner && r.Path == path && r.Event != "" {
r.Peers = counts[r.Event+"\x00"+r.Hash]
p.state.Records[key] = r
}
}
return f, nil
}
func (pl *planner) planFile(w wantFile, state ledger) (*filePlan, error) {
s, p, owner := pl.s, pl.p, pl.source.ConfigPath
base, err := s.base(w.target, w.root)
if err != nil {
return nil, err
}
if err := checkPath(base, w.path); err != nil {
return nil, err
}
data, exists, mode, err := safeRead(w.path)
if err != nil {
return nil, err
}
current := ""
if exists {
current = digest(data)
}
f := &filePlan{path: w.path, target: w.target, root: w.root, base: base, kind: kindFile, before: data, exists: exists, mode: w.mode, section: current}
if exists {
f.mode = mode
}
key := fileKey(w.path)
r, has := state.Records[key]
replace := pl.replaces(w.root, w.entry)
if has && r.Owner != owner {
if !ownerGone(r.Owner) || !replace || w.content == nil {
pl.note(w.target, w.path, w.root, w.entry, "conflict", "managed by another Skillshare config: "+r.Owner)
return f, nil
}
has = false
}
next := record{Owner: owner, Target: w.target, Path: w.path, Root: w.root, Entry: w.entry, Hash: digest(w.content)}
set := func(action, message string) {
f.keys = []string{key}
p.state.Records[key] = next
pl.note(w.target, w.path, w.root, w.entry, action, message)
}
switch {
case w.content == nil && !exists:
delete(p.state.Records, key)
case w.content == nil && current == r.Hash:
f.remove, f.keys = true, []string{key}
delete(p.state.Records, key)
pl.note(w.target, w.path, w.root, w.entry, "remove", "")
case w.content == nil && replace:
delete(p.state.Records, key)
pl.note(w.target, w.path, w.root, w.entry, "release", "left in place; Skillshare no longer manages it")
case w.content == nil:
pl.note(w.target, w.path, w.root, w.entry, "conflict", "file changed outside Skillshare, so it is not removed; explicitly replace to stop managing it")
case has && exists && current == r.Hash && current == next.Hash:
set("unchanged", "")
case has && exists && current == r.Hash:
f.write = w.content
set("update", "")
case has && !replace:
pl.note(w.target, w.path, w.root, w.entry, "conflict", "file changed or removed outside Skillshare; import it or explicitly replace it")
case !has && !exists:
f.write = w.content
set("add", "")
case !has && current == next.Hash && replace:
set("adopt", "")
case !has && !replace:
pl.note(w.target, w.path, w.root, w.entry, "conflict", "a file Skillshare does not manage already exists here; import it or explicitly replace it")
default:
f.write = w.content
set("update", "replacing a file Skillshare did not write")
}
if f.write != nil {
f.after = f.write
} else if !f.remove {
f.after = data
}
if w.target == "copilot" && (f.write != nil || f.remove) {
pl.fileEvents(w, data, f.write)
}
return f, nil
}
// fileEvents names the events a Copilot hook file gains, changes or loses, as a shared
// file's changes do. A file that does not parse contributes no events.
func (pl *planner) fileEvents(w wantFile, before, after []byte) {
hooksOf := func(data []byte) map[string]any {
var doc struct {
Hooks map[string]any `json:"hooks"`
}
_ = json.Unmarshal(data, &doc)
return doc.Hooks
}
old, next := hooksOf(before), hooksOf(after)
for event, value := range next {
prior, had := old[event]
switch {
case !had:
pl.event(w.target, w.path, w.root, w.entry, event, "added")
case !reflect.DeepEqual(prior, value):
pl.event(w.target, w.path, w.root, w.entry, event, "updated")
}
}
for event := range old {
if _, ok := next[event]; !ok {
pl.event(w.target, w.path, w.root, w.entry, event, "removed")
}
}
}
// refresh confirms a file still matches its preview; other settings may change.
func (f *filePlan) refresh() ([]byte, bool, os.FileMode, *nativeDoc, error) {
if err := checkPath(f.base, f.path); err != nil {
return nil, false, 0, nil, err
}
data, exists, mode, err := safeRead(f.path)
if err != nil {
return nil, false, 0, nil, err
}
if f.kind == kindFile {
current := ""
if exists {
current = digest(data)
}
if current != f.section {
return nil, false, 0, nil, fmt.Errorf("%s changed since preview: %w", f.path, ErrStaleRevision)
}
if !exists {
mode = f.mode
}
return data, exists, mode, nil, nil
}
doc, err := parseNative(f.target, data)
if err != nil {
return nil, false, 0, nil, fmt.Errorf("%s: %w", f.path, err)
}
if doc.sectionDigest() != f.section {
return nil, false, 0, nil, fmt.Errorf("%s hooks changed since preview: %w", f.path, ErrStaleRevision)
}
if !exists {
mode = f.mode
}
return data, exists, mode, doc, nil
}
// droidInlineHooks reads the hooks key of Droid's settings.json, an additional source
// Skillshare never edits.
func droidInlineHooks(path string) (map[string]any, error) {
data, exists, _, err := safeRead(path)
if err != nil || !exists {
return nil, err
}
doc, err := parseNative("claude", data) // same wrapped "hooks" shape
if err != nil {
return nil, err
}
out := map[string]any{}
for event, items := range doc.events {
out[event] = items
}
return out, nil
}
+289
View File
@@ -0,0 +1,289 @@
package hooks
import (
"errors"
"path/filepath"
"strings"
"testing"
)
func TestProjects_GlobalConfigPublishesIntoRootsOnly(t *testing.T) {
e := newEnv(t)
a := filepath.Join(filepath.Dir(e.home), "a")
b := filepath.Join(filepath.Dir(e.home), "b")
save(t, e.service, Mutation{Project: a})
save(t, e.service, Mutation{Project: a, Name: "guard", Entry: entry(t, claudeEntry)})
save(t, e.service, Mutation{Project: b, Name: "guard", Entry: entry(t, claudeEntry)})
for _, root := range []string{a, b} {
if n := len(events(t, filepath.Join(root, ".claude", "settings.json"), true)["PreToolUse"]); n != 1 {
t.Fatalf("%s: %d groups", root, n)
}
}
if exists(filepath.Join(e.home, ".claude")) {
t.Fatal("project entries must not reach the global scope")
}
source, err := LoadSource(e.config)
must(t, err)
if len(source.Projects) != 2 || len(source.Entries) != 0 {
t.Fatalf("source: %+v", source.Projects)
}
// Removing a block saves without sync; ApplyProject then prunes only that root.
p, err := e.service.PreviewMutation(Mutation{Project: a, Remove: true})
must(t, err)
_, err = e.service.Mutate(Mutation{Project: a, Remove: true}, p.Revision, false)
must(t, err)
if _, err := e.service.ApplyProject("x", a); !errors.Is(err, ErrUnknownProject) {
t.Fatalf("a removed block is no longer a known root: %v", err)
}
// Change b's entry without syncing, then sync only b.
_, err = e.service.Mutate(Mutation{Project: b, Name: "guard", Entry: entry(t, strings.Replace(claudeEntry, "echo guard", "echo v2", 1))}, "", false)
must(t, err)
p, err = e.service.Preview()
must(t, err)
roots := map[string]bool{}
for _, c := range p.Changes {
roots[c.Root] = true
}
if !roots[a] || !roots[b] {
t.Fatalf("changes must carry their root: %+v", p.Changes)
}
_, err = e.service.ApplyProject(p.Revision, b)
must(t, err)
if !strings.Contains(read(t, filepath.Join(b, ".claude", "settings.json")), "echo v2") {
t.Fatal("b not synced")
}
if !strings.Contains(read(t, filepath.Join(a, ".claude", "settings.json")), "echo guard") {
t.Fatal("syncing b must not prune a")
}
// A full sync then prunes a.
sync(t, e.service)
if exists(filepath.Join(a, ".claude", "settings.json")) {
t.Fatal("removed block's output must be pruned on sync")
}
}
func TestProjects_ApplyProjectNeedsFreshRevision(t *testing.T) {
e := newEnv(t)
root := filepath.Join(filepath.Dir(e.home), "a")
_, err := e.service.Mutate(Mutation{Project: root, Name: "guard", Entry: entry(t, claudeEntry)}, "", false)
must(t, err)
p, err := e.service.Preview()
must(t, err)
write(t, filepath.Join(root, ".claude", "settings.json"), `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]}}`)
if _, err := e.service.ApplyProject(p.Revision, root); !errors.Is(err, ErrStaleRevision) {
t.Fatalf("want ErrStaleRevision, got %v", err)
}
}
func TestProjects_MutationSyncsOnlyItsRoot(t *testing.T) {
e := newEnv(t)
a := filepath.Join(filepath.Dir(e.home), "a")
b := filepath.Join(filepath.Dir(e.home), "b")
// Pending global output, and a pending project B output that conflicts with an
// identical hook B's user wrote.
_, err := e.service.Mutate(Mutation{Name: "global", Entry: entry(t, claudeEntry)}, "", false)
must(t, err)
bPath := filepath.Join(b, ".claude", "settings.json")
write(t, bPath, `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard","timeout":5}]}]}}`)
_, err = e.service.Mutate(Mutation{Project: b, Name: "guard", Entry: entry(t, claudeEntry)}, "", false)
must(t, err)
bBefore := read(t, bPath)
r := save(t, e.service, Mutation{Project: a, Name: "guard", Entry: entry(t, claudeEntry)})
aPath := filepath.Join(a, ".claude", "settings.json")
if len(r.Applied) != 1 || r.Applied[0] != aPath {
t.Fatalf("only A's output may be written: %v", r.Applied)
}
if exists(filepath.Join(e.home, ".claude")) {
t.Fatal("pending global output must wait for its own sync")
}
if read(t, bPath) != bBefore {
t.Fatal("project B must not be touched")
}
// The revision still covers the whole plan: a change in B makes A's preview stale.
m := Mutation{Project: a, Name: "guard", Entry: entry(t, strings.Replace(claudeEntry, "echo guard", "echo v2", 1))}
p, err := e.service.PreviewMutation(m)
must(t, err)
write(t, bPath, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"x"}]}]}}`)
if _, err := e.service.Mutate(m, p.Revision, true); !errors.Is(err, ErrStaleRevision) {
t.Fatalf("want ErrStaleRevision, got %v", err)
}
if strings.Contains(read(t, aPath), "echo v2") {
t.Fatal("a stale mutation must not write")
}
}
func TestProjects_MutationConflictInItsRootBlocksSourceAndNative(t *testing.T) {
e := newEnv(t)
a := filepath.Join(filepath.Dir(e.home), "a")
aPath := filepath.Join(a, ".claude", "settings.json")
write(t, aPath, `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard","timeout":5}]}]}}`)
before, config := read(t, aPath), read(t, e.config)
m := Mutation{Project: a, Name: "guard", Entry: entry(t, claudeEntry)}
p, err := e.service.PreviewMutation(m)
must(t, err)
if _, err := e.service.Mutate(m, p.Revision, true); !errors.Is(err, ErrConflict) {
t.Fatalf("want ErrConflict, got %v", err)
}
if read(t, aPath) != before || read(t, e.config) != config {
t.Fatal("a conflict in the selected root must block the source and native writes")
}
}
func TestProjects_BlockRemovalSyncPrunesOnlyItsRoot(t *testing.T) {
e := newEnv(t)
a := filepath.Join(filepath.Dir(e.home), "a")
b := filepath.Join(filepath.Dir(e.home), "b")
save(t, e.service, Mutation{Project: a, Name: "guard", Entry: entry(t, claudeEntry)})
save(t, e.service, Mutation{Project: b, Name: "guard", Entry: entry(t, claudeEntry)})
_, err := e.service.Mutate(Mutation{Name: "global", Entry: entry(t, claudeEntry)}, "", false)
must(t, err)
_, err = e.service.Mutate(Mutation{Project: b, Name: "guard", Entry: entry(t, strings.Replace(claudeEntry, "echo guard", "echo v2", 1))}, "", false)
must(t, err)
save(t, e.service, Mutation{Project: a, Remove: true})
if exists(filepath.Join(a, ".claude", "settings.json")) {
t.Fatal("removing a block with sync must prune its root")
}
if !strings.Contains(read(t, filepath.Join(b, ".claude", "settings.json")), "echo guard") {
t.Fatal("B's pending change must wait for its own sync")
}
if exists(filepath.Join(e.home, ".claude")) {
t.Fatal("pending global output must wait for its own sync")
}
}
func TestProjects_RootsWithOwnConfigAreBlockedAndDisclosed(t *testing.T) {
e := newEnv(t)
root := filepath.Join(filepath.Dir(e.home), "own")
e.project(root)
_, err := e.service.Mutate(Mutation{Project: root, Name: "guard", Entry: entry(t, claudeEntry)}, "", false)
must(t, err)
inv, err := e.service.List()
must(t, err)
if len(inv.ProjectConfigs) != 1 || inv.ProjectConfigs[0] != root || !inv.Plan.Blocked {
t.Fatalf("own-config root must be blocked and disclosed: %+v %+v", inv.ProjectConfigs, inv.Plan)
}
if _, ok := inv.ProjectPaths[root]; ok {
t.Fatal("no native paths are shown for a root the global config cannot manage")
}
}
func TestProjects_ProjectScopeCannotDeclareProjects(t *testing.T) {
e := newEnv(t)
project := e.project(filepath.Join(filepath.Dir(e.home), "repo"))
if _, err := project.PreviewMutation(Mutation{Project: "/tmp/other"}); err == nil {
t.Fatal("project mode must reject hooks.projects mutations")
}
write(t, project.ConfigPath, "hooks:\n projects:\n /tmp/x:\n entries: {}\n")
if _, err := project.Preview(); err == nil {
t.Fatal("project config must not declare hooks.projects")
}
if _, err := project.Import(ImportRequest{From: "claude", Root: "/tmp/x"}); err == nil {
t.Fatal("project mode must reject import roots")
}
}
func TestList_InventoryShowsTargetsPathsUnmanagedAndBackups(t *testing.T) {
e := newEnv(t)
write(t, filepath.Join(e.home, ".claude", "settings.json"), userSettings)
write(t, filepath.Join(e.home, ".codex", "config.toml"), "[[hooks.Stop]]\n[[hooks.Stop.hooks]]\ntype = \"command\"\ncommand = \"echo\"\n")
write(t, filepath.Join(e.home, ".config", "opencode", "plugins", "mine.ts"), "export const Mine = async () => ({})\n")
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
inv, err := e.service.List()
must(t, err)
if len(inv.Targets) != 11 || inv.Paths["droid"] != filepath.Join(e.home, ".factory", "hooks.json") || len(inv.Backups) != 1 || inv.Plan == nil {
t.Fatalf("inventory: %+v", inv)
}
got := map[string]string{}
for _, u := range inv.Unmanaged {
got[u.Target+":"+filepath.Base(u.Path)] = strings.Join(u.Names, ",")
}
// PreToolUse holds both the user's group and the owned one; only the user's counts.
if got["claude:settings.json"] != "PreToolUse,Stop" || got["codex:config.toml"] != "Stop" || got["opencode:plugins"] != "mine.ts" {
t.Fatalf("unmanaged: %v", got)
}
for _, target := range inv.Targets {
if target.Note == "" || (target.Kind != KindCommand && target.Kind != KindCode) {
t.Fatalf("target definition: %+v", target)
}
}
}
func TestImport_OffersOnlyUnmanagedHooksWithoutExecuting(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, userSettings)
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
candidates, err := e.service.Import(ImportRequest{From: "claude"})
must(t, err)
names := []string{}
for _, c := range candidates {
names = append(names, c.Name)
if len(c.Problems) != 0 {
t.Fatalf("%s: %v", c.Name, c.Problems)
}
if strings.Contains(c.Name, "pretooluse") && len(c.Entry.Bindings["claude"].Events["PreToolUse"].([]any)) != 1 {
t.Fatal("the owned group must not be offered")
}
}
if strings.Join(names, ",") != "claude-pretooluse,claude-stop" {
t.Fatalf("candidates: %v", names)
}
one, err := e.service.Import(ImportRequest{From: "claude", Name: "mine"})
must(t, err)
if len(one) != 1 || one[0].Name != "mine" || len(one[0].Entry.Bindings["claude"].Events) != 2 {
t.Fatalf("named import merges everything: %+v", one)
}
// Saving the import and syncing with replace takes over in place.
save(t, e.service, Mutation{Name: "mine", Entry: &one[0].Entry, Replace: true})
if n := len(events(t, path, true)["PreToolUse"]); n != 2 {
t.Fatalf("import+replace must not duplicate: %d", n)
}
if rest, _ := e.service.Import(ImportRequest{From: "claude"}); len(rest) != 0 {
t.Fatalf("everything is managed now: %+v", rest)
}
}
func TestImport_ContentCodeAndCopilot(t *testing.T) {
e := newEnv(t)
code := "export default Plugin.define({ id: \"x\", async setup() {} })\n"
c, err := e.service.Import(ImportRequest{From: "opencode", Content: code, Name: "v2"})
must(t, err)
if len(c) != 1 || c[0].Entry.Bindings["opencode"].Code != code {
t.Fatalf("code must be imported verbatim: %+v", c)
}
write(t, filepath.Join(e.home, ".pi", "agent", "extensions", "guard.ts"), "export default function (pi) {}\n")
c, err = e.service.Import(ImportRequest{From: "pi"})
must(t, err)
if len(c) != 1 || c[0].Name != "guard" || len(c[0].Warnings) == 0 {
t.Fatalf("pi file import: %+v", c)
}
write(t, filepath.Join(e.home, ".copilot", "hooks", "team.json"), `{"version":1,"hooks":{"sessionStart":[{"type":"command","bash":"echo hi"}]}}`)
c, err = e.service.Import(ImportRequest{From: "copilot"})
must(t, err)
if len(c) != 1 || c[0].Name != "team" || len(c[0].Problems) != 0 {
t.Fatalf("copilot import: %+v", c)
}
c, err = e.service.Import(ImportRequest{From: "factory", Content: `{"Stop":[{"hooks":[{"type":"command","command":"echo"}]}]}`})
must(t, err)
if len(c) != 1 || c[0].Entry.Bindings["droid"].Events["Stop"] == nil {
t.Fatalf("droid content uses the unwrapped event map: %+v", c)
}
if _, err := e.service.Import(ImportRequest{From: "claude", Content: `{"hooks":`}); err == nil {
t.Fatal("malformed content must be rejected")
}
}
func TestImport_NamePicksOneCodeFile(t *testing.T) {
e := newEnv(t)
write(t, filepath.Join(e.home, ".config", "amp", "plugins", "one.ts"), "export default function (amp) {}\n")
write(t, filepath.Join(e.home, ".config", "amp", "plugins", "two.js"), "export default function (amp) {}\n")
c, err := e.service.Import(ImportRequest{From: "amp", Name: "two"})
must(t, err)
if len(c) != 1 || c[0].Name != "two" || c[0].Entry.Bindings["amp"].Code == "" {
t.Fatalf("name must pick one file: %+v", c)
}
}
+89
View File
@@ -0,0 +1,89 @@
package hooks
import (
"fmt"
"slices"
"strings"
)
// RenderedFile is one native output of a single hook: its contribution to a shared
// hooks file in that file's native wrapper, or a whole file it owns.
type RenderedFile struct {
Target string `json:"target"`
Path string `json:"path,omitempty"`
Content string `json:"content"`
Error string `json:"error,omitempty"`
}
// RenderNative shows what one hook writes, per Agent, without the rest of any existing
// file. It reads no ownership state or native file contents, writes nothing and runs
// nothing. A disabled entry renders its stored bindings, which sync would not write.
// A binding whose path cannot be resolved or safely written reports its own error.
func (s *Service) RenderNative(m Mutation) ([]RenderedFile, error) {
if m.Remove || m.Replace {
return nil, fmt.Errorf("render takes a hook definition, not a remove or replace")
}
if m.Name == "" || m.Entry == nil {
return nil, fmt.Errorf("hook name and entry are required")
}
root := ""
scope := s
if m.Project != "" {
if s.ProjectRoot != "" {
return nil, fmt.Errorf("hooks.projects belongs in the global config")
}
var err error
if root, err = projectRoot(m.Project); err != nil {
return nil, err
}
scope = s.scoped(root)
}
entry := *m.Entry
if err := entry.normalize(); err != nil {
return nil, err
}
if err := entry.Validate(m.Name); err != nil {
return nil, err
}
entry.Enabled = nil
out := []RenderedFile{}
for _, target := range sortedKeys(entry.Bindings) {
one := Entry{Bindings: map[string]Binding{target: entry.Bindings[target]}}
d := &desired{elements: map[string][]wantElement{}, targets: map[string]string{}, roots: map[string]string{}, files: map[string]wantFile{}}
if err := scope.renderScope(d, root, map[string]Entry{m.Name: one}); err != nil {
out = append(out, RenderedFile{Target: target, Error: err.Error()})
continue
}
base, err := scope.base(target, root)
if err != nil {
out = append(out, RenderedFile{Target: target, Error: err.Error()})
continue
}
var files []RenderedFile
for path, want := range d.elements {
f := RenderedFile{Target: target, Path: path}
ops := make([]elementOp, len(want))
for i, w := range want {
ops[i] = elementOp{Event: w.event, Index: -1, Value: w.value}
}
doc, _ := parseNative(target, nil)
if data, _, err := doc.edit(ops, nil, false); err != nil {
f.Error = err.Error()
} else {
f.Content = string(data)
}
files = append(files, f)
}
for path, want := range d.files {
files = append(files, RenderedFile{Target: target, Path: path, Content: string(want.content)})
}
for i := range files {
if err := checkPath(base, files[i].Path); err != nil && files[i].Error == "" {
files[i].Error = err.Error()
}
}
slices.SortFunc(files, func(a, b RenderedFile) int { return strings.Compare(a.Path, b.Path) })
out = append(out, files...)
}
return out, nil
}
+175
View File
@@ -0,0 +1,175 @@
package hooks
import (
"encoding/json"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
)
func allAdapters(t *testing.T) *Entry {
t.Helper()
var parts []string
for target, binding := range adapterEntry {
parts = append(parts, `"`+target+`":`+binding)
}
return entry(t, `{"enabled":false,"bindings":{`+strings.Join(parts, ",")+`}}`)
}
func rendered(t *testing.T, s *Service, m Mutation) map[string]RenderedFile {
t.Helper()
files, err := s.RenderNative(m)
must(t, err)
out := map[string]RenderedFile{}
for _, f := range files {
out[f.Path] = f
}
return out
}
func TestRender_AllAdaptersNativeShapesWithoutWriting(t *testing.T) {
e := newEnv(t)
// Existing settings and an unrelated invalid source entry are not part of the preview.
write(t, filepath.Join(e.home, ".claude", "settings.json"), `{"model":"x","hooks":{"Stop":[{"hooks":[{"type":"command","command":"mine"}]}]}}`)
write(t, e.config, "hooks:\n entries:\n broken:\n bindings:\n nope: {}\n")
got := rendered(t, e.service, Mutation{Name: "demo", Entry: allAdapters(t)})
want := map[string]string{
".claude/settings.json": "claude", ".codex/hooks.json": "codex", ".gemini/settings.json": "gemini",
".qwen/settings.json": "qwen", ".factory/hooks.json": "droid", ".cursor/hooks.json": "cursor",
".cursor/hooks/skillshare/demo/guard.sh": "cursor",
".copilot/hooks/skillshare-demo.json": "copilot", ".pi/agent/extensions/skillshare-demo.ts": "pi",
".config/amp/plugins/skillshare-demo.ts": "amp", ".config/opencode/plugins/skillshare-demo.ts": "opencode",
".gemini/config/hooks.json": "antigravity",
}
if len(got) != len(want) {
t.Fatalf("rendered %d files: %+v", len(got), got)
}
for rel, target := range want {
f, ok := got[filepath.Join(e.home, rel)]
if !ok || f.Target != target || f.Error != "" {
t.Fatalf("%s: %+v", rel, f)
}
var b Binding
must(t, json.Unmarshal([]byte(adapterEntry[target]), &b))
switch {
case strings.HasSuffix(rel, ".ts"):
if f.Content != b.Code {
t.Fatalf("%s: code must be verbatim: %q", rel, f.Content)
}
continue
case strings.HasSuffix(rel, ".sh"):
if f.Content != b.Files["guard.sh"] {
t.Fatalf("script content: %q", f.Content)
}
continue
}
var doc map[string]any
must(t, json.Unmarshal([]byte(f.Content), &doc))
section := doc
switch target {
case "droid":
case "antigravity":
section, _ = doc["demo"].(map[string]any)
if len(doc) != 1 {
t.Fatalf("%s: one block named after the hook: %s", rel, f.Content)
}
default:
section, _ = doc["hooks"].(map[string]any)
}
for event := range b.Events {
if items, _ := section[event].([]any); len(items) != 1 {
t.Fatalf("%s: %s missing from %s", rel, event, f.Content)
}
}
if len(section) != len(b.Events) || (target == "cursor" || target == "copilot") != (doc["version"] == float64(1)) {
t.Fatalf("%s: only this hook in its native wrapper: %s", rel, f.Content)
}
}
if strings.Contains(got[filepath.Join(e.home, ".claude", "settings.json")].Content, "mine") {
t.Fatal("existing native content must not be shown")
}
// Only the fixture files exist: nothing written, no state created.
var written []string
must(t, filepath.WalkDir(e.home, func(path string, d fs.DirEntry, err error) error {
if err == nil && !d.IsDir() {
written = append(written, path)
}
return err
}))
if len(written) != 1 || exists(e.service.StateDir) {
t.Fatalf("render must write nothing: %v", written)
}
}
func TestRender_ProjectScopes(t *testing.T) {
e := newEnv(t)
root := filepath.Join(filepath.Dir(e.home), "repo")
m := Mutation{Project: root, Name: "demo", Entry: entry(t, `{"bindings":{"factory":`+adapterEntry["droid"]+`,"claude":`+adapterEntry["claude"]+`}}`)}
got := rendered(t, e.service, m)
for _, rel := range []string{".factory/hooks.json", ".claude/settings.json"} {
if _, ok := got[filepath.Join(root, rel)]; !ok {
t.Fatalf("hooks.projects root paths: %+v", got)
}
}
project := e.project(root)
m.Project = ""
if got := rendered(t, project, m); got[filepath.Join(root, ".claude", "settings.json")].Target != "claude" {
t.Fatalf("project mode paths: %+v", got)
}
m.Project = root
if _, err := project.RenderNative(m); err == nil {
t.Fatal("project mode must reject hooks.projects roots")
}
}
func TestRender_RejectsNonRenderRequests(t *testing.T) {
e := newEnv(t)
ok := entry(t, claudeEntry)
for name, m := range map[string]Mutation{
"remove": {Name: "demo", Entry: ok, Remove: true},
"replace": {Name: "demo", Entry: ok, Replace: true},
"no name": {Entry: ok},
"no entry": {Name: "demo"},
"invalid": {Name: "demo", Entry: &Entry{Bindings: map[string]Binding{"claude": {Events: map[string]any{"PreToolUse": map[string]any{}}}}}},
"relative": {Project: "repo", Name: "demo", Entry: ok},
} {
if _, err := e.service.RenderNative(m); err == nil {
t.Fatalf("%s must be rejected", name)
}
}
}
func TestRender_UnsafePathIsReportedPerFile(t *testing.T) {
e := newEnv(t)
outside := filepath.Join(filepath.Dir(e.home), "outside")
must(t, os.MkdirAll(outside, 0755))
must(t, os.MkdirAll(filepath.Join(e.home, ".cursor"), 0755))
must(t, os.Symlink(outside, filepath.Join(e.home, ".cursor", "hooks")))
got := rendered(t, e.service, Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"cursor":`+adapterEntry["cursor"]+`}}`)})
if f := got[filepath.Join(e.home, ".cursor", "hooks", "skillshare", "demo", "guard.sh")]; f.Error == "" || f.Content == "" {
t.Fatalf("a script behind a symlink must carry an error: %+v", f)
}
if f := got[filepath.Join(e.home, ".cursor", "hooks.json")]; f.Error != "" || f.Content == "" {
t.Fatalf("the hooks file is still previewed: %+v", f)
}
}
func TestRender_EmptyScriptKeepsItsContentInJSON(t *testing.T) {
e := newEnv(t)
got := rendered(t, e.service, Mutation{Name: "demo", Entry: entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"empty.sh"}]}]},"files":{"empty.sh":""}}}}`)})
path := filepath.Join(e.home, ".claude", "hooks", "skillshare", "demo", "empty.sh")
f, ok := got[path]
if !ok || f.Error != "" || f.Content != "" {
t.Fatalf("empty script: %+v", got)
}
data, err := json.Marshal(f)
must(t, err)
if !strings.Contains(string(data), `"content":""`) {
t.Fatalf("an empty file's content must be serialized: %s", data)
}
if exists(filepath.Join(e.home, ".claude")) {
t.Fatal("render must write nothing")
}
}
+332
View File
@@ -0,0 +1,332 @@
package hooks
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/gofrs/flock"
)
// Service is scoped to one Skillshare config; StateDir is shared across scopes so
// separate configs cannot silently take over each other's native registrations.
type Service struct {
ConfigPath string
ProjectRoot string
Home string
StateDir string
Platform string
// ConfigDirs contains explicitly resolved native Agent directory overrides.
ConfigDirs map[string]string
}
// Mutation is shared by CLI and dashboard preview/save/sync flows. An empty
// mutation synchronizes the current source.
type Mutation struct {
// Project is a root under the global config's hooks.projects. Set alone, it creates
// an empty block; with Remove and no Name, it removes the block.
Project string `json:"project,omitempty"`
Name string `json:"name,omitempty"`
Entry *Entry `json:"entry,omitempty"`
Remove bool `json:"remove,omitempty"`
// Replace explicitly takes over this entry's conflicting native outputs: an
// identical unmanaged registration, an unmanaged file at an output path, or an
// owned output edited outside Skillshare. It never overrides another config.
Replace bool `json:"replace,omitempty"`
// Adopt saves an imported entry as the owner of the native registrations it was
// read from: identical unmanaged elements become its own without Replace, so the
// next sync adopts them in place. It never takes over edited outputs or another
// config's registrations.
Adopt bool `json:"adopt,omitempty"`
// Unmanage, with Remove and a Name, also forgets which native registrations the
// hook wrote, so sync leaves them in place as the user's own hooks.
Unmanage bool `json:"unmanage,omitempty"`
}
// Change deliberately carries no hook contents.
type Change struct {
Target string `json:"target"`
Path string `json:"path"`
Name string `json:"name"`
// Root is the hooks.projects root this change belongs to, empty for the config's own scope.
Root string `json:"root,omitempty"`
Action string `json:"action"` // add, update, remove, unchanged, adopt, release, conflict
Message string `json:"message,omitempty"`
// Events names the native events this change writes into a shared hooks file.
Events *EventChanges `json:"events,omitempty"`
}
// EventChanges is the event-level detail of a change to a shared hooks file: events
// the entry newly occupies, events whose registrations change, and events it leaves.
type EventChanges struct {
Added []string `json:"added,omitempty"`
Updated []string `json:"updated,omitempty"`
Removed []string `json:"removed,omitempty"`
}
// Plan is an optimistic-concurrency-protected preview.
type Plan struct {
Revision string `json:"revision"`
// Fingerprint identifies only what the preview shows about hooks: the proposed
// entries and projects, replacements, native hook sections and files, ownership
// and the resulting changes. Unrelated config or native settings leave it unchanged.
Fingerprint string `json:"fingerprint"`
SourcePath string `json:"sourcePath"`
Blocked bool `json:"blocked"`
Changes []Change `json:"changes"`
// Warnings are advisory, such as event names an Agent does not document; they
// never block a sync.
Warnings []string `json:"warnings"`
source *Source
state ledger
stateBytes []byte
files []*filePlan
// adopted are the ledger keys an Adopt mutation claims, recorded even without sync.
adopted []string
}
// FileDiff is one native file's text before and after a planned sync.
type FileDiff struct {
Target string `json:"target"`
Path string `json:"path"`
Root string `json:"root,omitempty"`
// Before is the current text, "" when the file is missing; After is exactly what
// sync writes, "" when it removes the file.
Before string `json:"before"`
After string `json:"after"`
}
// Files returns each native file the plan would change, with its full text.
func (p *Plan) Files() []FileDiff {
out := []FileDiff{}
for _, f := range p.files {
if f.changed() && string(f.before) != string(f.after) {
out = append(out, FileDiff{Target: f.target, Path: f.path, Root: f.root, Before: string(f.before), After: string(f.after)})
}
}
return out
}
// Result reports applied files individually; a multi-file operation is not a
// filesystem transaction and may leave completed files when a later one fails.
type Result struct {
Plan *Plan `json:"plan,omitempty"`
Applied []string `json:"applied"`
BackupIDs []string `json:"backupIds"`
}
// SourceInfo is the declaration shown by List.
type SourceInfo struct {
Path string `json:"path"`
ConfigPath string `json:"configPath"`
Entries map[string]Entry `json:"entries"`
// Projects are roots a global config publishes into, keyed by absolute path.
Projects map[string]Project `json:"projects,omitempty"`
}
// Backup is metadata for one native write.
type Backup struct {
ID string `json:"id"`
Target string `json:"target"`
Path string `json:"path"`
Time string `json:"time,omitempty"`
}
// Unmanaged names native hooks no Skillshare config owns, including additional
// sources Skillshare never edits.
type Unmanaged struct {
Target string `json:"target"`
Path string `json:"path"`
Names []string `json:"names"`
}
// Inventory is everything the list views need.
type Inventory struct {
Source SourceInfo `json:"source"`
Targets []TargetDef `json:"targets"`
Paths map[string]string `json:"paths"`
Plan *Plan `json:"plan,omitempty"`
PreviewError string `json:"previewError,omitempty"`
Backups []Backup `json:"backups"`
Unmanaged []Unmanaged `json:"unmanaged"`
// ProjectConfigs are hooks.projects roots that have their own Skillshare config;
// the global config cannot manage them.
ProjectConfigs []string `json:"projectConfigs"`
// ProjectPaths are each hooks.projects root's native destinations.
ProjectPaths map[string]map[string]string `json:"projectPaths"`
}
// ImportRequest reads native hooks without executing them. Content, when set,
// replaces reading the Agent's file in the current scope.
type ImportRequest struct {
From string `json:"from"`
// Root reads a hooks.projects root's native files instead of the current scope's.
Root string `json:"root,omitempty"`
Content string `json:"content,omitempty"`
Name string `json:"name,omitempty"`
}
// Candidate is one importable entry.
type Candidate struct {
Name string `json:"name"`
Entry Entry `json:"entry"`
Problems []string `json:"problems"`
Warnings []string `json:"warnings"`
}
// ConfigDirsFromEnv reads the Agent directory overrides Agents themselves honor.
func ConfigDirsFromEnv() map[string]string {
dirs := map[string]string{}
for key, env := range configDirEnv {
value := strings.TrimSpace(os.Getenv(env))
if value == "" || !filepath.IsAbs(value) {
continue
}
dirs[key] = value
}
return dirs
}
// configDirEnv maps ConfigDirs keys to the environment variables Agents document.
var configDirEnv = map[string]string{
"claude": "CLAUDE_CONFIG_DIR",
"codex": "CODEX_HOME",
"copilot": "COPILOT_HOME",
"pi": "PI_CODING_AGENT_DIR",
"xdg": "XDG_CONFIG_HOME",
}
func (s *Service) home() (string, error) {
if s.Home != "" {
return s.Home, nil
}
return os.UserHomeDir()
}
// configDir is the Agent's own config directory in this scope. A project scope never
// falls back to a global path.
func (s *Service) configDir(target string) (string, error) {
if s.ProjectRoot != "" {
dirs := map[string]string{"claude": ".claude", "codex": ".codex", "gemini": ".gemini", "qwen": ".qwen", "copilot": ".github", "cursor": ".cursor", "droid": ".factory", "antigravity": ".agents", "pi": ".pi", "amp": ".amp", "opencode": ".opencode"}
dir, ok := dirs[target]
if !ok {
return "", fmt.Errorf("unsupported hooks Agent %q", target)
}
return filepath.Join(s.ProjectRoot, dir), nil
}
if dir := s.ConfigDirs[target]; dir != "" {
if !filepath.IsAbs(dir) {
return "", fmt.Errorf("%s config directory must be absolute", target)
}
return filepath.Clean(dir), nil
}
home, err := s.home()
if err != nil {
return "", err
}
xdg := s.ConfigDirs["xdg"]
if xdg == "" {
xdg = filepath.Join(home, ".config")
}
switch target {
case "claude", "codex", "gemini", "qwen", "copilot", "cursor":
return filepath.Join(home, "."+target), nil
case "droid":
return filepath.Join(home, ".factory"), nil
case "antigravity":
return filepath.Join(home, ".gemini", "config"), nil
case "pi":
return filepath.Join(home, ".pi", "agent"), nil
case "amp":
return filepath.Join(xdg, "amp"), nil
case "opencode":
return filepath.Join(xdg, "opencode"), nil
}
return "", fmt.Errorf("unsupported hooks Agent %q", target)
}
// nativePath is the shared hooks file of a command Agent, or the folder that holds
// Skillshare's files for Copilot and the code Agents.
func (s *Service) nativePath(target string) (string, error) {
dir, err := s.configDir(target)
if err != nil {
return "", err
}
switch target {
case "claude", "gemini", "qwen":
return filepath.Join(dir, "settings.json"), nil
case "codex", "cursor", "droid", "antigravity":
return filepath.Join(dir, "hooks.json"), nil
case "copilot":
return filepath.Join(dir, "hooks"), nil
case "pi":
return filepath.Join(dir, "extensions"), nil
case "amp", "opencode":
return filepath.Join(dir, "plugins"), nil
}
return "", fmt.Errorf("unsupported hooks Agent %q", target)
}
// codePath is the Skillshare-owned file of a code Agent or Copilot for one entry.
func (s *Service) codePath(target, entry string) (string, error) {
dir, err := s.nativePath(target)
if err != nil {
return "", err
}
if target == "copilot" {
return filepath.Join(dir, "skillshare-"+entry+".json"), nil
}
return filepath.Join(dir, "skillshare-"+entry+".ts"), nil
}
// scriptDir holds an entry's script files for a command Agent.
func (s *Service) scriptDir(target, entry string) (string, error) {
dir, err := s.configDir(target)
if err != nil {
return "", err
}
return filepath.Join(dir, "hooks", "skillshare", entry), nil
}
// Paths exposes native destinations for the current scope.
func (s *Service) Paths() map[string]string {
out := map[string]string{}
for _, t := range Targets {
if path, err := s.nativePath(t.Name); err == nil {
out[t.Name] = path
}
}
return out
}
func (s *Service) platform() string {
if s.Platform != "" {
return s.Platform
}
return runtime.GOOS
}
func (s *Service) stateDir() string { return filepath.Join(s.StateDir, "hooks") }
func (s *Service) statePath() string { return filepath.Join(s.stateDir(), "state.json") }
func (s *Service) lock() (*flock.Flock, error) {
if s.StateDir == "" {
return nil, fmt.Errorf("hooks state directory is required")
}
if err := os.MkdirAll(s.stateDir(), 0700); err != nil {
return nil, err
}
lock := flock.New(filepath.Join(s.stateDir(), "operation.lock"))
ok, err := lock.TryLock()
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("another hooks operation is running; retry when it completes")
}
return lock, nil
}
+338
View File
@@ -0,0 +1,338 @@
package hooks
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
"skillshare/internal/utils"
)
// Source is the hooks section of one Skillshare config.
type Source struct {
ConfigPath string
Entries map[string]Entry
// Projects are hooks.projects roots, keyed by absolute clean path.
Projects map[string]Project
doc yaml.Node
bytes []byte
// touched are entries a draft changed; save re-encodes only these.
touched map[string]bool
// touchedProjects are roots whose block a draft changed; projectKeys keep each
// root as the config spells it, so saving keeps a leading ~.
touchedProjects map[string]bool
projectKeys map[string]string
// unmanaged are the hooks a draft stops managing, keyed by project root and name.
unmanaged map[string]bool
}
func mapping(node *yaml.Node) *yaml.Node {
if node.Kind == yaml.DocumentNode && len(node.Content) == 1 {
return node.Content[0]
}
return node
}
func field(node *yaml.Node, key string) *yaml.Node {
node = mapping(node)
if node.Kind != yaml.MappingNode {
return nil
}
for i := 0; i+1 < len(node.Content); i += 2 {
if node.Content[i].Value == key {
return node.Content[i+1]
}
}
return nil
}
func put(node *yaml.Node, key string, value any) error {
var n yaml.Node
if err := n.Encode(value); err != nil {
return err
}
blockStyle(&n)
node = mapping(node)
for i := 0; i+1 < len(node.Content); i += 2 {
if node.Content[i].Value == key {
node.Content[i+1] = &n
return nil
}
}
node.Content = append(node.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, &n)
return nil
}
func drop(node *yaml.Node, key string) {
node = mapping(node)
for i := 0; i+1 < len(node.Content); i += 2 {
if node.Content[i].Value == key {
node.Content = append(node.Content[:i], node.Content[i+2:]...)
return
}
}
}
func blockStyle(node *yaml.Node) {
if node.Kind == yaml.MappingNode || node.Kind == yaml.SequenceNode {
node.Style &^= yaml.FlowStyle
}
// Multi-line code and scripts stay readable as literal blocks.
if node.Kind == yaml.ScalarNode && node.Tag == "!!str" && bytes.ContainsRune([]byte(node.Value), '\n') {
node.Style = yaml.LiteralStyle
}
for _, child := range node.Content {
blockStyle(child)
}
}
func digest(data []byte) string { return fmt.Sprintf("%x", sha256.Sum256(data)) }
// LoadSource reads hooks.entries. A config without a hooks section has no entries.
func LoadSource(configPath string) (*Source, error) {
path, err := filepath.Abs(configPath)
if err != nil {
return nil, err
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read hooks config: %w", err)
}
return parseSource(path, data)
}
func parseSource(path string, data []byte) (*Source, error) {
s := &Source{ConfigPath: path, Entries: map[string]Entry{}, Projects: map[string]Project{}, touched: map[string]bool{}, touchedProjects: map[string]bool{}, projectKeys: map[string]string{}, unmanaged: map[string]bool{}, bytes: data}
d := yaml.NewDecoder(bytes.NewReader(s.bytes))
if err := d.Decode(&s.doc); err != nil {
if err == io.EOF {
s.doc = yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{{Kind: yaml.MappingNode, Tag: "!!map"}}}
return s, nil
}
return nil, fmt.Errorf("invalid YAML in %s", path)
}
if d.Decode(new(yaml.Node)) != io.EOF {
return nil, fmt.Errorf("%s must contain one YAML document", path)
}
if mapping(&s.doc).Kind != yaml.MappingNode {
return nil, fmt.Errorf("%s must be a YAML mapping", path)
}
var check map[string]any
if err := s.doc.Decode(&check); err != nil {
return nil, fmt.Errorf("invalid YAML mapping in %s; check duplicate keys", path)
}
section := field(&s.doc, "hooks")
if section == nil {
return s, nil
}
if section.Kind != yaml.MappingNode {
return nil, fmt.Errorf("hooks must be a mapping")
}
for i := 0; i < len(section.Content); i += 2 {
if k := section.Content[i].Value; k != "entries" && k != "projects" {
return nil, fmt.Errorf("unknown hooks field %q", k)
}
}
var err error
if s.Entries, err = decodeEntries(field(section, "entries"), "hooks.entries"); err != nil {
return nil, err
}
projects := field(section, "projects")
if projects == nil {
return s, nil
}
if projects.Kind != yaml.MappingNode {
return nil, fmt.Errorf("hooks.projects must be a mapping")
}
for i := 0; i+1 < len(projects.Content); i += 2 {
key, block := projects.Content[i].Value, projects.Content[i+1]
root, err := projectRoot(key)
if err != nil {
return nil, err
}
if _, dup := s.Projects[root]; dup {
return nil, fmt.Errorf("hooks.projects: %s is listed twice", root)
}
if block.Kind != yaml.MappingNode {
return nil, fmt.Errorf("hooks.projects: %s must be a mapping with entries", key)
}
for j := 0; j < len(block.Content); j += 2 {
if block.Content[j].Value != "entries" {
return nil, fmt.Errorf("hooks.projects: %s takes only entries", key)
}
}
entries, err := decodeEntries(field(block, "entries"), "hooks.projects."+key)
if err != nil {
return nil, err
}
s.Projects[root] = Project{Entries: entries}
s.projectKeys[root] = key
}
return s, nil
}
func decodeEntries(node *yaml.Node, where string) (map[string]Entry, error) {
entries := map[string]Entry{}
if node == nil || node.Kind == yaml.ScalarNode && node.Tag == "!!null" {
return entries, nil
}
if node.Kind != yaml.MappingNode {
return nil, fmt.Errorf("%s must be a mapping", where)
}
encoded, err := yaml.Marshal(node)
if err != nil {
return nil, err
}
decoder := yaml.NewDecoder(bytes.NewReader(encoded))
decoder.KnownFields(true)
if err := decoder.Decode(&entries); err != nil {
return nil, fmt.Errorf("invalid %s: each entry takes description, enabled and bindings (events, code, files): %v", where, err)
}
if entries == nil {
entries = map[string]Entry{}
}
for name, entry := range entries {
if err := entry.normalize(); err != nil {
return nil, fmt.Errorf("hook %s: %w", name, err)
}
if err := entry.Validate(name); err != nil {
return nil, err
}
entries[name] = entry
}
return entries, nil
}
// projectRoot resolves a hooks.projects key to an absolute clean path.
func projectRoot(key string) (string, error) {
root := key
if key == "~" || strings.HasPrefix(key, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
root = filepath.Join(home, strings.TrimPrefix(key[1:], "/"))
}
if !filepath.IsAbs(root) {
return "", fmt.Errorf("hooks.projects: %s must be an absolute path or start with ~", key)
}
return filepath.Clean(root), nil
}
// ValidateSection checks a config's hooks node the way LoadSource and a project's
// sync do, so the config editor never accepts a section sync would refuse.
func ValidateSection(node *yaml.Node, project bool) error {
if node == nil || node.Kind == 0 {
return nil
}
doc := yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{{Kind: yaml.ScalarNode, Tag: "!!str", Value: "hooks"}, node}}
data, err := yaml.Marshal(&doc)
if err != nil {
return err
}
source, err := parseSource("config.yaml", data)
if err != nil {
return err
}
if project && len(source.Projects) > 0 {
return fmt.Errorf("hooks.projects belongs in the global config")
}
return nil
}
// checkUnchanged rejects edits made after the source was read.
func (s *Source) checkUnchanged() error {
data, err := os.ReadFile(s.ConfigPath)
if err != nil || !bytes.Equal(data, s.bytes) {
return ErrStaleRevision
}
return nil
}
// save writes only the entries a draft touched; everything else keeps its bytes' meaning.
func (s *Source) save() error {
if len(s.touched) == 0 && len(s.touchedProjects) == 0 {
return nil
}
if err := s.checkUnchanged(); err != nil {
return err
}
root := mapping(&s.doc)
section := field(root, "hooks")
if section == nil || section.Kind != yaml.MappingNode {
if err := put(root, "hooks", map[string]any{}); err != nil {
return err
}
section = field(root, "hooks")
}
if len(s.touched) > 0 {
entries := field(section, "entries")
if entries == nil || entries.Kind != yaml.MappingNode {
if err := put(section, "entries", map[string]any{}); err != nil {
return err
}
entries = field(section, "entries")
}
for _, name := range sortedKeys(s.touched) {
if entry, ok := s.Entries[name]; ok {
if err := put(entries, name, entry); err != nil {
return err
}
} else {
drop(entries, name)
}
}
}
if len(s.touchedProjects) > 0 {
projects := field(section, "projects")
if projects == nil || projects.Kind != yaml.MappingNode {
if err := put(section, "projects", map[string]any{}); err != nil {
return err
}
projects = field(section, "projects")
}
// Only the roots that changed are re-encoded; the rest stay as written.
for _, root := range sortedKeys(s.touchedProjects) {
if project, ok := s.Projects[root]; ok {
if project.Entries == nil {
project.Entries = map[string]Entry{}
}
if err := put(projects, s.projectKeys[root], project); err != nil {
return err
}
} else {
drop(projects, s.projectKeys[root])
}
}
if len(projects.Content) == 0 {
drop(section, "projects")
}
}
// Empty mappings are encoded in flow style, and entries added to one would inherit it,
// so the section is expanded like the MCP section to stay readable in the editor.
blockStyle(section)
data, err := utils.MarshalYAML(&s.doc)
if err != nil {
return err
}
path := s.ConfigPath
// Dotfile managers often symlink config.yaml; write its target so the link survives.
if resolved, err := filepath.EvalSymlinks(path); err == nil {
path = resolved
}
info, err := os.Stat(path)
if err != nil {
return err
}
if err := atomicWrite(path, data, info.Mode().Perm()); err != nil {
return err
}
s.bytes = data
return nil
}
+147
View File
@@ -0,0 +1,147 @@
package hooks
import (
"path/filepath"
"strings"
"testing"
)
const trialSettings = `{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"afplay /System/Library/Sounds/Glass.aiff","timeout":5}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"~/.claude/guard.sh"}]}]}}`
func importOne(t *testing.T, s *Service, from, name string) Candidate {
t.Helper()
c, err := s.Import(ImportRequest{From: from, Name: name})
must(t, err)
if len(c) != 1 {
t.Fatalf("import %s: %+v", name, c)
}
return c[0]
}
func TestImport_CandidateNameTakesOnlyItsEvent(t *testing.T) {
e := newEnv(t)
write(t, filepath.Join(e.home, ".claude", "settings.json"), trialSettings)
c := importOne(t, e.service, "claude", "claude-stop")
if events := c.Entry.Bindings["claude"].Events; len(events) != 1 || events["Stop"] == nil {
t.Fatalf("claude-stop must hold only Stop: %v", events)
}
}
func TestImport_SavingTakesOverWithoutReplace(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, trialSettings)
c := importOne(t, e.service, "claude", "claude-stop")
for _, w := range c.Warnings {
if strings.Contains(w, "replace") {
t.Fatalf("import must not ask for replace: %q", w)
}
}
m := Mutation{Name: c.Name, Entry: &c.Entry, Adopt: true}
p, err := e.service.PreviewMutation(m)
must(t, err)
if p.Blocked || actions(p) != "claude:claude-stop:adopt" {
t.Fatalf("import preview: %s", actions(p))
}
// Saved without sync, the takeover is still recorded.
if _, err := e.service.Mutate(m, p.Revision, false); err != nil {
t.Fatal(err)
}
p, err = e.service.Preview()
must(t, err)
if p.Blocked || actions(p) != "claude:claude-stop:adopt" {
t.Fatalf("sync after import: %s", actions(p))
}
r := sync(t, e.service)
if len(r.Applied) != 0 || read(t, path) != trialSettings {
t.Fatalf("taking over must not rewrite the file: %v\n%s", r.Applied, read(t, path))
}
if p, _ = e.service.Preview(); actions(p) != "claude:claude-stop:unchanged" {
t.Fatalf("after the adopting sync: %s", actions(p))
}
if rest, _ := e.service.Import(ImportRequest{From: "claude"}); len(rest) != 1 || rest[0].Name != "claude-pretooluse" {
t.Fatalf("PreToolUse stays unmanaged: %+v", rest)
}
write(t, path, strings.Replace(trialSettings, `"timeout":5`, `"timeout":9`, 1))
if p, _ = e.service.Preview(); !p.Blocked {
t.Fatalf("an outside edit after import is a conflict: %s", actions(p))
}
}
func TestImport_AdoptNeverClaimsOtherConfigsOrPlainSaves(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, trialSettings)
c := importOne(t, e.service, "claude", "claude-stop")
p, err := e.service.PreviewMutation(Mutation{Name: "copy", Entry: &c.Entry})
must(t, err)
if !p.Blocked {
t.Fatalf("a plain add of an identical hook is still a conflict: %s", actions(p))
}
}
func TestPlan_NarrowedEntryIsAnUpdateWithEventDetail(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, `{"model":"opus"}`)
both := entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"echo stop"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard"}]}]}}}}`)
p, err := e.service.PreviewMutation(Mutation{Name: "trial", Entry: both})
must(t, err)
if c := p.Changes[0]; c.Action != "add" || c.Events == nil || strings.Join(c.Events.Added, ",") != "PreToolUse,Stop" {
t.Fatalf("add detail: %+v %+v", c, c.Events)
}
save(t, e.service, Mutation{Name: "trial", Entry: both})
stop := entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"echo stop2"}]}]}}}}`)
p, err = e.service.PreviewMutation(Mutation{Name: "trial", Entry: stop})
must(t, err)
c := p.Changes[0]
if c.Action != "update" || c.Events == nil || strings.Join(c.Events.Removed, ",") != "PreToolUse" || strings.Join(c.Events.Updated, ",") != "Stop" || len(c.Events.Added) != 0 {
t.Fatalf("narrowed entry: %+v %+v", c, c.Events)
}
narrowed := entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"echo stop"}]}]}}}}`)
p, err = e.service.PreviewMutation(Mutation{Name: "trial", Entry: narrowed})
must(t, err)
if c := p.Changes[0]; c.Action != "update" || strings.Join(c.Events.Removed, ",") != "PreToolUse" || len(c.Events.Updated) != 0 {
t.Fatalf("an entry that keeps Stop in the file is an update: %+v %+v", c, c.Events)
}
p, err = e.service.PreviewMutation(Mutation{Name: "trial", Remove: true})
must(t, err)
if c := p.Changes[0]; c.Action != "remove" || strings.Join(c.Events.Removed, ",") != "PreToolUse,Stop" {
t.Fatalf("leaving the file entirely is a remove: %+v %+v", c, c.Events)
}
}
func TestReplace_OwnedRegistrationEditedOutsideIsReplacedInPlace(t *testing.T) {
for _, viaSync := range []bool{false, true} {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
write(t, path, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"say done"}]}]}}`)
c := importOne(t, e.service, "claude", "claude-stop")
save(t, e.service, Mutation{Name: c.Name, Entry: &c.Entry, Adopt: true})
write(t, path, strings.Replace(read(t, path), "say done", "say finished", 1))
if p, _ := e.service.Preview(); !p.Blocked {
t.Fatalf("an outside edit is a conflict: %s", actions(p))
}
m := Mutation{Name: c.Name, Entry: &c.Entry, Replace: true}
if viaSync {
m = Mutation{Name: c.Name, Replace: true}
}
p, err := e.service.PreviewMutation(m)
must(t, err)
files := p.Files()
save(t, e.service, m)
got := events(t, path, true)["Stop"]
if len(got) != 1 || !strings.Contains(read(t, path), "say done") {
t.Fatalf("replace must take the edited group over in place (sync=%t):\n%s", viaSync, read(t, path))
}
if len(files) != 1 || files[0].After != read(t, path) {
t.Fatalf("preview after must match the written file: %+v", files)
}
if p, _ := e.service.Preview(); actions(p) != "claude:claude-stop:unchanged" {
t.Fatalf("after replace: %s", actions(p))
}
}
}
+68
View File
@@ -0,0 +1,68 @@
package hooks
import (
"path/filepath"
"strings"
"testing"
)
func TestUnmanage_KeepsNativeEntriesAndSyncLeavesThemAlone(t *testing.T) {
e := newEnv(t)
path := filepath.Join(e.home, ".claude", "settings.json")
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
before := read(t, path)
m := Mutation{Name: "guard", Remove: true, Unmanage: true}
p, err := e.service.PreviewMutation(m)
must(t, err)
if len(p.Changes) != 0 {
t.Fatalf("stop managing previews no change: %s", actions(p))
}
if _, err := e.service.Mutate(m, "", false); err != nil {
t.Fatal(err)
}
if read(t, path) != before {
t.Fatalf("native file changed:\n%s", read(t, path))
}
state, _, err := e.service.loadLedger()
must(t, err)
if len(state.Records) != 0 {
t.Fatalf("ownership kept: %+v", state.Records)
}
if p, _ = e.service.Preview(); len(p.Changes) != 0 {
t.Fatalf("sync still plans: %s", actions(p))
}
inv, err := e.service.List()
must(t, err)
if len(inv.Unmanaged) != 1 || inv.Unmanaged[0].Path != path {
t.Fatalf("entry is not listed as unmanaged: %+v", inv.Unmanaged)
}
if c, _ := e.service.Import(ImportRequest{From: "claude"}); len(c) != 1 {
t.Fatalf("entry is not importable again: %+v", c)
}
}
func TestUnmanage_InAProjectLeavesTheGlobalHookManaged(t *testing.T) {
e := newEnv(t)
root := filepath.Join(e.home, "projA")
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
save(t, e.service, Mutation{Project: root, Name: "guard", Entry: entry(t, claudeEntry)})
if _, err := e.service.Mutate(Mutation{Project: root, Name: "guard", Remove: true, Unmanage: true}, "", false); err != nil {
t.Fatal(err)
}
p, err := e.service.Preview()
must(t, err)
if actions(p) != "claude:guard:unchanged" {
t.Fatalf("only the global hook stays managed: %s", actions(p))
}
}
func TestUnmanage_Rejected(t *testing.T) {
e := newEnv(t)
save(t, e.service, Mutation{Name: "guard", Entry: entry(t, claudeEntry)})
if _, err := e.service.Mutate(Mutation{Name: "guard", Remove: true, Unmanage: true}, "", true); err == nil || !strings.Contains(err.Error(), "sync") {
t.Fatalf("with sync: %v", err)
}
if _, err := e.service.Mutate(Mutation{Name: "guard", Unmanage: true}, "", false); err == nil || !strings.Contains(err.Error(), "removing a named hook") {
t.Fatalf("without remove: %v", err)
}
}
+21 -16
View File
@@ -182,14 +182,14 @@ func TestCodexAccountSyncsIntoItsConfigToml(t *testing.T) {
}
}
// A Pi account keeps its own mcp-adapter.json, in the directory PI_CODING_AGENT_DIR moves.
func TestPiAccountSyncsIntoItsAdapterFile(t *testing.T) {
s, work := agentAccountService(t, "pi", "mcp:\n targets: [pi-work]\n servers:\n docs:\n url: https://example.com/mcp\n piExtension: pi-mcp-adapter\n")
// A Pi account keeps its own mcp.json, in the directory PI_CODING_AGENT_DIR moves.
func TestPiAccountSyncsIntoItsOwnFile(t *testing.T) {
s, work := agentAccountService(t, "pi", "mcp:\n targets: [pi-work]\n servers:\n docs:\n url: https://example.com/mcp\n")
plan, err := s.Preview()
if err != nil {
t.Fatal(err)
}
want := filepath.Join(work, "mcp-adapter.json")
want := filepath.Join(work, "mcp.json")
if len(plan.Changes) != 1 || plan.Changes[0].Target != "pi-work" || plan.Changes[0].Path != want {
t.Fatalf("changes: %+v", plan.Changes)
}
@@ -201,19 +201,24 @@ func TestPiAccountSyncsIntoItsAdapterFile(t *testing.T) {
}
}
// pi-mcp-extension reads ~/.pi/agent/mcp.json whatever the directory is, so it cannot
// serve an account.
func TestPiAccountRefusesTheExtensionThatIgnoresTheDirectory(t *testing.T) {
s, work := agentAccountService(t, "pi", "mcp:\n targets: [pi-work]\n servers:\n docs:\n url: https://example.com/mcp\n piExtension: pi-mcp-extension\n")
_, err := s.Preview()
if err == nil {
t.Fatal("pi-mcp-extension was accepted for an account")
// What an account's server had in the account's mcp-adapter.json is removed under the
// account's name, as its move to mcp.json is added.
func TestPiAccountAdapterEntryRemovedAsTheAccount(t *testing.T) {
s, work := agentAccountService(t, "pi", "mcp:\n targets: [pi-work]\n servers:\n docs:\n url: https://example.com/mcp\n piExtension: pi-mcp-adapter\n")
adapter, entry := filepath.Join(work, "mcp-adapter.json"), map[string]any{"url": "https://example.com/mcp"}
if err := writeJSONFile(adapter, map[string]any{"mcpServers": map[string]any{"docs": entry}}); err != nil {
t.Fatal(err)
}
// Nothing can be unset here, so the refusal names the account and what to select instead.
for _, want := range []string{"pi-work", work, "pi-mcp-adapter"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("the refusal does not say %q: %v", want, err)
}
record := ownership{Owner: s.ConfigPath, Target: "pi", Path: adapter, Name: "docs", Hash: entryHash(managedEntry("pi", entry))}
if err := writeJSONFile(s.statePath(), ledger{Version: 1, Entries: map[string]ownership{ownershipKey("pi", adapter, "docs"): record}}); err != nil {
t.Fatal(err)
}
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if c := changeFor(plan, adapter, "docs"); c == nil || c.Action != "remove" || c.Target != "pi-work" {
t.Fatalf("adapter entry: %+v", c)
}
}
+21
View File
@@ -133,6 +133,7 @@ func (s *Service) Check(opts CheckOptions) (*CheckReport, error) {
result.Findings = append(result.Findings, checkLaunch(server, opts)...)
}
result.Findings = append(result.Findings, preflight[k]...)
result.Findings = append(result.Findings, checkToolPolicy(source, k.root, server)...)
report.Servers = append(report.Servers, result)
}
byKey := map[checkKey]*CheckServer{}
@@ -302,6 +303,26 @@ func (s *Service) checkClientRules(source *Source, root, name string, server Ser
return out
}
// checkToolPolicy names each selected Agent that cannot hold a part of the server's tool
// policy, the same gaps the plan's notices list.
func checkToolPolicy(source *Source, root string, server Server) []CheckFinding {
defaults := source.Targets
if root != "" {
defaults = source.Projects[root].defaults(source)
}
var out []CheckFinding
for _, target := range server.Targets.orDefault(defaults) {
agent := target
if account, ok := source.Accounts[target]; ok {
agent = account.Agent
}
if gaps := toolPolicyGaps(agent, server.Tools); len(gaps) > 0 {
out = append(out, CheckFinding{Level: "warning", Check: "tools", Target: target, Message: toolPolicyMessage(target, gaps)})
}
}
return out
}
// syncFinding says whether an Agent's entry matches what the source asks for.
func syncFinding(c Change) CheckFinding {
f := CheckFinding{Level: "info", Check: "sync", Target: c.Target, Message: "in sync"}
+132 -28
View File
@@ -8,6 +8,8 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
@@ -40,6 +42,8 @@ type CheckLive struct {
ProtocolVersion string `json:"protocolVersion"`
ServerInfo LiveServerInfo `json:"serverInfo"`
Tools int `json:"tools"`
// ToolNames are the names tools/list returned, for choosing a tool policy.
ToolNames []string `json:"toolNames,omitempty"`
}
type LiveServerInfo struct {
@@ -149,15 +153,7 @@ func (p *liveProbe) redact(text string) string {
}
func (p *liveProbe) run() (*CheckLive, CheckFinding) {
ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
defer cancel()
var live *CheckLive
var err error
if p.server.Command != "" {
live, err = p.stdio(ctx)
} else {
live, err = p.http(ctx)
}
live, err := p.probe()
if err != nil {
var auth *authRequiredError
if errors.As(err, &auth) {
@@ -170,9 +166,6 @@ func (p *liveProbe) run() (*CheckLive, CheckFinding) {
}
return nil, CheckFinding{Level: "error", Check: "live", Message: p.redact("live probe failed: " + err.Error())}
}
live.ProtocolVersion = p.redact(live.ProtocolVersion)
live.ServerInfo.Name = p.redact(live.ServerInfo.Name)
live.ServerInfo.Version = p.redact(live.ServerInfo.Version)
who := strings.TrimSpace(live.ServerInfo.Name + " " + live.ServerInfo.Version)
if who == "" {
who = "unnamed server"
@@ -181,6 +174,111 @@ func (p *liveProbe) run() (*CheckLive, CheckFinding) {
Message: fmt.Sprintf("responds: %s, protocol %s, %d tool(s)", who, live.ProtocolVersion, live.Tools)}
}
// probe returns what the server reported about itself, with configured values redacted.
func (p *liveProbe) probe() (*CheckLive, error) {
ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
defer cancel()
var live *CheckLive
var err error
if p.server.Command != "" {
live, err = p.stdio(ctx)
} else {
live, err = p.http(ctx)
}
if err != nil {
return nil, err
}
live.ProtocolVersion = p.redact(live.ProtocolVersion)
live.ServerInfo.Name = p.redact(live.ServerInfo.Name)
live.ServerInfo.Version = p.redact(live.ServerInfo.Version)
for i, name := range live.ToolNames {
live.ToolNames[i] = p.redact(name)
}
return live, nil
}
// DraftProbe is a live probe of a server definition that is not saved.
type DraftProbe struct {
Live *CheckLive `json:"live,omitempty"`
// ErrorKind classifies a failure for a client to phrase: connect, timeout, auth,
// protocol, command, or unknown. Error is its detail, with configured values redacted.
ErrorKind string `json:"errorKind,omitempty"`
Error string `json:"error,omitempty"`
}
// ProbeDraft probes server as written rather than as saved, the way a live check probes a
// saved one; root is the mcp.projects root it belongs to. It saves and syncs nothing, and
// fails only for a definition that is not a valid server.
func ProbeDraft(server Server, root string, opts CheckOptions) (DraftProbe, error) {
if opts.LookupEnv == nil {
opts.LookupEnv = os.LookupEnv
}
if opts.LookPath == nil {
opts.LookPath = exec.LookPath
}
// Only the connection matters; a half-written tool policy must not stop a probe.
server = Server{Transport: server.Transport, Command: server.Command, Args: server.Args, URL: server.URL,
Env: server.Env, Headers: server.Headers, BearerToken: server.BearerToken}
if err := server.Validate("draft"); err != nil {
return DraftProbe{}, err
}
if missing := checkEnv(server, opts.LookupEnv); len(missing) > 0 {
return DraftProbe{ErrorKind: "auth", Error: missing[0].Message}, nil
}
for _, f := range checkLaunch(server, CheckOptions{SkipDNS: true, LookPath: opts.LookPath}) {
if f.Level == "error" {
return DraftProbe{ErrorKind: "command", Error: f.Message}, nil
}
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = DefaultLiveTimeout
}
p := newLiveProbe(server, root, timeout, opts)
live, err := p.probe()
if err != nil {
return DraftProbe{ErrorKind: liveErrorKind(err), Error: p.redact(err.Error())}, nil
}
return DraftProbe{Live: live}, nil
}
// liveErrorKind classifies why a probe failed.
func liveErrorKind(err error) string {
var auth *authRequiredError
var status *httpStatusError
var timeout *liveTimeoutError
var dns *net.DNSError
var op *net.OpError
var rpc *rpcError
var bad *protocolError
switch {
case errors.As(err, &auth), errors.As(err, &status) && (status.code == http.StatusUnauthorized || status.code == http.StatusForbidden):
return "auth"
case errors.As(err, &timeout):
return "timeout"
case errors.Is(err, exec.ErrNotFound), errors.Is(err, fs.ErrNotExist):
return "command"
case errors.As(err, &dns), errors.As(err, &op):
return "connect"
case errors.As(err, &status), errors.As(err, &rpc), errors.As(err, &bad):
return "protocol"
}
return "unknown"
}
// protocolError is a reply that is not the MCP a probe expects.
type protocolError struct{ message string }
func (e *protocolError) Error() string { return e.message }
func badReply(format string, args ...any) error {
return &protocolError{fmt.Sprintf(format, args...)}
}
type liveTimeoutError struct{ timeout time.Duration }
func (e *liveTimeoutError) Error() string { return fmt.Sprintf("no answer within %s", e.timeout) }
// rpcConn sends JSON-RPC over one transport. legacy switches it to a 2025-11-25 session.
type rpcConn interface {
call(ctx context.Context, method string, params any) (json.RawMessage, error)
@@ -233,14 +331,14 @@ func callResult(ctx context.Context, conn rpcConn, method string, params, out an
ResultType string `json:"resultType"`
}
if err := json.Unmarshal(raw, &kind); err != nil {
return fmt.Errorf("%s returned an invalid result", method)
return badReply("%s returned an invalid result", method)
}
// Servers before 2026-07-28 leave resultType out; that means complete.
if kind.ResultType != "" && kind.ResultType != "complete" {
return fmt.Errorf("%s returned resultType %q", method, kind.ResultType)
return badReply("%s returned resultType %q", method, kind.ResultType)
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("%s returned an invalid result", method)
return badReply("%s returned an invalid result", method)
}
return nil
}
@@ -253,7 +351,7 @@ func (p *liveProbe) handshake(ctx context.Context, conn rpcConn, discoverWait ti
live, err = p.initialize(ctx, conn)
}
if err != nil && ctx.Err() != nil {
return nil, fmt.Errorf("no answer within %s", p.timeout)
return nil, &liveTimeoutError{p.timeout}
}
return live, err
}
@@ -297,13 +395,14 @@ func (p *liveProbe) discover(ctx context.Context, conn rpcConn, wait time.Durati
}
live := &CheckLive{ProtocolVersion: liveProtocolVersion, ServerInfo: result.Meta.ServerInfo}
if _, ok := result.Capabilities["tools"]; ok {
live.Tools, err = countTools(ctx, conn, p.modernParams)
live.ToolNames, err = listTools(ctx, conn, p.modernParams)
live.Tools = len(live.ToolNames)
}
return live, err
}
func unsupportedVersions(versions []string) error {
return fmt.Errorf("server supports protocol version(s) %s; skillshare probes %s or the initialize handshake", strings.Join(versions, ", "), liveProtocolVersion)
return badReply("server supports protocol version(s) %s; skillshare probes %s or the initialize handshake", strings.Join(versions, ", "), liveProtocolVersion)
}
func (p *liveProbe) initialize(ctx context.Context, conn rpcConn) (*CheckLive, error) {
@@ -324,7 +423,7 @@ func (p *liveProbe) initialize(ctx context.Context, conn rpcConn) (*CheckLive, e
live := &CheckLive{ProtocolVersion: result.ProtocolVersion, ServerInfo: result.ServerInfo}
if _, ok := result.Capabilities["tools"]; ok {
var err error
live.Tools, err = countTools(ctx, conn, func(cursor string) map[string]any {
live.ToolNames, err = listTools(ctx, conn, func(cursor string) map[string]any {
if cursor == "" {
return map[string]any{}
}
@@ -333,27 +432,32 @@ func (p *liveProbe) initialize(ctx context.Context, conn rpcConn) (*CheckLive, e
if err != nil {
return nil, err
}
live.Tools = len(live.ToolNames)
}
return live, nil
}
func countTools(ctx context.Context, conn rpcConn, params func(cursor string) map[string]any) (int, error) {
count, cursor := 0, ""
func listTools(ctx context.Context, conn rpcConn, params func(cursor string) map[string]any) ([]string, error) {
names, cursor := []string{}, ""
for range liveMaxPages {
var page struct {
Tools []json.RawMessage `json:"tools"`
NextCursor string `json:"nextCursor"`
Tools []struct {
Name string `json:"name"`
} `json:"tools"`
NextCursor string `json:"nextCursor"`
}
if err := callResult(ctx, conn, "tools/list", params(cursor), &page); err != nil {
return 0, fmt.Errorf("tools/list: %w", err)
return nil, fmt.Errorf("tools/list: %w", err)
}
for _, tool := range page.Tools {
names = append(names, tool.Name)
}
count += len(page.Tools)
if page.NextCursor == "" {
break
}
cursor = page.NextCursor
}
return count, nil
return names, nil
}
// stdio starts the server, probes it over stdin/stdout, and always stops it again.
@@ -649,7 +753,7 @@ func (c *httpConn) call(ctx context.Context, method string, params any) (json.Ra
err = json.NewDecoder(body).Decode(msg)
}
if err != nil || (msg.Error == nil && msg.Result == nil) {
return nil, fmt.Errorf("%s: the response is not a JSON-RPC response", method)
return nil, badReply("%s: the response is not a JSON-RPC response", method)
}
case status.fallsBack():
// A modern server explains a rejection in a JSON-RPC error body.
@@ -729,7 +833,7 @@ func readSSE(r io.Reader, id string) (*rpcMessage, error) {
if err := scanner.Err(); err != nil {
return nil, err
}
return nil, errors.New("the event stream ended without a response")
return nil, badReply("the event stream ended without a response")
}
var resourceMetadataParam = regexp.MustCompile(`resource_metadata="([^"]*)"|resource_metadata=([^,\s]+)`)
+45 -8
View File
@@ -11,6 +11,7 @@ import (
"os/exec"
"os/signal"
"path/filepath"
"reflect"
"strings"
"syscall"
"testing"
@@ -137,8 +138,8 @@ func TestLiveStdioDiscover(t *testing.T) {
t.Fatal(err)
}
live, f := liveOf(t, report)
want := CheckLive{ProtocolVersion: "2026-07-28", ServerInfo: LiveServerInfo{Name: "helper", Version: "1.2.3"}, Tools: 2}
if f.Level != "info" || live == nil || *live != want || !report.Servers[0].OK {
want := CheckLive{ProtocolVersion: "2026-07-28", ServerInfo: LiveServerInfo{Name: "helper", Version: "1.2.3"}, Tools: 2, ToolNames: []string{"a", "b"}}
if f.Level != "info" || live == nil || !reflect.DeepEqual(*live, want) || !report.Servers[0].OK {
t.Fatalf("live = %+v, finding = %+v", live, f)
}
}
@@ -149,8 +150,8 @@ func TestLiveStdioFallsBackToInitialize(t *testing.T) {
t.Fatal(err)
}
live, f := liveOf(t, report)
want := CheckLive{ProtocolVersion: "2025-11-25", ServerInfo: LiveServerInfo{Name: "legacy", Version: "0.9"}, Tools: 3}
if live == nil || *live != want {
want := CheckLive{ProtocolVersion: "2025-11-25", ServerInfo: LiveServerInfo{Name: "legacy", Version: "0.9"}, Tools: 3, ToolNames: []string{"a", "b", "c"}}
if live == nil || !reflect.DeepEqual(*live, want) {
t.Fatalf("live = %+v, finding = %+v", live, f)
}
}
@@ -267,8 +268,8 @@ func TestLiveHTTPDiscoverJSON(t *testing.T) {
}
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": result})
})
want := CheckLive{ProtocolVersion: "2026-07-28", ServerInfo: LiveServerInfo{Name: "remote", Version: "2"}, Tools: 1}
if f.Level != "info" || report.Servers[0].Live == nil || *report.Servers[0].Live != want {
want := CheckLive{ProtocolVersion: "2026-07-28", ServerInfo: LiveServerInfo{Name: "remote", Version: "2"}, Tools: 1, ToolNames: []string{"x"}}
if f.Level != "info" || report.Servers[0].Live == nil || !reflect.DeepEqual(*report.Servers[0].Live, want) {
t.Fatalf("live = %+v, finding = %+v", report.Servers[0].Live, f)
}
}
@@ -308,8 +309,8 @@ func TestLiveHTTPFallsBackToInitialize(t *testing.T) {
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": map[string]any{"tools": []any{map[string]string{"name": "x"}, map[string]string{"name": "y"}}}})
}
})
want := CheckLive{ProtocolVersion: "2025-06-18", ServerInfo: LiveServerInfo{Name: "old", Version: "1"}, Tools: 2}
if report.Servers[0].Live == nil || *report.Servers[0].Live != want {
want := CheckLive{ProtocolVersion: "2025-06-18", ServerInfo: LiveServerInfo{Name: "old", Version: "1"}, Tools: 2, ToolNames: []string{"x", "y"}}
if report.Servers[0].Live == nil || !reflect.DeepEqual(*report.Servers[0].Live, want) {
t.Fatalf("live = %+v, finding = %+v", report.Servers[0].Live, f)
}
}
@@ -334,3 +335,39 @@ func TestLiveHTTPServerErrorIsError(t *testing.T) {
t.Fatalf("finding = %+v", f)
}
}
func TestProbeDraftErrorKinds(t *testing.T) {
status := func(code int) Server {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(code) }))
t.Cleanup(ts.Close)
return Server{URL: ts.URL + "/mcp"}
}
for name, tc := range map[string]struct {
server Server
want string
}{
"401": {status(http.StatusUnauthorized), "auth"},
"403": {status(http.StatusForbidden), "auth"},
"500": {status(http.StatusInternalServerError), "protocol"},
"unset variable": {Server{URL: "https://mcp.skillshare.invalid/mcp", BearerToken: &Value{FromEnv: "PROBE_DRAFT_UNSET"}}, "auth"},
"missing command": {Server{Command: "skillshare-probe-draft-missing"}, "command"},
} {
t.Run(name, func(t *testing.T) {
got, err := ProbeDraft(tc.server, "", CheckOptions{Timeout: 5 * time.Second, LookupEnv: func(string) (string, bool) { return "", false }})
if err != nil || got.ErrorKind != tc.want || got.Error == "" {
t.Fatalf("got %+v, %v; want kind %s", got, err, tc.want)
}
})
}
}
func TestProbeDraftTimesOut(t *testing.T) {
release := make(chan struct{})
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-release }))
defer ts.Close()
defer close(release)
got, err := ProbeDraft(Server{URL: ts.URL + "/mcp"}, "", CheckOptions{Timeout: 200 * time.Millisecond})
if err != nil || got.ErrorKind != "timeout" {
t.Fatalf("got %+v, %v", got, err)
}
}
+10 -26
View File
@@ -2,7 +2,6 @@ package mcp
import (
"fmt"
"maps"
"os"
"path/filepath"
"runtime"
@@ -16,33 +15,14 @@ type clientFormat struct {
stdioOnly bool
}
// piExtensionPath is the file pi-mcp-extension reads, next to pi-mcp-adapter's. Since its
// 3.0 the adapter reads mcp-adapter.json and leaves mcp.json to Pi's built-in MCP support,
// so nativePath gives the adapter's file. Refs: #298.
func piExtensionPath(adapterPath string) string {
return filepath.Join(filepath.Dir(adapterPath), "mcp.json")
}
// The older extension ignores Pi's global directory override and cannot use accounts.
func (s *Service) piModePath(mode string) (string, error) {
if mode == "pi-mcp-extension" && s.ProjectRoot == "" {
if s.account != "" {
return "", fmt.Errorf("pi-mcp-extension always reads ~/.pi/agent/mcp.json and cannot use account %s", s.account)
}
scoped := *s
scoped.ConfigDirs = maps.Clone(s.ConfigDirs)
delete(scoped.ConfigDirs, "pi")
s = &scoped
}
path, err := s.nativePath("pi")
if mode == "builtin" || mode == "pi-mcp-extension" {
path = piExtensionPath(path)
}
return path, err
// piAdapterPath is pi-mcp-adapter's file next to Pi's built-in mcp.json. Since 0.23.0
// Skillshare only reads it, to import from it, and removes the entries it wrote there.
func piAdapterPath(path string) string {
return filepath.Join(filepath.Dir(path), "mcp-adapter.json")
}
var clientFormats = map[string]clientFormat{
"pi": {key: "mcpServers", urlKey: "url", globalPath: ".pi/agent/mcp-adapter.json", projectPath: ".pi/mcp-adapter.json"},
"pi": {key: "mcpServers", urlKey: "url", refPrefix: "${", globalPath: ".pi/agent/mcp.json", projectPath: ".pi/mcp.json"},
"amp": {key: "amp.mcpServers", urlKey: "url", refPrefix: "${", globalPath: ".config/amp/settings.json", projectPath: ".amp/settings.json"},
"claude-desktop": {key: "mcpServers", urlKey: "url", stdioOnly: true},
"cline": {key: "mcpServers", localType: "stdio", remoteType: "streamableHttp", urlKey: "url", refPrefix: "${env:"},
@@ -137,7 +117,7 @@ func (s *Service) additionalClientPath(target string, format clientFormat) (stri
if !filepath.IsAbs(dir) {
return "", fmt.Errorf("PI_CODING_AGENT_DIR must be absolute")
}
return filepath.Join(dir, "mcp-adapter.json"), nil
return filepath.Join(dir, "mcp.json"), nil
}
case "copilot":
if dir := s.ConfigDirs["copilot"]; dir != "" {
@@ -214,7 +194,11 @@ func renderAdditionalClient(target string, format clientFormat, s Server) (map[s
}
}
if target == "copilot" {
// Copilot lists the tools it enables, by exact name, or "*" for all of them.
out["tools"] = []string{"*"}
if allow, _, _ := namedTools(s.Tools, false); allow != nil {
out["tools"] = allow
}
}
if target == "goose" {
out["enabled"] = true
+101 -120
View File
@@ -1,147 +1,108 @@
package mcp
import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
)
func TestDirectToolsRenderedOnlyForPiAdapter(t *testing.T) {
server := Server{Command: "echo", PiExtension: "pi-mcp-adapter", DirectTools: []any{"search", "fetch"}}
out, err := Render("pi", server)
if err != nil {
t.Fatal(err)
}
if list, ok := out["directTools"].([]any); !ok || len(list) != 2 {
t.Fatalf("pi entry: %v", out)
}
out, err = Render("opencode", server)
if err != nil || out["directTools"] != nil {
t.Fatalf("directTools leaked into another Agent: %v %v", out, err)
}
}
func TestDirectToolsRejected(t *testing.T) {
adapter := "pi-mcp-adapter"
for name, server := range map[string]Server{
"number": {Command: "echo", PiExtension: adapter, DirectTools: 3},
"unknown keyword": {Command: "echo", PiExtension: adapter, DirectTools: "all"},
"empty tool name": {Command: "echo", PiExtension: adapter, DirectTools: []any{""}},
"other extension": {Command: "echo", PiExtension: "pi-mcp-extension", DirectTools: true},
"no extension": {Command: "echo", DirectTools: true},
"switch only": {Disabled: true, PiExtension: adapter, DirectTools: true},
} {
if err := server.Validate("docs"); err == nil || !strings.Contains(err.Error(), "directTools") {
t.Errorf("%s: got %v", name, err)
}
}
for name, value := range map[string]any{"true": true, "false": false, "search": "search", "names": []any{"a"}} {
if err := (Server{Command: "echo", PiExtension: adapter, DirectTools: value}).Validate("docs"); err != nil {
t.Errorf("%s rejected: %v", name, err)
}
}
}
func TestDirectToolsSyncFollowsConfigAndKeepsHandAddedValue(t *testing.T) {
s := testService(t)
path := filepath.Join(s.Home, ".pi", "agent", "mcp-adapter.json")
sync := func(directTools, wantAction string) string {
t.Helper()
config := "mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piExtension: pi-mcp-adapter\n" + directTools
if err := os.WriteFile(s.ConfigPath, []byte(config), 0600); err != nil {
t.Fatal(err)
}
plan, err := s.Preview()
if err != nil || plan.Blocked || plan.Changes[0].Action != wantAction {
t.Fatalf("want %s, got %+v %v", wantAction, plan, err)
}
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(path)
return string(data)
}
sync("", "add")
// A value added by hand before Skillshare could set it must not become a conflict.
data, _ := os.ReadFile(path)
if err := os.WriteFile(path, []byte(strings.Replace(string(data), `"command"`, `"directTools": true, "command"`, 1)), 0600); err != nil {
t.Fatal(err)
}
if got := sync("", "unchanged"); !strings.Contains(got, `"directTools": true`) {
t.Fatalf("hand-added value lost: %s", got)
}
if got := sync(" directTools: [search]\n", "update"); !strings.Contains(got, `"search"`) || strings.Contains(got, `"directTools": true`) {
t.Fatalf("config value not written: %s", got)
}
sync(" directTools: [search]\n", "unchanged")
}
func TestDirectToolsImportedFromPi(t *testing.T) {
candidates, err := Import("pi", []byte(`{"mcpServers":{"docs":{"command":"docs","directTools":["search"]}}}`), "")
if err != nil || len(candidates) != 1 {
t.Fatalf("%+v %v", candidates, err)
}
if list, ok := candidates[0].Server.DirectTools.([]any); !ok || len(list) != 1 {
t.Fatalf("not imported: %+v", candidates[0])
}
for _, warning := range candidates[0].Warnings {
if strings.Contains(warning, "directTools") {
t.Fatalf("still reported as not imported: %s", warning)
}
}
}
func TestDirectToolsDefaultFillsPiServersWithoutTheirOwn(t *testing.T) {
// directTools and the adapter's includeTools/excludeTools were pi-mcp-adapter settings. Loading
// converts them to what Pi's built-in MCP reads, and the next save writes the result.
func TestDirectToolsConvertedOnLoad(t *testing.T) {
s, tmp := projectsService(t, `mcp:
targets: [pi, opencode]
targets: [pi]
directTools: true
servers:
inherits:
command: a
piExtension: pi-mcp-adapter
own:
elsewhere:
command: b
piExtension: pi-mcp-adapter
directTools: [search]
targets: [claude]
names:
command: c
directTools: [search, fetch]
held:
command: d
directTools: search
lists:
command: e
directTools: true
piOptions:
excludeTools: ["delete_*"]
includeTools: ["get_*"]
projects:
$TMP/quiet:
directTools: false
servers:
local:
command: c
piExtension: pi-mcp-adapter
targets: [pi]
$TMP/same:
servers:
local:
command: d
piExtension: pi-mcp-adapter
targets: [pi]
command: f
`)
source, err := LoadSource(s.ConfigPath)
if err != nil {
t.Fatal(err)
}
desired, err := s.render(source)
pi := func(name string) string {
data, _ := json.Marshal(source.Servers[name].PiOptions)
return string(data)
}
if got := pi("inherits"); got != `{"exposure":"direct"}` {
t.Errorf("mcp.directTools default: %s", got)
}
if got := source.Servers["elsewhere"]; got.PiOptions != nil || !got.Tools.IsZero() {
t.Errorf("the default reached a server without Pi: %+v", got)
}
if got := pi("names"); got != `{"toolExposure":{"search":"direct","fetch":"direct"}}` {
t.Errorf("a list keeps the other tools at Pi's default: %s", got)
}
if got := pi("held"); got != `{"exposure":"deferred"}` {
t.Errorf("search: %s", got)
}
if got, want := source.Servers["lists"].Tools, (ToolPolicy{Allow: []string{"get_*"}, Deny: []string{"delete_*"}}); !reflect.DeepEqual(got, want) || pi("lists") != `{"exposure":"direct"}` {
t.Errorf("tool lists: %+v %v", got, source.Servers["lists"].PiOptions)
}
if got := source.Projects[filepath.Join(tmp, "quiet")].Servers["local"]; got.PiOptions != nil {
t.Errorf("a project's false overrides the global default: %+v", got)
}
if len(source.Notices) != 1 || !strings.HasSuffix(source.Notices[0], "the next sync converts them: held, inherits, lists, names") {
t.Fatalf("notices: %q", source.Notices)
}
if _, err := s.Mutate(Mutation{Name: "other", Server: &Server{Command: "other"}}, "", false); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(s.ConfigPath)
for _, gone := range []string{"directTools", "excludeTools", "includeTools"} {
if strings.Contains(string(data), gone) {
t.Fatalf("saved config keeps %s: %s", gone, data)
}
}
if source, err = LoadSource(s.ConfigPath); err != nil || len(source.Notices) != 0 || pi("inherits") != `{"exposure":"direct"}` {
t.Fatalf("after save: %v %v", source.Notices, err)
}
}
// A setting that would overwrite exposure the server already sets is dropped, and said so.
func TestDirectToolsDroppedWhenExposureIsSet(t *testing.T) {
s, _ := projectsService(t, `mcp:
targets: [pi]
servers:
docs:
command: a
directTools: true
piOptions:
exposure: hidden
`)
source, err := LoadSource(s.ConfigPath)
if err != nil {
t.Fatal(err)
}
global := desired[fileKey{filepath.Join(tmp, ".pi", "agent", "mcp-adapter.json"), "pi"}]
if global["inherits"]["directTools"] != true {
t.Errorf("default not applied: %v", global["inherits"])
if got := source.Servers["docs"].PiOptions["exposure"]; got != "hidden" {
t.Fatalf("exposure: %v", got)
}
if list, ok := global["own"]["directTools"].([]any); !ok || len(list) != 1 {
t.Errorf("server value lost to the default: %v", global["own"])
}
if got := desired[fileKey{filepath.Join(tmp, "quiet", ".pi", "mcp-adapter.json"), "pi"}]["local"]["directTools"]; got != false {
t.Errorf("project default ignored: %v", got)
}
if got := desired[fileKey{filepath.Join(tmp, "same", ".pi", "mcp-adapter.json"), "pi"}]["local"]["directTools"]; got != true {
t.Errorf("project did not inherit the global default: %v", got)
}
if _, leaked := desired[fileKey{filepath.Join(tmp, ".config", "opencode", "opencode.json"), "opencode"}]["inherits"]["directTools"]; leaked {
t.Error("default leaked into another Agent")
if len(source.Notices) != 2 || !strings.HasSuffix(source.Notices[1], "are dropped; the next sync removes them: docs") {
t.Fatalf("notices: %q", source.Notices)
}
}
@@ -152,10 +113,30 @@ func TestDirectToolsDefaultRejectsBadValue(t *testing.T) {
}
}
func TestDirectToolsDefaultShowsInTheDashboardPreview(t *testing.T) {
s, _ := projectsService(t, "mcp:\n targets: [pi]\n directTools: search\n")
got := s.RenderNative("docs", Server{Command: "docs", PiExtension: "pi-mcp-adapter", Targets: []string{"pi"}})
if got[0].Error != "" || !strings.Contains(got[0].Content, `"directTools": "search"`) {
t.Fatalf("preview left out the default sync would write: %+v", got[0])
// A dashboard that still sends directTools gets the same conversion.
func TestServerJSONConvertsDirectTools(t *testing.T) {
var server Server
if err := json.Unmarshal([]byte(`{"command":"docs","directTools":true}`), &server); err != nil || server.PiOptions["exposure"] != "direct" {
t.Fatalf("%+v %v", server, err)
}
var settings Mutation
if err := json.Unmarshal([]byte(`{"settings":{"targets":["pi"],"directTools":true}}`), &settings); err != nil {
t.Fatalf("settings.directTools must still be accepted: %v", err)
}
}
func TestAdapterToolsImportedFromPi(t *testing.T) {
candidates, err := Import("pi", []byte(`{"mcpServers":{"docs":{"command":"docs","directTools":true,"excludeTools":["delete_*"],"lifecycle":"eager"}}}`), "")
if err != nil || len(candidates) != 1 || len(candidates[0].Problems) != 0 {
t.Fatalf("%+v %v", candidates, err)
}
if got, want := candidates[0].Server.Tools, (ToolPolicy{Deny: []string{"delete_*"}}); !reflect.DeepEqual(got, want) {
t.Fatalf("tools: %+v", got)
}
if got := candidates[0].Server.PiOptions; len(got) != 1 || got["exposure"] != "direct" {
t.Fatalf("directTools becomes piOptions.exposure, and nothing else reaches piOptions: %v", got)
}
if warnings := strings.Join(candidates[0].Warnings, ";"); !strings.Contains(warnings, "converted") || !strings.Contains(warnings, "not imported, because Pi's built-in MCP does not read it: lifecycle") {
t.Fatalf("warnings: %v", candidates[0].Warnings)
}
}
+66 -17
View File
@@ -15,7 +15,7 @@ import (
func TestDisabledTurnsOffGlobalServerInProject(t *testing.T) {
s := testService(t)
s.ProjectRoot = filepath.Join(s.Home, "project")
source := "mcp:\n servers:\n docs:\n disabled: true\n piExtension: pi-mcp-adapter\n targets: [opencode, kilocode, pi]\n"
source := "mcp:\n servers:\n docs:\n disabled: true\n targets: [opencode, kilocode]\n"
if err := os.WriteFile(s.ConfigPath, []byte(source), 0600); err != nil {
t.Fatal(err)
}
@@ -27,9 +27,8 @@ func TestDisabledTurnsOffGlobalServerInProject(t *testing.T) {
t.Fatal(err)
}
for file, want := range map[string]string{
"opencode.json": `{"mcp":{"docs":{"enabled":false}}}`,
"kilo.jsonc": `{"mcp":{"docs":{"enabled":false}}}`,
".pi/mcp-adapter.json": `{"mcpServers":{"docs":{"disabled":true}}}`,
"opencode.json": `{"mcp":{"docs":{"enabled":false}}}`,
"kilo.jsonc": `{"mcp":{"docs":{"enabled":false}}}`,
} {
data, err := os.ReadFile(filepath.Join(s.ProjectRoot, file))
if err != nil {
@@ -45,13 +44,13 @@ func TestDisabledTurnsOffGlobalServerInProject(t *testing.T) {
t.Fatalf("%s: got %s want %s", file, a, b)
}
}
if plan, err = s.Preview(); err != nil || len(plan.Changes) != 3 || plan.Changes[0].Action != "unchanged" {
if plan, err = s.Preview(); err != nil || len(plan.Changes) != 2 || plan.Changes[0].Action != "unchanged" {
t.Fatalf("not idempotent: %+v %v", plan, err)
}
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n servers: {}\n"), 0600); err != nil {
t.Fatal(err)
}
if plan, err = s.Preview(); err != nil || len(plan.Changes) != 3 || plan.Changes[0].Action != "remove" {
if plan, err = s.Preview(); err != nil || len(plan.Changes) != 2 || plan.Changes[0].Action != "remove" {
t.Fatalf("switch not removed with its source: %+v %v", plan, err)
}
}
@@ -65,7 +64,6 @@ func TestDisabledRejected(t *testing.T) {
"global mode": {false, "disabled: true\n targets: [opencode]", "project"},
"whole-entry agent": {true, "disabled: true\n targets: [cursor]", "cursor"},
"codex": {true, "disabled: true\n targets: [codex]", "whole config"},
"pi extension": {true, "disabled: true\n piExtension: pi-mcp-extension\n targets: [pi]", "pi-mcp-adapter"},
"with a command": {true, "disabled: true\n command: tool\n targets: [opencode]", "leave out"},
} {
t.Run(name, func(t *testing.T) {
@@ -83,6 +81,19 @@ func TestDisabledRejected(t *testing.T) {
}
}
// Loading drops pi from an old switch, but saving a new one for pi still fails.
func TestPiSwitchRejectedOnSave(t *testing.T) {
s := testService(t)
s.ProjectRoot = filepath.Join(s.Home, "project")
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n servers: {}\n"), 0600); err != nil {
t.Fatal(err)
}
_, err := s.Mutate(Mutation{Name: "docs", Server: &Server{Disabled: true, Targets: []string{"pi"}}}, "", false)
if err == nil || !strings.Contains(err.Error(), "pi cannot turn off") {
t.Fatalf("got %v", err)
}
}
// The dashboard's preview must refuse what saving would refuse.
func TestPreviewRefusesDisabledInGlobalMode(t *testing.T) {
s := testService(t)
@@ -281,8 +292,8 @@ func TestPlanMarksSwitchOnlyChanges(t *testing.T) {
}
return got
}
want := map[string]bool{"opencode/docs": true, "pi/docs": true, "claude/docs": true, "opencode/own": false}
added := marks("mcp:\n servers:\n docs:\n disabled: true\n piExtension: pi-mcp-adapter\n targets: [opencode, pi, claude]\n own:\n command: tool\n targets: [opencode]\n", "add")
want := map[string]bool{"opencode/docs": true, "claude/docs": true, "opencode/own": false}
added := marks("mcp:\n servers:\n docs:\n disabled: true\n targets: [opencode, claude]\n own:\n command: tool\n targets: [opencode]\n", "add")
if !maps.Equal(added, want) {
t.Fatalf("add: got %v want %v", added, want)
}
@@ -299,12 +310,12 @@ func TestSwitchWithoutTargetsFollowsTheProject(t *testing.T) {
global, project string
want []string
}{
"only what the project uses": {"claude, opencode, kilocode, pi", "opencode, pi", []string{"opencode", "pi"}},
"only what the project uses": {"claude, opencode, kilocode, pi", "opencode, kilocode", []string{"kilocode", "opencode"}},
"only what the server reaches": {"claude, codex, pi", "claude, opencode", []string{"claude"}},
"skips an Agent with no switch": {"cursor, opencode", "cursor, opencode", []string{"opencode"}},
"skips an Agent with no switch": {"cursor, opencode, pi", "cursor, opencode, pi", []string{"opencode"}},
} {
t.Run(name, func(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n piExtension: pi-mcp-adapter\n targets: ["+tc.global+"]\n projects:\n $TMP/p1:\n targets: ["+tc.project+"]\n servers:\n docs:\n disabled: true\n")
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n targets: ["+tc.global+"]\n projects:\n $TMP/p1:\n targets: ["+tc.project+"]\n servers:\n docs:\n disabled: true\n")
plan, err := s.Preview()
if err != nil {
t.Fatal(err)
@@ -323,11 +334,10 @@ func TestSwitchWithoutTargetsFollowsTheProject(t *testing.T) {
}
}
// Pi reads one config file per project, through one extension. Where the project's own
// servers use pi-mcp-extension, Pi has no switch there, so the switch leaves Pi alone
// instead of failing the whole plan over two extensions in one file.
func TestSwitchLeavesPiAloneWhereTheProjectUsesAnotherExtension(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n piExtension: pi-mcp-adapter\n targets: [opencode, pi]\n projects:\n $TMP/p1:\n targets: [opencode, pi]\n servers:\n mine:\n command: tool\n piExtension: pi-mcp-extension\n targets: [pi]\n docs:\n disabled: true\n")
// Pi's built-in MCP has no per-project switch, so a switch that names no targets leaves Pi
// alone even where the project and the global server both reach it.
func TestSwitchLeavesPiAlone(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n targets: [opencode, pi]\n projects:\n $TMP/p1:\n targets: [opencode, pi]\n servers:\n mine:\n command: tool\n targets: [pi]\n docs:\n disabled: true\n")
plan, err := s.Preview()
if err != nil {
t.Fatal(err)
@@ -342,3 +352,42 @@ func TestSwitchLeavesPiAloneWhereTheProjectUsesAnotherExtension(t *testing.T) {
t.Fatalf("got %v", got)
}
}
// Before 0.23.0 an adapter user could turn a global server off for one project in Pi. Pi's
// built-in MCP has no such switch, so loading drops pi from the entry instead of failing sync.
func TestPiSwitchLeavesPiOnLoad(t *testing.T) {
s, tmp := projectsService(t, `mcp:
targets: [opencode]
projects:
$TMP/both:
servers:
docs:
disabled: true
targets: [pi, opencode]
$TMP/only:
servers:
docs:
disabled: true
targets: [pi]
`)
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if len(plan.Changes) != 1 || plan.Changes[0].Target != "opencode" || plan.Changes[0].Root != filepath.Join(tmp, "both") {
t.Fatalf("changes: %+v", plan.Changes)
}
if want := "Pi cannot turn off a server per project; the next sync removes pi from these entries: docs (both, only)"; len(plan.Notices) != 1 || plan.Notices[0] != want {
t.Fatalf("notices: %q", plan.Notices)
}
if _, err := s.Mutate(Mutation{Name: "other", Server: &Server{Command: "other"}}, "", false); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(s.ConfigPath)
if strings.Contains(string(data), "- pi") || strings.Count(string(data), "- opencode") != 2 || !strings.Contains(string(data), "targets: []") {
t.Fatalf("saved config: %s", data)
}
if source, err := LoadSource(s.ConfigPath); err != nil || len(source.Notices) != 0 {
t.Fatalf("%v %v", source, err)
}
}
+68 -78
View File
@@ -6,7 +6,6 @@ import (
"net/url"
"path/filepath"
"regexp"
"slices"
"strings"
"github.com/tailscale/hujson"
@@ -121,7 +120,7 @@ func detectJSONFormat(data []byte) string {
// Import parses a native file or a single JSON entry without persisting it.
func Import(target string, data []byte, singleName string) ([]Candidate, error) {
return importPiMode(target, data, singleName, "")
return importNative(target, data, singleName, false)
}
// DetectImportFormat identifies a native JSON shape; ambiguous connections use Claude's shape.
@@ -129,15 +128,9 @@ func DetectImportFormat(data []byte) string {
return detectJSONFormat(data)
}
// ImportPi parses an exported Pi file using the mode explicitly selected by the caller.
func ImportPi(data []byte, singleName, mode string) ([]Candidate, error) {
if mode != "builtin" && mode != "pi-mcp-adapter" && mode != "pi-mcp-extension" {
return nil, fmt.Errorf("unsupported Pi MCP import mode %q", mode)
}
return importPiMode("pi", data, singleName, mode)
}
func importPiMode(target string, data []byte, singleName, mode string) ([]Candidate, error) {
// importNative converts native entries to portable drafts. adapter marks pi-mcp-adapter's
// mcp-adapter.json, whose !! escapes a literal beginning with !.
func importNative(target string, data []byte, singleName string, adapter bool) ([]Candidate, error) {
if target == "" {
target = detectJSONFormat(data)
}
@@ -163,7 +156,6 @@ func importPiMode(target string, data []byte, singleName, mode string) ([]Candid
out := []Candidate{}
for _, name := range sortedKeys(native.Entries) {
entry := native.Entries[name]
_, piTransport := entry["transport"]
c := Candidate{Name: name, Problems: []string{}, Warnings: []string{}}
normalizeClientImport(target, entry, &c)
if target == "antigravity" {
@@ -215,19 +207,34 @@ func importPiMode(target string, data []byte, singleName, mode string) ([]Candid
if target == "codex" {
allowed = map[string]bool{"command": true, "args": true, "url": true, "env": true, "env_vars": true, "http_headers": true, "env_http_headers": true, "bearer_token_env_var": true}
}
if target == "pi" && mode != "pi-mcp-extension" {
allowed["directTools"] = true
if c.Server.DirectTools = entry["directTools"]; c.Server.DirectTools != nil {
// Only pi-mcp-adapter has this field, so the file does identify the extension.
c.Server.PiExtension = "pi-mcp-adapter"
}
if target == "codex" {
importCodexTools(entry, &c)
allowed["enabled_tools"], allowed["disabled_tools"] = true, true
}
if target == "pi" && mode != "pi-mcp-extension" && (mode != "" || !piTransport) {
if target == "copilot" {
importCopilotTools(entry, &c)
allowed["tools"] = true
}
if target == "pi" {
// pi-mcp-adapter's settings: its tool lists convert, the rest Pi does not read.
list := func(key string) []any {
value, set := entry[key]
if !set {
return nil
}
if items, ok := value.([]any); ok && items != nil {
return items
}
return []any{}
}
directTools, include, exclude := entry["directTools"], list("includeTools"), list("excludeTools")
for _, key := range append([]string{"directTools", "includeTools", "excludeTools"}, adapterPiOptions...) {
if _, set := entry[key]; set {
allowed[key] = true
}
}
for key, value := range entry {
if !allowed[key] {
if mode == "pi-mcp-adapter" && (key == "exposure" || key == "toolExposure") {
c.Warnings = append(c.Warnings, "Pi built-in field imported as a pi-mcp-adapter option; verify adapter support: "+key)
}
if c.Server.PiOptions == nil {
c.Server.PiOptions = PiOptions{}
}
@@ -235,16 +242,22 @@ func importPiMode(target string, data []byte, singleName, mode string) ([]Candid
allowed[key] = true
}
}
if len(c.Server.PiOptions) > 0 && c.Server.PiExtension == "" {
c.Server.PiExtension = "builtin"
if entry["excludeTools"] != nil || entry["approveTools"] != nil {
c.Server.PiExtension = "pi-mcp-adapter"
importPiTools(&c)
if directTools != nil || include != nil || exclude != nil {
before, _ := json.Marshal(c.Server)
dropped := c.Server.adoptAdapterTools(directTools, include, exclude)
if after, _ := json.Marshal(c.Server); string(after) != string(before) {
c.Warnings = append(c.Warnings, "pi-mcp-adapter's directTools, includeTools and excludeTools are converted to Pi's exposure settings and tools")
}
for _, key := range dropped {
c.Warnings = append(c.Warnings, "pi-mcp-adapter setting not imported: "+key+"; the entry already sets that part of its tool exposure, or it is not a list of tool names")
}
}
for _, key := range adapterPiOptions {
if _, set := entry[key]; set {
c.Warnings = append(c.Warnings, "pi-mcp-adapter setting not imported, because Pi's built-in MCP does not read it: "+key)
}
}
}
if target == "pi" && mode != "" {
c.Server.PiExtension = mode
c.Warnings = slices.DeleteFunc(c.Warnings, func(w string) bool { return w == piExtensionWarning })
}
// Agent-only fields such as timeouts stay in existing Agent entries on sync.
for _, key := range sortedKeys(entry) {
@@ -295,9 +308,9 @@ func importPiMode(target string, data []byte, singleName, mode string) ([]Candid
c.Problems = append(c.Problems, key+" values must be strings")
continue
}
if target == "pi" && c.Server.PiExtension == "pi-mcp-adapter" && strings.HasPrefix(value, "!!") {
if target == "pi" && adapter && strings.HasPrefix(value, "!!") {
value = strings.TrimPrefix(value, "!")
} else if target == "pi" && c.Server.PiExtension != "pi-mcp-extension" && strings.HasPrefix(value, "!") {
} else if target == "pi" && strings.HasPrefix(value, "!") {
c.Problems = append(c.Problems, "Pi command-based credentials must remain in Pi; use an environment reference to import this connection")
continue
}
@@ -432,15 +445,17 @@ func (s *Service) ImportClient(target string) ([]Candidate, error) {
return s.ImportClientMode(target, "")
}
// ImportClientMode reads exactly the selected Pi mode's file. With no mode,
// legacy callers still read both files, with adapter entries taking precedence.
func (s *Service) ImportClientMode(target, piMode string) ([]Candidate, error) {
// ImportClientMode reads the target's file. Pi's pi-mcp-adapter file is still read, never
// written, so servers written there by hand can move to Pi's built-in MCP: with no piFile,
// both files, mcp.json first, and "pi-mcp-adapter" reads only the adapter's file. Any other
// piFile, which named a Pi MCP mode before 0.23.0, reads only mcp.json.
func (s *Service) ImportClientMode(target, piFile string) ([]Candidate, error) {
client, format, err := s.importClient(target)
if err != nil {
return nil, err
}
if piMode != "" && (format != "pi" || (piMode != "builtin" && piMode != "pi-mcp-adapter" && piMode != "pi-mcp-extension")) {
return nil, fmt.Errorf("unsupported Pi MCP import mode %q for %s", piMode, target)
if piFile != "" && (format != "pi" || (piFile != "builtin" && piFile != "pi-mcp-adapter" && piFile != "pi-mcp-extension")) {
return nil, fmt.Errorf("unsupported Pi MCP file %q for %s", piFile, target)
}
path, err := client.nativePath(format)
if err != nil {
@@ -448,16 +463,11 @@ func (s *Service) ImportClientMode(target, piMode string) ([]Candidate, error) {
}
paths := []string{path}
if format == "pi" {
switch piMode {
case "builtin", "pi-mcp-extension":
path, err = client.piModePath(piMode)
if err != nil {
return nil, err
}
paths = []string{path}
switch piFile {
case "":
paths = append(paths, piAdapterPath(path))
case "pi-mcp-adapter":
default:
paths = append(paths, piExtensionPath(path))
paths = []string{piAdapterPath(path)}
}
}
items, found := []Candidate{}, false
@@ -471,25 +481,20 @@ func (s *Service) ImportClientMode(target, piMode string) ([]Candidate, error) {
continue
}
found = true
mode := piMode
if format == "pi" && mode == "" && path == paths[0] {
mode = "pi-mcp-adapter"
}
read, err := importPiMode(format, data, "", mode)
adapter := format == "pi" && path == piAdapterPath(path)
read, err := importNative(format, data, "", adapter)
if err != nil {
return nil, err
}
for _, item := range read {
// mcp-adapter.json comes first and wins a name both files define.
// mcp.json comes first and wins a name both files define.
if seen[item.Name] {
continue
}
seen[item.Name] = true
item.From = target
if format == "pi" && mode == "pi-mcp-adapter" {
// Only pi-mcp-adapter reads this file, so it does identify the extension.
item.Server.PiExtension = "pi-mcp-adapter"
item.Warnings = slices.DeleteFunc(item.Warnings, func(w string) bool { return w == piExtensionWarning })
if adapter {
item.Warnings = append(item.Warnings, "Imported from pi-mcp-adapter's mcp-adapter.json; sync writes it to Pi's built-in mcp.json and leaves the adapter's file as it is")
}
items = append(items, item)
}
@@ -506,7 +511,7 @@ func (s *Service) ImportProjectClient(root, target string) ([]Candidate, error)
}
// ImportProjectClientMode selects a Pi file within a configured project root.
func (s *Service) ImportProjectClientMode(root, target, piMode string) ([]Candidate, error) {
func (s *Service) ImportProjectClientMode(root, target, piFile string) ([]Candidate, error) {
source, err := LoadSource(s.ConfigPath)
if err != nil {
return nil, err
@@ -517,10 +522,11 @@ func (s *Service) ImportProjectClientMode(root, target, piMode string) ([]Candid
}
scoped := *s
scoped.ProjectRoot = root
return scoped.ImportClientMode(target, piMode)
return scoped.ImportClientMode(target, piFile)
}
// ImportSource is one selectable native file and, for Pi, its parsing mode.
// ImportSource is one selectable native file. For Pi, PiExtension says which of its files:
// builtin for mcp.json, or pi-mcp-adapter for the adapter's file, read-only since 0.23.0.
type ImportSource struct {
Target string `json:"target"`
Path string `json:"path"`
@@ -546,23 +552,7 @@ func (s *Service) ImportSources(source *Source) map[string][]ImportSource {
for _, target := range sortedKeys(paths) {
path := paths[target]
if target == "pi" || source.Accounts[target].Agent == "pi" {
for _, mode := range []string{"builtin", "pi-mcp-adapter", "pi-mcp-extension"} {
if mode == "pi-mcp-extension" && target != "pi" {
continue
}
file := path
if mode != "pi-mcp-adapter" {
file = piExtensionPath(path)
}
if mode == "pi-mcp-extension" {
var err error
file, err = scope.piModePath(mode)
if err != nil {
continue
}
}
result[root] = append(result[root], ImportSource{Target: target, Path: file, PiExtension: mode})
}
result[root] = append(result[root], ImportSource{Target: target, Path: path, PiExtension: "builtin"}, ImportSource{Target: target, Path: piAdapterPath(path), PiExtension: "pi-mcp-adapter"})
} else {
result[root] = append(result[root], ImportSource{Target: target, Path: path})
}
@@ -608,11 +598,11 @@ func (s *Service) FindUnmanaged(source *Source) []Unmanaged {
found = append(found, Unmanaged{Target: target, Project: root, Path: path, Names: names})
}
}
// Pi's two files belong to different extensions, and ImportClient reads both.
// ImportClient still reads pi-mcp-adapter's file next to Pi's own.
scan := func(target, format, path, root string, defined map[string]Server) {
scanFile(target, format, path, root, defined)
if format == "pi" {
scanFile(target, format, piExtensionPath(path), root, defined)
scanFile(target, format, piAdapterPath(path), root, defined)
}
}
paths := s.ClientPaths()
+68 -3
View File
@@ -1,7 +1,9 @@
package mcp
// piExtensionWarning asks for the extension that an entry of Pi's mcp.json was written for.
const piExtensionWarning = "Select the Pi MCP mode (builtin, pi-mcp-adapter or pi-mcp-extension); mcp.json alone does not identify the mode"
import (
"slices"
"strings"
)
// Normalize native dialects before applying the common import validation.
func normalizeClientImport(target string, entry map[string]any, c *Candidate) {
@@ -10,7 +12,6 @@ func normalizeClientImport(target string, entry map[string]any, c *Candidate) {
entry["type"] = kind
delete(entry, "transport")
}
c.Warnings = append(c.Warnings, piExtensionWarning)
}
format, ok := clientFormats[target]
if !ok {
@@ -57,3 +58,67 @@ func normalizeClientImport(target string, entry map[string]any, c *Candidate) {
c.Problems = append(c.Problems, "Claude Desktop config files support only stdio servers")
}
}
// importPiTools moves Pi's toolExposure into tools when writing that policy back gives Pi
// the same settings. Otherwise it stays in piOptions, for Pi only. exposure always stays
// in piOptions.
func importPiTools(c *Candidate) {
if c.Server.PiOptions["toolExposure"] == nil {
return
}
policy, ok := piImportPolicy(c.Server.PiOptions)
if !ok {
c.Warnings = append(c.Warnings, "Pi's toolExposure stays in piOptions and applies to Pi only; tools cannot express it exactly")
return
}
delete(c.Server.PiOptions, "toolExposure")
if len(c.Server.PiOptions) == 0 {
c.Server.PiOptions = nil
}
c.Server.Tools = policy
}
// importCopilotTools reads Copilot's list of enabled tools into tools.allow. "*", Copilot's
// default, enables every tool, which is no policy.
func importCopilotTools(entry map[string]any, c *Candidate) {
raw, set := entry["tools"]
if !set {
return
}
items, _ := raw.([]any)
if slices.Contains(items, any("*")) {
return
}
names := toolNames(items)
policy := ToolPolicy{Allow: names}
if len(names) == 0 || len(names) != len(items) || slices.ContainsFunc(names, isToolPattern) || policy.validate("") != nil {
c.Warnings = append(c.Warnings, "Copilot tools not imported: only a list of exact tool names or \"*\" maps to tools.allow")
return
}
c.Server.Tools = policy
}
// importCodexTools reads Codex's enabled_tools and disabled_tools into tools.allow and
// tools.deny. Both list exact tool names; an empty enabled_tools, no tool at all, has no
// equivalent.
func importCodexTools(entry map[string]any, c *Candidate) {
var policy ToolPolicy
for key, dest := range map[string]*[]string{"enabled_tools": &policy.Allow, "disabled_tools": &policy.Deny} {
raw, set := entry[key]
if !set {
continue
}
items, _ := raw.([]any)
names := toolNames(items)
if len(names) == 0 || len(names) != len(items) || slices.ContainsFunc(names, isToolPattern) {
c.Warnings = append(c.Warnings, "Codex "+key+" not imported: only a non-empty list of exact tool names maps to tools")
continue
}
*dest = names
}
if err := policy.validate(""); err != nil {
c.Warnings = append(c.Warnings, "Codex enabled_tools and disabled_tools not imported: "+strings.TrimPrefix(err.Error(), "MCP : "))
return
}
c.Server.Tools = policy
}
+4 -3
View File
@@ -297,9 +297,10 @@ func TestNoTargetsSurvivesSaveAndTheAPI(t *testing.T) {
}
}
func TestDisabledEntryStillNeedsATarget(t *testing.T) {
if err := (Server{Disabled: true, Targets: []string{}}).Validate("docs"); err == nil {
t.Fatal("accepted a switch that turns nothing off")
// A switch whose only target was pi loses it on load and stays, turning nothing off.
func TestDisabledEntryMayHaveNoTargets(t *testing.T) {
if err := (Server{Disabled: true, Targets: []string{}}).Validate("docs"); err != nil {
t.Fatal(err)
}
}
+174
View File
@@ -0,0 +1,174 @@
package mcp
import (
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
)
const legacyConfig = `# my MCP servers
mcp:
targets: [pi, opencode]
directTools: search
servers:
ext:
command: a
piExtension: pi-mcp-adapter
prune:
command: b
piOptionsPrune: true
adapter:
command: c
piOptions:
idleTimeout: 5
lists:
command: d
piOptions:
includeTools: [get_*]
projects:
$TMP/shop:
servers:
ext:
disabled: true
targets: [pi, opencode]
`
var retiredFields = []string{"piExtension", "piOptionsPrune", "idleTimeout", "includeTools", "directTools", "[pi, opencode]"}
// legacyService is a service over legacyConfig that records the files it backs up.
func legacyService(t *testing.T) (*Service, *[]string) {
t.Helper()
s, tmp := projectsService(t, legacyConfig)
if err := os.MkdirAll(filepath.Join(tmp, "shop"), 0700); err != nil {
t.Fatal(err)
}
backups := &[]string{}
s.BackupSource = func(path string) (string, error) {
*backups = append(*backups, path)
return path + ".bak", nil
}
return s, backups
}
func assertMigrated(t *testing.T, path string) {
t.Helper()
data, _ := os.ReadFile(path)
for _, gone := range retiredFields {
if strings.Contains(string(data), gone) {
t.Fatalf("saved config keeps %s:\n%s", gone, data)
}
}
if !strings.Contains(string(data), "# my MCP servers") {
t.Fatalf("saving dropped the comment:\n%s", data)
}
source, err := LoadSource(path)
if err != nil || len(source.Notices) != 0 || source.NeedsMigration() {
t.Fatalf("after sync: %q %v", source.Notices, err)
}
}
// A sync saves the config without the settings 0.23.0 retired, backed up first, so the
// notices naming them go away.
func TestSyncSavesTheConfigWithoutRetiredSettings(t *testing.T) {
s, backups := legacyService(t)
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
// Five retired kinds, the tool policy lists converted from includeTools, and what Pi's
// built-in MCP needs, which the sync keeps saying after the config is saved.
if len(plan.Notices) != 7 || plan.Notices[6] != PiBuiltinNotice || !plan.Migrates {
t.Fatalf("notices: %q", plan.Notices)
}
result, err := s.Apply(plan.Revision)
if err != nil {
t.Fatal(err)
}
if want := []MigratedFile{{s.ConfigPath, s.ConfigPath + ".bak"}}; !reflect.DeepEqual(result.Migrated, want) || len(result.Plan.Notices) != 2 || len(*backups) != 1 {
t.Fatalf("migrated %v, notices %q, backups %v", result.Migrated, result.Plan.Notices, *backups)
}
assertMigrated(t, s.ConfigPath)
if data, err := os.ReadFile(filepath.Join(s.Home, ".pi", "agent", "mcp.json")); err != nil || !strings.Contains(string(data), `"ext"`) {
t.Fatalf("Pi file: %s %v", data, err)
}
if result, err = s.Apply(""); err != nil || result.Migrated != nil || len(*backups) != 1 {
t.Fatalf("a second sync saved again: %+v %v %v", result, err, *backups)
}
}
func TestPreviewLeavesTheLegacyConfigAlone(t *testing.T) {
s, backups := legacyService(t)
before, _ := os.ReadFile(s.ConfigPath)
if _, err := s.Preview(); err != nil {
t.Fatal(err)
}
after, _ := os.ReadFile(s.ConfigPath)
if string(before) != string(after) || len(*backups) != 0 {
t.Fatalf("preview wrote the config: %s", after)
}
}
func TestProjectSyncSavesTheConfigWithoutRetiredSettings(t *testing.T) {
s, backups := legacyService(t)
plan, err := s.Preview()
if err != nil {
t.Fatal(err)
}
result, err := s.ApplyProject(plan.Revision, filepath.Join(filepath.Dir(s.ConfigPath), "shop"))
if err != nil || result.Migrated == nil || len(*backups) != 1 {
t.Fatalf("%+v %v %v", result, err, *backups)
}
assertMigrated(t, s.ConfigPath)
}
// The dashboard's sync sends no change with sync set.
func TestDashboardSyncSavesTheConfigWithoutRetiredSettings(t *testing.T) {
s, _ := legacyService(t)
plan, err := s.PreviewMutation(Mutation{})
if err != nil {
t.Fatal(err)
}
result, err := s.Mutate(Mutation{}, plan.Revision, true)
if err != nil || result.Migrated == nil {
t.Fatalf("%+v %v", result, err)
}
assertMigrated(t, s.ConfigPath)
}
func TestSyncSavesAnExternalSourceWithoutRetiredSettings(t *testing.T) {
s, _ := projectsService(t, "sources:\n mcp: ./mcp.yaml\nmcp:\n targets: [pi]\n")
external := filepath.Join(filepath.Dir(s.ConfigPath), "mcp.yaml")
if err := os.WriteFile(external, []byte("# mine\nservers:\n ext:\n command: a\n piExtension: pi-mcp-adapter\n"), 0600); err != nil {
t.Fatal(err)
}
var backups []string
s.BackupSource = func(path string) (string, error) { backups = append(backups, path); return "", nil }
config, _ := os.ReadFile(s.ConfigPath)
if result, err := s.Apply(""); err != nil || result.Migrated == nil {
t.Fatalf("%+v %v", result, err)
}
data, _ := os.ReadFile(external)
if strings.Contains(string(data), "piExtension") || !strings.Contains(string(data), "# mine") || len(backups) != 1 || backups[0] != external {
t.Fatalf("external source %v:\n%s", backups, data)
}
if after, _ := os.ReadFile(s.ConfigPath); string(after) != string(config) {
t.Fatalf("config.yaml changed:\n%s", after)
}
}
// Agent files are written by then, so a failure says so and leaves the config as it was.
func TestSyncReportsAConfigItCouldNotSave(t *testing.T) {
s, _ := legacyService(t)
s.BackupSource = func(string) (string, error) { return "", errors.New("disk full") }
before, _ := os.ReadFile(s.ConfigPath)
result, err := s.Apply("")
if err == nil || !strings.Contains(err.Error(), "MCP files applied, but saving") || !strings.Contains(err.Error(), "disk full") || result == nil || result.Migrated != nil {
t.Fatalf("%+v %v", result, err)
}
if after, _ := os.ReadFile(s.ConfigPath); string(after) != string(before) {
t.Fatalf("config changed:\n%s", after)
}
}
+208 -17
View File
@@ -4,10 +4,12 @@
package mcp
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"regexp"
"slices"
"strings"
"gopkg.in/yaml.v3"
@@ -69,7 +71,6 @@ func (v Value) MarshalJSON() ([]byte, error) {
// Server contains only settings that have explicit native adapter mappings.
type Server struct {
PiExtension string `yaml:"piExtension,omitempty" json:"piExtension,omitempty"`
Transport string `yaml:"transport,omitempty" json:"transport,omitempty"`
Command string `yaml:"command,omitempty" json:"command,omitempty"`
Args []string `yaml:"args,omitempty" json:"args,omitempty"`
@@ -78,20 +79,208 @@ type Server struct {
Headers map[string]Value `yaml:"headers,omitempty" json:"headers,omitempty"`
BearerToken *Value `yaml:"bearerToken,omitempty" json:"bearerToken,omitempty"`
Targets TargetList `yaml:"targets,omitempty" json:"targets,omitzero"`
// DirectTools is pi-mcp-adapter's directTools: true, false, "search" or a list of
// tool names. Only Pi receives it.
DirectTools any `yaml:"directTools,omitempty" json:"directTools,omitempty"`
// PiOptions are builtin or adapter fields Skillshare has no setting for, such as
// excludeTools. They are written into Pi's entry as given.
// Tools is which of the server's tools reach the model, translated per Agent.
Tools ToolPolicy `yaml:"tools,omitempty" json:"tools,omitzero"`
// PiOptions are Pi built-in fields Skillshare has no setting for, such as timeout.
// They are written into Pi's entry as given.
PiOptions PiOptions `yaml:"piOptions,omitempty" json:"piOptions,omitempty"`
// PiOptionsPrune removes cleared fields only when the ledger owns their unchanged values.
PiOptionsPrune bool `yaml:"piOptionsPrune,omitempty" json:"piOptionsPrune,omitempty"`
// Disabled is the whole entry: it turns off, for one project, a server that the
// Agent's global config defines. Unselecting an Agent already covers a server
// Skillshare defines, so a disabled server carries no command or url.
Disabled bool `yaml:"disabled,omitempty" json:"disabled,omitempty"`
}
// legacyServerFields chose Pi's MCP extension and opted in to pruning Pi fields, before
// 0.23.0 made Pi use its built-in MCP and always prune. A config that still has them loads,
// and saving it drops them.
var legacyServerFields = []string{"piExtension", "piOptionsPrune"}
// UnmarshalJSON ignores legacyServerFields and converts directTools as loading does, so a
// dashboard that still sends them can save.
func (s *Server) UnmarshalJSON(data []byte) error {
var fields map[string]json.RawMessage
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
for _, key := range legacyServerFields {
delete(fields, key)
}
var directTools any
if raw, ok := fields["directTools"]; ok {
_ = json.Unmarshal(raw, &directTools)
delete(fields, "directTools")
}
data, err := json.Marshal(fields)
if err != nil {
return err
}
type plain Server
d := json.NewDecoder(bytes.NewReader(data))
d.DisallowUnknownFields()
if err := d.Decode((*plain)(s)); err != nil {
return err
}
s.adoptAdapterTools(directTools, nil, nil)
return nil
}
// adapterPiOptions are pi-mcp-adapter server fields that Pi's built-in MCP (0.99.0) does
// not read. Before 0.23.0 they reached the adapter's file through piOptions.
var adapterPiOptions = []string{"approveTools", "auth", "bearerToken", "bearerTokenEnv", "bearerTokenStore", "caFile", "debug", "exposeResources", "idleTimeout", "inheritEnv", "lifecycle", "protocolVersion", "requestHeadersCommand", "requestTimeoutMs", "searchKeywords", "socket", "tasks", "toolPrefix", "trace"}
func deref(n *yaml.Node) *yaml.Node {
if n != nil && n.Kind == yaml.AliasNode {
return n.Alias
}
return n
}
// migration is what migrateServers needs to know about a servers mapping's scope.
type migration struct {
// piAccounts are the account targets whose Agent is Pi.
piAccounts []string
// directTools is the scope's pi-mcp-adapter default, mcp.directTools or a project's,
// for the servers that reach Pi and set none; defaults are the scope's targets.
directTools any
defaults []string
}
// reachesPi reports a server whose targets, its own or the scope's, include Pi.
func (m migration) reachesPi(server *yaml.Node) bool {
targets := m.defaults
if n := deref(field(server, "targets")); n != nil {
targets = nil
_ = n.Decode(&targets)
}
return slices.ContainsFunc(targets, func(t string) bool { return t == "pi" || slices.Contains(m.piAccounts, t) })
}
// migrateServers rewrites, in place, what 0.23.0 retired in every server of a servers
// mapping, and names the servers each change touched, keyed by what changed:
// - legacyServerFields are dropped; a piExtension that chose pi-mcp-adapter or
// pi-mcp-extension is also keyed "piExtension.<extension>";
// - pi-mcp-adapter piOptions are dropped, keyed "piOptions.<field>";
// - directTools and piOptions includeTools/excludeTools become Pi exposure settings or
// tools (adoptAdapterTools), keyed "piTools", or are dropped, keyed "piTools.<field>";
// - pi and piAccounts leave the targets of a switch-only entry, keyed "piSwitch": Pi has
// no per-project switch, and an entry left with no targets stays, turning nothing off.
func migrateServers(servers *yaml.Node, m migration) map[string][]string {
found := map[string][]string{}
servers = deref(servers)
if servers == nil || servers.Kind != yaml.MappingNode {
return found
}
for i := 0; i+1 < len(servers.Content); i += 2 {
name, server := servers.Content[i].Value, deref(servers.Content[i+1])
if server.Kind != yaml.MappingNode {
continue
}
for _, key := range legacyServerFields {
if n := deref(field(server, key)); n != nil {
if key == "piExtension" && (n.Value == "pi-mcp-adapter" || n.Value == "pi-mcp-extension") {
found[key+"."+n.Value] = append(found[key+"."+n.Value], name)
}
drop(server, key)
found[key] = append(found[key], name)
}
}
if options := deref(field(server, "piOptions")); options != nil && options.Kind == yaml.MappingNode {
for _, key := range adapterPiOptions {
if field(options, key) != nil {
drop(options, key)
found["piOptions."+key] = append(found["piOptions."+key], name)
}
}
}
if dropped, ok := migrateAdapterTools(server, m); ok {
found["piTools"] = append(found["piTools"], name)
for _, key := range dropped {
found["piTools."+key] = append(found["piTools."+key], name)
}
}
if options := deref(field(server, "piOptions")); options != nil && options.Kind == yaml.MappingNode && len(options.Content) == 0 {
drop(server, "piOptions")
}
disabled := deref(field(server, "disabled"))
targets := deref(field(server, "targets"))
if disabled == nil || disabled.Tag != "!!bool" || disabled.Value != "true" || targets == nil || targets.Kind != yaml.SequenceNode {
continue
}
kept := []*yaml.Node{}
for _, target := range targets.Content {
if value := deref(target).Value; value != "pi" && !slices.Contains(m.piAccounts, value) {
kept = append(kept, target)
}
}
if len(kept) < len(targets.Content) {
targets.Content = kept
found["piSwitch"] = append(found["piSwitch"], name)
}
}
return found
}
// migrateAdapterTools converts one server's directTools, or the scope's when it reaches Pi
// and sets none, and its piOptions includeTools/excludeTools. It reports whether the server
// had any, and which of them it dropped.
func migrateAdapterTools(server *yaml.Node, m migration) ([]string, bool) {
var directTools any
var include, exclude []any
had := false
disabled := deref(field(server, "disabled"))
if n := field(server, "directTools"); n != nil {
_ = n.Decode(&directTools)
drop(server, "directTools")
had = true
} else if m.directTools != nil && m.directTools != false && disabled == nil && m.reachesPi(server) {
directTools = m.directTools
}
options := deref(field(server, "piOptions"))
if options != nil && options.Kind == yaml.MappingNode {
for key, list := range map[string]*[]any{"includeTools": &include, "excludeTools": &exclude} {
if n := field(options, key); n != nil {
if n.Decode(list) != nil || *list == nil {
*list = []any{}
}
drop(options, key)
had = true
}
}
}
if !had && directTools == nil {
return nil, false
}
// Only what decides the conversion is decoded; the rest of the node stays as written.
var draft Server
if n := field(server, "tools"); n != nil && n.Decode(&draft.Tools) != nil {
draft.Tools.Deny = []string{"unreadable"} // still counts as set
}
for _, key := range []string{"exposure", "toolExposure"} {
if options != nil && field(options, key) != nil {
if draft.PiOptions == nil {
draft.PiOptions = PiOptions{}
}
draft.PiOptions[key] = true
}
}
draft.Disabled = disabled != nil && disabled.Value == "true"
before := draft
dropped := draft.adoptAdapterTools(directTools, include, exclude)
if before.Tools.IsZero() && !draft.Tools.IsZero() {
_ = put(server, "tools", draft.Tools)
}
for _, key := range []string{"exposure", "toolExposure"} {
if value, set := draft.PiOptions[key]; set && before.PiOptions[key] == nil {
if options == nil || options.Kind != yaml.MappingNode {
_ = put(server, "piOptions", map[string]any{})
options = field(server, "piOptions")
}
_ = put(options, key, value)
}
}
return dropped, true
}
// TargetList tells a missing list from an empty one. Missing inherits mcp.targets; empty
// keeps the server in Skillshare and writes it to no Agent, so it has to survive a save.
type TargetList []string
@@ -152,9 +341,6 @@ func validateTargets(targets []string) error {
// Validate checks a portable server without executing or connecting to it.
func (s Server) Validate(name string) error {
if s.PiExtension != "" && s.PiExtension != "builtin" && s.PiExtension != "pi-mcp-adapter" && s.PiExtension != "pi-mcp-extension" {
return fmt.Errorf("MCP %s: piExtension must be builtin, pi-mcp-adapter or pi-mcp-extension", name)
}
for key := range s.Env {
if !envName.MatchString(key) {
return fmt.Errorf("MCP %s: invalid environment variable name", name)
@@ -163,19 +349,24 @@ func (s Server) Validate(name string) error {
if !serverName.MatchString(name) {
return fmt.Errorf("invalid MCP name %q: use letters, digits, dots, underscores or hyphens", name)
}
if err := s.validateDirectTools(name); err != nil {
return err
}
if err := s.validatePiOptions(name); err != nil {
return err
}
if !s.Tools.IsZero() {
switch {
case s.Disabled:
return fmt.Errorf("MCP %s: tools cannot be set on a disabled entry; it only switches the server off", name)
case s.PiOptions["toolExposure"] != nil:
return fmt.Errorf("MCP %s: tools and piOptions.toolExposure both set which tools Pi shows; keep it in tools", name)
}
if err := s.Tools.validate(name); err != nil {
return err
}
}
if s.Disabled {
if s.Command != "" || s.URL != "" || s.Transport != "" || s.BearerToken != nil || len(s.Args)+len(s.Env)+len(s.Headers) > 0 {
return fmt.Errorf("MCP %s: disabled turns off a server the Agent already has; leave out its command, url and settings", name)
}
if s.Targets != nil && len(s.Targets) == 0 {
return fmt.Errorf("MCP %s: disabled needs at least one target to turn the server off for; omit targets to inherit defaults", name)
}
return validateTargets(s.Targets)
}
if (s.Command == "") == (s.URL == "") {
+59 -13
View File
@@ -21,7 +21,7 @@ type Mutation struct {
// Project is a root under mcp.projects. Set, the rest of the mutation applies to that
// project; with Remove and no Name, the project itself is dropped.
Project string `json:"project,omitempty"`
// Settings replaces targets and directTools of the scope, so a value left out is cleared.
// Settings replaces the targets of the scope, so a value left out is cleared.
Settings *Settings `json:"settings,omitempty"`
Name string `json:"name,omitempty"`
Server *Server `json:"server,omitempty"`
@@ -33,16 +33,15 @@ type Mutation struct {
Replace bool `json:"replace,omitempty"`
}
// Settings are a scope's defaults: mcp.targets and mcp.directTools, or a project's own.
// Settings are a scope's defaults: mcp.targets, or a project's own.
type Settings struct {
Targets []string `json:"targets,omitempty"`
DirectTools any `json:"directTools,omitempty"`
Targets []string `json:"targets,omitempty"`
// DirectTools is ignored since 0.23.0, which converts it to each server's own tool
// exposure. It is accepted so a dashboard that still sends it can save.
DirectTools any `json:"directTools,omitempty"`
}
func (v Settings) validate() error {
if !ValidDirectTools(v.DirectTools) {
return fmt.Errorf("directTools must be true, false, \"search\" or a list of tool names")
}
return validateTargets(v.Targets)
}
@@ -95,7 +94,7 @@ func (s *Source) draftProject(m Mutation) error {
if err := m.Settings.validate(); err != nil {
return err
}
project.Targets, project.DirectTools = m.Settings.Targets, m.Settings.DirectTools
project.Targets = m.Settings.Targets
}
if s.Projects == nil {
s.Projects = map[string]Project{}
@@ -135,7 +134,7 @@ func (s *Service) draftMutations(mutations []Mutation) (*Source, error) {
if err := m.Settings.validate(); err != nil {
return nil, err
}
source.Targets, source.DirectTools, source.settingsChanged = m.Settings.Targets, m.Settings.DirectTools, true
source.Targets, source.settingsChanged = m.Settings.Targets, true
}
source.serversChanged = source.serversChanged || m.Remove || m.Server != nil
if m.Remove {
@@ -215,9 +214,6 @@ func (s *Source) save() error {
if err := putOrDrop(mcp, "targets", s.Targets, len(s.Targets) > 0); err != nil {
return err
}
if err := putOrDrop(mcp, "directTools", s.DirectTools, s.DirectTools != nil); err != nil {
return err
}
}
if len(s.touched) > 0 {
if field(mcp, "projects") == nil {
@@ -241,6 +237,56 @@ func (s *Source) save() error {
return writeYAML(s.ConfigPath, doc, mcp)
}
// NeedsMigration reports settings 0.23.0 retired that loading converted in memory only.
func (s *Source) NeedsMigration() bool { return s.migrateConfig || s.migrateExternal }
// MigratedFile is a config file a sync saved without the settings 0.23.0 retired, and the
// backup of its previous content.
type MigratedFile struct {
Path string `json:"path"`
Backup string `json:"backup,omitempty"`
}
// saveMigration writes back what loading converted from settings 0.23.0 retired, and
// nothing else: the documents already hold the converted fields. backup, when set, keeps
// each file's current content first.
func (s *Source) saveMigration(backup func(path string) (string, error)) ([]MigratedFile, error) {
var saved []MigratedFile
if !s.NeedsMigration() {
return nil, nil
}
if err := s.CheckUnchanged(); err != nil {
return nil, err
}
write := func(path string, doc, section *yaml.Node) error {
file := MigratedFile{Path: path}
if backup != nil {
var err error
if file.Backup, err = backup(path); err != nil {
return err
}
}
if err := writeYAML(path, doc, section); err != nil {
return err
}
saved = append(saved, file)
return nil
}
if s.migrateExternal {
if err := write(s.Path, &s.doc, mapping(&s.doc)); err != nil {
return saved, err
}
}
if s.migrateConfig {
inlineOrphanAliases(&s.configDoc)
if err := write(s.ConfigPath, &s.configDoc, field(&s.configDoc, "mcp")); err != nil {
return saved, err
}
}
s.migrateConfig, s.migrateExternal, s.piExtensionSettings, s.Notices = false, false, false, nil
return saved, nil
}
func putOrDrop(node *yaml.Node, key string, value any, keep bool) error {
if keep {
return put(node, key, value)
@@ -429,5 +475,5 @@ func (s *Service) MutateBatch(mutations []Mutation, revision string, sync bool)
if err != nil {
return result, fmt.Errorf("source saved; synchronization incomplete: %w", err)
}
return result, nil
return result, s.migrate(result)
}
+10 -10
View File
@@ -22,14 +22,14 @@ func mutateSaved(t *testing.T, s *Service, m Mutation) *Source {
func TestMutateSettingsSetsTheGlobalDefaults(t *testing.T) {
s, _ := projectsService(t, projectsConfig)
// directTools is ignored since 0.23.0; a dashboard that still sends it can save.
source := mutateSaved(t, s, Mutation{Settings: &Settings{Targets: []string{"opencode", "pi"}, DirectTools: "search"}})
if !reflect.DeepEqual(source.Targets, []string{"opencode", "pi"}) || source.DirectTools != "search" {
t.Fatalf("targets %v, directTools %v", source.Targets, source.DirectTools)
if !reflect.DeepEqual(source.Targets, []string{"opencode", "pi"}) {
t.Fatalf("targets %v", source.Targets)
}
// Both values are replaced, so leaving one out clears it.
source = mutateSaved(t, s, Mutation{Settings: &Settings{Targets: []string{"opencode"}}})
if source.DirectTools != nil {
t.Fatalf("directTools %v, want none", source.DirectTools)
data, _ := os.ReadFile(s.ConfigPath)
if strings.Contains(string(data), "directTools") {
t.Fatalf("directTools saved:\n%s", data)
}
}
@@ -93,10 +93,10 @@ func TestMutateProjectLeavesOtherRootsAsWritten(t *testing.T) {
func TestMutateProjectRejected(t *testing.T) {
s, tmp := projectsService(t, projectsConfig)
for name, m := range map[string]Mutation{
"relative root": {Project: "work/p1", Settings: &Settings{}},
"unknown root": {Project: filepath.Join(tmp, "nope"), Remove: true},
"bad directTool": {Project: filepath.Join(tmp, "projA"), Replace: true, Settings: &Settings{DirectTools: 3}},
"listed twice": {Project: filepath.Join(tmp, "projA"), Settings: &Settings{}},
"relative root": {Project: "work/p1", Settings: &Settings{}},
"unknown root": {Project: filepath.Join(tmp, "nope"), Remove: true},
"bad target": {Project: filepath.Join(tmp, "projA"), Replace: true, Settings: &Settings{Targets: []string{"nope!"}}},
"listed twice": {Project: filepath.Join(tmp, "projA"), Settings: &Settings{}},
} {
if _, err := s.Mutate(m, "", false); err == nil {
t.Errorf("%s: saved", name)
+1 -1
View File
@@ -377,7 +377,7 @@ var managedFields = map[string][]string{
"vscode": {"type", "command", "args", "env", "url", "headers", "enabled", "disabled"},
"opencode": {"type", "command", "environment", "url", "headers", "enabled", "disabled"},
"kilocode": {"type", "command", "environment", "url", "headers", "enabled", "disabled"},
"codex": {"command", "args", "env", "env_vars", "url", "http_headers", "env_http_headers", "bearer_token_env_var", "enabled", "disabled"},
"codex": {"command", "args", "env", "env_vars", "url", "http_headers", "env_http_headers", "bearer_token_env_var", "enabled_tools", "disabled_tools", "enabled", "disabled"},
"grok": {"command", "args", "env", "url", "headers", "enabled", "disabled"},
}
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"testing"
)
const ownershipSource = "mcp:\n targets: [pi]\n servers:\n mcp-test1:\n url: https://example.com/mcp\n piExtension: pi-mcp-extension\n"
const ownershipSource = "mcp:\n targets: [pi]\n servers:\n mcp-test1:\n url: https://example.com/mcp\n"
func writeSource(t *testing.T, path, body string) {
t.Helper()
+31 -100
View File
@@ -10,6 +10,8 @@ import (
)
// ValidDirectTools accepts what pi-mcp-adapter documents: a switch, "search", or tool names.
// Loading converts it to Pi's exposure settings (see adoptAdapterTools); the config editor
// still checks the value a config may carry until then.
func ValidDirectTools(value any) bool {
valid := true
switch v := value.(type) {
@@ -31,56 +33,37 @@ func ValidDirectTools(value any) bool {
return valid
}
func (s Server) validateDirectTools(name string) error {
if s.DirectTools == nil {
return nil
}
switch {
case !ValidDirectTools(s.DirectTools):
return fmt.Errorf("MCP %s: directTools must be true, false, \"search\" or a list of tool names", name)
case s.Disabled:
return fmt.Errorf("MCP %s: directTools cannot be set on a disabled entry; it only switches the server off", name)
case s.PiExtension != "pi-mcp-adapter":
return fmt.Errorf("MCP %s: directTools is a pi-mcp-adapter setting; set piExtension: pi-mcp-adapter", name)
}
return nil
}
func (s Server) validatePiOptions(name string) error {
if len(s.PiOptions) == 0 && !s.PiOptionsPrune {
if len(s.PiOptions) == 0 {
return nil
}
if s.Disabled {
return fmt.Errorf("MCP %s: piOptions cannot be set on a disabled entry; it only switches the server off", name)
}
if s.PiExtension != "pi-mcp-adapter" && s.PiExtension != "builtin" {
return fmt.Errorf("MCP %s: piOptions require piExtension: builtin or pi-mcp-adapter", name)
}
if field := piOptionCommand("", s.PiOptions); field != "" {
return fmt.Errorf("MCP %s: Pi option %s cannot contain a command beginning with !; keep it in Pi or use an environment reference", name, field)
}
for _, key := range append(additionalManagedFields("pi"), "directTools", "type", "settings", "autoEnableCodemode") {
if _, set := s.PiOptions[key]; set && !(key == "enabled" && s.PiExtension == "builtin") {
if _, set := s.PiOptions[key]; set && key != "enabled" {
return fmt.Errorf("MCP %s: piOptions cannot set %s; Skillshare writes that field from the server's own settings", name, key)
}
}
if s.PiExtension == "builtin" {
return validatePiBuiltinOptions(name, s.PiOptions)
for _, key := range adapterPiOptions {
if _, set := s.PiOptions[key]; set {
return fmt.Errorf("MCP %s: piOptions.%s is a pi-mcp-adapter setting that Pi's built-in MCP does not read", name, key)
}
}
return nil
for key, part := range map[string]string{"includeTools": "allow", "excludeTools": "deny"} {
if _, set := s.PiOptions[key]; set {
return fmt.Errorf("MCP %s: piOptions.%s is a pi-mcp-adapter setting; use tools.%s", name, key, part)
}
}
return validatePiBuiltinOptions(name, s.PiOptions)
}
// withDirectToolsDefault fills in mcp.directTools for a pi-mcp-adapter server that sets none.
func (s Server) withDirectToolsDefault(value any) Server {
if s.DirectTools == nil && s.PiExtension == "pi-mcp-adapter" && !s.Disabled {
s.DirectTools = value
}
return s
}
// agentFieldsChanged reports a field outside the ownership hash, Pi's directTools or a
// piOptions key, that the config sets and the file does not have yet. These stay out of
// the hash: people added them to Pi's file by hand before Skillshare could set them, and
// agentFieldsChanged reports a field outside the ownership hash, such as a piOptions key,
// that the config sets and the file does not have yet. These stay out of the hash: people
// added them to Pi's file by hand before Skillshare could set them, and
// hashing them would turn their next sync into a conflict.
func agentFieldsChanged(target string, current, want map[string]any) bool {
for key, value := range want {
@@ -96,76 +79,24 @@ func agentFieldsChanged(target string, current, want map[string]any) bool {
return false
}
// DefaultPiExtension gives a new server that reaches Pi, or an account of Pi, the built-in
// mode when none was chosen. Other servers' modes are not consulted.
func (s *Source) DefaultPiExtension(server *Server) {
if server.PiExtension != "" {
return
}
targets := server.Targets
if targets == nil {
targets = s.Targets
}
for _, target := range targets {
if target == "pi" || s.Accounts[target].Agent == "pi" {
server.PiExtension = "builtin"
return
}
}
}
// Pi's extensions differ in file, transport and credential syntax.
// Sync config only: installing or starting either extension remains explicit.
// renderPi writes an entry of Pi's built-in MCP (Pi >= 0.99.0). Sync writes configuration
// only; it never installs or starts anything.
func renderPi(s Server) (map[string]any, error) {
if s.PiExtension == "" {
return nil, fmt.Errorf("Pi requires piExtension: builtin (Pi >= 0.99.0), pi-mcp-adapter or pi-mcp-extension")
}
format := clientFormats["pi"]
if s.PiExtension == "pi-mcp-adapter" || s.PiExtension == "builtin" {
format.refPrefix = "${"
}
// The extension passes through the parent's environment, but cannot rename
// variables or interpolate headers. Never resolve credentials in Skillshare.
if s.PiExtension == "pi-mcp-extension" {
env := map[string]Value{}
for key, value := range s.Env {
if value.FromEnv != "" {
if value.FromEnv != key {
return nil, fmt.Errorf("pi-mcp-extension cannot rename environment variables; use matching names or pi-mcp-adapter")
}
} else {
env[key] = value
}
}
s.Env = env
}
out, err := renderAdditionalClient("pi", format, s)
out, err := renderAdditionalClient("pi", clientFormats["pi"], s)
if err != nil {
return nil, err
}
if s.PiExtension == "pi-mcp-extension" {
out["transport"] = "stdio"
if s.URL != "" {
out["transport"] = "streamable-http"
}
} else {
maps.Copy(out, s.PiOptions)
if s.DirectTools != nil {
out["directTools"] = s.DirectTools
}
for _, key := range []string{"env", "headers"} {
values, _ := out[key].(map[string]string)
for name, value := range values {
// Portable literals must not become executable secret commands.
if s.PiExtension == "builtin" && strings.HasPrefix(value, "!") {
return nil, fmt.Errorf("Pi built-in: a literal beginning with ! would run a command; use fromEnv instead")
}
if strings.HasPrefix(value, "!") {
values[name] = "!" + value
}
if strings.Contains(value, "$env:") {
return nil, fmt.Errorf("Pi: use fromEnv instead of $env: interpolation")
}
maps.Copy(out, s.PiOptions)
piToolPolicy(out, s.Tools)
for _, key := range []string{"env", "headers"} {
values, _ := out[key].(map[string]string)
for _, value := range values {
// Portable literals must not become executable secret commands.
if strings.HasPrefix(value, "!") {
return nil, fmt.Errorf("Pi built-in: a literal beginning with ! would run a command; use fromEnv instead")
}
if strings.Contains(value, "$env:") {
return nil, fmt.Errorf("Pi: use fromEnv instead of $env: interpolation")
}
}
}
+1 -8
View File
@@ -123,7 +123,7 @@ func validatePiBuiltinOptions(name string, options map[string]any) error {
return nil
}
// Import extension options recursively without copying literal credentials into the source.
// Import Pi options recursively without copying literal credentials into the source.
func importPiOption(name, key string, value any, warnings *[]string) any {
if text, ok := value.(string); ok && (sensitiveKey.MatchString(key) || hasURLPassword(text)) {
if strings.Contains(text, "${") {
@@ -166,13 +166,6 @@ func piOwnedFields(entry map[string]any) map[string]string {
return fields
}
func piPrunes(source *Source, root, name string) bool {
if root != "" {
return source.Projects[root].Servers[name].PiOptionsPrune
}
return source.Servers[name].PiOptionsPrune
}
// FieldChanges contains names only: previews must not expose credentials from native files.
type FieldChanges struct {
Added []string `json:"added,omitempty"`
+12 -9
View File
@@ -9,7 +9,7 @@ import (
)
func TestPiBuiltinRenderAndValidation(t *testing.T) {
s := Server{URL: "https://example.com/mcp", PiExtension: "builtin", BearerToken: &Value{FromEnv: "TOKEN"}, PiOptions: map[string]any{"exposure": "deferred", "timeout": 120, "custom": map[string]any{"flag": true}}}
s := Server{URL: "https://example.com/mcp", BearerToken: &Value{FromEnv: "TOKEN"}, PiOptions: map[string]any{"exposure": "deferred", "timeout": 120, "custom": map[string]any{"flag": true}}}
out, err := Render("pi", s)
if err != nil || out["transport"] != nil || out["exposure"] != "deferred" || out["headers"].(map[string]string)["Authorization"] != "Bearer ${TOKEN}" {
t.Fatalf("%+v %v", out, err)
@@ -26,7 +26,7 @@ func TestPiBuiltinRenderAndValidation(t *testing.T) {
if got := service.RenderNative("docs.with.dot", s); got[0].Error == "" {
t.Fatal("Pi built-in rejects dots in names")
}
if _, err := Render("pi", Server{Command: "echo", PiExtension: "builtin", Env: map[string]Value{"MODE": {Literal: "!date"}}}); err == nil {
if _, err := Render("pi", Server{Command: "echo", Env: map[string]Value{"MODE": {Literal: "!date"}}}); err == nil {
t.Fatal("a portable literal must not execute as a Pi secret command")
}
}
@@ -37,7 +37,7 @@ func TestPiBuiltinSyncImportAndScopes(t *testing.T) {
if project {
s.ProjectRoot = filepath.Join(s.Home, "project")
}
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piExtension: builtin\n piOptions:\n exposure: deferred\n timeout: 120\n custom: {flag: true}\n"), 0600); err != nil {
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piOptions:\n exposure: deferred\n timeout: 120\n custom: {flag: true}\n"), 0600); err != nil {
t.Fatal(err)
}
p, err := s.Preview()
@@ -51,7 +51,8 @@ func TestPiBuiltinSyncImportAndScopes(t *testing.T) {
t.Fatal(err)
}
c, err := s.ImportClient("pi")
if err != nil || len(c) != 1 || c[0].Server.PiOptions["exposure"] != "deferred" || c[0].Server.PiOptions["custom"] == nil {
// exposure stays in piOptions.
if err != nil || len(c) != 1 || !c[0].Server.Tools.IsZero() || c[0].Server.PiOptions["exposure"] != "deferred" || c[0].Server.PiOptions["custom"] == nil {
t.Fatalf("%+v %v", c, err)
}
p, err = s.Preview()
@@ -61,18 +62,20 @@ func TestPiBuiltinSyncImportAndScopes(t *testing.T) {
}
}
// Sync always prunes; a config that still opts out with piOptionsPrune: false loads and
// prunes all the same.
func TestPiOptionsPruneOnlyOwnedUnchangedFields(t *testing.T) {
s := testService(t)
write := func(options string) {
t.Helper()
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piExtension: builtin\n piOptionsPrune: true\n"+options), 0600); err != nil {
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piOptionsPrune: false\n"+options), 0600); err != nil {
t.Fatal(err)
}
}
write(" piOptions: {exposure: deferred, timeout: 120}\n")
p, err := s.Preview()
if err != nil {
t.Fatal(err)
if err != nil || len(p.Notices) != 1 || !strings.Contains(p.Notices[0], "piOptionsPrune") {
t.Fatalf("%+v %v", p, err)
}
if _, err := s.Apply(p.Revision); err != nil {
t.Fatal(err)
@@ -180,7 +183,7 @@ func TestPiToolExposureOrderAndCredentialImport(t *testing.T) {
func TestPiBuiltinEnabledAndNativePreview(t *testing.T) {
s := testService(t)
server := Server{Command: "docs", Targets: []string{"pi"}, PiExtension: "builtin", PiOptions: PiOptions{"enabled": false, "exposure": "direct"}}
server := Server{Command: "docs", Targets: []string{"pi"}, PiOptions: PiOptions{"enabled": false, "exposure": "direct"}}
if _, err := s.Mutate(Mutation{Name: "docs", Server: &server, Replace: true}, "", true); err != nil {
t.Fatal(err)
}
@@ -219,7 +222,7 @@ func TestPiBuiltinEnabledAndNativePreview(t *testing.T) {
func TestPiBuiltinNativeDisableDoesNotConflict(t *testing.T) {
s := testService(t)
server := Server{Command: "docs", Targets: []string{"pi"}, PiExtension: "builtin"}
server := Server{Command: "docs", Targets: []string{"pi"}}
if _, err := s.Mutate(Mutation{Name: "docs", Server: &server, Replace: true}, "", true); err != nil {
t.Fatal(err)
}
+50 -15
View File
@@ -7,30 +7,28 @@ import (
"testing"
)
// piOptions carries the pi-mcp-adapter fields Skillshare has no setting for. Refs: #289.
func TestPiOptionsRenderedOnlyForPiAdapter(t *testing.T) {
server := Server{Command: "echo", PiExtension: "pi-mcp-adapter", PiOptions: map[string]any{"excludeTools": []any{"*emulator*"}}}
// piOptions carries the Pi fields Skillshare has no setting for. Refs: #289.
func TestPiOptionsRenderedOnlyForPi(t *testing.T) {
server := Server{Command: "echo", PiOptions: map[string]any{"retries": 3}}
out, err := Render("pi", server)
if err != nil {
t.Fatal(err)
}
if list, ok := out["excludeTools"].([]any); !ok || len(list) != 1 {
if out["retries"] != 3 {
t.Fatalf("pi entry: %v", out)
}
out, err = Render("opencode", server)
if err != nil || out["excludeTools"] != nil {
if err != nil || out["retries"] != nil {
t.Fatalf("piOptions leaked into another Agent: %v %v", out, err)
}
}
func TestPiOptionsRejected(t *testing.T) {
options := map[string]any{"excludeTools": []any{"a"}}
options := map[string]any{"timeout": 30}
for name, server := range map[string]Server{
"other extension": {Command: "echo", PiExtension: "pi-mcp-extension", PiOptions: options},
"no extension": {Command: "echo", PiOptions: options},
"switch only": {Disabled: true, PiExtension: "pi-mcp-adapter", PiOptions: options},
"a field Skillshare writes": {Command: "echo", PiExtension: "pi-mcp-adapter", PiOptions: map[string]any{"command": "other"}},
"directTools": {Command: "echo", PiExtension: "pi-mcp-adapter", PiOptions: map[string]any{"directTools": true}},
"switch only": {Disabled: true, PiOptions: options},
"a field Skillshare writes": {Command: "echo", PiOptions: map[string]any{"command": "other"}},
"directTools": {Command: "echo", PiOptions: map[string]any{"directTools": true}},
} {
if err := server.Validate("docs"); err == nil || !strings.Contains(err.Error(), "piOptions") {
t.Errorf("%s: got %v", name, err)
@@ -42,7 +40,7 @@ func TestPiOptionsSyncFollowsConfig(t *testing.T) {
s := testService(t)
sync := func(options, wantAction string) string {
t.Helper()
config := "mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piExtension: pi-mcp-adapter\n" + options
config := "mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n" + options
if err := os.WriteFile(s.ConfigPath, []byte(config), 0600); err != nil {
t.Fatal(err)
}
@@ -53,12 +51,49 @@ func TestPiOptionsSyncFollowsConfig(t *testing.T) {
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(s.Home, ".pi", "agent", "mcp-adapter.json"))
data, _ := os.ReadFile(filepath.Join(s.Home, ".pi", "agent", "mcp.json"))
return string(data)
}
sync("", "add")
if got := sync(" piOptions:\n excludeTools: [\"*emulator*\"]\n retries: 3\n", "update"); !strings.Contains(got, `"*emulator*"`) || !strings.Contains(got, `"retries": 3`) {
if got := sync(" piOptions:\n timeout: 30\n retries: 3\n", "update"); !strings.Contains(got, `"timeout": 30`) || !strings.Contains(got, `"retries": 3`) {
t.Fatalf("options not written: %s", got)
}
sync(" piOptions:\n excludeTools: [\"*emulator*\"]\n retries: 3\n", "unchanged")
sync(" piOptions:\n timeout: 30\n retries: 3\n", "unchanged")
}
// pi-mcp-adapter options reached Pi's file through piOptions before 0.23.0. Pi's built-in
// MCP does not read them, so loading drops them with a notice; other keys still pass through.
func TestAdapterPiOptionsDroppedOnLoad(t *testing.T) {
s, _ := projectsService(t, `mcp:
targets: [pi]
servers:
docs:
command: docs
piOptions:
lifecycle: eager
idleTimeout: 5
timeout: 30
retries: 3
`)
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if len(plan.Notices) != 2 || plan.Notices[0] != "Pi's built-in MCP does not read idleTimeout, lifecycle; the next sync removes them: docs" || plan.Notices[1] != PiBuiltinNotice {
t.Fatalf("notices: %q", plan.Notices)
}
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(s.Home, ".pi", "agent", "mcp.json"))
if strings.Contains(string(data), "lifecycle") || strings.Contains(string(data), "idleTimeout") || !strings.Contains(string(data), `"retries": 3`) || !strings.Contains(string(data), `"timeout": 30`) {
t.Fatalf("pi file: %s", data)
}
}
func TestAdapterPiOptionsRejectedOnSave(t *testing.T) {
err := Server{Command: "echo", PiOptions: map[string]any{"lifecycle": "eager"}}.Validate("docs")
if err == nil || !strings.Contains(err.Error(), "piOptions.lifecycle is a pi-mcp-adapter setting") {
t.Fatalf("got %v", err)
}
}
+209 -219
View File
@@ -1,7 +1,6 @@
package mcp
import (
"encoding/json"
"os"
"path/filepath"
"slices"
@@ -10,36 +9,16 @@ import (
)
func TestPiRender(t *testing.T) {
for _, extension := range []string{"pi-mcp-adapter", "pi-mcp-extension"} {
t.Run(extension, func(t *testing.T) {
out, err := Render("pi", Server{URL: "https://example.com/mcp", PiExtension: extension})
if err != nil {
t.Fatal(err)
}
if out["url"] != "https://example.com/mcp" {
t.Fatal(out)
}
if extension == "pi-mcp-extension" && out["transport"] != "streamable-http" {
t.Fatal(out)
}
if extension == "pi-mcp-adapter" && out["transport"] != nil {
t.Fatal(out)
}
})
out, err := Render("pi", Server{URL: "https://example.com/mcp"})
if err != nil || out["url"] != "https://example.com/mcp" || out["transport"] != nil {
t.Fatalf("%v %v", out, err)
}
if _, err := Render("pi", Server{Command: "echo"}); err == nil {
t.Fatal("must choose extension")
if _, err := Render("pi", Server{Command: "echo", Env: map[string]Value{"LITERAL": {Literal: "!date"}}}); err == nil {
t.Fatal("a literal beginning with ! would run a command")
}
if _, err := Render("pi", Server{URL: "https://example.com", PiExtension: "pi-mcp-extension", BearerToken: &Value{FromEnv: "TOKEN"}}); err == nil {
t.Fatal("extension cannot interpolate headers")
}
out, err := Render("pi", Server{Command: "echo", PiExtension: "pi-mcp-adapter", Env: map[string]Value{"LITERAL": {Literal: "!date"}, "TOKEN": {FromEnv: "TOKEN"}}})
if err != nil {
t.Fatal(err)
}
env := out["env"].(map[string]string)
if env["LITERAL"] != "!!date" || env["TOKEN"] != "${TOKEN}" {
t.Fatal(env)
out, err = Render("pi", Server{Command: "echo", Env: map[string]Value{"TOKEN": {FromEnv: "TOKEN"}}})
if err != nil || out["env"].(map[string]string)["TOKEN"] != "${TOKEN}" {
t.Fatalf("%v %v", out, err)
}
}
@@ -60,7 +39,7 @@ func TestPiSyncScopesAndPreservation(t *testing.T) {
if err := os.WriteFile(path, []byte(original), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n url: https://example.com/mcp\n piExtension: pi-mcp-extension\n"), 0600); err != nil {
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n url: https://example.com/mcp\n"), 0600); err != nil {
t.Fatal(err)
}
p, err := s.Preview()
@@ -71,7 +50,7 @@ func TestPiSyncScopesAndPreservation(t *testing.T) {
t.Fatal(err)
}
data, _ := os.ReadFile(path)
if !strings.Contains(string(data), `"mine"`) || !strings.Contains(string(data), `"maxRetries"`) || !strings.Contains(string(data), `"streamable-http"`) {
if !strings.Contains(string(data), `"mine"`) || !strings.Contains(string(data), `"maxRetries"`) || !strings.Contains(string(data), `"https://example.com/mcp"`) {
t.Fatal(string(data))
}
p, err = s.Preview()
@@ -81,36 +60,15 @@ func TestPiSyncScopesAndPreservation(t *testing.T) {
}
}
func TestPiImportTransportAndMixedExtensions(t *testing.T) {
candidates, err := Import("pi", []byte(`{"mcpServers":{"docs":{"transport":"streamable-http","url":"https://example.com/mcp","lifecycle":"eager"}}}`), "")
if err != nil || len(candidates) != 1 || len(candidates[0].Problems) != 0 || candidates[0].Server.Transport != "streamable-http" || candidates[0].Server.PiExtension != "" || len(candidates[0].Server.PiOptions) != 0 {
func TestPiImportTransport(t *testing.T) {
candidates, err := Import("pi", []byte(`{"mcpServers":{"docs":{"transport":"streamable-http","url":"https://example.com/mcp","timeout":60}}}`), "")
if err != nil || len(candidates) != 1 || len(candidates[0].Problems) != 0 || candidates[0].Server.Transport != "streamable-http" || candidates[0].Server.PiOptions["timeout"] == nil {
t.Fatalf("%+v %v", candidates, err)
}
if !slices.Contains(candidates[0].Warnings, piExtensionWarning) {
t.Fatal("ambiguous extension import must request a Pi mode", candidates[0].Warnings)
}
candidates, err = Import("pi", []byte(`{"mcpServers":{"docs":{"transport":"sse","url":"https://example.com/sse"}}}`), "")
if err != nil || len(candidates[0].Problems) == 0 {
t.Fatal("legacy SSE silently converted")
}
s := testService(t)
_, err = s.render(&Source{Targets: []string{"pi"}, Servers: map[string]Server{
"a": {Command: "echo", PiExtension: "pi-mcp-adapter"},
"b": {Command: "echo", PiExtension: "pi-mcp-extension"},
}})
if err == nil {
t.Fatal("mixed extensions must not share a file")
}
}
func TestPiImportExplicitExtensionKeepsWarnings(t *testing.T) {
candidates, err := importPiMode("pi", []byte(`{"mcpServers":{"docs":{"transport":"stdio","command":"docs","lifecycle":"eager","directTools":true,"timeout":60}}}`), "", "pi-mcp-extension")
if err != nil || len(candidates) != 1 || len(candidates[0].Problems) != 0 || candidates[0].Server.PiExtension != "pi-mcp-extension" || len(candidates[0].Server.PiOptions) != 0 {
t.Fatalf("%+v %v", candidates, err)
}
if strings.Contains(strings.Join(candidates[0].Warnings, ";"), piExtensionWarning) || !strings.Contains(strings.Join(candidates[0].Warnings, ";"), "lifecycle") {
t.Fatal(candidates[0].Warnings)
}
}
func TestImportTimeoutDoesNotIdentifyPi(t *testing.T) {
@@ -125,7 +83,7 @@ func TestImportTimeoutDoesNotIdentifyPi(t *testing.T) {
t.Fatal(err)
}
for _, c := range candidates {
if len(c.Problems) != 0 || c.Server.PiExtension != "" || c.Server.PiOptions != nil || strings.Contains(strings.Join(c.Warnings, ";"), piExtensionWarning) {
if len(c.Problems) != 0 || c.Server.PiOptions != nil {
t.Fatalf("%+v", c)
}
}
@@ -133,121 +91,58 @@ func TestImportTimeoutDoesNotIdentifyPi(t *testing.T) {
}
}
func TestPiAdapterImportEscapedLiterals(t *testing.T) {
for _, server := range []Server{
{Command: "docs", PiExtension: "pi-mcp-adapter", Env: map[string]Value{"MODE": {Literal: "!literal"}}},
{URL: "https://example.com/mcp", PiExtension: "pi-mcp-adapter", Headers: map[string]Value{"X-Mode": {Literal: "!!literal"}}},
} {
entry, err := Render("pi", server)
if err != nil {
t.Fatal(err)
}
data, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{"docs": entry}})
candidates, err := importPiMode("pi", data, "", "pi-mcp-adapter")
if err != nil || len(candidates) != 1 || len(candidates[0].Problems) != 0 {
t.Fatalf("%+v %v", candidates, err)
}
got, err := Render("pi", candidates[0].Server)
want, _ := json.Marshal(entry)
actual, _ := json.Marshal(got)
if err != nil || string(actual) != string(want) {
t.Fatalf("%s != %s: %v", actual, want, err)
}
}
}
func TestPiImportInferredAdapterEscapedLiterals(t *testing.T) {
candidates, err := Import("pi", []byte(`{"mcpServers":{"local":{"command":"c","excludeTools":[],"env":{"MODE":"!!x"}},"remote":{"url":"https://example.com/mcp","approveTools":[],"headers":{"X-Mode":"!!x"}}}}`), "")
// pi-mcp-adapter escaped a literal beginning with ! as !!. Only its own file says so.
func TestPiAdapterFileImportUnescapesLiterals(t *testing.T) {
input := []byte(`{"mcpServers":{"local":{"command":"c","excludeTools":[],"env":{"MODE":"!!x"}},"remote":{"url":"https://example.com/mcp","headers":{"X-Mode":"!!x"}}}}`)
candidates, err := importNative("pi", input, "", true)
if err != nil || len(candidates) != 2 {
t.Fatalf("%+v %v", candidates, err)
}
for _, c := range candidates {
if len(c.Problems) != 0 || c.Server.PiExtension != "pi-mcp-adapter" || c.Server.DirectTools != nil {
t.Fatalf("adapter inference: %+v", c)
}
if c.Name == "local" && c.Server.Env["MODE"].Literal != "!x" || c.Name == "remote" && c.Server.Headers["X-Mode"].Literal != "!x" {
t.Fatalf("escaped literal: %+v", c.Server)
if len(c.Problems) != 0 || c.Name == "local" && c.Server.Env["MODE"].Literal != "!x" || c.Name == "remote" && c.Server.Headers["X-Mode"].Literal != "!x" {
t.Fatalf("escaped literal: %+v", c)
}
}
candidates, err = Import("pi", input, "")
if err != nil || len(candidates[0].Problems) == 0 {
t.Fatalf("mcp.json runs !: %+v %v", candidates, err)
}
}
func TestPiOptionsRejectNonSecretCommands(t *testing.T) {
for _, mode := range []string{"builtin", "pi-mcp-adapter"} {
for _, adapter := range []bool{false, true} {
input := []byte(`{"mcpServers":{"docs":{"url":"https://example.com/mcp","oauth":{"clientId":"!echo client"}}}}`)
candidates, err := importPiMode("pi", input, "", mode)
candidates, err := importNative("pi", input, "", adapter)
if err != nil || len(candidates) != 1 || len(candidates[0].Problems) == 0 {
t.Fatalf("unsafe import: %+v %v", candidates, err)
}
if _, err := Render("pi", Server{URL: "https://example.com/mcp", PiExtension: mode, PiOptions: PiOptions{"oauth": map[string]any{"clientId": "!echo client"}}}); err == nil {
t.Fatal("unsafe render")
}
}
if _, err := Render("pi", Server{URL: "https://example.com/mcp", PiOptions: PiOptions{"oauth": map[string]any{"clientId": "!echo client"}}}); err == nil {
t.Fatal("unsafe render")
}
}
func TestPiExtensionImportPathsIgnoreOverridesAndAccounts(t *testing.T) {
func TestPiImportSourcesAndPaths(t *testing.T) {
s := testService(t)
s.ConfigDirs = map[string]string{"pi": t.TempDir()}
account := t.TempDir()
source := &Source{Accounts: map[string]Account{"pi-work": {Agent: "pi", Dir: account}}, Servers: map[string]Server{"docs": {Command: "docs", Targets: []string{"pi"}, PiExtension: "pi-mcp-extension"}}}
path := filepath.Join(s.Home, ".pi", "agent", "mcp.json")
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(`{"mcpServers":{"docs":{"command":"docs","transport":"stdio","lifecycle":"eager"}}}`), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(s.ConfigPath, []byte("targets:\n pi-work: {agent: pi, config_dir: "+account+"}\nmcp: {}\n"), 0600); err != nil {
t.Fatal(err)
}
foundExtension := false
dir := filepath.Join(s.Home, "custom-pi")
s.ConfigDirs = map[string]string{"pi": dir}
source := &Source{Servers: map[string]Server{}}
found := map[string]string{}
for _, item := range s.ImportSources(source)[""] {
if item.PiExtension != "pi-mcp-extension" {
continue
}
foundExtension = true
if item.Target != "pi" || item.Path != path {
t.Fatalf("unsupported extension source: %+v", item)
if item.Target == "pi" {
found[item.PiExtension] = item.Path
}
}
if !foundExtension {
t.Fatal("extension import source missing")
if len(found) != 2 || found["builtin"] != filepath.Join(dir, "mcp.json") || found["pi-mcp-adapter"] != filepath.Join(dir, "mcp-adapter.json") {
t.Fatalf("import sources: %v", found)
}
if got := s.ConfiguredClientPaths(source)["pi"]; got != path {
if got := s.ConfiguredClientPaths(source)["pi"]; got != filepath.Join(dir, "mcp.json") {
t.Fatal(got)
}
candidates, err := s.ImportClientMode("pi", "pi-mcp-extension")
if err != nil || len(candidates) != 1 || len(candidates[0].Problems) != 0 || slices.Contains(candidates[0].Warnings, piExtensionWarning) {
t.Fatalf("%+v %v", candidates, err)
}
if _, err := s.ImportClientMode("pi-work", "pi-mcp-extension"); err == nil {
t.Fatal("extension account accepted")
}
}
func TestPiConfiguredPathsAreDeterministicForMixedModes(t *testing.T) {
s := testService(t)
source := &Source{Targets: []string{"pi"}, Servers: map[string]Server{"z": {Command: "builtin", PiExtension: "builtin"}, "a": {Command: "adapter", PiExtension: "pi-mcp-adapter"}}}
for i := 0; i < 30; i++ {
if got := s.ConfiguredClientPaths(source)["pi"]; got != filepath.Join(s.Home, ".pi", "agent", "mcp.json") {
t.Fatal(got)
}
}
}
func TestPiCredentials(t *testing.T) {
server := Server{Command: "echo", PiExtension: "pi-mcp-extension", Env: map[string]Value{"TOKEN": {FromEnv: "TOKEN"}, "MODE": {Literal: "dev"}}}
out, err := Render("pi", server)
if err != nil {
t.Fatal(err)
}
if out["env"].(map[string]string)["TOKEN"] != "" {
t.Fatal("must inherit TOKEN instead of writing an unexpanded placeholder")
}
server.Env["TOKEN"] = Value{FromEnv: "OTHER"}
if _, err = Render("pi", server); err == nil {
t.Fatal("cannot rename inherited variables")
}
out, err = Render("pi", Server{URL: "https://example.com/mcp", PiExtension: "pi-mcp-adapter", BearerToken: &Value{FromEnv: "TOKEN"}})
out, err := Render("pi", Server{URL: "https://example.com/mcp", BearerToken: &Value{FromEnv: "TOKEN"}})
if err != nil || out["headers"].(map[string]string)["Authorization"] != "Bearer ${TOKEN}" {
t.Fatalf("%+v %v", out, err)
}
@@ -257,22 +152,16 @@ func TestPiDirectoryOverride(t *testing.T) {
s := testService(t)
s.ConfigDirs = map[string]string{"pi": filepath.Join(s.Home, "custom-pi")}
path, err := s.nativePath("pi")
if err != nil || path != filepath.Join(s.Home, "custom-pi", "mcp-adapter.json") {
if err != nil || path != filepath.Join(s.Home, "custom-pi", "mcp.json") {
t.Fatalf("%s %v", path, err)
}
_, err = s.render(&Source{Targets: []string{"pi"}, Servers: map[string]Server{"docs": {Command: "echo", PiExtension: "pi-mcp-extension"}}})
if err == nil || !strings.Contains(err.Error(), "unset the override") {
t.Fatalf("extension ignores the directory override: %v", err)
}
candidates, err := Import("", []byte(`{"transport":"sse","url":"https://example.com/sse"}`), "docs")
if err != nil || len(candidates[0].Problems) == 0 {
t.Fatal("pasted SSE must not become streamable HTTP")
}
}
// pi-mcp-adapter 3 reads mcp-adapter.json and left mcp.json to Pi's built-in MCP support;
// pi-mcp-extension still reads mcp.json. Refs: #298.
func TestPiFileFollowsTheExtension(t *testing.T) {
func TestPiWritesOnlyBuiltinFile(t *testing.T) {
for _, project := range []bool{false, true} {
s := testService(t)
dir := filepath.Join(s.Home, ".pi", "agent")
@@ -280,107 +169,208 @@ func TestPiFileFollowsTheExtension(t *testing.T) {
s.ProjectRoot = filepath.Join(s.Home, "project")
dir = filepath.Join(s.ProjectRoot, ".pi")
}
for extension, file := range map[string]string{"pi-mcp-adapter": "mcp-adapter.json", "pi-mcp-extension": "mcp.json"} {
if path, _, err := s.destination("pi", Server{PiExtension: extension}); err != nil || path != filepath.Join(dir, file) {
t.Errorf("project=%v %s: %s %v", project, extension, path, err)
if path, _, err := s.destination("pi", Server{Command: "docs"}); err != nil || path != filepath.Join(dir, "mcp.json") {
t.Errorf("project=%v: %s %v", project, path, err)
}
}
}
// piMigration is a Pi home an earlier Skillshare synced docs into for the given extension,
// with the ledger owning the entry where that extension read it, next to a server of the
// user's own. An empty extension leaves piExtension out of the config and the ledger owning
// the entry in mcp-adapter.json, so only the ledger tells that the adapter had it.
func piMigration(t *testing.T, extension string, entry map[string]any) (s *Service, builtin, adapter string) {
t.Helper()
s = testService(t)
config := "mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n"
if extension != "" {
config += " piExtension: " + extension + "\n"
}
if err := os.WriteFile(s.ConfigPath, []byte(config), 0600); err != nil {
t.Fatal(err)
}
dir := filepath.Join(s.Home, ".pi", "agent")
builtin, adapter = filepath.Join(dir, "mcp.json"), filepath.Join(dir, "mcp-adapter.json")
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
owned := builtin
if extension == "pi-mcp-adapter" || extension == "" {
owned = adapter
}
if err := writeJSONFile(owned, map[string]any{"mcpServers": map[string]any{"docs": entry, "mine": map[string]any{"command": "mine"}}}); err != nil {
t.Fatal(err)
}
record := ownership{Owner: s.ConfigPath, Target: "pi", Path: owned, Name: "docs", Hash: entryHash(managedEntry("pi", entry))}
if err := writeJSONFile(s.statePath(), ledger{Version: 1, Entries: map[string]ownership{ownershipKey("pi", owned, "docs"): record}}); err != nil {
t.Fatal(err)
}
return s, builtin, adapter
}
// A server synced for pi-mcp-adapter moves to Pi's built-in mcp.json, and the entry
// Skillshare wrote to mcp-adapter.json goes; the user's own entry there stays.
func TestPiAdapterServerMovesToBuiltin(t *testing.T) {
s, builtin, adapter := piMigration(t, "pi-mcp-adapter", map[string]any{"command": "docs"})
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if c := changeFor(plan, adapter, "docs"); c == nil || c.Action != "remove" {
t.Fatalf("adapter entry: %+v", c)
}
if c := changeFor(plan, builtin, "docs"); c == nil || c.Action != "add" {
t.Fatalf("built-in entry: %+v", c)
}
if len(plan.Notices) != 2 || plan.Notices[0] != "Pi now uses its built-in MCP; the next sync updates the config: docs" || plan.Notices[1] != PiBuiltinNotice {
t.Fatalf("notices: %v", plan.Notices)
}
result, err := s.Apply(plan.Revision)
if err != nil || len(result.BackupIDs) == 0 {
t.Fatalf("%+v %v", result, err)
}
if data, _ := os.ReadFile(adapter); strings.Contains(string(data), `"docs"`) || !strings.Contains(string(data), `"mine"`) {
t.Fatalf("mcp-adapter.json: %s", data)
}
if data, _ := os.ReadFile(builtin); !strings.Contains(string(data), `"docs"`) {
t.Fatalf("mcp.json: %s", data)
}
}
// pi-mcp-extension read mcp.json too, so its entry is rewritten where it is.
func TestPiExtensionServerRewrittenInPlace(t *testing.T) {
s, builtin, _ := piMigration(t, "pi-mcp-extension", map[string]any{"command": "docs", "transport": "stdio"})
plan, err := s.Preview()
if err != nil || plan.Blocked || len(plan.Changes) != 1 {
t.Fatalf("%+v %v", plan, err)
}
if c := changeFor(plan, builtin, "docs"); c == nil || c.Action != "update" {
t.Fatalf("entry: %+v", c)
}
if !slices.Contains(plan.Notices, PiBuiltinNotice) {
t.Fatalf("notices: %v", plan.Notices)
}
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
if data, _ := os.ReadFile(builtin); strings.Contains(string(data), `"transport"`) || !strings.Contains(string(data), `"mine"`) {
t.Fatalf("mcp.json: %s", data)
}
}
// A config without piExtension can still own an entry in mcp-adapter.json, e.g. one edited
// by hand after a sync; the ledger alone shows the server leaving pi-mcp-adapter, and the
// sync must still say what Pi needs now.
func TestPiAdapterLedgerOnlyMoveWarns(t *testing.T) {
s, builtin, adapter := piMigration(t, "", map[string]any{"command": "docs"})
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if c := changeFor(plan, adapter, "docs"); c == nil || c.Action != "remove" {
t.Fatalf("adapter entry: %+v", c)
}
if c := changeFor(plan, builtin, "docs"); c == nil || c.Action != "add" {
t.Fatalf("built-in entry: %+v", c)
}
if len(plan.Notices) != 1 || plan.Notices[0] != PiBuiltinNotice {
t.Fatalf("notices: %v", plan.Notices)
}
result, err := s.Apply(plan.Revision)
if err != nil || !slices.Contains(result.Plan.Notices, PiBuiltinNotice) {
t.Fatalf("%+v %v", result, err)
}
again, err := s.Preview()
if err != nil || len(again.Notices) != 0 {
t.Fatalf("after sync: %v %v", again.Notices, err)
}
}
// A server already on Pi's built-in MCP syncs without the warning, including one whose
// config still says so with piExtension: builtin.
func TestPiBuiltinSyncHasNoMigrationNotice(t *testing.T) {
for _, extra := range []string{"", " piExtension: builtin\n"} {
s := testService(t)
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n"+extra), 0600); err != nil {
t.Fatal(err)
}
for range 2 {
plan, err := s.Preview()
if err != nil || slices.Contains(plan.Notices, PiBuiltinNotice) {
t.Fatalf("%q: %v %v", extra, plan.Notices, err)
}
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
}
}
}
// legacyPiService is a Pi home that an earlier Skillshare synced docs into for pi-mcp-adapter:
// the entry sits in mcp.json and the ledger owns it there.
func legacyPiService(t *testing.T) (s *Service, legacy, adapter string, entry map[string]any) {
t.Helper()
s = testService(t)
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piExtension: pi-mcp-adapter\n"), 0600); err != nil {
t.Fatal(err)
// A config set up for an old extension warns before its first sync, when nothing is
// written yet for the ledger to show.
func TestPiLegacyExtensionSettingsWarn(t *testing.T) {
for _, server := range []string{"piExtension: pi-mcp-extension", "piExtension: pi-mcp-adapter", "directTools: true", "piOptions:\n lifecycle: lazy"} {
s := testService(t)
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n "+server+"\n"), 0600); err != nil {
t.Fatal(err)
}
plan, err := s.Preview()
if err != nil || !slices.Contains(plan.Notices, PiBuiltinNotice) {
t.Fatalf("%q: %v %v", server, plan.Notices, err)
}
}
entry, err := Render("pi", Server{Command: "docs", PiExtension: "pi-mcp-adapter"})
if err != nil {
t.Fatal(err)
}
dir := filepath.Join(s.Home, ".pi", "agent")
legacy, adapter = filepath.Join(dir, "mcp.json"), filepath.Join(dir, "mcp-adapter.json")
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
owned := ownership{Owner: s.ConfigPath, Target: "pi", Path: legacy, Name: "docs", Hash: entryHash(managedEntry("pi", entry))}
if err := writeJSONFile(s.statePath(), ledger{Version: 1, Entries: map[string]ownership{ownershipKey("pi", legacy, "docs"): owned}}); err != nil {
t.Fatal(err)
}
return s, legacy, adapter, entry
}
func TestPiAdapterMovesOutOfMcpJSON(t *testing.T) {
s, legacy, adapter, entry := legacyPiService(t)
if err := writeJSONFile(legacy, map[string]any{"mcpServers": map[string]any{"docs": entry, "mine": map[string]any{"command": "mine"}}}); err != nil {
// Before 0.23.0 Pi took one mode per scope and refused a mix.
func TestPiMixedModesShareBuiltinFile(t *testing.T) {
s := testService(t)
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n targets: [pi]\n servers:\n a:\n command: a\n piExtension: pi-mcp-adapter\n b:\n command: b\n piExtension: pi-mcp-extension\n c:\n command: c\n piExtension: builtin\n"), 0600); err != nil {
t.Fatal(err)
}
plan, err := s.Preview()
if err != nil || plan.Blocked {
if err != nil || plan.Blocked || len(plan.Changes) != 3 {
t.Fatalf("%+v %v", plan, err)
}
if c := changeFor(plan, legacy, "docs"); c == nil || c.Action != "remove" {
t.Fatalf("old entry: %+v", c)
}
if c := changeFor(plan, adapter, "docs"); c == nil || c.Action != "add" {
t.Fatalf("new entry: %+v", c)
}
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
if data, _ := os.ReadFile(legacy); strings.Contains(string(data), `"docs"`) || !strings.Contains(string(data), `"mine"`) {
t.Fatalf("mcp.json: %s", data)
for _, c := range plan.Changes {
if c.Path != filepath.Join(s.Home, ".pi", "agent", "mcp.json") || c.Action != "add" {
t.Fatalf("%+v", c)
}
}
}
// Pi's warning tells the user to mv mcp.json to mcp-adapter.json. Skillshare keeps owning
// what it wrote there instead of reporting the moved entry as the user's own.
func TestPiAdapterKeepsOwningAMovedFile(t *testing.T) {
s, _, adapter, entry := legacyPiService(t)
if err := writeJSONFile(adapter, map[string]any{"mcpServers": map[string]any{"docs": entry}}); err != nil {
t.Fatal(err)
}
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
state, _, _ := s.loadLedger()
if _, owned := state.Entries[ownershipKey("pi", adapter, "docs")]; !owned {
t.Fatalf("ownership not moved: %+v", state.Entries)
}
}
// Both files are Pi's, so import and the unmanaged scan read the one each extension uses.
// Pi's built-in mcp.json comes first; the adapter's file is still read so hand-written
// servers there can be imported.
func TestPiImportReadsBothFiles(t *testing.T) {
s := testService(t)
dir := filepath.Join(s.Home, ".pi", "agent")
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
for file, name := range map[string]string{"mcp-adapter.json": "adapted", "mcp.json": "extended"} {
if err := writeJSONFile(filepath.Join(dir, file), map[string]any{"mcpServers": map[string]any{name: map[string]any{"command": name}}}); err != nil {
for file, entries := range map[string]map[string]any{
"mcp-adapter.json": {"adapted": map[string]any{"command": "adapted"}, "both": map[string]any{"command": "adapter"}},
"mcp.json": {"builtin": map[string]any{"command": "builtin"}, "both": map[string]any{"command": "builtin"}},
} {
if err := writeJSONFile(filepath.Join(dir, file), map[string]any{"mcpServers": entries}); err != nil {
t.Fatal(err)
}
}
candidates, err := s.ImportClient("pi")
if err != nil || len(candidates) != 2 {
if err != nil || len(candidates) != 3 {
t.Fatalf("%+v %v", candidates, err)
}
for _, c := range candidates {
if c.Name == "adapted" && c.Server.PiExtension != "pi-mcp-adapter" {
t.Errorf("mcp-adapter.json is only read by pi-mcp-adapter: %+v", c)
if c.Name == "both" && c.Server.Command != "builtin" {
t.Errorf("mcp.json must win: %+v", c)
}
if c.Name == "adapted" && !strings.Contains(strings.Join(c.Warnings, ";"), "mcp-adapter.json") {
t.Errorf("adapter origin not reported: %+v", c)
}
}
var names []string
for _, found := range s.FindUnmanaged(&Source{ConfigPath: s.ConfigPath}) {
names = append(names, found.Names...)
}
if strings.Join(names, ",") != "adapted,extended" {
if strings.Join(names, ",") != "both,builtin,adapted,both" {
t.Fatalf("unmanaged: %v", names)
}
}
+40 -58
View File
@@ -54,9 +54,15 @@ func changeRoot(target, path string, roots []string) string {
// Plan is a redacted, optimistic-concurrency-protected preview.
type Plan struct {
Revision string `json:"revision"`
SourcePath string `json:"sourcePath"`
Blocked bool `json:"blocked"`
Revision string `json:"revision"`
SourcePath string `json:"sourcePath"`
Blocked bool `json:"blocked"`
// Notices are the source's, about settings it still has that no longer apply, and name
// each Agent that cannot hold a part of a server's tool policy.
Notices []string `json:"notices,omitempty"`
// Migrates is set when applying the plan also saves its source without the settings
// 0.23.0 retired, even when no Agent file changes.
Migrates bool `json:"migrates,omitempty"`
Changes []Change `json:"changes"`
files []*filePlan
state ledger
@@ -78,6 +84,21 @@ type ledger struct {
Entries map[string]ownership `json:"entries"`
}
// PiBuiltinNotice is the plan's notice when it moves servers from pi-mcp-adapter or
// pi-mcp-extension to Pi's built-in MCP. Pi's MCP docs say an installed extension that
// registers /mcp replaces the built-in support; pi-mcp-extension, and pi-mcp-adapter
// before 3.0.0, read mcp.json too. The dashboard matches the text, so change both together.
const PiBuiltinNotice = "Pi's built-in MCP needs Pi 0.99.0 or later; on older Pi these servers stop loading until Pi is updated. If pi-mcp-adapter or pi-mcp-extension is still installed in Pi, remove it, because it can take the place of Pi's built-in MCP"
// piExtensionEntry reports an entry Skillshare wrote for pi-mcp-adapter or pi-mcp-extension
// before 0.23.0: one in the adapter's own file, or one with the transport field only
// pi-mcp-extension read. The built-in entry never has it, and it is part of the hash, so an
// owned entry that still matches carries it only from Skillshare.
func piExtensionEntry(target, path string, entry map[string]any) bool {
_, transport := entry["transport"]
return target == "pi" && (path == piAdapterPath(path) || transport)
}
// orphanedMessage leads a conflict whose owning config is gone. The dashboard matches
// conflicts on how the message starts, so the path stays last and nothing else may.
const orphanedMessage = "left over from a Skillshare config that was removed; import it or explicitly replace this entry"
@@ -201,7 +222,7 @@ func (s *Service) render(source *Source) (map[fileKey]map[string]map[string]any,
// A project's own config cannot see the global one, so only the Agents' limits apply.
servers = followingSwitches(servers, source.Targets, nil)
}
if err := s.renderScope(desired, servers, source.Targets, source.DirectTools); err != nil {
if err := s.renderScope(desired, servers, source.Targets); err != nil {
return nil, err
}
for _, root := range sortedKeys(source.Projects) {
@@ -212,11 +233,7 @@ func (s *Service) render(source *Source) (map[fileKey]map[string]map[string]any,
if defaults == nil {
defaults = source.Targets
}
directTools := project.DirectTools
if directTools == nil {
directTools = source.DirectTools
}
if err := scoped.renderScope(desired, followingSwitches(project.Servers, defaults, source), defaults, directTools); err != nil {
if err := scoped.renderScope(desired, followingSwitches(project.Servers, defaults, source), defaults); err != nil {
return nil, fmt.Errorf("%s: %w", root, err)
}
}
@@ -253,17 +270,6 @@ func followingSwitches(servers map[string]Server, defaults []string, global *Sou
if reached = shared.Targets; reached == nil {
reached = global.Targets
}
// Pi has a switch only with pi-mcp-adapter, which the global server already says.
if server.PiExtension == "" {
server.PiExtension = shared.PiExtension
}
}
}
// Pi reads one file per project through one extension. What the project's own servers
// use decides, and with pi-mcp-extension Pi has no switch to write.
for _, own := range servers {
if !own.Disabled && own.PiExtension != "" {
server.PiExtension = own.PiExtension
}
}
server.Targets = SwitchTargets(server, defaults, reached)
@@ -282,11 +288,9 @@ func followingSwitches(servers map[string]Server, defaults []string, global *Sou
}
// renderScope adds one scope's servers: the global one, or a single project root.
func (s *Service) renderScope(desired map[fileKey]map[string]map[string]any, servers map[string]Server, defaults []string, directTools any) error {
piExtension := ""
func (s *Service) renderScope(desired map[fileKey]map[string]map[string]any, servers map[string]Server, defaults []string) error {
for _, name := range sortedKeys(servers) {
server := servers[name]
server = server.withDirectToolsDefault(directTools)
// An explicit empty list is deliberate: the server stays in Skillshare and nothing is
// written. An inherited one is more likely a forgotten default, so it is refused.
selected := []string(server.Targets)
@@ -301,12 +305,6 @@ func (s *Service) renderScope(desired map[fileKey]map[string]map[string]any, ser
if err := s.checkScope(name, target, server); err != nil {
return err
}
if target == "pi" {
if piExtension != "" && piExtension != server.PiExtension {
return fmt.Errorf("Pi uses one MCP mode per scope; select the same piExtension for every Pi server")
}
piExtension = server.PiExtension
}
path, native, err := s.destination(target, server)
if err != nil {
return err
@@ -357,7 +355,7 @@ func (s *Service) shownAs(target, path string, accounts map[string]Account) stri
scoped := *s
scoped.accounts, scoped.ProjectRoot = accounts, ""
account, agent := scoped.forTarget(name)
if file, err := account.nativePath(agent); err == nil && agent == shown && (file == path || agent == "pi" && piExtensionPath(file) == path) {
if file, err := account.nativePath(agent); err == nil && agent == shown && (file == path || agent == "pi" && piAdapterPath(file) == path) {
return name
}
}
@@ -375,10 +373,6 @@ func (s *Service) destination(target string, server Server) (string, string, err
path, err := global.nativePath(target)
return path, claudeOffPrefix + s.ProjectRoot, err
}
if target == "pi" {
path, err := s.piModePath(server.PiExtension)
return path, target, err
}
path, err := s.nativePath(target)
return path, target, err
}
@@ -421,14 +415,7 @@ func (s *Service) checkScope(name, target string, server Server) error {
switch {
case server.Disabled && s.ProjectRoot == "":
return fmt.Errorf("MCP %s: disabled only applies in project mode, where it turns off a server from the Agent's global config; here, unselect the Agent instead", name)
case target == "pi" && s.ProjectRoot == "" && s.ConfigDirs["pi"] != "" && server.PiExtension == "pi-mcp-extension":
// An account is a directory the user chose, so say which one is out of reach and
// what to select instead; an environment override they can simply unset.
if s.account != "" {
return fmt.Errorf("pi-mcp-extension always reads ~/.pi/agent/mcp.json, so it cannot reach account %s (%s); set piExtension: pi-mcp-adapter on this server", s.account, s.ConfigDirs["pi"])
}
return fmt.Errorf("pi-mcp-extension uses ~/.pi/agent/mcp.json and does not honor PI_CODING_AGENT_DIR; unset the override before syncing")
case target == "pi" && server.PiExtension == "builtin" && strings.Contains(name, "."):
case target == "pi" && strings.Contains(name, "."):
return fmt.Errorf("Pi built-in MCP %s: use letters, digits, underscores or hyphens", name)
case target == "grok" && (!grokServerName.MatchString(name) || strings.Contains(name, "__") || strings.HasSuffix(name, "_")):
return fmt.Errorf("Grok MCP %s: use a name starting with a letter or underscore, containing only letters, digits, hyphens and single underscores, and not ending in underscore", name)
@@ -467,7 +454,7 @@ func (s *Service) previewResolved(source *Source, resolutions []Resolution) (*Pl
if err != nil {
return nil, err
}
p := &Plan{SourcePath: source.Path, Changes: []Change{}, source: source, state: state, stateBytes: stateBytes}
p := &Plan{SourcePath: source.Path, Notices: slices.Concat(source.Notices, source.toolPolicyNotices()), Migrates: source.NeedsMigration(), Changes: []Change{}, source: source, state: state, stateBytes: stateBytes}
desired, err := s.render(source)
if err != nil {
return nil, err
@@ -484,9 +471,8 @@ func (s *Service) previewResolved(source *Source, resolutions []Resolution) (*Pl
Servers map[string]Server
Targets []string
Resolutions []Resolution
DirectTools any
Projects map[string]Project
}{source.Servers, source.Targets, resolutions, source.DirectTools, source.Projects})
}{source.Servers, source.Targets, resolutions, source.Projects})
revision := digest(source.configBytes) + digest(source.bytes) + digest(stateBytes) + digest(proposal)
// Claude's local scope is per project, so look it up by the project file it shadows.
local := map[string]map[string]any{}
@@ -501,8 +487,7 @@ func (s *Service) previewResolved(source *Source, resolutions []Resolution) (*Pl
}
}
projectRoots := sortedKeys(source.Projects)
// The ownership before any file is planned, since planning one file drops entries of another.
owners := maps.Clone(state.Entries)
piMoves := source.piExtensionSettings
keys := make([]fileKey, 0, len(desired))
for key := range desired {
keys = append(keys, key)
@@ -546,7 +531,8 @@ func (s *Service) previewResolved(source *Source, resolutions []Resolution) (*Pl
wantHash := entryHash(managedEntry(target, want))
prune := map[string]bool{}
pruneConflict := false
if target == "pi" && want != nil && managed && owned.Owner == source.ConfigPath && piPrunes(source, changeRoot(target, path, projectRoots), name) {
// Fields this config wrote earlier and no longer sets go, unless Pi changed them since.
if target == "pi" && want != nil && managed && owned.Owner == source.ConfigPath {
for field, hash := range owned.PiFields {
if _, set := want[field]; set {
continue
@@ -560,16 +546,6 @@ func (s *Service) previewResolved(source *Source, resolutions []Resolution) (*Pl
}
}
}
// pi-mcp-adapter 3 tells the user to mv mcp.json to mcp-adapter.json. An entry this
// config owned there and that arrived unchanged is still its own. Refs: #298.
if !managed && target == "pi" && path != piExtensionPath(path) {
prior, ok := owners[ownershipKey(target, piExtensionPath(path), name)]
if ok && prior.Owner == source.ConfigPath && prior.Hash == currentHash {
owned = ownership{Owner: source.ConfigPath, Target: target, Path: path, Name: name, Hash: currentHash}
managed = true
p.state.Entries[key] = owned
}
}
for _, resolution := range resolutions {
if resolution.Target != shown || resolution.Name != name {
continue
@@ -659,6 +635,9 @@ func (s *Service) previewResolved(source *Source, resolutions []Resolution) (*Pl
p.state.Entries[key] = own
}
}
if (change.Action == "remove" || change.Action == "update") && piExtensionEntry(target, path, current) {
piMoves = true
}
change.Fields = changedFieldNames(current, f.changes[name], change.Action)
if change.Action == "conflict" {
p.Blocked = true
@@ -674,6 +653,9 @@ func (s *Service) previewResolved(source *Source, resolutions []Resolution) (*Pl
p.files = append(p.files, f)
}
p.Revision = digest([]byte(revision))
if piMoves {
p.Notices = append(p.Notices, PiBuiltinNotice)
}
for _, found := range matched {
if !found {
return nil, fmt.Errorf("conflict resolution does not refer to a selected MCP entry")
+32 -29
View File
@@ -12,8 +12,6 @@ func renderDisabled(target string, s Server) (map[string]any, error) {
switch {
case openCodeFormat(target):
return map[string]any{"enabled": false}, nil
case target == "pi" && s.PiExtension == "pi-mcp-adapter":
return map[string]any{"disabled": true}, nil
case target == "claude":
// No entry to write: destination sends the name to Claude Code's per-project off list.
return map[string]any{}, nil
@@ -24,7 +22,7 @@ func renderDisabled(target string, s Server) (map[string]any, error) {
// usually committed, so one person's switch would break Codex for a teammate.
return nil, fmt.Errorf("codex cannot turn off a global server from a project file: on a machine whose global config lacks the server, Codex stops loading its whole config; set enabled = false in ~/.codex/config.toml instead")
}
return nil, fmt.Errorf("%s cannot turn off a global server from a project file; disabled supports claude, opencode, kilocode and pi with pi-mcp-adapter", target)
return nil, fmt.Errorf("%s cannot turn off a global server from a project file; disabled supports claude, opencode and kilocode", target)
}
// Render converts a portable definition to a native entry without reading env.
@@ -144,6 +142,16 @@ func Render(target string, s Server) (map[string]any, error) {
out["env_http_headers"] = envHeaders
}
}
if target == "codex" {
// Codex applies disabled_tools after enabled_tools; both list exact tool names.
allow, deny, _ := namedTools(s.Tools, true)
if allow != nil {
out["enabled_tools"] = allow
}
if deny != nil {
out["disabled_tools"] = deny
}
}
return out, nil
}
@@ -153,19 +161,17 @@ type Rendered struct {
Path string `json:"path"`
Content string `json:"content,omitempty"`
Error string `json:"error,omitempty"`
// ToolGaps are the parts of the server's tool policy this Agent cannot hold, as the
// plan's notices name them, so an editor can say so before the server is saved.
ToolGaps []string `json:"toolGaps,omitempty"`
}
// RenderNative writes the server into an empty file per target, so the wrapper key and the
// format (JSON, TOML, YAML) come from the code that writes the real file, not from a guess
// made in the dashboard. Existing Pi-only settings are included with native secrets redacted; nothing is executed or written.
func (s *Service) RenderNative(name string, server Server) []Rendered {
// The saved mcp.directTools default is what sync would write; an unreadable config has none.
// An unreadable config has no accounts.
if source, err := LoadSource(s.ConfigPath); err == nil {
defaults := source.DirectTools
if project, ok := source.Projects[s.ProjectRoot]; ok && project.DirectTools != nil {
defaults = project.DirectTools
}
server = server.withDirectToolsDefault(defaults)
scoped := *s
scoped.accounts = source.Accounts
s = &scoped
@@ -174,6 +180,7 @@ func (s *Service) RenderNative(name string, server Server) []Rendered {
for _, target := range server.Targets {
r := Rendered{Target: target}
client, agent := s.forTarget(target)
r.ToolGaps = toolPolicyGaps(agent, server.Tools)
path, native, err := client.destination(agent, server)
r.Path = path
if err == nil {
@@ -192,27 +199,23 @@ func (s *Service) RenderNative(name string, server Server) []Rendered {
if readErr != nil {
err = readErr
} else {
before := current.Entries[name]
entry = withAgentFields("pi", before, entry)
if server.PiOptionsPrune {
state, _, stateErr := s.loadLedger()
if stateErr != nil {
err = stateErr
} else {
own := state.Entries[ownershipKey("pi", path, name)]
if own.Owner == s.ConfigPath {
for key, hash := range own.PiFields {
if _, set := server.PiOptions[key]; set || key == "directTools" && server.DirectTools != nil {
continue
}
if value, exists := before[key]; exists {
if piFieldHash(value) != hash {
err = fmt.Errorf("Pi setting changed since sync: %s", key)
break
}
delete(entry, key)
}
before, want := current.Entries[name], entry
entry = withAgentFields("pi", before, want)
// Sync removes the fields it wrote earlier that the server no longer sets.
state, _, stateErr := s.loadLedger()
if stateErr != nil {
err = stateErr
} else if own := state.Entries[ownershipKey("pi", path, name)]; own.Owner == s.ConfigPath {
for key, hash := range own.PiFields {
if _, set := want[key]; set {
continue
}
if value, exists := before[key]; exists {
if piFieldHash(value) != hash {
err = fmt.Errorf("Pi setting changed since sync: %s", key)
break
}
delete(entry, key)
}
}
}
+5 -31
View File
@@ -23,6 +23,10 @@ type Service struct {
Platform string
// ConfigDirs contains explicitly resolved native client directory overrides.
ConfigDirs map[string]string
// BackupSource keeps a config file's content before a sync rewrites it without the
// settings 0.23.0 retired, and returns where. The CLI and the server keep it in the
// file history.
BackupSource func(path string) (string, error)
// accounts are the source's, set while rendering it.
accounts map[string]Account
// account is the one this Service was scoped to, empty when it is the Agent's own.
@@ -203,40 +207,10 @@ func (s *Service) AccountPaths(accounts map[string]Account) map[string]string {
return out
}
// ConfiguredClientPaths names the selected Pi mode's destination for dashboard labels.
// ConfiguredClientPaths names each target's destination, accounts included, for dashboard labels.
func (s *Service) ConfiguredClientPaths(source *Source) map[string]string {
paths := s.ClientPaths()
maps.Copy(paths, s.AccountPaths(source.Accounts))
scoped := *s
scoped.accounts = source.Accounts
for target := range paths {
if target != "pi" && source.Accounts[target].Agent != "pi" {
continue
}
modes := map[string]bool{}
for _, server := range source.Servers {
selected := server.Targets
if selected == nil {
selected = source.Targets
}
if !server.Disabled && slices.Contains(selected, target) && server.PiExtension != "" {
modes[server.PiExtension] = true
}
}
mode := "builtin"
for _, candidate := range []string{"builtin", "pi-mcp-adapter", "pi-mcp-extension"} {
if modes[candidate] {
mode = candidate
break
}
}
client, _ := scoped.forTarget(target)
if path, err := client.piModePath(mode); err == nil {
paths[target] = path
} else {
delete(paths, target)
}
}
return paths
}
+172 -30
View File
@@ -20,14 +20,19 @@ type Source struct {
Path string `json:"path"`
Targets []string `json:"targets"`
Servers map[string]Server `json:"servers"`
// DirectTools is the default for pi-mcp-adapter servers that do not set their own,
// as Targets is for targets. It stands in for the adapter's settings.directTools,
// which shares Pi's file with the servers and a plan edits each file once.
DirectTools any `json:"directTools,omitempty"`
// Projects are project roots a global config syncs into, keyed by absolute path.
Projects map[string]Project `json:"projects,omitempty"`
// Accounts are the config's targets that are another config directory of an Agent.
Accounts map[string]Account `json:"accounts,omitempty"`
// Notices name settings the config still has that no longer apply. Loading the config
// is not an error for them; saving it drops what can be dropped.
Notices []string `json:"notices,omitempty"`
// migrateConfig and migrateExternal mark the files loading converted from settings
// 0.23.0 retired; sync writes them back so the notices go away.
migrateConfig, migrateExternal bool
// piExtensionSettings marks settings only pi-mcp-adapter or pi-mcp-extension read, so
// the plan warns what Pi's built-in MCP needs (PiBuiltinNotice).
piExtensionSettings bool
// projectKeys holds each root as config.yaml spells it, so saving keeps a leading ~.
projectKeys map[string]string
// What a draft changed, so save re-encodes nothing else.
@@ -44,9 +49,8 @@ type Source struct {
// Project is what a project's own config.yaml would hold under mcp, declared in the
// global config instead so one sync reaches every root.
type Project struct {
Targets []string `yaml:"targets,omitempty" json:"targets,omitempty"`
DirectTools any `yaml:"directTools,omitempty" json:"directTools,omitempty"`
Servers map[string]Server `yaml:"servers,omitempty" json:"servers,omitempty"`
Targets []string `yaml:"targets,omitempty" json:"targets,omitempty"`
Servers map[string]Server `yaml:"servers,omitempty" json:"servers,omitempty"`
}
func mapping(node *yaml.Node) *yaml.Node {
@@ -155,7 +159,66 @@ func LoadSource(configPath string) (*Source, error) {
if err := validateTargets(s.Targets); err != nil {
return nil, err
}
if s.Accounts, err = parseAccounts(field(&s.configDoc, "targets")); err != nil {
return nil, err
}
global := migration{defaults: s.Targets}
for name, account := range s.Accounts {
if account.Agent == "pi" {
global.piAccounts = append(global.piAccounts, name)
}
}
legacy := map[string][]legacyName{}
note := func(found map[string][]string, root string, external bool) {
for key, names := range found {
for _, name := range names {
legacy[key] = append(legacy[key], legacyName{name, root})
}
}
if len(found) > 0 {
s.migrateExternal = s.migrateExternal || external
s.migrateConfig = s.migrateConfig || !external
}
}
// A directTools default becomes each server's own before the servers are decoded.
directDefault := func(scope *yaml.Node, label string) (any, error) {
n := field(scope, "directTools")
if n == nil {
return nil, nil
}
var value any
if err := n.Decode(&value); err != nil || !ValidDirectTools(value) {
return nil, fmt.Errorf("%s must be true, false, \"search\" or a list of tool names", label)
}
// The servers it reaches are named; the default itself only needs the config saved.
drop(scope, "directTools")
s.migrateConfig = true
return value, nil
}
var servers *yaml.Node
if mcp != nil {
servers = field(mcp, "servers")
if global.directTools, err = directDefault(mcp, "mcp.directTools"); err != nil {
return nil, err
}
if projects := deref(field(mcp, "projects")); projects != nil && projects.Kind == yaml.MappingNode {
for i := 0; i+1 < len(projects.Content); i += 2 {
root, project := projects.Content[i].Value, deref(projects.Content[i+1])
scope := global
if project.Kind == yaml.MappingNode {
if value, err := directDefault(project, "directTools ("+root+")"); err != nil {
return nil, fmt.Errorf("mcp.projects: %s: %w", root, err)
} else if value != nil {
scope.directTools = value
}
if n := field(project, "targets"); n != nil {
scope.defaults = nil
_ = n.Decode(&scope.defaults)
}
}
note(migrateServers(field(project, "servers"), scope), root, false)
}
}
if s.Projects, err = ParseProjects(field(mcp, "projects")); err != nil {
return nil, err
}
@@ -166,15 +229,6 @@ func LoadSource(configPath string) (*Source, error) {
s.projectKeys[filepath.Clean(root)] = projects.Content[i].Value
}
}
if n := field(mcp, "directTools"); n != nil {
if err := n.Decode(&s.DirectTools); err != nil || !ValidDirectTools(s.DirectTools) {
return nil, fmt.Errorf("mcp.directTools must be true, false, \"search\" or a list of tool names")
}
}
}
var servers *yaml.Node
if mcp != nil {
servers = field(mcp, "servers")
}
if sources := field(&s.configDoc, "sources"); sources != nil {
if sources.Kind != yaml.MappingNode {
@@ -220,14 +274,9 @@ func LoadSource(configPath string) (*Source, error) {
if servers.Kind != yaml.MappingNode {
return nil, fmt.Errorf("MCP servers must be a mapping")
}
data, err := yaml.Marshal(servers)
if err != nil {
return nil, err
}
decoder := yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
if err := decoder.Decode(&s.Servers); err != nil {
return nil, fmt.Errorf("invalid MCP server fields: use command/args/env or url/headers/bearerToken and optional targets/transport/piExtension, or disabled with targets")
note(migrateServers(servers, global), "", s.Path != path)
if s.Servers, err = ParseServers(servers); err != nil {
return nil, fmt.Errorf("invalid MCP server fields: use command/args/env or url/headers/bearerToken and optional targets/transport/piOptions, or disabled with targets")
}
}
for name, server := range s.Servers {
@@ -235,12 +284,71 @@ func LoadSource(configPath string) (*Source, error) {
return nil, err
}
}
if s.Accounts, err = parseAccounts(field(&s.configDoc, "targets")); err != nil {
return nil, err
s.Notices = legacyNotices(legacy)
for key := range legacy {
if key == "piTools" || strings.HasPrefix(key, "piOptions.") || strings.HasPrefix(key, "piExtension.") {
s.piExtensionSettings = true
}
}
return s, s.checkTargets()
}
// legacyName is a server that had a setting 0.23.0 retired, and the mcp.projects root it
// is under, empty for the scope's own servers.
type legacyName struct{ name, root string }
// legacyNotices explains, one line per kind, the settings 0.23.0 retired that the config
// still has. Each server is named once; one found only under mcp.projects adds the folder
// names of its roots.
func legacyNotices(legacy map[string][]legacyName) []string {
list := func(keys ...string) string {
roots := map[string][]string{}
for _, key := range keys {
for _, n := range legacy[key] {
folder := ""
if n.root != "" {
folder = filepath.Base(filepath.Clean(n.root))
}
if !slices.Contains(roots[n.name], folder) {
roots[n.name] = append(roots[n.name], folder)
}
}
}
var names []string
for _, name := range sortedKeys(roots) {
folders := roots[name]
if slices.Contains(folders, "") {
names = append(names, name)
continue
}
slices.Sort(folders)
names = append(names, name+" ("+strings.Join(folders, ", ")+")")
}
return strings.Join(names, ", ")
}
var notices []string
add := func(text string, keys ...string) {
if names := list(keys...); names != "" {
notices = append(notices, text+": "+names)
}
}
add("Pi now uses its built-in MCP; the next sync updates the config", "piExtension")
add("piOptionsPrune is no longer used; the next sync removes it", "piOptionsPrune")
var adapter, keys []string
for _, key := range adapterPiOptions {
if len(legacy["piOptions."+key]) > 0 {
adapter, keys = append(adapter, key), append(keys, "piOptions."+key)
}
}
if len(adapter) > 0 {
add("Pi's built-in MCP does not read "+strings.Join(adapter, ", ")+"; the next sync removes them", keys...)
}
add("Pi cannot turn off a server per project; the next sync removes pi from these entries", "piSwitch")
add("directTools, includeTools and excludeTools become tool settings; the next sync converts them", "piTools")
add("directTools, includeTools or excludeTools the server already covers, or that are not tool lists, are dropped; the next sync removes them", "piTools.directTools", "piTools.excludeTools", "piTools.includeTools")
return notices
}
// parseAccounts reads the targets that are another config directory of an Agent whose MCP
// file follows that directory. The config package validates the section itself.
func parseAccounts(node *yaml.Node) (map[string]Account, error) {
@@ -344,6 +452,30 @@ func ReferenceWarning(configPath, target string) string {
return fmt.Sprintf("%s %s %s; remove it there too or the next mcp sync fails", strings.Join(places, ", "), names, target)
}
// ParseServers decodes a servers mapping strictly, after migrateServers has taken out what
// 0.23.0 retired. It does not validate the servers.
func ParseServers(node *yaml.Node) (map[string]Server, error) {
data, err := yaml.Marshal(expandAliases(node))
if err != nil {
return nil, err
}
var copied yaml.Node
if err := yaml.Unmarshal(data, &copied); err != nil {
return nil, err
}
migrateServers(mapping(&copied), migration{})
if data, err = yaml.Marshal(&copied); err != nil {
return nil, err
}
servers := map[string]Server{}
decoder := yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
if err := decoder.Decode(&servers); err != nil {
return nil, err
}
return servers, nil
}
// ParseProjects reads and validates mcp.projects. The config editor shares it, so it
// never accepts a section that sync would then refuse.
func ParseProjects(node *yaml.Node) (map[string]Project, error) {
@@ -356,6 +488,19 @@ func ParseProjects(node *yaml.Node) (map[string]Project, error) {
if err != nil {
return nil, err
}
var copied yaml.Node
if err := yaml.Unmarshal(data, &copied); err != nil {
return nil, err
}
if projects := mapping(&copied); projects.Kind == yaml.MappingNode {
for i := 0; i+1 < len(projects.Content); i += 2 {
drop(projects.Content[i+1], "directTools")
migrateServers(field(projects.Content[i+1], "servers"), migration{})
}
}
if data, err = yaml.Marshal(&copied); err != nil {
return nil, err
}
var declared map[string]Project
decoder := yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
@@ -371,7 +516,7 @@ func ParseProjects(node *yaml.Node) (map[string]Project, error) {
}
reason = strings.Join(typeErr.Errors, "; ")
}
return nil, fmt.Errorf("mcp.projects: %s; each project root takes only targets, servers and directTools", reason)
return nil, fmt.Errorf("mcp.projects: %s; each project root takes only targets and servers", reason)
}
projects := map[string]Project{}
for root, project := range declared {
@@ -389,9 +534,6 @@ func ParseProjects(node *yaml.Node) (map[string]Project, error) {
if err := validateTargets(project.Targets); err != nil {
return nil, err
}
if !ValidDirectTools(project.DirectTools) {
return nil, fmt.Errorf("mcp.projects: %s: directTools must be true, false, \"search\" or a list of tool names", root)
}
for name, server := range project.Servers {
if err := server.Validate(name); err != nil {
return nil, err
+48
View File
@@ -1,6 +1,7 @@
package mcp
import (
"encoding/json"
"os"
"path/filepath"
"strings"
@@ -84,3 +85,50 @@ func TestRenderDoesNotResolveSecrets(t *testing.T) {
t.Fatal("cannot silently rename Codex environment variables")
}
}
// piExtension and piOptionsPrune were retired in 0.23.0. A config that still has them loads
// with one notice each, and the next save drops them, from a project it did not touch too.
func TestLegacyPiFieldsLoadAndDropOnSave(t *testing.T) {
s, _ := projectsService(t, `mcp:
targets: [opencode]
servers:
docs:
command: docs
piExtension: pi-mcp-adapter
piOptionsPrune: true
projects:
$TMP/p1:
servers:
local:
command: local
piExtension: pi-mcp-extension
`)
source, err := LoadSource(s.ConfigPath)
if err != nil {
t.Fatal(err)
}
if len(source.Notices) != 2 || source.Notices[0] != "Pi now uses its built-in MCP; the next sync updates the config: docs, local (p1)" || !strings.Contains(source.Notices[1], "piOptionsPrune") {
t.Fatalf("notices: %q", source.Notices)
}
if _, err := s.Mutate(Mutation{Name: "other", Server: &Server{Command: "other"}}, "", false); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(s.ConfigPath)
if strings.Contains(string(data), "piExtension") || strings.Contains(string(data), "piOptionsPrune") || !strings.Contains(string(data), "command: local") {
t.Fatalf("saved config: %s", data)
}
if source, err = LoadSource(s.ConfigPath); err != nil || len(source.Notices) != 0 {
t.Fatalf("%v %v", source.Notices, err)
}
}
// The dashboard sent piExtension and piOptionsPrune before 0.23.0; they are accepted and ignored.
func TestServerJSONIgnoresLegacyPiFields(t *testing.T) {
var server Server
if err := json.Unmarshal([]byte(`{"command":"docs","piExtension":"pi-mcp-adapter","piOptionsPrune":true}`), &server); err != nil || server.Command != "docs" {
t.Fatalf("%+v %v", server, err)
}
if err := json.Unmarshal([]byte(`{"command":"docs","unknown":true}`), &server); err == nil {
t.Fatal("unknown field accepted")
}
}
+281
View File
@@ -0,0 +1,281 @@
package mcp
import (
"encoding/json"
"fmt"
"regexp"
"slices"
"strings"
)
// ToolPolicy says which of a server's tools reach the model. It is written once and
// translated per Agent; the plan and check name each Agent that cannot hold a part of it.
type ToolPolicy struct {
// Allow, when set, keeps only the tools that match. Deny removes the tools that match and
// beats Allow. Entries are tool names in which * matches any characters.
Allow []string `yaml:"allow,omitempty" json:"allow,omitempty"`
Deny []string `yaml:"deny,omitempty" json:"deny,omitempty"`
}
// IsZero makes an empty policy mean no policy, and keeps it out of YAML and JSON.
func (t ToolPolicy) IsZero() bool { return len(t.Allow) == 0 && len(t.Deny) == 0 }
// toolPattern leaves out the wildcards other than * and the comma the CLI splits lists on.
var toolPattern = regexp.MustCompile(`^[^\s,?\[\]{}]+$`)
func (t ToolPolicy) validate(name string) error {
for part, patterns := range map[string][]string{"allow": t.Allow, "deny": t.Deny} {
for i, pattern := range patterns {
if !toolPattern.MatchString(pattern) {
return fmt.Errorf("MCP %s: tools.%s: %q is not a tool name; use letters, digits and punctuation, with * matching any characters", name, part, pattern)
}
if slices.Contains(patterns[:i], pattern) {
return fmt.Errorf("MCP %s: tools.%s lists %q twice", name, part, pattern)
}
}
}
if len(t.Allow) > 0 && !slices.ContainsFunc(t.Allow, func(tool string) bool { return isToolPattern(tool) || !t.denied(tool) }) {
return fmt.Errorf("MCP %s: tools.deny removes every tool tools.allow keeps", name)
}
return nil
}
func isToolPattern(tool string) bool { return strings.Contains(tool, "*") }
func matchTool(pattern, tool string) bool {
return regexp.MustCompile("^" + strings.ReplaceAll(regexp.QuoteMeta(pattern), `\*`, ".*") + "$").MatchString(tool)
}
// denied reports a tool name that a deny entry matches.
func (t ToolPolicy) denied(tool string) bool {
return slices.ContainsFunc(t.Deny, func(pattern string) bool { return matchTool(pattern, tool) })
}
// piToolPolicy writes a policy into a Pi entry. Pi takes an exact tool name over any
// pattern, and among patterns the first that matches, so the denied tools come first,
// then the allowed ones, then "*": "hidden" to close the list. An allowed name that a
// denied pattern matches is left out, or it would win over that pattern. Allowed tools
// get the entry's exposure (piOptions.exposure), or Pi's default, codemode, when that is
// unset or hidden.
func piToolPolicy(entry map[string]any, t ToolPolicy) {
allowed := "codemode"
if exposure, _ := entry["exposure"].(string); exposure != "" && exposure != "hidden" {
allowed = exposure
}
var exposure piToolExposure
add := func(tool, value string) {
if !slices.ContainsFunc(exposure, func(e piExposureEntry) bool { return e.Key == tool }) {
exposure = append(exposure, piExposureEntry{tool, value})
}
}
for _, tool := range t.Deny {
add(tool, "hidden")
}
for _, tool := range t.Allow {
if isToolPattern(tool) || !t.denied(tool) {
add(tool, allowed)
}
}
if len(t.Allow) > 0 {
add("*", "hidden")
}
if len(exposure) > 0 {
entry["toolExposure"] = exposure
}
}
// namedTools is a policy for an Agent that lists exact tool names, and the parts it cannot
// hold. allow is nil when every tool stays. A deny list (denyList) takes denied names as
// they are; otherwise, or for denied patterns, an allow list of names leaves them out.
func namedTools(t ToolPolicy, denyList bool) (allow, deny, gaps []string) {
all := len(t.Allow) == 0 || slices.Contains(t.Allow, "*")
names := !all && !slices.ContainsFunc(t.Allow, isToolPattern)
if !all && !names {
gaps = append(gaps, "allow patterns")
}
switch {
case len(t.Deny) == 0:
case denyList && !slices.ContainsFunc(t.Deny, isToolPattern):
deny = slices.Clone(t.Deny)
case names:
case !denyList:
gaps = append(gaps, "deny")
default:
gaps = append(gaps, "deny patterns")
}
if names {
allow = slices.Clone(t.Allow)
if deny == nil {
allow = slices.DeleteFunc(allow, t.denied)
}
}
return allow, deny, gaps
}
// toolPolicyGaps names the parts of a policy an Agent cannot hold. Pi holds all of it;
// Codex and Copilot list exact tool names, and Copilot has no deny list. OpenCode and Kilo
// Code filter tools only in a permission section outside the server's entry.
func toolPolicyGaps(agent string, t ToolPolicy) []string {
switch {
case t.IsZero() || agent == "pi":
return nil
case agent == "codex" || agent == "copilot":
_, _, gaps := namedTools(t, agent == "codex")
return gaps
}
var gaps []string
if len(t.Allow) > 0 {
gaps = append(gaps, "allow")
}
if len(t.Deny) > 0 {
gaps = append(gaps, "deny")
}
return gaps
}
func toolPolicyMessage(target string, gaps []string) string {
return "tool policy not applied for " + target + ": " + strings.Join(gaps, ", ")
}
// toolPolicyNotices names, per selected target, the servers whose tool policy that Agent
// cannot hold, so no part of a policy is dropped without saying so.
func (s *Source) toolPolicyNotices() []string {
found := map[string][]string{}
add := func(servers map[string]Server, defaults []string, root string) {
for name, server := range servers {
if root != "" {
name += " (" + root + ")"
}
for _, target := range server.Targets.orDefault(defaults) {
agent := target
if account, ok := s.Accounts[target]; ok {
agent = account.Agent
}
if gaps := toolPolicyGaps(agent, server.Tools); len(gaps) > 0 {
message := toolPolicyMessage(target, gaps)
found[message] = append(found[message], name)
}
}
}
}
add(s.Servers, s.Targets, "")
for root, project := range s.Projects {
add(project.Servers, project.defaults(s), root)
}
var notices []string
for _, message := range sortedKeys(found) {
slices.Sort(found[message])
notices = append(notices, message+" ("+strings.Join(found[message], ", ")+")")
}
return notices
}
// directToolsExposure is what pi-mcp-adapter's directTools becomes in Pi's built-in MCP:
// true declares every tool to the model, like Pi's direct; "search" holds them until a
// search loads them, like Pi's deferred; a list declares those tools directly and leaves
// the rest at Pi's default. false, the adapter's default, and an invalid value give nothing.
func directToolsExposure(value any) (exposure string, direct []string) {
switch v := value.(type) {
case bool:
if v {
return "direct", nil
}
case string:
if v == "search" {
return "deferred", nil
}
case []string:
return "", v
case []any:
for _, item := range v {
if tool, ok := item.(string); ok && tool != "" {
direct = append(direct, tool)
}
}
}
return "", direct
}
// adoptAdapterTools moves pi-mcp-adapter's tool settings into what Pi's built-in MCP reads.
// includeTools and excludeTools become tools.allow and tools.deny. directTools becomes
// piOptions.exposure, or for a list of names piOptions.toolExposure, which unlike
// tools.allow keeps the other tools. It returns each setting it dropped because the server
// already sets that part, or it does not convert.
func (s *Server) adoptAdapterTools(directTools any, include, exclude []any) (dropped []string) {
exposure, direct := directToolsExposure(directTools)
if include != nil || exclude != nil {
policy := ToolPolicy{Allow: toolNames(include), Deny: toolNames(exclude)}
if s.Disabled || !s.Tools.IsZero() || s.PiOptions["toolExposure"] != nil || len(policy.Allow) != len(include) || len(policy.Deny) != len(exclude) || policy.validate("") != nil {
for key, list := range map[string][]any{"excludeTools": exclude, "includeTools": include} {
if list != nil {
dropped = append(dropped, key)
}
}
slices.Sort(dropped)
} else {
s.Tools = policy
}
}
switch {
case exposure == "" && direct == nil:
if directTools != nil && directTools != false {
dropped = append(dropped, "directTools")
}
case s.Disabled || s.PiOptions["exposure"] != nil,
exposure == "" && (!s.Tools.IsZero() || s.PiOptions["toolExposure"] != nil):
dropped = append(dropped, "directTools")
default:
if s.PiOptions == nil {
s.PiOptions = PiOptions{}
}
if exposure != "" {
s.PiOptions["exposure"] = exposure
} else {
var tools piToolExposure
for _, tool := range direct {
tools = append(tools, piExposureEntry{tool, "direct"})
}
s.PiOptions["toolExposure"] = tools
}
}
return dropped
}
// toolNames keeps the strings of a decoded list.
func toolNames(list []any) []string {
var names []string
for _, item := range list {
if name, ok := item.(string); ok {
names = append(names, name)
}
}
return names
}
// piImportPolicy reads Pi's toolExposure back into a tool policy when writing that policy
// next to the entry's exposure gives Pi exactly the same toolExposure, and otherwise
// reports false.
func piImportPolicy(options PiOptions) (ToolPolicy, bool) {
var t ToolPolicy
data, _ := json.Marshal(options["toolExposure"])
entries, err := orderedExposure(data)
if err != nil {
return t, false
}
for _, e := range entries {
switch {
case e.Value == "hidden" && len(t.Allow) == 0 && e.Key != "*":
t.Deny = append(t.Deny, e.Key)
case e.Value != "hidden" && e.Key != "*":
t.Allow = append(t.Allow, e.Key)
}
}
if t.validate("") != nil {
return t, false
}
want := map[string]any{"exposure": options["exposure"]}
piToolPolicy(want, t)
a, _ := json.Marshal(want["toolExposure"])
b, _ := json.Marshal(options["toolExposure"])
return t, string(a) == string(b)
}
+227
View File
@@ -0,0 +1,227 @@
package mcp
import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
)
func renderJSON(t *testing.T, target string, server Server, keys ...string) string {
t.Helper()
entry, err := Render(target, server)
if err != nil {
t.Fatal(err)
}
picked := map[string]any{}
for _, key := range keys {
if value, ok := entry[key]; ok {
picked[key] = value
}
}
data, _ := json.Marshal(picked)
return string(data)
}
// Pi takes an exact name over any pattern and the first matching pattern, so denied tools
// come first and "*": "hidden" last; an allowed name a denied pattern matches is left out.
func TestPiToolPolicyOrder(t *testing.T) {
for name, tc := range map[string]struct {
tools ToolPolicy
exposure string
want string
}{
"allow and deny": {ToolPolicy{Allow: []string{"get_*", "delete_all", "search"}, Deny: []string{"delete_*"}}, "",
`{"toolExposure":{"delete_*":"hidden","get_*":"codemode","search":"codemode","*":"hidden"}}`},
"allowed tools take piOptions.exposure": {ToolPolicy{Allow: []string{"get_*"}}, "codemode-deferred",
`{"exposure":"codemode-deferred","toolExposure":{"get_*":"codemode-deferred","*":"hidden"}}`},
"hidden server, allowed tools at Pi's default": {ToolPolicy{Allow: []string{"get_*"}}, "hidden",
`{"exposure":"hidden","toolExposure":{"get_*":"codemode","*":"hidden"}}`},
"deny only": {ToolPolicy{Deny: []string{"delete_*"}}, "", `{"toolExposure":{"delete_*":"hidden"}}`},
"no policy": {ToolPolicy{}, "", `{}`},
} {
server := Server{Command: "x", Tools: tc.tools}
if tc.exposure != "" {
server.PiOptions = PiOptions{"exposure": tc.exposure}
}
if got := renderJSON(t, "pi", server, "exposure", "toolExposure"); got != tc.want {
t.Errorf("%s: got %s want %s", name, got, tc.want)
}
}
}
func TestCopilotToolPolicy(t *testing.T) {
for name, tc := range map[string]struct {
tools ToolPolicy
want string
}{
"allowed names": {ToolPolicy{Allow: []string{"get_issue", "delete_issue"}, Deny: []string{"delete_*"}}, `{"tools":["get_issue"]}`},
"no allow": {ToolPolicy{Deny: []string{"delete_*"}}, `{"tools":["*"]}`},
"patterns are not applied": {ToolPolicy{Allow: []string{"get_*"}}, `{"tools":["*"]}`},
} {
if got := renderJSON(t, "copilot", Server{Command: "x", Tools: tc.tools}, "tools"); got != tc.want {
t.Errorf("%s: got %s want %s", name, got, tc.want)
}
}
}
func TestCodexToolPolicy(t *testing.T) {
for name, tc := range map[string]struct {
tools ToolPolicy
want string
}{
"names": {ToolPolicy{Allow: []string{"open", "screenshot"}, Deny: []string{"screenshot"}}, `{"disabled_tools":["screenshot"],"enabled_tools":["open","screenshot"]}`},
"denied patterns leave the allowed": {ToolPolicy{Allow: []string{"open", "delete_all"}, Deny: []string{"delete_*"}}, `{"enabled_tools":["open"]}`},
"allowed patterns are not applied": {ToolPolicy{Allow: []string{"get_*"}, Deny: []string{"delete_all"}}, `{"disabled_tools":["delete_all"]}`},
} {
if got := renderJSON(t, "codex", Server{Command: "x", Tools: tc.tools}, "enabled_tools", "disabled_tools"); got != tc.want {
t.Errorf("%s: got %s want %s", name, got, tc.want)
}
}
}
// Codex's tool lists are managed fields, so clearing the policy removes them on the next sync.
func TestCodexToolPolicyRemovedWithThePolicy(t *testing.T) {
s := testService(t)
sync := func(tools string) string {
t.Helper()
config := "mcp:\n targets: [codex]\n servers:\n docs:\n command: docs\n" + tools
if err := os.WriteFile(s.ConfigPath, []byte(config), 0600); err != nil {
t.Fatal(err)
}
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if _, err := s.Apply(plan.Revision); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(s.Home, ".codex", "config.toml"))
return string(data)
}
if got := sync(" tools:\n allow: [open]\n"); !strings.Contains(got, "enabled_tools") {
t.Fatalf("not written: %s", got)
}
if got := sync(""); strings.Contains(got, "enabled_tools") {
t.Fatalf("not removed: %s", got)
}
}
// A part of a policy an Agent cannot hold is named in the plan and by check, never dropped silently.
func TestToolPolicyNotAppliedIsReported(t *testing.T) {
s, _ := projectsService(t, `mcp:
targets: [pi, cursor, copilot, codex]
servers:
github:
url: https://example.com/mcp
tools:
allow: ["get_*"]
deny: [delete_repo]
plain:
url: https://example.com/plain
`)
plan, err := s.Preview()
if err != nil {
t.Fatal(err)
}
want := []string{
"tool policy not applied for codex: allow patterns (github)",
"tool policy not applied for copilot: allow patterns, deny (github)",
"tool policy not applied for cursor: allow, deny (github)",
}
if !reflect.DeepEqual(plan.Notices, want) {
t.Fatalf("notices:\n%q", plan.Notices)
}
report, err := s.Check(CheckOptions{SkipDNS: true, Names: []string{"github"}})
if err != nil {
t.Fatal(err)
}
var found []string
for _, f := range report.Servers[0].Findings {
if f.Check == "tools" {
found = append(found, f.Message+" ("+report.Servers[0].Name+")")
}
}
slices.Sort(found)
if !reflect.DeepEqual(found, want) {
t.Fatalf("check findings: %q", found)
}
}
func TestToolPolicyRejected(t *testing.T) {
for name, tc := range map[string]struct {
server Server
want string
}{
"another wildcard": {Server{Command: "x", Tools: ToolPolicy{Allow: []string{"get_?"}}}, "not a tool name"},
"listed twice": {Server{Command: "x", Tools: ToolPolicy{Deny: []string{"a", "a"}}}, "twice"},
"every tool denied": {Server{Command: "x", Tools: ToolPolicy{Allow: []string{"delete_a"}, Deny: []string{"delete_*"}}}, "removes every tool"},
"switch-only entry": {Server{Disabled: true, Tools: ToolPolicy{Deny: []string{"a"}}}, "disabled"},
"Pi exposure elsewhere": {Server{Command: "x", Tools: ToolPolicy{Deny: []string{"a"}}, PiOptions: PiOptions{"toolExposure": map[string]any{"b": "hidden"}}}, "keep it in tools"},
"adapter tool list": {Server{Command: "x", PiOptions: PiOptions{"excludeTools": []any{"a"}}}, "use tools.deny"},
} {
if err := tc.server.Validate("docs"); err == nil || !strings.Contains(err.Error(), tc.want) {
t.Errorf("%s: want %q, got %v", name, tc.want, err)
}
}
}
// Pi's exposure mode lives in piOptions and sits next to a tool policy.
func TestToolPolicyKeepsPiExposure(t *testing.T) {
server := Server{Command: "x", Tools: ToolPolicy{Deny: []string{"a"}}, PiOptions: PiOptions{"exposure": "direct"}}
if err := server.Validate("docs"); err != nil {
t.Fatal(err)
}
}
// What import reads back into tools renders to the same native fields.
func TestToolPolicyImportRoundTrip(t *testing.T) {
for target, tools := range map[string]ToolPolicy{
"pi": {Allow: []string{"get_*", "search"}, Deny: []string{"delete_*"}},
"copilot": {Allow: []string{"get_issue", "list_issues"}},
"codex": {Allow: []string{"open", "screenshot"}, Deny: []string{"screenshot"}},
} {
s := testService(t)
if err := os.WriteFile(s.ConfigPath, []byte("mcp:\n servers: {}\n"), 0600); err != nil {
t.Fatal(err)
}
rendered := s.RenderNative("docs", Server{Command: "docs", Targets: TargetList{target}, Tools: tools})
if rendered[0].Error != "" {
t.Fatalf("%s: %s", target, rendered[0].Error)
}
candidates, err := Import(target, []byte(rendered[0].Content), "")
if err != nil || len(candidates) != 1 {
t.Fatalf("%s: %+v %v", target, candidates, err)
}
if got := candidates[0].Server; !reflect.DeepEqual(got.Tools, tools) || got.PiOptions != nil {
t.Errorf("%s: got %+v %v, warnings %v", target, got.Tools, got.PiOptions, candidates[0].Warnings)
}
}
}
func TestRenderNativeNamesTheToolPolicyPartsEachAgentCannotHold(t *testing.T) {
service := testService(t)
got := map[string][]string{}
for _, r := range service.RenderNative("docs", Server{Command: "docs", Targets: TargetList{"pi", "copilot", "opencode"}, Tools: ToolPolicy{Allow: []string{"get_*"}, Deny: []string{"delete_issue"}}}) {
got[r.Target] = r.ToolGaps
}
want := map[string][]string{"pi": nil, "copilot": {"allow patterns", "deny"}, "opencode": {"allow", "deny"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
// Pi exposure a policy cannot express exactly stays in piOptions, for Pi only.
func TestPiExposureKeptWhenNotExpressible(t *testing.T) {
candidates, err := Import("pi", []byte(`{"mcpServers":{"docs":{"command":"docs","exposure":"codemode-deferred","toolExposure":{"a":"direct"}}}}`), "")
if err != nil || len(candidates) != 1 {
t.Fatalf("%+v %v", candidates, err)
}
c := candidates[0]
if !c.Server.Tools.IsZero() || c.Server.PiOptions["exposure"] != "codemode-deferred" || c.Server.PiOptions["toolExposure"] == nil || !strings.Contains(strings.Join(c.Warnings, ";"), "stays in piOptions") {
t.Fatalf("%+v %v", c.Server, c.Warnings)
}
}
+33 -2
View File
@@ -18,6 +18,29 @@ type Result struct {
Plan *Plan `json:"plan"`
Applied []string `json:"applied"`
BackupIDs []string `json:"backupIds"`
// Migrated are the config files the sync also saved without the settings 0.23.0
// retired, which the plan's notices named.
Migrated []MigratedFile `json:"migrated,omitempty"`
}
// migrate saves the plan's source without the settings 0.23.0 retired once its files are
// applied, so their notices go away. The Agent files are already written by then, so a
// failure says so rather than undoing them.
func (s *Service) migrate(result *Result) error {
source := result.Plan.source
if !source.NeedsMigration() {
return nil
}
legacy := len(source.Notices)
saved, err := source.saveMigration(s.BackupSource)
result.Migrated = saved
if err != nil {
return fmt.Errorf("MCP files applied, but saving %s without the settings 0.23.0 retired failed: %w", source.ConfigPath, err)
}
result.Plan.Migrates = false
// The plan's own notices start with the source's; those no longer apply.
result.Plan.Notices = result.Plan.Notices[legacy:]
return nil
}
type journal struct {
@@ -125,7 +148,11 @@ func (s *Service) Apply(revision string) (*Result, error) {
if revision != "" && revision != p.Revision {
return nil, fmt.Errorf("MCP configuration changed since preview; preview again")
}
return s.applyPlan(p)
result, err := s.applyPlan(p)
if err != nil {
return result, err
}
return result, s.migrate(result)
}
// ErrUnknownProject is returned for a root that mcp.projects does not declare.
@@ -157,7 +184,11 @@ func (s *Service) ApplyProject(revision, root string) (*Result, error) {
if revision != p.Revision {
return nil, fmt.Errorf("MCP configuration changed since preview; preview again")
}
return s.applyScoped(p, &root)
result, err := s.applyScoped(p, &root)
if err != nil {
return result, err
}
return result, s.migrate(result)
}
func (s *Service) applyPlan(p *Plan) (*Result, error) { return s.applyScoped(p, nil) }
+7
View File
@@ -10,6 +10,7 @@ import (
"gopkg.in/yaml.v3"
"skillshare/internal/config"
"skillshare/internal/hooks"
"skillshare/internal/plugin"
)
@@ -124,6 +125,9 @@ func (s *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
if validErr == nil {
validErr = config.ValidateMCP(testCfg.MCP, testCfg.Sources.MCP)
}
if validErr == nil {
validErr = hooks.ValidateSection(&testCfg.Hooks, true)
}
if validErr != nil {
writeError(w, http.StatusBadRequest, validErr.Error())
return
@@ -144,6 +148,9 @@ func (s *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
if validErr == nil {
validErr = config.ValidateMCP(testCfg.MCP, testCfg.Sources.MCP, testCfg.AgentConfigDirTargets()...)
}
if validErr == nil {
validErr = hooks.ValidateSection(&testCfg.Hooks, false)
}
if validErr != nil {
writeError(w, http.StatusBadRequest, validErr.Error())
return
+24
View File
@@ -190,3 +190,27 @@ func TestHandlePatchConfig_SavesModeAndLogLimit(t *testing.T) {
t.Fatalf("expected the saved log limit to be 500, got %v", cfg.Log.MaxEntries)
}
}
func TestHandlePutConfig_InvalidHooks_400(t *testing.T) {
s, sourceDir := newTestServer(t)
body := `{"raw":"source: ` + sourceDir + `\nmode: merge\ntargets: {}\nhooks:\n entries:\n guard:\n bindings:\n nosuchagent:\n events: {}\n"}`
req := httptest.NewRequest(http.MethodPut, "/api/config", strings.NewReader(body))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d: %s", rr.Code, rr.Body.String())
}
}
func TestHandlePutConfig_ProjectHooksProjects_400(t *testing.T) {
s, _ := newTestProjectServerWithExtras(t, nil)
body := `{"raw":"targets: [claude]\nhooks:\n projects:\n /work/app:\n entries: {}\n"}`
req := httptest.NewRequest(http.MethodPut, "/api/config", strings.NewReader(body))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusBadRequest || !strings.Contains(rr.Body.String(), "hooks.projects") {
t.Errorf("expected 400 naming hooks.projects, got %d: %s", rr.Code, rr.Body.String())
}
}
+245
View File
@@ -0,0 +1,245 @@
package server
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/hooks"
)
func (s *Server) hooksService() *hooks.Service {
return &hooks.Service{ConfigPath: s.configPath(), ProjectRoot: s.projectRoot, StateDir: config.StateDir(), ConfigDirs: hooks.ConfigDirsFromEnv()}
}
// requireLocalHooks applies the MCP DNS-rebinding guard: hooks write commands that Agents run.
func (s *Server) requireLocalHooks(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !mcpRequestAllowed(r, s.addr) {
writeError(w, http.StatusForbidden, "Hooks settings are available only when the dashboard is opened by localhost or an IP address, not a domain name")
return
}
next(w, r)
}
}
type hooksRequest struct {
Mutation hooks.Mutation `json:"mutation"`
Revision string `json:"revision"`
Sync bool `json:"sync"`
// Root, with sync and no mutation, applies only that hooks.projects root's changes.
Root string `json:"root"`
}
type hooksRestoreRequest struct {
BackupID string `json:"backupId"`
Preview bool `json:"preview"`
Revision string `json:"revision"`
}
func decodeHooksRequest(w http.ResponseWriter, r *http.Request, value any) bool {
var extra bool
err := decodeJSONWith(w, r, defaultJSONBodyLimit, func(d *json.Decoder) error {
d.DisallowUnknownFields()
if err := d.Decode(value); err != nil {
return err
}
extra = d.Decode(new(any)) != io.EOF
return nil
})
switch {
case errors.Is(err, errBodyTooLarge):
return false
case err != nil:
writeError(w, http.StatusBadRequest, "invalid hooks request")
return false
case extra:
writeError(w, http.StatusBadRequest, "expected one hooks request")
return false
}
return true
}
func (s *Server) handleHooksList(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
defer s.mu.RUnlock()
inventory, err := s.hooksService().List()
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, inventory)
}
// handleHooksCatalog lists each command Agent's documented events and timeout unit.
func (s *Server) handleHooksCatalog(w http.ResponseWriter, r *http.Request) {
writeJSON(w, hooks.Catalog)
}
func (s *Server) handleHooksPreview(w http.ResponseWriter, r *http.Request) {
var body hooksRequest
if !decodeHooksRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
p, err := s.hooksService().PreviewMutation(body.Mutation)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
// Only the preview carries full file texts, for the dashboard's diff.
writeJSON(w, struct {
*hooks.Plan
Files []hooks.FileDiff `json:"files"`
}{p, p.Files()})
}
// handleHooksRender shows one hook's native files without planning, saving or writing.
func (s *Server) handleHooksRender(w http.ResponseWriter, r *http.Request) {
var body struct {
Mutation hooks.Mutation `json:"mutation"`
}
if !decodeHooksRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
files, err := s.hooksService().RenderNative(body.Mutation)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, map[string]any{"rendered": files})
}
func (s *Server) handleHooksConfigure(w http.ResponseWriter, r *http.Request) {
var body hooksRequest
if !decodeHooksRequest(w, r, &body) {
return
}
if body.Revision == "" {
writeError(w, http.StatusBadRequest, "preview the hooks changes before saving")
return
}
if body.Root != "" && (!body.Sync || !reflect.DeepEqual(body.Mutation, hooks.Mutation{})) {
writeError(w, http.StatusBadRequest, "a project sync takes no changes")
return
}
if body.Root != "" && s.IsProjectMode() {
writeError(w, http.StatusBadRequest, "hooks.projects roots are available only in global mode; omit root")
return
}
s.mu.Lock()
defer s.mu.Unlock()
start := time.Now()
var result *hooks.Result
var err error
args := map[string]any{"scope": "ui", "sync": body.Sync}
if body.Root != "" {
args["project"] = body.Root
result, err = s.hooksService().ApplyProject(body.Revision, body.Root)
} else {
result, err = s.hooksService().Mutate(body.Mutation, body.Revision, body.Sync)
}
if body.Mutation.Name != "" {
args["name"] = body.Mutation.Name
}
s.writeOpsLog("hooks configure", opStatus(err), start, args, "")
if errors.Is(err, hooks.ErrUnknownProject) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err != nil {
writeHooksFailure(w, result, err)
return
}
if err := s.reloadConfig(); err != nil {
writeError(w, http.StatusInternalServerError, "hooks saved, but config reload failed")
return
}
writeJSON(w, result)
}
func (s *Server) handleHooksImport(w http.ResponseWriter, r *http.Request) {
var body hooks.ImportRequest
if !decodeHooksRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
candidates, err := s.hooksService().Import(body)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if candidates == nil {
candidates = []hooks.Candidate{}
}
writeJSON(w, map[string]any{"candidates": candidates})
}
func (s *Server) handleHooksRestore(w http.ResponseWriter, r *http.Request) {
var body hooksRestoreRequest
if !decodeHooksRequest(w, r, &body) {
return
}
if body.BackupID == "" {
writeError(w, http.StatusBadRequest, "backupId is required")
return
}
s.mu.Lock()
defer s.mu.Unlock()
service := s.hooksService()
if body.Preview {
p, err := service.PreviewRestore(body.BackupID)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, p)
return
}
if body.Revision == "" {
writeError(w, http.StatusBadRequest, "preview before restoring")
return
}
start := time.Now()
result, err := service.Restore(body.BackupID, body.Revision)
s.writeOpsLog("hooks restore", opStatus(err), start, map[string]any{"scope": "ui", "backup": body.BackupID}, "")
if err != nil {
writeHooksFailure(w, result, err)
return
}
writeJSON(w, result)
}
func opStatus(err error) string {
if err != nil {
return "error"
}
return "ok"
}
// writeHooksFailure reports stale previews, conflicts and partial writes as 409 with the
// result, so the dashboard can show what was already applied; other errors are 400.
func writeHooksFailure(w http.ResponseWriter, result *hooks.Result, err error) {
partial := result != nil && len(result.Applied) > 0
if !partial && !errors.Is(err, hooks.ErrStaleRevision) && !errors.Is(err, hooks.ErrConflict) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
message := err.Error()
if partial {
message += fmt.Sprintf("; already applied: %s; backup IDs: %s", strings.Join(result.Applied, ", "), strings.Join(result.BackupIDs, ", "))
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(map[string]any{"error": message, "result": result})
}
@@ -0,0 +1,349 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
// These tests replay the requests the dashboard sends (ui/src/api/hooks.ts and its callers)
// against the real handlers: the same endpoints, the same mutation JSON, and the revision
// taken from the preview the dialog used. UI tests mock one fixed revision, so a mismatch
// between what the dashboard previews and what it saves only shows up here.
type hooksUIView struct {
Source struct {
Entries map[string]json.RawMessage `json:"entries"`
Projects map[string]struct {
Entries map[string]json.RawMessage `json:"entries"`
} `json:"projects"`
} `json:"source"`
Plan *struct {
Blocked bool `json:"blocked"`
Changes []struct {
Name string `json:"name"`
Root string `json:"root"`
Action string `json:"action"`
} `json:"changes"`
} `json:"plan"`
Backups []struct {
ID string `json:"id"`
Path string `json:"path"`
} `json:"backups"`
Unmanaged []struct {
Path string `json:"path"`
Names []string `json:"names"`
} `json:"unmanaged"`
}
func hooksUIList(t *testing.T, s *Server) hooksUIView {
t.Helper()
w := httptest.NewRecorder()
s.handleHooksList(w, httptest.NewRequest(http.MethodGet, "/api/hooks", nil))
var view hooksUIView
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &view) != nil {
t.Fatalf("list: %d %s", w.Code, w.Body)
}
return view
}
// hooksUIConfigure is hooksApi.configure.
func hooksUIConfigure(s *Server, mutation, revision string, sync bool) *httptest.ResponseRecorder {
body, _ := json.Marshal(map[string]any{"mutation": json.RawMessage(mutation), "revision": revision, "sync": sync})
return hooksPost(s, s.handleHooksConfigure, "/api/hooks", string(body))
}
// hooksUISync is HooksSyncDialog without a project, and the Sync page: preview nothing, apply that plan.
func hooksUISync(t *testing.T, s *Server) {
t.Helper()
if w := hooksUIConfigure(s, `{}`, hooksPreviewRevision(t, s, `{}`), true); w.Code != http.StatusOK {
t.Fatalf("sync: %d %s", w.Code, w.Body)
}
}
func hooksEntryJSON(command string) string {
return `{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"` + command + `"}]}]}}}}`
}
// hooksUIScope is one place the dashboard manages hooks from: the global page, a
// hooks.projects root's tab, or a server started in project mode.
type hooksUIScope struct {
name string
s *Server
project string // mutation.project, empty outside a hooks.projects root
settings string
}
var hooksUIScopes = []func(t *testing.T) hooksUIScope{
func(t *testing.T) hooksUIScope {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
return hooksUIScope{"global", s, "", filepath.Join(home, ".claude", "settings.json")}
},
func(t *testing.T) hooksUIScope {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
root := t.TempDir()
return hooksUIScope{"hooks.projects root", s, root, filepath.Join(root, ".claude", "settings.json")}
},
func(t *testing.T) hooksUIScope {
s, root := newTestProjectServerWithExtras(t, nil)
hooksTestHome(t)
return hooksUIScope{"project mode", s, "", filepath.Join(root, ".claude", "settings.json")}
},
}
var hooksUIScopeNames = []string{"global", "hooks.projects root", "project mode"}
// mutation adds the scope's project field the way the dialogs spread `...(project && { project })`.
func (sc hooksUIScope) mutation(fields string) string {
if sc.project == "" {
return `{` + fields + `}`
}
return `{"project":"` + sc.project + `",` + fields + `}`
}
// addAndSync is HookDialog with "Save and sync": preview the mutation, configure with that revision.
func (sc hooksUIScope) addAndSync(t *testing.T, name, command string) {
t.Helper()
mutation := sc.mutation(`"name":"` + name + `","entry":` + hooksEntryJSON(command))
if w := hooksUIConfigure(sc.s, mutation, hooksPreviewRevision(t, sc.s, mutation), true); w.Code != http.StatusOK {
t.Fatalf("%s: add and sync: %d %s", sc.name, w.Code, w.Body)
}
if !strings.Contains(readOrEmpty(sc.settings), command) {
t.Fatalf("%s: not written:\n%s", sc.name, readOrEmpty(sc.settings))
}
}
func (sc hooksUIScope) entries(t *testing.T) map[string]json.RawMessage {
view := hooksUIList(t, sc.s)
if sc.project != "" {
return view.Source.Projects[sc.project].Entries
}
return view.Source.Entries
}
// HooksRemoveDialog: all three choices, in every scope.
func TestHooksUIContract_RemoveDialog(t *testing.T) {
for i, newScope := range hooksUIScopes {
for _, choice := range []string{"sync", "source only", "stop managing"} {
t.Run(hooksUIScopeNames[i]+"/"+choice, func(t *testing.T) {
sc := newScope(t)
sc.addAndSync(t, "guard", "echo contract-guard")
removal := sc.mutation(`"name":"guard","remove":true`)
planRevision := hooksPreviewRevision(t, sc.s, removal)
var w *httptest.ResponseRecorder
switch choice {
case "sync":
w = hooksUIConfigure(sc.s, removal, planRevision, true)
case "source only":
w = hooksUIConfigure(sc.s, removal, planRevision, false)
case "stop managing":
unmanage := sc.mutation(`"name":"guard","remove":true,"unmanage":true`)
w = hooksUIConfigure(sc.s, unmanage, hooksPreviewRevision(t, sc.s, unmanage), false)
}
if w.Code != http.StatusOK {
t.Fatalf("%d %s", w.Code, w.Body)
}
if _, ok := sc.entries(t)["guard"]; ok {
t.Fatal("still in the source")
}
written := strings.Contains(readOrEmpty(sc.settings), "echo contract-guard")
view := hooksUIList(t, sc.s)
pending := view.Plan != nil && len(view.Plan.Changes) > 0
switch choice {
case "sync":
if written || pending {
t.Fatalf("written=%v pending=%v", written, pending)
}
case "source only":
if !written || !pending || view.Plan.Changes[0].Action != "remove" {
t.Fatalf("written=%v plan=%+v", written, view.Plan)
}
case "stop managing":
if !written || pending || len(view.Unmanaged) != 1 || view.Unmanaged[0].Path != sc.settings {
t.Fatalf("written=%v plan=%+v unmanaged=%+v", written, view.Plan, view.Unmanaged)
}
}
})
}
}
}
// Stop managing plans no file change, so its revision differs from the removal preview's.
// A dashboard that reuses the removal preview's revision is refused as stale (fixed in the UI
// by previewing the unmanage mutation itself); this pins the server side of that contract.
func TestHooksUIContract_StopManagingRejectsTheRemovalPreviewRevision(t *testing.T) {
sc := hooksUIScopes[0](t)
sc.addAndSync(t, "guard", "echo contract-guard")
removalRevision := hooksPreviewRevision(t, sc.s, `{"name":"guard","remove":true}`)
w := hooksUIConfigure(sc.s, `{"name":"guard","remove":true,"unmanage":true}`, removalRevision, false)
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "changed since preview") {
t.Fatalf("%d %s", w.Code, w.Body)
}
if _, ok := sc.entries(t)["guard"]; !ok {
t.Fatal("a refused save changed the source")
}
}
// HookDialog edit: same name, new entry, no replace flag; then save-only edits and HooksScope's
// enable switch, which saves the entry with enabled:false.
func TestHooksUIContract_EditAndToggle(t *testing.T) {
for i, newScope := range hooksUIScopes {
t.Run(hooksUIScopeNames[i], func(t *testing.T) {
sc := newScope(t)
sc.addAndSync(t, "guard", "echo contract-v1")
sc.addAndSync(t, "guard", "echo contract-v2")
if got := readOrEmpty(sc.settings); strings.Contains(got, "contract-v1") {
t.Fatalf("edit kept the old command:\n%s", got)
}
hooksSave(t, sc.s, sc.mutation(`"name":"guard","entry":`+strings.Replace(hooksEntryJSON("echo contract-v2"), `{"bindings"`, `{"enabled":false,"bindings"`, 1)))
hooksUISync(t, sc.s)
if strings.Contains(readOrEmpty(sc.settings), "contract-v2") {
t.Fatal("a disabled hook stayed in the target file")
}
hooksSave(t, sc.s, sc.mutation(`"name":"guard","entry":`+hooksEntryJSON("echo contract-v2")))
hooksUISync(t, sc.s)
if !strings.Contains(readOrEmpty(sc.settings), "contract-v2") {
t.Fatal("enabling did not write the hook back")
}
})
}
}
// HooksSyncDialog with a takeover (and HookDialog with its takeover box): the source entry
// with replace:true, previewed and applied with sync, overwrites an outside edit.
func TestHooksUIContract_TakeOverOutsideEdit(t *testing.T) {
for i, newScope := range hooksUIScopes {
t.Run(hooksUIScopeNames[i], func(t *testing.T) {
sc := newScope(t)
sc.addAndSync(t, "guard", "echo contract-guard")
edited := strings.Replace(readOrEmpty(sc.settings), "echo contract-guard", "echo edited-outside", 1)
if err := os.WriteFile(sc.settings, []byte(edited), 0644); err != nil {
t.Fatal(err)
}
if view := hooksUIList(t, sc.s); view.Plan == nil || !view.Plan.Blocked {
t.Fatalf("outside edit is not a conflict: %+v", view.Plan)
}
takeover := sc.mutation(`"name":"guard","entry":` + string(sc.entries(t)["guard"]) + `,"replace":true`)
if w := hooksUIConfigure(sc.s, takeover, hooksPreviewRevision(t, sc.s, takeover), true); w.Code != http.StatusOK {
t.Fatalf("takeover: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(sc.settings); strings.Contains(got, "edited-outside") || !strings.Contains(got, "contract-guard") {
t.Fatalf("takeover did not restore the source hook:\n%s", got)
}
if view := hooksUIList(t, sc.s); view.Plan == nil || view.Plan.Blocked {
t.Fatalf("still blocked after takeover: %+v", view.Plan)
}
})
}
}
// HooksImportDialog in a hooks.projects root: import with root, save with adopt, then the
// project's sync adopts the registration in place.
func TestHooksUIContract_ProjectImportAdopt(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
root := t.TempDir()
hooksSave(t, s, `{"project":"`+root+`"}`) // AddProjectDialog
settings := filepath.Join(root, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
t.Fatal(err)
}
native := `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo project-native"}]}]}}`
if err := os.WriteFile(settings, []byte(native), 0644); err != nil {
t.Fatal(err)
}
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","root":"`+root+`"}`)
var imported struct {
Candidates []struct {
Name string `json:"name"`
Entry json.RawMessage `json:"entry"`
} `json:"candidates"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &imported) != nil || len(imported.Candidates) != 1 {
t.Fatalf("import: %d %s", w.Code, w.Body)
}
hooksSave(t, s, `{"project":"`+root+`","name":"stop","entry":`+string(imported.Candidates[0].Entry)+`,"adopt":true}`)
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+hooksPreviewRevision(t, s, `{}`)+`","sync":true,"root":"`+root+`"}`); w.Code != http.StatusOK {
t.Fatalf("project sync: %d %s", w.Code, w.Body)
}
view := hooksUIList(t, s)
if len(view.Unmanaged) != 0 || view.Plan == nil || view.Plan.Blocked || view.Plan.Changes[0].Action != "unchanged" {
t.Fatalf("adopted hook is not managed: unmanaged=%+v plan=%+v", view.Unmanaged, view.Plan)
}
if readOrEmpty(settings) != native {
t.Fatalf("adopting rewrote the file:\n%s", readOrEmpty(settings))
}
hooksSave(t, s, `{"project":"`+root+`","remove":true}`) // ProjectDetailPage removing the project
if _, ok := hooksUIList(t, s).Source.Projects[root]; ok {
t.Fatal("project still configured")
}
}
// The global sync writes the whole plan, hooks.projects roots included.
func TestHooksUIContract_GlobalSyncWritesEveryScope(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
root := t.TempDir()
hooksSave(t, s, hooksTestMutation)
hooksSave(t, s, hooksProjectEntry(root, "a", "echo hook-a"))
hooksUISync(t, s)
if !strings.Contains(readOrEmpty(filepath.Join(home, ".claude", "settings.json")), "skillshare-hooks-test") || !strings.Contains(readOrEmpty(filepath.Join(root, ".claude", "settings.json")), "echo hook-a") {
t.Fatal("global sync skipped a scope")
}
}
// HooksRestoreDialog: preview the backup, restore with that revision. A shared settings file
// gets back only what that write changed; the rest of the file stays.
func TestHooksUIContract_RestoreBackup(t *testing.T) {
sc := hooksUIScopes[0](t)
if err := os.MkdirAll(filepath.Dir(sc.settings), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(sc.settings, []byte(`{"model":"opus"}`), 0644); err != nil {
t.Fatal(err)
}
sc.addAndSync(t, "guard", "echo contract-guard")
backups := hooksUIList(t, sc.s).Backups
if len(backups) != 1 {
t.Fatalf("backups: %+v", backups)
}
preview := hooksPost(sc.s, sc.s.handleHooksRestore, "/api/hooks/restore", `{"backupId":"`+backups[0].ID+`","preview":true}`)
var p struct {
Revision string `json:"revision"`
}
if preview.Code != http.StatusOK || json.Unmarshal(preview.Body.Bytes(), &p) != nil || p.Revision == "" {
t.Fatalf("restore preview: %d %s", preview.Code, preview.Body)
}
if w := hooksPost(sc.s, sc.s.handleHooksRestore, "/api/hooks/restore", `{"backupId":"`+backups[0].ID+`","revision":"`+p.Revision+`"}`); w.Code != http.StatusOK {
t.Fatalf("restore: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(sc.settings); strings.Contains(got, "contract-guard") || !strings.Contains(got, `"model":"opus"`) {
t.Fatalf("restored file:\n%s", got)
}
}
// HookDialog with its takeover box ticked but saved without sync: replace is not kept in the
// source, so the conflict stays for the next takeover preview to resolve.
func TestHooksUIContract_TakeOverSaveOnlyKeepsTheConflict(t *testing.T) {
sc := hooksUIScopes[0](t)
sc.addAndSync(t, "guard", "echo contract-guard")
edited := strings.Replace(readOrEmpty(sc.settings), "echo contract-guard", "echo edited-outside", 1)
if err := os.WriteFile(sc.settings, []byte(edited), 0644); err != nil {
t.Fatal(err)
}
hooksSave(t, sc.s, `{"name":"guard","entry":`+hooksEntryJSON("echo contract-v2")+`,"replace":true}`)
if view := hooksUIList(t, sc.s); view.Plan == nil || !view.Plan.Blocked {
t.Fatalf("save-only takeover resolved the conflict: %+v", view.Plan)
}
if readOrEmpty(sc.settings) != edited {
t.Fatal("save-only takeover wrote the target file")
}
}
+420
View File
@@ -0,0 +1,420 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/oplog"
)
const hooksTestMutation = `{"name":"bash-log","entry":{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo skillshare-hooks-test"}]}]}}}}}`
func hooksTestHome(t *testing.T) string {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("CLAUDE_CONFIG_DIR", "")
return home
}
func hooksPost(s *Server, handler http.HandlerFunc, path, body string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
handler(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)))
return w
}
// hooksPreviewRevision previews the mutation and returns its revision.
func hooksPreviewRevision(t *testing.T, s *Server, mutation string) string {
t.Helper()
w := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":`+mutation+`}`)
var p struct {
Revision string `json:"revision"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || p.Revision == "" {
t.Fatalf("preview: %d %s", w.Code, w.Body)
}
return p.Revision
}
func TestHooksAPIPreviewThenApply(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
settings := filepath.Join(home, ".claude", "settings.json")
revision := hooksPreviewRevision(t, s, hooksTestMutation)
if _, err := os.Stat(settings); !os.IsNotExist(err) {
t.Fatal("preview wrote native configuration")
}
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+revision+`","sync":true}`)
if w.Code != http.StatusOK {
t.Fatalf("apply: %d %s", w.Code, w.Body)
}
data, err := os.ReadFile(settings)
if err != nil || !strings.Contains(string(data), "skillshare-hooks-test") {
t.Fatalf("apply did not write Claude settings: %v %s", err, data)
}
list := httptest.NewRecorder()
s.handleHooksList(list, httptest.NewRequest(http.MethodGet, "/api/hooks", nil))
var view struct {
Source struct {
Entries map[string]json.RawMessage `json:"entries"`
} `json:"source"`
}
if list.Code != http.StatusOK || json.Unmarshal(list.Body.Bytes(), &view) != nil || view.Source.Entries["bash-log"] == nil {
t.Fatalf("list: %d %s", list.Code, list.Body)
}
}
func TestHooksAPIProjectModeWritesProjectFiles(t *testing.T) {
s, root := newTestProjectServerWithExtras(t, nil)
home := hooksTestHome(t)
revision := hooksPreviewRevision(t, s, hooksTestMutation)
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+revision+`","sync":true}`)
if w.Code != http.StatusOK {
t.Fatalf("apply: %d %s", w.Code, w.Body)
}
if data, err := os.ReadFile(filepath.Join(root, ".claude", "settings.json")); err != nil || !strings.Contains(string(data), "skillshare-hooks-test") {
t.Fatalf("project apply did not write project settings: %v", err)
}
if _, err := os.Stat(filepath.Join(home, ".claude", "settings.json")); !os.IsNotExist(err) {
t.Fatal("project apply wrote global settings")
}
}
func TestHooksAPIRejectsUnpreviewedOrStaleSaves(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
missing := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"sync":true}`)
if missing.Code != http.StatusBadRequest {
t.Fatalf("save without revision: %d %s", missing.Code, missing.Body)
}
stale := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"stale","sync":true}`)
if stale.Code != http.StatusConflict {
t.Fatalf("stale revision: %d %s", stale.Code, stale.Body)
}
}
func TestHooksAPIRejectsMalformedRequests(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
for _, tc := range []struct {
name string
handler http.HandlerFunc
body string
}{
{"unknown field", s.handleHooksPreview, `{"mutation":{},"extra":true}`},
{"two documents", s.handleHooksPreview, `{"mutation":{}}{"mutation":{}}`},
{"import unknown field", s.handleHooksImport, `{"from":"claude","piExtension":"builtin"}`},
{"restore without backup", s.handleHooksRestore, `{"preview":true}`},
{"restore without preview", s.handleHooksRestore, `{"backupId":"x"}`},
} {
if w := hooksPost(s, tc.handler, "/", tc.body); w.Code != http.StatusBadRequest {
t.Errorf("%s: %d %s", tc.name, w.Code, w.Body)
}
}
large := hooksPost(s, s.handleHooksPreview, "/", `{"mutation":{"name":"`+strings.Repeat("x", int(defaultJSONBodyLimit))+`"}}`)
if large.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized body: %d", large.Code)
}
}
func TestHooksAPIImportListsCandidatesWithoutExecuting(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
marker := filepath.Join(t.TempDir(), "executed")
settings := filepath.Join(home, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
t.Fatal(err)
}
native := `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"touch ` + marker + `"}]}]}}`
if err := os.WriteFile(settings, []byte(native), 0644); err != nil {
t.Fatal(err)
}
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude"}`)
var result struct {
Candidates []struct {
Name string `json:"name"`
} `json:"candidates"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Candidates) == 0 {
t.Fatalf("import: %d %s", w.Code, w.Body)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatal("import executed a hook command")
}
}
func TestHooksRoutesRejectRebindingHost(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
s.addr = "127.0.0.1:19420"
for _, route := range []string{"GET /api/hooks", "POST /api/hooks", "POST /api/hooks/preview", "POST /api/hooks/render", "POST /api/hooks/import", "POST /api/hooks/restore", "GET /api/hooks/catalog"} {
method, path, _ := strings.Cut(route, " ")
req := httptest.NewRequest(method, path, strings.NewReader(`{}`))
req.RemoteAddr = "127.0.0.1:5555"
req.Host = "attacker.example:19420"
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("%s: status = %d, want 403", route, w.Code)
}
}
}
func TestHooksAPIRenderShowsOneHookWithoutWriting(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
config := readOrEmpty(s.configPath())
root := t.TempDir()
for _, tc := range []struct{ mutation, path string }{
{hooksTestMutation, filepath.Join(home, ".claude", "settings.json")},
{hooksProjectEntry(root, "guard", "echo skillshare-hooks-test"), filepath.Join(root, ".claude", "settings.json")},
} {
w := hooksPost(s, s.handleHooksRender, "/api/hooks/render", `{"mutation":`+tc.mutation+`}`)
var body struct {
Rendered []struct {
Target, Path, Content, Error string
} `json:"rendered"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &body) != nil || len(body.Rendered) != 1 {
t.Fatalf("render: %d %s", w.Code, w.Body)
}
f := body.Rendered[0]
if f.Target != "claude" || f.Path != tc.path || f.Error != "" || !strings.Contains(f.Content, `"hooks"`) || !strings.Contains(f.Content, "skillshare-hooks-test") {
t.Fatalf("rendered: %+v", f)
}
if _, err := os.Stat(tc.path); !os.IsNotExist(err) {
t.Fatal("render wrote native configuration")
}
}
if readOrEmpty(s.configPath()) != config {
t.Fatal("render must not save the source")
}
if entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10); len(entries) != 0 {
t.Fatalf("render must not write the operations log: %+v", entries)
}
}
func TestHooksAPIRenderRejectsNonRenderRequests(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
for _, body := range []string{
`{"mutation":` + hooksTestMutation + `,"revision":"x"}`,
`{"mutation":{"name":"bash-log","remove":true}}`,
`{"mutation":{"name":"bash-log"}}`,
`{"mutation":{"entry":{"bindings":{}}}}`,
`{"mutation":` + strings.Replace(hooksTestMutation, `"name"`, `"replace":true,"name"`, 1) + `}`,
`{"mutation":` + hooksTestMutation + `}{}`,
} {
if w := hooksPost(s, s.handleHooksRender, "/api/hooks/render", body); w.Code != http.StatusBadRequest {
t.Fatalf("%s: status %d %s", body, w.Code, w.Body)
}
}
}
// hooksSave previews and saves a mutation to the source without syncing.
func hooksSave(t *testing.T, s *Server, mutation string) {
t.Helper()
revision := hooksPreviewRevision(t, s, mutation)
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+mutation+`,"revision":"`+revision+`"}`); w.Code != http.StatusOK {
t.Fatalf("save %s: %d %s", mutation, w.Code, w.Body)
}
}
func hooksProjectEntry(root, name, command string) string {
return `{"project":"` + root + `","name":"` + name + `","entry":{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"` + command + `"}]}]}}}}}`
}
func readOrEmpty(path string) string {
data, _ := os.ReadFile(path)
return string(data)
}
func TestHooksAPIProjectSyncAppliesOnlyThatRoot(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
rootA, rootB := t.TempDir(), t.TempDir()
settingsA := filepath.Join(rootA, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settingsA), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(settingsA, []byte(`{"theme":"dark"}`), 0644); err != nil {
t.Fatal(err)
}
hooksSave(t, s, hooksProjectEntry(rootA, "a", "echo hook-a"))
hooksSave(t, s, hooksProjectEntry(rootB, "b", "echo hook-b"))
hooksSave(t, s, hooksTestMutation)
revision := hooksPreviewRevision(t, s, `{}`)
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootA+`"}`)
if w.Code != http.StatusOK {
t.Fatalf("project sync: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(settingsA); !strings.Contains(got, "echo hook-a") || !strings.Contains(got, `"theme"`) {
t.Fatalf("root A not synced with its settings kept:\n%s", got)
}
if got := readOrEmpty(filepath.Join(rootB, ".claude", "settings.json")); got != "" {
t.Fatalf("syncing root A wrote root B:\n%s", got)
}
if got := readOrEmpty(filepath.Join(home, ".claude", "settings.json")); got != "" {
t.Fatalf("syncing root A wrote the global settings:\n%s", got)
}
stale := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootB+`"}`)
if stale.Code != http.StatusConflict {
t.Fatalf("reused revision: %d %s", stale.Code, stale.Body)
}
hooksSave(t, s, `{"project":"`+rootA+`","name":"a","remove":true}`)
revision = hooksPreviewRevision(t, s, `{}`)
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootA+`"}`); w.Code != http.StatusOK {
t.Fatalf("prune sync: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(settingsA); strings.Contains(got, "echo hook-a") || !strings.Contains(got, `"theme"`) {
t.Fatalf("prune did not remove only the owned hook:\n%s", got)
}
if got := readOrEmpty(filepath.Join(rootB, ".claude", "settings.json")); got != "" {
t.Fatalf("pruning root A wrote root B:\n%s", got)
}
}
func TestHooksAPIProjectSyncRejectsInvalidRoot(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
root := t.TempDir()
hooksSave(t, s, hooksProjectEntry(root, "a", "echo hook-a"))
revision := hooksPreviewRevision(t, s, `{}`)
for name, body := range map[string]string{
"with changes": `{"mutation":{"name":"a","remove":true},"revision":"` + revision + `","sync":true,"root":"` + root + `"}`,
"without sync": `{"mutation":{},"revision":"` + revision + `","root":"` + root + `"}`,
"unknown root": `{"mutation":{},"revision":"` + revision + `","sync":true,"root":"` + t.TempDir() + `"}`,
} {
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", body); w.Code != http.StatusBadRequest {
t.Errorf("%s: %d %s", name, w.Code, w.Body)
}
}
project, _ := newTestProjectServerWithExtras(t, nil)
revision = hooksPreviewRevision(t, project, `{}`)
w := hooksPost(project, project.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+root+`"}`)
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "global mode") {
t.Fatalf("project mode root: %d %s", w.Code, w.Body)
}
}
func TestHooksAPIImportReadsProjectRoot(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
root := t.TempDir()
hooksSave(t, s, `{"project":"`+root+`"}`)
settings := filepath.Join(root, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(settings, []byte(`{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo project-native"}]}]}}`), 0644); err != nil {
t.Fatal(err)
}
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","root":"`+root+`"}`)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "project-native") {
t.Fatalf("project import: %d %s", w.Code, w.Body)
}
global := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude"}`)
if global.Code != http.StatusOK || strings.Contains(global.Body.String(), "project-native") {
t.Fatalf("global import read the project file: %d %s", global.Code, global.Body)
}
if w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","root":"`+t.TempDir()+`"}`); w.Code != http.StatusBadRequest {
t.Fatalf("unknown import root: %d %s", w.Code, w.Body)
}
}
func TestHooksAPICatalogListsCommandAgentEvents(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
w := httptest.NewRecorder()
s.handleHooksCatalog(w, httptest.NewRequest(http.MethodGet, "/api/hooks/catalog", nil))
var catalog map[string]struct {
Events []struct {
Name string `json:"name"`
Description string `json:"description"`
Matcher bool `json:"matcher"`
} `json:"events"`
TimeoutUnit string `json:"timeoutUnit"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &catalog) != nil {
t.Fatalf("catalog: %d %s", w.Code, w.Body)
}
if c := catalog["gemini"]; c.TimeoutUnit != "milliseconds" || len(c.Events) == 0 || c.Events[0].Description == "" {
t.Fatalf("gemini catalog: %+v", c)
}
if _, ok := catalog["pi"]; ok {
t.Fatal("code Agents have no event catalog")
}
}
func TestHooksAPIImportSaveTakesOverWithoutReplace(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
settings := filepath.Join(home, ".claude", "settings.json")
native := `{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo stop"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard"}]}]}}`
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(settings, []byte(native), 0644); err != nil {
t.Fatal(err)
}
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","name":"claude-stop"}`)
var imported struct {
Candidates []struct {
Entry json.RawMessage `json:"entry"`
} `json:"candidates"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &imported) != nil || len(imported.Candidates) != 1 {
t.Fatalf("import: %d %s", w.Code, w.Body)
}
mutation := `{"name":"claude-stop","entry":` + string(imported.Candidates[0].Entry) + `,"adopt":true}`
revision := hooksPreviewRevision(t, s, mutation)
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+mutation+`,"revision":"`+revision+`","sync":false}`); w.Code != http.StatusOK {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
preview := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":{}}`)
var plan struct {
Blocked bool `json:"blocked"`
Changes []struct {
Action string `json:"action"`
} `json:"changes"`
}
if json.Unmarshal(preview.Body.Bytes(), &plan) != nil || plan.Blocked || len(plan.Changes) != 1 || plan.Changes[0].Action != "adopt" {
t.Fatalf("sync after an imported save: %s", preview.Body)
}
}
func TestHooksAPIPreviewCarriesFileTexts(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
w := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":`+hooksTestMutation+`}`)
var p struct {
Revision string `json:"revision"`
Files []struct {
Target, Path, Before, After string
} `json:"files"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || len(p.Files) != 1 {
t.Fatalf("preview: %d %s", w.Code, w.Body)
}
f := p.Files[0]
if f.Target != "claude" || f.Path != filepath.Join(home, ".claude", "settings.json") || f.Before != "" || !strings.Contains(f.After, "skillshare-hooks-test") {
t.Fatalf("file diff: %+v", f)
}
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+p.Revision+`","sync":true}`); w.Code != http.StatusOK {
t.Fatalf("apply: %d %s", w.Code, w.Body)
}
if data, _ := os.ReadFile(f.Path); string(data) != f.After {
t.Fatalf("written file differs from the preview:\n%s", data)
}
}
+36 -24
View File
@@ -15,10 +15,13 @@ import (
"skillshare/internal/config"
"skillshare/internal/mcp"
syncpkg "skillshare/internal/sync"
)
func (s *Server) mcpService() *mcp.Service {
return &mcp.Service{ConfigPath: s.configPath(), ProjectRoot: s.projectRoot, StateDir: config.StateDir(), ConfigDirs: mcp.ConfigDirsFromEnv()}
return &mcp.Service{ConfigPath: s.configPath(), ProjectRoot: s.projectRoot, StateDir: config.StateDir(), ConfigDirs: mcp.ConfigDirsFromEnv(), BackupSource: func(path string) (string, error) {
return syncpkg.StoreBackup(path, syncpkg.BackupReasonMigrate)
}}
}
type mcpRequest struct {
@@ -117,26 +120,37 @@ func (s *Server) handleMCPRender(w http.ResponseWriter, r *http.Request) {
writeError(w, 400, "server is required")
return
}
service := s.mcpService()
if body.Mutation.Project != "" {
if service.ProjectRoot != "" {
writeError(w, 400, "MCP project overrides are not available in project mode; omit mutation.project")
return
}
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
writeError(w, 400, err.Error())
return
}
if _, ok := source.Projects[body.Mutation.Project]; !ok {
writeError(w, 400, "unknown MCP project")
return
}
service.ProjectRoot = body.Mutation.Project
service, ok := s.mcpProjectService(w, body.Mutation.Project)
if !ok {
return
}
writeJSON(w, map[string]any{"rendered": service.RenderNative(body.Mutation.Name, *body.Mutation.Server)})
}
// mcpProjectService is the service for one mcp.projects root, or for this scope when
// project is empty. It writes the error and reports false when the root is not configured.
func (s *Server) mcpProjectService(w http.ResponseWriter, project string) (*mcp.Service, bool) {
service := s.mcpService()
if project == "" {
return service, true
}
if service.ProjectRoot != "" {
writeError(w, 400, "MCP project overrides are not available in project mode; omit mutation.project")
return nil, false
}
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
writeError(w, 400, err.Error())
return nil, false
}
if _, ok := source.Projects[project]; !ok {
writeError(w, 400, "unknown MCP project")
return nil, false
}
service.ProjectRoot = project
return service, true
}
func (s *Server) handleMCPConfigure(w http.ResponseWriter, r *http.Request) {
var body mcpRequest
if !decodeMCPRequest(w, r, &body) {
@@ -184,9 +198,11 @@ func (s *Server) handleMCPConfigure(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleMCPImport(w http.ResponseWriter, r *http.Request) {
var body struct {
From string `json:"from"`
Content string `json:"content"`
Name string `json:"name"`
From string `json:"from"`
Content string `json:"content"`
Name string `json:"name"`
// PiExtension picks one of Pi's files: pi-mcp-adapter for the adapter's, anything
// else for mcp.json. Pasted content ignores it.
PiExtension string `json:"piExtension"`
// Root reads the target's file in that mcp.projects root instead of this scope.
Root string `json:"root"`
@@ -199,10 +215,6 @@ func (s *Server) handleMCPImport(w http.ResponseWriter, r *http.Request) {
var candidates []mcp.Candidate
var err error
if body.Content != "" {
if body.PiExtension != "" {
writeError(w, 400, "Pi import mode requires a target file")
return
}
candidates, err = mcp.Import(body.From, []byte(body.Content), body.Name)
} else if body.Root != "" {
candidates, err = s.mcpService().ImportProjectClientMode(body.Root, body.From, body.PiExtension)
+41 -2
View File
@@ -4,18 +4,57 @@ import (
"net/http"
"skillshare/internal/mcp"
"skillshare/internal/version"
)
// handleMCPCheck answers `skillshare mcp check --json` for the dashboard. It is read-only
// and writes no operation log entry. Findings that are errors still return 200; only a
// check that cannot run fails the request. ?dns=0 skips host lookups.
// check that cannot run fails the request. ?dns=0 skips host lookups. ?live=1 also probes
// the servers, as `mcp check --live` does, and each server's live result lists the tool
// names it reported; repeated ?name= limits the check to those servers.
func (s *Server) handleMCPCheck(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
defer s.mu.RUnlock()
report, err := s.mcpService().Check(mcp.CheckOptions{SkipDNS: r.URL.Query().Get("dns") == "0"})
query := r.URL.Query()
report, err := s.mcpService().Check(mcp.CheckOptions{
SkipDNS: query.Get("dns") == "0",
Live: query.Get("live") == "1",
Names: query["name"],
ClientVersion: version.Version,
})
if err != nil {
writeError(w, 400, err.Error())
return
}
writeJSON(w, report)
}
// handleMCPProbe probes the server in the request, as the dashboard's form describes it
// before it is saved, the way ?live=1 probes a saved one. It saves and syncs nothing.
func (s *Server) handleMCPProbe(w http.ResponseWriter, r *http.Request) {
var body mcpRequest
if !decodeMCPRequest(w, r, &body) {
return
}
if body.Mutation.Server == nil {
writeError(w, 400, "server is required")
return
}
s.mu.RLock()
service, ok := s.mcpProjectService(w, body.Mutation.Project)
s.mu.RUnlock()
if !ok {
return
}
// A project server starts in its root, as a live check of a saved one does.
root := ""
if body.Mutation.Project != "" {
root = service.ProjectRoot
}
result, err := mcp.ProbeDraft(*body.Mutation.Server, root, mcp.CheckOptions{ClientVersion: version.Version})
if err != nil {
writeError(w, 400, err.Error())
return
}
writeJSON(w, result)
}
+54
View File
@@ -71,3 +71,57 @@ func TestMCPCheckFailsWhenCheckCannotRun(t *testing.T) {
t.Fatalf("status = %d body = %s", w.Code, w.Body.String())
}
}
func probeDraft(t *testing.T, s *Server, server string) map[string]any {
t.Helper()
w := httptest.NewRecorder()
s.handleMCPProbe(w, httptest.NewRequest(http.MethodPost, "/api/mcp/probe", strings.NewReader(`{"mutation":{"name":"docs","server":`+server+`}}`)))
if w.Code != http.StatusOK {
t.Fatalf("status = %d body = %s", w.Code, w.Body.String())
}
var result map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
func TestMCPProbeListsToolsOfAnUnsavedServer(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
mcpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req struct {
ID json.RawMessage `json:"id"`
Method string `json:"method"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
result := map[string]any{"tools": []any{map[string]string{"name": "search"}, map[string]string{"name": "fetch"}}}
if req.Method == "server/discover" {
result = map[string]any{"supportedVersions": []string{"2026-07-28"}, "capabilities": map[string]any{"tools": map[string]any{}}}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": result})
}))
defer mcpServer.Close()
before, err := os.ReadFile(s.configPath())
if err != nil {
t.Fatal(err)
}
result := probeDraft(t, s, `{"url":"`+mcpServer.URL+`/mcp","tools":{"allow":["half typed"]}}`)
live, _ := result["live"].(map[string]any)
if live == nil || live["tools"] != float64(2) || result["errorKind"] != nil {
t.Fatalf("result = %v", result)
}
if after, _ := os.ReadFile(s.configPath()); string(after) != string(before) {
t.Fatal("a probe must not save the server")
}
}
func TestMCPProbeClassifiesARefusedConnection(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
closed := httptest.NewServer(http.NotFoundHandler())
closed.Close()
result := probeDraft(t, s, `{"url":"`+closed.URL+`/mcp"}`)
if result["errorKind"] != "connect" || !strings.Contains(result["error"].(string), "refused") {
t.Fatalf("result = %v", result)
}
}
@@ -0,0 +1,347 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
// The MCP half of the dashboard contract: each test replays what ui/src/api/mcp.ts and its
// callers send, with the revision taken from the preview the dialog used.
type mcpUIView struct {
Source struct {
Servers map[string]json.RawMessage `json:"servers"`
Projects map[string]struct {
Servers map[string]json.RawMessage `json:"servers"`
} `json:"projects"`
} `json:"source"`
Plan *struct {
Blocked bool `json:"blocked"`
Changes []struct {
Name string `json:"name"`
Root string `json:"root"`
Action string `json:"action"`
} `json:"changes"`
} `json:"plan"`
Backups []struct {
ID string `json:"id"`
} `json:"backups"`
Unmanaged []struct {
Path string `json:"path"`
Names []string `json:"names"`
} `json:"unmanaged"`
}
func mcpPost(handler http.HandlerFunc, path, body string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
handler(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)))
return w
}
func mcpUIList(t *testing.T, s *Server) mcpUIView {
t.Helper()
w := httptest.NewRecorder()
s.handleMCPList(w, httptest.NewRequest(http.MethodGet, "/api/mcp", nil))
var view mcpUIView
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &view) != nil {
t.Fatalf("list: %d %s", w.Code, w.Body)
}
return view
}
func mcpUIPreviewRevision(t *testing.T, s *Server, mutation string) string {
t.Helper()
w := mcpPost(s.handleMCPPreview, "/api/mcp/preview", `{"mutation":`+mutation+`}`)
var p struct {
Revision string `json:"revision"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || p.Revision == "" {
t.Fatalf("preview %s: %d %s", mutation, w.Code, w.Body)
}
return p.Revision
}
// mcpUIConfigure is mcpApi.configure.
func mcpUIConfigure(s *Server, mutation, revision string, sync bool) *httptest.ResponseRecorder {
body, _ := json.Marshal(map[string]any{"mutation": json.RawMessage(mutation), "revision": revision, "sync": sync})
return mcpPost(s.handleMCPConfigure, "/api/mcp", string(body))
}
// mcpUISave is mcpApi.save: preview the mutation, save the source with that revision.
func mcpUISave(t *testing.T, s *Server, mutation string) {
t.Helper()
if w := mcpUIConfigure(s, mutation, mcpUIPreviewRevision(t, s, mutation), false); w.Code != http.StatusOK {
t.Fatalf("save %s: %d %s", mutation, w.Code, w.Body)
}
}
// mcpUISync is the Sync page and MCPSyncDialog (runSync): the global plan, or one project's.
func mcpUISync(t *testing.T, s *Server, root string) {
t.Helper()
revision := mcpUIPreviewRevision(t, s, `{}`)
var w *httptest.ResponseRecorder
if root == "" {
w = mcpUIConfigure(s, `{}`, revision, true)
} else {
w = mcpPost(s.handleMCPConfigure, "/api/mcp", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+root+`"}`)
}
if w.Code != http.StatusOK {
t.Fatalf("sync %q: %d %s", root, w.Code, w.Body)
}
}
const mcpUIServer = `{"url":"https://example.com/contract","targets":["claude"]}`
// mcpUIScope is one place the dashboard manages MCP from.
type mcpUIScope struct {
s *Server
project string // mutation.project, empty outside an mcp.projects root
root string // the sync root the dashboard passes for this scope
file string // Claude's MCP file here
}
var mcpUIScopeNames = []string{"global", "mcp.projects root", "project mode"}
var mcpUIScopes = []func(t *testing.T) mcpUIScope{
func(t *testing.T) mcpUIScope {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
return mcpUIScope{s, "", "", filepath.Join(home, ".claude.json")}
},
func(t *testing.T) mcpUIScope {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
root := t.TempDir()
mcpUISave(t, s, `{"project":"`+root+`","settings":{"targets":["claude"]}}`) // AddProjectDialog
return mcpUIScope{s, root, root, filepath.Join(root, ".mcp.json")}
},
func(t *testing.T) mcpUIScope {
s, root := newTestProjectServerWithExtras(t, nil)
hooksTestHome(t)
return mcpUIScope{s, "", "", filepath.Join(root, ".mcp.json")}
},
}
func (sc mcpUIScope) mutation(fields string) string {
if sc.project == "" {
return `{` + fields + `}`
}
return `{"project":"` + sc.project + `",` + fields + `}`
}
func (sc mcpUIScope) servers(t *testing.T) map[string]json.RawMessage {
view := mcpUIList(t, sc.s)
if sc.project != "" {
return view.Source.Projects[sc.project].Servers
}
return view.Source.Servers
}
// addAndSync is MCPServerDialog's save followed by the scope's sync.
func (sc mcpUIScope) addAndSync(t *testing.T) {
t.Helper()
mcpUISave(t, sc.s, sc.mutation(`"name":"docs","server":`+mcpUIServer+`,"replace":false`))
mcpUISync(t, sc.s, sc.root)
if !strings.Contains(readOrEmpty(sc.file), "example.com/contract") {
t.Fatalf("not written:\n%s", readOrEmpty(sc.file))
}
}
func (sc mcpUIScope) pending(t *testing.T) []string {
var out []string
if p := mcpUIList(t, sc.s).Plan; p != nil {
for _, c := range p.Changes {
if c.Action != "unchanged" {
out = append(out, c.Name+":"+c.Action)
}
}
}
return out
}
// MCPRemoveDialog: all three choices, in every scope.
func TestMCPUIContract_RemoveDialog(t *testing.T) {
for i, newScope := range mcpUIScopes {
for _, choice := range []string{"sync", "source only", "stop managing"} {
t.Run(mcpUIScopeNames[i]+"/"+choice, func(t *testing.T) {
sc := newScope(t)
sc.addAndSync(t)
removal := sc.mutation(`"name":"docs","remove":true`)
planRevision := mcpUIPreviewRevision(t, sc.s, removal)
var w *httptest.ResponseRecorder
switch choice {
case "sync":
w = mcpUIConfigure(sc.s, removal, planRevision, true)
case "source only":
w = mcpUIConfigure(sc.s, removal, planRevision, false)
case "stop managing":
unmanage := sc.mutation(`"name":"docs","remove":true,"unmanage":true`)
w = mcpUIConfigure(sc.s, unmanage, mcpUIPreviewRevision(t, sc.s, unmanage), false)
}
if w.Code != http.StatusOK {
t.Fatalf("%d %s", w.Code, w.Body)
}
if _, ok := sc.servers(t)["docs"]; ok {
t.Fatal("still in the source")
}
written := strings.Contains(readOrEmpty(sc.file), "example.com/contract")
pending := sc.pending(t)
switch choice {
case "sync":
if written || len(pending) != 0 {
t.Fatalf("written=%v pending=%v", written, pending)
}
case "source only":
if !written || len(pending) != 1 || pending[0] != "docs:remove" {
t.Fatalf("written=%v pending=%v", written, pending)
}
case "stop managing":
unmanaged := mcpUIList(t, sc.s).Unmanaged
if !written || len(pending) != 0 || len(unmanaged) != 1 || unmanaged[0].Path != sc.file {
t.Fatalf("written=%v pending=%v unmanaged=%+v", written, pending, unmanaged)
}
}
})
}
}
}
// MCPPage's conflict "replace": the resolution alone, previewed and applied with sync.
func TestMCPUIContract_ReplaceOutsideEdit(t *testing.T) {
for i, newScope := range mcpUIScopes {
t.Run(mcpUIScopeNames[i], func(t *testing.T) {
sc := newScope(t)
sc.addAndSync(t)
edited := strings.Replace(readOrEmpty(sc.file), "example.com/contract", "example.com/edited", 1)
if err := os.WriteFile(sc.file, []byte(edited), 0644); err != nil {
t.Fatal(err)
}
if p := mcpUIList(t, sc.s).Plan; p == nil || !p.Blocked {
t.Fatalf("outside edit is not a conflict: %+v", p)
}
replace := `{"resolutions":[{"target":"claude","name":"docs","action":"replace"}]}`
if w := mcpUIConfigure(sc.s, replace, mcpUIPreviewRevision(t, sc.s, replace), true); w.Code != http.StatusOK {
t.Fatalf("replace: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(sc.file); strings.Contains(got, "example.com/edited") || !strings.Contains(got, "example.com/contract") {
t.Fatalf("replace did not restore the source server:\n%s", got)
}
if p := mcpUIList(t, sc.s).Plan; p == nil || p.Blocked {
t.Fatalf("still blocked: %+v", p)
}
})
}
}
// MCPImportDialog: import an Agent's own entry and save it with an adopt resolution; the
// next sync treats it as managed instead of a conflict.
func TestMCPUIContract_ImportAdopt(t *testing.T) {
for i, newScope := range mcpUIScopes {
t.Run(mcpUIScopeNames[i], func(t *testing.T) {
sc := newScope(t)
if err := os.WriteFile(sc.file, []byte(`{"mcpServers":{"docs":{"type":"http","url":"https://example.com/native"}}}`), 0644); err != nil {
t.Fatal(err)
}
request := `{"from":"claude"}`
if sc.project != "" {
request = `{"from":"claude","root":"` + sc.project + `"}`
}
w := mcpPost(sc.s.handleMCPImport, "/api/mcp/import", request)
var imported struct {
Candidates []struct {
Name string `json:"name"`
Server map[string]json.RawMessage `json:"server"`
} `json:"candidates"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &imported) != nil || len(imported.Candidates) != 1 {
t.Fatalf("import: %d %s", w.Code, w.Body)
}
server := imported.Candidates[0].Server
server["targets"] = json.RawMessage(`["claude"]`)
serverJSON, _ := json.Marshal(server)
mcpUISave(t, sc.s, sc.mutation(`"name":"docs","server":`+string(serverJSON)+`,"replace":false,"resolutions":[{"target":"claude","name":"docs","action":"adopt"}]`))
if p := mcpUIList(t, sc.s).Plan; p == nil || p.Blocked {
t.Fatalf("adopted server is a conflict: %+v", p)
}
// The next sync may only re-lay out the adopted entry, never change or refuse it.
mcpUISync(t, sc.s, sc.root)
if got := readOrEmpty(sc.file); !strings.Contains(got, "example.com/native") {
t.Fatalf("sync changed the adopted server:\n%s", got)
}
})
}
}
// useMCPToggle and MCPProjectView's switches save the whole server with replace:true; a
// project turning a global server off saves a disabled entry, and on again removes it.
func TestMCPUIContract_Toggles(t *testing.T) {
sc := mcpUIScopes[0](t)
sc.addAndSync(t)
mcpUISave(t, sc.s, `{"name":"docs","server":{"url":"https://example.com/contract","targets":[]},"replace":true}`)
mcpUISync(t, sc.s, "")
if strings.Contains(readOrEmpty(sc.file), "example.com/contract") {
t.Fatal("unticked Agent kept the server")
}
mcpUISave(t, sc.s, `{"name":"docs","server":`+mcpUIServer+`,"replace":true}`)
mcpUISync(t, sc.s, "")
root := t.TempDir()
mcpUISave(t, sc.s, `{"project":"`+root+`","settings":{"targets":["claude"]}}`)
mcpUISave(t, sc.s, `{"project":"`+root+`","name":"docs","replace":true,"server":{"disabled":true}}`)
mcpUISync(t, sc.s, root)
if pending := sc.pending(t); len(pending) != 0 {
t.Fatalf("turning off in a project left changes: %v", pending)
}
mcpUISave(t, sc.s, `{"project":"`+root+`","name":"docs","remove":true}`)
mcpUISync(t, sc.s, root)
if pending := sc.pending(t); len(pending) != 0 {
t.Fatalf("turning back on left changes: %v", pending)
}
mcpUISave(t, sc.s, `{"project":"`+root+`","remove":true}`) // MCPProjectView and ProjectDetailPage dropping the project
if _, ok := mcpUIList(t, sc.s).Source.Projects[root]; ok {
t.Fatal("project still configured")
}
}
// MCPPage's default targets: a server without its own targets follows them.
func TestMCPUIContract_DefaultTargets(t *testing.T) {
sc := mcpUIScopes[0](t)
mcpUISave(t, sc.s, `{"settings":{"targets":["claude"]},"replace":true}`)
mcpUISave(t, sc.s, `{"name":"docs","server":{"url":"https://example.com/contract"},"replace":false}`)
mcpUISync(t, sc.s, "")
if !strings.Contains(readOrEmpty(sc.file), "example.com/contract") {
t.Fatal("default target was not written")
}
}
// MCPRestoreDialog: preview the backup, restore with that revision.
func TestMCPUIContract_RestoreBackup(t *testing.T) {
sc := mcpUIScopes[0](t)
if err := os.WriteFile(sc.file, []byte(`{"theme":"dark"}`), 0644); err != nil {
t.Fatal(err)
}
sc.addAndSync(t)
backups := mcpUIList(t, sc.s).Backups
if len(backups) != 1 {
t.Fatalf("backups: %+v", backups)
}
preview := mcpPost(sc.s.handleMCPRestore, "/api/mcp/restore", `{"backupId":"`+backups[0].ID+`","preview":true}`)
var p struct {
Revision string `json:"revision"`
}
if preview.Code != http.StatusOK || json.Unmarshal(preview.Body.Bytes(), &p) != nil || p.Revision == "" {
t.Fatalf("restore preview: %d %s", preview.Code, preview.Body)
}
if w := mcpPost(sc.s.handleMCPRestore, "/api/mcp/restore", `{"backupId":"`+backups[0].ID+`","revision":"`+p.Revision+`"}`); w.Code != http.StatusOK {
t.Fatalf("restore: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(sc.file); strings.Contains(got, "example.com/contract") || !strings.Contains(got, `"theme"`) {
t.Fatalf("restored file:\n%s", got)
}
}
+45 -28
View File
@@ -8,6 +8,8 @@ import (
"path/filepath"
"strings"
"testing"
syncpkg "skillshare/internal/sync"
)
func TestMCPPiImportSourceSelection(t *testing.T) {
@@ -48,20 +50,9 @@ func TestMCPPiImportSourceSelection(t *testing.T) {
}
continue
}
for mode, file := range map[string]string{"builtin": "mcp.json", "pi-mcp-adapter": "mcp-adapter.json", "pi-mcp-extension": "mcp.json"} {
if mode == "pi-mcp-extension" && target == "pi-work" {
if _, exists := found[mode]; exists {
t.Fatal("extension offered an account")
}
continue
}
modeBase := base
if mode == "pi-mcp-extension" && scope == "" {
modeBase = filepath.Join(home, ".pi", "agent")
}
if found[mode] != filepath.Join(modeBase, file) {
t.Fatalf("%s %s %s: %+v", scope, target, mode, found)
}
// Pi's built-in file, and the adapter's, which is still read for import.
if len(found) != 2 || found["builtin"] != filepath.Join(base, "mcp.json") || found["pi-mcp-adapter"] != filepath.Join(base, "mcp-adapter.json") {
t.Fatalf("%s %s: %+v", scope, target, found)
}
if err := os.MkdirAll(base, 0755); err != nil {
t.Fatal(err)
@@ -71,19 +62,8 @@ func TestMCPPiImportSourceSelection(t *testing.T) {
t.Fatal(err)
}
}
if scope == "" && target == "pi" {
extensionDir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(extensionDir, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(extensionDir, "mcp.json"), []byte(`{"mcpServers":{"docs":{"command":"native","transport":"stdio","lifecycle":"eager"}}}`), 0600); err != nil {
t.Fatal(err)
}
}
// A dashboard from before 0.23.0 may still send pi-mcp-extension; it reads mcp.json.
for mode, command := range map[string]string{"builtin": "native", "pi-mcp-adapter": "adapter", "pi-mcp-extension": "native"} {
if mode == "pi-mcp-extension" && target == "pi-work" {
continue
}
body, _ := json.Marshal(map[string]string{"from": target, "root": scope, "piExtension": mode})
w := httptest.NewRecorder()
s.handleMCPImport(w, httptest.NewRequest(http.MethodPost, "/api/mcp/import", strings.NewReader(string(body))))
@@ -91,10 +71,10 @@ func TestMCPPiImportSourceSelection(t *testing.T) {
Candidates []struct {
From string
Warnings []string
Server struct{ Command, PiExtension string }
Server struct{ Command string }
}
}
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Candidates) != 1 || result.Candidates[0].From != target || result.Candidates[0].Server.Command != command || result.Candidates[0].Server.PiExtension != mode || strings.Contains(strings.Join(result.Candidates[0].Warnings, ";"), "Select the Pi MCP mode") {
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Candidates) != 1 || result.Candidates[0].From != target || result.Candidates[0].Server.Command != command {
t.Fatalf("%s %s %s: %s", scope, target, mode, w.Body)
}
}
@@ -230,3 +210,40 @@ func TestMCPRenderRejectsProjectOverrideInProjectMode(t *testing.T) {
t.Fatalf("%d %s", w.Code, w.Body)
}
}
// The dashboard's sync saves the config without the settings 0.23.0 retired, keeping the
// previous version in the file history, so the list no longer shows their notices.
func TestMCPSyncSavesTheConfigWithoutRetiredSettings(t *testing.T) {
s, sourceDir := newTestServerWithExtras(t, nil, "")
t.Setenv("HOME", t.TempDir())
t.Setenv("PI_CODING_AGENT_DIR", t.TempDir())
data := "source: " + sourceDir + "\nmcp:\n targets: [pi]\n servers:\n docs:\n command: docs\n piExtension: pi-mcp-adapter\n"
if err := os.WriteFile(s.configPath(), []byte(data), 0600); err != nil {
t.Fatal(err)
}
plan, err := s.mcpService().Preview()
if err != nil || !plan.Migrates || len(plan.Notices) != 2 {
t.Fatalf("%+v %v", plan, err)
}
body, _ := json.Marshal(map[string]any{"mutation": map[string]any{}, "revision": plan.Revision, "sync": true})
w := httptest.NewRecorder()
s.handleMCPConfigure(w, httptest.NewRequest(http.MethodPost, "/api/mcp", strings.NewReader(string(body))))
if w.Code != 200 || !strings.Contains(w.Body.String(), `"migrated":[{"path":`) {
t.Fatalf("%d %s", w.Code, w.Body)
}
if saved, _ := os.ReadFile(s.configPath()); strings.Contains(string(saved), "piExtension") || !strings.Contains(string(saved), "command: docs") {
t.Fatalf("saved config:\n%s", saved)
}
versions, err := syncpkg.FileBackupVersions(s.configPath())
if err != nil || len(versions) != 1 || versions[0].Reason != syncpkg.BackupReasonMigrate {
t.Fatalf("backups: %+v %v", versions, err)
}
if kept, _, err := syncpkg.ReadFileBackupVersion(s.configPath(), versions[0].ID); err != nil || string(kept) != data {
t.Fatalf("backup: %s %v", kept, err)
}
list := httptest.NewRecorder()
s.handleMCPList(list, httptest.NewRequest(http.MethodGet, "/api/mcp", nil))
if list.Code != 200 || strings.Contains(list.Body.String(), `"notices"`) || strings.Contains(list.Body.String(), `"migrates"`) {
t.Fatalf("list: %s", list.Body)
}
}
+8
View File
@@ -545,10 +545,18 @@ func (s *Server) registerRoutes() {
s.mux.HandleFunc("GET /api/mcp", s.requireLocalMCP(s.handleMCPList))
s.mux.HandleFunc("POST /api/mcp", s.requireLocalMCP(s.handleMCPConfigure))
s.mux.HandleFunc("GET /api/mcp/check", s.requireLocalMCP(s.handleMCPCheck))
s.mux.HandleFunc("POST /api/mcp/probe", s.requireLocalMCP(s.handleMCPProbe))
s.mux.HandleFunc("POST /api/mcp/preview", s.requireLocalMCP(s.handleMCPPreview))
s.mux.HandleFunc("POST /api/mcp/render", s.requireLocalMCP(s.handleMCPRender))
s.mux.HandleFunc("POST /api/mcp/import", s.requireLocalMCP(s.handleMCPImport))
s.mux.HandleFunc("POST /api/mcp/restore", s.requireLocalMCP(s.handleMCPRestore))
s.mux.HandleFunc("GET /api/hooks", s.requireLocalHooks(s.handleHooksList))
s.mux.HandleFunc("POST /api/hooks", s.requireLocalHooks(s.handleHooksConfigure))
s.mux.HandleFunc("POST /api/hooks/preview", s.requireLocalHooks(s.handleHooksPreview))
s.mux.HandleFunc("POST /api/hooks/render", s.requireLocalHooks(s.handleHooksRender))
s.mux.HandleFunc("POST /api/hooks/import", s.requireLocalHooks(s.handleHooksImport))
s.mux.HandleFunc("POST /api/hooks/restore", s.requireLocalHooks(s.handleHooksRestore))
s.mux.HandleFunc("GET /api/hooks/catalog", s.requireLocalHooks(s.handleHooksCatalog))
s.mux.HandleFunc("GET /api/extras", s.handleExtras)
s.mux.HandleFunc("GET /api/extras/extensions", s.handleExtrasExtensions)
s.mux.HandleFunc("GET /api/extras/diff", s.handleExtrasDiff)
+1
View File
@@ -38,6 +38,7 @@ const (
BackupReasonCollect = "collect" // before a target's edit is collected into the shared file
BackupReasonAttach = "attach" // the file replaced when a target was first attached
BackupReasonRestore = "restore" // before an older version is restored
BackupReasonMigrate = "migrate" // before a sync drops settings a release retired
)
// Why a drift backup (an edit skillshare replaced) was taken.
+15
View File
@@ -330,6 +330,21 @@ func ManagedImportLines(content string) []int {
// reason is one of the BackupReason constants.
func BackupFile(path, reason string) error { return backupExtraFile(path, reason) }
// StoreBackup is BackupFile returning the backup that holds the current content: the new
// copy, or the latest one when it already held the same content.
func StoreBackup(path, reason string) (string, error) {
name, err := storeExtraBackup(path, reason)
if err != nil {
return "", err
}
dir := extraBackupDir(path)
if name == "" {
names := extraBackupNames(dir)
name = names[len(names)-1]
}
return filepath.Join(dir, name), nil
}
func syncExtraImport(f ExtraFile, dryRun bool) (*ExtraResult, error) {
result := &ExtraResult{Synced: 1}
attached := extraAttached(f.Target)
+1
View File
@@ -8,6 +8,7 @@
"allOf": [{"not": {"required": ["sources", "mcp"], "properties": {"sources": {"required": ["mcp"]}, "mcp": {"required": ["servers"]}}}}],
"properties": {
"mcp": {"$ref": "mcp.schema.json#/$defs/globalConfiguration"},
"hooks": {"$ref": "hooks.schema.json#/$defs/globalConfiguration"},
"source": {
"type": "string",
"description": "Legacy top-level skills source path. Prefer sources.skills (added in v0.19.16). When both are set, sources.skills wins. Supports ~ for home directory.",
+75
View File
@@ -0,0 +1,75 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://raw.githubusercontent.com/runkids/skillshare/main/schemas/hooks.schema.json",
"title": "Skillshare Hooks",
"description": "One hook entry as read by 'skillshare hooks add|edit --file'. The same definitions describe the hooks section of config.yaml.",
"$ref": "#/$defs/entry",
"$defs": {
"name": {"type": "string", "pattern": "^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$"},
"commandBinding": {
"type": "object", "additionalProperties": false, "required": ["events"],
"properties": {
"events": {
"type": "object", "minProperties": 1,
"description": "The Agent's own native event map, written without translation: event names, matchers, timeout units and handler fields stay exactly as the Agent documents them.",
"propertyNames": {"pattern": "^[A-Za-z][A-Za-z0-9_]*$"},
"additionalProperties": {"type": "array", "minItems": 1, "items": {"type": "object"}}
},
"files": {
"type": "object",
"description": "Script files written to <Agent config dir>/hooks/skillshare/<entry>/. Commands must reference them by path themselves.",
"propertyNames": {"$ref": "#/$defs/name"},
"additionalProperties": {"type": "string"}
}
}
},
"codeBinding": {
"type": "object", "additionalProperties": false, "required": ["code"],
"properties": {"code": {"type": "string", "minLength": 1, "description": "One standalone native TypeScript/JavaScript extension or plugin, written verbatim as skillshare-<entry>.ts. It must use the plugin API of the installed Agent version."}}
},
"bindings": {
"type": "object", "additionalProperties": false,
"description": "Keyed by Agent. An empty map keeps the hook in Skillshare without publishing it. factory is an alias for droid; antigravity-cli and agy are aliases for antigravity.",
"properties": {
"claude": {"$ref": "#/$defs/commandBinding"},
"codex": {"$ref": "#/$defs/commandBinding"},
"gemini": {"$ref": "#/$defs/commandBinding"},
"qwen": {"$ref": "#/$defs/commandBinding"},
"copilot": {"$ref": "#/$defs/commandBinding"},
"cursor": {"$ref": "#/$defs/commandBinding"},
"droid": {"$ref": "#/$defs/commandBinding"},
"factory": {"$ref": "#/$defs/commandBinding"},
"antigravity": {"$ref": "#/$defs/commandBinding"},
"antigravity-cli": {"$ref": "#/$defs/commandBinding"},
"agy": {"$ref": "#/$defs/commandBinding"},
"pi": {"$ref": "#/$defs/codeBinding"},
"amp": {"$ref": "#/$defs/codeBinding"},
"opencode": {"$ref": "#/$defs/codeBinding"}
}
},
"entry": {
"type": "object", "additionalProperties": false, "required": ["bindings"],
"properties": {
"description": {"type": "string"},
"enabled": {"type": "boolean", "default": true, "description": "false keeps the definition and removes only its unchanged native outputs."},
"bindings": {"$ref": "#/$defs/bindings"}
}
},
"entries": {"type": "object", "propertyNames": {"$ref": "#/$defs/name"}, "additionalProperties": {"$ref": "#/$defs/entry"}},
"configuration": {
"type": "object", "additionalProperties": false,
"properties": {"entries": {"$ref": "#/$defs/entries"}}
},
"globalConfiguration": {
"type": "object", "additionalProperties": false,
"properties": {
"entries": {"$ref": "#/$defs/entries"},
"projects": {
"type": "object",
"description": "Project roots this global config publishes hooks into, keyed by absolute path or ~ path. A root with its own Skillshare config is managed there instead.",
"additionalProperties": {"type": "object", "additionalProperties": false, "properties": {"entries": {"$ref": "#/$defs/entries"}}}
}
}
}
}
}
+18 -6
View File
@@ -9,9 +9,20 @@
"$defs": {
"targets": {"type": "array", "uniqueItems": true, "items": {"anyOf": [{"enum": ["claude", "codex", "cursor", "vscode", "opencode", "kilocode", "grok", "antigravity", "amp", "claude-desktop", "cline", "copilot", "factory", "gemini", "goose", "junie", "kiro", "lmstudio", "warp", "windsurf", "pi"]}, {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$", "description": "A target that is another account of an Agent, declared under targets with agent and config_dir. Global config only."}]}},
"directTools": {
"description": "pi-mcp-adapter only: register a server's tools as individual Pi tools. true for all, a list of tool names, or \"search\" to register them inactive until a search activates them. Other Agents ignore it. Under mcp or a project it is the default for servers that do not set their own.",
"deprecated": true,
"description": "Converted since 0.23.0: pi-mcp-adapter's setting becomes Pi's exposure (true: direct, \"search\": deferred) in piOptions, or piOptions.toolExposure for a list of tool names; a default under mcp or a project applies to each server that reaches Pi. Saving the config drops it.",
"oneOf": [{"type": "boolean"}, {"const": "search"}, {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}]
},
"toolList": {"type": "array", "uniqueItems": true, "minItems": 1, "items": {"type": "string", "pattern": "^[^\\s,?\\[\\]{}]+$", "description": "A tool name; * matches any characters."}},
"tools": {
"type": "object", "additionalProperties": false,
"description": "Which of the server's tools reach the model, translated per Agent. Pi holds all of it; Codex and Copilot take exact tool names; the plan and mcp check name each Agent that cannot hold a part.",
"properties": {
"expose": {"enum": ["direct", "deferred", "hidden"], "description": "How the model reaches the tools: declared directly, loaded through tool search, or hidden. Unset leaves each Agent's default."},
"allow": {"$ref": "#/$defs/toolList", "description": "Only the tools that match are available."},
"deny": {"$ref": "#/$defs/toolList", "description": "The tools that match are never available; deny beats allow."}
}
},
"reference": {
"type": "object", "required": ["fromEnv"], "additionalProperties": false,
"properties": {"fromEnv": {"type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"}}
@@ -46,7 +57,7 @@
"server": {
"type": "object", "additionalProperties": false,
"properties": {
"piExtension": {"enum": ["builtin", "pi-mcp-adapter", "pi-mcp-extension"]},
"piExtension": {"enum": ["builtin", "pi-mcp-adapter", "pi-mcp-extension"], "deprecated": true, "description": "Ignored since 0.23.0: Pi always uses its built-in MCP. Saving the config drops it."},
"transport": {"enum": ["stdio", "streamable-http"]},
"command": {"type": "string", "minLength": 1},
"args": {"type": "array", "items": {"type": "string"}},
@@ -56,12 +67,13 @@
"bearerToken": {"$ref": "#/$defs/reference"},
"targets": {"$ref": "#/$defs/targets"},
"directTools": {"$ref": "#/$defs/directTools"},
"piOptions": {"type": "object", "description": "Pi built-in or pi-mcp-adapter per-server options. Known built-in fields are validated; unknown fields are preserved."},
"piOptionsPrune": {"type": "boolean", "description": "Remove cleared Pi options only if Skillshare owns their unchanged values."},
"disabled": {"const": true, "description": "Project mode only: turn off a server that the Agent's global config defines. Supported by opencode, kilocode and pi with pi-mcp-adapter."}
"tools": {"$ref": "#/$defs/tools"},
"piOptions": {"type": "object", "description": "Pi built-in per-server options. Known built-in fields are validated; unknown fields are preserved. pi-mcp-adapter-only fields are refused: set tool lists in tools; exposure and toolExposure cannot be combined with tools."},
"piOptionsPrune": {"type": "boolean", "deprecated": true, "description": "Ignored since 0.23.0: sync always removes Pi options Skillshare wrote that are unchanged. Saving the config drops it."},
"disabled": {"const": true, "description": "Project mode only: turn off a server that the Agent's global config defines. Supported by claude, opencode and kilocode."}
},
"oneOf": [
{"required": ["disabled"], "not": {"anyOf": [{"required": ["directTools"]}, {"required": ["command"]}, {"required": ["url"]}, {"required": ["args"]}, {"required": ["env"]}, {"required": ["headers"]}, {"required": ["bearerToken"]}, {"required": ["transport"]}]}},
{"required": ["disabled"], "not": {"anyOf": [{"required": ["directTools"]}, {"required": ["tools"]}, {"required": ["command"]}, {"required": ["url"]}, {"required": ["args"]}, {"required": ["env"]}, {"required": ["headers"]}, {"required": ["bearerToken"]}, {"required": ["transport"]}]}},
{"required": ["command"], "not": {"anyOf": [{"required": ["disabled"]}, {"required": ["url"]}, {"required": ["headers"]}, {"required": ["bearerToken"]}]}, "properties": {"transport": {"const": "stdio"}}},
{"required": ["url"], "not": {"anyOf": [{"required": ["disabled"]}, {"required": ["command"]}, {"required": ["args"]}, {"required": ["env"]}]}, "properties": {"transport": {"const": "streamable-http"}}}
]
+1
View File
@@ -9,6 +9,7 @@
"allOf": [{"not": {"required": ["sources", "mcp"], "properties": {"sources": {"required": ["mcp"]}, "mcp": {"required": ["servers"]}}}}],
"properties": {
"mcp": {"$ref": "mcp.schema.json#/$defs/configuration"},
"hooks": {"$ref": "hooks.schema.json#/$defs/configuration"},
"sources": {
"type": "object",
"description": "Custom source directories for project resources. Each key overrides the default <project-dir>/{key}/ path. Relative paths resolve from the project root.",

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