Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

OK skill editor: author, install, version skills (PRD-6935) (#1662)

tim-inkeep72ecc9c8551a
diff --git a/.changeset/cowork-hidden-command.md b/.changeset/cowork-hidden-command.md
new file mode 100644
index 000000000..fa97a49f6
--- /dev/null
+++ b/.changeset/cowork-hidden-command.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Rename the `ok install-skill` CLI command to a deliberately hidden, unadvertised `ok cowork`. The old name implied an automatic install it never performed — it builds the `openknowledge.skill` bundle and opens the Claude Desktop App for a manual upload (the only path to the separate Skills list Claude Chat & Cowork read, which `ok init`'s editor wiring can't reach). The command is now registered hidden (absent from `ok --help`), and `ok init` no longer pushes a hint toward it — it is a power-user escape hatch discovered pull-only via the Open Knowledge skill. The underlying bundle build and the `POST /api/install-skill` route are unchanged.
diff --git a/.changeset/fix-reinstall-pack-skill.md b/.changeset/fix-reinstall-pack-skill.md
new file mode 100644
index 000000000..9fef3b5af
--- /dev/null
+++ b/.changeset/fix-reinstall-pack-skill.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge": patch
+---
+
+Fix a starter-pack skill being unable to reinstall after a user uninstalls it. Pack skills are named `open-knowledge-pack-<packId>`, which sits under the `open-knowledge*` prefix reserved for OK's shipped skills. The seed installs them by copying directly, but a user-triggered reinstall re-runs the install validation, which rejected the reserved prefix and failed with "uses the reserved `open-knowledge*` prefix." The install guard now exempts the `open-knowledge-pack-*` namespace (OK's own shipped pack content), so reinstalling a pack skill works while user-authored `open-knowledge*` names stay blocked.
diff --git a/.changeset/fix-skill-graph-flicker-and-seed-safety.md b/.changeset/fix-skill-graph-flicker-and-seed-safety.md
new file mode 100644
index 000000000..b61172824
--- /dev/null
+++ b/.changeset/fix-skill-graph-flicker-and-seed-safety.md
@@ -0,0 +1,13 @@
+---
+"@inkeep/open-knowledge-core": patch
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge": patch
+---
+
+Fix skill reference graph links, the skills-dock flicker, and re-seed data safety.
+
+- A `[[references/<name>]]` wiki-link inside a skill's SKILL.md now resolves to that skill's bundle reference doc and forms a real backlink and graph edge. Previously the natural wiki form silently mis-resolved to a phantom top-level doc (only an absolute `[[.ok/skills/<name>/references/<name>]]` or a markdown link resolved), so a skill's references never appeared as links or backlinks. Adds a shared `resolveSkillBundleWikiTarget` helper used by the link index, and updates the write-skill guidance to author references as wiki-links (a backtick code path renders dead and never joins the graph).
+- The skills sidebar no longer flickers (list flashing empty then repopulating) on every skill create/edit/install/move. The list now revalidates in place instead of resetting to a loading state.
+- Re-running seed no longer overwrites a user-edited starter-pack skill. `installPackSkill` only authors the source when it does not already exist; an existing skill keeps its edits and shadow history while still refreshing its editor projection and install marker.
+- `POST /api/create-page` now rejects a path inside `.ok/` (or a managed-artifact doc name), so a page can no longer be created inside the indexed `.ok/skills/**` namespace and bypass skill-schema validation.
+- The `install` MCP tool description now lists OpenCode (`.opencode/skills/`) as a valid projection target, matching the schema.
diff --git a/.changeset/fix-skill-move-bundle-and-tabs.md b/.changeset/fix-skill-move-bundle-and-tabs.md
new file mode 100644
index 000000000..703b14ce0
--- /dev/null
+++ b/.changeset/fix-skill-move-bundle-and-tabs.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge": patch
+---
+
+Fix skill move/scope-change losing bundle files and dropping references from the link graph. A cross-scope skill move (global ↔ project) copied only `SKILL.md` and then deleted the source, silently losing every `references/**` and `scripts/**` file; both the MCP `move` verb and the editor's scope switch now copy the full bundle through the per-type write path (project `.md` references rejoin the backlink/tag graph; global references and all scripts are written fs-direct) before deleting the source, aborting without data loss on any partial-copy failure. A same-scope skill rename now re-indexes the relocated `SKILL.md` and its `.md` references into the live backlink/tag graph (previously they sat unindexed until a manual rescan). The editor also reconciles open skill tabs after a server-side move — a tab whose skill moved scopes retargets to the new location, and one whose skill was deleted closes — so no stale phantom tab is left behind. Also adds the new skill write routes to the mutating-route CSRF guard and the conflict gate.
diff --git a/.changeset/global-skill-graph-participation.md b/.changeset/global-skill-graph-participation.md
new file mode 100644
index 000000000..82be8937a
--- /dev/null
+++ b/.changeset/global-skill-graph-participation.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge-core": patch
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge": patch
+---
+
+Show global skill references in the link graph, connected to their skill.
+
+A global skill's `SKILL.md` and its `references/*.md` now appear as connected nodes in the link graph, the same as a project skill — even though global skills live in `~/.ok/skills/` outside the project content tree. Global bundle docs are ingested as graph nodes (at boot, on branch switch, and live via the managed-artifact watcher) and connected by structural edges derived from the bundle path. The connection is within-bundle only: a global skill is never linked into a specific project's knowledge base (a global reference's wiki-links are not followed), and its cluster is visible from every project since global skills are shared across all of them. Clicking a global reference node in the graph opens it read-only through the scope-aware skill-file viewer.
diff --git a/.changeset/skill-authoring-ux.md b/.changeset/skill-authoring-ux.md
new file mode 100644
index 000000000..8f5d3cb77
--- /dev/null
+++ b/.changeset/skill-authoring-ux.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge-app": patch
+---
+
+Skill authoring UX fixes. Deleting a personal (Global) skill and then re-creating one with the same name now persists reliably — previously a same-name re-create that authored identical content was silently dropped because the managed-artifact last-known-good cache was not evicted on delete, so the re-create was classed a no-op and never re-landed on disk. Writing a raw `document` under `.ok/skills/…` (or `.ok/templates/…`) now returns a path-aware error pointing at the correct `skill` (or `template`) target instead of a generic rejection, and the `write` / `edit` tool descriptions and the project skill now name all five write targets so an agent reaches for `skill` instead of defaulting to a plain document. Skill scope is labeled "Global Skill" / "Project Skill" (the word "scope" is gone from the UI) with a colored level toggle.
diff --git a/.changeset/skill-bundle-graph-and-file-viewing.md b/.changeset/skill-bundle-graph-and-file-viewing.md
new file mode 100644
index 000000000..569fb7f0b
--- /dev/null
+++ b/.changeset/skill-bundle-graph-and-file-viewing.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge-core": patch
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge": patch
+---
+
+Make a project skill's references show up connected in the graph, and let global skill bundle files be opened.
+
+- A project skill's `SKILL.md` and its `references/*.md` now appear connected in the link graph automatically, whether the body references them as `[[wiki-links]]` or as plain backticked paths. The references were already graph nodes; this adds the structural edges between a skill's `SKILL.md` and its own reference docs, derived strictly from the bundle path (`.ok/skills/<name>/`). Regular documents and folders are unaffected — co-membership in an ordinary folder does not create edges. Authored wiki-links keep working and are not double-drawn.
+- Clicking a global skill's reference or script in the Skills sidebar now opens it (read-only) instead of failing with "could not be found." Global skill bundle files live in `~/.ok/skills/` outside the project content tree, so they are now read through the scope-aware skill-file endpoint rather than as a project content-dir asset. A fetch failure shows a terminal state instead of a perpetual loading spinner.
+- The write-skill guidance is updated: project skill references auto-connect in the graph regardless of how they are referenced, a wiki-link is only needed for a clickable inline link, and global skill references should stay plain backtick paths since global references are not graph docs.
diff --git a/.changeset/skill-editor-url-addressable.md b/.changeset/skill-editor-url-addressable.md
new file mode 100644
index 000000000..7d39a5d41
--- /dev/null
+++ b/.changeset/skill-editor-url-addressable.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge-app": patch
+---
+
+Make skills URL-addressable in the editor and resolvable by the MCP, so a skill behaves like a document. The skill editor now has its own route (`#/__skill__/<scope>/<name>`): opening a skill updates the URL, so it is reload-stable, shareable, and deep-linkable; loading a skill URL opens straight into the editor with the file sidebar visible. Closing routes the URL back to the document underneath, and navigating to a document dismisses the skill editor. The `write` and `edit` MCP tools now ride a route-only `previewUrl` for skills (the same preview envelope documents already carry), and the `preview_url` tool accepts a `{ skill }` target, so an agent that authors a skill in Open Knowledge can hand back a URL that opens it in the running editor.
+
+Creating a skill now opens the editor directly instead of a modal: the "New skill" action drops a draft into the main editor pane with an inline Project/Personal scope toggle in its Properties panel. Filling in a name and description enables Create; once it commits, the editor re-points to the saved skill and switches into the same autosave edit experience, so authoring a new skill and editing an existing one are one continuous surface.
diff --git a/.changeset/skill-file-rendered-markdown.md b/.changeset/skill-file-rendered-markdown.md
new file mode 100644
index 000000000..027628e0f
--- /dev/null
+++ b/.changeset/skill-file-rendered-markdown.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Render a global skill's `.md`/`.mdx` references as formatted read-only markdown instead of raw source.
+
+Opening a global skill bundle file in the Skills sidebar previously showed the raw markdown source. Markdown references now render formatted (headings, bold, lists) read-only — the same rendering the editor uses (via the shared extension set, with no editing and no collaboration binding). Scripts and other non-markdown files keep the source view.
diff --git a/.changeset/skill-graph-node-styling-and-review-polish.md b/.changeset/skill-graph-node-styling-and-review-polish.md
new file mode 100644
index 000000000..f9fd14d6e
--- /dev/null
+++ b/.changeset/skill-graph-node-styling-and-review-polish.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge": patch
+---
+
+Render skill reference graph nodes as resolved, and address review follow-ups.
+
+- A skill-bundle reference node in the link graph now renders as a normal resolved node instead of the dashed-red "missing" treatment. The node always resolved to a real, openable read-only viewer (clicking it works), but it was misclassified as a missing link target, so it read as broken.
+- A failed skill move no longer turns into a 500 when the post-rename graph re-index throws — the rename already succeeded, so a re-index failure is logged and swallowed.
+- The skills-list handler now logs when `readdirSync` fails instead of silently returning an empty list, and the bundle-file path classifier rejects NUL bytes for parity with its sibling validators.
+- The starter-pack update dialog and toasts show the skill's display name instead of its raw internal id, and the skill menu's update action reads as an imperative ("Update skill").
diff --git a/.changeset/skills-templates-editor-tabs.md b/.changeset/skills-templates-editor-tabs.md
new file mode 100644
index 000000000..dec03482f
--- /dev/null
+++ b/.changeset/skills-templates-editor-tabs.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-app": minor
+---
+
+Edit skills and templates as first-class editor tabs instead of separate full-screen overlays. Opening a skill or template (from the sidebar Skills section or Settings) now opens it as a normal tab through the same editor pipeline documents use — with the file sidebar, tab bar, property panel, and version history. Skills additionally carry Install / Reinstall / Uninstall + history controls in the per-document toolbar. Skill and template tabs resolve as real documents everywhere (navigation, hash round-trip, graph/links), and a doc that links to a skill/template by its `.ok/skills/<name>/SKILL` or `.ok/templates/<name>` file path now opens the artifact editor instead of offering to create a missing page.
diff --git a/.changeset/skills-templates-link-index.md b/.changeset/skills-templates-link-index.md
new file mode 100644
index 000000000..1b864d8dd
--- /dev/null
+++ b/.changeset/skills-templates-link-index.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-app": minor
+---
+
+Skills and templates now participate in the link / backlink / graph index like documents, while staying hidden from the file tree. A document that links to a skill or template by its `.ok/skills/<name>/SKILL` or `<folder>/.ok/templates/<name>` file path resolves to the artifact identity, so the link connects to the skill/template entity (backlinks both directions) instead of a dangling file path. Editing a skill or template re-derives its own outgoing links. The file-tree exclusion is unchanged — they remain hidden from the tree.
diff --git a/packages/app/package.json b/packages/app/package.json
index 8d79eeaa6..d6257709b 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -18,6 +18,8 @@
"test:dom": "bash scripts/run-test-dom.sh",
"check": "tsc --noEmit && biome check . && bun run test && bun run test:dom && bun run test:integration && bun run test:conversion",
"test:integration": "bun test --timeout 30000 tests/integration/ tests/meta/ tests/lint-plugins/ --path-ignore-patterns=per-session-um-perf",
+ "test:integration:shard1": "bun test --timeout 30000 tests/integration/ tests/meta/ tests/lint-plugins/ --path-ignore-patterns=per-session-um-perf --shard=1/2",
+ "test:integration:shard2": "bun test --timeout 30000 tests/integration/ tests/meta/ tests/lint-plugins/ --path-ignore-patterns=per-session-um-perf --shard=2/2",
"test:perf:sessions": "bun test tests/integration/per-session-um-perf.test.ts --timeout 60000",
"test:conversion": "bun test tests/conversion/",
"test:stress:api": "bun run tests/stress/stress-api.ts",
@@ -42,7 +44,7 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "430 kB",
+ "limit": "450 kB",
"gzip": true,
"running": false
},
@@ -56,7 +58,7 @@
{
"name": "main CSS (gzipped)",
"path": "dist/assets/index-*.css",
- "limit": "51 kB",
+ "limit": "52 kB",
"gzip": true,
"running": false
}
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index 0c68ae9fd..f2ea683fe 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -56,6 +56,8 @@ mock.module('@/editor/DocumentContext', () => ({
clearTarget: clearTargetMock,
syncOpenTabsWithKnownTargets: syncOpenTabsWithKnownTargetsMock,
tabSessionLoaded,
+ openTabs: [],
+ closeDocument: () => {},
}),
useDocumentTransition: () => ({
openTargetTransition: openTargetTransitionMock,
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 106c3ce08..5e9660674 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -29,9 +29,15 @@ import {
useDocumentContext,
useDocumentTransition,
} from '@/editor/DocumentContext';
+import { useReconcileSkillTabs } from '@/hooks/use-reconcile-skill-tabs';
import { fetchApiConfig } from '@/lib/api-config';
import { ConfigProvider } from '@/lib/config-provider';
-import { assetPathFromHash, docNameFromHash, isContentRootHash } from '@/lib/doc-hash';
+import {
+ assetPathFromHash,
+ docNameFromHash,
+ isContentRootHash,
+ skillFileFromHash,
+} from '@/lib/doc-hash';
import { mark, ProfilerBoundary } from '@/lib/perf';
import { SingleFileModeProvider, useSingleFileMode } from '@/lib/single-file-mode';
import { isSettingsShortcut, SETTINGS_OPEN_HASH } from '@/lib/use-settings-route';
@@ -64,6 +70,7 @@ function knownTargetsSignature(
function NavigationHandler() {
const { clearTarget, syncOpenTabsWithKnownTargets, tabSessionLoaded } = useDocumentContext();
const { openTargetTransition } = useDocumentTransition();
+ useReconcileSkillTabs();
const { assetPaths, folderPaths, loading, pageMeta, pages, pagesBySlug, pagesByBasename } =
usePageList();
const lastSyncedTargetsSignatureRef = useRef<string | null>(null);
@@ -109,6 +116,18 @@ function NavigationHandler() {
});
return;
}
+ const skillFile = skillFileFromHash(window.location.hash);
+ if (skillFile) {
+ mark('ok/nav/hash-change', { docName: null, kind: 'skill-file' });
+ openTargetTransition({
+ kind: 'skill-file',
+ target: `${skillFile.scope}/${skillFile.name}/${skillFile.path}`,
+ scope: skillFile.scope,
+ name: skillFile.name,
+ path: skillFile.path,
+ });
+ return;
+ }
if (isContentRootHash(window.location.hash)) {
mark('ok/nav/hash-change', { docName: null, kind: 'folder' });
openTargetTransition({ kind: 'folder', target: '', folderPath: '' });
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index d7e61a226..d13639d33 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -34,6 +34,7 @@
* (invalidate + nav), or (c) Activity eviction from the MRU mount list.
*/
+import { isManagedArtifactDocName } from '@inkeep/open-knowledge-core';
import { t } from '@lingui/core/macro';
import { Loader2, RefreshCw } from 'lucide-react';
import {
@@ -53,6 +54,7 @@ import { clearMountId, getMountId, setMountId } from '@/editor/mount-id-registry
import type { ServerRestartRecoveryState } from '@/editor/provider-pool';
import { TiptapEditor } from '@/editor/TiptapEditor';
import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
+import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
import { mark, ProfilerBoundary } from '@/lib/perf';
import { readNumericOverride } from '@/lib/perf/env-override';
import { DiffViewBoundary } from './DiffViewBoundary';
@@ -64,6 +66,10 @@ import { usePageList } from './PageListContext';
import { PropertyPanel } from './PropertyPanel';
import { Button } from './ui/button';
+const ManagedArtifactProperties = lazy(async () => ({
+ default: (await import('./ManagedArtifactProperties')).ManagedArtifactProperties,
+}));
+
export const LARGE_DOC_CHAR_THRESHOLD = readNumericOverride('LARGE_DOC_CHAR_THRESHOLD', 500_000);
interface EditorMountGateArgs {
@@ -290,7 +296,9 @@ function EditorActivityPoolInner({
isActive={entry.docName === activeDocName}
isSourceMode={isSourceMode}
editorPlaceholder={editorPlaceholder}
- isNewDoc={!loading && !pages.has(entry.docName)}
+ isNewDoc={
+ !loading && !pages.has(entry.docName) && !isManagedArtifactDocName(entry.docName)
+ }
previousDocName={previousDocName}
onNavigateBack={onNavigateBack}
onRecycle={onRecycle}
@@ -652,21 +660,29 @@ function ActivityEntry({
visible editor to 8000px and creating bottom whitespace on
short docs — see globals.css §.ok-mode-hidden). */
<div className="flex h-full flex-col">
- {/* PageHeader: cover banner + page icon, decorative-only
- chrome above the property panel. Reads `cover` + `icon`
- from the same frontmatter binding PropertyPanel uses.
- Returns null when neither is set, so docs that don't
- opt in pay zero layout cost. Hidden in source mode
- (CodeMirror surfaces the raw YAML directly). */}
- {!isSourceMode && <PageHeader provider={entry.provider} />}
- {/* PropertyPanel: top-of-doc frontmatter table, sibling to the
- dual-editor stack inside DocumentBoundary so it shares the
- same suspend/error scope and remounts cleanly on doc switch.
- Hidden in source mode (CodeMirror surfaces raw YAML).
- The panel itself returns null when the doc has no
- frontmatter — empty-state shows the toolbar trigger in
- EditorHeader instead. */}
- {!isSourceMode && <PropertyPanel provider={entry.provider} />}
+ {/* Property region (WYSIWYG only — source mode surfaces the
+ raw YAML directly in CodeMirror). Managed-artifact docs
+ (skills/templates) render their own identity panel in
+ place of the document PageHeader + PropertyPanel: `name`
+ (and a skill's `scope`) are identity, not free-form
+ frontmatter, and they have no cover/icon. Regular docs get
+ PageHeader (decorative cover+icon, null when unset) +
+ PropertyPanel (frontmatter table, null when empty). */}
+ {!isSourceMode &&
+ (isManagedArtifactDocName(entry.docName) ||
+ parseProjectSkillContentDocName(entry.docName) ? (
+ <Suspense fallback={null}>
+ <ManagedArtifactProperties
+ docName={entry.docName}
+ provider={entry.provider}
+ />
+ </Suspense>
+ ) : (
+ <>
+ <PageHeader provider={entry.provider} />
+ <PropertyPanel provider={entry.provider} />
+ </>
+ ))}
<div className="relative flex-1">
{gate.renderSource ? (
<div className={isSourceMode ? 'h-full' : 'ok-mode-hidden h-full'}>
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 3133cdef8..764179907 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -23,6 +23,7 @@ import { FolderOverview } from '@/components/FolderOverview';
import { LargeFileEditorState } from '@/components/LargeFileEditorState';
import { MountStalledAffordance } from '@/components/MountStalledAffordance';
import { PropertyProvider, useProperties } from '@/components/PropertyContext';
+import { SkillFileViewer } from '@/components/SkillFileViewer';
import { SettingsDialogShell } from '@/components/settings/SettingsDialogShell';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
import { useDocumentContext, useDocumentTransition } from '@/editor/DocumentContext';
@@ -378,6 +379,15 @@ function EditorAreaInner({
mediaKind={activeTarget.mediaKind}
/>
);
+ } else if (activeTarget?.kind === 'skill-file') {
+ viewContent = (
+ <SkillFileViewer
+ key={`${activeTarget.scope}/${activeTarget.name}/${activeTarget.path}`}
+ scope={activeTarget.scope}
+ name={activeTarget.name}
+ path={activeTarget.path}
+ />
+ );
} else if (!activeProvider || !activeDocName) {
const hashDoc = typeof window !== 'undefined' ? docNameFromHash(window.location.hash) : null;
if (hashDoc !== null) {
diff --git a/packages/app/src/components/EditorBreadcrumb.tsx b/packages/app/src/components/EditorBreadcrumb.tsx
index bebc7e52e..f5e64c68e 100644
--- a/packages/app/src/components/EditorBreadcrumb.tsx
+++ b/packages/app/src/components/EditorBreadcrumb.tsx
@@ -1,3 +1,4 @@
+import { parseManagedArtifactName } from '@inkeep/open-knowledge-core';
import { MoreHorizontalIcon } from 'lucide-react';
import { Fragment } from 'react';
import {
@@ -25,9 +26,12 @@ type BreadcrumbNode =
export function EditorBreadcrumb({ docName, className }: EditorBreadcrumbProps) {
if (!docName) return null;
- const { prefix } = tabParts(docName, '');
- if (!prefix) return null;
- const segments = prefix.replace(/\/$/, '').split('/').filter(Boolean);
+ const managed = parseManagedArtifactName(docName);
+ const segments = managed
+ ? managed.kind === 'template'
+ ? managed.folder.split('/').filter(Boolean)
+ : []
+ : tabParts(docName, '').prefix.replace(/\/$/, '').split('/').filter(Boolean);
if (segments.length === 0) return null;
const segmentNode = (value: string, absoluteIndex: number): BreadcrumbNode => ({
diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsx
index f54e8d85b..d190b73b3 100644
--- a/packages/app/src/components/EditorHeader.tsx
+++ b/packages/app/src/components/EditorHeader.tsx
@@ -1,3 +1,4 @@
+import { parseManagedArtifactName } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { Search } from 'lucide-react';
import { useState } from 'react';
@@ -32,6 +33,7 @@ interface EditorHeaderProps {
export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHeaderProps) {
const { t } = useLingui();
const { activeDocName, activeTarget } = useDocumentContext();
+ const managedArtifact = activeDocName ? parseManagedArtifactName(activeDocName) : null;
const { state: sidebarState, isDraggingRail } = useSidebar();
const singleFile = useSingleFileMode();
const sidebarShortcut = formatShortcut('toggle-files-sidebar');
@@ -41,7 +43,7 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
if (activeTarget?.kind === 'folder') {
return buildFolderShareInput(activeTarget.folderPath);
}
- if (activeDocName) {
+ if (activeDocName && !managedArtifact) {
return buildDocShareInput(activeDocName);
}
return null;
diff --git a/packages/app/src/components/EditorModeToggle.tsx b/packages/app/src/components/EditorModeToggle.tsx
new file mode 100644
index 000000000..2d10a24b2
--- /dev/null
+++ b/packages/app/src/components/EditorModeToggle.tsx
@@ -0,0 +1,75 @@
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import type { EditorModeValue } from '@/editor/use-editor-mode';
+import { Markdown } from './icons/markdown';
+import { Textbox } from './icons/textbox';
+
+interface EditorModeToggleProps {
+ isSourceMode: boolean;
+ onModeChange: (mode: EditorModeValue) => void;
+ sourceDisabled?: boolean;
+}
+
+export function EditorModeToggle({
+ isSourceMode,
+ onModeChange,
+ sourceDisabled = false,
+}: EditorModeToggleProps) {
+ const { t } = useLingui();
+ return (
+ <ToggleGroup
+ type="single"
+ value={isSourceMode ? 'source' : 'wysiwyg'}
+ onValueChange={(v: EditorModeValue | '') => {
+ if (v) onModeChange(v);
+ }}
+ aria-label={t`Editor mode`}
+ variant="segmented"
+ size="sm"
+ spacing={1}
+ className="shrink-0 bg-muted p-0.5 data-[size=sm]:rounded-[10px]"
+ >
+ <Tooltip>
+ <ToggleGroupItem
+ value="wysiwyg"
+ aria-label={t`Visual editor`}
+ className="size-7 px-0 dark:data-[state=on]:bg-foreground/15"
+ asChild
+ >
+ <TooltipTrigger>
+ <Textbox className="size-4" />
+ </TooltipTrigger>
+ </ToggleGroupItem>
+ <TooltipContent side="bottom">
+ <Trans>Visual</Trans>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* Disabled <button> doesn't fire pointer events; wrap so the tooltip still triggers. */}
+ <div>
+ <ToggleGroupItem
+ value="source"
+ aria-label={t`Markdown source`}
+ disabled={sourceDisabled}
+ className="size-7 px-0 dark:data-[state=on]:bg-foreground/15"
+ >
+ <Markdown className="size-4" />
+ </ToggleGroupItem>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {sourceDisabled ? (
+ <Trans>
+ Source mode requires a live connection — your edits are saved and will appear when you
+ reconnect.
+ </Trans>
+ ) : (
+ <Trans>Markdown</Trans>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ </ToggleGroup>
+ );
+}
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index 88871d88a..2b0c2188b 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -750,8 +750,9 @@ export function EditorTabs() {
);
}
- if (tab.kind === 'asset') {
- const { baseName, label, prefix } = tabParts(tab.assetPath, '');
+ if (tab.kind === 'asset' || tab.kind === 'skill-file') {
+ const labelPath = tab.kind === 'asset' ? tab.assetPath : tab.path;
+ const { baseName, label, prefix } = tabParts(labelPath, '');
const accessibleLabel = `${prefix}${label}`;
return (
<EditorTabContextMenu
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index 2ae64d5b4..f4c72251e 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -1,13 +1,18 @@
+import { parseManagedArtifactName, type SkillScope } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { ListPlus, PanelRightClose, PanelRightOpen } from 'lucide-react';
+import { lazy, Suspense } from 'react';
import { Button } from '@/components/ui/button.tsx';
-import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import type { EditorModeValue } from '@/editor/use-editor-mode.ts';
import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
+import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
import { EditorBreadcrumb } from './EditorBreadcrumb';
-import { Markdown } from './icons/markdown';
-import { Textbox } from './icons/textbox';
+import { EditorModeToggle } from './EditorModeToggle';
+
+const SkillEditorActions = lazy(async () => ({
+ default: (await import('./SkillEditorActions')).SkillEditorActions,
+}));
interface EditorToolbarProps {
activeDocName: string | null;
@@ -33,6 +38,14 @@ export function EditorToolbar({
const { t } = useLingui();
const panelShortcut = formatShortcut('toggle-document-panel');
const panelShortcutLabel = formatShortcutLabel('toggle-document-panel');
+ const managed = activeDocName ? parseManagedArtifactName(activeDocName) : null;
+ const projectSkillName = activeDocName ? parseProjectSkillContentDocName(activeDocName) : null;
+ const activeSkill: { scope: SkillScope; name: string } | null =
+ managed?.kind === 'skill'
+ ? { scope: managed.scope, name: managed.name }
+ : projectSkillName
+ ? { scope: 'project', name: projectSkillName }
+ : null;
return (
<div data-testid="editor-toolbar" className="pointer-events-none absolute inset-x-0 top-0 z-10">
{/*
@@ -52,62 +65,17 @@ export function EditorToolbar({
Future siblings dropped into this cell must follow the same rule.
*/}
<div className="pointer-events-auto flex min-w-0 items-center">
- <EditorBreadcrumb docName={activeDocName} />
+ {/* 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} />}
</div>
<div className="pointer-events-auto flex justify-center">
- <ToggleGroup
- type="single"
- value={isSourceMode ? 'source' : 'wysiwyg'}
- onValueChange={(v: EditorModeValue | '') => {
- if (v) onModeChange(v);
- }}
- aria-label={t`Editor mode`}
- variant="segmented"
- size="sm"
- spacing={1}
- className="shrink-0 data-[size=sm]:rounded-[10px] bg-muted p-0.5"
- >
- <Tooltip>
- <ToggleGroupItem
- value="wysiwyg"
- aria-label={t`Visual editor`}
- className="size-7 px-0 dark:data-[state=on]:bg-foreground/15"
- asChild
- >
- <TooltipTrigger>
- <Textbox className="size-4" />
- </TooltipTrigger>
- </ToggleGroupItem>
- <TooltipContent side="bottom">
- <Trans>Visual</Trans>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- {/* Disabled <button> doesn't fire pointer events; wrap so the tooltip still triggers. */}
- <div>
- <ToggleGroupItem
- value="source"
- aria-label={t`Markdown source`}
- disabled={sourceDisabled}
- className="size-7 px-0 dark:data-[state=on]:bg-foreground/15"
- >
- <Markdown className="size-4" />
- </ToggleGroupItem>
- </div>
- </TooltipTrigger>
- <TooltipContent side="bottom">
- {sourceDisabled ? (
- <Trans>
- Source mode requires a live connection — your edits are saved and will appear
- when you reconnect.
- </Trans>
- ) : (
- <Trans>Markdown</Trans>
- )}
- </TooltipContent>
- </Tooltip>
- </ToggleGroup>
+ <EditorModeToggle
+ isSourceMode={isSourceMode}
+ onModeChange={onModeChange}
+ sourceDisabled={sourceDisabled}
+ />
</div>
{/*
Third column kept empty so the mode toggle stays centered in the
@@ -123,6 +91,11 @@ export function EditorToolbar({
re-enables clicks under the toolbar's `pointer-events-none` root.
*/}
<div className="pointer-events-auto absolute top-0 right-0 flex items-center justify-end gap-1 py-2 pr-2">
+ {activeSkill ? (
+ <Suspense fallback={null}>
+ <SkillEditorActions scope={activeSkill.scope} name={activeSkill.name} />
+ </Suspense>
+ ) : null}
{showAddPropertyButton && (
<Tooltip>
<Button
diff --git a/packages/app/src/components/FileSidebar.dom.test.tsx b/packages/app/src/components/FileSidebar.dom.test.tsx
index 723526bd8..c25f9b7e1 100644
--- a/packages/app/src/components/FileSidebar.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.dom.test.tsx
@@ -154,6 +154,10 @@ mock.module('@/components/ConflictsSection', () => ({
ConflictsSection: () => <div data-testid="conflicts-section" />,
}));
+mock.module('@/components/SkillsSidebarSection', () => ({
+ SkillsSidebarSection: () => <div data-testid="skills-sidebar-section" />,
+}));
+
mock.module('@/components/ProjectSwitcher', () => ({
ProjectSwitcher: () => <button type="button">Project switcher</button>,
}));
@@ -294,6 +298,9 @@ mock.module('@/components/ui/sidebar', () => ({
),
SidebarMenu: ElementPassThrough,
SidebarMenuItem: ElementPassThrough,
+ SidebarGroup: ElementPassThrough,
+ SidebarGroupContent: ElementPassThrough,
+ SidebarGroupLabel: ElementPassThrough,
SidebarRail: ({ enableToggle }: { enableToggle?: boolean }) => (
<button data-enable-toggle={String(enableToggle)} data-testid="sidebar-rail" type="button" />
),
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 69403817b..baadb3e17 100644
--- a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
@@ -107,10 +107,17 @@ mock.module('@/components/ui/sidebar', () => ({
SidebarHeader: ElementPassThrough,
SidebarMenu: ElementPassThrough,
SidebarMenuItem: ElementPassThrough,
+ SidebarGroup: ElementPassThrough,
+ SidebarGroupContent: ElementPassThrough,
+ SidebarGroupLabel: ElementPassThrough,
SidebarRail: () => null,
useSidebar: () => ({ state: 'expanded', toggleSidebar: toggleSidebarMock }),
}));
+mock.module('@/components/SkillsSidebarSection', () => ({
+ SkillsSidebarSection: () => null,
+}));
+
mock.module('@/components/ui/context-menu', () => ({
ContextMenu: PassThrough,
ContextMenuCheckboxItem: Button,
diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsx
index bac5e025b..073c0115c 100644
--- a/packages/app/src/components/FileSidebar.tsx
+++ b/packages/app/src/components/FileSidebar.tsx
@@ -1,6 +1,7 @@
import { humanFormat } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import {
+ ChevronRight,
Copy,
FilePlus,
FolderOpen,
@@ -24,9 +25,11 @@ import {
import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
import { ProjectSwitcher } from '@/components/ProjectSwitcher';
import { onPillRenderError, SidebarSearchBar } from '@/components/SidebarSearchBar';
+import { SkillsSidebarSection } from '@/components/SkillsSidebarSection';
import { TemplateMenuRows } from '@/components/template-menu-rows';
import { UpdateNotices } from '@/components/UpdateNotices';
import { Button } from '@/components/ui/button';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import {
ContextMenu,
ContextMenuCheckboxItem,
@@ -48,6 +51,8 @@ import {
Sidebar,
SidebarContent,
SidebarFooter,
+ SidebarGroup,
+ SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuItem,
@@ -121,6 +126,7 @@ const ToolbarButton: FC<ToolbarButtonProps> = ({ icon: Icon, label, ...props })
function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
const { t } = useLingui();
const [tree, setTree] = useState<FileTreeHandle | null>(null);
+ const [treeContentHeight, setTreeContentHeight] = useState<number | null>(null);
const { activeDocName, activeTarget } = useDocumentContext();
const baseCreateDir =
@@ -178,6 +184,10 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
const workspace = useWorkspace();
+ const projectName =
+ bridge?.config?.projectName ||
+ workspace?.contentDir.split('/').filter(Boolean).pop() ||
+ t`Files`;
const handoffInstallStates = useInstalledAgents().states;
const { dispatch: dispatchHandoff } = useHandoffDispatch();
const emptySpaceHandoffInput = buildProjectScopedHandoffInput({ workspace });
@@ -468,7 +478,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
<DropdownMenuTrigger asChild>
<ToolbarButton icon={ListCollapse} label={t`Tree view options`} />
</DropdownMenuTrigger>
- <DropdownMenuContent align="end">
+ <DropdownMenuContent align="end" className="min-w-52">
{!allExpanded ? (
<DropdownMenuItem onSelect={() => tree?.expandAll()}>
<UnfoldVertical aria-hidden="true" />
@@ -494,7 +504,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
<DropdownMenuTrigger asChild>
<ToolbarButton icon={FilePlus} label={t`New from template`} />
</DropdownMenuTrigger>
- <DropdownMenuContent align="end">
+ <DropdownMenuContent align="end" className="min-w-52">
<TemplateMenuRows
parentDir={initialCreateDir}
onSelectTemplate={(templateName) =>
@@ -582,7 +592,49 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
</div>
<SidebarContent>
<ConflictsSection />
- <FileTree ref={setTree} />
+ {/* Project files, under a collapsible header named for the project
+ — a true peer to the Skills section below 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. */}
+ <SidebarGroup className="min-h-0">
+ <SidebarGroupLabel asChild className="shrink-0">
+ <CollapsibleTrigger className="flex w-full 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>
+ </SidebarGroupLabel>
+ <CollapsibleContent
+ className="flex max-h-[70vh] flex-col overflow-hidden"
+ style={{
+ height: treeContentHeight != null ? `${treeContentHeight}px` : '50vh',
+ }}
+ >
+ <FileTree ref={setTree} onContentHeightChange={setTreeContentHeight} />
+ </CollapsibleContent>
+ </SidebarGroup>
+ </Collapsible>
+ <SkillsSidebarSection />
+ {/* 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
+ the creation target (New file / New folder then land at the
+ project root) and neutralizes the focused row's ring, exactly
+ like the old empty-tree-area click. Flex-grows to fill whatever
+ space the two sections leave; collapses to nothing (and the
+ sidebar scrolls) once they exceed the viewport. */}
+ <div
+ aria-hidden
+ data-sidebar-empty-deselect
+ className="min-h-8 flex-1 cursor-default"
+ onClick={() => tree?.clearCreationTarget()}
+ />
</SidebarContent>
<SidebarFooter className="px-0">
<UpdateNotices />
@@ -621,7 +673,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
/>
</div>
</ContextMenuTrigger>
- <ContextMenuContent>
+ <ContextMenuContent className="min-w-52">
{/*
* Empty-space menu — 11 items, 4 sections.
*
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 043700f66..8c5f46ee5 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -1002,6 +1002,7 @@ export interface FileTreeHandle {
collapseAll(): void;
getFolderState(): { folderCount: number; expandedCount: number };
isCreationTargetCleared(): boolean;
+ clearCreationTarget(): void;
subscribe(listener: () => void): () => void;
}
@@ -1046,7 +1047,13 @@ async function fetchShowAllDepth1Listing(
}
}
-export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
+export function FileTree({
+ ref,
+ onContentHeightChange,
+}: {
+ ref?: Ref<FileTreeHandle | null>;
+ onContentHeightChange?: (px: number) => void;
+}) {
const { t, i18n } = useLingui();
const {
activeDocName,
@@ -1957,6 +1964,47 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
treePathsSignature,
);
+ useEffect(() => {
+ if (!onContentHeightChange) return;
+ let raf = 0;
+ let attachRaf = 0;
+ const getList = () =>
+ (fileTreeHostRef.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;
+ const h = Number.parseFloat(list.style.height);
+ if (Number.isFinite(h)) onContentHeightChange(h);
+ };
+ 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, model]);
+
// biome-ignore lint/correctness/useExhaustiveDependencies: setCreationDirCleared is a stable state setter; baseActiveTreePath is the sole trigger.
useEffect(() => {
setCreationDirCleared(false);
@@ -2838,6 +2886,9 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
isCreationTargetCleared() {
return creationDirClearedRef.current;
},
+ clearCreationTarget() {
+ setCreationDirCleared(true);
+ },
subscribe(listener: () => void) {
handleListenersRef.current.add(listener);
const unsubscribeModel = model.subscribe(listener);
diff --git a/packages/app/src/components/GraphPanel.tsx b/packages/app/src/components/GraphPanel.tsx
index 3067dd523..30f4caa26 100644
--- a/packages/app/src/components/GraphPanel.tsx
+++ b/packages/app/src/components/GraphPanel.tsx
@@ -333,15 +333,19 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
const activeMode = isExpanded ? fullscreenMode : 'explore';
const showUrlNodes = isExpanded ? showUrlNodesFull : showUrlNodesDocked;
const setShowUrlNodes = isExpanded ? setShowUrlNodesFull : setShowUrlNodesDocked;
- const selectedDocDisplayState =
+ const selectedNodeIntent =
selectedNode?.kind === 'doc' && !pageListLoading
? resolveTargetNavigationIntent(selectedNode.docName, {
pages,
folderPaths,
pagesBySlug,
pagesByBasename,
- }).displayState
- : 'doc';
+ })
+ : null;
+ const selectedDocDisplayState = selectedNodeIntent?.displayState ?? 'doc';
+ const hashForSelectedNode = (
+ selection: Parameters<typeof getHashForGraphDocSelection>[0],
+ ): string => selectedNodeIntent?.hash ?? getHashForGraphDocSelection(selection);
const selectedNodeState =
selectedNode === null
? null
@@ -353,7 +357,7 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
actionLabel: t`Create page`,
secondaryLabel: selectedNode.docName,
onAction: () => {
- const hash = getHashForGraphDocSelection(selectedNode);
+ const hash = hashForSelectedNode(selectedNode);
setIsExpanded(false);
window.location.assign(hash);
},
@@ -366,7 +370,7 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
actionLabel: t`Open`,
secondaryLabel: selectedNode.docName,
onAction: () => {
- const hash = getHashForGraphDocSelection(selectedNode);
+ const hash = hashForSelectedNode(selectedNode);
setIsExpanded(false);
window.location.assign(hash);
},
@@ -379,7 +383,7 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
actionLabel: t`Open`,
secondaryLabel: selectedNode.docName,
onAction: () => {
- const hash = getHashForGraphDocSelection(selectedNode);
+ const hash = hashForSelectedNode(selectedNode);
setIsExpanded(false);
window.location.assign(hash);
},
diff --git a/packages/app/src/components/GraphView.tsx b/packages/app/src/components/GraphView.tsx
index 3bab8a3d8..63152eba2 100644
--- a/packages/app/src/components/GraphView.tsx
+++ b/packages/app/src/components/GraphView.tsx
@@ -638,6 +638,7 @@ export function GraphView({
? {
displayState: 'doc' as const,
hashDocName: node.docName,
+ hash: null,
}
: resolveTargetNavigationIntent(node.docName, {
pages,
@@ -1176,10 +1177,11 @@ export function GraphView({
if (node.docName) {
const navigationIntent = navigationIntentByNodeId.get(node.id);
window.location.assign(
- hashFromDocName(
- navigationIntent?.hashDocName ?? node.docName,
- node.anchor ?? null,
- ),
+ navigationIntent?.hash ??
+ hashFromDocName(
+ navigationIntent?.hashDocName ?? node.docName,
+ node.anchor ?? null,
+ ),
);
}
}}
diff --git a/packages/app/src/components/InstallInClaudeDesktopDialog.tsx b/packages/app/src/components/InstallInClaudeDesktopDialog.tsx
index 369e22670..d649a3604 100644
--- a/packages/app/src/components/InstallInClaudeDesktopDialog.tsx
+++ b/packages/app/src/components/InstallInClaudeDesktopDialog.tsx
@@ -15,7 +15,7 @@ import {
import { dispatchExternalLinkClick } from '@/lib/external-link';
import { cn } from '@/lib/utils';
-const INSTALL_COMMAND = 'npx @inkeep/open-knowledge install-skill';
+const INSTALL_COMMAND = 'npx @inkeep/open-knowledge cowork';
const DOCS_URL = 'https://openknowledge.ai/docs/integrations/claude-code';
interface InstallInClaudeDesktopDialogProps {
diff --git a/packages/app/src/components/LinksPanel.tsx b/packages/app/src/components/LinksPanel.tsx
index 66c6f8c78..4787d0460 100644
--- a/packages/app/src/components/LinksPanel.tsx
+++ b/packages/app/src/components/LinksPanel.tsx
@@ -4,6 +4,7 @@ import {
BacklinksSuccessSchema,
type ForwardLinkEntry,
ForwardLinksSuccessSchema,
+ isManagedArtifactDocName,
ProblemDetailsSchema,
} from '@inkeep/open-knowledge-core';
import { t } from '@lingui/core/macro';
@@ -243,7 +244,7 @@ function BacklinksSection({ docName }: { docName: string }) {
} = useQuery({
queryKey: ['backlinks', docName],
queryFn: () => fetchBacklinks(docName),
- enabled: !loading && pages.has(docName),
+ enabled: !loading && (pages.has(docName) || isManagedArtifactDocName(docName)),
});
const [expanded, setExpanded] = useState(false);
const [prevDocName, setPrevDocName] = useState(docName);
@@ -325,7 +326,7 @@ function ForwardLinksSection({ docName }: { docName: string }) {
} = useQuery({
queryKey: ['forward-links', docName],
queryFn: () => fetchForwardLinks(docName),
- enabled: !pagesLoading && pages.has(docName),
+ enabled: !pagesLoading && (pages.has(docName) || isManagedArtifactDocName(docName)),
});
const [creatingKey, setCreatingKey] = useState<string | null>(null);
const [expanded, setExpanded] = useState(false);
@@ -386,7 +387,10 @@ function ForwardLinksSection({ docName }: { docName: string }) {
const key = `doc:${link.docName}:${link.anchor ?? ''}`;
const navigateHashDocName =
linkIntent.kind === 'navigate' ? linkIntent.hashDocName : link.docName;
- const navigateHref = hashFromDocName(navigateHashDocName, link.anchor);
+ const navigateHref =
+ linkIntent.kind === 'navigate' && linkIntent.hash
+ ? linkIntent.hash
+ : hashFromDocName(navigateHashDocName, link.anchor);
if (unresolved && linkIntent.kind === 'create') {
const seed = {
diff --git a/packages/app/src/components/ManagedArtifactProperties.tsx b/packages/app/src/components/ManagedArtifactProperties.tsx
new file mode 100644
index 000000000..50fb7c08c
--- /dev/null
+++ b/packages/app/src/components/ManagedArtifactProperties.tsx
@@ -0,0 +1,227 @@
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { parseManagedArtifactName, type SkillScope } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { SkillProperties } from '@/components/SkillProperties';
+import { TemplateProperties } from '@/components/TemplateProperties';
+import { useDocumentContext } from '@/editor/DocumentContext';
+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';
+
+export function ManagedArtifactProperties({
+ docName,
+ provider,
+}: {
+ docName: string;
+ provider: HocuspocusProvider;
+}) {
+ const parsed = parseManagedArtifactName(docName);
+ if (parsed?.kind === 'skill') {
+ return (
+ <SkillPropertiesPanel
+ provider={provider}
+ docName={docName}
+ scope={parsed.scope}
+ name={parsed.name}
+ />
+ );
+ }
+ if (parsed?.kind === 'template') {
+ return (
+ <TemplatePropertiesPanel
+ provider={provider}
+ docName={docName}
+ folder={parsed.folder}
+ name={parsed.name}
+ />
+ );
+ }
+ const projectSkillName = parseProjectSkillContentDocName(docName);
+ if (projectSkillName) {
+ return (
+ <ProjectSkillPropertiesPanel provider={provider} docName={docName} name={projectSkillName} />
+ );
+ }
+ return null;
+}
+
+function useManagedArtifactRetarget(): (fromDocName: string, toDocName: string) => void {
+ const { closeDocument } = useDocumentContext();
+ return (fromDocName, toDocName) => {
+ if (fromDocName === toDocName) return;
+ openManagedArtifactTab(toDocName);
+ closeDocument(fromDocName);
+ };
+}
+
+function SkillPropertiesPanel({
+ provider,
+ docName,
+ scope,
+ name,
+}: {
+ provider: HocuspocusProvider;
+ docName: string;
+ scope: SkillScope;
+ name: string;
+}) {
+ 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 });
+ if (!result.ok) {
+ setRenameError(result.error);
+ toast.error(t`Couldn't rename skill: ${result.error}`);
+ return;
+ }
+ toast.success(t`Skill renamed`);
+ 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]}`);
+ }
+ retarget(docName, skillLiveDocName(next, name));
+ }
+
+ return (
+ <SkillProperties
+ provider={provider}
+ name={name}
+ onRename={handleRename}
+ nameError={renameError}
+ nameEditable={!movingScope}
+ scopeControl={{ scope, onScopeChange: handleScopeChange }}
+ />
+ );
+}
+
+function ProjectSkillPropertiesPanel({
+ provider,
+ docName,
+ name,
+}: {
+ provider: HocuspocusProvider;
+ docName: string;
+ name: string;
+}) {
+ 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: '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]}`);
+ }
+ retarget(docName, skillLiveDocName(next, name));
+ }
+
+ return (
+ <SkillProperties
+ provider={provider}
+ name={name}
+ onRename={handleRename}
+ nameError={renameError}
+ nameEditable={!movingScope}
+ scopeControl={{ scope: 'project', onScopeChange: handleScopeChange }}
+ />
+ );
+}
+
+function TemplatePropertiesPanel({
+ provider,
+ docName,
+ folder,
+ name,
+}: {
+ provider: HocuspocusProvider;
+ docName: string;
+ folder: string;
+ name: string;
+}) {
+ const { t } = useLingui();
+ const retarget = useManagedArtifactRetarget();
+ const [renameError, setRenameError] = useState<string | null>(null);
+
+ async function handleRename(next: string) {
+ setRenameError(null);
+ const result = await moveTemplate({
+ fromFolder: folder,
+ fromName: name,
+ toFolder: folder,
+ toName: next,
+ });
+ if (!result.ok) {
+ setRenameError(result.error);
+ toast.error(t`Couldn't rename template: ${result.error}`);
+ return;
+ }
+ toast.success(t`Template renamed`);
+ retarget(docName, templateDocName(folder, next));
+ }
+
+ return (
+ <TemplateProperties
+ provider={provider}
+ name={name}
+ folder={folder}
+ onRename={handleRename}
+ nameError={renameError}
+ />
+ );
+}
diff --git a/packages/app/src/components/NewSkillDialog.tsx b/packages/app/src/components/NewSkillDialog.tsx
new file mode 100644
index 000000000..a8ede3d1e
--- /dev/null
+++ b/packages/app/src/components/NewSkillDialog.tsx
@@ -0,0 +1,205 @@
+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 { 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 {
+ 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;
+ onCreated: (created: { scope: SkillScope; name: string }) => void;
+}
+
+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,
+ onOpenChange,
+ onCreated,
+}: {
+ defaultScope: SkillScope;
+ onOpenChange: (open: boolean) => void;
+ onCreated: (created: { scope: SkillScope; name: 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 trimmedName = name.trim();
+ const nameInvalid = trimmedName === '' || !SKILL_NAME_REGEX.test(trimmedName);
+ const nameCollides = !nameInvalid && nameSets[scope].has(trimmedName);
+ const canCreate = !creating && !nameInvalid && !nameCollides;
+
+ function sanitizeNameInput(text: string): string {
+ return text
+ .toLowerCase()
+ .replace(/[^a-z0-9-]+/g, '-')
+ .replace(/-{2,}/g, '-')
+ .replace(/^-+/, '');
+ }
+
+ 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}`);
+ return;
+ }
+ toast.success(t`Skill "${trimmedName}" created`);
+ onCreated({ scope, name: trimmedName });
+ onOpenChange(false);
+ }
+
+ 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>
+ </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>
+ </>
+ );
+}
diff --git a/packages/app/src/components/NewTemplateDialog.tsx b/packages/app/src/components/NewTemplateDialog.tsx
index 5b9ec362c..b1c2cc023 100644
--- a/packages/app/src/components/NewTemplateDialog.tsx
+++ b/packages/app/src/components/NewTemplateDialog.tsx
@@ -16,7 +16,7 @@ interface Props {
existingNames: ReadonlySet<string>;
open: boolean;
onOpenChange: (open: boolean) => void;
- onCreated: () => void;
+ onCreated: (createdName: string) => void;
}
const EMPTY_INITIAL = {
@@ -60,15 +60,15 @@ function Body({
folderPath: string;
existingNames: ReadonlySet<string>;
onOpenChange: (open: boolean) => void;
- onCreated: () => void;
+ onCreated: (createdName: string) => void;
}) {
const form = useTemplateForm({
mode: 'create',
folderPath,
initial: EMPTY_INITIAL,
existingNames,
- onCommitted: () => {
- onCreated();
+ onCommitted: (createdName) => {
+ onCreated(createdName);
onOpenChange(false);
},
});
diff --git a/packages/app/src/components/OutlinePanel.tsx b/packages/app/src/components/OutlinePanel.tsx
index 61de05c4d..3e0d892c9 100644
--- a/packages/app/src/components/OutlinePanel.tsx
+++ b/packages/app/src/components/OutlinePanel.tsx
@@ -1,6 +1,7 @@
// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — file uses raw <button>/<input>/<textarea> awaiting shadcn migration; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
import {
type HeadingEntry,
+ isManagedArtifactDocName,
PageHeadingsSuccessSchema,
ProblemDetailsSchema,
} from '@inkeep/open-knowledge-core';
@@ -100,7 +101,7 @@ function OutlinePanelInner({
} = useQuery({
queryKey: ['page-headings', docName],
queryFn: () => fetchHeadings(docName),
- enabled: !loading && pages.has(docName),
+ enabled: !loading && (pages.has(docName) || isManagedArtifactDocName(docName)),
staleTime: Number.POSITIVE_INFINITY,
});
diff --git a/packages/app/src/components/PropertyDisclosure.tsx b/packages/app/src/components/PropertyDisclosure.tsx
new file mode 100644
index 000000000..b127f7136
--- /dev/null
+++ b/packages/app/src/components/PropertyDisclosure.tsx
@@ -0,0 +1,58 @@
+import { ChevronRight } from 'lucide-react';
+import { type ReactNode, type Ref, useState } from 'react';
+import { Button } from '@/components/ui/button';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+import { cn } from '@/lib/utils';
+
+export function PropertyDisclosure({
+ title,
+ className,
+ testId,
+ open: openProp,
+ onOpenChange,
+ children,
+ ref,
+}: {
+ title: ReactNode;
+ className?: string;
+ testId?: string;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ children: ReactNode;
+ /** Forwarded to the container element — e.g. so a selection-publishing hook
+ * can observe text selection within the panel. React 19 ref-as-prop. */
+ ref?: Ref<HTMLDivElement>;
+}) {
+ const [internalCollapsed, setInternalCollapsed] = useState(false);
+ const open = openProp ?? !internalCollapsed;
+ const setOpen = (next: boolean) => {
+ if (onOpenChange) onOpenChange(next);
+ else setInternalCollapsed(!next);
+ };
+ return (
+ <div
+ ref={ref}
+ className={cn('property-panel editor-content-aligned text-sm', className)}
+ data-testid={testId}
+ >
+ <Collapsible open={open} onOpenChange={setOpen}>
+ <CollapsibleTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ className="mb-1.5 flex h-auto w-fit items-center gap-1 bg-transparent! px-1 py-0.5 text-base font-medium text-foreground hover:bg-transparent hover:text-foreground"
+ >
+ <ChevronRight
+ data-expanded={open}
+ className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
+ />
+ <span>{title}</span>
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">
+ {children}
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsx
index 7530f47bb..7ea9f989e 100644
--- a/packages/app/src/components/PropertyPanel.tsx
+++ b/packages/app/src/components/PropertyPanel.tsx
@@ -28,7 +28,7 @@ import {
readFmRegionWithError,
} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { AlertTriangle, ChevronRight, Plus } from 'lucide-react';
+import { AlertTriangle, Plus } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { FrontmatterBindingProvider } from '@/components/FrontmatterBindingContext';
import {
@@ -38,13 +38,14 @@ import {
type RenameDraft,
} from '@/components/FrontmatterRow';
import { useProperties } from '@/components/PropertyContext';
+import { PropertyDisclosure } from '@/components/PropertyDisclosure';
import { coerceValue, DEFAULT_VALUE_FOR_TYPE } from '@/components/PropertyWidgets';
import { Button } from '@/components/ui/button';
-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { usePublishFrontmatterSelection } from '@/hooks/use-selection-context';
interface PropertyPanelProps {
provider: HocuspocusProvider;
+ reservedKeys?: readonly string[];
}
function readInitialSnapshot(provider: PropertyPanelProps['provider']): FrontmatterSnapshot {
@@ -54,8 +55,9 @@ function readInitialSnapshot(provider: PropertyPanelProps['provider']): Frontmat
return { map, keys, parseError };
}
-export function PropertyPanel({ provider }: PropertyPanelProps) {
+export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {
const { t } = useLingui();
+ const reserved = new Set(reservedKeys ?? []);
const [binding, setBinding] = useState<FrontmatterBinding | null>(null);
const [snapshot, setSnapshot] = useState<FrontmatterSnapshot>(() =>
readInitialSnapshot(provider),
@@ -327,7 +329,9 @@ export function PropertyPanel({ provider }: PropertyPanelProps) {
setRenaming({ ...renaming, error: message });
}
- const renderKeys = orderedKeys.length > 0 ? orderedKeys : Object.keys(map);
+ const renderKeys = (orderedKeys.length > 0 ? orderedKeys : Object.keys(map)).filter(
+ (k) => !reserved.has(k),
+ );
const dupCount = new Map<string, number>();
for (const k of renderKeys) dupCount.set(k, (dupCount.get(k) ?? 0) + 1);
@@ -336,86 +340,68 @@ export function PropertyPanel({ provider }: PropertyPanelProps) {
return (
<FrontmatterBindingProvider binding={binding}>
- <div
+ <PropertyDisclosure
ref={panelRef}
- className="property-panel editor-content-aligned pt-4 pb-4 text-sm"
- data-testid="property-panel"
+ title={<Trans>Properties</Trans>}
+ testId="property-panel"
+ className="pt-4 pb-4"
+ open={!collapsed}
+ onOpenChange={(open) => setCollapsed(!open)}
>
- <Collapsible open={!collapsed} onOpenChange={(open) => setCollapsed(!open)}>
- <CollapsibleTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- className="mb-1.5 flex h-auto w-fit bg-transparent! items-center gap-1 px-1 py-0.5 text-base font-medium text-foreground hover:bg-transparent hover:text-foreground"
- >
- <ChevronRight
- data-expanded={!collapsed}
- className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
- />
- <span>
- <Trans>Properties</Trans>
- </span>
- </Button>
- </CollapsibleTrigger>
- <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">
- {parseError ? (
- <div
- role="alert"
- data-testid="property-panel-yaml-error"
- className="mb-1 flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive"
- >
- <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
- <div>
- <Trans>
- The properties block at the top of this doc has a formatting error. Switch to
- source mode to fix it.
- </Trans>
- <span className="block text-[10px] opacity-80">{parseError}</span>
- </div>
- </div>
- ) : null}
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={renderKeys.map((k, i) => rowId(k, i))}
- strategy={verticalListSortingStrategy}
- >
- {renderKeys.map((key, idx) => {
- const value = map[key];
- if (value === undefined) return null;
- const declared = overrides[key] ?? inferType(value);
- const renameState = renaming?.key === key ? renaming : null;
- const isDuplicate = (dupCount.get(key) ?? 0) > 1;
- return (
- <FrontmatterRow
- // biome-ignore lint/suspicious/noArrayIndexKey: position-aware key for dup-name rows.
- key={`${key}-${idx}`}
- sortableId={rowId(key, idx)}
- keyName={key}
- value={value}
- declared={declared}
- error={errors[key] ?? null}
- resetCounter={resetCounters[key] ?? 0}
- isDuplicate={isDuplicate}
- rename={{
- state: renameState,
- onBegin: () => beginRename(key),
- onChangeDraft: changeRenameDraft,
- onCommit: commitRename,
- onCancel: cancelRename,
- }}
- onCommit={(v) => commitProperty(key, v)}
- onChangeType={(t) => setType(key, t)}
- onRemove={() => removeProperty(key)}
- />
- );
- })}
- </SortableContext>
- </DndContext>
- {/*
+ {parseError ? (
+ <div
+ role="alert"
+ data-testid="property-panel-yaml-error"
+ className="mb-1 flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive"
+ >
+ <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
+ <div>
+ <Trans>
+ The properties block at the top of this doc has a formatting error. Switch to source
+ mode to fix it.
+ </Trans>
+ <span className="block text-[10px] opacity-80">{parseError}</span>
+ </div>
+ </div>
+ ) : null}
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
+ <SortableContext
+ items={renderKeys.map((k, i) => rowId(k, i))}
+ strategy={verticalListSortingStrategy}
+ >
+ {renderKeys.map((key, idx) => {
+ const value = map[key];
+ if (value === undefined) return null;
+ const declared = overrides[key] ?? inferType(value);
+ const renameState = renaming?.key === key ? renaming : null;
+ const isDuplicate = (dupCount.get(key) ?? 0) > 1;
+ return (
+ <FrontmatterRow
+ // biome-ignore lint/suspicious/noArrayIndexKey: position-aware key for dup-name rows.
+ key={`${key}-${idx}`}
+ sortableId={rowId(key, idx)}
+ keyName={key}
+ value={value}
+ declared={declared}
+ error={errors[key] ?? null}
+ resetCounter={resetCounters[key] ?? 0}
+ isDuplicate={isDuplicate}
+ rename={{
+ state: renameState,
+ onBegin: () => beginRename(key),
+ onChangeDraft: changeRenameDraft,
+ onCommit: commitRename,
+ onCancel: cancelRename,
+ }}
+ onCommit={(v) => commitProperty(key, v)}
+ onChangeType={(t) => setType(key, t)}
+ onRemove={() => removeProperty(key)}
+ />
+ );
+ })}
+ </SortableContext>
+ </DndContext>
+ {/*
Tags discoverability affordance — render an empty, pinned-at-
end `tags` row when the key is absent from the file YAML
(`map`). The first commit from this virtual row writes the YAML
@@ -425,50 +411,48 @@ export function PropertyPanel({ provider }: PropertyPanelProps) {
the virtual row is purely for "this doc has no tags field yet,
but you can add one here."
*/}
- {!Object.hasOwn(map, 'tags') ? (
- <FrontmatterRow
- key="virtual-tags"
- keyName="tags"
- value={[]}
- declared="list"
- error={errors.tags ?? null}
- resetCounter={resetCounters.tags ?? 0}
- isPlaceholder
- onCommit={(v) => commitProperty('tags', v)}
- onChangeType={() => {}}
- />
- ) : null}
- {adding ? (
- <AddPropertyRow
- draft={adding}
- onChangeName={changeAddName}
- onChangeType={changeAddType}
- onChangeValue={changeAddValue}
- onCommit={commitAdd}
- onCancel={cancelAdd}
- />
- ) : (
- <div className="mt-1 flex items-center gap-1">
- <span aria-hidden className="h-7 w-4 shrink-0" />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- data-testid="add-property-trigger"
- onClick={beginAdd}
- aria-label={t`Add property`}
- className="flex items-center gap-1.5 rounded px-2 py-1 font-medium text-sm hover:bg-muted/50 hover:text-foreground"
- >
- <Plus className="size-3.5" />
- <span>
- <Trans>Add</Trans>
- </span>
- </Button>
- </div>
- )}
- </CollapsibleContent>
- </Collapsible>
- </div>
+ {!reserved.has('tags') && !Object.hasOwn(map, 'tags') ? (
+ <FrontmatterRow
+ key="virtual-tags"
+ keyName="tags"
+ value={[]}
+ declared="list"
+ error={errors.tags ?? null}
+ resetCounter={resetCounters.tags ?? 0}
+ isPlaceholder
+ onCommit={(v) => commitProperty('tags', v)}
+ onChangeType={() => {}}
+ />
+ ) : null}
+ {adding ? (
+ <AddPropertyRow
+ draft={adding}
+ onChangeName={changeAddName}
+ onChangeType={changeAddType}
+ onChangeValue={changeAddValue}
+ onCommit={commitAdd}
+ onCancel={cancelAdd}
+ />
+ ) : (
+ <div className="mt-1 flex items-center gap-1">
+ <span aria-hidden className="h-7 w-4 shrink-0" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="add-property-trigger"
+ onClick={beginAdd}
+ aria-label={t`Add property`}
+ className="flex items-center gap-1.5 rounded px-2 py-1 font-medium text-sm hover:bg-muted/50 hover:text-foreground"
+ >
+ <Plus className="size-3.5" />
+ <span>
+ <Trans>Add</Trans>
+ </span>
+ </Button>
+ </div>
+ )}
+ </PropertyDisclosure>
</FrontmatterBindingProvider>
);
}
diff --git a/packages/app/src/components/PropertyWidgets.tsx b/packages/app/src/components/PropertyWidgets.tsx
index 7c33e932e..bdb1228f0 100644
--- a/packages/app/src/components/PropertyWidgets.tsx
+++ b/packages/app/src/components/PropertyWidgets.tsx
@@ -21,9 +21,8 @@ import {
Type,
X,
} from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
+import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
-import { Calendar } from '@/components/ui/calendar';
import { Checkbox } from '@/components/ui/checkbox';
import {
DropdownMenu,
@@ -240,6 +239,10 @@ export function BooleanWidget({ keyName, value, onCommit }: CommonWidgetProps<bo
);
}
+const Calendar = lazy(() =>
+ import('@/components/ui/calendar').then((m) => ({ default: m.Calendar })),
+);
+
export function DateWidget({ keyName, value, onCommit, onSubmit }: CommonWidgetProps<string>) {
const { t } = useLingui();
const date = parseDate(value);
@@ -337,14 +340,18 @@ export function DateWidget({ keyName, value, onCommit, onSubmit }: CommonWidgetP
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto overflow-hidden p-0" align="end">
- <Calendar
- mode="single"
- selected={date}
- month={month}
- onMonthChange={setMonth}
- onSelect={handleCalendarSelect}
- captionLayout="dropdown"
- />
+ {/* Sized to the calendar's footprint so the popover doesn't resize
+ when the lazy chunk resolves. */}
+ <Suspense fallback={<div className="h-[19rem] w-[17rem]" />}>
+ <Calendar
+ mode="single"
+ selected={date}
+ month={month}
+ onMonthChange={setMonth}
+ onSelect={handleCalendarSelect}
+ captionLayout="dropdown"
+ />
+ </Suspense>
</PopoverContent>
</Popover>
</div>
diff --git a/packages/app/src/components/SeedDialog.tsx b/packages/app/src/components/SeedDialog.tsx
index 74cc5b758..50339c596 100644
--- a/packages/app/src/components/SeedDialog.tsx
+++ b/packages/app/src/components/SeedDialog.tsx
@@ -137,7 +137,7 @@ export function SeedDialog({ open, onOpenChange, onSeedApplied, initialPackId }:
setPhase({ kind: 'error', message: result.error.message });
return;
}
- const hasWork = result.plan.created.length > 0;
+ const hasWork = result.plan.created.length > 0 || result.plan.packSkill?.pending === true;
setPhase(
hasWork
? { kind: 'plan', plan: result.plan }
@@ -172,10 +172,13 @@ export function SeedDialog({ open, onOpenChange, onSeedApplied, initialPackId }:
if (result.ok) {
const packName = selectedPack?.name ?? t`starter pack`;
const projectEntries = result.result.applied;
+ const skillReinstalled = planAtClick.packSkill?.pending === true;
const message =
- projectEntries === 0
- ? t`${packName} was already set up. Nothing to do.`
- : t`${packName} initialized (${plural(projectEntries, { one: '# entry', other: '# entries' })})`;
+ projectEntries > 0
+ ? t`${packName} initialized (${plural(projectEntries, { one: '# entry', other: '# entries' })})`
+ : skillReinstalled
+ ? t`${packName} skill installed.`
+ : t`${packName} was already set up. Nothing to do.`;
toast.success(message);
onSeedApplied?.();
onOpenChange(false);
@@ -372,7 +375,18 @@ function SeedDialogBody({
return (
<div className="space-y-6 py-1 text-sm">
- <CreatedItemsList plan={phase.plan} selectedPack={selectedPack} />
+ {phase.plan.created.length > 0 ? (
+ <CreatedItemsList plan={phase.plan} selectedPack={selectedPack} />
+ ) : null}
+ {phase.plan.packSkill?.pending ? (
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ The pack skill{' '}
+ <code className="font-mono text-foreground/80">{phase.plan.packSkill.name}</code> will
+ be (re)installed.
+ </Trans>
+ </p>
+ ) : null}
{phase.plan.warnings.length > 0 ? (
<div className="rounded-md bg-warning/10 p-3 text-xs text-warning-foreground">
{phase.plan.warnings.map((w) => (
diff --git a/packages/app/src/components/SkillDeleteDialog.tsx b/packages/app/src/components/SkillDeleteDialog.tsx
new file mode 100644
index 000000000..33f1edc07
--- /dev/null
+++ b/packages/app/src/components/SkillDeleteDialog.tsx
@@ -0,0 +1,50 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { DeleteConfirmationDialog } from '@/components/DeleteConfirmationDialog';
+import { Dialog } from '@/components/ui/dialog';
+import { deleteSkill } from '@/lib/skills-api';
+
+interface Props {
+ skill: SkillsListEntry | null;
+ onOpenChange: (open: boolean) => void;
+ onDeleted: () => void;
+}
+
+export function SkillDeleteDialog({ skill, onOpenChange, onDeleted }: Props) {
+ const { t } = useLingui();
+ const [deleting, setDeleting] = useState(false);
+
+ async function handleDelete(target: SkillsListEntry) {
+ setDeleting(true);
+ const result = await deleteSkill(target.scope, target.name);
+ setDeleting(false);
+ if (!result.ok) {
+ const { error } = result;
+ toast.error(t`Couldn't delete skill: ${error}`);
+ return;
+ }
+ toast.success(t`Skill "${target.name}" deleted`);
+ onDeleted();
+ onOpenChange(false);
+ }
+
+ return (
+ <Dialog
+ open={skill !== null}
+ onOpenChange={(open) => {
+ if (!open && !deleting) onOpenChange(false);
+ }}
+ >
+ {skill ? (
+ <DeleteConfirmationDialog
+ 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.`}
+ />
+ ) : null}
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillEditorActions.dom.test.tsx b/packages/app/src/components/SkillEditorActions.dom.test.tsx
new file mode 100644
index 000000000..ef712b1a9
--- /dev/null
+++ b/packages/app/src/components/SkillEditorActions.dom.test.tsx
@@ -0,0 +1,55 @@
+import { describe, expect, mock, test } from 'bun:test';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import * as linguiShim from '../../tests/lingui-macro-shim';
+
+mock.module('@lingui/react/macro', () => linguiShim);
+
+const installedEntry = {
+ scope: 'project' as const,
+ name: 'foo',
+ path: 'foo',
+ description: '',
+ installed: true,
+ hosts: ['claude'],
+};
+
+const uninstall = mock(async () => ({ ok: false as const, error: 'boom' }));
+const install = mock(async () => ({ ok: false as const, error: 'boom' }));
+
+mock.module('@/hooks/use-skills', () => ({
+ useSkills: () => ({ status: 'ready', data: [installedEntry] }),
+}));
+mock.module('@/components/skill-actions', () => ({
+ useSkillActions: () => ({
+ installingName: null,
+ install,
+ uninstall,
+ duplicate: async () => {},
+ requestDelete: () => {},
+ requestRename: () => {},
+ dialogs: null,
+ }),
+}));
+
+const { SkillEditorActions } = await import('./SkillEditorActions');
+
+describe('SkillEditorActions — optimistic rollback', () => {
+ test('reverts the pill to Installed when uninstall fails', async () => {
+ const user = userEvent.setup();
+ render(<SkillEditorActions scope="project" name="foo" />);
+
+ 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'));
+
+ await waitFor(() => expect(uninstall).toHaveBeenCalledTimes(1));
+ await waitFor(() =>
+ expect(screen.getByTestId('skill-install-menu-trigger').getAttribute('data-state')).toBe(
+ 'installed',
+ ),
+ );
+ });
+});
diff --git a/packages/app/src/components/SkillEditorActions.tsx b/packages/app/src/components/SkillEditorActions.tsx
new file mode 100644
index 000000000..484e1cf3b
--- /dev/null
+++ b/packages/app/src/components/SkillEditorActions.tsx
@@ -0,0 +1,159 @@
+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 { 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 { cn } from '@/lib/utils';
+
+const INSTALL_EDITORS: readonly SkillTargetEditor[] = SkillTargetEditorSchema.options;
+
+export function SkillEditorActions({ scope, name }: { scope: SkillScope; name: string }) {
+ const skillsState = useSkills();
+ const actions = useSkillActions();
+
+ const entry =
+ skillsState.status === 'ready'
+ ? skillsState.data.find((s) => s.scope === scope && s.name === name)
+ : undefined;
+ const skill: SkillsListEntry = entry ?? {
+ scope,
+ name,
+ path: name,
+ description: '',
+ installed: false,
+ hosts: [],
+ };
+ const installing = actions.installingName === name;
+
+ 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);
+ useEffect(() => {
+ if (optimisticHosts === null) liveHostsRef.current = skill.hosts;
+ }, [optimisticHosts, skill.hosts]);
+
+ 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);
+ 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);
+ }
+
+ return (
+ <div className="flex items-center gap-1.5">
+ <DropdownMenu>
+ <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. */}
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={installing}
+ data-testid="skill-install-menu-trigger"
+ data-state={installed ? 'installed' : 'draft'}
+ 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',
+ )}
+ >
+ {installing ? (
+ <Trans>Working</Trans>
+ ) : installed ? (
+ <Trans>Installed</Trans>
+ ) : (
+ <Trans>Draft</Trans>
+ )}
+ <ChevronDown 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([]);
+ void (async () => {
+ const result = await actions.uninstall(skill);
+ if (!result.ok) setOptimisticHosts(null);
+ })();
+ }}
+ >
+ <Trans>Uninstall everywhere</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {actions.dialogs}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/SkillFileViewer.dom.test.tsx b/packages/app/src/components/SkillFileViewer.dom.test.tsx
new file mode 100644
index 000000000..1bc116fba
--- /dev/null
+++ b/packages/app/src/components/SkillFileViewer.dom.test.tsx
@@ -0,0 +1,79 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, waitFor } from '@testing-library/react';
+
+const loadSkillFileTextMock = mock(
+ async (_input: { scope: string; name: string; path: string }) =>
+ ({ ok: true, text: '' }) as { ok: true; text: string } | { ok: false; status?: number },
+);
+mock.module('@/lib/skills-api', () => ({
+ loadSkillFileText: loadSkillFileTextMock,
+}));
+
+const { SkillFileViewer } = await import('./SkillFileViewer.tsx');
+
+describe('SkillFileViewer — scope-aware bundle-file read + render dispatch', () => {
+ afterEach(() => {
+ cleanup();
+ loadSkillFileTextMock.mockReset();
+ });
+
+ test('global reference (.md) renders as formatted markdown (not source)', async () => {
+ loadSkillFileTextMock.mockResolvedValueOnce({
+ ok: true,
+ text: '# Reference body\n\nSome **bold** prose.\n',
+ });
+ const { container } = render(
+ <SkillFileViewer scope="global" name="trip-log" path="references/guide.md" />,
+ );
+ await waitFor(() => {
+ expect(container.querySelector('[data-skill-markdown-viewer]')).not.toBeNull();
+ });
+ expect(loadSkillFileTextMock).toHaveBeenCalledWith(
+ {
+ scope: 'global',
+ name: 'trip-log',
+ path: 'references/guide.md',
+ },
+ expect.any(AbortSignal),
+ );
+ const heading = container.querySelector('h1');
+ expect(heading?.textContent).toBe('Reference body');
+ expect(container.querySelector('strong')?.textContent).toBe('bold');
+ expect(container.textContent ?? '').not.toContain('# Reference body');
+ expect(container.textContent ?? '').not.toContain('**bold**');
+ expect(container.querySelector('[contenteditable="true"]')).toBeNull();
+ expect(container.querySelector('[data-text-viewer]')).toBeNull();
+ });
+
+ test('global script (.sh) renders through the source TextViewer', async () => {
+ loadSkillFileTextMock.mockResolvedValueOnce({ ok: true, text: 'echo hi' });
+ const { container } = render(
+ <SkillFileViewer scope="global" name="trip-log" path="scripts/run.sh" />,
+ );
+ await waitFor(() => {
+ expect(container.querySelector('[data-text-viewer-state="loaded"]')).not.toBeNull();
+ });
+ expect(loadSkillFileTextMock).toHaveBeenCalledWith(
+ {
+ scope: 'global',
+ name: 'trip-log',
+ path: 'scripts/run.sh',
+ },
+ expect.any(AbortSignal),
+ );
+ expect(container.querySelector('[data-text-viewer-extension="sh"]')).not.toBeNull();
+ expect(container.querySelector('[data-skill-markdown-viewer]')).toBeNull();
+ });
+
+ test('a failed markdown read lands in the error pane (terminal, not perpetual loading)', async () => {
+ loadSkillFileTextMock.mockResolvedValueOnce({ ok: false, status: 404 });
+ const { container } = render(
+ <SkillFileViewer scope="global" name="trip-log" path="references/missing.md" />,
+ );
+ await waitFor(() => {
+ expect(container.querySelector('[data-skill-markdown-state="error"]')).not.toBeNull();
+ });
+ expect(container.querySelector('[data-skill-markdown-state="loading"]')).toBeNull();
+ expect(container.querySelector('a[href*="/api/asset"]')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/SkillFileViewer.tsx b/packages/app/src/components/SkillFileViewer.tsx
new file mode 100644
index 000000000..2746cbee9
--- /dev/null
+++ b/packages/app/src/components/SkillFileViewer.tsx
@@ -0,0 +1,32 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { SkillMarkdownLoader } from '@/components/SkillMarkdownLoader';
+import { TextViewer } from '@/components/TextViewer';
+import { loadSkillFileText } from '@/lib/skills-api';
+
+const MARKDOWN_EXTENSIONS = new Set(['md', 'mdx']);
+
+export function SkillFileViewer({
+ scope,
+ name,
+ path,
+}: {
+ scope: SkillScope;
+ name: string;
+ path: string;
+}) {
+ const fileName = path.split('/').pop() ?? path;
+ const dot = fileName.lastIndexOf('.');
+ const extension = dot >= 0 ? fileName.slice(dot + 1).toLowerCase() : '';
+
+ if (MARKDOWN_EXTENSIONS.has(extension)) {
+ return <SkillMarkdownLoader scope={scope} name={name} path={path} fileName={fileName} />;
+ }
+
+ return (
+ <TextViewer
+ fileName={fileName}
+ extension={extension}
+ loadText={(signal: AbortSignal) => loadSkillFileText({ scope, name, path }, signal)}
+ />
+ );
+}
diff --git a/packages/app/src/components/SkillMarkdownLoader.tsx b/packages/app/src/components/SkillMarkdownLoader.tsx
new file mode 100644
index 000000000..9aa454914
--- /dev/null
+++ b/packages/app/src/components/SkillMarkdownLoader.tsx
@@ -0,0 +1,33 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import { SkillMarkdownViewer } from '@/components/SkillMarkdownViewer';
+import { ViewerErrorPane, ViewerLoadingPane } from '@/components/ViewerStatusPane';
+import { loadSkillFileText } from '@/lib/skills-api';
+import { useViewerText } from './use-viewer-text';
+
+const DATA_ATTR = 'data-skill-markdown';
+
+export function SkillMarkdownLoader({
+ scope,
+ name,
+ path,
+ fileName,
+}: {
+ scope: SkillScope;
+ name: string;
+ path: string;
+ fileName: string;
+}) {
+ const fetchState = useViewerText({
+ loadText: (signal) => loadSkillFileText({ scope, name, path }, signal),
+ });
+
+ if (fetchState.status === 'loading') {
+ return <ViewerLoadingPane fileName={fileName} dataAttr={DATA_ATTR} />;
+ }
+ if (fetchState.status === 'error') {
+ return (
+ <ViewerErrorPane fileName={fileName} dataAttr={DATA_ATTR} message={fetchState.message} />
+ );
+ }
+ return <SkillMarkdownViewer fileName={fileName} text={fetchState.content} />;
+}
diff --git a/packages/app/src/components/SkillMarkdownViewer.tsx b/packages/app/src/components/SkillMarkdownViewer.tsx
new file mode 100644
index 000000000..ec061b422
--- /dev/null
+++ b/packages/app/src/components/SkillMarkdownViewer.tsx
@@ -0,0 +1,60 @@
+import { stripFrontmatter } from '@inkeep/open-knowledge-core';
+import { EditorContent, useEditor } from '@tiptap/react';
+import { useLayoutEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { sharedExtensions } from '@/editor/extensions/shared.ts';
+import { getSharedMarkdownManager } from '@/editor/utils/md-singleton';
+
+export function SkillMarkdownViewer({ fileName, text }: { fileName: string; text: string }) {
+ const body = stripFrontmatter(text).body;
+ const editor = useEditor(
+ {
+ extensions: sharedExtensions,
+ editable: false,
+ content: getSharedMarkdownManager().parseWithFallback(body),
+ editorProps: {
+ attributes: {
+ class: 'pt-4 pb-4',
+ },
+ },
+ },
+ [text],
+ );
+
+ const [portalTarget] = useState(() => {
+ const el = document.createElement('div');
+ el.style.display = 'contents';
+ return el;
+ });
+ const portalSlotRef = useRef<HTMLDivElement | null>(null);
+ useLayoutEffect(() => {
+ const slot = portalSlotRef.current;
+ if (!slot) return;
+ slot.appendChild(portalTarget);
+ return () => {
+ if (portalTarget.parentNode === slot) slot.removeChild(portalTarget);
+ };
+ }, [portalTarget]);
+
+ return (
+ <main
+ className="flex h-full min-h-0 flex-col bg-background"
+ aria-label={fileName}
+ data-skill-markdown-viewer=""
+ data-skill-markdown-viewer-state="loaded"
+ >
+ <div className="editor-doc-scroll min-h-0 flex-1 overflow-auto">
+ {/* 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>
+ {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" />,
+ portalTarget,
+ )}
+ </main>
+ );
+}
diff --git a/packages/app/src/components/SkillProperties.dom.test.tsx b/packages/app/src/components/SkillProperties.dom.test.tsx
new file mode 100644
index 000000000..7197e62d6
--- /dev/null
+++ b/packages/app/src/components/SkillProperties.dom.test.tsx
@@ -0,0 +1,60 @@
+import { describe, expect, mock, test } from 'bun:test';
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { fireEvent, render, screen } from '@testing-library/react';
+import * as Y from 'yjs';
+import * as linguiShim from '../../tests/lingui-macro-shim';
+
+mock.module('@lingui/react/macro', () => linguiShim);
+
+const { SkillProperties } = await import('./SkillProperties');
+const { PropertyProvider } = await import('./PropertyContext');
+
+/** SkillProperties reuses the document PropertyPanel, which reads the shared
+ * property-panel context — the same `PropertyProvider` EditorArea mounts. */
+function renderPanel(ui: Parameters<typeof render>[0]) {
+ return render(<PropertyProvider>{ui}</PropertyProvider>);
+}
+
+function makeProvider(source: string): { provider: HocuspocusProvider; ytext: Y.Text } {
+ const document = new Y.Doc();
+ const ytext = document.getText('source');
+ ytext.insert(0, source);
+ const provider = {
+ document,
+ configuration: { name: '__skill__/project/foo' },
+ on: () => {},
+ off: () => {},
+ } as unknown as HocuspocusProvider;
+ return { provider, ytext };
+}
+
+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={() => {}} />);
+ expect(screen.getByTestId('property-panel')).toBeTruthy();
+ expect(screen.getByDisplayValue('initial desc')).toBeTruthy();
+ });
+
+ test('committing a changed name fires onRename (a git-mv rename), not a patch', () => {
+ const { provider, ytext } = makeProvider(SOURCE);
+ const onRename = mock((_next: string) => {});
+ renderPanel(<SkillProperties provider={provider} name="foo" onRename={onRename} />);
+ const nameInput = screen.getByTestId('skill-name-input');
+ fireEvent.change(nameInput, { target: { value: 'bar' } });
+ fireEvent.blur(nameInput);
+ expect(onRename).toHaveBeenCalledWith('bar');
+ expect(ytext.toString()).toContain('name: foo');
+ });
+
+ test('an unchanged name does not fire onRename', () => {
+ const { provider } = makeProvider(SOURCE);
+ const onRename = mock((_next: string) => {});
+ renderPanel(<SkillProperties provider={provider} name="foo" onRename={onRename} />);
+ const nameInput = screen.getByTestId('skill-name-input');
+ fireEvent.blur(nameInput);
+ expect(onRename).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/SkillProperties.tsx b/packages/app/src/components/SkillProperties.tsx
new file mode 100644
index 000000000..add4640cc
--- /dev/null
+++ b/packages/app/src/components/SkillProperties.tsx
@@ -0,0 +1,187 @@
+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 { 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';
+
+const SKILL_RESERVED_KEYS = ['name'] as const;
+
+interface ScopeControl {
+ scope: SkillScope;
+ onScopeChange: (scope: SkillScope) => void;
+}
+
+export function SkillProperties({
+ provider,
+ name,
+ scopeControl,
+ onRename,
+ nameError,
+ onNameDraftChange,
+ nameEditable = true,
+}: {
+ provider: HocuspocusProvider;
+ 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;
+ nameError?: string | null;
+ onNameDraftChange?: (next: string) => void;
+ nameEditable?: boolean;
+}) {
+ const { t } = useLingui();
+ const nameId = useId();
+ const scopeId = useId();
+ const scopeLabels = useSkillScopePillLabels();
+
+ const [nameDraft, setNameDraft] = useState(name);
+ useEffect(() => setNameDraft(name), [name]);
+ const trimmedName = nameDraft.trim();
+ const nameInvalid = trimmedName !== '' && !SKILL_NAME_REGEX.test(trimmedName);
+
+ function commitName() {
+ if (!onRename) return;
+ if (nameInvalid || trimmedName === '' || trimmedName === name) return;
+ onRename(trimmedName);
+ }
+
+ 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>
+ ) : (
+ <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>
+ )}
+ </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>
+ );
+}
+
+/** 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;
+}) {
+ 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>
+ );
+}
diff --git a/packages/app/src/components/SkillRenameDialog.tsx b/packages/app/src/components/SkillRenameDialog.tsx
new file mode 100644
index 000000000..52a79ca96
--- /dev/null
+++ b/packages/app/src/components/SkillRenameDialog.tsx
@@ -0,0 +1,113 @@
+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 { 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 { moveSkill } from '@/lib/skills-api';
+
+interface Props {
+ skill: SkillsListEntry | null;
+ existingNames: ReadonlySet<string>;
+ onOpenChange: (open: boolean) => void;
+ onRenamed?: (name: string) => void;
+}
+
+export function SkillRenameDialog({ skill, existingNames, onOpenChange, onRenamed }: Props) {
+ const { t } = useLingui();
+ const open = skill !== null;
+ const inputId = useId();
+ const [name, setName] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-seed only when the target skill changes, not on every keystroke.
+ useEffect(() => {
+ if (skill) setName(skill.name);
+ }, [skill?.scope, skill?.name]);
+
+ if (!skill) return null;
+
+ const trimmed = name.trim();
+ const unchanged = trimmed === skill.name;
+ const invalid = trimmed === '' || !SKILL_NAME_REGEX.test(trimmed);
+ 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 });
+ setSaving(false);
+ if (!result.ok) {
+ toast.error(t`Couldn't rename "${skill.name}": ${result.error}`);
+ return;
+ }
+ toast.success(t`Renamed to "${trimmed}"`);
+ onRenamed?.(trimmed);
+ onOpenChange(false);
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => (next ? null : onOpenChange(false))}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Rename skill</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>Renames the folder on disk and the id agents use to invoke it.</Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-1.5">
+ <Label htmlFor={inputId}>
+ <Trans>Name</Trans>
+ </Label>
+ <Input
+ id={inputId}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void submit();
+ }}
+ spellCheck={false}
+ autoCapitalize="off"
+ autoCorrect="off"
+ aria-invalid={invalid || collides}
+ aria-describedby={
+ (invalid && trimmed !== '') || collides ? `${inputId}-error` : undefined
+ }
+ className="font-mono"
+ />
+ {invalid && trimmed !== '' ? (
+ <p id={`${inputId}-error`} className="text-xs text-destructive">
+ <Trans>
+ Use lowercase letters, digits, and <code className="font-mono">-</code> only.
+ </Trans>
+ </p>
+ ) : collides ? (
+ <p id={`${inputId}-error`} className="text-xs text-destructive">
+ <Trans>A skill with that name already exists.</Trans>
+ </p>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" 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/SkillRow.tsx b/packages/app/src/components/SkillRow.tsx
new file mode 100644
index 000000000..a3609c20d
--- /dev/null
+++ b/packages/app/src/components/SkillRow.tsx
@@ -0,0 +1,116 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { DownloadCloud, 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;
+ installing: boolean;
+}
+
+export function SkillRow({
+ skill,
+ onEdit,
+ onDelete,
+ onInstall,
+ onUninstall,
+ installing,
+}: SkillRowProps) {
+ const { t } = useLingui();
+ const workspace = useWorkspace();
+ 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>
+ <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>
+ <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/SkillStateBadge.tsx b/packages/app/src/components/SkillStateBadge.tsx
new file mode 100644
index 000000000..f59da7dc8
--- /dev/null
+++ b/packages/app/src/components/SkillStateBadge.tsx
@@ -0,0 +1,34 @@
+import { Trans } from '@lingui/react/macro';
+import { Badge } from '@/components/ui/badge';
+import { cn } from '@/lib/utils';
+
+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/SkillUpdateDialog.tsx b/packages/app/src/components/SkillUpdateDialog.tsx
new file mode 100644
index 000000000..1ddf76b90
--- /dev/null
+++ b/packages/app/src/components/SkillUpdateDialog.tsx
@@ -0,0 +1,92 @@
+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 {
+ skill: SkillsListEntry | null;
+ onOpenChange: (open: boolean) => void;
+ 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;
+ }
+ 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/SkillsSidebarSection.tsx b/packages/app/src/components/SkillsSidebarSection.tsx
new file mode 100644
index 000000000..8ef71d28b
--- /dev/null
+++ b/packages/app/src/components/SkillsSidebarSection.tsx
@@ -0,0 +1,455 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import {
+ ChevronRight,
+ FileCode,
+ FileText,
+ Hexagon,
+ MoreHorizontal,
+ Plus,
+ RefreshCw,
+} from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { NewSkillDialog } from '@/components/NewSkillDialog';
+import { SkillStateBadge } from '@/components/SkillStateBadge';
+import {
+ type SkillActions,
+ SkillContextMenuItems,
+ useSkillActions,
+} from '@/components/skill-actions';
+import { Button } from '@/components/ui/button';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import {
+ SidebarGroup,
+ SidebarGroupAction,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarMenu,
+ SidebarMenuAction,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ SidebarMenuSub,
+ SidebarMenuSubButton,
+ SidebarMenuSubItem,
+} from '@/components/ui/sidebar';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { useSkills } from '@/hooks/use-skills';
+import { hashFromDocName, hashFromSkillFile, replaceHashWithoutNavigation } 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';
+import {
+ SKILL_SCOPE_ORDER,
+ skillDisplayName,
+ skillNameSetsByScope,
+ useSkillScopeLabels,
+} from '@/lib/skill-scope';
+import {
+ getSkillBundledFiles,
+ getSkillsManagement,
+ type SkillBundledFile,
+ setSkillsManagement,
+} from '@/lib/skills-api';
+
+export function SkillsSidebarSection() {
+ const { t } = useLingui();
+ const state = useSkills();
+ const { activeDocName } = useDocumentContext();
+ const [newSkillOpen, setNewSkillOpen] = useState(false);
+ const actions = useSkillActions();
+
+ const skills = state.status === 'ready' ? state.data : [];
+ const nameSets = skillNameSetsByScope(skills);
+ const scopeLabel = useSkillScopeLabels();
+
+ const [openScopes, setOpenScopes] = useState<Record<string, boolean>>({});
+
+ return (
+ <Collapsible className="group/skills shrink-0">
+ <SidebarGroup>
+ <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 />
+ {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) => {
+ const holdsActive = skills.some(
+ (s) => s.scope === scope && skillLiveDocName(s.scope, s.name) === activeDocName,
+ );
+ return (
+ <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}
+ <NewSkillDialog
+ defaultScope="project"
+ open={newSkillOpen}
+ onOpenChange={setNewSkillOpen}
+ onCreated={({ scope, name }) => openManagedArtifactTab(skillLiveDocName(scope, name))}
+ />
+ </SidebarGroup>
+ </Collapsible>
+ );
+}
+
+function SkillFolderItem({
+ skill,
+ activeDocName,
+ actions,
+ existingNames,
+}: {
+ skill: SkillsListEntry;
+ activeDocName: string | null;
+ actions: SkillActions;
+ existingNames: ReadonlySet<string>;
+}) {
+ const { t } = useLingui();
+ const [open, setOpen] = 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]">
+ <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}
+ <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>
+ <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>
+ );
+}
+
+interface FileNode {
+ name: string;
+ path: string;
+ children?: FileNode[];
+ 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;
+ });
+ }
+ sortTree(root);
+ return root;
+}
+
+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);
+ });
+ 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);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const { openTarget } = useDocumentContext();
+
+ function openProjectDoc(docName: string) {
+ openTarget({ kind: 'doc', target: docName, docName }, { tabBehavior: 'append' });
+ replaceHashWithoutNavigation(hashFromDocName(docName));
+ }
+
+ function openFile(filePath: string) {
+ 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;
+ }
+ const target = {
+ kind: 'skill-file' as const,
+ target: `${skill.scope}/${skill.name}/${filePath}`,
+ scope: skill.scope,
+ name: skill.name,
+ path: filePath,
+ };
+ openTarget(target, { tabBehavior: 'replace-active' });
+ replaceHashWithoutNavigation(
+ hashFromSkillFile({ scope: skill.scope, name: skill.name, path: filePath }),
+ );
+ }
+
+ 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 {
+ setFiles([]);
+ setLoadFailed(true);
+ }
+ });
+ };
+ load();
+ const unsub = subscribeToSkillsChanged(load);
+ return () => {
+ active = false;
+ unsub();
+ };
+ }, [skill.scope, skill.name]);
+
+ const tree = files ? buildFileTree(files) : [];
+
+ 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.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>
+ </span>
+ </SidebarMenuSubItem>
+ ) : (
+ tree.map((node) => (
+ <FileTreeNode key={node.path} node={node} depth={0} onOpenFile={openFile} />
+ ))
+ )}
+ </SidebarMenuSub>
+ );
+}
+
+function FileTreeNode({
+ node,
+ depth,
+ onOpenFile,
+}: {
+ node: FileNode;
+ depth: number;
+ onOpenFile: (filePath: string) => 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>
+ );
+ }
+
+ 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>
+ );
+}
+
+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;
+ };
+ }, []);
+
+ if (!state || state.managed !== null || state.importable === 0) return null;
+
+ const decide = async (manage: boolean) => {
+ setBusy(true);
+ const ok = await setSkillsManagement(manage);
+ if (!ok) {
+ 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
+ them into the knowledge base?
+ </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/TemplateEditDialog.tsx b/packages/app/src/components/TemplateEditDialog.tsx
deleted file mode 100644
index 471ab34c3..000000000
--- a/packages/app/src/components/TemplateEditDialog.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import { Trans, useLingui } from '@lingui/react/macro';
-import { InheritedBadge } from '@/components/FrontmatterRow';
-import { TemplateFormFields, useTemplateForm } from '@/components/TemplateForm';
-import { Button } from '@/components/ui/button';
-import {
- Dialog,
- DialogBody,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog';
-import { Skeleton } from '@/components/ui/skeleton';
-import {
- type TemplateDetail,
- type TemplateMenuEntry,
- useTemplate,
-} from '@/hooks/use-folder-config';
-
-interface Props {
- folderPath: string;
- template: TemplateMenuEntry | null;
- onOpenChange: (open: boolean) => void;
- onSaved: () => void;
-}
-
-export function TemplateEditDialog({ folderPath, template, onOpenChange, onSaved }: Props) {
- const { t } = useLingui();
- const open = template !== null;
- const templateLabel = template?.title ?? template?.name ?? t`Template`;
-
- function handleClose() {
- onOpenChange(false);
- }
-
- function handleSaved() {
- onSaved();
- handleClose();
- }
-
- return (
- <Dialog open={open} onOpenChange={(next) => (next ? null : handleClose())}>
- <DialogContent className="sm:max-w-3xl max-h-[85vh] flex flex-col">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <Trans>Edit {templateLabel}</Trans>
- {template?.scope === 'inherited' && template ? (
- <InheritedBadge
- source={template.source_folder}
- target={`templates/${template.name}.md`}
- />
- ) : null}
- </DialogTitle>
- <DialogDescription className="sr-only">
- {template?.description ?? t`Edit template`}
- </DialogDescription>
- </DialogHeader>
- {template ? (
- <TemplateEditBody
- key={`${template.source_folder}::${template.name}`}
- folderPath={folderPath}
- template={template}
- onCancel={handleClose}
- onSaved={handleSaved}
- />
- ) : null}
- </DialogContent>
- </Dialog>
- );
-}
-
-function TemplateEditBody({
- folderPath,
- template,
- onCancel,
- onSaved,
-}: {
- folderPath: string;
- template: TemplateMenuEntry;
- onCancel: () => void;
- onSaved: () => void;
-}) {
- const state = useTemplate(folderPath, template.name);
-
- if (state.status === 'loading' || state.status === 'idle') {
- return (
- <DialogBody className="overflow-y-auto subtle-scrollbar">
- <div className="space-y-3">
- <Skeleton className="h-32 w-full" />
- <Skeleton className="h-48 w-full" />
- </div>
- </DialogBody>
- );
- }
- if (state.status === 'error') {
- const errorMessage = state.message;
- return (
- <DialogBody className="overflow-y-auto subtle-scrollbar">
- <p role="alert" className="text-sm text-destructive">
- <Trans>Failed to load template: {errorMessage}</Trans>
- </p>
- </DialogBody>
- );
- }
- return <TemplateEditForm detail={state.data} onCancel={onCancel} onSaved={onSaved} />;
-}
-
-function TemplateEditForm({
- detail,
- onCancel,
- onSaved,
-}: {
- detail: TemplateDetail;
- onCancel: () => void;
- onSaved: () => void;
-}) {
- const fm = detail.frontmatter as Record<string, unknown>;
- const form = useTemplateForm({
- mode: 'edit',
- folderPath: detail.folder,
- scope: detail.scope,
- initial: {
- name: detail.name,
- title: typeof fm.title === 'string' ? fm.title : '',
- description: typeof fm.description === 'string' ? fm.description : '',
- body: detail.body,
- },
- onCommitted: onSaved,
- });
-
- return (
- <>
- <DialogBody className="overflow-y-auto subtle-scrollbar">
- <TemplateFormFields form={form} />
- </DialogBody>
- <DialogFooter>
- <Button
- variant="outline"
- className="font-mono uppercase"
- onMouseDown={(e) => e.preventDefault()}
- onClick={onCancel}
- disabled={form.isSaving}
- >
- <Trans>Cancel</Trans>
- </Button>
- <Button onClick={() => void form.submit()} disabled={form.isSaving}>
- {form.isSaving ? <Trans>Saving</Trans> : <Trans>Save</Trans>}
- </Button>
- </DialogFooter>
- </>
- );
-}
diff --git a/packages/app/src/components/TemplateForm.tsx b/packages/app/src/components/TemplateForm.tsx
index da760a84d..e4d7fa2d6 100644
--- a/packages/app/src/components/TemplateForm.tsx
+++ b/packages/app/src/components/TemplateForm.tsx
@@ -111,7 +111,7 @@ interface UseTemplateFormArgs {
scope?: 'local' | 'inherited';
initial: TemplateFormInitial;
existingNames?: ReadonlySet<string>;
- onCommitted: () => void;
+ onCommitted: (committedName: string) => void;
}
export interface TemplateFormState {
@@ -238,7 +238,7 @@ export function useTemplateForm({
} else {
toast.success(t`Template saved`);
}
- onCommitted();
+ onCommitted(mode === 'create' || renaming ? trimmedSlug : initial.name);
}
return {
diff --git a/packages/app/src/components/TemplateProperties.dom.test.tsx b/packages/app/src/components/TemplateProperties.dom.test.tsx
new file mode 100644
index 000000000..963369e16
--- /dev/null
+++ b/packages/app/src/components/TemplateProperties.dom.test.tsx
@@ -0,0 +1,58 @@
+import { describe, expect, mock, test } from 'bun:test';
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { fireEvent, render, screen } from '@testing-library/react';
+import * as Y from 'yjs';
+import * as linguiShim from '../../tests/lingui-macro-shim';
+
+mock.module('@lingui/react/macro', () => linguiShim);
+
+const { TemplateProperties } = await import('./TemplateProperties');
+
+function makeProvider(source: string): { provider: HocuspocusProvider; ytext: Y.Text } {
+ const document = new Y.Doc();
+ const ytext = document.getText('source');
+ ytext.insert(0, source);
+ const provider = {
+ document,
+ configuration: { name: '__template__/notes/meeting' },
+ on: () => {},
+ off: () => {},
+ } as unknown as HocuspocusProvider;
+ return { provider, ytext };
+}
+
+const SOURCE = '---\ntitle: Meeting\ndescription: initial desc\n---\n\n# Agenda\n';
+
+describe('TemplateProperties (CRDT)', () => {
+ test('seeds title + description from the doc frontmatter', () => {
+ const { provider } = makeProvider(SOURCE);
+ render(<TemplateProperties provider={provider} name="meeting" folder="notes" />);
+ expect((screen.getByTestId('template-title-input') as HTMLInputElement).value).toBe('Meeting');
+ expect((screen.getByTestId('template-description-input') as HTMLTextAreaElement).value).toBe(
+ 'initial desc',
+ );
+ });
+
+ test('editing the title patches the YAML region of Y.Text (CRDT)', () => {
+ const { provider, ytext } = makeProvider(SOURCE);
+ render(<TemplateProperties provider={provider} name="meeting" folder="notes" />);
+ const title = screen.getByTestId('template-title-input');
+ fireEvent.change(title, { target: { value: 'Standup' } });
+ fireEvent.blur(title);
+ expect(ytext.toString()).toContain('title: Standup');
+ expect(ytext.toString()).toContain('# Agenda');
+ });
+
+ test('committing a changed name fires onRename (a git-mv rename), not a patch', () => {
+ const { provider, ytext } = makeProvider(SOURCE);
+ const onRename = mock((_next: string) => {});
+ render(
+ <TemplateProperties provider={provider} name="meeting" folder="notes" onRename={onRename} />,
+ );
+ const nameInput = screen.getByTestId('template-name-input');
+ fireEvent.change(nameInput, { target: { value: 'standup' } });
+ fireEvent.blur(nameInput);
+ expect(onRename).toHaveBeenCalledWith('standup');
+ expect(ytext.toString()).toContain('# Agenda');
+ });
+});
diff --git a/packages/app/src/components/TemplateProperties.tsx b/packages/app/src/components/TemplateProperties.tsx
new file mode 100644
index 000000000..703cf33d7
--- /dev/null
+++ b/packages/app/src/components/TemplateProperties.tsx
@@ -0,0 +1,140 @@
+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 { PropertyDisclosure } from '@/components/PropertyDisclosure';
+import { Input } from '@/components/ui/input';
+import { Textarea } from '@/components/ui/textarea';
+import { useFrontmatterField } from '@/lib/use-frontmatter-field';
+
+export function TemplateProperties({
+ provider,
+ name,
+ folder,
+ onRename,
+ nameError,
+}: {
+ provider: HocuspocusProvider;
+ name: string;
+ folder: string;
+ onRename?: (next: string) => void;
+ nameError?: string | null;
+}) {
+ const { t } = useLingui();
+ const nameId = useId();
+ const titleId = useId();
+ const descriptionId = useId();
+ const folderId = useId();
+
+ const title = useFrontmatterField(provider, 'title');
+ const description = useFrontmatterField(provider, 'description');
+
+ const [nameDraft, setNameDraft] = useState(name);
+ useEffect(() => setNameDraft(name), [name]);
+ const trimmedName = nameDraft.trim();
+ const nameInvalid = trimmedName !== '' && !TEMPLATE_NAME_REGEX.test(trimmedName);
+ function commitName() {
+ if (!onRename) return;
+ if (nameInvalid || trimmedName === '' || trimmedName === name) return;
+ onRename(trimmedName);
+ }
+ const showNameError = nameInvalid || Boolean(nameError);
+
+ return (
+ <PropertyDisclosure title={<Trans>Properties</Trans>} className="pt-4 pb-2">
+ <PropertyRow 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}>
+ <Input
+ id={nameId}
+ data-testid="template-name-input"
+ value={nameDraft}
+ onChange={(e) => setNameDraft(e.target.value)}
+ onBlur={commitName}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') e.currentTarget.blur();
+ }}
+ aria-invalid={showNameError}
+ className="h-8 border-input bg-transparent px-2 font-mono shadow-none focus-visible:bg-muted/30"
+ />
+ {showNameError ? (
+ <p className="px-1 pt-0.5 text-[11px] text-destructive">
+ {nameError ? (
+ nameError
+ ) : (
+ <Trans>
+ Use letters, digits, <code className="font-mono">_</code> and{' '}
+ <code className="font-mono">-</code> only.
+ </Trans>
+ )}
+ </p>
+ ) : (
+ <p className="px-1 pt-0.5 text-[11px] text-muted-foreground">
+ <Trans>The template's filename (without `.md`).</Trans>
+ </p>
+ )}
+ </PropertyRow>
+ <PropertyRow icon={<Type className="size-3.5" />} label={t`title`} htmlFor={titleId}>
+ <Input
+ id={titleId}
+ data-testid="template-title-input"
+ value={title.value}
+ onChange={(e) => title.setValue(e.target.value)}
+ onFocus={title.onFocus}
+ onBlur={title.onBlur}
+ className="h-8 border-input bg-transparent px-2 shadow-none focus-visible:bg-muted/30"
+ />
+ <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
+ icon={<Type className="size-3.5" />}
+ label={t`description`}
+ htmlFor={descriptionId}
+ >
+ <Textarea
+ id={descriptionId}
+ data-testid="template-description-input"
+ value={description.value}
+ onChange={(e) => description.setValue(e.target.value)}
+ onFocus={description.onFocus}
+ onBlur={description.onBlur}
+ className="min-h-16 resize-none border-input bg-transparent px-2 py-1.5 shadow-none focus-visible:bg-muted/30"
+ />
+ <p className="px-1 pt-0.5 text-[11px] text-muted-foreground">
+ <Trans>Disambiguates similarly-named templates in the menu.</Trans>
+ </p>
+ </PropertyRow>
+ </PropertyDisclosure>
+ );
+}
+
+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/TemplateRow.tsx b/packages/app/src/components/TemplateRow.tsx
index 5e1763db4..0c496647e 100644
--- a/packages/app/src/components/TemplateRow.tsx
+++ b/packages/app/src/components/TemplateRow.tsx
@@ -70,7 +70,7 @@ export function TemplateRow({ template, onEdit, onDelete, onCreate, badge }: Tem
<MoreVertical className="size-4" aria-hidden />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end">
+ <DropdownMenuContent align="end" className="min-w-52">
<DropdownMenuItem onSelect={onEdit}>
<Pencil aria-hidden />
<Trans>Edit</Trans>
diff --git a/packages/app/src/components/TemplatesCard.tsx b/packages/app/src/components/TemplatesCard.tsx
index 9ca14945a..ccf7db2f6 100644
--- a/packages/app/src/components/TemplatesCard.tsx
+++ b/packages/app/src/components/TemplatesCard.tsx
@@ -5,7 +5,6 @@ import { InheritedBadge } from '@/components/FrontmatterRow';
import { NewItemDialog } from '@/components/NewItemDialog';
import { NewTemplateDialog } from '@/components/NewTemplateDialog';
import { TemplateDeleteDialog } from '@/components/TemplateDeleteDialog';
-import { TemplateEditDialog } from '@/components/TemplateEditDialog';
import { TemplateRow } from '@/components/TemplateRow';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -16,6 +15,8 @@ import type {
FolderConfigSnapshot,
TemplateMenuEntry,
} from '@/hooks/use-folder-config';
+import { templateDocName } from '@/lib/managed-artifact-doc-name';
+import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';
interface Props {
folderPath: string;
@@ -25,7 +26,6 @@ interface Props {
}
export function TemplatesCard({ folderPath, state, onChange, folderConfigHandle }: Props) {
- const [editTarget, setEditTarget] = useState<TemplateMenuEntry | null>(null);
const [deleteTarget, setDeleteTarget] = useState<TemplateMenuEntry | null>(null);
const [createFromTemplate, setCreateFromTemplate] = useState<string | null>(null);
const [newOpen, setNewOpen] = useState(false);
@@ -95,7 +95,9 @@ export function TemplatesCard({ folderPath, state, onChange, folderConfigHandle
key={tpl.path}
template={tpl}
onCreate={() => setCreateFromTemplate(tpl.name)}
- onEdit={() => setEditTarget(tpl)}
+ onEdit={() =>
+ openManagedArtifactTab(templateDocName(tpl.source_folder, tpl.name))
+ }
onDelete={() => setDeleteTarget(tpl)}
badge={
tpl.scope === 'inherited' ? (
@@ -111,14 +113,6 @@ export function TemplatesCard({ folderPath, state, onChange, folderConfigHandle
)}
</div>
</section>
- <TemplateEditDialog
- folderPath={folderPath}
- template={editTarget}
- onOpenChange={(open) => {
- if (!open) setEditTarget(null);
- }}
- onSaved={onChange}
- />
<TemplateDeleteDialog
template={deleteTarget}
onOpenChange={(open) => {
@@ -131,7 +125,10 @@ export function TemplatesCard({ folderPath, state, onChange, folderConfigHandle
existingNames={new Set(templates.map((tpl) => tpl.name))}
open={newOpen}
onOpenChange={setNewOpen}
- onCreated={onChange}
+ onCreated={(createdName) => {
+ onChange();
+ openManagedArtifactTab(templateDocName(folderPath, createdName));
+ }}
/>
<NewItemDialog
open={createFromTemplate !== null}
diff --git a/packages/app/src/components/TextViewer.tsx b/packages/app/src/components/TextViewer.tsx
index 7415b644b..c01d0d29f 100644
--- a/packages/app/src/components/TextViewer.tsx
+++ b/packages/app/src/components/TextViewer.tsx
@@ -1,12 +1,13 @@
import { EditorState } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import { codeLanguageForExtension } from '@inkeep/open-knowledge-core';
-import { Trans, useLingui } from '@lingui/react/macro';
import { basicDarkInit, basicLightInit } from '@uiw/codemirror-theme-basic';
import { basicSetup } from 'codemirror';
import { useTheme } from 'next-themes';
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useRef } from 'react';
import { loadCodeMirrorLanguageForExtension } from './text-viewer-languages';
+import { useViewerText, type ViewerTextSource } from './use-viewer-text';
+import { ViewerErrorPane, ViewerLoadingPane } from './ViewerStatusPane';
const darkTheme = basicDarkInit({
settings: {
@@ -22,66 +23,16 @@ const lightTheme = basicLightInit({
},
});
-interface TextViewerProps {
- src: string;
+type TextViewerProps = ViewerTextSource & {
fileName: string;
extension: string;
-}
-
-type FetchState =
- | { status: 'loading' }
- | { status: 'error'; message: string }
- | { status: 'loaded'; content: string };
-
-function useAssetText(src: string): FetchState {
- const { t } = useLingui();
- const [state, setState] = useState<FetchState>({ status: 'loading' });
- useEffect(() => {
- let cancelled = false;
- const ctrl = new AbortController();
- setState({ status: 'loading' });
- fetch(src, { credentials: 'same-origin', signal: ctrl.signal })
- .then(async (resp) => {
- if (!resp.ok) {
- const status = resp.status;
- if (status === 413) {
- throw new Error(
- t`This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app.`,
- );
- }
- if (status === 404) {
- throw new Error(t`This file could not be found.`);
- }
- if (status === 400) {
- throw new Error(t`This file can't be opened in the text editor.`);
- }
- throw new Error(t`Something went wrong opening this file (HTTP ${status}).`);
- }
- return resp.text();
- })
- .then((content) => {
- if (cancelled) return;
- setState({ status: 'loaded', content });
- })
- .catch((err: unknown) => {
- if (cancelled) return;
- if (err instanceof Error && err.name === 'AbortError') return;
- const message = err instanceof Error ? err.message : t`Failed to load file`;
- setState({ status: 'error', message });
- });
- return () => {
- cancelled = true;
- ctrl.abort();
- };
- }, [src, t]);
- return state;
-}
+};
-export function TextViewer({ src, fileName, extension }: TextViewerProps) {
+export function TextViewer({ fileName, extension, ...source }: TextViewerProps) {
const containerRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
const { resolvedTheme } = useTheme();
- const fetchState = useAssetText(src);
+ const fetchState = useViewerText(source);
const loadedContent = fetchState.status === 'loaded' ? fetchState.content : null;
useEffect(() => {
@@ -118,42 +69,22 @@ export function TextViewer({ src, fileName, extension }: TextViewerProps) {
};
}, [loadedContent, extension, resolvedTheme]);
+ const extraAttrs = { 'data-text-viewer-extension': extension };
if (fetchState.status === 'loading') {
return (
- <main
- className="flex h-full min-h-0 flex-col items-center justify-center bg-background text-muted-foreground text-sm"
- aria-label={fileName}
- data-text-viewer=""
- data-text-viewer-state="loading"
- data-text-viewer-extension={extension}
- >
- <span>
- <Trans>Loading {fileName}</Trans>
- </span>
- </main>
+ <ViewerLoadingPane fileName={fileName} dataAttr="data-text-viewer" extraAttrs={extraAttrs} />
);
}
if (fetchState.status === 'error') {
return (
- <main
- className="flex h-full min-h-0 flex-col items-center justify-center gap-2 bg-background p-4 text-center"
- aria-label={fileName}
- data-text-viewer=""
- data-text-viewer-state="error"
- data-text-viewer-extension={extension}
- >
- <div className="font-medium text-sm">
- <Trans>Couldn't load {fileName}</Trans>
- </div>
- <div className="text-muted-foreground text-xs">{fetchState.message}</div>
- <a
- href={src}
- className="mt-2 rounded-md border px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"
- >
- <Trans>Open file</Trans>
- </a>
- </main>
+ <ViewerErrorPane
+ fileName={fileName}
+ dataAttr="data-text-viewer"
+ extraAttrs={extraAttrs}
+ message={fetchState.message}
+ openHref={source.src}
+ />
);
}
diff --git a/packages/app/src/components/ViewerStatusPane.tsx b/packages/app/src/components/ViewerStatusPane.tsx
new file mode 100644
index 000000000..d95b2f50e
--- /dev/null
+++ b/packages/app/src/components/ViewerStatusPane.tsx
@@ -0,0 +1,55 @@
+import { Trans } from '@lingui/react/macro';
+
+interface ViewerStatusPaneBaseProps {
+ fileName: string;
+ dataAttr: string;
+ extraAttrs?: Record<string, string>;
+}
+
+export function ViewerLoadingPane({ fileName, dataAttr, extraAttrs }: ViewerStatusPaneBaseProps) {
+ return (
+ <main
+ className="flex h-full min-h-0 flex-col items-center justify-center bg-background text-muted-foreground text-sm"
+ aria-label={fileName}
+ {...{ [dataAttr]: '', [`${dataAttr}-state`]: 'loading' }}
+ {...extraAttrs}
+ >
+ <span>
+ <Trans>Loading {fileName}</Trans>
+ </span>
+ </main>
+ );
+}
+
+export function ViewerErrorPane({
+ fileName,
+ dataAttr,
+ extraAttrs,
+ message,
+ openHref,
+}: ViewerStatusPaneBaseProps & {
+ message: string;
+ openHref?: string;
+}) {
+ return (
+ <main
+ className="flex h-full min-h-0 flex-col items-center justify-center gap-2 bg-background p-4 text-center"
+ aria-label={fileName}
+ {...{ [dataAttr]: '', [`${dataAttr}-state`]: 'error' }}
+ {...extraAttrs}
+ >
+ <div className="font-medium text-sm">
+ <Trans>Couldn't load {fileName}</Trans>
+ </div>
+ <div className="text-muted-foreground text-xs">{message}</div>
+ {openHref ? (
+ <a
+ href={openHref}
+ className="mt-2 rounded-md border px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"
+ >
+ <Trans>Open file</Trans>
+ </a>
+ ) : null}
+ </main>
+ );
+}
diff --git a/packages/app/src/components/file-tree-adapter.test.ts b/packages/app/src/components/file-tree-adapter.test.ts
index 1a541b7e6..1423dac69 100644
--- a/packages/app/src/components/file-tree-adapter.test.ts
+++ b/packages/app/src/components/file-tree-adapter.test.ts
@@ -77,6 +77,17 @@ describe('file-tree-adapter', () => {
).toEqual(['docs/', 'docs/nested/', 'empty/', 'empty/child/']);
});
+ test('excludes .ok/** from collected folder paths (skills are not tree folders)', () => {
+ expect(
+ collectTreeFolderPathsFromDocuments([
+ doc('docs/guide'),
+ doc('.ok/skills/my-skill/SKILL'),
+ { kind: 'folder', path: '.ok/skills/my-skill', size: 0, modified: '' },
+ doc('notes/.ok/templates/daily'),
+ ]),
+ ).toEqual(['docs/']);
+ });
+
test('computes active ancestor paths using Trees directory slash convention', () => {
expect(computeTreeAncestorPaths('README.md')).toEqual([]);
expect(computeTreeAncestorPaths('docs/guide.md')).toEqual(['docs/']);
diff --git a/packages/app/src/components/file-tree-adapter.ts b/packages/app/src/components/file-tree-adapter.ts
index cca9b71fb..d1912d53e 100644
--- a/packages/app/src/components/file-tree-adapter.ts
+++ b/packages/app/src/components/file-tree-adapter.ts
@@ -67,16 +67,17 @@ export function documentsTreePathSignature(documents: readonly FileEntry[]): str
export function collectTreeFolderPathsFromDocuments(documents: readonly FileEntry[]): string[] {
const folderPaths = new Set<string>();
for (const entry of documents) {
- if (isFolderEntry(entry)) {
- const folderPath = folderPathToTreeDirectoryPath(entry.path);
- if (folderPath) folderPaths.add(folderPath);
- }
const path = isFolderEntry(entry)
? entry.path
: isAssetEntry(entry)
? entry.path
: entry.docName;
const segments = path.split('/').filter(Boolean);
+ if (segments.includes('.ok')) continue;
+ if (isFolderEntry(entry)) {
+ const folderPath = folderPathToTreeDirectoryPath(entry.path);
+ if (folderPath) folderPaths.add(folderPath);
+ }
const folderSegmentLimit = isFolderEntry(entry) ? segments.length : segments.length - 1;
for (let i = 1; i <= folderSegmentLimit; i++) {
folderPaths.add(`${segments.slice(0, i).join('/')}/`);
diff --git a/packages/app/src/components/file-tree-selection.ts b/packages/app/src/components/file-tree-selection.ts
index 73a4665b6..34223158e 100644
--- a/packages/app/src/components/file-tree-selection.ts
+++ b/packages/app/src/components/file-tree-selection.ts
@@ -67,6 +67,7 @@ export function resolveFileTreeSelection(
navigationPath: null,
};
case 'asset':
+ case 'skill-file':
return {
selectedFilePath: null,
selectedFolderPath: null,
diff --git a/packages/app/src/components/handoff/useHandoffDispatch.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.test.ts
index 8a4524ec4..b17dbf079 100644
--- a/packages/app/src/components/handoff/useHandoffDispatch.test.ts
+++ b/packages/app/src/components/handoff/useHandoffDispatch.test.ts
@@ -634,6 +634,50 @@ describe('buildHandoffInput — shared surface helper (US-011)', () => {
});
});
+describe('buildSkillHandoffInput + selectScopedPrompt — skill scope (author-with-AI)', () => {
+ test('null workspace or empty name returns null', async () => {
+ const { buildSkillHandoffInput } = await import('./useHandoffDispatch');
+ expect(
+ buildSkillHandoffInput({ skillName: 'x', scope: 'project', workspace: null }),
+ ).toBeNull();
+ expect(
+ buildSkillHandoffInput({
+ skillName: '',
+ scope: 'project',
+ workspace: { contentDir: '/repo', pathSeparator: '/' },
+ }),
+ ).toBeNull();
+ });
+
+ test('carries the skill name + scope; no doc path (agent reaches it via OK MCP)', async () => {
+ const { buildSkillHandoffInput } = await import('./useHandoffDispatch');
+ const input = buildSkillHandoffInput({
+ skillName: 'commit-helper',
+ scope: 'global',
+ workspace: { contentDir: '/Users/sarah/proj', pathSeparator: '/' },
+ });
+ expect(input).toEqual({
+ docContext: null,
+ skill: { name: 'commit-helper', scope: 'global' },
+ projectDir: '/Users/sarah/proj',
+ docPath: '',
+ });
+ });
+
+ test('selectScopedPrompt routes a skill input to composeSkillPrompt', async () => {
+ const { buildSkillHandoffInput, selectScopedPrompt } = await import('./useHandoffDispatch');
+ const input = buildSkillHandoffInput({
+ skillName: 'commit-helper',
+ scope: 'project',
+ workspace: { contentDir: '/repo', pathSeparator: '/' },
+ });
+ if (!input) throw new Error('expected a non-null skill input');
+ expect(selectScopedPrompt(input, 'claude-code', true)).toBe(
+ 'Use your open-knowledge-write-skill skill to author the project Open Knowledge skill `commit-helper`. Edit it with the Open Knowledge tools. Open the OK editor in web view.',
+ );
+ });
+});
+
describe('buildProjectScopedHandoffInput — empty-state cards helper', () => {
test('null workspace returns null (cards render disabled while resolving)', async () => {
const { buildProjectScopedHandoffInput } = await import('./useHandoffDispatch');
@@ -1464,7 +1508,7 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +
expect(composeTerminalLaunchPrompt(input, 'cursor')).toBe(claudeOut);
});
- test('typed instruction is preserved per CLI (keeps the directive composer, no "stop")', async () => {
+ test('typed instruction is preserved per CLI, led by the terminal-surface preamble', async () => {
const { composeTerminalLaunchPrompt, selectScopedPrompt } = await import(
'./useHandoffDispatch'
);
@@ -1475,17 +1519,18 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +
instruction: 'summarize the open questions',
};
expect(composeTerminalLaunchPrompt(input, 'claude')).toBe(
- selectScopedPrompt(input, 'claude-code', false),
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,
);
expect(composeTerminalLaunchPrompt(input, 'codex')).toBe(
- selectScopedPrompt(input, 'codex', false),
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'codex', false)}`,
);
expect(composeTerminalLaunchPrompt(input, 'cursor')).toBe(
- selectScopedPrompt(input, 'cursor', false),
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'cursor', false)}`,
);
const claudeOut = composeTerminalLaunchPrompt(input, 'claude');
expect(claudeOut).toContain('summarize the open questions');
- expect(claudeOut).not.toContain(OK_TERMINAL_SURFACE_PREAMBLE);
+ expect(claudeOut).toContain(OK_TERMINAL_SURFACE_PREAMBLE);
+ expect(claudeOut).not.toContain('Then stop.');
});
test('composer (compose scope) threads the typed instruction — NOT a bare launch', async () => {
@@ -1504,18 +1549,18 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +
docPath: '/proj/notes/work-log.md',
};
expect(composeTerminalLaunchPrompt(input, 'claude')).toBe(
- selectScopedPrompt(input, 'claude-code', false),
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,
);
expect(composeTerminalLaunchPrompt(input, 'codex')).toBe(
- selectScopedPrompt(input, 'codex', false),
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'codex', false)}`,
);
expect(composeTerminalLaunchPrompt(input, 'cursor')).toBe(
- selectScopedPrompt(input, 'cursor', false),
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'cursor', false)}`,
);
const claudeOut = composeTerminalLaunchPrompt(input, 'claude');
expect(claudeOut).toContain('What does this file do?');
expect(claudeOut).not.toBe(composeTerminalBareLaunchPrompt('notes/work-log.md'));
- expect(claudeOut).not.toContain(OK_TERMINAL_SURFACE_PREAMBLE);
+ expect(claudeOut).toContain(OK_TERMINAL_SURFACE_PREAMBLE);
});
test('whitespace-only instruction is treated as a bare launch', async () => {
@@ -1547,9 +1592,11 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +
docPath: '',
};
const out = composeTerminalLaunchPrompt(input, 'claude');
- expect(out).toBe(selectScopedPrompt(input, 'claude-code', false));
+ expect(out).toBe(
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,
+ );
expect(out).toContain('a fishing log');
- expect(out).not.toContain(OK_TERMINAL_SURFACE_PREAMBLE);
+ expect(out).toContain(OK_TERMINAL_SURFACE_PREAMBLE);
});
test('empty create brief still routes to the directive composer (createDescription !== undefined)', async () => {
@@ -1564,9 +1611,11 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +
docPath: '',
};
const out = composeTerminalLaunchPrompt(input, 'claude');
- expect(out).toBe(selectScopedPrompt(input, 'claude-code', false));
+ expect(out).toBe(
+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,
+ );
expect(out).not.toBe(composeTerminalBareLaunchPrompt(null));
- expect(out).not.toContain(OK_TERMINAL_SURFACE_PREAMBLE);
+ expect(out).toContain(OK_TERMINAL_SURFACE_PREAMBLE);
});
test('bare terminal launch never carries the web-view preview trailer', async () => {
diff --git a/packages/app/src/components/handoff/useHandoffDispatch.ts b/packages/app/src/components/handoff/useHandoffDispatch.ts
index 8916ba5b8..3c723e3d6 100644
--- a/packages/app/src/components/handoff/useHandoffDispatch.ts
+++ b/packages/app/src/components/handoff/useHandoffDispatch.ts
@@ -9,12 +9,15 @@ import {
composeFilePrompt,
composeFolderPrompt,
composeSelectionPrompt,
+ composeSkillPrompt,
composeTerminalBareLaunchPrompt,
type DocContext,
type HandoffOutcome,
type HandoffPayload,
type HandoffScope,
type HandoffTarget,
+ OK_TERMINAL_SURFACE_PREAMBLE,
+ type SkillScope,
type TargetData,
TERMINAL_CLIS,
type TerminalCli,
@@ -86,6 +89,11 @@ export interface HandoffDispatchInput {
* it lives in and the user's instruction. Set for selection scope only;
* absent for file / folder / project scope. */
readonly selection?: SelectionContext;
+ /** Skill-scope payload — the skill's identity + which store it lives in.
+ * Set by `buildSkillHandoffInput`; absent for every other scope. Routes
+ * `selectScopedPrompt` to `composeSkillPrompt` (author-with-AI: hand the
+ * draft to an agent to write via the `open-knowledge-write-skill` skill). */
+ readonly skill?: { readonly name: string; readonly scope: SkillScope };
/** Ask-scope payload — the active doc's relative path plus the user's typed
* instruction, with NO selection. Set for the bottom "Ask AI" composer
* only; absent for every other scope. A dedicated discriminator rather than
@@ -212,6 +220,20 @@ export function buildSelectionHandoffInput(args: {
};
}
+export function buildSkillHandoffInput(args: {
+ readonly skillName: string;
+ readonly scope: SkillScope;
+ readonly workspace: Workspace | null;
+}): HandoffDispatchInput | null {
+ if (!args.workspace?.contentDir || !args.skillName) return null;
+ return {
+ docContext: null,
+ skill: { name: args.skillName, scope: args.scope },
+ projectDir: args.workspace.contentDir,
+ docPath: '',
+ };
+}
+
export function buildAskHandoffInput(args: {
readonly docName: string | null;
readonly workspace: Workspace | null;
@@ -396,6 +418,9 @@ export function selectScopedPrompt(
if (input.selection) {
return composeSelectionPrompt({ ...input.selection, target });
}
+ if (input.skill) {
+ return composeSkillPrompt(input.skill.name, input.skill.scope, autoOpen);
+ }
if (input.ask) {
return composeAskPrompt(input.ask.relativePath, input.ask.instruction, autoOpen, target);
}
@@ -418,7 +443,7 @@ export function selectScopedPrompt(
export function composeTerminalLaunchPrompt(input: HandoffDispatchInput, cli: TerminalCli): string {
const hasInstruction = typeof input.instruction === 'string' && input.instruction.trim() !== '';
if (input.compose !== undefined || input.createDescription !== undefined || hasInstruction) {
- return selectScopedPrompt(input, TERMINAL_CLIS[cli].handoffTarget, false);
+ return `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, TERMINAL_CLIS[cli].handoffTarget, false)}`;
}
return composeTerminalBareLaunchPrompt(input.docContext?.relativePath ?? null);
}
diff --git a/packages/app/src/components/link-target-intent.test.ts b/packages/app/src/components/link-target-intent.test.ts
index ff387e267..37edb7598 100644
--- a/packages/app/src/components/link-target-intent.test.ts
+++ b/packages/app/src/components/link-target-intent.test.ts
@@ -12,6 +12,7 @@ describe('resolveLinkTargetIntent', () => {
docName: 'reports',
},
hashDocName: 'reports',
+ hash: null,
});
});
@@ -27,6 +28,7 @@ describe('resolveLinkTargetIntent', () => {
noteKind: 'canonical-index',
},
hashDocName: 'reports',
+ hash: null,
});
});
@@ -42,6 +44,7 @@ describe('resolveLinkTargetIntent', () => {
noteKind: 'legacy-folder-note',
},
hashDocName: 'reports',
+ hash: null,
});
});
@@ -60,6 +63,7 @@ describe('resolveLinkTargetIntent', () => {
folderPath: 'reports',
},
hashDocName: 'reports',
+ hash: null,
});
});
@@ -95,6 +99,27 @@ describe('resolveLinkTargetIntent', () => {
docName: 'my-notes',
},
hashDocName: 'my-notes',
+ hash: null,
+ });
+ });
+
+ test('navigates a skill-bundle reference to the read-only viewer instead of create-page', () => {
+ expect(
+ resolveLinkTargetIntent('__skill__/global/test/references/notes', {
+ pages: new Set<string>(),
+ }),
+ ).toEqual({
+ kind: 'navigate',
+ displayState: 'resolved',
+ resolvedTarget: {
+ kind: 'skill-file',
+ target: 'global/test/references/notes.md',
+ scope: 'global',
+ name: 'test',
+ path: 'references/notes.md',
+ },
+ hashDocName: 'global/test/references/notes.md',
+ hash: '#/__skill-file__/global/test/references/notes.md',
});
});
});
diff --git a/packages/app/src/components/link-target-intent.ts b/packages/app/src/components/link-target-intent.ts
index 75a8abfa1..0ffa66708 100644
--- a/packages/app/src/components/link-target-intent.ts
+++ b/packages/app/src/components/link-target-intent.ts
@@ -1,3 +1,4 @@
+import { hashFromSkillFile } from '@/lib/doc-hash';
import { docNameToDialogSeed } from '@/lib/doc-paths';
import { type ResolvedNavigationTarget, resolveNavigationTarget } from './navigation-targets';
@@ -5,14 +6,16 @@ type NavigableTarget = Extract<
ResolvedNavigationTarget,
{ kind: 'doc' | 'folder-index' | 'folder' | 'large-file' }
>;
+type SkillFileTarget = Extract<ResolvedNavigationTarget, { kind: 'skill-file' }>;
type MissingTarget = Extract<ResolvedNavigationTarget, { kind: 'missing' }>;
type LinkTargetIntent =
| {
kind: 'navigate';
displayState: 'resolved' | 'folder';
- resolvedTarget: NavigableTarget;
+ resolvedTarget: NavigableTarget | SkillFileTarget;
hashDocName: string;
+ hash: string | null;
}
| {
kind: 'create';
@@ -22,6 +25,20 @@ type LinkTargetIntent =
suggestedName: string;
};
+/** A `skill-file` resolves to the read-only bundle-file viewer — navigable, not a
+ * missing page. Build the navigate intent with its kind-aware viewer hash. */
+function skillFileNavigate(
+ target: SkillFileTarget,
+): Extract<LinkTargetIntent, { kind: 'navigate' }> {
+ return {
+ kind: 'navigate',
+ displayState: 'resolved',
+ resolvedTarget: target,
+ hashDocName: target.target,
+ hash: hashFromSkillFile({ scope: target.scope, name: target.name, path: target.path }),
+ };
+}
+
export function resolveLinkTargetIntent(
target: string,
options: {
@@ -50,6 +67,7 @@ export function resolveLinkTargetIntent(
pagesBySlug: options.pagesBySlug,
pagesByBasename: options.pagesByBasename,
});
+ if (resolvedTarget.kind === 'skill-file') return skillFileNavigate(resolvedTarget);
if (resolvedTarget.kind === 'asset') continue;
if (resolvedTarget.kind === 'missing') {
missingTarget ??= resolvedTarget;
@@ -60,6 +78,7 @@ export function resolveLinkTargetIntent(
displayState: resolvedTarget.kind === 'folder' ? 'folder' : 'resolved',
resolvedTarget,
hashDocName: resolvedTarget.target,
+ hash: null,
};
}
@@ -71,12 +90,14 @@ export function resolveLinkTargetIntent(
pagesBySlug: options.pagesBySlug,
pagesByBasename: options.pagesByBasename,
});
+ if (resolvedFallback.kind === 'skill-file') return skillFileNavigate(resolvedFallback);
if (resolvedFallback.kind !== 'missing' && resolvedFallback.kind !== 'asset') {
return {
kind: 'navigate',
displayState: resolvedFallback.kind === 'folder' ? 'folder' : 'resolved',
resolvedTarget: resolvedFallback,
hashDocName: resolvedFallback.target,
+ hash: null,
};
}
const finalMissingTarget: MissingTarget =
diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.ts
index 520cffdf2..eff6b11ef 100644
--- a/packages/app/src/components/navigation-targets.test.ts
+++ b/packages/app/src/components/navigation-targets.test.ts
@@ -18,6 +18,67 @@ describe('deriveKnownFolderPaths', () => {
});
describe('resolveNavigationTarget', () => {
+ test('resolves managed-artifact docs as real doc targets (never missing)', () => {
+ for (const docName of ['__skill__/global/foo', '__template__/notes/daily']) {
+ expect(resolveNavigationTarget(docName, { pages: new Set() })).toEqual({
+ kind: 'doc',
+ target: docName,
+ docName,
+ });
+ }
+ });
+
+ test('resolves a GLOBAL skill bundle reference node to a read-only skill-file target', () => {
+ 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',
+ });
+ 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',
+ });
+ });
+
+ test('the GLOBAL SKILL doc itself stays a normal editor doc target (not skill-file)', () => {
+ expect(resolveNavigationTarget('__skill__/global/demo', { pages: new Set() })).toEqual({
+ kind: 'doc',
+ target: '__skill__/global/demo',
+ docName: '__skill__/global/demo',
+ });
+ });
+
+ test('redirects a stale `__skill__/project/<name>` deep-link to the content doc', () => {
+ expect(resolveNavigationTarget('__skill__/project/foo', { pages: new Set() })).toEqual({
+ kind: 'doc',
+ target: '.ok/skills/foo/SKILL',
+ docName: '.ok/skills/foo/SKILL',
+ });
+ });
+
+ test('resolves a skill file-path link as content and a template link to its artifact', () => {
+ const skillDoc = '.ok/skills/open-knowledge-pack-knowledge-base/SKILL';
+ expect(resolveNavigationTarget(skillDoc, { pages: new Set([skillDoc]) })).toEqual({
+ kind: 'doc',
+ target: skillDoc,
+ docName: skillDoc,
+ });
+ expect(resolveNavigationTarget('notes/.ok/templates/daily', { pages: new Set() })).toEqual({
+ kind: 'doc',
+ target: '__template__/notes/daily',
+ docName: '__template__/notes/daily',
+ });
+ });
+
test('prefers an exact document over folder landing notes', () => {
const resolved = resolveNavigationTarget('reports', {
pages: new Set(['reports', 'reports/index', 'reports/reports']),
diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.ts
index bbd27c32c..6673758c1 100644
--- a/packages/app/src/components/navigation-targets.ts
+++ b/packages/app/src/components/navigation-targets.ts
@@ -2,6 +2,12 @@ import {
DOCUMENT_OPEN_BYTE_LIMIT,
type InlineAssetMediaKind,
isDocumentOverOpenByteLimit,
+ isManagedArtifactDocName,
+ managedArtifactDocNameFromContentTarget,
+ parseGlobalSkillBundleDoc,
+ parseManagedArtifactName,
+ projectSkillContentDocName,
+ type SkillScope,
toWikiLinkSlug,
} from '@inkeep/open-knowledge-core';
import { normalizeDocNameInput } from '@/lib/doc-paths';
@@ -31,6 +37,13 @@ export type ResolvedNavigationTarget =
assetPath: string;
mediaKind: InlineAssetMediaKind | null;
}
+ | {
+ kind: 'skill-file';
+ target: string;
+ scope: SkillScope;
+ name: string;
+ path: string;
+ }
| {
kind: 'large-file';
target: string;
@@ -95,6 +108,29 @@ export function resolveNavigationTarget(
pagesByBasename?: ReadonlyMap<string, string>;
},
): ResolvedNavigationTarget {
+ if (isManagedArtifactDocName(target)) {
+ 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,
+ };
+ }
+ const parsed = parseManagedArtifactName(target);
+ if (parsed?.kind === 'skill' && parsed.scope === 'project') {
+ const docName = projectSkillContentDocName(parsed.name);
+ return { kind: 'doc', target: docName, docName };
+ }
+ return { kind: 'doc', target, docName: target };
+ }
+ const artifactDocName = managedArtifactDocNameFromContentTarget(target);
+ if (artifactDocName) {
+ return { kind: 'doc', target: artifactDocName, docName: artifactDocName };
+ }
const { normalizedTarget, expectsFolder } = normalizeTargetPath(target);
if (!normalizedTarget) {
return { kind: 'missing', target: normalizedTarget };
@@ -214,6 +250,7 @@ export function docNameForNavigationTarget(target: ResolvedNavigationTarget): st
case 'missing':
return target.target;
case 'asset':
+ case 'skill-file':
case 'folder':
return null;
}
diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsx
index e892c480a..c74559e1f 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx
@@ -72,6 +72,7 @@ import { EmbeddingsKeySection } from './EmbeddingsKeySection';
import { OkignoreSection } from './OkignoreSection';
import { ProjectTemplatesSection } from './ProjectTemplatesSection';
import { SearchSection } from './SearchSection';
+import { SkillsManagerSection } from './SkillsManagerSection';
import {
getEnumOptions,
getFieldDefault,
@@ -163,6 +164,9 @@ export function SettingsDialogBody({
if (activeId === 'project-templates') {
return <ProjectTemplatesSection />;
}
+ if (activeId === 'skills') {
+ return <SkillsManagerSection />;
+ }
if (activeId === 'sharing') {
return <SharingSection />;
}
diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsx
index bb3828574..f8a1e1c1d 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx
@@ -70,6 +70,7 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP
{ id: 'search', label: t`Search` },
...(isOkDesktopHost ? [{ id: 'terminal', label: t`Terminal` }] : []),
{ id: 'project-templates', label: t`Templates` },
+ { id: 'skills', label: t`Skills` },
{ id: 'okignore', label: t`Ignore patterns` },
{ id: 'sharing', label: t`Config sharing` },
],
diff --git a/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx b/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
new file mode 100644
index 000000000..d516d1ad2
--- /dev/null
+++ b/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
@@ -0,0 +1,83 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+
+mock.module('@lingui/react/macro', () => ({
+ 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;
+ if (i < values.length) out += String(values[i]);
+ });
+ return out;
+ },
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: { error: mock(() => {}), info: mock(() => {}), success: mock(() => {}) },
+}));
+
+const { SkillTargetsPicker } = await import('./SkillTargetsPicker');
+
+const realFetch = global.fetch;
+afterEach(() => {
+ cleanup();
+ global.fetch = realFetch;
+});
+
+describe('SkillTargetsPicker', () => {
+ test('renders a checkbox per editor reflecting the committed set', async () => {
+ global.fetch = mock(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ targets: ['claude'], configured: true }),
+ })) as unknown as typeof fetch;
+
+ render(<SkillTargetsPicker />);
+
+ await waitFor(() => expect(screen.getByTestId('skill-target-claude')).toBeDefined());
+ 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();
+ });
+
+ test('toggling an editor PUTs the updated target set', async () => {
+ const calls: Array<{ url: string; method?: string; body?: string }> = [];
+ global.fetch = mock(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 }),
+ };
+ }) as unknown as typeof fetch;
+
+ render(<SkillTargetsPicker />);
+ await waitFor(() => expect(screen.getByTestId('skill-target-cursor')).toBeDefined());
+
+ fireEvent.click(screen.getByTestId('skill-target-cursor'));
+
+ 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[] };
+ expect(new Set(sent.targets)).toEqual(new Set(['claude', 'cursor']));
+ });
+});
diff --git a/packages/app/src/components/settings/SkillTargetsPicker.tsx b/packages/app/src/components/settings/SkillTargetsPicker.tsx
new file mode 100644
index 000000000..6d127f896
--- /dev/null
+++ b/packages/app/src/components/settings/SkillTargetsPicker.tsx
@@ -0,0 +1,91 @@
+import {
+ EDITOR_LABELS,
+ PROJECT_SKILL_EDITOR_IDS,
+ type SkillTargetEditor,
+} from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { toast } from 'sonner';
+import { Checkbox } from '@/components/ui/checkbox';
+import { Label } from '@/components/ui/label';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useSkillTargets } from '@/hooks/use-skill-targets';
+
+export function SkillTargetsPicker() {
+ const { t } = useLingui();
+ const { state, save, saving } = useSkillTargets();
+ const headingId = 'settings-skill-targets-heading';
+
+ const editors = PROJECT_SKILL_EDITOR_IDS as readonly SkillTargetEditor[];
+
+ const selected = state.status === 'ready' ? new Set(state.data.targets) : new Set<string>();
+
+ 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)}`,
+ );
+ }
+ };
+
+ return (
+ <section
+ aria-labelledby={headingId}
+ className="space-y-2 rounded-lg border bg-card p-3"
+ data-testid="settings-skill-targets"
+ >
+ <div>
+ <h4 id={headingId} className="text-sm font-medium">
+ <Trans>Install skills into</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>
+ )}
+ </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>
+ </div>
+ ) : state.status === 'idle' || state.status === 'loading' ? (
+ <div className="space-y-2 pt-1">
+ <Skeleton className="h-5 w-40" />
+ <Skeleton className="h-5 w-40" />
+ </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}`;
+ 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>
+ );
+ })}
+ </fieldset>
+ )}
+ </section>
+ );
+}
diff --git a/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx b/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
new file mode 100644
index 000000000..69ab3a97b
--- /dev/null
+++ b/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
@@ -0,0 +1,113 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { SkillsListSuccess } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+
+mock.module('@lingui/react/macro', () => ({
+ 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;
+ if (i < values.length) out += String(values[i]);
+ });
+ return out;
+ },
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: { error: mock(() => {}), info: mock(() => {}), success: mock(() => {}) },
+}));
+mock.module('@/components/handoff/OpenInAgentMenu', () => ({
+ OpenInAgentMenu: () => null,
+}));
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ openDocument: () => {} }),
+}));
+
+const { SkillsManagerSection } = await import('./SkillsManagerSection');
+
+const realFetch = global.fetch;
+afterEach(() => {
+ cleanup();
+ global.fetch = realFetch;
+});
+
+const EMPTY_TARGETS = { targets: [], configured: false };
+
+function routeFetch(
+ skillsResponse: () => { ok: boolean; status: number; json: () => Promise<unknown> },
+) {
+ global.fetch = mock(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' }) }));
+}
+
+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());
+
+ const installedRow = screen.getByTestId('skill-row-trip-log');
+ expect(installedRow.textContent).toContain('Installed');
+ expect(installedRow.textContent).toContain('claude');
+ expect(installedRow.textContent).toContain('cursor');
+
+ const draftRow = screen.getByTestId('skill-row-draft-skill');
+ expect(draftRow.textContent).toContain('Draft');
+ expect(draftRow.textContent?.toLowerCase()).toContain('description');
+
+ 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());
+ });
+});
diff --git a/packages/app/src/components/settings/SkillsManagerSection.tsx b/packages/app/src/components/settings/SkillsManagerSection.tsx
new file mode 100644
index 000000000..864458ae1
--- /dev/null
+++ b/packages/app/src/components/settings/SkillsManagerSection.tsx
@@ -0,0 +1,188 @@
+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 { 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 } from '@/lib/open-managed-artifact-tab';
+import { SKILL_SCOPE_ORDER, useSkillScopeLabels } from '@/lib/skill-scope';
+import { useSettingsRoute } from '@/lib/use-settings-route';
+
+interface ScopeGroupChrome {
+ title: ReactNode;
+ blurb: ReactNode;
+ 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);
+
+ function openSkillTab(scope: SkillScope, name: string) {
+ openManagedArtifactTab(skillLiveDocName(scope, name));
+ settingsRoute.close();
+ }
+
+ const actions = useSkillActions();
+
+ 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">
+ <Trans>
+ Skills teach agents repeatable tasks. Author them here; install a skill to project it
+ into your editors' skill folders.
+ </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>
+ </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()));
+ 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.scope, skill.name)}
+ 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>
+ </section>
+ );
+}
diff --git a/packages/app/src/components/settings/TemplatesManagerSection.tsx b/packages/app/src/components/settings/TemplatesManagerSection.tsx
index bb310eb45..dd6f346cc 100644
--- a/packages/app/src/components/settings/TemplatesManagerSection.tsx
+++ b/packages/app/src/components/settings/TemplatesManagerSection.tsx
@@ -3,12 +3,14 @@ import { Plus } from 'lucide-react';
import { type ReactNode, useState } from 'react';
import { NewTemplateDialog } from '@/components/NewTemplateDialog';
import { TemplateDeleteDialog } from '@/components/TemplateDeleteDialog';
-import { TemplateEditDialog } from '@/components/TemplateEditDialog';
import { TemplateRow } from '@/components/TemplateRow';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { type TemplateMenuEntry, useFolderConfig } from '@/hooks/use-folder-config';
+import { templateDocName } from '@/lib/managed-artifact-doc-name';
+import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';
+import { useSettingsRoute } from '@/lib/use-settings-route';
interface TemplatesManagerConfig {
scope: TemplateMenuEntry['scope'];
@@ -23,9 +25,14 @@ interface TemplatesManagerConfig {
export function TemplatesManagerSection({ config }: { config: TemplatesManagerConfig }) {
const { state, refresh } = useFolderConfig('');
- const [editTarget, setEditTarget] = useState<TemplateMenuEntry | null>(null);
const [deleteTarget, setDeleteTarget] = useState<TemplateMenuEntry | null>(null);
const [newOpen, setNewOpen] = useState(false);
+ const settingsRoute = useSettingsRoute();
+
+ function openTemplateTab(folder: string, name: string) {
+ openManagedArtifactTab(templateDocName(folder, name));
+ settingsRoute.close();
+ }
const templates: TemplateMenuEntry[] =
state.status === 'ready'
@@ -59,7 +66,10 @@ export function TemplatesManagerSection({ config }: { config: TemplatesManagerCo
existingNames={new Set()}
open={newOpen}
onOpenChange={setNewOpen}
- onCreated={refresh}
+ onCreated={(createdName) => {
+ refresh();
+ openTemplateTab('', createdName);
+ }}
/>
</section>
);
@@ -102,7 +112,7 @@ export function TemplatesManagerSection({ config }: { config: TemplatesManagerCo
<TemplateRow
key={tpl.name}
template={tpl}
- onEdit={() => setEditTarget(tpl)}
+ onEdit={() => openTemplateTab(tpl.source_folder, tpl.name)}
onDelete={() => setDeleteTarget(tpl)}
badge={
<Badge variant={config.badge.variant} className="text-2xs">
@@ -120,15 +130,10 @@ export function TemplatesManagerSection({ config }: { config: TemplatesManagerCo
existingNames={new Set(templates.map((tpl) => tpl.name))}
open={newOpen}
onOpenChange={setNewOpen}
- onCreated={refresh}
- />
- <TemplateEditDialog
- folderPath=""
- template={editTarget}
- onOpenChange={(open) => {
- if (!open) setEditTarget(null);
+ onCreated={(createdName) => {
+ refresh();
+ openTemplateTab('', createdName);
}}
- onSaved={refresh}
/>
<TemplateDeleteDialog
template={deleteTarget}
diff --git a/packages/app/src/components/skill-actions.tsx b/packages/app/src/components/skill-actions.tsx
new file mode 100644
index 000000000..38acd716c
--- /dev/null
+++ b/packages/app/src/components/skill-actions.tsx
@@ -0,0 +1,305 @@
+import {
+ EDITOR_LABELS,
+ type SkillInstallWarningCode,
+ type SkillsListEntry,
+} from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import {
+ Copy,
+ CopyPlus,
+ DownloadCloud,
+ FolderOpen,
+ Pencil,
+ PencilLine,
+ PowerOff,
+ RefreshCw,
+ Trash2,
+} from 'lucide-react';
+import { type ReactNode, useState } from 'react';
+import { toast } from 'sonner';
+import { OpenInAgentContextSubmenu } from '@/components/handoff/OpenInAgentContextSubmenu';
+import {
+ buildSkillHandoffInput,
+ useHandoffDispatch,
+} from '@/components/handoff/useHandoffDispatch';
+import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
+import { SkillDeleteDialog } from '@/components/SkillDeleteDialog';
+import { SkillRenameDialog } from '@/components/SkillRenameDialog';
+import { SkillUpdateDialog } from '@/components/SkillUpdateDialog';
+import {
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from '@/components/ui/dropdown-menu';
+import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
+import { duplicateSkill, installSkill, uninstallSkill } from '@/lib/skills-api';
+import { useWorkspace } from '@/lib/use-workspace';
+
+export interface SkillActions {
+ installingName: string | null;
+ install: (
+ skill: SkillsListEntry,
+ targets?: readonly string[],
+ ) => Promise<Awaited<ReturnType<typeof installSkill>>>;
+ uninstall: (skill: SkillsListEntry) => Promise<Awaited<ReturnType<typeof uninstallSkill>>>;
+ duplicate: (skill: SkillsListEntry, existingNames: ReadonlySet<string>) => Promise<void>;
+ requestDelete: (skill: SkillsListEntry) => void;
+ requestUpdate: (skill: SkillsListEntry) => void;
+ requestRename: (skill: SkillsListEntry, existingNames: ReadonlySet<string>) => void;
+ dialogs: ReactNode;
+}
+
+export function useSkillActions(): SkillActions {
+ const { t } = useLingui();
+ 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 [installingName, setInstallingName] = useState<string | null>(null);
+
+ async function install(skill: SkillsListEntry, targets?: readonly string[]) {
+ setInstallingName(skill.name);
+ const result = await installSkill({
+ scope: skill.scope,
+ name: skill.name,
+ ...(targets ? { targets: [...targets] } : {}),
+ });
+ setInstallingName(null);
+ if (!result.ok) {
+ toast.error(t`Couldn't install skill: ${result.error}`);
+ return result;
+ }
+ const label = (ids: readonly string[]) =>
+ ids.map((id) => EDITOR_LABELS[id as keyof typeof EDITOR_LABELS] ?? id).join(', ');
+ const now = new Set(result.hosts);
+ const added = result.hosts.filter((h) => !skill.hosts.includes(h));
+ const removed = skill.hosts.filter((h) => !now.has(h));
+
+ const messageFor = (code: SkillInstallWarningCode): string | undefined => {
+ const i = result.warningCodes.indexOf(code);
+ return i >= 0 ? result.warnings[i] : undefined;
+ };
+ const noTargetsWarning = messageFor('no-targets');
+ if (noTargetsWarning) {
+ toast.warning(noTargetsWarning);
+ return result;
+ }
+ if (added.length > 0) {
+ const scriptsWarning = messageFor('scripts-present');
+ if (scriptsWarning) toast.warning(scriptsWarning);
+ }
+
+ if (result.hosts.length === 0) {
+ toast.success(t`"${skill.name}" uninstalled — back to a draft`);
+ } 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) {
+ toast.success(t`Uninstalled "${skill.name}" from ${label(removed)}`);
+ } else if (added.length > 0 && removed.length > 0) {
+ toast.success(t`Updated "${skill.name}": added ${label(added)}, removed ${label(removed)}`);
+ } else {
+ toast.success(t`"${skill.name}" install refreshed (${label(result.hosts)})`);
+ }
+ return result;
+ }
+
+ async function uninstall(skill: SkillsListEntry) {
+ setInstallingName(skill.name);
+ const result = await uninstallSkill({ scope: skill.scope, name: skill.name });
+ 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;
+ }
+
+ async function duplicate(skill: SkillsListEntry, existingNames: ReadonlySet<string>) {
+ const result = await duplicateSkill({ scope: skill.scope, name: skill.name, existingNames });
+ if (!result.ok) {
+ toast.error(t`Couldn't duplicate "${skill.name}": ${result.error}`);
+ return;
+ }
+ toast.success(t`Duplicated to "${result.name}"`);
+ }
+
+ const dialogs = (
+ <>
+ <SkillDeleteDialog
+ skill={deleteTarget}
+ onOpenChange={(open) => {
+ if (!open) setDeleteTarget(null);
+ }}
+ onDeleted={() => setDeleteTarget(null)}
+ />
+ <SkillRenameDialog
+ skill={renameTarget?.skill ?? null}
+ existingNames={renameTarget?.existingNames ?? EMPTY_NAME_SET}
+ onOpenChange={(open) => {
+ if (!open) setRenameTarget(null);
+ }}
+ onRenamed={() => setRenameTarget(null)}
+ />
+ <SkillUpdateDialog
+ skill={updateTarget}
+ onOpenChange={(open) => {
+ if (!open) setUpdateTarget(null);
+ }}
+ onUpdated={() => setUpdateTarget(null)}
+ />
+ </>
+ );
+
+ return {
+ installingName,
+ install,
+ uninstall,
+ duplicate,
+ requestDelete: setDeleteTarget,
+ requestRename: (skill, existingNames) => setRenameTarget({ skill, existingNames }),
+ requestUpdate: setUpdateTarget,
+ dialogs,
+ };
+}
+
+const EMPTY_NAME_SET: ReadonlySet<string> = new Set();
+
+export function SkillActionMenuItems({
+ skill,
+ onEdit,
+ onInstall,
+ onUninstall,
+ onDelete,
+}: {
+ skill: SkillsListEntry;
+ onEdit: () => void;
+ onInstall?: () => void;
+ onUninstall: () => void;
+ onDelete: () => void;
+}) {
+ return (
+ <>
+ <DropdownMenuItem onSelect={onEdit}>
+ <Pencil aria-hidden />
+ <Trans>Edit</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>
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem variant="destructive" onSelect={onDelete}>
+ <Trash2 aria-hidden />
+ <Trans>Delete</Trans>
+ </DropdownMenuItem>
+ </>
+ );
+}
+
+export function SkillContextMenuItems({
+ skill,
+ actions,
+ existingNames,
+}: {
+ skill: SkillsListEntry;
+ actions: SkillActions;
+ existingNames: ReadonlySet<string>;
+}) {
+ const { t } = useLingui();
+ const workspace = useWorkspace();
+ const installStates = useInstalledAgents().states;
+ const { dispatch } = useHandoffDispatch();
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ const absolutePath = skill.absolutePath;
+
+ async function copy(text: string) {
+ try {
+ await scheduleClipboardWrite(text);
+ toast.success(t`Copied path`);
+ } catch {
+ toast.error(t`Couldn't copy path`);
+ }
+ }
+
+ return (
+ <>
+ {bridge && absolutePath ? (
+ <DropdownMenuItem onSelect={() => void bridge.shell.showItemInFolder(absolutePath)}>
+ <FolderOpen aria-hidden />
+ <Trans>Reveal in Finder</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ {/* Open in Terminal lives inside this submenu now (docked terminal + AI
+ handoff) — the standalone system-terminal item was removed app-wide
+ when the in-app shell landed. */}
+ <OpenInAgentContextSubmenu
+ input={buildSkillHandoffInput({ skillName: skill.name, scope: skill.scope, workspace })}
+ installStates={installStates}
+ isElectronHost={bridge != null}
+ dispatch={dispatch}
+ />
+ {/* Always available: Relative Path needs no host. Full Path appears once
+ the server has supplied the skill's absolute path (always, post-build;
+ absent only on a cold partial entry). */}
+ <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>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => void actions.duplicate(skill, existingNames)}>
+ <CopyPlus aria-hidden />
+ <Trans>Duplicate</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => actions.requestRename(skill, existingNames)}>
+ <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)}>
+ <DownloadCloud aria-hidden />
+ <Trans>Install</Trans>
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => actions.requestDelete(skill)}>
+ <Trash2 aria-hidden />
+ <Trans>Delete</Trans>
+ </DropdownMenuItem>
+ </>
+ );
+}
diff --git a/packages/app/src/components/target-navigation-intent.test.ts b/packages/app/src/components/target-navigation-intent.test.ts
index a0c5fd91a..a8942e42d 100644
--- a/packages/app/src/components/target-navigation-intent.test.ts
+++ b/packages/app/src/components/target-navigation-intent.test.ts
@@ -17,6 +17,7 @@ describe('resolveTargetNavigationIntent', () => {
noteKind: 'canonical-index',
},
hashDocName: 'reports',
+ hash: null,
displayState: 'folder',
});
});
@@ -34,6 +35,7 @@ describe('resolveTargetNavigationIntent', () => {
docName: 'reports/index',
},
hashDocName: 'reports/index',
+ hash: null,
displayState: 'doc',
});
});
@@ -52,6 +54,7 @@ describe('resolveTargetNavigationIntent', () => {
noteKind: 'legacy-folder-note',
},
hashDocName: 'reports',
+ hash: null,
displayState: 'folder',
});
});
@@ -69,6 +72,7 @@ describe('resolveTargetNavigationIntent', () => {
folderPath: 'reports',
},
hashDocName: 'reports',
+ hash: null,
displayState: 'folder',
});
});
@@ -84,6 +88,7 @@ describe('resolveTargetNavigationIntent', () => {
target: 'reports',
},
hashDocName: 'reports',
+ hash: null,
displayState: 'missing',
});
});
@@ -101,6 +106,26 @@ describe('resolveTargetNavigationIntent', () => {
docName: 'andrew-data/project-x/analysis',
},
hashDocName: 'andrew-data/project-x/analysis',
+ hash: null,
+ displayState: 'doc',
+ });
+ });
+
+ test('a GLOBAL skill bundle reference node carries the skill-file viewer hash', () => {
+ 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',
+ },
+ hashDocName: 'global/demo/references/notes.md',
+ hash: '#/__skill-file__/global/demo/references/notes.md',
displayState: 'doc',
});
});
diff --git a/packages/app/src/components/target-navigation-intent.ts b/packages/app/src/components/target-navigation-intent.ts
index 67be38b51..55c4d0c41 100644
--- a/packages/app/src/components/target-navigation-intent.ts
+++ b/packages/app/src/components/target-navigation-intent.ts
@@ -1,3 +1,4 @@
+import { hashFromSkillFile } from '@/lib/doc-hash';
import { type ResolvedNavigationTarget, resolveNavigationTarget } from './navigation-targets';
type TargetDisplayState = 'doc' | 'folder' | 'missing';
@@ -5,6 +6,7 @@ type TargetDisplayState = 'doc' | 'folder' | 'missing';
interface TargetNavigationIntent {
resolvedTarget: ResolvedNavigationTarget;
hashDocName: string;
+ hash: string | null;
displayState: TargetDisplayState;
}
@@ -13,6 +15,8 @@ function getTargetDisplayState(resolvedTarget: ResolvedNavigationTarget): Target
case 'doc':
case 'large-file':
return 'doc';
+ case 'skill-file':
+ return 'doc';
case 'folder':
case 'folder-index':
return 'folder';
@@ -36,6 +40,14 @@ export function resolveTargetNavigationIntent(
return {
resolvedTarget,
hashDocName: resolvedTarget.target,
+ hash:
+ resolvedTarget.kind === 'skill-file'
+ ? hashFromSkillFile({
+ scope: resolvedTarget.scope,
+ name: resolvedTarget.name,
+ path: resolvedTarget.path,
+ })
+ : null,
displayState: getTargetDisplayState(resolvedTarget),
};
}
diff --git a/packages/app/src/components/use-viewer-text.ts b/packages/app/src/components/use-viewer-text.ts
new file mode 100644
index 000000000..d5d7bd2c7
--- /dev/null
+++ b/packages/app/src/components/use-viewer-text.ts
@@ -0,0 +1,104 @@
+import { useLingui } from '@lingui/react/macro';
+import { useEffect, useRef, useState } from 'react';
+
+type TextViewerLoadResult =
+ | { ok: true; text: string }
+ | { ok: false; status?: number; message?: string };
+
+export type ViewerTextSource =
+ | {
+ src: string;
+ loadText?: never;
+ }
+ | {
+ src?: never;
+ loadText: (signal: AbortSignal) => Promise<TextViewerLoadResult>;
+ };
+
+export type FetchState =
+ | { status: 'loading' }
+ | { status: 'error'; message: string }
+ | { status: 'loaded'; content: string };
+
+export function useViewerText(props: ViewerTextSource): FetchState {
+ const { t } = useLingui();
+ const messageForStatus = (status: number | undefined): string => {
+ if (status === 413) {
+ return t`This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app.`;
+ }
+ if (status === 415) {
+ return t`This file is binary and can't be shown as text.`;
+ }
+ if (status === 404) {
+ return t`This file could not be found.`;
+ }
+ if (status === 400) {
+ return t`This file can't be opened in the text editor.`;
+ }
+ if (typeof status === 'number') {
+ return t`Something went wrong opening this file (HTTP ${status}).`;
+ }
+ return t`Failed to load file`;
+ };
+ const { src, loadText } = props;
+ const loadFnRef = useRef(loadText);
+ const messageForStatusRef = useRef(messageForStatus);
+ useEffect(() => {
+ loadFnRef.current = loadText;
+ messageForStatusRef.current = messageForStatus;
+ });
+ const [state, setState] = useState<FetchState>({ status: 'loading' });
+ useEffect(() => {
+ let cancelled = false;
+ const ctrl = new AbortController();
+ setState({ status: 'loading' });
+
+ const loadFn = loadFnRef.current;
+ if (loadFn) {
+ loadFn(ctrl.signal)
+ .then((result) => {
+ if (cancelled) return;
+ if (result.ok) {
+ setState({ status: 'loaded', content: result.text });
+ return;
+ }
+ setState({
+ status: 'error',
+ message: result.message ?? messageForStatusRef.current(result.status),
+ });
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ if (err instanceof Error && err.name === 'AbortError') return;
+ setState({ status: 'error', message: t`Failed to load file` });
+ });
+ return () => {
+ cancelled = true;
+ ctrl.abort();
+ };
+ }
+
+ fetch(src ?? '', { credentials: 'same-origin', signal: ctrl.signal })
+ .then(async (resp) => {
+ if (!resp.ok) {
+ throw new Error(messageForStatusRef.current(resp.status));
+ }
+ return resp.text();
+ })
+ .then((content) => {
+ if (cancelled) return;
+ setState({ status: 'loaded', content });
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ if (err instanceof Error && err.name === 'AbortError') return;
+ const message = err instanceof Error ? err.message : t`Failed to load file`;
+ setState({ status: 'error', message });
+ });
+ return () => {
+ cancelled = true;
+ ctrl.abort();
+ };
+ }, [src, t]);
+ return state;
+}
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index c226174b2..ec820815a 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -14,6 +14,8 @@ import {
hashFromAssetPath,
hashFromDocName,
hashFromFolderPath,
+ hashFromSkillFile,
+ skillFileFromHash,
} from '@/lib/doc-hash';
import { emitBranchChanged, emitDocumentsChanged } from '@/lib/documents-events';
import { mark } from '@/lib/perf';
@@ -48,6 +50,7 @@ import {
remapVisibleTabsForRename,
removeOpenTab,
removePinnedTab,
+ skillFileTabId,
tabIdForNavigationTarget,
writeLocalTabSessionState,
} from './editor-tabs';
@@ -231,12 +234,16 @@ function hashFromTabId(tabId: string): string {
return hashFromFolderPath(tab.folderPath);
case 'asset':
return hashFromAssetPath(tab.assetPath);
+ case 'skill-file':
+ return hashFromSkillFile({ scope: tab.scope, name: tab.name, path: tab.path });
}
}
function tabIdFromHash(hash: string): string | null {
const assetPath = assetPathFromHash(hash);
if (assetPath) return assetTabId(assetPath);
+ const skillFile = skillFileFromHash(hash);
+ if (skillFile) return skillFileTabId(skillFile);
const docName = docNameFromHash(hash);
if (!docName) return null;
const trimmed = docName.trim();
@@ -289,6 +296,8 @@ function navigationTargetKey(target: ResolvedNavigationTarget): string {
return `folder:${target.folderPath}`;
case 'asset':
return `asset:${target.assetPath}:${target.mediaKind ?? ''}`;
+ case 'skill-file':
+ return `skill-file:${target.scope}:${target.name}:${target.path}`;
case 'large-file':
return `large-file:${target.docName}:${target.size}:${target.limit}`;
case 'missing':
@@ -1066,6 +1075,18 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
if (window.location.hash !== nextHash) window.location.hash = nextHash;
return;
}
+ if (tab.kind === 'skill-file') {
+ setActiveTarget({
+ kind: 'skill-file',
+ target: `${tab.scope}/${tab.name}/${tab.path}`,
+ scope: tab.scope,
+ name: tab.name,
+ path: tab.path,
+ });
+ const nextHash = hashFromSkillFile({ scope: tab.scope, name: tab.name, path: tab.path });
+ 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;
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index 323d40a5f..f3f774827 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 3d2940a37..cc50d78ad 100644
--- a/packages/app/src/editor/editor-tabs.ts
+++ b/packages/app/src/editor/editor-tabs.ts
@@ -1,4 +1,15 @@
-import type { RenamedAssetMapping } from '@inkeep/open-knowledge-core';
+import {
+ isManagedArtifactDocName,
+ MANAGED_ARTIFACT_SCOPES,
+ type RenamedAssetMapping,
+ type SkillScope,
+} from '@inkeep/open-knowledge-core';
+import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
+import { skillDisplayName } from '@/lib/skill-scope';
+
+function isSkillScope(value: string): value is SkillScope {
+ return (MANAGED_ARTIFACT_SCOPES as readonly string[]).includes(value);
+}
interface EditorTabSessionState {
openTabs: string[];
@@ -24,6 +35,7 @@ interface KnownTabTargets {
const LOCAL_TAB_SESSION_PREFIX = 'ok-editor-tabs-v1:';
const FOLDER_TAB_PREFIX = '\u0000folder:';
const ASSET_TAB_PREFIX = '\u0000asset:';
+const SKILL_FILE_TAB_PREFIX = '\u0000skill-file:';
const TAB_INSTANCE_SEPARATOR = '\u0000doc-tab:';
const MARKDOWN_TAB_EXTENSION_PATTERN = /\.(md|mdx)$/i;
@@ -58,9 +70,31 @@ function isValidTabId(value: unknown): value is string {
const base = baseTabId(value);
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;
return true;
}
+export interface SkillFileTabTarget {
+ scope: SkillScope;
+ name: string;
+ path: string;
+}
+
+export function skillFileTabId(target: SkillFileTabTarget): string {
+ return `${SKILL_FILE_TAB_PREFIX}${target.scope}/${target.name}/${target.path}`;
+}
+
+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 path = rest.join('/');
+ if (!scope || !name || !path || !isSkillScope(scope)) return null;
+ return { scope, name, path };
+}
+
export function docTabId(docName: string): string {
return docName;
}
@@ -99,6 +133,11 @@ export function tabParts(
docName: string,
docExt: string,
): { baseName: string; extension: string; label: string; prefix: string } {
+ const projectSkill = parseProjectSkillContentDocName(docName);
+ if (projectSkill) {
+ const display = skillDisplayName(projectSkill);
+ return { baseName: display, extension: '', label: display, prefix: '' };
+ }
const slash = docName.lastIndexOf('/');
const baseName = slash < 0 ? docName : docName.slice(slash + 1);
const label = `${baseName}${docExt}`;
@@ -117,6 +156,7 @@ 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: 'large-file'; docName: string }
| { kind: 'missing'; target: string },
): string | null {
@@ -131,6 +171,8 @@ export function tabIdForNavigationTarget(
return docTabId(target.target);
case 'asset':
return assetTabId(target.assetPath);
+ case 'skill-file':
+ return skillFileTabId(target);
}
}
@@ -139,7 +181,8 @@ export function parseEditorTabId(
):
| { kind: 'doc'; docName: string }
| { kind: 'folder'; folderPath: string }
- | { kind: 'asset'; assetPath: string } {
+ | { kind: 'asset'; assetPath: string }
+ | { kind: 'skill-file'; scope: SkillScope; name: string; path: string } {
const base = baseTabId(tabId);
if (base.startsWith(FOLDER_TAB_PREFIX)) {
return { kind: 'folder', folderPath: base.slice(FOLDER_TAB_PREFIX.length) };
@@ -147,6 +190,10 @@ export function parseEditorTabId(
if (base.startsWith(ASSET_TAB_PREFIX)) {
return { kind: 'asset', assetPath: base.slice(ASSET_TAB_PREFIX.length) };
}
+ const skillFile = parseSkillFileTabBody(base);
+ if (skillFile) {
+ return { kind: 'skill-file', ...skillFile };
+ }
return { kind: 'doc', docName: base };
}
@@ -360,8 +407,10 @@ export function filterOpenTabsForKnownTargets(
const tab = parseEditorTabId(tabId);
if (tab.kind === 'folder') return folderPaths.has(tab.folderPath);
if (tab.kind === 'asset') return assetPaths.has(tab.assetPath);
+ if (tab.kind === 'skill-file') return true;
return (
pages.has(tab.docName) ||
+ isManagedArtifactDocName(tab.docName) ||
tab.docName === keepMissingDocName ||
tab.docName === keepHashDocName
);
@@ -414,7 +463,9 @@ export function remapOpenTabs(
? remapDocTabBase(parsed.docName, baseTabId(tab))
: parsed.kind === 'folder'
? folderTabId(remapPathForFolderRenames(parsed.folderPath, folderMappings))
- : remapAssetTabBase(parsed.assetPath);
+ : parsed.kind === 'asset'
+ ? remapAssetTabBase(parsed.assetPath)
+ : baseTabId(tab);
const mapped = `${mappedBase}${instanceSuffix}`;
if (seen.has(mapped)) continue;
seen.add(mapped);
@@ -428,7 +479,9 @@ export function remapOpenTabs(
? remapDocTabBase(parsed.docName, tabId)
: parsed.kind === 'folder'
? folderTabId(remapPathForFolderRenames(parsed.folderPath, folderMappings))
- : remapAssetTabBase(parsed.assetPath);
+ : parsed.kind === 'asset'
+ ? remapAssetTabBase(parsed.assetPath)
+ : baseTabId(tabId);
});
return capOpenTabsPreservingPinned(next, limit, remappedPinnedTabIds);
}
diff --git a/packages/app/src/hooks/use-folder-config.ts b/packages/app/src/hooks/use-folder-config.ts
index 233acc84d..4f429c7c2 100644
--- a/packages/app/src/hooks/use-folder-config.ts
+++ b/packages/app/src/hooks/use-folder-config.ts
@@ -31,15 +31,6 @@ export interface TemplateMenuEntry {
scope: 'local' | 'inherited';
}
-export interface TemplateDetail {
- name: string;
- folder: string;
- scope: 'local' | 'inherited';
- path: string;
- frontmatter: Record<string, unknown>;
- body: string;
-}
-
export type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
@@ -111,51 +102,6 @@ export function useFolderConfig(folderPath: string | null): FolderConfigHandle {
};
}
-export function useTemplate(
- folder: string | null,
- name: string | null,
-): AsyncState<TemplateDetail> {
- const [state, setState] = useState<AsyncState<TemplateDetail>>({ status: 'idle' });
-
- useEffect(() => {
- if (!name || folder === null) {
- setState({ status: 'idle' });
- return;
- }
- let cancelled = false;
- setState({ status: 'loading' });
- const qs = `?folder=${encodeURIComponent(folder)}&name=${encodeURIComponent(name)}`;
- fetch(`/api/template${qs}`)
- .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<{ template: TemplateDetail }>;
- })
- .then((payload) => {
- if (cancelled) return;
- if (!payload || typeof payload !== 'object' || !payload.template) {
- setState({
- status: 'error',
- message: 'Server returned an incomplete template response.',
- });
- return;
- }
- setState({ status: 'ready', data: payload.template });
- })
- .catch((err: unknown) => {
- if (cancelled) return;
- setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
- });
- return () => {
- cancelled = true;
- };
- }, [folder, name]);
-
- return state;
-}
-
export function useAllTemplates(): AsyncState<readonly TemplatesListEntry[]> {
const [state, setState] = useState<AsyncState<readonly TemplatesListEntry[]>>({ status: 'idle' });
const [refreshKey, setRefreshKey] = useState(0);
diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
new file mode 100644
index 000000000..4f9a91db2
--- /dev/null
+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, test } from 'bun:test';
+import { skillLiveDocName } from '@inkeep/open-knowledge-core';
+import { computeSkillTabReconcile, parseSkillTabDocName } from './use-reconcile-skill-tabs';
+
+describe('parseSkillTabDocName', () => {
+ test('parses a project skill content doc', () => {
+ expect(parseSkillTabDocName('.ok/skills/demo/SKILL')).toEqual({
+ scope: 'project',
+ name: 'demo',
+ });
+ });
+
+ test('parses a global skill managed-artifact doc', () => {
+ expect(parseSkillTabDocName(skillLiveDocName('global', 'demo'))).toEqual({
+ scope: 'global',
+ name: 'demo',
+ });
+ });
+
+ test('rejects a non-skill doc (plain page, template, ref)', () => {
+ expect(parseSkillTabDocName('notes/standup')).toBeNull();
+ expect(parseSkillTabDocName('__template__/notes/daily')).toBeNull();
+ expect(parseSkillTabDocName('.ok/skills/demo/references/notes')).toBeNull();
+ });
+});
+
+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' }],
+ );
+ expect(actions).toEqual([]);
+ });
+
+ test('retargets an orphaned project tab to the OTHER scope when the skill moved there', () => {
+ const actions = computeSkillTabReconcile(
+ ['.ok/skills/demo/SKILL'],
+ [{ scope: 'global', name: 'demo' }],
+ );
+ expect(actions).toEqual([
+ {
+ kind: 'retarget',
+ fromDocName: '.ok/skills/demo/SKILL',
+ toDocName: skillLiveDocName('global', 'demo'),
+ },
+ ]);
+ });
+
+ test('retargets an orphaned global tab to project when the skill moved there', () => {
+ const actions = computeSkillTabReconcile(
+ [skillLiveDocName('global', 'demo')],
+ [{ scope: 'project', name: 'demo' }],
+ );
+ expect(actions).toEqual([
+ {
+ kind: 'retarget',
+ fromDocName: skillLiveDocName('global', 'demo'),
+ toDocName: skillLiveDocName('project', 'demo'),
+ },
+ ]);
+ });
+
+ test('closes an orphaned tab when the skill is gone from both scopes', () => {
+ const actions = computeSkillTabReconcile(
+ ['.ok/skills/gone/SKILL'],
+ [{ scope: 'project', name: 'other' }],
+ );
+ expect(actions).toEqual([{ kind: 'close', docName: '.ok/skills/gone/SKILL' }]);
+ });
+
+ 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
new file mode 100644
index 000000000..9ae178049
--- /dev/null
+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.ts
@@ -0,0 +1,79 @@
+import {
+ type ManagedArtifactScope,
+ parseManagedArtifactName,
+ type SkillsListEntry,
+ skillLiveDocName,
+} from '@inkeep/open-knowledge-core';
+import { useEffect, useRef } from 'react';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
+import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';
+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. */
+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 };
+ return null;
+}
+
+export type SkillTabReconcileAction =
+ | { kind: 'retarget'; fromDocName: string; toDocName: string }
+ | { kind: 'close'; docName: string };
+
+export function computeSkillTabReconcile(
+ openTabDocNames: ReadonlyArray<string>,
+ skills: ReadonlyArray<Pick<SkillsListEntry, 'name' | 'scope'>>,
+): SkillTabReconcileAction[] {
+ const present = new Set(skills.map((s) => `${s.scope}\u0000${s.name}`));
+ 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}`)) {
+ actions.push({
+ kind: 'retarget',
+ fromDocName: docName,
+ toDocName: skillLiveDocName(otherScope, tab.name),
+ });
+ } else {
+ actions.push({ kind: 'close', docName });
+ }
+ }
+ return actions;
+}
+
+export function useReconcileSkillTabs(): void {
+ const { openTabs, closeDocument } = useDocumentContext();
+ const hasSkillTab = openTabs.some((docName) => parseSkillTabDocName(docName) !== null);
+ const skillsState = useSkills({ enabled: hasSkillTab });
+ const lastSignatureRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (skillsState.status !== 'ready') return;
+ const skills = skillsState.data;
+ const signature = `${openTabs.join('\u0001')}\u0002${skills
+ .map((s) => `${s.scope}\u0000${s.name}`)
+ .sort()
+ .join('\u0001')}`;
+ if (lastSignatureRef.current === signature) return;
+ lastSignatureRef.current = signature;
+
+ const actions = computeSkillTabReconcile(openTabs, skills);
+ for (const action of actions) {
+ if (action.kind === 'retarget') {
+ openManagedArtifactTab(action.toDocName);
+ closeDocument(action.fromDocName);
+ } else {
+ closeDocument(action.docName);
+ }
+ }
+ }, [skillsState, openTabs, closeDocument]);
+}
diff --git a/packages/app/src/hooks/use-skill-targets.ts b/packages/app/src/hooks/use-skill-targets.ts
new file mode 100644
index 000000000..2cf116b1e
--- /dev/null
+++ b/packages/app/src/hooks/use-skill-targets.ts
@@ -0,0 +1,77 @@
+import {
+ type SkillTargetEditor,
+ 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 type { AsyncState } from './use-folder-config';
+
+export interface SkillTargetsHandle {
+ state: AsyncState<SkillTargetsGetSuccess>;
+ save: (targets: SkillTargetEditor[]) => Promise<void>;
+ saving: boolean;
+}
+
+export function useSkillTargets(): SkillTargetsHandle {
+ const [state, setState] = useState<AsyncState<SkillTargetsGetSuccess>>({ status: 'idle' });
+ const [refreshKey, setRefreshKey] = useState(0);
+ const [saving, setSaving] = useState(false);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-fetch trigger is the only purpose of refreshKey
+ useEffect(() => {
+ let cancelled = false;
+ setState({ status: 'loading' });
+ fetch('/api/skill-targets')
+ .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>;
+ })
+ .then((payload) => {
+ if (cancelled) return;
+ const parsed = SkillTargetsGetSuccessSchema.safeParse(payload);
+ if (!parsed.success) {
+ console.error(
+ '[ok-skills] /api/skill-targets response failed schema validation:',
+ parsed.error.issues,
+ );
+ setState({
+ status: 'error',
+ message: 'Server returned an incomplete skill-targets response.',
+ });
+ return;
+ }
+ setState({ status: 'ready', data: parsed.data });
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [refreshKey]);
+
+ const save = async (targets: SkillTargetEditor[]): Promise<void> => {
+ setSaving(true);
+ const res = await fetch('/api/skill-targets', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ targets }),
+ }).catch(() => null);
+ if (!res?.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'));
+ }
+ emitSkillsChanged();
+ setRefreshKey((k) => k + 1);
+ setSaving(false);
+ };
+
+ return { state, save, saving };
+}
diff --git a/packages/app/src/hooks/use-skills.ts b/packages/app/src/hooks/use-skills.ts
new file mode 100644
index 000000000..dd2b2708c
--- /dev/null
+++ b/packages/app/src/hooks/use-skills.ts
@@ -0,0 +1,60 @@
+import { type SkillsListEntry, SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { useEffect, useState } from 'react';
+import { subscribeToDocumentsChanged, subscribeToSkillsChanged } from '@/lib/documents-events';
+import { parseApiError } from '@/lib/parse-api-error';
+import type { AsyncState } from './use-folder-config';
+
+export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly SkillsListEntry[]> {
+ const enabled = options?.enabled ?? true;
+ const [state, setState] = useState<AsyncState<readonly SkillsListEntry[]>>({ status: 'idle' });
+ const [refreshKey, setRefreshKey] = useState(0);
+
+ useEffect(() => {
+ const bump = () => setRefreshKey((k) => k + 1);
+ const unsubLocal = subscribeToSkillsChanged(bump);
+ const unsubRemote = subscribeToDocumentsChanged((channels) => {
+ if (channels.includes('files')) bump();
+ });
+ return () => {
+ unsubLocal();
+ unsubRemote();
+ };
+ }, []);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-fetch trigger is the only purpose of refreshKey
+ useEffect(() => {
+ if (!enabled) return;
+ let cancelled = false;
+ 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>;
+ })
+ .then((payload) => {
+ if (cancelled) return;
+ const parsed = SkillsListSuccessSchema.safeParse(payload);
+ if (!parsed.success) {
+ console.error(
+ '[ok-skills] /api/skills response failed schema validation:',
+ parsed.error.issues,
+ );
+ setState({ status: 'error', message: 'Server returned an incomplete skills response.' });
+ return;
+ }
+ setState({ status: 'ready', data: parsed.data.skills });
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [refreshKey, enabled]);
+
+ return state;
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 5f1edadd8..bf3b4d3c9 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -32,6 +32,10 @@ export interface OkScaffoldPlan {
created: OkScaffoldFileEntry[];
skipped: OkScaffoldSkipEntry[];
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, so the
+ * pack isn't fully set up even if its folders/templates exist. */
+ packSkill?: { name: string; pending: boolean };
}
interface OkScaffoldApplyError {
path: string;
diff --git a/packages/app/src/lib/doc-hash.test.ts b/packages/app/src/lib/doc-hash.test.ts
index b8203b416..09463efb5 100644
--- a/packages/app/src/lib/doc-hash.test.ts
+++ b/packages/app/src/lib/doc-hash.test.ts
@@ -7,8 +7,12 @@ import {
hashFromAssetPath,
hashFromDocName,
hashFromFolderPath,
+ hashFromSkillFile,
isContentRootHash,
+ type SkillFileHashTarget,
+ skillFileFromHash,
} from './doc-hash';
+import { skillLiveDocName, templateDocName } from './managed-artifact-doc-name';
describe('docNameFromHash', () => {
test('returns null for empty hash', () => {
@@ -212,3 +216,67 @@ describe('asset hash helpers', () => {
expect(docNameFromHash(hashFromAssetPath('docs/photo.png'))).toBeNull();
});
});
+
+describe('managed-artifact doc names round-trip as documents', () => {
+ test('skill doc name round-trips through the hash', () => {
+ const docName = skillLiveDocName('global', 'run-tests');
+ expect(docName).toBe('__skill__/global/run-tests');
+ expect(hashFromDocName(docName)).toBe('#/__skill__/global/run-tests');
+ expect(docNameFromHash(hashFromDocName(docName))).toBe(docName);
+ });
+
+ test('template doc name (nested folder) round-trips through the hash', () => {
+ const docName = templateDocName('a/b/c', 'deep');
+ expect(docName).toBe('__template__/a/b/c/deep');
+ expect(hashFromDocName(docName)).toBe('#/__template__/a/b/c/deep');
+ expect(docNameFromHash(hashFromDocName(docName))).toBe(docName);
+ });
+
+ test('template at the project root', () => {
+ expect(templateDocName('', 'daily')).toBe('__template__/daily');
+ expect(docNameFromHash('#/__template__/daily')).toBe('__template__/daily');
+ });
+
+ test('a percent-encoded URL hash decodes back to the raw doc name', () => {
+ expect(docNameFromHash('#/__template__/My%20Notes/plan')).toBe('__template__/My Notes/plan');
+ });
+});
+
+describe('skill-file hash', () => {
+ test('round-trips scope / name / nested path', () => {
+ const target = {
+ scope: 'global',
+ name: 'trip-log',
+ path: 'references/guide.md',
+ } satisfies SkillFileHashTarget;
+ const hash = hashFromSkillFile(target);
+ expect(hash).toBe('#/__skill-file__/global/trip-log/references/guide.md');
+ expect(skillFileFromHash(hash)).toEqual(target);
+ });
+
+ test('round-trips a script path', () => {
+ const target = {
+ scope: 'project',
+ name: 'my-skill',
+ path: 'scripts/run.sh',
+ } satisfies SkillFileHashTarget;
+ expect(skillFileFromHash(hashFromSkillFile(target))).toEqual(target);
+ });
+
+ 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();
+ expect(assetPathFromHash(hash)).toBeNull();
+ });
+
+ test('returns null for a non-skill-file hash', () => {
+ expect(skillFileFromHash('#/some/doc')).toBeNull();
+ expect(skillFileFromHash('#/__asset__/images/x.png')).toBeNull();
+ expect(skillFileFromHash('#/__skill-file__/global/trip-log')).toBeNull();
+ });
+
+ test('rejects an unknown scope segment (hash is untrusted/editable)', () => {
+ expect(skillFileFromHash('#/__skill-file__/bogus/trip-log/references/x.md')).toBeNull();
+ expect(skillFileFromHash('#/__skill-file__/personal/trip-log/references/x.md')).toBeNull();
+ });
+});
diff --git a/packages/app/src/lib/doc-hash.ts b/packages/app/src/lib/doc-hash.ts
index 3ab8e5683..64b62f43a 100644
--- a/packages/app/src/lib/doc-hash.ts
+++ b/packages/app/src/lib/doc-hash.ts
@@ -1,3 +1,9 @@
+import { MANAGED_ARTIFACT_SCOPES, type SkillScope } from '@inkeep/open-knowledge-core';
+
+function isSkillScope(value: string): value is SkillScope {
+ return (MANAGED_ARTIFACT_SCOPES as readonly string[]).includes(value);
+}
+
/** Parse a docName from a `#/<path>?<query>` hash. Returns null if the hash
* is empty, malformed, or not in the `#/` namespace.
*
@@ -6,6 +12,7 @@
* docName matches the server's on-disk name (e.g. `My Notes/Ideas — 2026`). */
export function docNameFromHash(hash: string): string | null {
if (hash.startsWith(ASSET_HASH_PREFIX)) return null;
+ if (hash.startsWith(SKILL_FILE_HASH_PREFIX)) return null;
if (!hash.startsWith('#/')) return null;
const rest = hash.slice(2);
const delimiter = firstRouteDelimiterIndex(rest);
@@ -99,3 +106,34 @@ export function assetPathFromHash(hash: string): string | null {
export function hashFromAssetPath(assetPath: string): string {
return `${ASSET_HASH_PREFIX}${assetPath.split('/').map(encodeURIComponent).join('/')}`;
}
+
+const SKILL_FILE_HASH_PREFIX = '#/__skill-file__/';
+
+export interface SkillFileHashTarget {
+ scope: SkillScope;
+ name: string;
+ path: string;
+}
+
+export function hashFromSkillFile(target: SkillFileHashTarget): string {
+ const head = [target.scope, target.name].map(encodeURIComponent).join('/');
+ const tail = target.path.split('/').map(encodeURIComponent).join('/');
+ return `${SKILL_FILE_HASH_PREFIX}${head}/${tail}`;
+}
+
+export function skillFileFromHash(hash: string): SkillFileHashTarget | null {
+ if (!hash.startsWith(SKILL_FILE_HASH_PREFIX)) return null;
+ const encoded = hash.slice(SKILL_FILE_HASH_PREFIX.length);
+ if (!encoded) return null;
+ let segments: string[];
+ try {
+ segments = encoded.split('/').map(decodeURIComponent);
+ } catch {
+ return null;
+ }
+ if (segments.length < 3) return null;
+ const [scope, name, ...rest] = segments;
+ const path = rest.join('/');
+ if (!scope || !name || !path || !isSkillScope(scope)) return null;
+ return { scope, name, path };
+}
diff --git a/packages/app/src/lib/documents-events.ts b/packages/app/src/lib/documents-events.ts
index 2b768d821..8a8063344 100644
--- a/packages/app/src/lib/documents-events.ts
+++ b/packages/app/src/lib/documents-events.ts
@@ -76,3 +76,15 @@ export function subscribeToTemplatesChanged(onChange: () => void): () => void {
window.addEventListener(TEMPLATES_CHANGED_EVENT, listener);
return () => window.removeEventListener(TEMPLATES_CHANGED_EVENT, listener);
}
+
+const SKILLS_CHANGED_EVENT = 'open-knowledge:skills-changed';
+
+export function emitSkillsChanged(): void {
+ window.dispatchEvent(new CustomEvent(SKILLS_CHANGED_EVENT));
+}
+
+export function subscribeToSkillsChanged(onChange: () => void): () => void {
+ const listener = () => onChange();
+ window.addEventListener(SKILLS_CHANGED_EVENT, listener);
+ return () => window.removeEventListener(SKILLS_CHANGED_EVENT, listener);
+}
diff --git a/packages/app/src/lib/managed-artifact-doc-name.ts b/packages/app/src/lib/managed-artifact-doc-name.ts
new file mode 100644
index 000000000..f508a88ba
--- /dev/null
+++ b/packages/app/src/lib/managed-artifact-doc-name.ts
@@ -0,0 +1,27 @@
+import {
+ MANAGED_ARTIFACT_PREFIX_TEMPLATE,
+ projectSkillContentDocName,
+ SKILL_CONTENT_ROOT,
+ skillLiveDocName,
+} from '@inkeep/open-knowledge-core';
+
+export { projectSkillContentDocName, skillLiveDocName };
+
+export function templateDocName(folder: string, name: string): string {
+ const trimmed = folder.replace(/^\/+|\/+$/g, '');
+ 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}`;
+}
+
+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;
+}
diff --git a/packages/app/src/lib/open-managed-artifact-tab.ts b/packages/app/src/lib/open-managed-artifact-tab.ts
new file mode 100644
index 000000000..61f50e819
--- /dev/null
+++ b/packages/app/src/lib/open-managed-artifact-tab.ts
@@ -0,0 +1,7 @@
+import { hashFromDocName } from '@/lib/doc-hash';
+
+export function openManagedArtifactTab(docName: string): void {
+ if (typeof window === 'undefined') return;
+ const hash = hashFromDocName(docName);
+ if (window.location.hash !== hash) window.location.hash = hash;
+}
diff --git a/packages/app/src/lib/seed-client.ts b/packages/app/src/lib/seed-client.ts
index d8d0e6b7c..423b90bea 100644
--- a/packages/app/src/lib/seed-client.ts
+++ b/packages/app/src/lib/seed-client.ts
@@ -9,6 +9,7 @@ import type {
OkSeedPackInfo,
OkSeedPlanResult,
} from '@/lib/desktop-bridge-types';
+import { emitSkillsChanged } from '@/lib/documents-events';
async function translateSeedError(res: Response): Promise<OkSeedError> {
const body = (await res.json().catch(() => null)) as unknown;
@@ -47,9 +48,14 @@ interface SeedClientShape {
export function seedClient(): SeedClientShape {
const okDesktop = typeof window !== 'undefined' ? window.okDesktop : undefined;
if (okDesktop?.seed) {
+ const desktopApply = okDesktop.seed.apply;
return {
plan: okDesktop.seed.plan,
- apply: okDesktop.seed.apply,
+ apply: async (plan, options) => {
+ const result = await desktopApply(plan, options);
+ if (result.ok) emitSkillsChanged();
+ return result;
+ },
listPacks: okDesktop.seed.listPacks,
};
}
@@ -87,6 +93,7 @@ export function seedClient(): SeedClientShape {
if (!body?.result) {
return { ok: false, error: { kind: 'internal', message: 'Malformed apply response' } };
}
+ emitSkillsChanged();
return { ok: true, result: body.result };
},
listPacks: async (): Promise<OkSeedListPacksResult> => {
diff --git a/packages/app/src/lib/skill-scope.ts b/packages/app/src/lib/skill-scope.ts
new file mode 100644
index 000000000..82e51982a
--- /dev/null
+++ b/packages/app/src/lib/skill-scope.ts
@@ -0,0 +1,33 @@
+import type { SkillScope, SkillsListEntry } 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;
+
+export function skillNameSetsByScope(
+ skills: readonly SkillsListEntry[],
+): Record<SkillScope, Set<string>> {
+ return {
+ project: new Set(skills.filter((s) => s.scope === 'project').map((s) => s.name)),
+ global: new Set(skills.filter((s) => s.scope === 'global').map((s) => s.name)),
+ };
+}
+
+const PACK_SKILL_DISPLAY_PREFIX = 'open-knowledge-pack-';
+
+export function skillDisplayName(name: string): string {
+ return name.startsWith(PACK_SKILL_DISPLAY_PREFIX)
+ ? name.slice(PACK_SKILL_DISPLAY_PREFIX.length)
+ : name;
+}
+
+export function useSkillScopeLabels(): Record<SkillScope, string> {
+ const { t } = useLingui();
+ return { project: t`Project`, global: t`Global` };
+}
+
+export function useSkillScopePillLabels(): Record<SkillScope, string> {
+ const { t } = useLingui();
+ return { project: t`Project Skill`, global: t`Global Skill` };
+}
diff --git a/packages/app/src/lib/skills-api.ts b/packages/app/src/lib/skills-api.ts
new file mode 100644
index 000000000..3d92edc25
--- /dev/null
+++ b/packages/app/src/lib/skills-api.ts
@@ -0,0 +1,403 @@
+import type {
+ SkillFrontmatter,
+ SkillInstallWarningCode,
+ SkillScope,
+} from '@inkeep/open-knowledge-core';
+import { emitSkillsChanged } from '@/lib/documents-events';
+import { parseApiError } from '@/lib/parse-api-error';
+
+async function readErrorBody(res: Response): Promise<string> {
+ const body = (await res.json().catch(() => null)) as unknown;
+ return parseApiError(body) ?? `HTTP ${res.status}`;
+}
+
+type WriteResult<T> = ({ ok: true } & T) | { ok: false; error: string };
+
+export async function saveSkill(input: {
+ scope: SkillScope;
+ name: string;
+ frontmatter: SkillFrontmatter;
+ body: string;
+}): Promise<WriteResult<{ created: boolean; warnings: string[] }>> {
+ try {
+ const res = await fetch('/api/skill', {
+ 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 {
+ created?: boolean;
+ warnings?: string[];
+ } | null;
+ emitSkillsChanged();
+ return { ok: true, created: payload?.created ?? false, warnings: payload?.warnings ?? [] };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+async function saveSkillFile(input: {
+ scope: SkillScope;
+ name: string;
+ path: string;
+ content: string;
+}): Promise<WriteResult<{ created: boolean }>> {
+ 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 { created?: boolean } | null;
+ emitSkillsChanged();
+ return { ok: true, created: payload?.created ?? false };
+ } 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> {
+ 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;
+ }
+}
+
+/** 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> {
+ try {
+ const res = await fetch('/api/skills/management', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ manageEditorSkills }),
+ });
+ if (!res.ok) return false;
+ emitSkillsChanged();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function nextCopyName(base: string, existing: ReadonlySet<string>): string {
+ const first = `${base}-copy`;
+ if (!existing.has(first)) return first;
+ for (let i = 2; i < 1000; i += 1) {
+ const candidate = `${base}-copy-${i}`;
+ if (!existing.has(candidate)) return candidate;
+ }
+ return `${base}-copy-${existing.size + 1}`;
+}
+
+export async function duplicateSkill(input: {
+ scope: SkillScope;
+ name: string;
+ 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,
+ });
+ if (!saved.ok) return { ok: false, error: saved.error };
+ return { ok: true, name: toName };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export async function moveSkillScope(input: {
+ name: string;
+ fromScope: SkillScope;
+ toScope: SkillScope;
+}): Promise<WriteResult<{ scope: SkillScope; skippedBinaryFiles?: 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 : '';
+
+ 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,
+ });
+ if (!saved.ok) return saved;
+
+ 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) {
+ 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}`,
+ };
+ }
+ emitSkillsChanged();
+ return {
+ ok: true,
+ scope: toScope,
+ ...(skippedBinaryFiles.length > 0 ? { skippedBinaryFiles } : {}),
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export async function moveSkill(input: {
+ scope: SkillScope;
+ fromName: string;
+ toName: string;
+ frontmatter?: SkillFrontmatter;
+ body?: string;
+}): Promise<WriteResult<{ committed: boolean }>> {
+ try {
+ const res = await fetch('/api/skill', {
+ 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 { committed?: boolean } | null;
+ emitSkillsChanged();
+ return { ok: true, committed: payload?.committed ?? false };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export async function deleteSkill(
+ scope: SkillScope,
+ name: string,
+): Promise<WriteResult<{ existed: boolean }>> {
+ try {
+ const qs = `?name=${encodeURIComponent(name)}&scope=${encodeURIComponent(scope)}`;
+ const res = await fetch(`/api/skill${qs}`, { method: 'DELETE' });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as { existed?: boolean } | null;
+ emitSkillsChanged();
+ return { ok: true, existed: payload?.existed ?? false };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export interface SkillBundledFile {
+ path: string;
+ text: string | null;
+}
+
+export async function getSkillBundledFiles(
+ scope: SkillScope,
+ name: string,
+): Promise<WriteResult<{ files: SkillBundledFile[] }>> {
+ try {
+ const params = new URLSearchParams({ name, scope });
+ 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 {
+ skill?: { files?: SkillBundledFile[] };
+ } | null;
+ return { ok: true, files: detail?.skill?.files ?? [] };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+type SkillFileReadResult =
+ | { ok: true; text: string }
+ | { ok: false; status?: number; error: string };
+
+async function getSkillFile(input: {
+ scope: SkillScope;
+ name: string;
+ path: string;
+ signal?: AbortSignal;
+}): Promise<SkillFileReadResult> {
+ try {
+ const params = new URLSearchParams({
+ name: input.name,
+ scope: input.scope,
+ path: input.path,
+ });
+ const res = await fetch(`/api/skill-file?${params.toString()}`, { signal: input.signal });
+ if (!res.ok) {
+ return { ok: false, status: res.status, error: await readErrorBody(res) };
+ }
+ const detail = (await res.json().catch(() => null)) as { text?: unknown } | null;
+ if (typeof detail?.text !== 'string') {
+ return { ok: false, status: res.status, error: `HTTP ${res.status}` };
+ }
+ return { ok: true, text: detail.text };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export function loadSkillFileText(
+ input: {
+ scope: SkillScope;
+ name: string;
+ path: string;
+ },
+ signal?: AbortSignal,
+): Promise<{ ok: true; text: string } | { ok: false; status?: number }> {
+ return getSkillFile({ ...input, signal }).then((result) =>
+ result.ok ? { ok: true, text: result.text } : { ok: false, status: result.status },
+ );
+}
+
+export async function installSkill(input: {
+ scope: SkillScope;
+ name: string;
+ targets?: string[];
+}): Promise<
+ WriteResult<{
+ hosts: string[];
+ scripts: boolean;
+ warnings: string[];
+ warningCodes: SkillInstallWarningCode[];
+ }>
+> {
+ try {
+ const res = await fetch('/api/skill/install', {
+ 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 {
+ hosts?: string[];
+ scripts?: boolean;
+ warnings?: string[];
+ warningCodes?: SkillInstallWarningCode[];
+ } | null;
+ emitSkillsChanged();
+ return {
+ ok: true,
+ hosts: payload?.hosts ?? [],
+ scripts: payload?.scripts ?? false,
+ warnings: payload?.warnings ?? [],
+ warningCodes: payload?.warningCodes ?? [],
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export async function uninstallSkill(input: {
+ scope: SkillScope;
+ name: string;
+}): Promise<WriteResult<{ uninstalled: boolean }>> {
+ try {
+ const res = await fetch('/api/skill/uninstall', {
+ 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 { uninstalled?: boolean } | null;
+ emitSkillsChanged();
+ return { ok: true, uninstalled: payload?.uninstalled ?? false };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export async function updatePackSkill(input: {
+ scope: SkillScope;
+ name: string;
+}): Promise<WriteResult<{ version: string; previousVersion?: string; checkpointRef?: string }>> {
+ try {
+ const res = await fetch('/api/skill/update', {
+ 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;
+ } | null;
+ emitSkillsChanged();
+ return {
+ ok: true,
+ version: payload?.version ?? '',
+ previousVersion: payload?.previousVersion,
+ checkpointRef: payload?.checkpointRef,
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
diff --git a/packages/app/src/lib/use-frontmatter-field.ts b/packages/app/src/lib/use-frontmatter-field.ts
new file mode 100644
index 000000000..215a8280e
--- /dev/null
+++ b/packages/app/src/lib/use-frontmatter-field.ts
@@ -0,0 +1,57 @@
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { bindFrontmatterDoc } from '@inkeep/open-knowledge-core';
+import { useEffect, useRef, useState } from 'react';
+
+export interface FrontmatterFieldBinding {
+ value: string;
+ setValue: (next: string) => void;
+ onFocus: () => void;
+ onBlur: () => void;
+}
+
+function readField(binding: ReturnType<typeof bindFrontmatterDoc>, key: string): string {
+ const value = binding.current().map[key];
+ return typeof value === 'string' ? value : '';
+}
+
+export function useFrontmatterField(
+ provider: HocuspocusProvider,
+ key: string,
+): FrontmatterFieldBinding {
+ const [binding, setBinding] = useState<ReturnType<typeof bindFrontmatterDoc> | null>(null);
+ const [value, setValue] = useState<string>(() => {
+ const b = bindFrontmatterDoc(provider);
+ const v = readField(b, key);
+ b.dispose();
+ return v;
+ });
+ const focusedRef = useRef(false);
+
+ useEffect(() => {
+ const b = bindFrontmatterDoc(provider);
+ setBinding(b);
+ setValue(readField(b, key));
+ const unsub = b.subscribe(() => {
+ if (!focusedRef.current) setValue(readField(b, key));
+ });
+ return () => {
+ unsub();
+ b.dispose();
+ setBinding((prev) => (prev === b ? null : prev));
+ };
+ }, [provider, key]);
+
+ return {
+ value,
+ setValue,
+ onFocus: () => {
+ focusedRef.current = true;
+ },
+ onBlur: () => {
+ focusedRef.current = false;
+ if (binding && value !== readField(binding, key)) {
+ binding.patch({ [key]: value });
+ }
+ },
+ };
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 8abb08089..99f604c67 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -25,6 +25,7 @@
"-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."],
"-wePNM": [
"Search matches file names, paths, and folders. Open a file to search its body (⌘F)."
@@ -35,12 +36,14 @@
"04RA0-": ["Failed to enable sync — ", ["detail"]],
"05n5wS": ["Doc mention suggestions"],
"06SZfb": ["Template \"", ["trimmedTitle"], "\" created"],
+ "07eGJB": ["Couldn't move skill: ", ["0"]],
"07gHun": ["You don't have access to this private repo. Sign in with an account that does."],
"07q4Qk": ["File sidebar"],
"09Tv5j": ["Reconnecting…"],
"0BB9ID": ["No headings yet."],
"0E9DR6": ["Type to find a doc"],
"0Gd0NU": ["Shared"],
+ "0LBDjY": ["\"", ["0"], "\" uninstalled — back to a draft"],
"0NA4b3": ["Keep my version"],
"0YEbfk": ["Connect to AI tools"],
"0_J12R": [
@@ -52,6 +55,7 @@
["targetLabel"]
],
"0eHrMb": ["Could not complete delete"],
+ "0g7rCZ": ["Duplicated to \"", ["0"], "\""],
"0jD-Gn": ["A team knowledge base, a personal wiki, project docs..."],
"0kTAXe": ["Open source: ", ["mirrorSrc"]],
"0njBIq": [
@@ -78,14 +82,15 @@
"1RluQD": ["Show replace"],
"1TNIig": ["Open"],
"1Ta7Fd": ["Open ", ["basename"]],
- "1WgmEM": ["Failed to load template: ", ["errorMessage"]],
"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"]],
"1bDVu5": ["Workspace Command Palette"],
"1d1F11": ["Select all files and folders"],
"1di5fu": ["Document not found"],
+ "1hvhf0": ["The folder on disk and the id agents use to invoke this skill."],
"1nke1r": ["Open ", ["0"], " on GitHub (opens in a new tab)"],
"1t_NnN": ["Reject"],
"2277Tu": ["Collapse graph"],
@@ -103,6 +108,7 @@
"2YOwme": ["Restarted — now running v", ["appRuntime"], "."],
"2YZwPB": ["Forward-links response did not match expected shape."],
"2Znqb1": [" (missing)"],
+ "2bVHbB": ["Available in every project on this computer."],
"2fkdnR": ["Nothing to undo on this file"],
"2hpdRq": ["Hide panel (", ["panelShortcutLabel"], ")"],
"2n3oDU": [
@@ -124,6 +130,7 @@
"3Fcb0I": ["Open graph"],
"3HNlwb": ["Hello, world!"],
"3Ib6FN": ["Move down"],
+ "3Ijjy1": ["Couldn't load this skill's files."],
"3IseAk": ["Install an AI agent to create with AI"],
"3J7d2N": ["Big section heading."],
"3JYy1p": ["Branch ", ["0"], " no longer exists. Cloned to default branch."],
@@ -157,6 +164,13 @@
"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"],
"48uGTI": ["Failed to load docs. Press Escape and re-open to retry."],
"4A3Yzu": ["Code block"],
@@ -168,6 +182,9 @@
"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."
+ ],
"4buZWd": ["Inherited from ", ["path"]],
"4c_a6S": ["Nothing set yet."],
"4g19V6": ["Failed to update property"],
@@ -210,6 +227,7 @@
"5Tk8Fb": ["Loading files"],
"5WDhAk": ["Link to a page or external URL."],
"5ZB7XC": ["File drop zone"],
+ "5e1Dri": ["The menu label agents pick this template by (required)."],
"5gr_ev": [
"Becomes the document's content when someone creates a doc from this template. Type <0>",
["dateToken"],
@@ -242,6 +260,7 @@
"636K3K": ["Delete adjacent chip"],
"67f-3g": ["Duplicate succeeded but the sidebar may be out of date — refresh to resync"],
"6Aih4U": ["Offline"],
+ "6EKG_c": ["What agents match on to decide when to use the skill."],
"6LbUG7": ["The repository is private and your GitHub account doesn't have access to it."],
"6MnZEC": ["Terminal failed to load"],
"6O626z": ["No headings match \"", ["trimmedAnchorQuery"], "\""],
@@ -261,6 +280,7 @@
"6cyguR": ["Connect GitHub to continue."],
"6eniID": ["Map the architecture"],
"6fGjTz": ["Show fewer"],
+ "6g2jsp": ["Update skill"],
"6gRgw8": ["Retry"],
"6h4zVU": ["What would you like to create?"],
"6hfDJr": ["Server error: ", ["status"]],
@@ -379,6 +399,7 @@
"9tJX8r": ["By meaning"],
"9zb2WA": ["Connecting"],
"A1taO8": ["Search"],
+ "A50vr3": ["Use lowercase letters, digits, and <0>-</0> only."],
"A5CYnd": ["Broken link"],
"A5hiCy": ["Create template"],
"A67Uwj": ["Still loading"],
@@ -409,8 +430,10 @@
"Aq-O0x": ["status"],
"AqnqMJ": ["API key set"],
"ArBWJf": ["Undo last edit"],
+ "AtBdnD": ["Couldn't delete skill: ", ["error"]],
"B11p-O": ["Edit markdown link"],
"B2DrPb": ["Auto-save"],
+ "B2Srgd": [["packName"], " skill installed."],
"B3NAZC": ["Open Navigator"],
"B4_ipX": [
[
@@ -445,6 +468,7 @@
"BymzO4": ["Document outline"],
"C37Zkt": ["Send to"],
"C62P6b": ["Editor selection"],
+ "C7XjNB": ["Global Skill"],
"C9TBvF": ["No Outgoing"],
"CCTop_": ["Recent"],
"CKyk7Q": ["Go back"],
@@ -460,6 +484,7 @@
],
"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"]],
"CvsD6Y": ["via ", ["viaTags"]],
@@ -475,6 +500,15 @@
"D_WKe_": ["Click an agent's avatar in the presence bar to view their session."],
"DbILZA": ["No matches. Some files are excluded from search (hidden or ignored files)."],
"DeDYLr": ["Unrecognized wiki link"],
+ "DhK_hZ": [
+ "Moved \"",
+ ["name"],
+ "\" to ",
+ ["0"],
+ " (",
+ ["skipped"],
+ " binary file(s) not copied)"
+ ],
"DhLHEb": ["Failed to load activity"],
"DiFKSL": ["Counting markdown files"],
"Dnn2XG": ["Automatic"],
@@ -484,6 +518,11 @@
"Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."
],
"Dw1T_W": ["Rename ", ["label"]],
+ "E1Da_b": [
+ "This permanently removes ",
+ ["0"],
+ ". Agents that invoke this skill by name will fail until it's recreated."
+ ],
"E1_c72": ["Task list"],
"E1tG2u": ["Get Claude Code"],
"E2Mv-X": ["Copy source"],
@@ -509,6 +548,7 @@
"\" 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"],
"EbZT7P": ["Toggle the left file sidebar."],
"EcM3k7": ["Failed to clean up pending ", ["kind"]],
@@ -520,6 +560,7 @@
"Ehkru0": ["Open, navigate, accept, or dismiss CodeMirror completion suggestions."],
"EiVgl5": ["You don't have permission to push to this repo."],
"Eji13z": ["Toggle highlight formatting."],
+ "EkH9pt": ["Update"],
"El7NbA": ["Heading 2"],
"Emz5BG": [
"Embeddings are computed only when a search runs and are cached locally under <0>.ok/local</0>."
@@ -532,6 +573,7 @@
"EvPX7f": ["Opens a folder picker to choose where to clone the repository."],
"Evq3lu": ["Orphan mode"],
"ExPiRQ": ["Move to the next CodeMirror lint diagnostic."],
+ "ExUzM4": ["skill \"", ["0"], "\""],
"F-NRCj": ["Add property"],
"F-vBv0": ["Ask"],
"F0OA00": ["Get ", ["displayName"]],
@@ -556,6 +598,7 @@
"Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."
],
"FRYB1Q": ["/api/config returned a malformed body"],
+ "FRqZ9v": ["Couldn't update skill: ", ["0"]],
"FTUGgh": ["Enter a repository URL or owner/repo"],
"FUMerq": ["Could not enable sync: ", ["detail"]],
"FWQuPE": [
@@ -600,6 +643,7 @@
"GUqTzn": ["Competitor research"],
"GXf9hG": ["Cloning ", ["repoName"], "..."],
"G_686w": ["Task List"],
+ "G_efLf": ["Installed into"],
"G_mWXb": ["Filter languages"],
"GamjcN": ["Template saved"],
"GemPfn": ["Failed to parse forward-links error response (HTTP ", ["status"], ")"],
@@ -631,6 +675,7 @@
"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"],
"I1gRhX": ["Failed to rename"],
"I5AfhE": ["Sync status unavailable — server unreachable."],
"IA1wNb": ["The Claude Desktop App didn't open the file. Is it installed? (", ["msg"], ")"],
@@ -667,6 +712,7 @@
],
"JE21eh": ["Symlink to ", ["targetPath"]],
"JK-Ave": ["Hide thumbnails"],
+ "JL3si7": ["Updating"],
"JLUTgi": ["No tags yet — author `#tagname` in any doc to populate the index."],
"JLzQi_": ["Close ", ["accessibleLabel"]],
"JOcPqH": ["Bring a remote repository onto this machine."],
@@ -720,6 +766,7 @@
"KmydK6": ["Bold"],
"KnoB--": ["Will be saved as <0>", ["sanitized"], "</0>."],
"KsAPaB": ["This branch is checked out in:"],
+ "KszKI_": ["Skill level"],
"KujtjC": ["Find"],
"L-rMC9": ["Reset to default"],
"L1ZE3M": ["Document statistics"],
@@ -792,11 +839,21 @@
"MZoxVx": ["Failed to load tags. Press Escape and re-open to retry."],
"Mb_20S": ["Visual"],
"Md709y": ["Loading ", ["fileName"]],
+ "MdpSC1": ["New skill"],
+ "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."],
"MrwYIK": ["Toggle a source comment through CodeMirror."],
"MsuXaI": ["Hide panel (", ["panelShortcut"], ")"],
+ "My9uXI": [
+ "Updated \"",
+ ["display"],
+ "\" to ",
+ ["0"],
+ " — your previous version is in history if you need to restore it."
+ ],
"N1YYa7": ["Loading image"],
"N1mdmS": ["This file can't be opened in the text editor."],
"N2FcBE": ["Synced"],
@@ -838,15 +895,16 @@
"O6yEPk": ["Create a new OpenKnowledge project in the folder of your choice."],
"O7_W_a": ["Open with AI"],
"OD0FCX": ["Hidden “", ["basename"], "”"],
- "ODD5Jc": ["Edit ", ["templateLabel"]],
"ODGGlj": ["Folder name: ", ["detail"]],
"OETysD": ["No hub pages yet. Hubs appear once pages accumulate inbound graph links."],
+ "OEu_0l": ["Failed to load skills: ", ["0"]],
"OJTOUj": ["Requires ", ["brand"], "."],
"OJeiSH": ["Failed to add property"],
"OLBz-_": ["Mermaid diagram failed to render."],
"OLIKgw": ["Drag item ", ["0"], " to reorder"],
"ONPvOb": ["Loading agent activity"],
"ONgEZF": ["Loading headings for ", ["pageTarget"]],
+ "OOIVJo": ["Uninstalled \"", ["0"], "\" from ", ["1"]],
"OTF92M": ["Label <0>(optional display text)</0>"],
"OVjNeX": ["Terminal ", ["0"]],
"OX2Neh": ["Inline code"],
@@ -863,6 +921,7 @@
"Oos8fo": ["Copy command"],
"OuY8t9": ["Open in current branch"],
"OvEjsP": ["Copying..."],
+ "OxplNM": ["Updated \"", ["0"], "\": added ", ["1"], ", removed ", ["2"]],
"Oxyd5f": ["Pick a name"],
"OyIC0Q": ["Project name"],
"P-ye9o": ["Could not open folder picker"],
@@ -875,13 +934,16 @@
"PB4upl": ["Find previous match"],
"PBwmDJ": ["Searching by meaning"],
"PBxg_E": ["Not now"],
+ "PCSkw2": ["Skills"],
"PKLY-1": ["Opening..."],
"PMyJ9C": ["No edit session yet"],
+ "PPFQ3o": ["Installed \"", ["0"], "\" into ", ["1"]],
"PQCdtv": ["\"", ["docName"], "\" doesn't exist."],
"PR9FSv": ["Move to the next visual-editor find result."],
"PVUn_c": ["Open folder"],
"PZt1uN": ["Search files, commands, projects, and AI handoff actions."],
"PdA9NZ": [["ahead"], " ahead"],
+ "PdJZ5p": ["No skills yet."],
"Pgu10b": ["Saved as <0>", ["slug"], ".md</0>"],
"PgzIpb": ["Move to the previous visual-editor find result."],
"PiH3UR": ["Copied!"],
@@ -901,6 +963,7 @@
"QWks14": ["A short line shown under the name in the template list."],
"QYfQdv": [["displayName"], " CLI"],
"QcpeeE": ["Navigate to ", ["docName"]],
+ "QfFBdJ": ["The template's filename (without `.md`)."],
"QlxHAH": ["Showing results for \"", ["semanticResultsLabel"], "\""],
"QqBQu1": ["Label <0>(visible link text)</0>"],
"Qvls7J": ["Eng specs"],
@@ -920,6 +983,7 @@
"R65q-K": [
"A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
],
+ "R9IDFz": ["Renames the folder on disk and the id agents use to invoke it."],
"RDjuBN": ["Setup"],
"RDrXh4": ["Configure user, project, and integration settings."],
"RG4XHV": ["Copy ", ["0"], " prompt"],
@@ -930,6 +994,7 @@
"We'll build <0>openknowledge.skill</0>, save it to <1>~/Downloads</1>, and open the Claude Desktop App for you."
],
"RSqaSd": ["Project root"],
+ "RXNu_r": ["Shared via git with everyone working on this project."],
"RY6Bq1": ["Open shared ", ["targetNoun"]],
"RaPMZv": ["Keyboard shortcuts available in the editor and workspace."],
"Rah7yq": ["What should the AI do? (optional)"],
@@ -938,6 +1003,7 @@
"RgbKEe": ["You don't have access to this repository."],
"Rj01Fz": ["Links"],
"RlCInP": ["Slash commands"],
+ "RlLl3G": ["Actions for ", ["0"]],
"RmBY0A": ["No git remote"],
"RobAKV": ["Update the destination and optional section anchor."],
"Rq1vFD": ["Tree view options"],
@@ -952,6 +1018,7 @@
"SFN6dN": ["Heading 3"],
"STTOnz": [["keyName"], " type: complex value (nested; read-only)"],
"SUOoXn": ["Failed to open project."],
+ "SXCSQd": ["Copied path"],
"SYfHmN": ["Unpin tab"],
"Sc1bKE": [
"Local collaboration data for \"",
@@ -963,6 +1030,7 @@
"SgKLfA": ["Not connected to GitHub."],
"SiUUCS": ["Next match"],
"SkMZlS": ["Couldn't remove <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
+ "Sq8lf2": ["Editors to install skills into"],
"SrOuyg": ["Document panels"],
"T-4cw2": [
"Pick a layout that matches what you're building. Each pack ships with folders, templates, and agent-readable descriptions. You can mix and match later."
@@ -992,7 +1060,10 @@
"UBv8UK": ["Delete Permanently"],
"UDFrWm": ["Checking GitHub connection..."],
"UL8A9w": ["Tag"],
+ "UMrOy2": ["Skill \"", ["trimmedName"], "\" created"],
+ "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"],
@@ -1021,6 +1092,7 @@
"V48OUT": ["You deleted <0>", ["filePath"], "</0> locally, but it was modified upstream."],
"V7QxyT": ["Connection dropped"],
"VAHWL_": ["Connected as <0>@", ["signedInLogin"], "</0>"],
+ "VM7H66": ["This file is binary and can't be shown as text."],
"VNgKZz": ["Advanced settings"],
"VU3Nrn": ["Missing"],
"VUijjF": ["Embed an image with optional alt text."],
@@ -1093,6 +1165,7 @@
"Xet9MX": ["Failed to load backlinks"],
"XfzqjK": ["template \"", ["name"], "\""],
"Xl-UUg": ["guides/install or https://example.com"],
+ "XmJfZT": ["name"],
"XnlF3W": ["Add the next matching source selection."],
"XnoA1k": [
"This ",
@@ -1103,6 +1176,7 @@
],
"XopE_I": ["Failed to parse backlinks error response (HTTP ", ["status"], ")"],
"XpIZmv": ["Fenced code block with monospace text."],
+ "XqNHcm": ["Couldn't update skill targets: ", ["0"]],
"XtRoxT": ["Page ", ["pageNumber"]],
"XvPJaT": ["Diff layout"],
"Xv_ijG": ["https://github.com/owner/repo or owner/repo"],
@@ -1124,6 +1198,7 @@
"YGQm6y": [
"OpenKnowledge manages the <0>open-knowledge</0> MCP server name, the <1>open-knowledge-ui</1> launch config, and <2>ok</2> / <3>open-knowledge</3> on PATH (including OK-owned symlinks). Using a custom wrapper? Register it under a different name."
],
+ "YJ1BTp": ["A skill with that name already exists."],
"YKLP_-": ["Template renamed"],
"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" still exists on disk"],
"YSFv5w": ["No git repository — config sharing does not apply here."],
@@ -1149,6 +1224,7 @@
],
"Z8KDox": ["Enter a folder name (e.g. brain)."],
"Z8lGw6": ["Share"],
+ "ZARuZJ": ["Couldn't load files"],
"ZBYKxv": [
"Reverts every change this agent made to <0>",
["docName"],
@@ -1188,7 +1264,6 @@
"</1>."
],
"_BthEY": ["Open in ", ["shareBranch"]],
- "_K2CvV": ["Template"],
"_PACVa": ["Release notes"],
"_PBJRl": ["Add at least one letter or number."],
"_QwkMu": ["No matching paths"],
@@ -1203,6 +1278,7 @@
"_bth6g": ["Claude Code is installed, but OpenKnowledge tools aren't connected to it yet."],
"_eguJc": ["Uploading"],
"_gkGSK": ["deleted template"],
+ "_hPpdX": ["Skill renamed"],
"_pY_Vq": ["The repository was moved, renamed, or deleted."],
"_qD6mn": ["Pick the folder where you've cloned it."],
"_rP3HI": [["minutes"], "m ago"],
@@ -1216,6 +1292,7 @@
"/ and all files inside? This action cannot be undone."
],
"a9OzSn": ["No pages found for \"", ["trimmedQuery"], "\""],
+ "aBgwis": ["Scope"],
"aByJ8j": ["How does sharing work?"],
"aE2_XM": ["One pattern per line — appended to <0>.okignore</0>."],
"aENGMB": [
@@ -1242,7 +1319,6 @@
"bD8I7O": ["Complete"],
"bGa3Fk": ["Uploading file"],
"bH382I": ["Edit this HTML — the preview updates live."],
- "bHboUQ": ["Edit template"],
"bS_boY": ["Replace current match"],
"bUUVED": ["Asset"],
"bWLmRK": ["Could not fetch branch. Check your connection."],
@@ -1266,6 +1342,7 @@
"cKjLuT": ["(project + user)"],
"cOSAfL": ["No repositories found on your GitHub account."],
"cOrTMo": ["Your share link is ready below."],
+ "cRHuuI": ["Couldn't copy path"],
"cSCbv3": ["BETA"],
"cUK8lW": [
["conflictCount", "plural", { "one": ["#", " conflict"], "other": ["#", " conflicts"] }]
@@ -1299,6 +1376,7 @@
"dOxPd4": ["Footnote"],
"dPOFid": ["Show or hide terminal"],
"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."
],
@@ -1312,6 +1390,7 @@
"dprWmL": ["Anchor in this page"],
"dr1vFs": ["Replace all matches"],
"dvGKu2": ["Shared auto-sync default"],
+ "dw_3cv": ["Rename skill"],
"dw_dUJ": ["Failed to duplicate path"],
"e0NrBM": ["Project"],
"e1Rn_k": ["Open containing folder"],
@@ -1326,12 +1405,16 @@
"eKThTQ": ["Failed to reorder"],
"eNQGRb": ["Inline LaTeX math rendered with KaTeX."],
"ePK91l": ["Edit"],
+ "eQkgKV": ["Installed"],
"eSu2Xn": [
"Writes a project-MCP config for each selected tool; Claude also gets <0>.claude/launch.json</0>."
],
"eTL5y9": ["Show selection preview"],
+ "eTsJYJ": ["description"],
"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],
+ "el312q": ["Install skills into"],
"emgiet": ["Authoritative content; mirrored verbatim everywhere it's referenced."],
+ "eneWvv": ["Draft"],
"euc6Ns": ["Duplicate"],
"evs0iw": ["Tags matching \"", ["tagListQuery"], "\""],
"f1XQyZ": ["Move block"],
@@ -1354,6 +1437,7 @@
"fbsiBw": ["Something went wrong starting the terminal."],
"fcgvCA": ["Claude"],
"fiMNLl": ["Sync settings not yet loaded — try again in a moment"],
+ "fo0VXg": ["Uninstall"],
"fqSfXY": ["Replace"],
"fwhX-N": ["Indent or outdent source"],
"g3UF2V": ["Accept"],
@@ -1385,6 +1469,7 @@
],
"ggs9f8": ["Search files, folders, or commands"],
"gijbne": ["Failed to rename path"],
+ "gk_-qj": ["Couldn't rename template: ", ["0"]],
"gljvbT": [["words", "plural", { "one": ["word"], "other": ["words"] }]],
"gmJ0An": ["Failed to open folder."],
"goO4Ll": ["Editor status bar"],
@@ -1403,6 +1488,7 @@
"</1>. Your current content is already saved in the timeline — you can restore it anytime."
],
"h7FzJC": ["Link-graph response did not match expected shape."],
+ "h9QFb9": ["Skill \"", ["0"], "\" deleted"],
"hBMK4W": ["Project templates"],
"hDEaQu": ["Connect OpenKnowledge to other tools you use."],
"hDKtoF": [["diffHrs"], "h ago"],
@@ -1432,6 +1518,7 @@
"i92eAT": ["We'll create a repository and start syncing — no terminal needed."],
"i9OyGp": ["Undo or redo"],
"i9toLO": ["Agent configuration file"],
+ "iAoh55": ["Update \"", ["0"], "\"?"],
"iDZtvM": ["Failed to load templates: ", ["message"]],
"iEQQyu": ["Agent"],
"iEYxO4": ["Show thumbnails"],
@@ -1475,6 +1562,7 @@
"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"], ")"],
@@ -1504,6 +1592,7 @@
"kCqCyf": ["Open CodeMirror's lint diagnostics panel."],
"kFLlsI": ["Insert a footnote reference + matching definition stub."],
"kNqMMd": ["Folder"],
+ "kPtvEH": ["The pack skill <0>", ["0"], "</0> will be (re)installed."],
"kUn-CN": ["Sync off"],
"kV2YZv": [
"Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."
@@ -1524,11 +1613,13 @@
"l1aQKz": ["Visual editor table"],
"l1l8sj": [["0"], "d ago"],
"l3mSlL": ["Append-only timeline"],
+ "l3s5ri": ["Import"],
"l6OXqI": ["No installed agents found"],
"l8G3S9": ["Auto-sync is off — you don't have permission to push to this repo"],
"lAiyU_": ["Only the current document uses <0>#", ["tag"], "</0>."],
"lGs_bQ": ["Page <0>*</0>"],
"lHwYMr": ["Server error: ", ["status"], " ", ["statusText"]],
+ "lI0Td2": ["Use letters, digits, <0>_</0> and <1>-</1> only."],
"lIn9L9": ["Disable sync"],
"lPzyrU": ["All hunks resolved"],
"lVWEIL": ["Indexed ", ["embedded"], " of ", ["total"], " pages."],
@@ -1556,12 +1647,14 @@
"mGaZwZ": ["See the full install guide"],
"mHVPm5": ["Reconnect required"],
"mNY1G6": ["Undo all edits"],
+ "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."
],
"mSJ3Rn": ["Computing scaffold plan"],
"mU3j1b": ["Remove item ", ["0"]],
"mWVJRX": ["Collapsible section with a clickable summary."],
+ "mY8U64": ["Teach agents a repeatable task. You can edit the body after creating."],
"mYGY3B": ["Date"],
"mZ1r4i": ["Create a document from ", ["label"]],
"maDWIB": ["Mirror source <0>api-spec</0>"],
@@ -1592,7 +1685,13 @@
],
"n7aopT": ["Editor mode"],
"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."],
+ "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."
],
@@ -1616,6 +1715,7 @@
["errorDetail"],
". Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
],
+ "npcziF": ["Install on"],
"nrGWJ7": [
"Git identity isn't set — commits use a default author. Set yours so teammates see your name."
],
@@ -1635,6 +1735,7 @@
"o9CrsQ": ["research-note"],
"oAFVKX": ["Failed to update the project sync default — ", ["detail"]],
"oBXkm2": ["Delete code block"],
+ "oCHfGC": ["Level"],
"oCZkaG": ["Copy path"],
"oJl7eO": ["Unknown component: ", ["componentName"], " — source editable below"],
"oKBnk5": ["More requests were blocked."],
@@ -1685,6 +1786,7 @@
"q2kXMG": ["Inline Math"],
"q4YJl_": ["The terminal session ended (exit code ", ["0"], ")."],
"q6-JVU": ["Loading pages"],
+ "q7F5am": ["title"],
"qAQVSD": ["Page headings response was not JSON"],
"qAhFeg": [
["userName"],
@@ -1762,6 +1864,8 @@
". You can still create a blank note."
],
"sER-bs": ["Files"],
+ "sFhaTJ": ["Disambiguates similarly-named templates in the menu."],
+ "sHrqDx": ["Couldn't rename skill: ", ["0"]],
"sIGbBZ": ["Convert selection to footnote"],
"sIxSSP": ["Resolve conflict in your terminal"],
"sJK6pq": ["Permission denied"],
@@ -1791,7 +1895,9 @@
"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"],
"tAPZEx": ["Below"],
+ "tHKQ6j": ["Renaming"],
"tP5DDk": ["Apply link"],
"tUvUfp": ["Use a folder you already have."],
"tW_yvQ": ["Expand ", ["docName"]],
@@ -1814,6 +1920,9 @@
"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."
+ ],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
"uKRYiW": ["Sync status unavailable — server error."],
"uL_Wx8": ["The terminal stopped unexpectedly."],
@@ -1852,6 +1961,7 @@
{ "one": ["Uploaded one file"], "other": ["Uploaded ", ["uploadedCount"], " files"] }
]
],
+ "v7hK0U": ["Use lowercase letters, digits, and hyphens only."],
"v7lbnC": ["Find next match"],
"vDXqVv": ["Insert a markdown hard break."],
"vEJDlt": ["The file is in your Trash; the file-watcher will reconcile."],
@@ -1878,6 +1988,7 @@
],
"w7SsvI": ["That folder isn't an OpenKnowledge project yet. Initialize it and open?"],
"w7nm4K": ["Indented blockquote for citations."],
+ "wDgmsr": ["\"", ["0"], "\" install refreshed (", ["1"], ")"],
"wJijgU": ["Location"],
"wJo9oS": ["Close find"],
"wQp1V3": ["Mirror of <0>", ["src"], "</0>"],
@@ -1890,9 +2001,13 @@
"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."],
"wtcxiD": ["Share this setup with your team?"],
"wvbc1r": ["Couldn't open document"],
+ "x-5mJ1": ["Install on all"],
"x2fr_j": ["Graph"],
"x3-2ta": [
["packName"],
@@ -1928,11 +2043,19 @@
"xeiujy": ["Text"],
"xhlFsx": ["Inherited — set a value here to replace it."],
"xiv-dW": ["No files yet."],
+ "xloBjn": ["Relative Path"],
+ "xnP32l": ["No description yet — add one so agents know when to use this skill."],
+ "xrVr_k": ["Couldn't create skill: ", ["0"]],
"xsZhu-": ["Page number"],
"xzktOa": ["Edit wiki link"],
"y1t8bQ": ["Settings sections"],
"y3aU20": ["Save changes"],
"y46m5r": ["The desktop app isn't responding. Refresh and try again."],
+ "y48eD2": [
+ "Open Knowledge can manage ",
+ ["0"],
+ " editor skill(s) for this project — import them into the knowledge base?"
+ ],
"y5FUYi": ["Suggestion menu open"],
"y8B54M": ["Couldn't send your prompt — please try again."],
"yCX4jp": [" Your selection could not be restored."],
@@ -1968,6 +2091,7 @@
["typeLabel"],
" (inherited from folder properties; not editable here)"
],
+ "yitgD9": ["Failed to load skill targets: ", ["0"]],
"yjExfe": ["Branch <0>", ["shareBranch"], "</0> is checked out in:"],
"ylXj1N": ["Selected"],
"ynIa4S": ["Visual editor list item"],
@@ -1983,11 +2107,13 @@
"z0a2EA": ["Diagram from Mermaid source — flowchart, sequence, class, state, ER, gantt, pie."],
"z1uNN0": ["No emoji found."],
"z2JdQ-": ["Config sharing unchanged — see details below."],
+ "z2funE": ["Full Path"],
"z5pqI8": ["Cannot upload: no document is open"],
"z60Lgn": [
"Saves the file to <0>~/Downloads/openknowledge.skill</0> and opens the Claude Desktop App. Requires Node.js or Bun on your PATH."
],
"zAsDLY": ["Graph visualization of document links"],
+ "zKxoPm": ["Couldn't rename \"", ["0"], "\": ", ["1"]],
"zL0LPh": ["Global outside text fields"],
"zLGXna": ["No starter packs available."],
"zLak8b": ["Activate new tab"],
@@ -1999,6 +2125,7 @@
"The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
],
"zbymaY": [["0"], "m ago"],
+ "zd00pH": ["Copy Path"],
"zgSFyG": ["External link"],
"zkz0Fg": ["Set up syncing"],
"zlErBl": ["Page headings error response did not match RFC 9457"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index f21adb553..cb836daad 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -29,6 +29,17 @@ msgstr " Your selection could not be restored."
msgid " Your selection has been restored."
msgstr " Your selection has been restored."
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(result.hosts)
+#: src/components/skill-actions.tsx
+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"
+
#: src/components/DocumentErrorBoundary.tsx
msgid "\"{docName}\" doesn't exist."
msgstr "\"{docName}\" doesn't exist."
@@ -320,6 +331,10 @@ msgstr "{owner}/{name} already exists"
msgid "{packName} initialized ({projectEntries, plural, one {# entry} other {# entries}})"
msgstr "{packName} initialized ({projectEntries, plural, one {# entry} other {# entries}})"
+#: src/components/SeedDialog.tsx
+msgid "{packName} skill installed."
+msgstr "{packName} skill installed."
+
#: src/components/SeedDialog.tsx
msgid "{packName} was already set up. Nothing to do."
msgstr "{packName} was already set up. Nothing to do."
@@ -465,6 +480,14 @@ msgstr "A reusable starting point for new documents in this folder."
msgid "A short line shown under the name in the template list."
msgstr "A short line shown under the name in the template list."
+#: 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/empty-state/CreatePromptComposer.tsx
msgid "A team knowledge base, a personal wiki, project docs..."
msgstr "A team knowledge base, a personal wiki, project docs..."
@@ -494,6 +517,12 @@ 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}"
@@ -768,6 +797,10 @@ 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/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>."
msgstr "Available in the OpenKnowledge desktop app. From a terminal, use<0> ok config-sharing status</0> / <1>share</1> / <2>unshare</2>."
@@ -933,13 +966,15 @@ msgstr "Can't nest projects. An OpenKnowledge project already exists at <0>{root
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/MountStalledAffordance.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/SeedDialog.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
-#: src/components/TemplateEditDialog.tsx
+#: src/components/SkillRenameDialog.tsx
+#: src/components/SkillUpdateDialog.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
#: src/editor/components/CodePreviewEditModal.tsx
@@ -1000,6 +1035,10 @@ msgstr "Choose agent"
msgid "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."
msgstr "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."
+#: 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"
@@ -1384,6 +1423,10 @@ msgstr "Copied"
msgid "Copied full path"
msgstr "Copied full path"
+#: src/components/skill-actions.tsx
+msgid "Copied path"
+msgstr "Copied path"
+
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Copied relative path"
@@ -1436,6 +1479,10 @@ msgstr "Copy full path, No workspace"
msgid "Copy path"
msgstr "Copy path"
+#: src/components/skill-actions.tsx
+msgid "Copy Path"
+msgstr "Copy Path"
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Copy share link"
msgstr "Copy share link"
@@ -1575,6 +1622,10 @@ msgstr "Couldn't connect OpenKnowledge tools to Claude Code. Please try again."
msgid "Couldn't construct the share URL. Try Done and re-share."
msgstr "Couldn't construct the share URL. Try Done and re-share."
+#: src/components/skill-actions.tsx
+msgid "Couldn't copy path"
+msgstr "Couldn't copy path"
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Couldn't copy: {detail}"
msgstr "Couldn't copy: {detail}"
@@ -1583,10 +1634,19 @@ msgstr "Couldn't copy: {detail}"
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
+msgid "Couldn't create skill: {0}"
+msgstr "Couldn't create skill: {0}"
+
#: src/components/TemplateForm.tsx
msgid "Couldn't create template: {error}"
msgstr "Couldn't create template: {error}"
+#: src/components/SkillDeleteDialog.tsx
+msgid "Couldn't delete skill: {error}"
+msgstr "Couldn't delete skill: {error}"
+
#: src/components/TemplateDeleteDialog.tsx
msgid "Couldn't delete template: {error}"
msgstr "Couldn't delete template: {error}"
@@ -1595,7 +1655,18 @@ msgstr "Couldn't delete template: {error}"
msgid "Couldn't disconnect — please try again."
msgstr "Couldn't disconnect — please try again."
-#: src/components/TextViewer.tsx
+#. placeholder {0}: skill.name
+#. placeholder {1}: result.error
+#: src/components/skill-actions.tsx
+msgid "Couldn't duplicate \"{0}\": {1}"
+msgstr "Couldn't duplicate \"{0}\": {1}"
+
+#. placeholder {0}: result.error
+#: src/components/skill-actions.tsx
+msgid "Couldn't install skill: {0}"
+msgstr "Couldn't install skill: {0}"
+
+#: src/components/ViewerStatusPane.tsx
msgid "Couldn't load {fileName}"
msgstr "Couldn't load {fileName}"
@@ -1611,6 +1682,10 @@ 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}"
@@ -1619,6 +1694,15 @@ 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."
+
+#. placeholder {0}: result.error
+#: src/components/ManagedArtifactProperties.tsx
+msgid "Couldn't move skill: {0}"
+msgstr "Couldn't move skill: {0}"
+
#: src/components/TrashFailureModal.tsx
msgid "Couldn't move to Trash"
msgstr "Couldn't move to Trash"
@@ -1651,6 +1735,22 @@ msgstr "Couldn't reconnect after server restart"
msgid "Couldn't remove <0>{targetGitPath}</0>: {removeGitError}"
msgstr "Couldn't remove <0>{targetGitPath}</0>: {removeGitError}"
+#. placeholder {0}: skill.name
+#. placeholder {1}: result.error
+#: src/components/SkillRenameDialog.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}"
+msgstr "Couldn't rename template: {0}"
+
#: src/components/DiffViewBoundary.tsx
msgid "Couldn't resolve the conflict for {filePath}."
msgstr "Couldn't resolve the conflict for {filePath}."
@@ -1683,6 +1783,21 @@ msgstr "Couldn't send the selection — please try again."
msgid "Couldn't send your prompt — please try again."
msgstr "Couldn't send your prompt — please try again."
+#. 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}"
+
#: src/components/ConsentDialogBody.tsx
msgid "Counting markdown files"
msgstr "Counting markdown files"
@@ -1737,6 +1852,10 @@ msgstr "Create new tag #{tagValue}"
msgid "Create page"
msgstr "Create page"
+#: 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."
@@ -1773,6 +1892,7 @@ msgstr "created template"
#: src/components/CreateProjectDialog.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
msgid "Creating"
msgstr "Creating"
@@ -1811,6 +1931,7 @@ msgid "Default properties"
msgstr "Default properties"
#: src/components/DeleteConfirmationDialog.tsx
+#: src/components/skill-actions.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/JsxComponentView.tsx
msgid "Delete"
@@ -1885,6 +2006,11 @@ 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/TemplateProperties.tsx
+msgid "description"
+msgstr "description"
+
+#: src/components/NewSkillDialog.tsx
#: src/components/TemplateForm.tsx
msgid "Description"
msgstr "Description"
@@ -1909,6 +2035,10 @@ msgstr "Detached HEAD — checkout a branch to resume"
msgid "Details"
msgstr "Details"
+#: 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."
+
#: src/components/McpConsentDialogBody.tsx
msgid "Detected on this machine"
msgstr "Detected on this machine"
@@ -1942,6 +2072,10 @@ msgstr "Disable semantic search"
msgid "Disable sync"
msgstr "Disable sync"
+#: src/components/TemplateProperties.tsx
+msgid "Disambiguates similarly-named templates in the menu."
+msgstr "Disambiguates similarly-named templates in the menu."
+
#: src/components/settings/AccountSection.tsx
msgid "Disconnect"
msgstr "Disconnect"
@@ -2038,6 +2172,11 @@ msgstr "Download started"
msgid "Downloads {shareOwner}/{shareRepo} from GitHub."
msgstr "Downloads {shareOwner}/{shareRepo} 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"
@@ -2060,6 +2199,7 @@ msgid "Drag item {0} to reorder"
msgstr "Drag item {0} to reorder"
#: src/components/FileTree.tsx
+#: src/components/skill-actions.tsx
msgid "Duplicate"
msgstr "Duplicate"
@@ -2079,6 +2219,11 @@ msgstr "Duplicate succeeded but the sidebar may be out of date — refresh to re
msgid "Duplicate the focused file-tree item when focus is in the Files sidebar."
msgstr "Duplicate the focused file-tree item when focus is in the Files sidebar."
+#. placeholder {0}: result.name
+#: src/components/skill-actions.tsx
+msgid "Duplicated to \"{0}\""
+msgstr "Duplicated to \"{0}\""
+
#: src/components/settings/OkignoreSection.tsx
msgid "e.g. drafts/ or *.draft.md"
msgstr "e.g. drafts/ or *.draft.md"
@@ -2091,6 +2236,7 @@ msgstr "e.g. server.ts"
msgid "Each selected tool gets an OpenKnowledge MCP entry."
msgstr "Each selected tool gets an OpenKnowledge MCP entry."
+#: src/components/skill-actions.tsx
#: src/components/TemplateForm.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
@@ -2107,10 +2253,6 @@ msgstr "Edit {0} source"
msgid "Edit {keyName}"
msgstr "Edit {keyName}"
-#: src/components/TemplateEditDialog.tsx
-msgid "Edit {templateLabel}"
-msgstr "Edit {templateLabel}"
-
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "Edit markdown link"
msgstr "Edit markdown link"
@@ -2119,10 +2261,6 @@ msgstr "Edit markdown link"
msgid "Edit source"
msgstr "Edit source"
-#: src/components/TemplateEditDialog.tsx
-msgid "Edit template"
-msgstr "Edit template"
-
#: src/editor/slash-command/embed-starter-items.tsx
msgid "Edit this HTML — the preview updates live."
msgstr "Edit this HTML — the preview updates live."
@@ -2147,7 +2285,7 @@ msgstr "editing [[{realCurrentDoc}]]"
msgid "Editing broken MDX source: {reason}"
msgstr "Editing broken MDX source: {reason}"
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Editor mode"
msgstr "Editor mode"
@@ -2159,6 +2297,10 @@ 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/editor/slash-command/component-items.tsx
msgid "Edits at the source land here — no copy-paste drift."
msgstr "Edits at the source land here — no copy-paste drift."
@@ -2388,7 +2530,7 @@ msgstr "Failed to load docs. Press Escape and re-open to retry."
msgid "Failed to load documents"
msgstr "Failed to load documents"
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "Failed to load file"
msgstr "Failed to load file"
@@ -2434,14 +2576,20 @@ msgstr "Failed to load project templates"
msgid "Failed to load recent projects."
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}"
+
#: src/components/CommandPalette.tsx
msgid "Failed to load tags. Press Escape and re-open to retry."
msgstr "Failed to load tags. Press Escape and re-open to retry."
-#: src/components/TemplateEditDialog.tsx
-msgid "Failed to load template: {errorMessage}"
-msgstr "Failed to load template: {errorMessage}"
-
#: src/components/TemplatesCard.tsx
msgid "Failed to load templates: {message}"
msgstr "Failed to load templates: {message}"
@@ -2641,6 +2789,7 @@ msgstr "Fold, unfold, fold all, or unfold all source ranges."
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
+#: src/components/TemplateProperties.tsx
msgid "folder"
msgstr "folder"
@@ -2704,6 +2853,10 @@ msgstr "Full guide"
msgid "Full path"
msgstr "Full path"
+#: src/components/skill-actions.tsx
+msgid "Full Path"
+msgstr "Full Path"
+
#: src/lib/keyboard-shortcuts.ts
msgid "General"
msgstr "General"
@@ -2733,6 +2886,7 @@ 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/lib/keyboard-shortcuts.ts
+#: src/lib/skill-scope.ts
msgid "Global"
msgstr "Global"
@@ -2740,6 +2894,10 @@ 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"
@@ -2938,6 +3096,10 @@ msgstr "Ignore patterns"
msgid "Ignore patterns (raw text)"
msgstr "Ignore patterns (raw text)"
+#: src/components/SkillsSidebarSection.tsx
+msgid "Import"
+msgstr "Import"
+
#: src/components/SeedDialog.tsx
msgid "In a subfolder"
msgstr "In a subfolder"
@@ -3061,6 +3223,8 @@ msgstr "Insert, delete, move, copy, and indent source editor lines through CodeM
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/settings/SettingsDialogBody.tsx
+#: src/components/skill-actions.tsx
+#: src/components/SkillRow.tsx
msgid "Install"
msgstr "Install"
@@ -3089,6 +3253,34 @@ msgstr "Install handoff failed: {msg}"
msgid "Install in Claude Desktop"
msgstr "Install in Claude Desktop"
+#: src/components/SkillEditorActions.tsx
+msgid "Install on"
+msgstr "Install on"
+
+#: src/components/SkillEditorActions.tsx
+msgid "Install on all"
+msgstr "Install on all"
+
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Install skills into"
+msgstr "Install skills into"
+
+#: src/components/SkillEditorActions.tsx
+#: src/components/SkillRow.tsx
+#: src/components/SkillStateBadge.tsx
+msgid "Installed"
+msgstr "Installed"
+
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(added)
+#: src/components/skill-actions.tsx
+msgid "Installed \"{0}\" into {1}"
+msgstr "Installed \"{0}\" into {1}"
+
+#: src/components/SkillRow.tsx
+msgid "Installed into"
+msgstr "Installed into"
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Installing"
msgstr "Installing"
@@ -3179,6 +3371,10 @@ msgstr "Layout options"
msgid "Let Tab leave the source editor instead of indenting."
msgstr "Let Tab leave the source editor instead of indenting."
+#: src/components/SkillProperties.tsx
+msgid "Level"
+msgstr "Level"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Light, dark, or follow the OS."
msgstr "Light, dark, or follow the OS."
@@ -3217,13 +3413,14 @@ msgid "List"
msgstr "List"
#: src/components/PageHeaderWidgets.tsx
+#: src/components/SkillsSidebarSection.tsx
#: src/editor/components/TagDialog.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Loading"
msgstr "Loading"
-#: src/components/TextViewer.tsx
+#: src/components/ViewerStatusPane.tsx
msgid "Loading {fileName}"
msgstr "Loading {fileName}"
@@ -3378,11 +3575,11 @@ msgstr "Map the architecture"
msgid "Mark a block as the source of truth. Mirror references elsewhere render this content read-only and update live as you edit here."
msgstr "Mark a block as the source of truth. Mirror references elsewhere render this content read-only and update live as you edit here."
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Markdown"
msgstr "Markdown"
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Markdown source"
msgstr "Markdown source"
@@ -3503,6 +3700,16 @@ msgstr "Move to the previous visual-editor find result."
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)"
+
#: src/components/FolderTimelineCard.tsx
msgid "moved template"
msgstr "moved template"
@@ -3511,8 +3718,15 @@ msgstr "moved template"
msgid "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
msgstr "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
+#: src/components/SkillProperties.tsx
+#: src/components/TemplateProperties.tsx
+msgid "name"
+msgstr "name"
+
#: src/components/AuthModal.tsx
#: src/components/FolderOverview.tsx
+#: src/components/NewSkillDialog.tsx
+#: src/components/SkillRenameDialog.tsx
#: src/editor/slash-command/items.tsx
msgid "Name"
msgstr "Name"
@@ -3624,6 +3838,12 @@ msgstr "New project"
msgid "New property name"
msgstr "New property name"
+#: src/components/NewSkillDialog.tsx
+#: src/components/settings/SkillsManagerSection.tsx
+#: src/components/SkillsSidebarSection.tsx
+msgid "New skill"
+msgstr "New skill"
+
#: src/components/EditorTabs.tsx
msgid "New tab"
msgstr "New tab"
@@ -3658,6 +3878,10 @@ msgstr "No changes"
msgid "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
msgstr "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
+#: 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/ActivityPanelBurstRow.tsx
msgid "No diff."
msgstr "No diff."
@@ -3698,6 +3922,10 @@ msgstr "No git remote"
msgid "No git repository — config sharing does not apply here."
msgstr "No git repository — config sharing does not apply 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}"
@@ -3801,6 +4029,10 @@ msgstr "No pages matched \"{semanticQueryText}\" by meaning."
msgid "No patterns yet. Type a folder or file name below to start hiding files."
msgstr "No patterns yet. Type a folder or file name below to start hiding files."
+#: 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."
@@ -3818,6 +4050,10 @@ msgstr "no response"
msgid "No results"
msgstr "No results"
+#: src/components/SkillsSidebarSection.tsx
+msgid "No skills yet."
+msgstr "No skills yet."
+
#: src/components/PackCardGrid.tsx
msgid "No starter packs available."
msgstr "No starter packs available."
@@ -3882,6 +4118,7 @@ msgstr "Not detected"
msgid "Not installed"
msgstr "Not installed"
+#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
msgid "Not now"
msgstr "Not now"
@@ -4045,7 +4282,7 @@ msgid "Open emoji picker for {keyName}"
msgstr "Open emoji picker for {keyName}"
#: src/components/AssetPreview.tsx
-#: src/components/TextViewer.tsx
+#: src/components/ViewerStatusPane.tsx
msgid "Open file"
msgstr "Open file"
@@ -4071,6 +4308,11 @@ msgstr "Open in {shareBranch}"
msgid "Open in current branch"
msgstr "Open in current branch"
+#. placeholder {0}: state.importable
+#: src/components/SkillsSidebarSection.tsx
+msgid "Open Knowledge can manage {0} editor skill(s) for this project — import them into the knowledge base?"
+msgstr "Open Knowledge can manage {0} editor skill(s) for this project — import them into the knowledge base?"
+
#: src/components/GraphPanel.tsx
msgid "Open link"
msgstr "Open link"
@@ -4462,6 +4704,7 @@ msgid "project"
msgstr "project"
#: src/components/CommandPalette.tsx
+#: src/lib/skill-scope.ts
msgid "Project"
msgstr "Project"
@@ -4478,6 +4721,10 @@ msgstr "Project name"
msgid "Project root"
msgstr "Project root"
+#: src/lib/skill-scope.ts
+msgid "Project Skill"
+msgstr "Project Skill"
+
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "Project templates"
msgstr "Project templates"
@@ -4503,6 +4750,7 @@ msgid "Project-level pages with no outgoing graph edges."
msgstr "Project-level pages with no outgoing graph edges."
#: src/components/PropertyPanel.tsx
+#: src/components/TemplateProperties.tsx
msgid "Properties"
msgstr "Properties"
@@ -4650,6 +4898,10 @@ msgstr "Reject"
msgid "Relative path"
msgstr "Relative path"
+#: src/components/skill-actions.tsx
+msgid "Relative Path"
+msgstr "Relative Path"
+
#: src/components/FileTree.tsx
msgid "Relaunching to install the update…"
msgstr "Relaunching to install the update…"
@@ -4731,6 +4983,8 @@ msgid "Removing"
msgstr "Removing"
#: src/components/FileTree.tsx
+#: src/components/skill-actions.tsx
+#: src/components/SkillRenameDialog.tsx
msgid "Rename"
msgstr "Rename"
@@ -4742,6 +4996,10 @@ msgstr "Rename {keyName}"
msgid "Rename {label}"
msgstr "Rename {label}"
+#: src/components/SkillRenameDialog.tsx
+msgid "Rename skill"
+msgstr "Rename skill"
+
#: src/components/FileTree.tsx
msgid "Rename succeeded but the sidebar may be out of date — refresh to resync"
msgstr "Rename succeeded but the sidebar may be out of date — refresh to resync"
@@ -4750,6 +5008,18 @@ msgstr "Rename succeeded but the sidebar may be out of date — refresh to resyn
msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
msgstr "Rename succeeded but the tabstrip may be out of date — refresh to resync"
+#: src/components/SkillRenameDialog.tsx
+msgid "Renamed to \"{trimmed}\""
+msgstr "Renamed to \"{trimmed}\""
+
+#: 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/SkillRenameDialog.tsx
+msgid "Renaming"
+msgstr "Renaming"
+
#: src/components/TemplateForm.tsx
msgid "Renaming changes the file on disk and the id agents use to pick this template."
msgstr "Renaming changes the file on disk and the id agents use to pick this template."
@@ -4919,6 +5189,7 @@ msgstr "Reveal in File Explorer, {hint}"
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
+#: src/components/skill-actions.tsx
msgid "Reveal in Finder"
msgstr "Reveal in Finder"
@@ -4960,7 +5231,6 @@ msgstr "Sandboxed HTML embed — write HTML, see the rendered preview live."
#: src/components/AuthModal.tsx
#: src/components/settings/EmbeddingsKeySection.tsx
-#: src/components/TemplateEditDialog.tsx
#: src/editor/components/CodePreviewEditModal.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
@@ -4998,7 +5268,6 @@ msgid "Saves the file to <0>~/Downloads/openknowledge.skill</0> and opens the Cl
msgstr "Saves the file to <0>~/Downloads/openknowledge.skill</0> and opens the Claude Desktop App. Requires Node.js or Bun on your PATH."
#: src/components/settings/EmbeddingsKeySection.tsx
-#: src/components/TemplateEditDialog.tsx
msgid "Saving"
msgstr "Saving"
@@ -5006,6 +5275,10 @@ msgstr "Saving"
msgid "Scaffold directly under this project."
msgstr "Scaffold directly under this project."
+#: src/components/NewSkillDialog.tsx
+msgid "Scope"
+msgstr "Scope"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Scope: "
msgstr "Scope: "
@@ -5285,6 +5558,10 @@ 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/PublishToGitHubDialog.tsx
msgid "Sharing a doc needs a GitHub repository. Create one for this project."
msgstr "Sharing a doc needs a GitHub repository. Create one for this project."
@@ -5394,6 +5671,38 @@ msgstr "Sign-in stream ended without confirmation — please try again"
msgid "Single page"
msgstr "Single page"
+#. placeholder {0}: skill.name
+#: src/components/SkillDeleteDialog.tsx
+msgid "skill \"{0}\""
+msgstr "skill \"{0}\""
+
+#. placeholder {0}: target.name
+#: src/components/SkillDeleteDialog.tsx
+msgid "Skill \"{0}\" deleted"
+msgstr "Skill \"{0}\" deleted"
+
+#: src/components/NewSkillDialog.tsx
+msgid "Skill \"{trimmedName}\" created"
+msgstr "Skill \"{trimmedName}\" created"
+
+#: src/components/SkillProperties.tsx
+msgid "Skill level"
+msgstr "Skill level"
+
+#: src/components/ManagedArtifactProperties.tsx
+msgid "Skill renamed"
+msgstr "Skill renamed"
+
+#: src/components/settings/SettingsDialogShell.tsx
+#: src/components/settings/SkillsManagerSection.tsx
+#: src/components/SkillsSidebarSection.tsx
+msgid "Skills"
+msgstr "Skills"
+
+#: 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."
+
#. Secondary button — dismisses the dialog without wiring any tools
#: src/components/AuthModal.tsx
#: src/components/McpConsentDialogBody.tsx
@@ -5420,7 +5729,7 @@ msgstr "Something went wrong loading the settings panel."
msgid "Something went wrong opening \"{docName}\"."
msgstr "Something went wrong opening \"{docName}\"."
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "Something went wrong opening this file (HTTP {status})."
msgstr "Something went wrong opening this file (HTTP {status})."
@@ -5444,7 +5753,7 @@ msgstr "Source editor search panel"
msgid "Source find results"
msgstr "Source find results"
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Source mode requires a live connection — your edits are saved and will appear when you reconnect."
msgstr "Source mode requires a live connection — your edits are saved and will appear when you reconnect."
@@ -5679,14 +5988,14 @@ 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."
+
#: src/components/CreateProjectDialog.tsx
msgid "Team Wiki"
msgstr "Team Wiki"
-#: src/components/TemplateEditDialog.tsx
-msgid "Template"
-msgstr "Template"
-
#: src/components/TemplateDeleteDialog.tsx
msgid "Template \"{label}\" deleted"
msgstr "Template \"{label}\" deleted"
@@ -5703,6 +6012,7 @@ msgstr "Template \"{trimmedTitle}\" created"
msgid "Template list"
msgstr "Template list"
+#: src/components/ManagedArtifactProperties.tsx
#: src/components/TemplateForm.tsx
msgid "Template renamed"
msgstr "Template renamed"
@@ -5792,6 +6102,11 @@ msgstr "The file is in your Trash; the file-watcher will reconcile."
msgid "The file on disk, and the id agents use. It can't be changed later."
msgstr "The file on disk, and the id agents use. It can't be changed later."
+#: 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."
+
#: src/components/SeedDialog.tsx
msgid "The folders and templates are in place; there's nothing left to scaffold."
msgstr "The folders and templates are in place; there's nothing left to scaffold."
@@ -5800,6 +6115,15 @@ msgstr "The folders and templates are in place; there's nothing left to scaffold
msgid "The formula <0>c = √(a² + b²)</0> renders inline."
msgstr "The formula <0>c = √(a² + b²)</0> renders inline."
+#: src/components/TemplateProperties.tsx
+msgid "The menu label agents pick this template by (required)."
+msgstr "The menu label agents pick this template by (required)."
+
+#. placeholder {0}: phase.plan.packSkill.name
+#: src/components/SeedDialog.tsx
+msgid "The pack skill <0>{0}</0> will be (re)installed."
+msgstr "The pack skill <0>{0}</0> will be (re)installed."
+
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
msgstr "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
@@ -5816,6 +6140,10 @@ msgstr "The repository is private and your GitHub account doesn't have access to
msgid "The repository was moved, renamed, or deleted."
msgstr "The repository was moved, renamed, or deleted."
+#: src/components/TemplateProperties.tsx
+msgid "The template's filename (without `.md`)."
+msgstr "The template's filename (without `.md`)."
+
#: src/components/TerminalGate.tsx
msgid "The terminal is turned off for this project. Turn it back on to run commands here."
msgstr "The terminal is turned off for this project. Turn it back on to run commands here."
@@ -5866,15 +6194,19 @@ msgstr "This branch is checked out in:"
msgid "This document is already active in the editor. Use Open to collapse the graph."
msgstr "This document is already active in the editor. Use Open to collapse the graph."
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "This file can't be opened in the text editor."
msgstr "This file can't be opened in the text editor."
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "This file could not be found."
msgstr "This file could not be found."
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
+msgid "This file is binary and can't be shown as text."
+msgstr "This file is binary and can't be shown as text."
+
+#: src/components/use-viewer-text.ts
msgid "This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."
msgstr "This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."
@@ -5906,6 +6238,11 @@ msgstr "This page doesn't link to anything yet."
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
+#. placeholder {0}: skill.path
+#: src/components/SkillDeleteDialog.tsx
+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."
+
#: 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."
@@ -5943,6 +6280,17 @@ msgstr "This project's running server doesn't support live editing. Restart Open
msgid "This project's server (v{0}) is newer than this app (v{1})."
msgstr "This project's server (v{0}) is newer than this app (v{1})."
+#. 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}: 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/settings/SearchSection.tsx
msgid "This sends content off your machine"
msgstr "This sends content off your machine"
@@ -5968,6 +6316,10 @@ msgstr "This will replace the current document content with the version from <0>
msgid "Timeline"
msgstr "Timeline"
+#: src/components/TemplateProperties.tsx
+msgid "title"
+msgstr "title"
+
#: src/components/TemplateForm.tsx
#: src/editor/extensions/CodeBlockView.tsx
msgid "Title"
@@ -6160,6 +6512,20 @@ msgstr "Undone all edits on {docName}"
msgid "Unified diff"
msgstr "Unified diff"
+#: src/components/skill-actions.tsx
+msgid "Uninstall"
+msgstr "Uninstall"
+
+#: src/components/SkillEditorActions.tsx
+msgid "Uninstall everywhere"
+msgstr "Uninstall everywhere"
+
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(removed)
+#: src/components/skill-actions.tsx
+msgid "Uninstalled \"{0}\" from {1}"
+msgstr "Uninstalled \"{0}\" from {1}"
+
#: src/components/FolderTimelineCard.tsx
msgid "Unknown"
msgstr "Unknown"
@@ -6196,14 +6562,57 @@ msgstr "Unrecognized link"
msgid "Unrecognized wiki link"
msgstr "Unrecognized wiki link"
+#: src/components/SkillUpdateDialog.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"
+
+#. placeholder {0}: skill.bundledVersion ? ` (${skill.bundledVersion})` : ''
+#: src/components/SkillsSidebarSection.tsx
+msgid "Update available{0}"
+msgstr "Update available{0}"
+
+#: src/components/skill-actions.tsx
+msgid "Update skill"
+msgstr "Update skill"
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "Update the destination and optional section anchor."
msgstr "Update the destination and optional section anchor."
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(added)
+#. placeholder {2}: label(removed)
+#: src/components/skill-actions.tsx
+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}."
+
#: src/components/FolderTimelineCard.tsx
msgid "updated folder properties"
msgstr "updated folder properties"
+#: src/components/SkillUpdateDialog.tsx
+msgid "Updating"
+msgstr "Updating"
+
#: src/components/PageHeaderWidgets.tsx
msgid "Upload {keyName}"
msgstr "Upload {keyName}"
@@ -6260,10 +6669,23 @@ msgstr "Use a starter pack"
msgid "Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."
msgstr "Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."
+#: src/components/TemplateProperties.tsx
+msgid "Use letters, digits, <0>_</0> and <1>-</1> only."
+msgstr "Use letters, digits, <0>_</0> and <1>-</1> only."
+
#: src/components/TemplateForm.tsx
msgid "Use letters, digits, <0>-</0> or <1>_</1> only."
msgstr "Use letters, digits, <0>-</0> or <1>_</1> only."
+#: src/components/SkillProperties.tsx
+#: src/components/SkillRenameDialog.tsx
+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."
+
#: src/components/settings/SettingsDialogShell.tsx
msgid "User"
msgstr "User"
@@ -6289,11 +6711,11 @@ msgstr "View as text"
msgid "Visibility"
msgstr "Visibility"
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Visual"
msgstr "Visual"
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Visual editor"
msgstr "Visual editor"
@@ -6342,6 +6764,10 @@ msgstr "We'll build <0>openknowledge.skill</0>, save it to <1>~/Downloads</1>, a
msgid "We'll create a repository and start syncing — no terminal needed."
msgstr "We'll create a repository and start syncing — no terminal needed."
+#: 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"
@@ -6404,6 +6830,7 @@ msgid "Word wrap"
msgstr "Word wrap"
#: src/components/McpConsentDialogBody.tsx
+#: src/components/SkillEditorActions.tsx
msgid "Working"
msgstr "Working"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 1c966489b..ef6e4c031 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -25,6 +25,7 @@
"-q4abP": [
"Ŕēśũĺţś ćàƥƥēď — ţĥĩś ŵōŕķśƥàćē ĥàś ḿōŕē ƒĩĺēś ţĥàń śēàŕćĥ ćàń ĩńďēx. À ḿĩśśĩńĝ ƒĩĺē ḿàŷ ƀē à ćàƥ àŕţĩƒàćţ, ńōţ à ţŷƥō."
],
+ "-r_Kx7": ["Ćŕēàţē śķĩĺĺ"],
"-slrNR": ["Ţōĝĝĺē à ţàśķ ĺĩśţ."],
"-wePNM": [
"Śēàŕćĥ ḿàţćĥēś ƒĩĺē ńàḿēś, ƥàţĥś, àńď ƒōĺďēŕś. Ōƥēń à ƒĩĺē ţō śēàŕćĥ ĩţś ƀōďŷ (⌘Ƒ)."
@@ -35,12 +36,14 @@
"04RA0-": ["Ƒàĩĺēď ţō ēńàƀĺē śŷńć — ", ["detail"]],
"05n5wS": ["Ďōć ḿēńţĩōń śũĝĝēśţĩōńś"],
"06SZfb": ["Ţēḿƥĺàţē \"", ["trimmedTitle"], "\" ćŕēàţēď"],
+ "07eGJB": ["Ćōũĺďń'ţ ḿōvē śķĩĺĺ: ", ["0"]],
"07gHun": ["Ŷōũ ďōń'ţ ĥàvē àććēśś ţō ţĥĩś ƥŕĩvàţē ŕēƥō. Śĩĝń ĩń ŵĩţĥ àń àććōũńţ ţĥàţ ďōēś."],
"07q4Qk": ["Ƒĩĺē śĩďēƀàŕ"],
"09Tv5j": ["Ŕēćōńńēćţĩńĝ…"],
"0BB9ID": ["Ńō ĥēàďĩńĝś ŷēţ."],
"0E9DR6": ["Ţŷƥē ţō ƒĩńď à ďōć"],
"0Gd0NU": ["Śĥàŕēď"],
+ "0LBDjY": ["\"", ["0"], "\" ũńĩńśţàĺĺēď — ƀàćķ ţō à ďŕàƒţ"],
"0NA4b3": ["Ķēēƥ ḿŷ vēŕśĩōń"],
"0YEbfk": ["Ćōńńēćţ ţō ÀĨ ţōōĺś"],
"0_J12R": [
@@ -52,6 +55,7 @@
["targetLabel"]
],
"0eHrMb": ["Ćōũĺď ńōţ ćōḿƥĺēţē ďēĺēţē"],
+ "0g7rCZ": ["Ďũƥĺĩćàţēď ţō \"", ["0"], "\""],
"0jD-Gn": ["À ţēàḿ ķńōŵĺēďĝē ƀàśē, à ƥēŕśōńàĺ ŵĩķĩ, ƥŕōĴēćţ ďōćś..."],
"0kTAXe": ["Ōƥēń śōũŕćē: ", ["mirrorSrc"]],
"0njBIq": [
@@ -78,14 +82,15 @@
"1RluQD": ["Śĥōŵ ŕēƥĺàćē"],
"1TNIig": ["Ōƥēń"],
"1Ta7Fd": ["Ōƥēń ", ["basename"]],
- "1WgmEM": ["Ƒàĩĺēď ţō ĺōàď ţēḿƥĺàţē: ", ["errorMessage"]],
"1XSMhZ": [
"Śŵĩţćĥĩńĝ ţō <0>ĺōćàĺ-ōńĺŷ</0> ŵĩĺĺ ŕēƒũśē ũńţĩĺ ţĥēŷ'ŕē ũńţŕàćķēď vĩà<1> ĝĩţ ŕḿ --ćàćĥēď</1>."
],
+ "1YJ4Yg": ["Ũƥďàţē àvàĩĺàƀĺē", ["0"]],
"1ZpfyB": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"], ", ", ["hint"]],
"1bDVu5": ["Ŵōŕķśƥàćē Ćōḿḿàńď Ƥàĺēţţē"],
"1d1F11": ["Śēĺēćţ àĺĺ ƒĩĺēś àńď ƒōĺďēŕś"],
"1di5fu": ["Ďōćũḿēńţ ńōţ ƒōũńď"],
+ "1hvhf0": ["Ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ţĥĩś śķĩĺĺ."],
"1nke1r": ["Ōƥēń ", ["0"], " ōń ĜĩţĤũƀ (ōƥēńś ĩń à ńēŵ ţàƀ)"],
"1t_NnN": ["ŔēĴēćţ"],
"2277Tu": ["Ćōĺĺàƥśē ĝŕàƥĥ"],
@@ -103,6 +108,7 @@
"2YOwme": ["Ŕēśţàŕţēď — ńōŵ ŕũńńĩńĝ v", ["appRuntime"], "."],
"2YZwPB": ["Ƒōŕŵàŕď-ĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
"2Znqb1": [" (ḿĩśśĩńĝ)"],
+ "2bVHbB": ["Àvàĩĺàƀĺē ĩń ēvēŕŷ ƥŕōĴēćţ ōń ţĥĩś ćōḿƥũţēŕ."],
"2fkdnR": ["Ńōţĥĩńĝ ţō ũńďō ōń ţĥĩś ƒĩĺē"],
"2hpdRq": ["Ĥĩďē ƥàńēĺ (", ["panelShortcutLabel"], ")"],
"2n3oDU": [
@@ -124,6 +130,7 @@
"3Fcb0I": ["Ōƥēń ĝŕàƥĥ"],
"3HNlwb": ["Ĥēĺĺō, ŵōŕĺď!"],
"3Ib6FN": ["Ḿōvē ďōŵń"],
+ "3Ijjy1": ["Ćōũĺďń'ţ ĺōàď ţĥĩś śķĩĺĺ'ś ƒĩĺēś."],
"3IseAk": ["Ĩńśţàĺĺ àń ÀĨ àĝēńţ ţō ćŕēàţē ŵĩţĥ ÀĨ"],
"3J7d2N": ["ßĩĝ śēćţĩōń ĥēàďĩńĝ."],
"3JYy1p": ["ßŕàńćĥ ", ["0"], " ńō ĺōńĝēŕ ēxĩśţś. Ćĺōńēď ţō ďēƒàũĺţ ƀŕàńćĥ."],
@@ -157,6 +164,13 @@
"Àĺŕēàďŷ ĥàvē à ĝĩţ ŕēƥōśĩţōŕŷ? Àďď ĩţ ŵĩţĥ <0>ĝĩţ ŕēḿōţē àďď ōŕĩĝĩń <url></0> ĩń ţĥĩś ƥŕōĴēćţ'ś ƒōĺďēŕ. Ţĥĩś ƥàĝē ũƥďàţēś àũţōḿàţĩćàĺĺŷ ōńćē à ŕēḿōţē ĩś ďēţēćţēď."
],
"45MZFs": ["Ćōḿḿàńďś"],
+ "47EXvY": [
+ "Ţĥĩś ŕēƥĺàćēś ţĥē ćũŕŕēńţ śķĩĺĺ ćōńţēńţ ŵĩţĥ ţĥē ƀũńďĺēď vēŕśĩōń ",
+ ["0"],
+ " (ŷōũ ĥàvē ",
+ ["1"],
+ "). Àńŷ ĺōćàĺ ēďĩţś ŵĩĺĺ ƀē ŕēƥĺàćēď — ŷōũŕ ćũŕŕēńţ vēŕśĩōń ĩś śàvēď ţō ĥĩśţōŕŷ ƒĩŕśţ, śō ŷōũ ćàń ŕēśţōŕē ĩţ."
+ ],
"484LKL": ["Ŕēḿōvē ĺĩńķ"],
"48uGTI": ["Ƒàĩĺēď ţō ĺōàď ďōćś. Ƥŕēśś Ēśćàƥē àńď ŕē-ōƥēń ţō ŕēţŕŷ."],
"4A3Yzu": ["Ćōďē ƀĺōćķ"],
@@ -168,6 +182,9 @@
"4PYsOz": ["Ĥĩďē Ƒĩĺēś (", ["sidebarShortcutLabel"], ")"],
"4Sxexw": ["Śōũŕćē ũńďō ōŕ ŕēďō"],
"4TzU0n": ["Ĩńĩţĩàĺĩźē"],
+ "4XL6N4": [
+ "Ďēţēćţēď ƒŕōḿ ţĥē ēďĩţōŕś ţĥĩś ƥŕōĴēćţ ĩś śēţ ũƥ ƒōŕ. ÀďĴũśţ ţō ćōńţŕōĺ ŵĥēŕē ēvēŕŷ śķĩĺĺ ĩńśţàĺĺś."
+ ],
"4buZWd": ["Ĩńĥēŕĩţēď ƒŕōḿ ", ["path"]],
"4c_a6S": ["Ńōţĥĩńĝ śēţ ŷēţ."],
"4g19V6": ["Ƒàĩĺēď ţō ũƥďàţē ƥŕōƥēŕţŷ"],
@@ -210,6 +227,7 @@
"5Tk8Fb": ["Ĺōàďĩńĝ ƒĩĺēś"],
"5WDhAk": ["Ĺĩńķ ţō à ƥàĝē ōŕ ēxţēŕńàĺ ŨŔĹ."],
"5ZB7XC": ["Ƒĩĺē ďŕōƥ źōńē"],
+ "5e1Dri": ["Ţĥē ḿēńũ ĺàƀēĺ àĝēńţś ƥĩćķ ţĥĩś ţēḿƥĺàţē ƀŷ (ŕēǫũĩŕēď)."],
"5gr_ev": [
"ßēćōḿēś ţĥē ďōćũḿēńţ'ś ćōńţēńţ ŵĥēń śōḿēōńē ćŕēàţēś à ďōć ƒŕōḿ ţĥĩś ţēḿƥĺàţē. Ţŷƥē <0>",
["dateToken"],
@@ -242,6 +260,7 @@
"636K3K": ["Ďēĺēţē àďĴàćēńţ ćĥĩƥ"],
"67f-3g": ["Ďũƥĺĩćàţē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"6Aih4U": ["Ōƒƒĺĩńē"],
+ "6EKG_c": ["Ŵĥàţ àĝēńţś ḿàţćĥ ōń ţō ďēćĩďē ŵĥēń ţō ũśē ţĥē śķĩĺĺ."],
"6LbUG7": ["Ţĥē ŕēƥōśĩţōŕŷ ĩś ƥŕĩvàţē àńď ŷōũŕ ĜĩţĤũƀ àććōũńţ ďōēśń'ţ ĥàvē àććēśś ţō ĩţ."],
"6MnZEC": ["Ţēŕḿĩńàĺ ƒàĩĺēď ţō ĺōàď"],
"6O626z": ["Ńō ĥēàďĩńĝś ḿàţćĥ \"", ["trimmedAnchorQuery"], "\""],
@@ -261,6 +280,7 @@
"6cyguR": ["Ćōńńēćţ ĜĩţĤũƀ ţō ćōńţĩńũē."],
"6eniID": ["Ḿàƥ ţĥē àŕćĥĩţēćţũŕē"],
"6fGjTz": ["Śĥōŵ ƒēŵēŕ"],
+ "6g2jsp": ["Ũƥďàţē śķĩĺĺ"],
"6gRgw8": ["Ŕēţŕŷ"],
"6h4zVU": ["Ŵĥàţ ŵōũĺď ŷōũ ĺĩķē ţō ćŕēàţē?"],
"6hfDJr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"]],
@@ -379,6 +399,7 @@
"9tJX8r": ["ßŷ ḿēàńĩńĝ"],
"9zb2WA": ["Ćōńńēćţĩńĝ"],
"A1taO8": ["Śēàŕćĥ"],
+ "A50vr3": ["Ũśē ĺōŵēŕćàśē ĺēţţēŕś, ďĩĝĩţś, àńď <0>-</0> ōńĺŷ."],
"A5CYnd": ["ßŕōķēń ĺĩńķ"],
"A5hiCy": ["Ćŕēàţē ţēḿƥĺàţē"],
"A67Uwj": ["Śţĩĺĺ ĺōàďĩńĝ"],
@@ -409,8 +430,10 @@
"Aq-O0x": ["śţàţũś"],
"AqnqMJ": ["ÀƤĨ ķēŷ śēţ"],
"ArBWJf": ["Ũńďō ĺàśţ ēďĩţ"],
+ "AtBdnD": ["Ćōũĺďń'ţ ďēĺēţē śķĩĺĺ: ", ["error"]],
"B11p-O": ["Ēďĩţ ḿàŕķďōŵń ĺĩńķ"],
"B2DrPb": ["Àũţō-śàvē"],
+ "B2Srgd": [["packName"], " śķĩĺĺ ĩńśţàĺĺēď."],
"B3NAZC": ["Ōƥēń Ńàvĩĝàţōŕ"],
"B4_ipX": [
[
@@ -445,6 +468,7 @@
"BymzO4": ["Ďōćũḿēńţ ōũţĺĩńē"],
"C37Zkt": ["Śēńď ţō"],
"C62P6b": ["Ēďĩţōŕ śēĺēćţĩōń"],
+ "C7XjNB": ["Ĝĺōƀàĺ Śķĩĺĺ"],
"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],
"CCTop_": ["Ŕēćēńţ"],
"CKyk7Q": ["Ĝō ƀàćķ"],
@@ -460,6 +484,7 @@
],
"C_cPoW": ["Ŷōũŕ ĜĩţĤũƀ śēśśĩōń ēxƥĩŕēď — śĩĝń ĩń àĝàĩń ţō vēŕĩƒŷ ƥũśĥ àććēśś."],
"ChAtFg": ["Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
+ "CifUuG": ["Ũƥďàţē àvàĩĺàƀĺē"],
"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],
"CvsD6Y": ["vĩà ", ["viaTags"]],
@@ -475,6 +500,15 @@
"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],
"DbILZA": ["Ńō ḿàţćĥēś. Śōḿē ƒĩĺēś àŕē ēxćĺũďēď ƒŕōḿ śēàŕćĥ (ĥĩďďēń ōŕ ĩĝńōŕēď ƒĩĺēś)."],
"DeDYLr": ["Ũńŕēćōĝńĩźēď ŵĩķĩ ĺĩńķ"],
+ "DhK_hZ": [
+ "Ḿōvēď \"",
+ ["name"],
+ "\" ţō ",
+ ["0"],
+ " (",
+ ["skipped"],
+ " ƀĩńàŕŷ ƒĩĺē(ś) ńōţ ćōƥĩēď)"
+ ],
"DhLHEb": ["Ƒàĩĺēď ţō ĺōàď àćţĩvĩţŷ"],
"DiFKSL": ["Ćōũńţĩńĝ ḿàŕķďōŵń ƒĩĺēś"],
"Dnn2XG": ["Àũţōḿàţĩć"],
@@ -484,6 +518,11 @@
"Ƥŕēvĩēŵ ƀŕōŵśēŕś ćàń'ţ àũţō-ćōƥŷ. Ũśē Ćḿď/Ćţŕĺ+Ć ōń ţĥē ŨŔĹ àƀōvē, ōŕ ōƥēń ŌĶ ĩń ţĥē ďēśķţōƥ àƥƥ."
],
"Dw1T_W": ["Ŕēńàḿē ", ["label"]],
+ "E1Da_b": [
+ "Ţĥĩś ƥēŕḿàńēńţĺŷ ŕēḿōvēś ",
+ ["0"],
+ ". Àĝēńţś ţĥàţ ĩńvōķē ţĥĩś śķĩĺĺ ƀŷ ńàḿē ŵĩĺĺ ƒàĩĺ ũńţĩĺ ĩţ'ś ŕēćŕēàţēď."
+ ],
"E1_c72": ["Ţàśķ ĺĩśţ"],
"E1tG2u": ["Ĝēţ Ćĺàũďē Ćōďē"],
"E2Mv-X": ["Ćōƥŷ śōũŕćē"],
@@ -509,6 +548,7 @@
"\" ţō ţĥē Ţŕàśĥ. Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"
],
"E_tNGD": ["Ćōńńēćţēď àś @", ["login"]],
+ "Ea1prf": ["Ćĥōōśē ŵĥĩćĥ ēďĩţōŕś ēvēŕŷ śķĩĺĺ ĩń ţĥĩś ƥŕōĴēćţ ĩńśţàĺĺś ĩńţō."],
"EarrCe": ["Śēàŕćĥ ēḿōĴĩ"],
"EbZT7P": ["Ţōĝĝĺē ţĥē ĺēƒţ ƒĩĺē śĩďēƀàŕ."],
"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],
@@ -520,6 +560,7 @@
"Ehkru0": ["Ōƥēń, ńàvĩĝàţē, àććēƥţ, ōŕ ďĩśḿĩśś ĆōďēḾĩŕŕōŕ ćōḿƥĺēţĩōń śũĝĝēśţĩōńś."],
"EiVgl5": ["Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō."],
"Eji13z": ["Ţōĝĝĺē ĥĩĝĥĺĩĝĥţ ƒōŕḿàţţĩńĝ."],
+ "EkH9pt": ["Ũƥďàţē"],
"El7NbA": ["Ĥēàďĩńĝ 2"],
"Emz5BG": [
"Ēḿƀēďďĩńĝś àŕē ćōḿƥũţēď ōńĺŷ ŵĥēń à śēàŕćĥ ŕũńś àńď àŕē ćàćĥēď ĺōćàĺĺŷ ũńďēŕ <0>.ōķ/ĺōćàĺ</0>."
@@ -532,6 +573,7 @@
"EvPX7f": ["Ōƥēńś à ƒōĺďēŕ ƥĩćķēŕ ţō ćĥōōśē ŵĥēŕē ţō ćĺōńē ţĥē ŕēƥōśĩţōŕŷ."],
"Evq3lu": ["Ōŕƥĥàń ḿōďē"],
"ExPiRQ": ["Ḿōvē ţō ţĥē ńēxţ ĆōďēḾĩŕŕōŕ ĺĩńţ ďĩàĝńōśţĩć."],
+ "ExUzM4": ["śķĩĺĺ \"", ["0"], "\""],
"F-NRCj": ["Àďď ƥŕōƥēŕţŷ"],
"F-vBv0": ["Àśķ"],
"F0OA00": ["Ĝēţ ", ["displayName"]],
@@ -556,6 +598,7 @@
"Ŷōũŕ ŌƥēńÀĨ ÀƤĨ ķēŷ, ũśēď ōńĺŷ ţō ćŕēàţē ēḿƀēďďĩńĝś ōƒ ŷōũŕ ćōńţēńţ ƒōŕ śēḿàńţĩć śēàŕćĥ. Śţōŕēď ōńćē ƒōŕ ţĥĩś ḿàćĥĩńē ĩń <0>~/.ōķ/śēćŕēţś.ŷḿĺ</0> (ŕēàďàƀĺē ōńĺŷ ƀŷ ŷōũŕ ũśēŕ àććōũńţ) àńď śĥàŕēď àćŕōśś àĺĺ ƥŕōĴēćţś. Ţũŕń ţĥē ƒēàţũŕē ōń ƥēŕ ƥŕōĴēćţ ĩń Ţĥĩś ƥŕōĴēćţ → Śēàŕćĥ."
],
"FRYB1Q": ["/àƥĩ/ćōńƒĩĝ ŕēţũŕńēď à ḿàĺƒōŕḿēď ƀōďŷ"],
+ "FRqZ9v": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺ: ", ["0"]],
"FTUGgh": ["Ēńţēŕ à ŕēƥōśĩţōŕŷ ŨŔĹ ōŕ ōŵńēŕ/ŕēƥō"],
"FUMerq": ["Ćōũĺď ńōţ ēńàƀĺē śŷńć: ", ["detail"]],
"FWQuPE": [
@@ -600,6 +643,7 @@
"GUqTzn": ["Ćōḿƥēţĩţōŕ ŕēśēàŕćĥ"],
"GXf9hG": ["Ćĺōńĩńĝ ", ["repoName"], "..."],
"G_686w": ["Ţàśķ Ĺĩśţ"],
+ "G_efLf": ["Ĩńśţàĺĺēď ĩńţō"],
"G_mWXb": ["Ƒĩĺţēŕ ĺàńĝũàĝēś"],
"GamjcN": ["Ţēḿƥĺàţē śàvēď"],
"GemPfn": ["Ƒàĩĺēď ţō ƥàŕśē ƒōŕŵàŕď-ĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],
@@ -631,6 +675,7 @@
"ŌƥēńĶńōŵĺēďĝē śţōŕēś ĩţś ćōńƒĩĝũŕàţĩōń àńď ĩńţēŕńàĺ ƒĩĺēś ĩńśĩďē à ńēŵĺŷ ćŕēàţēď <0>.ōķ</0> ďĩŕēćţōŕŷ ĩń ŷōũŕ ƥŕōĴēćţ ŕōōţ ƒōĺďēŕ."
],
"Hrz9NY": ["Ŵĩķĩ ĺĩńķ"],
+ "HyvSqq": ["ƤŕōĴēćţ Śķĩĺĺ"],
"I1gRhX": ["Ƒàĩĺēď ţō ŕēńàḿē"],
"I5AfhE": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ũńŕēàćĥàƀĺē."],
"IA1wNb": ["Ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ďĩďń'ţ ōƥēń ţĥē ƒĩĺē. Ĩś ĩţ ĩńśţàĺĺēď? (", ["msg"], ")"],
@@ -667,6 +712,7 @@
],
"JE21eh": ["Śŷḿĺĩńķ ţō ", ["targetPath"]],
"JK-Ave": ["Ĥĩďē ţĥũḿƀńàĩĺś"],
+ "JL3si7": ["Ũƥďàţĩńĝ"],
"JLUTgi": ["Ńō ţàĝś ŷēţ — àũţĥōŕ `#ţàĝńàḿē` ĩń àńŷ ďōć ţō ƥōƥũĺàţē ţĥē ĩńďēx."],
"JLzQi_": ["Ćĺōśē ", ["accessibleLabel"]],
"JOcPqH": ["ßŕĩńĝ à ŕēḿōţē ŕēƥōśĩţōŕŷ ōńţō ţĥĩś ḿàćĥĩńē."],
@@ -720,6 +766,7 @@
"KmydK6": ["ßōĺď"],
"KnoB--": ["Ŵĩĺĺ ƀē śàvēď àś <0>", ["sanitized"], "</0>."],
"KsAPaB": ["Ţĥĩś ƀŕàńćĥ ĩś ćĥēćķēď ōũţ ĩń:"],
+ "KszKI_": ["Śķĩĺĺ ĺēvēĺ"],
"KujtjC": ["Ƒĩńď"],
"L-rMC9": ["Ŕēśēţ ţō ďēƒàũĺţ"],
"L1ZE3M": ["Ďōćũḿēńţ śţàţĩśţĩćś"],
@@ -792,11 +839,21 @@
"MZoxVx": ["Ƒàĩĺēď ţō ĺōàď ţàĝś. Ƥŕēśś Ēśćàƥē àńď ŕē-ōƥēń ţō ŕēţŕŷ."],
"Mb_20S": ["Vĩśũàĺ"],
"Md709y": ["Ĺōàďĩńĝ ", ["fileName"]],
+ "MdpSC1": ["Ńēŵ śķĩĺĺ"],
+ "Mj8R8K": ["Ćōũĺďń'ţ ĩńśţàĺĺ śķĩĺĺ: ", ["0"]],
"MmDDWK": ["Ŕēćēńţĺŷ ōƥēńēď"],
+ "MmqnGI": ["Ńō ĝĺōƀàĺ śķĩĺĺś ŷēţ."],
"Mnavhe": [["propPanelDescriptorLabel"], " Ƥŕōƥēŕţĩēś"],
"MqQoV-": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ ŵàńţ ţō ƀũĩĺď, śţàŕţ à ƀĺàńķ ƒĩĺē, ōŕ śćàƒƒōĺď ƒŕōḿ à ţēḿƥĺàţē."],
"MrwYIK": ["Ţōĝĝĺē à śōũŕćē ćōḿḿēńţ ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ."],
"MsuXaI": ["Ĥĩďē ƥàńēĺ (", ["panelShortcut"], ")"],
+ "My9uXI": [
+ "Ũƥďàţēď \"",
+ ["display"],
+ "\" ţō ",
+ ["0"],
+ " — ŷōũŕ ƥŕēvĩōũś vēŕśĩōń ĩś ĩń ĥĩśţōŕŷ ĩƒ ŷōũ ńēēď ţō ŕēśţōŕē ĩţ."
+ ],
"N1YYa7": ["Ĺōàďĩńĝ ĩḿàĝē"],
"N1mdmS": ["Ţĥĩś ƒĩĺē ćàń'ţ ƀē ōƥēńēď ĩń ţĥē ţēxţ ēďĩţōŕ."],
"N2FcBE": ["Śŷńćēď"],
@@ -838,15 +895,16 @@
"O6yEPk": ["Ćŕēàţē à ńēŵ ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ĩń ţĥē ƒōĺďēŕ ōƒ ŷōũŕ ćĥōĩćē."],
"O7_W_a": ["Ōƥēń ŵĩţĥ ÀĨ"],
"OD0FCX": ["Ĥĩďďēń “", ["basename"], "”"],
- "ODD5Jc": ["Ēďĩţ ", ["templateLabel"]],
"ODGGlj": ["Ƒōĺďēŕ ńàḿē: ", ["detail"]],
"OETysD": ["Ńō ĥũƀ ƥàĝēś ŷēţ. Ĥũƀś àƥƥēàŕ ōńćē ƥàĝēś àććũḿũĺàţē ĩńƀōũńď ĝŕàƥĥ ĺĩńķś."],
+ "OEu_0l": ["Ƒàĩĺēď ţō ĺōàď śķĩĺĺś: ", ["0"]],
"OJTOUj": ["Ŕēǫũĩŕēś ", ["brand"], "."],
"OJeiSH": ["Ƒàĩĺēď ţō àďď ƥŕōƥēŕţŷ"],
"OLBz-_": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ƒàĩĺēď ţō ŕēńďēŕ."],
"OLIKgw": ["Ďŕàĝ ĩţēḿ ", ["0"], " ţō ŕēōŕďēŕ"],
"ONPvOb": ["Ĺōàďĩńĝ àĝēńţ àćţĩvĩţŷ"],
"ONgEZF": ["Ĺōàďĩńĝ ĥēàďĩńĝś ƒōŕ ", ["pageTarget"]],
+ "OOIVJo": ["Ũńĩńśţàĺĺēď \"", ["0"], "\" ƒŕōḿ ", ["1"]],
"OTF92M": ["Ĺàƀēĺ <0>(ōƥţĩōńàĺ ďĩśƥĺàŷ ţēxţ)</0>"],
"OVjNeX": ["Ţēŕḿĩńàĺ ", ["0"]],
"OX2Neh": ["Ĩńĺĩńē ćōďē"],
@@ -863,6 +921,7 @@
"Oos8fo": ["Ćōƥŷ ćōḿḿàńď"],
"OuY8t9": ["Ōƥēń ĩń ćũŕŕēńţ ƀŕàńćĥ"],
"OvEjsP": ["Ćōƥŷĩńĝ..."],
+ "OxplNM": ["Ũƥďàţēď \"", ["0"], "\": àďďēď ", ["1"], ", ŕēḿōvēď ", ["2"]],
"Oxyd5f": ["Ƥĩćķ à ńàḿē"],
"OyIC0Q": ["ƤŕōĴēćţ ńàḿē"],
"P-ye9o": ["Ćōũĺď ńōţ ōƥēń ƒōĺďēŕ ƥĩćķēŕ"],
@@ -875,13 +934,16 @@
"PB4upl": ["Ƒĩńď ƥŕēvĩōũś ḿàţćĥ"],
"PBwmDJ": ["Śēàŕćĥĩńĝ ƀŷ ḿēàńĩńĝ"],
"PBxg_E": ["Ńōţ ńōŵ"],
+ "PCSkw2": ["Śķĩĺĺś"],
"PKLY-1": ["Ōƥēńĩńĝ..."],
"PMyJ9C": ["Ńō ēďĩţ śēśśĩōń ŷēţ"],
+ "PPFQ3o": ["Ĩńśţàĺĺēď \"", ["0"], "\" ĩńţō ", ["1"]],
"PQCdtv": ["\"", ["docName"], "\" ďōēśń'ţ ēxĩśţ."],
"PR9FSv": ["Ḿōvē ţō ţĥē ńēxţ vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţ."],
"PVUn_c": ["Ōƥēń ƒōĺďēŕ"],
"PZt1uN": ["Śēàŕćĥ ƒĩĺēś, ćōḿḿàńďś, ƥŕōĴēćţś, àńď ÀĨ ĥàńďōƒƒ àćţĩōńś."],
"PdA9NZ": [["ahead"], " àĥēàď"],
+ "PdJZ5p": ["Ńō śķĩĺĺś ŷēţ."],
"Pgu10b": ["Śàvēď àś <0>", ["slug"], ".ḿď</0>"],
"PgzIpb": ["Ḿōvē ţō ţĥē ƥŕēvĩōũś vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţ."],
"PiH3UR": ["Ćōƥĩēď!"],
@@ -901,6 +963,7 @@
"QWks14": ["À śĥōŕţ ĺĩńē śĥōŵń ũńďēŕ ţĥē ńàḿē ĩń ţĥē ţēḿƥĺàţē ĺĩśţ."],
"QYfQdv": [["displayName"], " ĆĹĨ"],
"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],
+ "QfFBdJ": ["Ţĥē ţēḿƥĺàţē'ś ƒĩĺēńàḿē (ŵĩţĥōũţ `.ḿď`)."],
"QlxHAH": ["Śĥōŵĩńĝ ŕēśũĺţś ƒōŕ \"", ["semanticResultsLabel"], "\""],
"QqBQu1": ["Ĺàƀēĺ <0>(vĩśĩƀĺē ĺĩńķ ţēxţ)</0>"],
"Qvls7J": ["Ēńĝ śƥēćś"],
@@ -920,6 +983,7 @@
"R65q-K": [
"À ŕēàĺ śĥēĺĺ ĩś ōƒƒ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕńĩńĝ ĩţ ōń ŕũńś ćōḿḿàńďś ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ḿàćŌŚ ũśēŕ àććōũńţ."
],
+ "R9IDFz": ["Ŕēńàḿēś ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ĩţ."],
"RDjuBN": ["Śēţũƥ"],
"RDrXh4": ["Ćōńƒĩĝũŕē ũśēŕ, ƥŕōĴēćţ, àńď ĩńţēĝŕàţĩōń śēţţĩńĝś."],
"RG4XHV": ["Ćōƥŷ ", ["0"], " ƥŕōḿƥţ"],
@@ -930,6 +994,7 @@
"Ŵē'ĺĺ ƀũĩĺď <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0>, śàvē ĩţ ţō <1>~/Ďōŵńĺōàďś</1>, àńď ōƥēń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ƒōŕ ŷōũ."
],
"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],
+ "RXNu_r": ["Śĥàŕēď vĩà ĝĩţ ŵĩţĥ ēvēŕŷōńē ŵōŕķĩńĝ ōń ţĥĩś ƥŕōĴēćţ."],
"RY6Bq1": ["Ōƥēń śĥàŕēď ", ["targetNoun"]],
"RaPMZv": ["Ķēŷƀōàŕď śĥōŕţćũţś àvàĩĺàƀĺē ĩń ţĥē ēďĩţōŕ àńď ŵōŕķśƥàćē."],
"Rah7yq": ["Ŵĥàţ śĥōũĺď ţĥē ÀĨ ďō? (ōƥţĩōńàĺ)"],
@@ -938,6 +1003,7 @@
"RgbKEe": ["Ŷōũ ďōń'ţ ĥàvē àććēśś ţō ţĥĩś ŕēƥōśĩţōŕŷ."],
"Rj01Fz": ["Ĺĩńķś"],
"RlCInP": ["Śĺàśĥ ćōḿḿàńďś"],
+ "RlLl3G": ["Àćţĩōńś ƒōŕ ", ["0"]],
"RmBY0A": ["Ńō ĝĩţ ŕēḿōţē"],
"RobAKV": ["Ũƥďàţē ţĥē ďēśţĩńàţĩōń àńď ōƥţĩōńàĺ śēćţĩōń àńćĥōŕ."],
"Rq1vFD": ["Ţŕēē vĩēŵ ōƥţĩōńś"],
@@ -952,6 +1018,7 @@
"SFN6dN": ["Ĥēàďĩńĝ 3"],
"STTOnz": [["keyName"], " ţŷƥē: ćōḿƥĺēx vàĺũē (ńēśţēď; ŕēàď-ōńĺŷ)"],
"SUOoXn": ["Ƒàĩĺēď ţō ōƥēń ƥŕōĴēćţ."],
+ "SXCSQd": ["Ćōƥĩēď ƥàţĥ"],
"SYfHmN": ["Ũńƥĩń ţàƀ"],
"Sc1bKE": [
"Ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"",
@@ -963,6 +1030,7 @@
"SgKLfA": ["Ńōţ ćōńńēćţēď ţō ĜĩţĤũƀ."],
"SiUUCS": ["Ńēxţ ḿàţćĥ"],
"SkMZlS": ["Ćōũĺďń'ţ ŕēḿōvē <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
+ "Sq8lf2": ["Ēďĩţōŕś ţō ĩńśţàĺĺ śķĩĺĺś ĩńţō"],
"SrOuyg": ["Ďōćũḿēńţ ƥàńēĺś"],
"T-4cw2": [
"Ƥĩćķ à ĺàŷōũţ ţĥàţ ḿàţćĥēś ŵĥàţ ŷōũ'ŕē ƀũĩĺďĩńĝ. Ēàćĥ ƥàćķ śĥĩƥś ŵĩţĥ ƒōĺďēŕś, ţēḿƥĺàţēś, àńď àĝēńţ-ŕēàďàƀĺē ďēśćŕĩƥţĩōńś. Ŷōũ ćàń ḿĩx àńď ḿàţćĥ ĺàţēŕ."
@@ -992,7 +1060,10 @@
"UBv8UK": ["Ďēĺēţē Ƥēŕḿàńēńţĺŷ"],
"UDFrWm": ["Ćĥēćķĩńĝ ĜĩţĤũƀ ćōńńēćţĩōń..."],
"UL8A9w": ["Ţàĝ"],
+ "UMrOy2": ["Śķĩĺĺ \"", ["trimmedName"], "\" ćŕēàţēď"],
+ "UPjaXD": ["Ćōũĺďń'ţ ďũƥĺĩćàţē \"", ["0"], "\": ", ["1"]],
"UQAp48": ["Śēàŕćĥ ţēḿƥĺàţēś"],
+ "UQMMvx": ["Ḿōvēď \"", ["name"], "\" ţō ", ["0"]],
"URmyfc": ["Ďēţàĩĺś"],
"UTNVyS": ["Śēĺēćţ ţĥē ƒũĺĺ śōũŕćē ďōćũḿēńţ."],
"UTZ97u": ["Śēĺēćţĩōń ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],
@@ -1021,6 +1092,7 @@
"V48OUT": ["Ŷōũ ďēĺēţēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ḿōďĩƒĩēď ũƥśţŕēàḿ."],
"V7QxyT": ["Ćōńńēćţĩōń ďŕōƥƥēď"],
"VAHWL_": ["Ćōńńēćţēď àś <0>@", ["signedInLogin"], "</0>"],
+ "VM7H66": ["Ţĥĩś ƒĩĺē ĩś ƀĩńàŕŷ àńď ćàń'ţ ƀē śĥōŵń àś ţēxţ."],
"VNgKZz": ["Àďvàńćēď śēţţĩńĝś"],
"VU3Nrn": ["Ḿĩśśĩńĝ"],
"VUijjF": ["Ēḿƀēď àń ĩḿàĝē ŵĩţĥ ōƥţĩōńàĺ àĺţ ţēxţ."],
@@ -1093,6 +1165,7 @@
"Xet9MX": ["Ƒàĩĺēď ţō ĺōàď ƀàćķĺĩńķś"],
"XfzqjK": ["ţēḿƥĺàţē \"", ["name"], "\""],
"Xl-UUg": ["ĝũĩďēś/ĩńśţàĺĺ ōŕ ĥţţƥś://ēxàḿƥĺē.ćōḿ"],
+ "XmJfZT": ["ńàḿē"],
"XnlF3W": ["Àďď ţĥē ńēxţ ḿàţćĥĩńĝ śōũŕćē śēĺēćţĩōń."],
"XnoA1k": [
"Ţĥĩś ",
@@ -1103,6 +1176,7 @@
],
"XopE_I": ["Ƒàĩĺēď ţō ƥàŕśē ƀàćķĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],
"XpIZmv": ["Ƒēńćēď ćōďē ƀĺōćķ ŵĩţĥ ḿōńōśƥàćē ţēxţ."],
+ "XqNHcm": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺ ţàŕĝēţś: ", ["0"]],
"XtRoxT": ["Ƥàĝē ", ["pageNumber"]],
"XvPJaT": ["Ďĩƒƒ ĺàŷōũţ"],
"Xv_ijG": ["ĥţţƥś://ĝĩţĥũƀ.ćōḿ/ōŵńēŕ/ŕēƥō ōŕ ōŵńēŕ/ŕēƥō"],
@@ -1124,6 +1198,7 @@
"YGQm6y": [
"ŌƥēńĶńōŵĺēďĝē ḿàńàĝēś ţĥē <0>ōƥēń-ķńōŵĺēďĝē</0> ḾĆƤ śēŕvēŕ ńàḿē, ţĥē <1>ōƥēń-ķńōŵĺēďĝē-ũĩ</1> ĺàũńćĥ ćōńƒĩĝ, àńď <2>ōķ</2> / <3>ōƥēń-ķńōŵĺēďĝē</3> ōń ƤÀŢĤ (ĩńćĺũďĩńĝ ŌĶ-ōŵńēď śŷḿĺĩńķś). Ũśĩńĝ à ćũśţōḿ ŵŕàƥƥēŕ? Ŕēĝĩśţēŕ ĩţ ũńďēŕ à ďĩƒƒēŕēńţ ńàḿē."
],
+ "YJ1BTp": ["À śķĩĺĺ ŵĩţĥ ţĥàţ ńàḿē àĺŕēàďŷ ēxĩśţś."],
"YKLP_-": ["Ţēḿƥĺàţē ŕēńàḿēď"],
"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" śţĩĺĺ ēxĩśţś ōń ďĩśķ"],
"YSFv5w": ["Ńō ĝĩţ ŕēƥōśĩţōŕŷ — ćōńƒĩĝ śĥàŕĩńĝ ďōēś ńōţ àƥƥĺŷ ĥēŕē."],
@@ -1149,6 +1224,7 @@
],
"Z8KDox": ["Ēńţēŕ à ƒōĺďēŕ ńàḿē (ē.ĝ. ƀŕàĩń)."],
"Z8lGw6": ["Śĥàŕē"],
+ "ZARuZJ": ["Ćōũĺďń'ţ ĺōàď ƒĩĺēś"],
"ZBYKxv": [
"Ŕēvēŕţś ēvēŕŷ ćĥàńĝē ţĥĩś àĝēńţ ḿàďē ţō <0>",
["docName"],
@@ -1188,7 +1264,6 @@
"</1>."
],
"_BthEY": ["Ōƥēń ĩń ", ["shareBranch"]],
- "_K2CvV": ["Ţēḿƥĺàţē"],
"_PACVa": ["Ŕēĺēàśē ńōţēś"],
"_PBJRl": ["Àďď àţ ĺēàśţ ōńē ĺēţţēŕ ōŕ ńũḿƀēŕ."],
"_QwkMu": ["Ńō ḿàţćĥĩńĝ ƥàţĥś"],
@@ -1203,6 +1278,7 @@
"_bth6g": ["Ćĺàũďē Ćōďē ĩś ĩńśţàĺĺēď, ƀũţ ŌƥēńĶńōŵĺēďĝē ţōōĺś àŕēń'ţ ćōńńēćţēď ţō ĩţ ŷēţ."],
"_eguJc": ["Ũƥĺōàďĩńĝ"],
"_gkGSK": ["ďēĺēţēď ţēḿƥĺàţē"],
+ "_hPpdX": ["Śķĩĺĺ ŕēńàḿēď"],
"_pY_Vq": ["Ţĥē ŕēƥōśĩţōŕŷ ŵàś ḿōvēď, ŕēńàḿēď, ōŕ ďēĺēţēď."],
"_qD6mn": ["Ƥĩćķ ţĥē ƒōĺďēŕ ŵĥēŕē ŷōũ'vē ćĺōńēď ĩţ."],
"_rP3HI": [["minutes"], "ḿ àĝō"],
@@ -1216,6 +1292,7 @@
"/ àńď àĺĺ ƒĩĺēś ĩńśĩďē? Ţĥĩś àćţĩōń ćàńńōţ ƀē ũńďōńē."
],
"a9OzSn": ["Ńō ƥàĝēś ƒōũńď ƒōŕ \"", ["trimmedQuery"], "\""],
+ "aBgwis": ["Śćōƥē"],
"aByJ8j": ["Ĥōŵ ďōēś śĥàŕĩńĝ ŵōŕķ?"],
"aE2_XM": ["Ōńē ƥàţţēŕń ƥēŕ ĺĩńē — àƥƥēńďēď ţō <0>.ōķĩĝńōŕē</0>."],
"aENGMB": [
@@ -1242,7 +1319,6 @@
"bD8I7O": ["Ćōḿƥĺēţē"],
"bGa3Fk": ["Ũƥĺōàďĩńĝ ƒĩĺē"],
"bH382I": ["Ēďĩţ ţĥĩś ĤŢḾĹ — ţĥē ƥŕēvĩēŵ ũƥďàţēś ĺĩvē."],
- "bHboUQ": ["Ēďĩţ ţēḿƥĺàţē"],
"bS_boY": ["Ŕēƥĺàćē ćũŕŕēńţ ḿàţćĥ"],
"bUUVED": ["Àśśēţ"],
"bWLmRK": ["Ćōũĺď ńōţ ƒēţćĥ ƀŕàńćĥ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
@@ -1266,6 +1342,7 @@
"cKjLuT": ["(ƥŕōĴēćţ + ũśēŕ)"],
"cOSAfL": ["Ńō ŕēƥōśĩţōŕĩēś ƒōũńď ōń ŷōũŕ ĜĩţĤũƀ àććōũńţ."],
"cOrTMo": ["Ŷōũŕ śĥàŕē ĺĩńķ ĩś ŕēàďŷ ƀēĺōŵ."],
+ "cRHuuI": ["Ćōũĺďń'ţ ćōƥŷ ƥàţĥ"],
"cSCbv3": ["ßĒŢÀ"],
"cUK8lW": [
["conflictCount", "plural", { "one": ["#", " ćōńƒĺĩćţ"], "other": ["#", " ćōńƒĺĩćţś"] }]
@@ -1299,6 +1376,7 @@
"dOxPd4": ["Ƒōōţńōţē"],
"dPOFid": ["Śĥōŵ ōŕ ĥĩďē ţēŕḿĩńàĺ"],
"dTaauv": ["Ŕēàśōń: ", ["reason"]],
+ "dUCQo4": ["Ŕēńàḿēď ţō \"", ["trimmed"], "\""],
"dUQ7_J": [
"Àďď ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō śēàŕćĥ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĥēń ţĥēŷ śĥàŕē ńō ķēŷŵōŕďś. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."
],
@@ -1312,6 +1390,7 @@
"dprWmL": ["Àńćĥōŕ ĩń ţĥĩś ƥàĝē"],
"dr1vFs": ["Ŕēƥĺàćē àĺĺ ḿàţćĥēś"],
"dvGKu2": ["Śĥàŕēď àũţō-śŷńć ďēƒàũĺţ"],
+ "dw_3cv": ["Ŕēńàḿē śķĩĺĺ"],
"dw_dUJ": ["Ƒàĩĺēď ţō ďũƥĺĩćàţē ƥàţĥ"],
"e0NrBM": ["ƤŕōĴēćţ"],
"e1Rn_k": ["Ōƥēń ćōńţàĩńĩńĝ ƒōĺďēŕ"],
@@ -1326,12 +1405,16 @@
"eKThTQ": ["Ƒàĩĺēď ţō ŕēōŕďēŕ"],
"eNQGRb": ["Ĩńĺĩńē ĹàŢēX ḿàţĥ ŕēńďēŕēď ŵĩţĥ ĶàŢēX."],
"ePK91l": ["Ēďĩţ"],
+ "eQkgKV": ["Ĩńśţàĺĺēď"],
"eSu2Xn": [
"Ŵŕĩţēś à ƥŕōĴēćţ-ḾĆƤ ćōńƒĩĝ ƒōŕ ēàćĥ śēĺēćţēď ţōōĺ; Ćĺàũďē àĺśō ĝēţś <0>.ćĺàũďē/ĺàũńćĥ.Ĵśōń</0>."
],
"eTL5y9": ["Śĥōŵ śēĺēćţĩōń ƥŕēvĩēŵ"],
+ "eTsJYJ": ["ďēśćŕĩƥţĩōń"],
"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],
+ "el312q": ["Ĩńśţàĺĺ śķĩĺĺś ĩńţō"],
"emgiet": ["Àũţĥōŕĩţàţĩvē ćōńţēńţ; ḿĩŕŕōŕēď vēŕƀàţĩḿ ēvēŕŷŵĥēŕē ĩţ'ś ŕēƒēŕēńćēď."],
+ "eneWvv": ["Ďŕàƒţ"],
"euc6Ns": ["Ďũƥĺĩćàţē"],
"evs0iw": ["Ţàĝś ḿàţćĥĩńĝ \"", ["tagListQuery"], "\""],
"f1XQyZ": ["Ḿōvē ƀĺōćķ"],
@@ -1354,6 +1437,7 @@
"fbsiBw": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ śţàŕţĩńĝ ţĥē ţēŕḿĩńàĺ."],
"fcgvCA": ["Ćĺàũďē"],
"fiMNLl": ["Śŷńć śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
+ "fo0VXg": ["Ũńĩńśţàĺĺ"],
"fqSfXY": ["Ŕēƥĺàćē"],
"fwhX-N": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē"],
"g3UF2V": ["Àććēƥţ"],
@@ -1385,6 +1469,7 @@
],
"ggs9f8": ["Śēàŕćĥ ƒĩĺēś, ƒōĺďēŕś, ōŕ ćōḿḿàńďś"],
"gijbne": ["Ƒàĩĺēď ţō ŕēńàḿē ƥàţĥ"],
+ "gk_-qj": ["Ćōũĺďń'ţ ŕēńàḿē ţēḿƥĺàţē: ", ["0"]],
"gljvbT": [["words", "plural", { "one": ["ŵōŕď"], "other": ["ŵōŕďś"] }]],
"gmJ0An": ["Ƒàĩĺēď ţō ōƥēń ƒōĺďēŕ."],
"goO4Ll": ["Ēďĩţōŕ śţàţũś ƀàŕ"],
@@ -1403,6 +1488,7 @@
"</1>. Ŷōũŕ ćũŕŕēńţ ćōńţēńţ ĩś àĺŕēàďŷ śàvēď ĩń ţĥē ţĩḿēĺĩńē — ŷōũ ćàń ŕēśţōŕē ĩţ àńŷţĩḿē."
],
"h7FzJC": ["Ĺĩńķ-ĝŕàƥĥ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
+ "h9QFb9": ["Śķĩĺĺ \"", ["0"], "\" ďēĺēţēď"],
"hBMK4W": ["ƤŕōĴēćţ ţēḿƥĺàţēś"],
"hDEaQu": ["Ćōńńēćţ ŌƥēńĶńōŵĺēďĝē ţō ōţĥēŕ ţōōĺś ŷōũ ũśē."],
"hDKtoF": [["diffHrs"], "ĥ àĝō"],
@@ -1432,6 +1518,7 @@
"i92eAT": ["Ŵē'ĺĺ ćŕēàţē à ŕēƥōśĩţōŕŷ àńď śţàŕţ śŷńćĩńĝ — ńō ţēŕḿĩńàĺ ńēēďēď."],
"i9OyGp": ["Ũńďō ōŕ ŕēďō"],
"i9toLO": ["Àĝēńţ ćōńƒĩĝũŕàţĩōń ƒĩĺē"],
+ "iAoh55": ["Ũƥďàţē \"", ["0"], "\"?"],
"iDZtvM": ["Ƒàĩĺēď ţō ĺōàď ţēḿƥĺàţēś: ", ["message"]],
"iEQQyu": ["Àĝēńţ"],
"iEYxO4": ["Śĥōŵ ţĥũḿƀńàĩĺś"],
@@ -1475,6 +1562,7 @@
"jSO1X5": ["Ĩńĥēŕĩţēď ţēḿƥĺàţēś ćàń'ţ ƀē ŕēńàḿēď ĥēŕē — ŕēńàḿē ĩţ ĩń ţĥē ƒōĺďēŕ ţĥàţ ōŵńś ĩţ."],
"jSY41h": ["\"", ["docName"], "\" ţōōķ ţōō ĺōńĝ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
"jTLWxh": ["Ēḿƀēď àń ēxţēŕńàĺ ƥàĝē ĩń àń ĩńĺĩńē ĩƒŕàḿē (ďōćś, ďēḿōś, Ƒĩĝḿà, ĆōďēŚàńďƀōx)."],
+ "jX0IPx": ["À śķĩĺĺ ŵĩţĥ ţĥĩś ńàḿē àĺŕēàďŷ ēxĩśţś."],
"jZ_E5M": ["Ƒēţćĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
"j_Z6g7": ["Śĥàŕēď ďēƒàũĺţ"],
"jbSG8V": ["Śĥōŵ Ƒĩĺēś (", ["sidebarShortcutLabel"], ")"],
@@ -1504,6 +1592,7 @@
"kCqCyf": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĺĩńţ ďĩàĝńōśţĩćś ƥàńēĺ."],
"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],
"kNqMMd": ["Ƒōĺďēŕ"],
+ "kPtvEH": ["Ţĥē ƥàćķ śķĩĺĺ <0>", ["0"], "</0> ŵĩĺĺ ƀē (ŕē)ĩńśţàĺĺēď."],
"kUn-CN": ["Śŷńć ōƒƒ"],
"kV2YZv": [
"Ďōń'ţ śēē <0>Śķĩĺĺś</0>? Ēńàƀĺē <1>Śēţţĩńĝś <2/> Ćàƥàƀĩĺĩţĩēś <3/> Ćōďē ēxēćũţĩōń àńď ƒĩĺē ćŕēàţĩōń</1> ƒĩŕśţ."
@@ -1524,11 +1613,13 @@
"l1aQKz": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē"],
"l1l8sj": [["0"], "ď àĝō"],
"l3mSlL": ["Àƥƥēńď-ōńĺŷ ţĩḿēĺĩńē"],
+ "l3s5ri": ["Ĩḿƥōŕţ"],
"l6OXqI": ["Ńō ĩńśţàĺĺēď àĝēńţś ƒōũńď"],
"l8G3S9": ["Àũţō-śŷńć ĩś ōƒƒ — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
"lAiyU_": ["Ōńĺŷ ţĥē ćũŕŕēńţ ďōćũḿēńţ ũśēś <0>#", ["tag"], "</0>."],
"lGs_bQ": ["Ƥàĝē <0>*</0>"],
"lHwYMr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"], " ", ["statusText"]],
+ "lI0Td2": ["Ũśē ĺēţţēŕś, ďĩĝĩţś, <0>_</0> àńď <1>-</1> ōńĺŷ."],
"lIn9L9": ["Ďĩśàƀĺē śŷńć"],
"lPzyrU": ["Àĺĺ ĥũńķś ŕēśōĺvēď"],
"lVWEIL": ["Ĩńďēxēď ", ["embedded"], " ōƒ ", ["total"], " ƥàĝēś."],
@@ -1556,12 +1647,14 @@
"mGaZwZ": ["Śēē ţĥē ƒũĺĺ ĩńśţàĺĺ ĝũĩďē"],
"mHVPm5": ["Ŕēćōńńēćţ ŕēǫũĩŕēď"],
"mNY1G6": ["Ũńďō àĺĺ ēďĩţś"],
+ "mPneVR": ["Ũƥďàţēď \"", ["display"], "\" ţō ", ["0"], "."],
"mPy9lS": [
"Ōŕĝàńĩźē ḿŷ ēxĩśţĩńĝ śƥēćś ĩńţō à ĺĩńķēď ĩńďēx ĝŕōũƥēď ƀŷ àŕēà, àńď ƒĺàĝ àńŷ ţĥàţ ĥàvē ďŕĩƒţēď ōũţ ōƒ śŷńć ŵĩţĥ ţĥē ćũŕŕēńţ ćōďē."
],
"mSJ3Rn": ["Ćōḿƥũţĩńĝ śćàƒƒōĺď ƥĺàń"],
"mU3j1b": ["Ŕēḿōvē ĩţēḿ ", ["0"]],
"mWVJRX": ["Ćōĺĺàƥśĩƀĺē śēćţĩōń ŵĩţĥ à ćĺĩćķàƀĺē śũḿḿàŕŷ."],
+ "mY8U64": ["Ţēàćĥ àĝēńţś à ŕēƥēàţàƀĺē ţàśķ. Ŷōũ ćàń ēďĩţ ţĥē ƀōďŷ àƒţēŕ ćŕēàţĩńĝ."],
"mYGY3B": ["Ďàţē"],
"mZ1r4i": ["Ćŕēàţē à ďōćũḿēńţ ƒŕōḿ ", ["label"]],
"maDWIB": ["Ḿĩŕŕōŕ śōũŕćē <0>àƥĩ-śƥēć</0>"],
@@ -1592,7 +1685,13 @@
],
"n7aopT": ["Ēďĩţōŕ ḿōďē"],
"nCzR-G": ["Ćōƥŷ ćōďē ", ["userCode"]],
+ "nD7Fx9": [
+ "Ţĥĩś ŕēƥĺàćēś ţĥē ćũŕŕēńţ śķĩĺĺ ćōńţēńţ ŵĩţĥ ţĥē ƀũńďĺēď vēŕśĩōń ",
+ ["0"],
+ ". Àńŷ ĺōćàĺ ēďĩţś ŵĩĺĺ ƀē ŕēƥĺàćēď — ŷōũŕ ćũŕŕēńţ vēŕśĩōń ĩś śàvēď ţō ĥĩśţōŕŷ ƒĩŕśţ, śō ŷōũ ćàń ŕēśţōŕē ĩţ."
+ ],
"nDT8qt": ["Ĩńĩţĩàĺĩźēď ", ["0"], " ƀũţ ćōũĺď ńōţ ōƥēń ĩţ."],
+ "nJq7et": ["Ćōũĺďń'ţ ũńĩńśţàĺĺ śķĩĺĺ: ", ["0"]],
"nMSYz5": [
"Ţĥĩś ƥàţĥ ĩś ōń àń ēxţēŕńàĺ vōĺũḿē (/Vōĺũḿēś/...). ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĺōśē ţŕàćķ ōƒ ƒĩĺēś ŵĥēń ţĥē ďŕĩvē ēĴēćţś."
],
@@ -1616,6 +1715,7 @@
["errorDetail"],
". Ţŕŷ <0>ōķ śţàţũś</0> ōŕ ćĥēćķ <1>.ōķ/ĺōćàĺ/ĺàśţ-śƥàŵń-ēŕŕōŕ.ĺōĝ</1>."
],
+ "npcziF": ["Ĩńśţàĺĺ ōń"],
"nrGWJ7": [
"Ĝĩţ ĩďēńţĩţŷ ĩśń'ţ śēţ — ćōḿḿĩţś ũśē à ďēƒàũĺţ àũţĥōŕ. Śēţ ŷōũŕś śō ţēàḿḿàţēś śēē ŷōũŕ ńàḿē."
],
@@ -1635,6 +1735,7 @@
"o9CrsQ": ["ŕēśēàŕćĥ-ńōţē"],
"oAFVKX": ["Ƒàĩĺēď ţō ũƥďàţē ţĥē ƥŕōĴēćţ śŷńć ďēƒàũĺţ — ", ["detail"]],
"oBXkm2": ["Ďēĺēţē ćōďē ƀĺōćķ"],
+ "oCHfGC": ["Ĺēvēĺ"],
"oCZkaG": ["Ćōƥŷ ƥàţĥ"],
"oJl7eO": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["componentName"], " — śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],
"oKBnk5": ["Ḿōŕē ŕēǫũēśţś ŵēŕē ƀĺōćķēď."],
@@ -1685,6 +1786,7 @@
"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],
"q4YJl_": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (ēxĩţ ćōďē ", ["0"], ")."],
"q6-JVU": ["Ĺōàďĩńĝ ƥàĝēś"],
+ "q7F5am": ["ţĩţĺē"],
"qAQVSD": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ŵàś ńōţ ĵŚŌŃ"],
"qAhFeg": [
["userName"],
@@ -1762,6 +1864,8 @@
". Ŷōũ ćàń śţĩĺĺ ćŕēàţē à ƀĺàńķ ńōţē."
],
"sER-bs": ["Ƒĩĺēś"],
+ "sFhaTJ": ["Ďĩśàḿƀĩĝũàţēś śĩḿĩĺàŕĺŷ-ńàḿēď ţēḿƥĺàţēś ĩń ţĥē ḿēńũ."],
+ "sHrqDx": ["Ćōũĺďń'ţ ŕēńàḿē śķĩĺĺ: ", ["0"]],
"sIGbBZ": ["Ćōńvēŕţ śēĺēćţĩōń ţō ƒōōţńōţē"],
"sIxSSP": ["Ŕēśōĺvē ćōńƒĺĩćţ ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"sJK6pq": ["Ƥēŕḿĩśśĩōń ďēńĩēď"],
@@ -1791,7 +1895,9 @@
"t-JXbf": ["Ńōţĩōń-śţŷĺē ĩńĺĩńē ŕōŵ ƒōŕ à ďōŵńĺōàďàƀĺē ƒĩĺē. Ďŕàĝ-ďŕōƥ àĺśō ŵōŕķś."],
"t18QYR": ["Ũńƥĩń ", ["accessibleLabel"]],
"t2TkQ3": ["Śŷńć ƥàũśēď — ŕēśōĺvē ćōńƒĺĩćţś ţō ŕēśũḿē."],
+ "t422_7": ["Ũńĩńśţàĺĺ ēvēŕŷŵĥēŕē"],
"tAPZEx": ["ßēĺōŵ"],
+ "tHKQ6j": ["Ŕēńàḿĩńĝ"],
"tP5DDk": ["Àƥƥĺŷ ĺĩńķ"],
"tUvUfp": ["Ũśē à ƒōĺďēŕ ŷōũ àĺŕēàďŷ ĥàvē."],
"tW_yvQ": ["Ēxƥàńď ", ["docName"]],
@@ -1814,6 +1920,9 @@
"Ďōćũḿēńţ ţĥē àŕćĥĩţēćţũŕē ōƒ ţĥĩś ŕēƥō: ćŕēàţē àń ōvēŕvĩēŵ ƥàĝē ţĥàţ ĺĩńķś ţō à ƥàĝē ƥēŕ ḿàĴōŕ ḿōďũĺē ďēśćŕĩƀĩńĝ ĩţś ŕēśƥōńśĩƀĩĺĩţĩēś àńď ēńţŕŷ ƥōĩńţś."
],
"uF9ruK": ["Śàvĩńĝ"],
+ "uFOL2y": [
+ "Ńō ƥŕōĴēćţ śķĩĺĺś ŷēţ. Àũţĥōŕ ōńē ţō ţēàćĥ àĝēńţś à ŕēƥēàţàƀĺē ţàśķ śćōƥēď ţō ţĥĩś ķńōŵĺēďĝē ƀàśē."
+ ],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
"uKRYiW": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ēŕŕōŕ."],
"uL_Wx8": ["Ţĥē ţēŕḿĩńàĺ śţōƥƥēď ũńēxƥēćţēďĺŷ."],
@@ -1852,6 +1961,7 @@
{ "one": ["Ũƥĺōàďēď ōńē ƒĩĺē"], "other": ["Ũƥĺōàďēď ", ["uploadedCount"], " ƒĩĺēś"] }
]
],
+ "v7hK0U": ["Ũśē ĺōŵēŕćàśē ĺēţţēŕś, ďĩĝĩţś, àńď ĥŷƥĥēńś ōńĺŷ."],
"v7lbnC": ["Ƒĩńď ńēxţ ḿàţćĥ"],
"vDXqVv": ["Ĩńśēŕţ à ḿàŕķďōŵń ĥàŕď ƀŕēàķ."],
"vEJDlt": ["Ţĥē ƒĩĺē ĩś ĩń ŷōũŕ Ţŕàśĥ; ţĥē ƒĩĺē-ŵàţćĥēŕ ŵĩĺĺ ŕēćōńćĩĺē."],
@@ -1878,6 +1988,7 @@
],
"w7SsvI": ["Ţĥàţ ƒōĺďēŕ ĩśń'ţ àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ŷēţ. Ĩńĩţĩàĺĩźē ĩţ àńď ōƥēń?"],
"w7nm4K": ["Ĩńďēńţēď ƀĺōćķǫũōţē ƒōŕ ćĩţàţĩōńś."],
+ "wDgmsr": ["\"", ["0"], "\" ĩńśţàĺĺ ŕēƒŕēśĥēď (", ["1"], ")"],
"wJijgU": ["Ĺōćàţĩōń"],
"wJo9oS": ["Ćĺōśē ƒĩńď"],
"wQp1V3": ["Ḿĩŕŕōŕ ōƒ <0>", ["src"], "</0>"],
@@ -1890,9 +2001,13 @@
"wlwXUk": [
"Ŷōũ ƥĩćķēď ~/Ďōŵńĺōàďś. Ƒĩĺēś ţĥēŕē àŕē ũśũàĺĺŷ ţŕàńśĩēńţ — ćōńśĩďēŕ à śţàƀĺē ƒōĺďēŕ ĩńśţēàď."
],
+ "wn8EJi": [
+ "Śķĩĺĺś ţēàćĥ àĝēńţś ŕēƥēàţàƀĺē ţàśķś. Àũţĥōŕ ţĥēḿ ĥēŕē; ĩńśţàĺĺ à śķĩĺĺ ţō ƥŕōĴēćţ ĩţ ĩńţō ŷōũŕ ēďĩţōŕś' śķĩĺĺ ƒōĺďēŕś."
+ ],
"wndeIl": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńēĩţĥēŕ ĩńćōḿĩńĝ ńōŕ ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],
"wtcxiD": ["Śĥàŕē ţĥĩś śēţũƥ ŵĩţĥ ŷōũŕ ţēàḿ?"],
"wvbc1r": ["Ćōũĺďń'ţ ōƥēń ďōćũḿēńţ"],
+ "x-5mJ1": ["Ĩńśţàĺĺ ōń àĺĺ"],
"x2fr_j": ["Ĝŕàƥĥ"],
"x3-2ta": [
["packName"],
@@ -1928,11 +2043,19 @@
"xeiujy": ["Ţēxţ"],
"xhlFsx": ["Ĩńĥēŕĩţēď — śēţ à vàĺũē ĥēŕē ţō ŕēƥĺàćē ĩţ."],
"xiv-dW": ["Ńō ƒĩĺēś ŷēţ."],
+ "xloBjn": ["Ŕēĺàţĩvē Ƥàţĥ"],
+ "xnP32l": ["Ńō ďēśćŕĩƥţĩōń ŷēţ — àďď ōńē śō àĝēńţś ķńōŵ ŵĥēń ţō ũśē ţĥĩś śķĩĺĺ."],
+ "xrVr_k": ["Ćōũĺďń'ţ ćŕēàţē śķĩĺĺ: ", ["0"]],
"xsZhu-": ["Ƥàĝē ńũḿƀēŕ"],
"xzktOa": ["Ēďĩţ ŵĩķĩ ĺĩńķ"],
"y1t8bQ": ["Śēţţĩńĝś śēćţĩōńś"],
"y3aU20": ["Śàvē ćĥàńĝēś"],
"y46m5r": ["Ţĥē ďēśķţōƥ àƥƥ ĩśń'ţ ŕēśƥōńďĩńĝ. Ŕēƒŕēśĥ àńď ţŕŷ àĝàĩń."],
+ "y48eD2": [
+ "Ōƥēń Ķńōŵĺēďĝē ćàń ḿàńàĝē ",
+ ["0"],
+ " ēďĩţōŕ śķĩĺĺ(ś) ƒōŕ ţĥĩś ƥŕōĴēćţ — ĩḿƥōŕţ ţĥēḿ ĩńţō ţĥē ķńōŵĺēďĝē ƀàśē?"
+ ],
"y5FUYi": ["Śũĝĝēśţĩōń ḿēńũ ōƥēń"],
"y8B54M": ["Ćōũĺďń'ţ śēńď ŷōũŕ ƥŕōḿƥţ — ƥĺēàśē ţŕŷ àĝàĩń."],
"yCX4jp": [" Ŷōũŕ śēĺēćţĩōń ćōũĺď ńōţ ƀē ŕēśţōŕēď."],
@@ -1968,6 +2091,7 @@
["typeLabel"],
" (ĩńĥēŕĩţēď ƒŕōḿ ƒōĺďēŕ ƥŕōƥēŕţĩēś; ńōţ ēďĩţàƀĺē ĥēŕē)"
],
+ "yitgD9": ["Ƒàĩĺēď ţō ĺōàď śķĩĺĺ ţàŕĝēţś: ", ["0"]],
"yjExfe": ["ßŕàńćĥ <0>", ["shareBranch"], "</0> ĩś ćĥēćķēď ōũţ ĩń:"],
"ylXj1N": ["Śēĺēćţēď"],
"ynIa4S": ["Vĩśũàĺ ēďĩţōŕ ĺĩśţ ĩţēḿ"],
@@ -1983,11 +2107,13 @@
"z0a2EA": ["Ďĩàĝŕàḿ ƒŕōḿ Ḿēŕḿàĩď śōũŕćē — ƒĺōŵćĥàŕţ, śēǫũēńćē, ćĺàśś, śţàţē, ĒŔ, ĝàńţţ, ƥĩē."],
"z1uNN0": ["Ńō ēḿōĴĩ ƒōũńď."],
"z2JdQ-": ["Ćōńƒĩĝ śĥàŕĩńĝ ũńćĥàńĝēď — śēē ďēţàĩĺś ƀēĺōŵ."],
+ "z2funE": ["Ƒũĺĺ Ƥàţĥ"],
"z5pqI8": ["Ćàńńōţ ũƥĺōàď: ńō ďōćũḿēńţ ĩś ōƥēń"],
"z60Lgn": [
"Śàvēś ţĥē ƒĩĺē ţō <0>~/Ďōŵńĺōàďś/ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> àńď ōƥēńś ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ. Ŕēǫũĩŕēś Ńōďē.Ĵś ōŕ ßũń ōń ŷōũŕ ƤÀŢĤ."
],
"zAsDLY": ["Ĝŕàƥĥ vĩśũàĺĩźàţĩōń ōƒ ďōćũḿēńţ ĺĩńķś"],
+ "zKxoPm": ["Ćōũĺďń'ţ ŕēńàḿē \"", ["0"], "\": ", ["1"]],
"zL0LPh": ["Ĝĺōƀàĺ ōũţśĩďē ţēxţ ƒĩēĺďś"],
"zLGXna": ["Ńō śţàŕţēŕ ƥàćķś àvàĩĺàƀĺē."],
"zLak8b": ["Àćţĩvàţē ńēŵ ţàƀ"],
@@ -1999,6 +2125,7 @@
"Ţĥē ƥŕōƥēŕţĩēś ƀĺōćķ àţ ţĥē ţōƥ ōƒ ţĥĩś ďōć ĥàś à ƒōŕḿàţţĩńĝ ēŕŕōŕ. Śŵĩţćĥ ţō śōũŕćē ḿōďē ţō ƒĩx ĩţ."
],
"zbymaY": [["0"], "ḿ àĝō"],
+ "zd00pH": ["Ćōƥŷ Ƥàţĥ"],
"zgSFyG": ["Ēxţēŕńàĺ ĺĩńķ"],
"zkz0Fg": ["Śēţ ũƥ śŷńćĩńĝ"],
"zlErBl": ["Ƥàĝē ĥēàďĩńĝś ēŕŕōŕ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ŔƑĆ 9457"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index cd9ce039b..9187d4cbf 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -29,6 +29,17 @@ msgstr ""
msgid " Your selection has been restored."
msgstr ""
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(result.hosts)
+#: src/components/skill-actions.tsx
+msgid "\"{0}\" install refreshed ({1})"
+msgstr ""
+
+#. placeholder {0}: skill.name
+#: src/components/skill-actions.tsx
+msgid "\"{0}\" uninstalled — back to a draft"
+msgstr ""
+
#: src/components/DocumentErrorBoundary.tsx
msgid "\"{docName}\" doesn't exist."
msgstr ""
@@ -320,6 +331,10 @@ msgstr ""
msgid "{packName} initialized ({projectEntries, plural, one {# entry} other {# entries}})"
msgstr ""
+#: src/components/SeedDialog.tsx
+msgid "{packName} skill installed."
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "{packName} was already set up. Nothing to do."
msgstr ""
@@ -460,6 +475,14 @@ msgstr ""
msgid "A short line shown under the name in the template list."
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."
+msgstr ""
+
#: src/components/empty-state/CreatePromptComposer.tsx
msgid "A team knowledge base, a personal wiki, project docs..."
msgstr ""
@@ -489,6 +512,12 @@ 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 ""
@@ -763,6 +792,10 @@ msgstr ""
msgid "Available"
msgstr ""
+#: src/components/settings/SkillsManagerSection.tsx
+msgid "Available in every project on this computer."
+msgstr ""
+
#: 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>."
msgstr ""
@@ -928,13 +961,15 @@ msgstr ""
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/MountStalledAffordance.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/SeedDialog.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
-#: src/components/TemplateEditDialog.tsx
+#: src/components/SkillRenameDialog.tsx
+#: src/components/SkillUpdateDialog.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
#: src/editor/components/CodePreviewEditModal.tsx
@@ -995,6 +1030,10 @@ msgstr ""
msgid "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."
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 ""
@@ -1379,6 +1418,10 @@ msgstr ""
msgid "Copied full path"
msgstr ""
+#: src/components/skill-actions.tsx
+msgid "Copied path"
+msgstr ""
+
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Copied relative path"
@@ -1431,6 +1474,10 @@ msgstr ""
msgid "Copy path"
msgstr ""
+#: src/components/skill-actions.tsx
+msgid "Copy Path"
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Copy share link"
msgstr ""
@@ -1570,6 +1617,10 @@ msgstr ""
msgid "Couldn't construct the share URL. Try Done and re-share."
msgstr ""
+#: src/components/skill-actions.tsx
+msgid "Couldn't copy path"
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Couldn't copy: {detail}"
msgstr ""
@@ -1578,10 +1629,19 @@ msgstr ""
msgid "Couldn't copy. Select the URL above to copy it manually."
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/NewSkillDialog.tsx
+msgid "Couldn't create skill: {0}"
+msgstr ""
+
#: src/components/TemplateForm.tsx
msgid "Couldn't create template: {error}"
msgstr ""
+#: src/components/SkillDeleteDialog.tsx
+msgid "Couldn't delete skill: {error}"
+msgstr ""
+
#: src/components/TemplateDeleteDialog.tsx
msgid "Couldn't delete template: {error}"
msgstr ""
@@ -1590,7 +1650,18 @@ msgstr ""
msgid "Couldn't disconnect — please try again."
msgstr ""
-#: src/components/TextViewer.tsx
+#. placeholder {0}: skill.name
+#. placeholder {1}: result.error
+#: src/components/skill-actions.tsx
+msgid "Couldn't duplicate \"{0}\": {1}"
+msgstr ""
+
+#. placeholder {0}: result.error
+#: src/components/skill-actions.tsx
+msgid "Couldn't install skill: {0}"
+msgstr ""
+
+#: src/components/ViewerStatusPane.tsx
msgid "Couldn't load {fileName}"
msgstr ""
@@ -1606,6 +1677,10 @@ 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 ""
@@ -1614,6 +1689,15 @@ msgstr ""
msgid "Couldn't load templates"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "Couldn't load this skill's files."
+msgstr ""
+
+#. placeholder {0}: result.error
+#: src/components/ManagedArtifactProperties.tsx
+msgid "Couldn't move skill: {0}"
+msgstr ""
+
#: src/components/TrashFailureModal.tsx
msgid "Couldn't move to Trash"
msgstr ""
@@ -1646,6 +1730,22 @@ msgstr ""
msgid "Couldn't remove <0>{targetGitPath}</0>: {removeGitError}"
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}"
+msgstr ""
+
+#. placeholder {0}: result.error
+#: src/components/ManagedArtifactProperties.tsx
+msgid "Couldn't rename template: {0}"
+msgstr ""
+
#: src/components/DiffViewBoundary.tsx
msgid "Couldn't resolve the conflict for {filePath}."
msgstr ""
@@ -1678,6 +1778,21 @@ msgstr ""
msgid "Couldn't send your prompt — please try again."
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}"
+msgstr ""
+
#: src/components/ConsentDialogBody.tsx
msgid "Counting markdown files"
msgstr ""
@@ -1732,6 +1847,10 @@ msgstr ""
msgid "Create page"
msgstr ""
+#: src/components/NewSkillDialog.tsx
+msgid "Create skill"
+msgstr ""
+
#: src/components/empty-state/empty-state-copy.ts
msgid "Create something great."
msgstr ""
@@ -1768,6 +1887,7 @@ msgstr ""
#: src/components/CreateProjectDialog.tsx
#: src/components/NewItemDialog.tsx
+#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
msgid "Creating"
msgstr ""
@@ -1806,6 +1926,7 @@ msgid "Default properties"
msgstr ""
#: src/components/DeleteConfirmationDialog.tsx
+#: src/components/skill-actions.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/JsxComponentView.tsx
msgid "Delete"
@@ -1880,6 +2001,11 @@ msgstr ""
msgid "Describe what you're working on and the agent sets it up for you."
msgstr ""
+#: src/components/TemplateProperties.tsx
+msgid "description"
+msgstr ""
+
+#: src/components/NewSkillDialog.tsx
#: src/components/TemplateForm.tsx
msgid "Description"
msgstr ""
@@ -1904,6 +2030,10 @@ msgstr ""
msgid "Details"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Detected from the editors this project is set up for. Adjust to control where every skill installs."
+msgstr ""
+
#: src/components/McpConsentDialogBody.tsx
msgid "Detected on this machine"
msgstr ""
@@ -1937,6 +2067,10 @@ msgstr ""
msgid "Disable sync"
msgstr ""
+#: src/components/TemplateProperties.tsx
+msgid "Disambiguates similarly-named templates in the menu."
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "Disconnect"
msgstr ""
@@ -2033,6 +2167,11 @@ msgstr ""
msgid "Downloads {shareOwner}/{shareRepo} 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 ""
@@ -2055,6 +2194,7 @@ msgid "Drag item {0} to reorder"
msgstr ""
#: src/components/FileTree.tsx
+#: src/components/skill-actions.tsx
msgid "Duplicate"
msgstr ""
@@ -2074,6 +2214,11 @@ msgstr ""
msgid "Duplicate the focused file-tree item when focus is in the Files sidebar."
msgstr ""
+#. placeholder {0}: result.name
+#: src/components/skill-actions.tsx
+msgid "Duplicated to \"{0}\""
+msgstr ""
+
#: src/components/settings/OkignoreSection.tsx
msgid "e.g. drafts/ or *.draft.md"
msgstr ""
@@ -2086,6 +2231,7 @@ msgstr ""
msgid "Each selected tool gets an OpenKnowledge MCP entry."
msgstr ""
+#: src/components/skill-actions.tsx
#: src/components/TemplateForm.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
@@ -2102,10 +2248,6 @@ msgstr ""
msgid "Edit {keyName}"
msgstr ""
-#: src/components/TemplateEditDialog.tsx
-msgid "Edit {templateLabel}"
-msgstr ""
-
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "Edit markdown link"
msgstr ""
@@ -2114,10 +2256,6 @@ msgstr ""
msgid "Edit source"
msgstr ""
-#: src/components/TemplateEditDialog.tsx
-msgid "Edit template"
-msgstr ""
-
#: src/editor/slash-command/embed-starter-items.tsx
msgid "Edit this HTML — the preview updates live."
msgstr ""
@@ -2142,7 +2280,7 @@ msgstr ""
msgid "Editing broken MDX source: {reason}"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Editor mode"
msgstr ""
@@ -2154,6 +2292,10 @@ msgstr ""
msgid "Editor status bar"
msgstr ""
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Editors to install skills into"
+msgstr ""
+
#: src/editor/slash-command/component-items.tsx
msgid "Edits at the source land here — no copy-paste drift."
msgstr ""
@@ -2383,7 +2525,7 @@ msgstr ""
msgid "Failed to load documents"
msgstr ""
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "Failed to load file"
msgstr ""
@@ -2429,12 +2571,18 @@ msgstr ""
msgid "Failed to load recent projects."
msgstr ""
-#: src/components/CommandPalette.tsx
-msgid "Failed to load tags. Press Escape and re-open to retry."
+#. 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}"
msgstr ""
-#: src/components/TemplateEditDialog.tsx
-msgid "Failed to load template: {errorMessage}"
+#: src/components/CommandPalette.tsx
+msgid "Failed to load tags. Press Escape and re-open to retry."
msgstr ""
#: src/components/TemplatesCard.tsx
@@ -2636,6 +2784,7 @@ msgstr ""
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
+#: src/components/TemplateProperties.tsx
msgid "folder"
msgstr ""
@@ -2699,6 +2848,10 @@ msgstr ""
msgid "Full path"
msgstr ""
+#: src/components/skill-actions.tsx
+msgid "Full Path"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "General"
msgstr ""
@@ -2728,6 +2881,7 @@ msgid "GitHub sign-in is missing or expired. Reconnect to resume syncing."
msgstr ""
#: src/lib/keyboard-shortcuts.ts
+#: src/lib/skill-scope.ts
msgid "Global"
msgstr ""
@@ -2735,6 +2889,10 @@ 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"
@@ -2933,6 +3091,10 @@ msgstr ""
msgid "Ignore patterns (raw text)"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "Import"
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "In a subfolder"
msgstr ""
@@ -3056,6 +3218,8 @@ msgstr ""
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/settings/SettingsDialogBody.tsx
+#: src/components/skill-actions.tsx
+#: src/components/SkillRow.tsx
msgid "Install"
msgstr ""
@@ -3084,6 +3248,34 @@ msgstr ""
msgid "Install in Claude Desktop"
msgstr ""
+#: src/components/SkillEditorActions.tsx
+msgid "Install on"
+msgstr ""
+
+#: src/components/SkillEditorActions.tsx
+msgid "Install on all"
+msgstr ""
+
+#: src/components/settings/SkillTargetsPicker.tsx
+msgid "Install skills into"
+msgstr ""
+
+#: src/components/SkillEditorActions.tsx
+#: src/components/SkillRow.tsx
+#: src/components/SkillStateBadge.tsx
+msgid "Installed"
+msgstr ""
+
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(added)
+#: src/components/skill-actions.tsx
+msgid "Installed \"{0}\" into {1}"
+msgstr ""
+
+#: src/components/SkillRow.tsx
+msgid "Installed into"
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Installing"
msgstr ""
@@ -3174,6 +3366,10 @@ msgstr ""
msgid "Let Tab leave the source editor instead of indenting."
msgstr ""
+#: src/components/SkillProperties.tsx
+msgid "Level"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Light, dark, or follow the OS."
msgstr ""
@@ -3212,13 +3408,14 @@ msgid "List"
msgstr ""
#: src/components/PageHeaderWidgets.tsx
+#: src/components/SkillsSidebarSection.tsx
#: src/editor/components/TagDialog.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Loading"
msgstr ""
-#: src/components/TextViewer.tsx
+#: src/components/ViewerStatusPane.tsx
msgid "Loading {fileName}"
msgstr ""
@@ -3373,11 +3570,11 @@ msgstr ""
msgid "Mark a block as the source of truth. Mirror references elsewhere render this content read-only and update live as you edit here."
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Markdown"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Markdown source"
msgstr ""
@@ -3498,6 +3695,16 @@ 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)"
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
msgid "moved template"
msgstr ""
@@ -3506,8 +3713,15 @@ msgstr ""
msgid "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
msgstr ""
+#: src/components/SkillProperties.tsx
+#: src/components/TemplateProperties.tsx
+msgid "name"
+msgstr ""
+
#: src/components/AuthModal.tsx
#: src/components/FolderOverview.tsx
+#: src/components/NewSkillDialog.tsx
+#: src/components/SkillRenameDialog.tsx
#: src/editor/slash-command/items.tsx
msgid "Name"
msgstr ""
@@ -3619,6 +3833,12 @@ msgstr ""
msgid "New property name"
msgstr ""
+#: src/components/NewSkillDialog.tsx
+#: src/components/settings/SkillsManagerSection.tsx
+#: src/components/SkillsSidebarSection.tsx
+msgid "New skill"
+msgstr ""
+
#: src/components/EditorTabs.tsx
msgid "New tab"
msgstr ""
@@ -3653,6 +3873,10 @@ msgstr ""
msgid "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
msgstr ""
+#: src/components/SkillRow.tsx
+msgid "No description yet — add one so agents know when to use this skill."
+msgstr ""
+
#: src/components/ActivityPanelBurstRow.tsx
msgid "No diff."
msgstr ""
@@ -3693,6 +3917,10 @@ msgstr ""
msgid "No git repository — config sharing does not apply 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 ""
@@ -3796,6 +4024,10 @@ msgstr ""
msgid "No patterns yet. Type a folder or file name below to start hiding files."
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 ""
@@ -3813,6 +4045,10 @@ msgstr ""
msgid "No results"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
+msgid "No skills yet."
+msgstr ""
+
#: src/components/PackCardGrid.tsx
msgid "No starter packs available."
msgstr ""
@@ -3877,6 +4113,7 @@ msgstr ""
msgid "Not installed"
msgstr ""
+#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
msgid "Not now"
msgstr ""
@@ -4040,7 +4277,7 @@ msgid "Open emoji picker for {keyName}"
msgstr ""
#: src/components/AssetPreview.tsx
-#: src/components/TextViewer.tsx
+#: src/components/ViewerStatusPane.tsx
msgid "Open file"
msgstr ""
@@ -4066,6 +4303,11 @@ msgstr ""
msgid "Open in current branch"
msgstr ""
+#. placeholder {0}: state.importable
+#: src/components/SkillsSidebarSection.tsx
+msgid "Open Knowledge can manage {0} editor skill(s) for this project — import them into the knowledge base?"
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "Open link"
msgstr ""
@@ -4457,6 +4699,7 @@ msgid "project"
msgstr ""
#: src/components/CommandPalette.tsx
+#: src/lib/skill-scope.ts
msgid "Project"
msgstr ""
@@ -4473,6 +4716,10 @@ msgstr ""
msgid "Project root"
msgstr ""
+#: src/lib/skill-scope.ts
+msgid "Project Skill"
+msgstr ""
+
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "Project templates"
msgstr ""
@@ -4498,6 +4745,7 @@ msgid "Project-level pages with no outgoing graph edges."
msgstr ""
#: src/components/PropertyPanel.tsx
+#: src/components/TemplateProperties.tsx
msgid "Properties"
msgstr ""
@@ -4645,6 +4893,10 @@ msgstr ""
msgid "Relative path"
msgstr ""
+#: src/components/skill-actions.tsx
+msgid "Relative Path"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Relaunching to install the update…"
msgstr ""
@@ -4726,6 +4978,8 @@ msgid "Removing"
msgstr ""
#: src/components/FileTree.tsx
+#: src/components/skill-actions.tsx
+#: src/components/SkillRenameDialog.tsx
msgid "Rename"
msgstr ""
@@ -4737,6 +4991,10 @@ msgstr ""
msgid "Rename {label}"
msgstr ""
+#: src/components/SkillRenameDialog.tsx
+msgid "Rename skill"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Rename succeeded but the sidebar may be out of date — refresh to resync"
msgstr ""
@@ -4745,6 +5003,18 @@ msgstr ""
msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
msgstr ""
+#: src/components/SkillRenameDialog.tsx
+msgid "Renamed to \"{trimmed}\""
+msgstr ""
+
+#: src/components/SkillRenameDialog.tsx
+msgid "Renames the folder on disk and the id agents use to invoke it."
+msgstr ""
+
+#: src/components/SkillRenameDialog.tsx
+msgid "Renaming"
+msgstr ""
+
#: src/components/TemplateForm.tsx
msgid "Renaming changes the file on disk and the id agents use to pick this template."
msgstr ""
@@ -4914,6 +5184,7 @@ msgstr ""
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
+#: src/components/skill-actions.tsx
msgid "Reveal in Finder"
msgstr ""
@@ -4955,7 +5226,6 @@ msgstr ""
#: src/components/AuthModal.tsx
#: src/components/settings/EmbeddingsKeySection.tsx
-#: src/components/TemplateEditDialog.tsx
#: src/editor/components/CodePreviewEditModal.tsx
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
@@ -4993,7 +5263,6 @@ msgid "Saves the file to <0>~/Downloads/openknowledge.skill</0> and opens the Cl
msgstr ""
#: src/components/settings/EmbeddingsKeySection.tsx
-#: src/components/TemplateEditDialog.tsx
msgid "Saving"
msgstr ""
@@ -5001,6 +5270,10 @@ msgstr ""
msgid "Scaffold directly under this project."
msgstr ""
+#: src/components/NewSkillDialog.tsx
+msgid "Scope"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Scope: "
msgstr ""
@@ -5280,6 +5553,10 @@ msgstr ""
msgid "Shared repositories"
msgstr ""
+#: src/components/settings/SkillsManagerSection.tsx
+msgid "Shared via git with everyone working on this project."
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Sharing a doc needs a GitHub repository. Create one for this project."
msgstr ""
@@ -5389,6 +5666,38 @@ msgstr ""
msgid "Single page"
msgstr ""
+#. placeholder {0}: skill.name
+#: src/components/SkillDeleteDialog.tsx
+msgid "skill \"{0}\""
+msgstr ""
+
+#. placeholder {0}: target.name
+#: src/components/SkillDeleteDialog.tsx
+msgid "Skill \"{0}\" deleted"
+msgstr ""
+
+#: src/components/NewSkillDialog.tsx
+msgid "Skill \"{trimmedName}\" created"
+msgstr ""
+
+#: src/components/SkillProperties.tsx
+msgid "Skill level"
+msgstr ""
+
+#: src/components/ManagedArtifactProperties.tsx
+msgid "Skill renamed"
+msgstr ""
+
+#: src/components/settings/SettingsDialogShell.tsx
+#: src/components/settings/SkillsManagerSection.tsx
+#: src/components/SkillsSidebarSection.tsx
+msgid "Skills"
+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."
+msgstr ""
+
#. Secondary button — dismisses the dialog without wiring any tools
#: src/components/AuthModal.tsx
#: src/components/McpConsentDialogBody.tsx
@@ -5415,7 +5724,7 @@ msgstr ""
msgid "Something went wrong opening \"{docName}\"."
msgstr ""
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "Something went wrong opening this file (HTTP {status})."
msgstr ""
@@ -5439,7 +5748,7 @@ msgstr ""
msgid "Source find results"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Source mode requires a live connection — your edits are saved and will appear when you reconnect."
msgstr ""
@@ -5674,12 +5983,12 @@ msgstr ""
msgid "Task List"
msgstr ""
-#: src/components/CreateProjectDialog.tsx
-msgid "Team Wiki"
+#: src/components/NewSkillDialog.tsx
+msgid "Teach agents a repeatable task. You can edit the body after creating."
msgstr ""
-#: src/components/TemplateEditDialog.tsx
-msgid "Template"
+#: src/components/CreateProjectDialog.tsx
+msgid "Team Wiki"
msgstr ""
#: src/components/TemplateDeleteDialog.tsx
@@ -5698,6 +6007,7 @@ msgstr ""
msgid "Template list"
msgstr ""
+#: src/components/ManagedArtifactProperties.tsx
#: src/components/TemplateForm.tsx
msgid "Template renamed"
msgstr ""
@@ -5787,6 +6097,11 @@ msgstr ""
msgid "The file on disk, and the id agents use. It can't be changed later."
msgstr ""
+#: src/components/NewSkillDialog.tsx
+#: src/components/SkillProperties.tsx
+msgid "The folder on disk and the id agents use to invoke this skill."
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "The folders and templates are in place; there's nothing left to scaffold."
msgstr ""
@@ -5795,6 +6110,15 @@ msgstr ""
msgid "The formula <0>c = √(a² + b²)</0> renders inline."
msgstr ""
+#: src/components/TemplateProperties.tsx
+msgid "The menu label agents pick this template by (required)."
+msgstr ""
+
+#. placeholder {0}: phase.plan.packSkill.name
+#: src/components/SeedDialog.tsx
+msgid "The pack skill <0>{0}</0> will be (re)installed."
+msgstr ""
+
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
msgstr ""
@@ -5811,6 +6135,10 @@ msgstr ""
msgid "The repository was moved, renamed, or deleted."
msgstr ""
+#: src/components/TemplateProperties.tsx
+msgid "The template's filename (without `.md`)."
+msgstr ""
+
#: src/components/TerminalGate.tsx
msgid "The terminal is turned off for this project. Turn it back on to run commands here."
msgstr ""
@@ -5861,15 +6189,19 @@ msgstr ""
msgid "This document is already active in the editor. Use Open to collapse the graph."
msgstr ""
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "This file can't be opened in the text editor."
msgstr ""
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
msgid "This file could not be found."
msgstr ""
-#: src/components/TextViewer.tsx
+#: src/components/use-viewer-text.ts
+msgid "This file is binary and can't be shown as text."
+msgstr ""
+
+#: src/components/use-viewer-text.ts
msgid "This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."
msgstr ""
@@ -5901,6 +6233,11 @@ msgstr ""
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr ""
+#. placeholder {0}: skill.path
+#: src/components/SkillDeleteDialog.tsx
+msgid "This permanently removes {0}. Agents that invoke this skill by name will fail until it's recreated."
+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 ""
@@ -5938,6 +6275,17 @@ msgstr ""
msgid "This project's server (v{0}) is newer than this app (v{1})."
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."
+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."
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "This sends content off your machine"
msgstr ""
@@ -5963,6 +6311,10 @@ msgstr ""
msgid "Timeline"
msgstr ""
+#: src/components/TemplateProperties.tsx
+msgid "title"
+msgstr ""
+
#: src/components/TemplateForm.tsx
#: src/editor/extensions/CodeBlockView.tsx
msgid "Title"
@@ -6155,6 +6507,20 @@ msgstr ""
msgid "Unified diff"
msgstr ""
+#: src/components/skill-actions.tsx
+msgid "Uninstall"
+msgstr ""
+
+#: src/components/SkillEditorActions.tsx
+msgid "Uninstall everywhere"
+msgstr ""
+
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(removed)
+#: src/components/skill-actions.tsx
+msgid "Uninstalled \"{0}\" from {1}"
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
msgid "Unknown"
msgstr ""
@@ -6191,14 +6557,57 @@ msgstr ""
msgid "Unrecognized wiki link"
msgstr ""
+#: src/components/SkillUpdateDialog.tsx
+msgid "Update"
+msgstr ""
+
+#. placeholder {0}: skillDisplayName(skill.name)
+#: src/components/SkillUpdateDialog.tsx
+msgid "Update \"{0}\"?"
+msgstr ""
+
+#: src/components/SkillsSidebarSection.tsx
+msgid "Update available"
+msgstr ""
+
+#. placeholder {0}: skill.bundledVersion ? ` (${skill.bundledVersion})` : ''
+#: src/components/SkillsSidebarSection.tsx
+msgid "Update available{0}"
+msgstr ""
+
+#: src/components/skill-actions.tsx
+msgid "Update skill"
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "Update the destination and optional section anchor."
msgstr ""
+#. placeholder {0}: skill.name
+#. placeholder {1}: label(added)
+#. placeholder {2}: label(removed)
+#: src/components/skill-actions.tsx
+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}."
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
msgid "updated folder properties"
msgstr ""
+#: src/components/SkillUpdateDialog.tsx
+msgid "Updating"
+msgstr ""
+
#: src/components/PageHeaderWidgets.tsx
msgid "Upload {keyName}"
msgstr ""
@@ -6255,10 +6664,23 @@ msgstr ""
msgid "Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."
msgstr ""
+#: src/components/TemplateProperties.tsx
+msgid "Use letters, digits, <0>_</0> and <1>-</1> only."
+msgstr ""
+
#: src/components/TemplateForm.tsx
msgid "Use letters, digits, <0>-</0> or <1>_</1> only."
msgstr ""
+#: src/components/SkillProperties.tsx
+#: src/components/SkillRenameDialog.tsx
+msgid "Use lowercase letters, digits, and <0>-</0> only."
+msgstr ""
+
+#: src/components/NewSkillDialog.tsx
+msgid "Use lowercase letters, digits, and hyphens only."
+msgstr ""
+
#: src/components/settings/SettingsDialogShell.tsx
msgid "User"
msgstr ""
@@ -6284,11 +6706,11 @@ msgstr ""
msgid "Visibility"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
msgid "Visual"
msgstr ""
-#: src/components/EditorToolbar.tsx
+#: src/components/EditorModeToggle.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Visual editor"
msgstr ""
@@ -6337,6 +6759,10 @@ msgstr ""
msgid "We'll create a repository and start syncing — no terminal needed."
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 ""
@@ -6399,6 +6825,7 @@ msgid "Word wrap"
msgstr ""
#: src/components/McpConsentDialogBody.tsx
+#: src/components/SkillEditorActions.tsx
msgid "Working"
msgstr ""
diff --git a/packages/app/tests/dom/jsdom-preload.ts b/packages/app/tests/dom/jsdom-preload.ts
index dd888861d..007dfbb0c 100644
--- a/packages/app/tests/dom/jsdom-preload.ts
+++ b/packages/app/tests/dom/jsdom-preload.ts
@@ -25,6 +25,7 @@ Object.assign(globalThis, {
Node: win.Node,
NodeList: win.NodeList,
NodeFilter: win.NodeFilter,
+
DocumentFragment: win.DocumentFragment,
DOMRect: win.DOMRect,
Event: win.Event,
diff --git a/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts b/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts
index 52ecae09b..cb1f3165d 100644
--- a/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts
+++ b/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts
@@ -23,6 +23,7 @@ const SNAPSHOT_EXCLUDED_DIRS = new Set([
'.claude',
'.cursor',
'.codex',
+ '.opencode',
'.agents',
]);
diff --git a/packages/app/tests/integration/api-error-envelope/create-page.test.ts b/packages/app/tests/integration/api-error-envelope/create-page.test.ts
index 61ea3059a..c9fd402b0 100644
--- a/packages/app/tests/integration/api-error-envelope/create-page.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/create-page.test.ts
@@ -1,4 +1,6 @@
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
import { CreatePageSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
@@ -75,6 +77,31 @@ describe('create-page envelope (RFC 9457)', () => {
}
});
+ test('rejects a .ok/skills/** target and writes nothing', async () => {
+ const relPath = 'skills/phantom-from-create-page/SKILL.md';
+ const res = await postCreate({ path: `.ok/${relPath}` });
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ const parsed = ProblemDetailsSchema.safeParse(body);
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.type).toBe('urn:ok:error:reserved-doc-name');
+ }
+ expect(existsSync(join(server.contentDir, '.ok', relPath))).toBe(false);
+ });
+
+ test('rejects a bare .ok/-rooted target and writes nothing', async () => {
+ const res = await postCreate({ path: '.ok/local/sneaky.md' });
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ const parsed = ProblemDetailsSchema.safeParse(body);
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.type).toBe('urn:ok:error:reserved-doc-name');
+ }
+ expect(existsSync(join(server.contentDir, '.ok', 'local', 'sneaky.md'))).toBe(false);
+ });
+
test('path traversal emits urn:ok:error:path-escape', async () => {
const res = await postCreate({ path: '../escape.md' });
expect(res.status).toBe(400);
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
new file mode 100644
index 000000000..859931343
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
@@ -0,0 +1,141 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import { createTestServer, type TestServer } from '../test-harness';
+
+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 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\nLogging a trip.',
+ frontmatter: { name, description: 'Use when logging a trip.' },
+ }),
+ });
+
+const delSkill = (scope: 'global' | 'project', name: string) =>
+ fetch(`${base()}/api/skill?name=${name}&scope=${scope}`, { method: 'DELETE' });
+
+const installSkill = (scope: 'global' | 'project', name: string, targets: readonly string[]) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope, name, targets }),
+ });
+
+const skillSrc = (scope: 'global' | 'project', name: string) =>
+ scope === 'global'
+ ? join(tmpHome, '.ok', 'skills', name)
+ : join(server.contentDir, '.ok', 'skills', name);
+
+const projectionDir = (
+ scope: 'global' | 'project',
+ editor: (typeof EDITORS)[number],
+ name: string,
+) =>
+ scope === 'global'
+ ? join(tmpHome, HOST_DOTDIR[editor], 'skills', name)
+ : join(server.contentDir, HOST_DOTDIR[editor], 'skills', name);
+
+async function moveCrossScope(from: 'global' | 'project', to: 'global' | 'project', name: string) {
+ expect((await putSkill(to, name)).status).toBe(200);
+ expect((await delSkill(from, name)).status).toBe(200);
+}
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-xscope-uninstall-home-'));
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('DELETE uninstalls a multi-editor install (the move relies on this)', () => {
+ test('project skill: install claude+cursor+codex → DELETE → all projections gone', async () => {
+ const N = 'del-project-probe';
+ expect((await putSkill('project', N)).status).toBe(200);
+ expect((await installSkill('project', N, EDITORS)).status).toBe(200);
+ for (const e of EDITORS) {
+ expect(existsSync(join(projectionDir('project', e, N), 'SKILL.md'))).toBe(true);
+ }
+
+ expect((await delSkill('project', N)).status).toBe(200);
+ for (const e of EDITORS) {
+ expect(existsSync(projectionDir('project', e, N))).toBe(false);
+ }
+ expect(existsSync(skillSrc('project', N))).toBe(false);
+ });
+
+ test('global skill: install claude+cursor+codex → DELETE → all projections gone', async () => {
+ const N = 'del-global-probe';
+ expect((await putSkill('global', N)).status).toBe(200);
+ expect((await installSkill('global', N, EDITORS)).status).toBe(200);
+ for (const e of EDITORS) {
+ expect(existsSync(join(projectionDir('global', e, N), 'SKILL.md'))).toBe(true);
+ }
+
+ expect((await delSkill('global', N)).status).toBe(200);
+ for (const e of EDITORS) {
+ expect(existsSync(projectionDir('global', e, N))).toBe(false);
+ }
+ expect(existsSync(skillSrc('global', N))).toBe(false);
+ });
+});
+
+describe('cross-scope move removes the SOURCE projections in both directions', () => {
+ test('project → global: project claude+cursor+codex projections all removed', async () => {
+ const N = 'move-p2g-probe';
+ expect((await putSkill('project', N)).status).toBe(200);
+ expect((await installSkill('project', N, EDITORS)).status).toBe(200);
+ for (const e of EDITORS) {
+ expect(existsSync(join(projectionDir('project', e, N), 'SKILL.md'))).toBe(true);
+ }
+
+ await moveCrossScope('project', 'global', N);
+
+ for (const e of EDITORS) {
+ expect(existsSync(projectionDir('project', e, N))).toBe(false);
+ }
+ expect(existsSync(skillSrc('project', N))).toBe(false);
+ expect(existsSync(join(skillSrc('global', N), 'SKILL.md'))).toBe(true);
+ for (const e of EDITORS) {
+ expect(existsSync(projectionDir('global', e, N))).toBe(false);
+ }
+ });
+
+ test('global → project: global claude+cursor+codex projections all removed', async () => {
+ const N = 'move-g2p-probe';
+ expect((await putSkill('global', N)).status).toBe(200);
+ expect((await installSkill('global', N, EDITORS)).status).toBe(200);
+ for (const e of EDITORS) {
+ expect(existsSync(join(projectionDir('global', e, N), 'SKILL.md'))).toBe(true);
+ }
+
+ await moveCrossScope('global', 'project', N);
+
+ for (const e of EDITORS) {
+ expect(existsSync(projectionDir('global', e, N))).toBe(false);
+ }
+ expect(existsSync(skillSrc('global', N))).toBe(false);
+ expect(existsSync(join(skillSrc('project', N), 'SKILL.md'))).toBe(true);
+ for (const e of EDITORS) {
+ expect(existsSync(projectionDir('project', e, N))).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
new file mode 100644
index 000000000..eb7ca5fa6
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-install.test.ts
@@ -0,0 +1,143 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { ProblemDetailsSchema, SkillInstallSuccessSchema } from '@inkeep/open-knowledge-core';
+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 putSkill = (name: string, frontmatter = `name: ${name}\ndescription: Use when testing.`) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, body: '# Steps', frontmatter: parseFm(frontmatter) }),
+ });
+
+function parseFm(fm: string): { name: string; description: string } {
+ const name = /name:\s*(.+)/.exec(fm)?.[1]?.trim() ?? '';
+ const description = /description:\s*(.+)/.exec(fm)?.[1]?.trim() ?? '';
+ return { name, description };
+}
+
+const installSkill = (body: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+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();
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+});
+
+describe('skill install-projection lifecycle', () => {
+ test('install projects verbatim into explicit targets + records the marker', async () => {
+ expect((await putSkill('trip-log')).status).toBe(200);
+
+ const res = await installSkill({ name: 'trip-log', targets: ['claude', 'cursor'] });
+ expect(res.status).toBe(200);
+ const parsed = SkillInstallSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.hosts.sort()).toEqual(['claude', 'cursor']);
+ expect(parsed.data.scripts).toBe(false);
+ }
+
+ 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');
+
+ 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 () => {
+ const res = await fetch(`${base()}/api/skill?name=trip-log&scope=project`, {
+ method: 'DELETE',
+ });
+ expect(res.status).toBe(200);
+ 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 () => {
+ 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);
+
+ const moveRes = await fetch(`${base()}/api/skill`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ fromName: 'rename-me', toName: 'renamed-ok', scope: 'project' }),
+ });
+ expect(moveRes.status).toBe(200);
+
+ const after = readMarker();
+ expect(after.skills['rename-me']).toBeUndefined();
+ expect(after.skills['renamed-ok']?.hosts).toEqual(['claude']);
+ expect(existsSync(hostSkillMd('.claude', 'rename-me'))).toBe(false);
+ expect(existsSync(hostSkillMd('.claude', 'renamed-ok'))).toBe(true);
+ });
+
+ test('install of a missing skill → 404', async () => {
+ const res = await installSkill({ name: 'ghost', targets: ['claude'] });
+ expect(res.status).toBe(404);
+ });
+
+ test('install refuses the reserved open-knowledge* prefix → 400', async () => {
+ expect((await putSkill('open-knowledge-mine')).status).toBe(200);
+ const res = await installSkill({ name: 'open-knowledge-mine', targets: ['claude'] });
+ expect(res.status).toBe(400);
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.title.includes('reserved')).toBe(true);
+ });
+
+ test('install refuses a source with git conflict markers → 400', async () => {
+ const dir = join(server.contentDir, '.ok', 'skills', 'conflicted');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ '---\nname: conflicted\ndescription: d\n---\n<<<<<<< HEAD\na\n=======\nb\n>>>>>>> x\n',
+ 'utf-8',
+ );
+ const res = await installSkill({ name: 'conflicted', targets: ['claude'] });
+ expect(res.status).toBe(400);
+ expect(existsSync(hostSkillMd('.claude', 'conflicted'))).toBe(false);
+ });
+
+ test('install with no targets + none configured → 200 with a warning, nothing projected', async () => {
+ expect((await putSkill('lonely')).status).toBe(200);
+ const res = await installSkill({ name: 'lonely' });
+ expect(res.status).toBe(200);
+ const parsed = SkillInstallSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.hosts).toEqual([]);
+ 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-personal-scope.test.ts b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
new file mode 100644
index 000000000..3e0db3669
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
@@ -0,0 +1,147 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ ProblemDetailsSchema,
+ SkillGetSuccessSchema,
+ SkillsListSuccessSchema,
+} from '@inkeep/open-knowledge-core';
+import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import { createTestServer, type TestServer } from '../test-harness';
+
+let server: TestServer;
+let tmpHome: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+
+const putSkill = (body: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-personal-home-'));
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('global-scope skills', () => {
+ test('PUT global → writes under <home>/.ok/skills/', async () => {
+ const res = await putSkill({
+ scope: 'global',
+ name: 'daily-standup',
+ body: '## When\n\nEvery morning.',
+ frontmatter: { name: 'daily-standup', description: 'Use when writing a standup update.' },
+ });
+ expect(res.status).toBe(200);
+ expect(existsSync(join(tmpHome, '.ok', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);
+ });
+
+ test('GET global returns the payload', async () => {
+ const res = await fetch(`${base()}/api/skill?name=daily-standup&scope=global`);
+ expect(res.status).toBe(200);
+ const parsed = SkillGetSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.skill.scope).toBe('global');
+ expect(parsed.data.skill.frontmatter.description).toBe('Use when writing a standup update.');
+ }
+ });
+
+ test('GET /api/skills lists the global skill with scope=global', async () => {
+ await putSkill({
+ scope: 'project',
+ name: 'project-only',
+ frontmatter: { name: 'project-only', description: 'A project skill.' },
+ });
+ const res = await fetch(`${base()}/api/skills`);
+ const parsed = SkillsListSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ const personal = parsed.data.skills.find((s) => s.name === 'daily-standup');
+ const project = parsed.data.skills.find((s) => s.name === 'project-only');
+ expect(personal?.scope).toBe('global');
+ expect(project?.scope).toBe('project');
+ expect(personal?.installed).toBe(false);
+ expect(personal?.hosts).toEqual([]);
+ }
+ });
+
+ test('global history is always empty (unversioned)', async () => {
+ const res = await fetch(
+ `${base()}/api/history?docName=${encodeURIComponent('__skill__/global/daily-standup')}`,
+ );
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { entries: unknown[] };
+ expect(body.entries).toEqual([]);
+ });
+
+ test('restore on a global skill → 400 (unversioned)', async () => {
+ const res = await fetch(`${base()}/api/skill/restore`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'global', name: 'daily-standup', version: 'deadbeef' }),
+ });
+ expect(res.status).toBe(400);
+ expect(ProblemDetailsSchema.safeParse(await res.json()).success).toBe(true);
+ });
+
+ test('install a global skill → projects into the user-global host dirs', async () => {
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'global', name: 'daily-standup', targets: ['claude'] }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { hosts: string[] };
+ expect(body.hosts).toContain('claude');
+ 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 () => {
+ const res = await fetch(`${base()}/api/skills`);
+ const parsed = SkillsListSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ const personal = parsed.data.skills.find((s) => s.name === 'daily-standup');
+ expect(personal?.installed).toBe(true);
+ expect(personal?.hosts).toContain('claude');
+ }
+ });
+
+ test('uninstall demotes the global skill to Draft (source kept, projection gone)', 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);
+ expect(existsSync(join(tmpHome, '.ok', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(tmpHome, '.claude', 'skills', 'daily-standup'))).toBe(false);
+ 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([]);
+ }
+ });
+
+ test('DELETE global removes the source + its global projection', async () => {
+ const res = await fetch(`${base()}/api/skill?name=daily-standup&scope=global`, {
+ method: 'DELETE',
+ });
+ expect(res.status).toBe(200);
+ expect(existsSync(join(tmpHome, '.ok', 'skills', 'daily-standup'))).toBe(false);
+ 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
new file mode 100644
index 000000000..eecef0236
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts
@@ -0,0 +1,90 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import {
+ HistorySuccessSchema,
+ SkillGetSuccessSchema,
+ SkillRestoreSuccessSchema,
+} from '@inkeep/open-knowledge-core';
+
+const SKILL_DOC_NAME = '.ok/skills/trip-log/SKILL';
+
+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 AGENT = { agentId: 'agent-test', agentName: 'Test Agent' };
+
+const writeSkill = (body: string) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'trip-log',
+ body,
+ frontmatter: { name: 'trip-log', description: 'Use when logging a trip.' },
+ ...AGENT,
+ }),
+ });
+
+const getBody = async () => {
+ const res = await fetch(`${base()}/api/skill?name=trip-log&scope=project`);
+ const parsed = SkillGetSuccessSchema.safeParse(await res.json());
+ return parsed.success ? parsed.data.skill.body : '';
+};
+
+beforeAll(async () => {
+ server = await createTestServer();
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+});
+
+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);
+ expect(await getBody()).toContain('Version TWO');
+
+ const histRes = await fetch(
+ `${base()}/api/history?docName=${encodeURIComponent(SKILL_DOC_NAME)}`,
+ );
+ expect(histRes.status).toBe(200);
+ const hist = HistorySuccessSchema.safeParse(await histRes.json());
+ expect(hist.success).toBe(true);
+ if (!hist.success) return;
+ expect(hist.data.entries.length).toBeGreaterThanOrEqual(2);
+ const oldest = hist.data.entries[hist.data.entries.length - 1];
+ expect(oldest?.sha).toMatch(/^[0-9a-f]{40}$/);
+
+ const restoreRes = await fetch(`${base()}/api/skill/restore`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'trip-log', version: oldest?.sha, ...AGENT }),
+ });
+ expect(restoreRes.status).toBe(200);
+ const restored = SkillRestoreSuccessSchema.safeParse(await restoreRes.json());
+ expect(restored.success).toBe(true);
+ if (restored.success) expect(restored.data.restoredFiles).toContain('SKILL.md');
+
+ expect(await getBody()).toContain('Version ONE');
+ expect(await getBody()).not.toContain('Version TWO');
+ });
+
+ test('restore of a bogus version → 404', async () => {
+ const res = await fetch(`${base()}/api/skill/restore`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'trip-log', version: 'f'.repeat(40), ...AGENT }),
+ });
+ expect(res.status).toBe(404);
+ });
+
+ test('history for an unknown skill → 200 empty', async () => {
+ const res = await fetch(
+ `${base()}/api/history?docName=${encodeURIComponent('.ok/skills/ghost/SKILL')}`,
+ );
+ expect(res.status).toBe(200);
+ const parsed = HistorySuccessSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.entries).toEqual([]);
+ });
+});
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
new file mode 100644
index 000000000..20156dfc9
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
@@ -0,0 +1,134 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import { createTestServer, pollUntil, type TestServer } from '../test-harness';
+
+let server: TestServer;
+let tmpHome: string;
+const base = () => `http://127.0.0.1:${server.port}`;
+const NAME = 'trip-log';
+
+const putSkill = (scope: 'global' | 'project', name = NAME) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ scope,
+ name,
+ body: '## When\n\nLogging a trip.',
+ frontmatter: { name, description: 'Use when logging a trip.' },
+ }),
+ });
+
+const delSkill = (scope: 'global' | 'project', name = NAME) =>
+ fetch(`${base()}/api/skill?name=${name}&scope=${scope}`, { method: 'DELETE' });
+
+async function move(from: 'global' | 'project', to: 'global' | 'project') {
+ expect((await putSkill(to)).status).toBe(200);
+ expect((await delSkill(from)).status).toBe(200);
+}
+
+const putSkillFile = (scope: 'global' | 'project', name: string, path: string, content: string) =>
+ fetch(`${base()}/api/skill-file`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope, name, path, content }),
+ });
+
+async function bundleFilePaths(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?: { files?: Array<{ path?: string }> };
+ } | null;
+ return (detail?.skill?.files ?? [])
+ .map((f) => f.path)
+ .filter((p): p is string => typeof p === 'string');
+}
+
+async function moveFullBundle(from: 'global' | 'project', to: 'global' | 'project', name: string) {
+ expect((await putSkill(to, name)).status).toBe(200);
+ for (const path of await bundleFilePaths(from, name)) {
+ const read = await fetch(`${base()}/api/skill-file?name=${name}&scope=${from}&path=${path}`);
+ expect(read.ok).toBe(true);
+ const { text } = (await read.json()) as { text: string };
+ expect((await putSkillFile(to, name, path, text)).status).toBe(200);
+ }
+ expect((await delSkill(from, name)).status).toBe(200);
+}
+
+async function backlinkSources(target: string): Promise<string[]> {
+ const res = await fetch(`${base()}/api/backlinks?docName=${encodeURIComponent(target)}`);
+ const data = (await res.json()) as { backlinks?: Array<{ source: string }> };
+ return Array.isArray(data.backlinks) ? data.backlinks.map((b) => b.source) : [];
+}
+
+async function scopeOf(name: string): Promise<string | undefined> {
+ const res = await fetch(`${base()}/api/skills`);
+ const parsed = SkillsListSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ return parsed.success ? parsed.data.skills.find((s) => s.name === name)?.scope : undefined;
+}
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-scope-move-home-'));
+ server = await createTestServer({ configHomedirOverride: tmpHome });
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+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((await delSkill('global', N)).status).toBe(200);
+ expect(existsSync(join(tmpHome, '.ok', 'skills', N, 'SKILL.md'))).toBe(false);
+ expect((await putSkill('global', N)).status).toBe(200);
+ expect(existsSync(join(tmpHome, '.ok', 'skills', N, 'SKILL.md'))).toBe(true);
+ });
+
+ test('global → project → global: list shows it under global at each step', async () => {
+ expect((await putSkill('global')).status).toBe(200);
+ expect(await scopeOf(NAME)).toBe('global');
+ await move('global', 'project');
+ expect(await scopeOf(NAME)).toBe('project');
+ await move('project', 'global');
+ expect(await scopeOf(NAME)).toBe('global');
+ });
+
+ test('a cross-scope move carries references + scripts; the project .md ref rejoins the graph', async () => {
+ const N = 'bundle-move-probe';
+ expect((await putSkill('global', N)).status).toBe(200);
+ expect(
+ (await putSkillFile('global', N, 'references/notes.md', '# Notes\n\nSee [[xs-target]].\n'))
+ .status,
+ ).toBe(200);
+ const script = '#!/usr/bin/env bash\necho hi\n';
+ expect((await putSkillFile('global', N, 'scripts/run.sh', script)).status).toBe(200);
+
+ await moveFullBundle('global', 'project', N);
+
+ const projRef = join(server.contentDir, '.ok', 'skills', N, 'references', 'notes.md');
+ const projScript = join(server.contentDir, '.ok', 'skills', N, 'scripts', 'run.sh');
+ expect(existsSync(projRef)).toBe(true);
+ expect(existsSync(projScript)).toBe(true);
+ expect(readFileSync(projScript, 'utf-8')).toBe(script);
+ expect(existsSync(join(tmpHome, '.ok', 'skills', N))).toBe(false);
+ expect(await scopeOf(N)).toBe('project');
+
+ const target = await fetch(`${base()}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName: 'xs-target', markdown: '# T\n', position: 'replace' }),
+ });
+ expect(target.ok).toBe(true);
+ await pollUntil(async () =>
+ (await backlinkSources('xs-target')).includes(`.ok/skills/${N}/references/notes`),
+ );
+ }, 20000);
+});
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
new file mode 100644
index 000000000..f5bcfc56c
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts
@@ -0,0 +1,106 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ SkillTargetsGetSuccessSchema,
+ SkillTargetsPutSuccessSchema,
+} from '@inkeep/open-knowledge-core';
+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();
+ 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 () => {
+ 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);
+ });
+
+ test('PUT narrows targets → skill + bundle drop from cursor, kept in claude', async () => {
+ expect(existsSync(join(hostSkill('.cursor', 'trip-log'), 'SKILL.md'))).toBe(true);
+
+ const res = await fetch(`${base()}/api/skill-targets`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ targets: ['claude'] }),
+ });
+ 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']);
+ expect(parsed.data.bundleHosts).toEqual(['claude']);
+ }
+
+ expect(existsSync(join(hostSkill('.claude', 'trip-log'), 'SKILL.md'))).toBe(true);
+ expect(existsSync(hostSkill('.cursor', 'trip-log'))).toBe(false);
+
+ expect(existsSync(join(hostSkill('.claude', 'open-knowledge'), 'SKILL.md'))).toBe(true);
+ expect(existsSync(hostSkill('.cursor', 'open-knowledge'))).toBe(false);
+
+ const marker = JSON.parse(readFileSync(markerPath(), 'utf-8')) as {
+ skills: Record<string, { hosts: string[] }>;
+ };
+ expect(marker.skills['trip-log']?.hosts).toEqual(['claude']);
+ });
+
+ 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 () => {
+ const res = await fetch(`${base()}/api/skill-targets`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ targets: ['claude', 'cursor'] }),
+ });
+ 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);
+ });
+
+ test('PUT rejects an unknown editor id (.strict enum) → 400', async () => {
+ const res = await fetch(`${base()}/api/skill-targets`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ targets: ['claude', 'vscode'] }),
+ });
+ 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
new file mode 100644
index 000000000..efeed6ec3
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/skill.test.ts
@@ -0,0 +1,177 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import {
+ ProblemDetailsSchema,
+ SkillDeleteSuccessSchema,
+ SkillGetSuccessSchema,
+ SkillMoveSuccessSchema,
+ SkillPutSuccessSchema,
+ SkillsListSuccessSchema,
+} from '@inkeep/open-knowledge-core';
+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 putSkill = (body: Record<string, unknown>) =>
+ fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+beforeAll(async () => {
+ server = await createTestServer();
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(async () => {
+ await server.cleanup();
+});
+
+describe('skill envelope (RFC 9457) + CRUD lifecycle', () => {
+ test('PUT happy path → 200 flat success body, created:true', async () => {
+ const res = await putSkill({
+ name: 'trip-log',
+ body: '# Steps\n\nLog the trip.',
+ frontmatter: { name: 'trip-log', description: 'Use when logging a fishing trip.' },
+ });
+ expect(res.status).toBe(200);
+ expect(res.headers.get('content-type')).toBe('application/json');
+ const body = await res.json();
+ const parsed = SkillPutSuccessSchema.safeParse(body);
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.created).toBe(true);
+ expect(parsed.data.path).toBe('trip-log/SKILL.md');
+ }
+ expect((body as Record<string, unknown>).ok).toBeUndefined();
+ });
+
+ test('re-PUT the same skill → created:false (overwrite)', async () => {
+ const res = await putSkill({
+ name: 'trip-log',
+ body: '# Steps v2',
+ frontmatter: { name: 'trip-log', description: 'Use when logging a fishing trip.' },
+ });
+ expect(res.status).toBe(200);
+ const parsed = SkillPutSuccessSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.created).toBe(false);
+ });
+
+ test('PUT with an XML tag in description → 400 invalid-request', async () => {
+ const res = await putSkill({
+ name: 'bad-desc',
+ body: 'x',
+ frontmatter: { name: 'bad-desc', description: 'Use when <folder> appears.' },
+ });
+ expect(res.status).toBe(400);
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.type).toBe('urn:ok:error:invalid-request');
+ });
+
+ test('PUT with name ≠ frontmatter.name → 400', async () => {
+ const res = await putSkill({
+ name: 'trip-log',
+ body: 'x',
+ frontmatter: { name: 'other', description: 'mismatch' },
+ });
+ expect(res.status).toBe(400);
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.type).toBe('urn:ok:error:invalid-request');
+ });
+
+ test('PUT with an injected `version` key → 400 (.strict frontmatter purity)', async () => {
+ const res = await putSkill({
+ name: 'versioned',
+ body: 'x',
+ frontmatter: { name: 'versioned', description: 'has version', version: '1.0' },
+ });
+ expect(res.status).toBe(400);
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.type).toBe('urn:ok:error:invalid-request');
+ });
+
+ test('PUT with global scope → 200 (global store at <home>/.ok/skills)', async () => {
+ const res = await putSkill({
+ scope: 'global',
+ name: 'mine',
+ body: 'x',
+ frontmatter: { name: 'mine', description: 'global scope' },
+ });
+ expect(res.status).toBe(200);
+ });
+
+ test('GET one returns the skill payload', async () => {
+ const res = await fetch(`${base()}/api/skill?name=trip-log&scope=project`);
+ expect(res.status).toBe(200);
+ const parsed = SkillGetSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.skill.name).toBe('trip-log');
+ expect(parsed.data.skill.frontmatter.description).toBe('Use when logging a fishing trip.');
+ }
+ });
+
+ test('GET /api/skills lists the written skill', 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) {
+ const entry = parsed.data.skills.find((s) => s.name === 'trip-log');
+ expect(entry).toBeDefined();
+ expect(entry?.installed).toBe(false);
+ expect(entry?.hosts).toEqual([]);
+ }
+ });
+
+ test('POST rename keeps SKILL.md name in sync with the new directory', async () => {
+ const res = await fetch(`${base()}/api/skill`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', fromName: 'trip-log', toName: 'voyage-log' }),
+ });
+ expect(res.status).toBe(200);
+ const parsed = SkillMoveSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+
+ const get = await fetch(`${base()}/api/skill?name=voyage-log&scope=project`);
+ expect(get.status).toBe(200);
+ const got = SkillGetSuccessSchema.safeParse(await get.json());
+ expect(got.success && got.data.skill.frontmatter.name).toBe('voyage-log');
+
+ const old = await fetch(`${base()}/api/skill?name=trip-log&scope=project`);
+ expect(old.status).toBe(404);
+ });
+
+ test('DELETE happy path (existed=true, then false)', async () => {
+ const first = await fetch(`${base()}/api/skill?name=voyage-log&scope=project`, {
+ method: 'DELETE',
+ });
+ expect(first.status).toBe(200);
+ const parsed = SkillDeleteSuccessSchema.safeParse(await first.json());
+ expect(parsed.success && parsed.data.existed).toBe(true);
+
+ const second = await fetch(`${base()}/api/skill?name=voyage-log&scope=project`, {
+ method: 'DELETE',
+ });
+ expect(second.status).toBe(200);
+ const parsed2 = SkillDeleteSuccessSchema.safeParse(await second.json());
+ expect(parsed2.success && parsed2.data.existed).toBe(false);
+ });
+
+ test('GET on a missing skill → 404 problem+json', async () => {
+ const res = await fetch(`${base()}/api/skill?name=ghost&scope=project`);
+ expect(res.status).toBe(404);
+ expect(res.headers.get('content-type')).toBe('application/problem+json');
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.status).toBe(404);
+ });
+
+ test('method-not-allowed on PATCH → 405 + Allow header', async () => {
+ const res = await fetch(`${base()}/api/skill`, { method: 'PATCH' });
+ expect(res.status).toBe(405);
+ expect(res.headers.get('allow')).toBe('GET, PUT, POST, DELETE');
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success && parsed.data.type).toBe('urn:ok:error:method-not-allowed');
+ });
+});
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index ed6e20cab..b1c675f85 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -34,6 +34,7 @@ const REQUIRED_HANDLERS = [
'handleDuplicatePath',
'handleTrashCleanup',
'handleUploadAsset',
+ 'handleSkillUpdate',
];
const EXEMPT_HANDLERS = new Set([
@@ -57,6 +58,14 @@ const EXEMPT_HANDLERS = new Set([
'handleFolderConfig',
'handleTemplate',
'handleTemplatesList',
+ 'handleSkill',
+ 'handleSkillFile',
+ 'handleSkillsList',
+ 'handleSkillInstall',
+ 'handleSkillUninstall',
+ 'handleSkillTargets',
+ 'handleSkillsManagement',
+ 'handleSkillRestore',
'handleSuggestLinks',
'handlePageHeadings',
'handleHistory',
@@ -165,10 +174,10 @@ describe('attribution sweep coverage (FR-5, D42)', () => {
const body = extractHandlerBody(handler);
if (body === null) continue;
if (!body.includes('errorResponse(')) continue; // pre-migration; skip
- const identityIdx = Math.max(
- body.indexOf('extractAgentIdentity('),
- body.indexOf('extractActorIdentity('),
- );
+ const agentIdx = body.indexOf('extractAgentIdentity(');
+ const actorIdx = body.indexOf('extractActorIdentity(');
+ const presentIdxs = [agentIdx, actorIdx].filter((i) => i !== -1);
+ const identityIdx = presentIdxs.length === 0 ? -1 : Math.min(...presentIdxs);
if (identityIdx === -1) continue; // already failed by the prior test
const firstErrorIdx = body.indexOf('errorResponse(');
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index 9993b1e45..226dfd8c0 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -18,6 +18,11 @@ const REQUIRED_HANDLERS = [
'handleTemplatePut',
'handleTemplateDelete',
'handleTemplateMove',
+ 'handleSkill',
+ 'handleSkillPut',
+ 'handleSkillFile',
+ 'handleSkillFilePut',
+ 'handleSkillUpdate',
];
const EXEMPT_HANDLERS = new Set([
@@ -75,6 +80,12 @@ const EXEMPT_HANDLERS = new Set([
'handleHandoffDispatchRoute',
'handleInstallSkill',
'handleSkillInstallState',
+ 'handleSkillsList',
+ 'handleSkillInstall',
+ 'handleSkillUninstall',
+ 'handleSkillTargets',
+ 'handleSkillRestore',
+ 'handleSkillsManagement',
'handleSeedPlan',
'handleSeedApply',
'handleSeedPacks',
@@ -132,13 +143,17 @@ describe('conflict-gate coverage (FR9)', () => {
continue;
}
const directGate =
- body.includes('respondDocInConflict(') || body.includes('checkTemplateConflictGate(');
+ body.includes('respondDocInConflict(') ||
+ body.includes('checkTemplateConflictGate(') ||
+ body.includes('checkSkillDocConflictGate(');
const spineRouting =
body.includes('applyAgentMarkdownWrite(') || body.includes('applyAgentUndo(');
const dispatcherRouting =
body.includes('handleTemplatePut(') ||
body.includes('handleTemplateDelete(') ||
- body.includes('handleTemplateMove(');
+ body.includes('handleTemplateMove(') ||
+ body.includes('handleSkillPut(') ||
+ body.includes('handleSkillFilePut(');
if (!directGate && !spineRouting && !dispatcherRouting) {
failures.push(
`${handler}: missing conflict gate — must call respondDocInConflict(...) directly, route through applyAgentMarkdownWrite/applyAgentUndo, or dispatch to a gated sub-handler`,
diff --git a/packages/app/tests/integration/global-skill-bundle-graph.test.ts b/packages/app/tests/integration/global-skill-bundle-graph.test.ts
new file mode 100644
index 000000000..7c4fc562a
--- /dev/null
+++ b/packages/app/tests/integration/global-skill-bundle-graph.test.ts
@@ -0,0 +1,90 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { createTestServer, type TestServer } from './test-harness.ts';
+
+describe('global skill bundle graph participation', () => {
+ let server: TestServer;
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+ const base = () => `http://127.0.0.1:${server.port}`;
+
+ async function putGlobalSkill(name: string, body: string): Promise<void> {
+ const res = await fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name,
+ scope: 'global',
+ body,
+ frontmatter: { name, description: 'a global skill with bundle refs' },
+ }),
+ });
+ if (!res.ok) throw new Error(`global skill PUT failed: ${res.status} ${await res.text()}`);
+ }
+
+ async function putGlobalSkillFile(name: string, path: string, content: string): Promise<void> {
+ const res = await fetch(`${base()}/api/skill-file`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, scope: 'global', path, content }),
+ });
+ if (!res.ok) throw new Error(`global skill-file PUT failed: ${res.status} ${await res.text()}`);
+ }
+
+ async function rescan(): Promise<void> {
+ const res = await fetch(`${base()}/api/test-rescan-backlinks`, { method: 'POST' });
+ if (!res.ok) throw new Error(`rescan failed: ${res.status} ${await res.text()}`);
+ }
+
+ async function fullGraph(): Promise<{
+ nodes: Array<{ id: string }>;
+ links: Array<{ source: string; target: string }>;
+ }> {
+ const res = await fetch(`${base()}/api/link-graph`);
+ const data = (await res.json()) as {
+ nodes?: Array<{ id: string }>;
+ links?: Array<{ source: string; target: string }>;
+ };
+ return { nodes: data.nodes ?? [], links: data.links ?? [] };
+ }
+
+ async function backlinkSources(target: string): Promise<string[]> {
+ const res = await fetch(`${base()}/api/backlinks?docName=${encodeURIComponent(target)}`);
+ const data = (await res.json()) as { backlinks?: Array<{ source: string }> };
+ return Array.isArray(data.backlinks) ? data.backlinks.map((b) => b.source) : [];
+ }
+
+ test('a global SKILL connects to its references and never into the project KB', async () => {
+ const skillNode = '__skill__/global/demo/references/notes';
+ const skillDoc = '__skill__/global/demo';
+
+ const seed = await fetch(`${base()}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName: 'architecture',
+ markdown: '# Architecture\n',
+ position: 'replace',
+ }),
+ });
+ expect(seed.ok).toBe(true);
+
+ await putGlobalSkill('demo', '# Demo\n\nDetails in `references/notes.md`.\n');
+ await putGlobalSkillFile('demo', 'references/notes.md', '# Notes\n\nSee [[architecture]].\n');
+ await rescan();
+
+ const graph = await fullGraph();
+ const ids = new Set(graph.nodes.map((n) => n.id));
+ expect(ids.has(skillDoc)).toBe(true);
+ expect(ids.has(skillNode)).toBe(true);
+ expect(graph.links).toEqual(expect.arrayContaining([{ source: skillDoc, target: skillNode }]));
+
+ expect(graph.links).not.toEqual(
+ expect.arrayContaining([{ source: skillNode, target: 'architecture' }]),
+ );
+ expect(await backlinkSources('architecture')).not.toContain(skillNode);
+ }, 20000);
+});
diff --git a/packages/app/tests/integration/managed-artifact-doc.test.ts b/packages/app/tests/integration/managed-artifact-doc.test.ts
new file mode 100644
index 000000000..2c99cde1e
--- /dev/null
+++ b/packages/app/tests/integration/managed-artifact-doc.test.ts
@@ -0,0 +1,184 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createTestClient, createTestServer, type TestServer } from './test-harness.ts';
+
+describe('skill + template CRDT docs — end to end', () => {
+ let server: TestServer;
+
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+
+ async function pollFor(path: string, timeoutMs = 3000): Promise<boolean> {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (existsSync(path)) return true;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ return existsSync(path);
+ }
+
+ test('editing a project skill content doc persists Y.Text verbatim to .ok/skills/<n>/SKILL.md', async () => {
+ const docName = '.ok/skills/demo-skill/SKILL';
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+
+ const src = '---\nname: demo-skill\ndescription: a demo\n---\n\n# Demo\n\nBody.\n';
+ client.doc.transact(() => client.ytext.insert(0, src));
+
+ const skillFile = resolve(server.contentDir, '.ok', 'skills', 'demo-skill', 'SKILL.md');
+ expect(await pollFor(skillFile)).toBe(true);
+ expect(readFileSync(skillFile, 'utf-8')).toBe(src);
+
+ await client.cleanup();
+ });
+
+ test('a project skill on disk loads its content into a fresh client', async () => {
+ const docName = '.ok/skills/roundtrip/SKILL';
+ const src = '---\nname: roundtrip\ndescription: rt\n---\n\nHello.\n';
+
+ const skillFile = resolve(server.contentDir, '.ok', 'skills', 'roundtrip', 'SKILL.md');
+ mkdirSync(resolve(skillFile, '..'), { recursive: true });
+ writeFileSync(skillFile, src, 'utf-8');
+
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+ const start = Date.now();
+ while (Date.now() - start < 3000 && client.ytext.toString() !== src) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(client.ytext.toString()).toBe(src);
+ await client.cleanup();
+ });
+
+ test('an external SKILL.md disk edit reconciles into the open project skill doc', async () => {
+ await server.cleanup();
+ const seedDir = mkdtempSync(join(tmpdir(), 'ok-skill-reconcile-'));
+ mkdirSync(resolve(seedDir, '.ok'), { recursive: true });
+ writeFileSync(resolve(seedDir, '.ok', 'config.yml'), '', 'utf-8');
+ const skillFile = resolve(seedDir, '.ok', 'skills', 'watched', 'SKILL.md');
+ const src = '---\nname: watched\ndescription: initial\n---\n\n# Watched\n\nv1.\n';
+ mkdirSync(resolve(skillFile, '..'), { recursive: true });
+ writeFileSync(skillFile, src, 'utf-8');
+ server = await createTestServer({ contentDir: seedDir });
+
+ const docName = '.ok/skills/watched/SKILL';
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+ const loadStart = Date.now();
+ while (Date.now() - loadStart < 5000 && client.ytext.toString() !== src) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(client.ytext.toString()).toBe(src);
+
+ const edited = '---\nname: watched\ndescription: edited externally\n---\n\n# Watched\n\nv2.\n';
+ const start = Date.now();
+ while (Date.now() - start < 15000 && client.ytext.toString() !== edited) {
+ writeFileSync(skillFile, edited, 'utf-8');
+ await new Promise((r) => setTimeout(r, 200));
+ }
+ expect(client.ytext.toString()).toBe(edited);
+
+ 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`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'put-routed',
+ body: '# Routed\n\nVia CRDT.\n',
+ frontmatter: { name: 'put-routed', description: 'Use when proving the CRDT write path.' },
+ }),
+ });
+ expect(res.status).toBe(200);
+
+ const expected =
+ '---\nname: put-routed\ndescription: Use when proving the CRDT write path.\n---\n# Routed\n\nVia CRDT.\n';
+ const start = Date.now();
+ while (Date.now() - start < 5000 && client.ytext.toString() !== expected) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ 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();
+ });
+
+ test('a __template__ doc persists folder-addressed to <folder>/.ok/templates/<name>.md', async () => {
+ const docName = '__template__/daily-note';
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+
+ const src = '---\ntitle: Daily Note\ndescription: a daily note\n---\n\n# {{date}}\n\nNotes.\n';
+ client.doc.transact(() => client.ytext.insert(0, src));
+
+ const tplFile = resolve(server.contentDir, '.ok', 'templates', 'daily-note.md');
+ expect(await pollFor(tplFile)).toBe(true);
+ expect(readFileSync(tplFile, 'utf-8')).toBe(src);
+
+ await client.cleanup();
+ });
+
+ test('PUT /api/template routes the body through the open CRDT doc (Slice E)', async () => {
+ const docName = '__template__/notes/meeting';
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/template`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ folder: 'notes',
+ name: 'meeting',
+ body: '# Agenda\n\n- item\n',
+ frontmatter: { title: 'Meeting', description: 'Use for meeting notes.' },
+ }),
+ });
+ expect(res.status).toBe(200);
+
+ const expected =
+ '---\ntemplate:\n title: Meeting\n description: Use for meeting notes.\n---\n# Agenda\n\n- item\n';
+ const start = Date.now();
+ while (Date.now() - start < 5000 && client.ytext.toString() !== expected) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ expect(client.ytext.toString()).toBe(expected);
+
+ const tplFile = resolve(server.contentDir, 'notes', '.ok', 'templates', 'meeting.md');
+ expect(await pollFor(tplFile)).toBe(true);
+ expect(readFileSync(tplFile, 'utf-8')).toBe(expected);
+
+ await client.cleanup();
+ });
+
+ test('an external template .md disk edit reconciles into the open doc (root folder)', async () => {
+ const docName = '__template__/daily';
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+
+ const src = '---\ntitle: Daily\ndescription: initial\n---\n\n# {{date}}\n';
+ client.doc.transact(() => client.ytext.insert(0, src));
+ const tplFile = resolve(server.contentDir, '.ok', 'templates', 'daily.md');
+ expect(await pollFor(tplFile)).toBe(true);
+
+ const edited =
+ '---\ntitle: Daily\ndescription: edited externally\n---\n\n# {{date}}\n\nMore.\n';
+ mkdirSync(resolve(server.contentDir, '.ok', 'templates'), { recursive: true });
+ writeFileSync(tplFile, edited, 'utf-8');
+
+ const start = Date.now();
+ while (Date.now() - start < 5000 && client.ytext.toString() !== edited) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(client.ytext.toString()).toBe(edited);
+
+ 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
new file mode 100644
index 000000000..de160a467
--- /dev/null
+++ b/packages/app/tests/integration/skill-bundle-files.test.ts
@@ -0,0 +1,176 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
+
+describe('skill bundle files via /api/skill-file', () => {
+ let server: TestServer;
+
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+
+ const base = () => `http://127.0.0.1:${server.port}`;
+
+ async function putSkill(name: string, description: string, body: string): Promise<void> {
+ 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()}`);
+ }
+
+ async function putSkillFile(name: string, path: string, content: string) {
+ const res = await fetch(`${base()}/api/skill-file`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, scope: 'project', path, content }),
+ });
+ return res;
+ }
+
+ 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 refRes = await putSkillFile(
+ 'demo',
+ 'references/notes.md',
+ '# Notes\n\nSee [[target-doc]] for context.\n',
+ );
+ expect(refRes.ok).toBe(true);
+ const refBody = (await refRes.json()) as { kind: string; content: boolean; path: string };
+ expect(refBody.kind).toBe('reference');
+ expect(refBody.content).toBe(true);
+
+ const refFile = resolve(server.contentDir, '.ok', 'skills', 'demo', 'references', 'notes.md');
+ await pollUntil(() => existsSync(refFile));
+ expect(readFileSync(refFile, 'utf-8')).toContain('[[target-doc]]');
+
+ const target = await fetch(`${base()}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName: 'target-doc',
+ markdown: '# Target\n\nBody.\n',
+ position: 'replace',
+ }),
+ });
+ expect(target.ok).toBe(true);
+
+ await pollUntil(async () => {
+ const res = await fetch(`${base()}/api/backlinks?docName=target-doc`);
+ 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')
+ );
+ });
+ });
+
+ async function renameSkill(fromName: string, toName: string) {
+ const res = await fetch(`${base()}/api/skill`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', fromName, toName }),
+ });
+ return res;
+ }
+
+ async function backlinkSources(target: string): Promise<string[]> {
+ const res = await fetch(`${base()}/api/backlinks?docName=${encodeURIComponent(target)}`);
+ const data = (await res.json()) as { backlinks?: Array<{ source: string }> };
+ return Array.isArray(data.backlinks) ? data.backlinks.map((b) => b.source) : [];
+ }
+
+ 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 refRes = await putSkillFile(
+ 'demo3',
+ 'references/notes.md',
+ '# Notes\n\nSee [[move-target]] for context.\n',
+ );
+ expect(refRes.ok).toBe(true);
+
+ const target = await fetch(`${base()}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName: 'move-target', markdown: '# Target\n', position: 'replace' }),
+ });
+ expect(target.ok).toBe(true);
+
+ await pollUntil(async () =>
+ (await backlinkSources('move-target')).includes('.ok/skills/demo3/references/notes'),
+ );
+
+ const moved = await renameSkill('demo3', 'demo3-renamed');
+ expect(moved.ok).toBe(true);
+
+ await pollUntil(async () =>
+ (await backlinkSources('move-target')).includes('.ok/skills/demo3-renamed/references/notes'),
+ );
+ const sources = await backlinkSources('move-target');
+ expect(sources).not.toContain('.ok/skills/demo3/references/notes');
+ }, 20000);
+
+ test('a script round-trips through the universal per-file read (no native cat)', async () => {
+ await putSkill('runner', 'runs things', '# Runner\n');
+ const scriptText = '#!/usr/bin/env bash\nset -euo pipefail\necho "hello from a skill script"\n';
+ const put = await putSkillFile('runner', 'scripts/run.sh', scriptText);
+ expect(put.ok).toBe(true);
+ const putBody = (await put.json()) as { kind: string; content: boolean };
+ expect(putBody.kind).toBe('script');
+ expect(putBody.content).toBe(false);
+
+ const params = new URLSearchParams({
+ name: 'runner',
+ scope: 'project',
+ path: 'scripts/run.sh',
+ });
+ const get = await fetch(`${base()}/api/skill-file?${params.toString()}`);
+ expect(get.ok).toBe(true);
+ const got = (await get.json()) as { path: string; kind: string; text: string };
+ expect(got.kind).toBe('script');
+ expect(got.text).toBe(scriptText);
+ });
+
+ test('a .mdx reference opens when requested as .md (extension-less node fallback)', async () => {
+ 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',
+ );
+ await pollUntil(() => existsSync(onDisk));
+
+ const params = new URLSearchParams({
+ name: 'mdxskill',
+ scope: 'project',
+ path: 'references/guide.md',
+ });
+ const get = await fetch(`${base()}/api/skill-file?${params.toString()}`);
+ expect(get.ok).toBe(true);
+ const got = (await get.json()) as { path: string; kind: string; text: string };
+ expect(got.text).toContain('MDX body.');
+ expect(got.path).toBe('references/guide.mdx');
+ expect(got.kind).toBe('reference');
+ });
+
+ 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');
+ expect(escaping.status).toBe(400);
+
+ const ghost = await putSkillFile('ghost-skill', 'references/x.md', 'x');
+ expect(ghost.status).toBe(404);
+ });
+});
diff --git a/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts b/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
new file mode 100644
index 000000000..2ab6b5dfd
--- /dev/null
+++ b/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
+
+describe('skill SKILL.md → references/<x> inbound backlink (live index)', () => {
+ let server: TestServer;
+ beforeEach(async () => {
+ server = await createTestServer();
+ });
+ afterEach(async () => {
+ await server.cleanup();
+ });
+ const base = () => `http://127.0.0.1:${server.port}`;
+
+ async function putSkill(name: string, body: string): Promise<void> {
+ const res = await fetch(`${base()}/api/skill`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name,
+ scope: 'project',
+ body,
+ frontmatter: { name, description: 'a skill with bundle refs' },
+ }),
+ });
+ if (!res.ok) throw new Error(`skill PUT failed: ${res.status} ${await res.text()}`);
+ }
+ async function putSkillFile(name: string, path: string, content: string) {
+ return fetch(`${base()}/api/skill-file`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, scope: 'project', path, content }),
+ });
+ }
+ async function backlinkSources(target: string): Promise<string[]> {
+ const res = await fetch(`${base()}/api/backlinks?docName=${encodeURIComponent(target)}`);
+ const data = (await res.json()) as { backlinks?: Array<{ source: string }> };
+ return Array.isArray(data.backlinks) ? data.backlinks.map((b) => b.source) : [];
+ }
+
+ async function graphNeighborhood(
+ docName: string,
+ ): Promise<{ nodes: Array<{ id: string }>; links: Array<{ source: string; target: string }> }> {
+ const res = await fetch(
+ `${base()}/api/link-graph?docName=${encodeURIComponent(docName)}&degrees=1`,
+ );
+ const data = (await res.json()) as {
+ nodes?: Array<{ id: string }>;
+ links?: Array<{ source: string; target: string }>;
+ };
+ return { nodes: data.nodes ?? [], links: data.links ?? [] };
+ }
+
+ 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';
+
+ 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));
+
+ expect(await backlinkSources('references/notes')).not.toContain(skillDoc);
+
+ const graph = await graphNeighborhood(skillDoc);
+ expect(graph.nodes.map((n) => n.id)).toEqual(expect.arrayContaining([skillDoc, refDoc]));
+ expect(graph.links).toEqual(expect.arrayContaining([{ source: skillDoc, target: refDoc }]));
+ }, 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';
+
+ 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));
+ }, 20000);
+});
diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.ts
index d4b878713..79c58c354 100644
--- a/packages/app/tests/integration/test-harness.ts
+++ b/packages/app/tests/integration/test-harness.ts
@@ -89,6 +89,7 @@ export interface CreateTestServerOptions {
gitEnabled?: boolean;
commitDebounceMs?: number;
localOpCliArgs?: string[];
+ configHomedirOverride?: string;
ephemeral?: boolean;
projectDir?: string;
singleDocRelPath?: string;
@@ -102,6 +103,11 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
options.contentDir !== undefined
? realpathSync(options.contentDir)
: realpathSync(mkdtempSync(join(tmpdir(), 'ok-test-')));
+ const ownedHomeDir =
+ options.configHomedirOverride === undefined
+ ? realpathSync(mkdtempSync(join(tmpdir(), 'ok-test-home-')))
+ : null;
+ const homeOverride = options.configHomedirOverride ?? (ownedHomeDir as string);
const createdProjectDir = ephemeral && options.projectDir === undefined;
const projectDir = ephemeral
@@ -133,6 +139,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
contentRoot: options.gitEnabled === true ? '.' : undefined,
enableTestRoutes: true,
localOpCliArgs: options.localOpCliArgs,
+ configHomedirOverride: homeOverride,
mdManager: options.mdManager,
...(ephemeral ? { ephemeral: true, singleDocRelPath: options.singleDocRelPath } : {}),
skipStateManifestCheck: true,
@@ -191,6 +198,9 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
if (!options.keepContentDir) {
rmSync(contentDir, { recursive: true, force: true });
}
+ if (ownedHomeDir !== null) {
+ rmSync(ownedHomeDir, { recursive: true, force: true });
+ }
},
};
}
diff --git a/packages/app/tests/stress/file-tree-deselect-to-root.e2e.ts b/packages/app/tests/stress/file-tree-deselect-to-root.e2e.ts
index f82bc1c6c..deb6f9125 100644
--- a/packages/app/tests/stress/file-tree-deselect-to-root.e2e.ts
+++ b/packages/app/tests/stress/file-tree-deselect-to-root.e2e.ts
@@ -17,11 +17,11 @@ import { expect, resetContentToFixtureBaseline, test } from './_helpers';
const SIDEBAR = '[data-slot="sidebar-container"]';
async function clickEmptyTreeArea(page: Page): Promise<void> {
- const scroll = page.locator('[data-file-tree-virtualized-scroll]');
- await expect(scroll).toBeVisible();
- const box = await scroll.boundingBox();
- if (!box) throw new Error('tree scroll container has no bounding box');
- await page.mouse.click(box.x + box.width / 2, box.y + box.height - 8);
+ const filler = page.locator('[data-sidebar-empty-deselect]');
+ await expect(filler).toBeVisible();
+ const box = await filler.boundingBox();
+ if (!box) throw new Error('sidebar deselect filler has no bounding box');
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
}
async function createFileAndGetDocName(
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 710b6b25b..77c3c5a25 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -33,7 +33,7 @@
"scripts": {
"build:cli": "tsdown",
"build:app": "cp -r ../app/dist dist/public",
- "build:skill-asset": "bun ../server/scripts/build-skill-bundles.ts && mkdir -p dist/assets/skills && cp -R ../server/dist/assets/skills/discovery ../server/dist/assets/skills/project dist/assets/skills/ && if [ -d ../server/dist/assets/skills/packs ]; then cp -R ../server/dist/assets/skills/packs dist/assets/skills/; fi",
+ "build:skill-asset": "bun ../server/scripts/build-skill-bundles.ts && mkdir -p dist/assets/skills && cp -R ../server/dist/assets/skills/. dist/assets/skills/",
"build:notices": "mkdir -p dist && cp ../../THIRD_PARTY_NOTICES.md dist/THIRD_PARTY_NOTICES.md",
"build:license": "mkdir -p dist && cp ../../LICENSE dist/LICENSE",
"build:schema": "bun --conditions=development scripts/build-config-schema.mjs",
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 136aac93a..45bb0a102 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -18,11 +18,11 @@ import { bugReportCommand } from './commands/bug-report.ts';
import { cleanCommand } from './commands/clean.ts';
import { cloneCommand } from './commands/clone.ts';
import { configCommand } from './commands/config.ts';
+import { coworkCommand } from './commands/cowork.ts';
import { createRealDetectDeps, detectDesktop, launchDesktop } from './commands/desktop-dispatch.ts';
import { diagnoseCommand } from './commands/diagnose.ts';
import { embeddingsCommand } from './commands/embeddings/index.ts';
import { initCommand } from './commands/init.ts';
-import { installSkillCommand } from './commands/install-skill.ts';
import { mcpCommand } from './commands/mcp.ts';
import { openCommand } from './commands/open.ts';
import { previewCommand } from './commands/preview.ts';
@@ -39,6 +39,7 @@ import {
scanRootArgv,
} from './commands/single-file-dispatch.ts';
import { createRealSingleFileOpenDeps, runSingleFileOpen } from './commands/single-file-open.ts';
+import { skillsCommand } from './commands/skills.ts';
import { runStartCommand, startCommand } from './commands/start.ts';
import { statusCommand } from './commands/status.ts';
import { stopCommand } from './commands/stop.ts';
@@ -128,10 +129,12 @@ program.addCommand(initCommand());
program.addCommand(seedCommand());
-program.addCommand(installSkillCommand());
+program.addCommand(coworkCommand(), { hidden: true });
program.addCommand(repairSkillsCommand());
+program.addCommand(skillsCommand());
+
const preview = previewCommand(() => resolvedConfig);
program.addCommand(preview);
diff --git a/packages/cli/src/commands/install-skill.test.ts b/packages/cli/src/commands/cowork.test.ts
similarity index 90%
rename from packages/cli/src/commands/install-skill.test.ts
rename to packages/cli/src/commands/cowork.test.ts
index 21364126e..7dea590d1 100644
--- a/packages/cli/src/commands/install-skill.test.ts
+++ b/packages/cli/src/commands/cowork.test.ts
@@ -3,7 +3,7 @@ import type { spawn } from 'node:child_process';
import { existsSync, mkdtempSync, rmSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { runInstallSkill } from './install-skill.ts';
+import { runCoworkSkill } from './cowork.ts';
function makeFakeSpawn(capture: {
command?: string;
@@ -23,11 +23,11 @@ function stripAnsi(s: string): string {
return s.replace(/\[[0-9;]*m/g, '');
}
-describe('runInstallSkill', () => {
+describe('runCoworkSkill', () => {
let testDir: string;
beforeEach(() => {
- testDir = mkdtempSync(join(tmpdir(), 'install-skill-test-'));
+ testDir = mkdtempSync(join(tmpdir(), 'cowork-skill-test-'));
});
afterEach(() => {
@@ -36,7 +36,7 @@ describe('runInstallSkill', () => {
it('builds to the provided --out path and exits without opening (--no-open)', async () => {
const outPath = join(testDir, 'my-custom.skill');
- const result = await runInstallSkill({ out: outPath, home: testDir, noOpen: true });
+ const result = await runCoworkSkill({ out: outPath, home: testDir, noOpen: true });
expect(result.status).toBe('built');
expect(result.exitCode).toBe(0);
@@ -52,7 +52,7 @@ describe('runInstallSkill', () => {
it('spawns `open` on darwin when opening is allowed', async () => {
const outPath = join(testDir, 'darwin.skill');
const capture: { command?: string; args?: readonly string[] } = {};
- const result = await runInstallSkill({
+ const result = await runCoworkSkill({
out: outPath,
home: testDir,
platformName: 'darwin',
@@ -71,7 +71,7 @@ describe('runInstallSkill', () => {
it('spawns `cmd /c start` on win32', async () => {
const outPath = join(testDir, 'win32.skill');
const capture: { command?: string; args?: readonly string[] } = {};
- const result = await runInstallSkill({
+ const result = await runCoworkSkill({
out: outPath,
home: testDir,
platformName: 'win32',
@@ -88,7 +88,7 @@ describe('runInstallSkill', () => {
it('spawns `xdg-open` on linux', async () => {
const outPath = join(testDir, 'linux.skill');
const capture: { command?: string; args?: readonly string[] } = {};
- const result = await runInstallSkill({
+ const result = await runCoworkSkill({
out: outPath,
home: testDir,
platformName: 'linux',
@@ -101,7 +101,7 @@ describe('runInstallSkill', () => {
it('falls back to `built` with a helpful message on unsupported platforms', async () => {
const outPath = join(testDir, 'aix.skill');
- const result = await runInstallSkill({
+ const result = await runCoworkSkill({
out: outPath,
home: testDir,
platformName: 'aix' as NodeJS.Platform,
@@ -118,7 +118,7 @@ describe('runInstallSkill', () => {
it('surfaces spawn errors as `built` (non-fatal)', async () => {
const outPath = join(testDir, 'spawn-error.skill');
- const result = await runInstallSkill({
+ const result = await runCoworkSkill({
out: outPath,
home: testDir,
platformName: 'darwin',
diff --git a/packages/cli/src/commands/install-skill.ts b/packages/cli/src/commands/cowork.ts
similarity index 89%
rename from packages/cli/src/commands/install-skill.ts
rename to packages/cli/src/commands/cowork.ts
index 9aafc6d87..7f5e525ef 100644
--- a/packages/cli/src/commands/install-skill.ts
+++ b/packages/cli/src/commands/cowork.ts
@@ -6,7 +6,7 @@ import {
import { Command } from 'commander';
import { accent, dim, error as errorColor, info, success, warning } from '../ui/colors.ts';
-interface InstallSkillCommandOptions {
+interface BuildDesktopSkillOptions {
out?: string;
noOpen?: boolean;
/** Bypass the install-state gate and rebuild unconditionally. When Claude
@@ -20,7 +20,7 @@ interface InstallSkillCommandOptions {
home?: string;
}
-interface InstallSkillCliResult extends BuildAndOpenSkillResult {
+interface BuildDesktopSkillCliResult extends BuildAndOpenSkillResult {
message: string;
exitCode: number;
}
@@ -76,9 +76,9 @@ function formatFailedMessage(result: BuildAndOpenSkillResult): string {
return `${errorColor('Error:')} ${result.buildError ?? 'unknown build failure'}`;
}
-export async function runInstallSkill(
- opts: InstallSkillCommandOptions = {},
-): Promise<InstallSkillCliResult> {
+export async function runCoworkSkill(
+ opts: BuildDesktopSkillOptions = {},
+): Promise<BuildDesktopSkillCliResult> {
const result = await buildAndOpenSkill(opts);
if (result.status === 'failed') {
@@ -93,16 +93,16 @@ export async function runInstallSkill(
return { ...result, message: formatBuiltMessage(result), exitCode: 0 };
}
-export function installSkillCommand(): Command {
- return new Command('install-skill')
+export function coworkCommand(): Command {
+ return new Command('cowork')
.description(
- 'Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. Not needed for Claude — `ok init` covers that separately.',
+ 'Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. (Advanced/rarely needed — `ok init` already wires Claude.)',
)
.option('--out <path>', 'Custom output path (default: ~/Downloads/openknowledge.skill)')
.option('--no-open', 'Build the file but skip the OS file-association handoff')
.option('--force', 'Bypass the install-state gate and rebuild unconditionally')
.action(async (cliOpts: { out?: string; open: boolean; force?: boolean }) => {
- const result = await runInstallSkill({
+ const result = await runCoworkSkill({
out: cliOpts.out,
noOpen: !cliOpts.open,
force: cliOpts.force ?? false,
diff --git a/packages/cli/src/commands/editor-targets-lockstep.test.ts b/packages/cli/src/commands/editor-targets-lockstep.test.ts
new file mode 100644
index 000000000..56277cb0a
--- /dev/null
+++ b/packages/cli/src/commands/editor-targets-lockstep.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, test } from 'bun:test';
+import { ALL_EDITOR_IDS, EDITOR_PROJECT_SKILL_ROOT } from '@inkeep/open-knowledge-core';
+import { EDITOR_TARGETS } from './editors.ts';
+
+describe('EDITOR_TARGETS project-skill path lockstep with core root', () => {
+ const cwd = '/tmp/proj';
+
+ for (const id of ALL_EDITOR_IDS) {
+ test(`${id}: projectSkillPath agrees with EDITOR_PROJECT_SKILL_ROOT`, () => {
+ const root = EDITOR_PROJECT_SKILL_ROOT[id];
+ const builder = EDITOR_TARGETS[id].projectSkillPath;
+ if (root === null) {
+ expect(builder).toBeUndefined();
+ return;
+ }
+ expect(builder).toBeDefined();
+ const got = builder?.(cwd).split(/[\\/]/).join('/');
+ expect(got?.startsWith(`${cwd}/${root}/`)).toBe(true);
+ expect(got?.endsWith('/SKILL.md')).toBe(true);
+ });
+ }
+});
diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.ts
index 4796ae9e2..83110415b 100644
--- a/packages/cli/src/commands/editors.ts
+++ b/packages/cli/src/commands/editors.ts
@@ -3,6 +3,7 @@ import { basename, dirname, join, posix, resolve, sep, win32 } from 'node:path';
import {
ALL_EDITOR_IDS as CORE_ALL_EDITOR_IDS,
EDITOR_LABELS as CORE_EDITOR_LABELS,
+ HOSTS_WITH_USER_SKILL_DIR as CORE_HOSTS_WITH_USER_SKILL_DIR,
type EditorId as CoreEditorId,
} from '@inkeep/open-knowledge-core';
import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
@@ -10,6 +11,9 @@ import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
export type EditorId = CoreEditorId;
export const ALL_EDITOR_IDS: readonly EditorId[] = CORE_ALL_EDITOR_IDS;
export const EDITOR_LABELS: Record<EditorId, string> = CORE_EDITOR_LABELS;
+/** Re-export of core's derived list — the host-dir sweep set for `repair-skills`
+ * (CLI) + `skill-reclaim` (desktop). Both import it from the package surface. */
+export const HOSTS_WITH_USER_SKILL_DIR = CORE_HOSTS_WITH_USER_SKILL_DIR;
const DEV_MCP_SERVER_COMMAND = 'node';
const DEV_MCP_ENV = {
@@ -282,7 +286,7 @@ export const EDITOR_TARGETS: Record<EditorId, EditorMcpTarget> = {
scope: 'global',
detectPath: (_cwd, home) => dirname(resolveCodexConfigPath({ home })),
projectConfigPath: (cwd) => join(cwd, '.codex', 'config.toml'),
- projectSkillPath: (cwd) => join(cwd, '.agents', 'skills', 'open-knowledge', 'SKILL.md'),
+ projectSkillPath: (cwd) => join(cwd, '.codex', 'skills', 'open-knowledge', 'SKILL.md'),
},
opencode: {
id: 'opencode',
@@ -295,7 +299,7 @@ export const EDITOR_TARGETS: Record<EditorId, EditorMcpTarget> = {
scope: 'global',
detectPath: (_cwd, home) => dirname(resolveOpenCodeConfigPath({ home })),
projectConfigPath: (cwd) => join(cwd, 'opencode.json'),
- projectSkillPath: (cwd) => join(cwd, '.agents', 'skills', 'open-knowledge', 'SKILL.md'),
+ projectSkillPath: (cwd) => join(cwd, '.opencode', 'skills', 'open-knowledge', 'SKILL.md'),
},
};
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index f2db7f0a6..da2b2a3eb 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -515,12 +515,17 @@ describe('runInit', () => {
expect(config.mcp[result.editors[0].serverName]).toEqual(PUBLISHED_OPENCODE_ENTRY);
});
- it('writes the shared .agents/skills/ skill once when Codex + OpenCode are both selected', async () => {
+ it('writes a distinct project skill for Codex and OpenCode in their own dirs', async () => {
const result = await runInitForTest({ editors: ['codex', 'opencode'], scope: 'project' });
- const sharedSkill = join(testDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md');
- const sharedEntries = result.projectSkills.filter((s) => s.path === sharedSkill);
- expect(sharedEntries).toHaveLength(1);
- expect(existsSync(sharedSkill)).toBe(true);
+ const codexSkill = join(testDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md');
+ const opencodeSkill = join(testDir, '.opencode', 'skills', 'open-knowledge', 'SKILL.md');
+ expect(result.projectSkills.some((s) => s.path === codexSkill)).toBe(true);
+ expect(result.projectSkills.some((s) => s.path === opencodeSkill)).toBe(true);
+ expect(existsSync(codexSkill)).toBe(true);
+ expect(existsSync(opencodeSkill)).toBe(true);
+ expect(existsSync(join(testDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ false,
+ );
});
});
@@ -601,36 +606,14 @@ describe('runInit', () => {
);
});
- it('flags claudeDesktopDetected=true when Claude config dir exists', async () => {
- mkdirSync(dirname(resolveClaudeDesktopConfigPath({ home: fakeHome })), { recursive: true });
-
- const result = await runInitForTest();
-
- expect(result.claudeDesktopDetected).toBe(true);
- });
-
- it('flags claudeDesktopDetected=false when Claude config dir is absent', async () => {
- const result = await runInitForTest();
-
- expect(result.claudeDesktopDetected).toBe(false);
- });
-
- it('renders the Cowork install hint when Claude Desktop is detected', async () => {
+ it('does NOT advertise the Cowork bundle, even when Claude Desktop is present', async () => {
mkdirSync(dirname(resolveClaudeDesktopConfigPath({ home: fakeHome })), { recursive: true });
const result = await runInitForTest();
const output = formatInitResult(result, testDir);
- expect(output).toContain('Claude Desktop App detected.');
- expect(output).toContain('Claude Chat & Cowork');
- expect(output).toContain('ok install-skill');
- });
-
- it('omits the Cowork install hint when Claude Desktop is absent', async () => {
- const result = await runInitForTest();
- const output = formatInitResult(result, testDir);
-
- expect(output).not.toContain('Claude Desktop detected. For Cowork:');
+ expect(output).not.toContain('ok cowork');
+ expect(output).not.toContain('Claude Chat & Cowork');
expect(output).not.toContain('openknowledge.skill');
});
});
@@ -1307,14 +1290,14 @@ describe('runInit', () => {
expect.objectContaining({
editorId: 'codex',
action: 'written',
- path: join(testDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md'),
+ path: join(testDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md'),
}),
]),
);
expect(existsSync(join(testDir, '.cursor', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
true,
);
- expect(existsSync(join(testDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ expect(existsSync(join(testDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
true,
);
});
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index fd910a3ac..5453dc425 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -6,7 +6,6 @@ import type {
InstallUserSkillResult,
} from '@inkeep/open-knowledge-server';
import {
- detectClaudeDesktopPresence,
ensureProjectGit,
initContent,
installUserSkill,
@@ -227,7 +226,6 @@ interface InitCommandResult {
* Only set when `didGitInit` is also `true` AND no `.gitignore` was already
* present at `projectRoot` — pre-existing files are never touched. */
rootGitignoreCreated: boolean;
- claudeDesktopDetected: boolean;
mcpAction: 'written' | 'overwritten' | 'skipped-missing' | 'skipped-flag' | 'failed';
mcpPath: string;
mcpError?: string;
@@ -618,7 +616,6 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
legacyProjectConfigs: [],
didGitInit: gitResult.didInit,
rootGitignoreCreated: false,
- claudeDesktopDetected: false,
mcpAction: 'failed',
mcpPath: fallbackPath,
mcpError: `Content scaffolding failed: ${err instanceof Error ? err.message : String(err)}`,
@@ -726,8 +723,6 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
const installSkill = options.installUserSkill ?? installUserSkill;
const skillInstall = await installSkill({ home: options.home });
- const claudeDesktopDetected = detectClaudeDesktopPresence({ home: options.home });
-
const defaultAction: EditorMcpResult['action'] = skipMcp ? 'skipped-flag' : 'skipped-missing';
const primary = editorResults.find((r) => r.editorId === 'claude') ??
editorResults[0] ?? {
@@ -759,7 +754,6 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
skillInstall,
didGitInit: gitResult.didInit,
rootGitignoreCreated,
- claudeDesktopDetected,
mcpAction: primary.action,
mcpPath: primary.configPath,
mcpError: 'error' in primary ? (primary as EditorMcpResult).error : undefined,
@@ -1036,13 +1030,6 @@ export function formatInitResult(result: InitCommandResult, cwd: string): string
}
}
- if (result.claudeDesktopDetected) {
- lines.push('');
- lines.push(
- `Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${accent('ok install-skill')}`,
- );
- }
-
if (result.preview) {
lines.push('');
lines.push(formatPreviewBlock(result.preview, cwd));
diff --git a/packages/cli/src/commands/repair-skills.test.ts b/packages/cli/src/commands/repair-skills.test.ts
index 8eecbd56c..f27cafaa8 100644
--- a/packages/cli/src/commands/repair-skills.test.ts
+++ b/packages/cli/src/commands/repair-skills.test.ts
@@ -61,7 +61,7 @@ function depsBuilder(opts: {
}): RepairSkillsDeps {
return {
resolveProjectBundledSkillDir: () => opts.projectBundleDir,
- resolveDiscoveryBundledSkillDir: () => opts.discoveryBundleDir,
+ resolveUserBundledSkillDir: () => opts.discoveryBundleDir,
readBundledVersion: async () => opts.bundledVersion,
readRecordedVersion: async () => opts.recordedVersion,
writeRecordedVersion: async (home, version) => {
@@ -323,7 +323,7 @@ describe('repairSkills — project sweep create-if-wired gate', () => {
throw new Error('unreachable');
expect(result.project.entries.find((e) => e.editorId === 'codex')?.outcome).toBe('created');
expect(
- existsSync(join(scratch.project, '.agents', 'skills', PROJECT_SKILL_DIR_NAME, 'SKILL.md')),
+ existsSync(join(scratch.project, '.codex', 'skills', PROJECT_SKILL_DIR_NAME, 'SKILL.md')),
).toBe(true);
});
@@ -468,6 +468,7 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
it('AC-B2: refreshes central + per-host and advances skill-state when version mismatches', async () => {
mkdirSync(join(scratch.home, '.claude'), { recursive: true });
mkdirSync(join(scratch.home, '.cursor'), { recursive: true });
+ mkdirSync(join(scratch.home, '.codex'), { recursive: true });
const written: Array<{ home: string; version: string }> = [];
const result = await repairSkills({
@@ -495,8 +496,10 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
expect(existsSync(join(claudeDest, 'SKILL.md'))).toBe(true);
expect(existsSync(join(cursorDest, 'SKILL.md'))).toBe(true);
+ const codexDest = join(scratch.home, '.codex', 'skills', USER_SKILL_DIR_NAME);
+ expect(existsSync(join(codexDest, 'SKILL.md'))).toBe(true);
const codexEntry = result.user.entries.find((e) => e.kind === 'host' && e.editorId === 'codex');
- expect(codexEntry?.outcome).toBe('skipped-collapsed-with-central');
+ expect(codexEntry?.outcome).toBe('written');
expect(written).toEqual([{ home: scratch.home, version: '9.9.9' }]);
});
@@ -649,7 +652,7 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
logger: (event) => logEvents.push(event),
deps: {
resolveProjectBundledSkillDir: () => projectBundleDir,
- resolveDiscoveryBundledSkillDir: () => {
+ resolveUserBundledSkillDir: () => {
throw new Error('synthetic: discovery bundle not found');
},
readBundledVersion: async () => '9.9.9',
@@ -879,7 +882,7 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
home: scratch.home,
deps: {
resolveProjectBundledSkillDir: () => projectBundleDir,
- resolveDiscoveryBundledSkillDir: () => {
+ resolveUserBundledSkillDir: () => {
throw new Error('synthetic: discovery bundle not found');
},
readBundledVersion: async () => '9.9.9',
@@ -908,7 +911,7 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
home: scratch.home,
deps: {
resolveProjectBundledSkillDir: () => projectBundleDir,
- resolveDiscoveryBundledSkillDir: () => discoveryBundleDir,
+ resolveUserBundledSkillDir: () => discoveryBundleDir,
readBundledVersion: async () => {
throw new Error('synthetic: cannot read package.json');
},
@@ -1048,7 +1051,7 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
home: scratch.home,
deps: {
resolveProjectBundledSkillDir: () => projectBundleDir,
- resolveDiscoveryBundledSkillDir: () => discoveryBundleDir,
+ resolveUserBundledSkillDir: () => discoveryBundleDir,
readBundledVersion: async () => '9.9.9',
readRecordedVersion: async () => '0.6.0',
writeRecordedVersion: async (home, version) => {
@@ -1078,7 +1081,7 @@ describe('formatRepairSkillsResult — done-branch stdout formatting', () => {
{ editorId: 'cursor', hostDir: '.cursor', path: '/y', outcome: 'no-token' },
{
editorId: 'codex',
- hostDir: '.agents',
+ hostDir: '.codex',
path: '/z',
outcome: 'failed',
error: 'simulated',
@@ -1107,9 +1110,9 @@ describe('formatRepairSkillsResult — done-branch stdout formatting', () => {
{
kind: 'host',
editorId: 'codex',
- hostDir: '.agents',
+ hostDir: '.codex',
path: '/g',
- outcome: 'skipped-collapsed-with-central',
+ outcome: 'skipped-host-absent',
},
],
},
diff --git a/packages/cli/src/commands/repair-skills.ts b/packages/cli/src/commands/repair-skills.ts
index 054e02671..6a703c78b 100644
--- a/packages/cli/src/commands/repair-skills.ts
+++ b/packages/cli/src/commands/repair-skills.ts
@@ -10,26 +10,24 @@ import {
import { homedir } from 'node:os';
import { dirname, join, resolve as resolvePath } from 'node:path';
import {
+ BUNDLE_SKILL_NAME,
+ type BundleId,
readServerPackageVersion,
readTargetVersion,
recordSkillInstallEvent,
resolveBundledSkillDir,
type SkillInstallEvent,
+ USER_GLOBAL_BUNDLE_IDS,
writeTargetVersion,
} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { assertProjectPathSafe } from '../integrations/write-project-skill.ts';
-import { CHAIN_VERSION_SENTINEL, EDITOR_TARGETS, type EditorId } from './editors.ts';
-
-const HOSTS_WITH_USER_SKILL_DIR: ReadonlyArray<{
- readonly hostDir: string;
- readonly editorId: string;
-}> = [
- { hostDir: '.claude', editorId: 'claude' },
- { hostDir: '.cursor', editorId: 'cursor' },
- { hostDir: '.agents', editorId: 'codex' },
- { hostDir: '.agents', editorId: 'opencode' },
-];
+import {
+ CHAIN_VERSION_SENTINEL,
+ EDITOR_TARGETS,
+ type EditorId,
+ HOSTS_WITH_USER_SKILL_DIR,
+} from './editors.ts';
const USER_SKILL_DIR_NAME = 'open-knowledge-discovery';
const PROJECT_SKILL_DIR_NAME = 'open-knowledge';
@@ -82,7 +80,7 @@ const defaultFsOps: RepairSkillsFsOps = {
export interface RepairSkillsDeps {
resolveProjectBundledSkillDir?(): string;
- resolveDiscoveryBundledSkillDir?(): string;
+ resolveUserBundledSkillDir?(bundle: BundleId): string;
readBundledVersion?(): Promise<string>;
readRecordedVersion?(home: string): Promise<string | null>;
writeRecordedVersion?(home: string, version: string): Promise<void>;
@@ -91,8 +89,7 @@ export interface RepairSkillsDeps {
const defaultDeps: Required<RepairSkillsDeps> = {
resolveProjectBundledSkillDir: () => resolveBundledSkillDir('project', { checkDesktop: false }),
- resolveDiscoveryBundledSkillDir: () =>
- resolveBundledSkillDir('discovery', { checkDesktop: false }),
+ resolveUserBundledSkillDir: (bundle) => resolveBundledSkillDir(bundle, { checkDesktop: false }),
readBundledVersion: () => readServerPackageVersion(),
readRecordedVersion: (home) => readTargetVersion(home, 'cli-hosts'),
writeRecordedVersion: (home, version) =>
@@ -181,6 +178,104 @@ function copyDirContents(sourceDir: string, destDir: string, fs: RepairSkillsFsO
}
}
+function installUserBundleToHostDirs(
+ home: string,
+ bundleDirName: string,
+ sourceDir: string,
+ fs: RepairSkillsFsOps,
+ logger: (event: RepairSkillsLogEvent) => void,
+ version: string,
+): { 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 });
+ }
+
+ for (const host of HOSTS_WITH_USER_SKILL_DIR) {
+ const hostRoot = join(home, host.hostDir);
+ const hostDest = join(hostRoot, 'skills', bundleDirName);
+ if (hostDest === centralDest) {
+ entries.push({
+ kind: 'host',
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: hostDest,
+ outcome: 'skipped-collapsed-with-central',
+ });
+ continue;
+ }
+ if (!fs.existsSync(hostRoot)) {
+ entries.push({
+ kind: 'host',
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: hostDest,
+ outcome: 'skipped-host-absent',
+ });
+ continue;
+ }
+ const existedBefore = fs.existsSync(hostDest);
+ try {
+ replaceDir(sourceDir, hostDest, fs);
+ entries.push({
+ kind: 'host',
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: hostDest,
+ outcome: existedBefore ? 'overwritten' : 'written',
+ });
+ logger({
+ event: 'user-skill-reclaim-host-written',
+ scope: 'user',
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: hostDest,
+ preexisting: existedBefore,
+ version,
+ });
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ entries.push({
+ kind: 'host',
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: hostDest,
+ outcome: 'failed',
+ error,
+ });
+ logger({
+ event: 'user-skill-reclaim-host-failed',
+ scope: 'user',
+ editorId: host.editorId,
+ hostDir: host.hostDir,
+ path: hostDest,
+ error,
+ });
+ }
+ }
+ return { entries, centralWritten };
+}
+
function editorWiredForOk(configPath: string | undefined, fs: RepairSkillsFsOps): boolean {
if (!configPath) return false;
try {
@@ -316,119 +411,50 @@ async function runUserSweep(
return { outcome: 'skipped', reason: 'version-current' };
}
- let sourceDir: string;
- try {
- sourceDir = deps.resolveDiscoveryBundledSkillDir();
- } catch (err) {
- const error = err instanceof Error ? err.message : String(err);
- logger({ event: 'user-skill-reclaim-bundle-missing', scope: 'user', error });
+ const resolvedBundles: Array<{ id: BundleId; sourceDir: string }> = [];
+ let lastResolveError: string | null = null;
+ for (const bundleId of USER_GLOBAL_BUNDLE_IDS) {
+ try {
+ resolvedBundles.push({ id: bundleId, sourceDir: deps.resolveUserBundledSkillDir(bundleId) });
+ } catch (err) {
+ lastResolveError = err instanceof Error ? err.message : String(err);
+ }
+ }
+ if (resolvedBundles.length === 0) {
+ logger({
+ event: 'user-skill-reclaim-bundle-missing',
+ scope: 'user',
+ error: lastResolveError ?? 'no user-global bundles',
+ });
recordEventSoft({
ts: nowIso(),
surface: 'cli-start',
target: 'cli-hosts',
- bundle: 'discovery',
outcome: 'failed',
- reason: `bundle-missing:${error}`,
+ reason: `bundle-missing:${lastResolveError}`,
});
return { outcome: 'skipped', reason: 'bundle-missing' };
}
const entries: UserSkillEntry[] = [];
-
- const centralDest = join(home, ...CENTRAL_USER_SKILL_REL);
- const centralExistedBefore = fs.existsSync(centralDest);
- try {
- replaceDir(sourceDir, centralDest, fs);
- entries.push({
- kind: 'central',
- path: centralDest,
- outcome: centralExistedBefore ? 'overwritten' : 'written',
- });
- logger({
- event: 'user-skill-reclaim-central-written',
- scope: 'user',
- path: centralDest,
- preexisting: centralExistedBefore,
- version: bundledVersion,
- });
- } 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) {
- const hostRoot = join(home, host.hostDir);
- const hostDest = join(hostRoot, 'skills', USER_SKILL_DIR_NAME);
- if (hostDest === centralDest) {
- entries.push({
- kind: 'host',
- editorId: host.editorId,
- hostDir: host.hostDir,
- path: hostDest,
- outcome: 'skipped-collapsed-with-central',
- });
- continue;
- }
- if (!fs.existsSync(hostRoot)) {
- entries.push({
- kind: 'host',
- editorId: host.editorId,
- hostDir: host.hostDir,
- path: hostDest,
- outcome: 'skipped-host-absent',
- });
- continue;
- }
- const existedBefore = fs.existsSync(hostDest);
- try {
- replaceDir(sourceDir, hostDest, fs);
- entries.push({
- kind: 'host',
- editorId: host.editorId,
- hostDir: host.hostDir,
- path: hostDest,
- outcome: existedBefore ? 'overwritten' : 'written',
- });
- logger({
- event: 'user-skill-reclaim-host-written',
- scope: 'user',
- editorId: host.editorId,
- hostDir: host.hostDir,
- path: hostDest,
- preexisting: existedBefore,
- version: bundledVersion,
- });
- } catch (err) {
- const error = err instanceof Error ? err.message : String(err);
- entries.push({
- kind: 'host',
- editorId: host.editorId,
- hostDir: host.hostDir,
- path: hostDest,
- outcome: 'failed',
- error,
- });
- logger({
- event: 'user-skill-reclaim-host-failed',
- scope: 'user',
- editorId: host.editorId,
- hostDir: host.hostDir,
- path: hostDest,
- error,
- });
- }
+ let everyCentralWritten = resolvedBundles.length === USER_GLOBAL_BUNDLE_IDS.length;
+ for (const { id, sourceDir } of resolvedBundles) {
+ const result = installUserBundleToHostDirs(
+ home,
+ BUNDLE_SKILL_NAME[id],
+ sourceDir,
+ fs,
+ logger,
+ bundledVersion,
+ );
+ entries.push(...result.entries);
+ if (!result.centralWritten) everyCentralWritten = false;
}
- const centralEntry = entries.find((e) => e.kind === 'central');
- const anyWriteSucceeded =
- centralEntry?.outcome === 'written' || centralEntry?.outcome === 'overwritten';
- if (anyWriteSucceeded) {
+ const anyCentralWritten = entries.some(
+ (e) => e.kind === 'central' && (e.outcome === 'written' || e.outcome === 'overwritten'),
+ );
+ if (everyCentralWritten && anyCentralWritten) {
let stateWriteError: string | null = null;
try {
await deps.writeRecordedVersion(home, bundledVersion);
@@ -446,22 +472,23 @@ async function runUserSweep(
error: stateWriteError,
});
}
- recordEventSoft({
- ts: nowIso(),
- surface: 'cli-start',
- target: 'cli-hosts',
- bundle: 'discovery',
- outcome: stateWriteError === null ? 'installed' : 'failed',
- version: bundledVersion,
- ...(stateWriteError === null ? {} : { reason: `state-write-failed:${stateWriteError}` }),
- });
+ for (const { id } of resolvedBundles) {
+ recordEventSoft({
+ ts: nowIso(),
+ surface: 'cli-start',
+ target: 'cli-hosts',
+ bundle: id,
+ outcome: stateWriteError === null ? 'installed' : 'failed',
+ version: bundledVersion,
+ ...(stateWriteError === null ? {} : { reason: `state-write-failed:${stateWriteError}` }),
+ });
+ }
} else {
const anyHostFailed = entries.some((e) => e.kind === 'host' && e.outcome === 'failed');
recordEventSoft({
ts: nowIso(),
surface: 'cli-start',
target: 'cli-hosts',
- bundle: 'discovery',
outcome: 'failed',
version: bundledVersion,
reason: anyHostFailed ? 'all-writes-failed' : 'no-hosts-installed',
diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts
new file mode 100644
index 000000000..e5e1a9eb4
--- /dev/null
+++ b/packages/cli/src/commands/skills.ts
@@ -0,0 +1,63 @@
+import { resolve as resolvePath } from 'node:path';
+import { isProjectSkillManaged, writeSkillManagement } from '@inkeep/open-knowledge-server';
+import { Command } from 'commander';
+import { accent, dim, error as errorColor, info, success } from '../ui/colors.ts';
+
+export function skillsCommand(): Command {
+ const skills = new Command('skills').description(
+ 'Manage Open Knowledge skills for this project.',
+ );
+
+ skills
+ .command('manage')
+ .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).',
+ )
+ .option('--status', 'Print the current setting.')
+ .action(async (opts: { on?: boolean; off?: boolean; status?: boolean }) => {
+ const projectDir = resolvePath(process.cwd());
+ const chosen = [opts.on, opts.off, opts.status].filter(Boolean).length;
+ if (chosen !== 1) {
+ process.stderr.write(
+ `${errorColor('Error:')} pass exactly one of --on, --off, --status.\n`,
+ );
+ process.exitCode = 1;
+ return;
+ }
+
+ if (opts.status) {
+ 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);
+ try {
+ await writeSkillManagement(projectDir, { manageEditorSkills, surface: 'cli' });
+ } 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.exitCode = 1;
+ return;
+ }
+ 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`,
+ );
+ });
+
+ return skills;
+}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index af0238f07..b4225290e 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -11,6 +11,7 @@ export {
EDITOR_TARGETS,
type EditorId,
type EditorMcpTarget,
+ HOSTS_WITH_USER_SKILL_DIR,
isEntryUpToDate,
isOwnManagedEntry,
type McpInstallOptions,
diff --git a/packages/cli/src/integrations/project-integration-writers.test.ts b/packages/cli/src/integrations/project-integration-writers.test.ts
index 9e9650a02..41197e35a 100644
--- a/packages/cli/src/integrations/project-integration-writers.test.ts
+++ b/packages/cli/src/integrations/project-integration-writers.test.ts
@@ -125,11 +125,11 @@ describe('projectSkillWriter', () => {
expect(existsSync(outcome.path ?? '')).toBe(true);
});
- test('writes for codex (.agents/skills/open-knowledge/SKILL.md)', () => {
+ test('writes for codex (.codex/skills/open-knowledge/SKILL.md)', () => {
const outcome = projectSkillWriter.write(EDITOR_TARGETS.codex, projectDir, {});
expect(outcome.action).toBe('written');
- expect(outcome.path).toBe(join(projectDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md'));
+ expect(outcome.path).toBe(join(projectDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md'));
expect(existsSync(outcome.path ?? '')).toBe(true);
});
@@ -229,7 +229,7 @@ describe('applyProjectIntegrations', () => {
true,
);
expect(existsSync(join(projectDir, '.codex', 'config.toml'))).toBe(true);
- expect(existsSync(join(projectDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ expect(existsSync(join(projectDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
true,
);
});
diff --git a/packages/cli/src/integrations/write-project-ai-integrations.test.ts b/packages/cli/src/integrations/write-project-ai-integrations.test.ts
index 5c7f1b89d..98db24da0 100644
--- a/packages/cli/src/integrations/write-project-ai-integrations.test.ts
+++ b/packages/cli/src/integrations/write-project-ai-integrations.test.ts
@@ -49,7 +49,7 @@ describe('writeProjectAiIntegrations — installs MCP config AND the project ski
expect(existsSync(join(projectDir, '.cursor', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
true,
);
- expect(existsSync(join(projectDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ expect(existsSync(join(projectDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
true,
);
});
diff --git a/packages/cli/src/sharing/git-exclude.test.ts b/packages/cli/src/sharing/git-exclude.test.ts
index 999a490e0..83fb98326 100644
--- a/packages/cli/src/sharing/git-exclude.test.ts
+++ b/packages/cli/src/sharing/git-exclude.test.ts
@@ -47,7 +47,7 @@ describe('getOkArtifactPaths', () => {
rmSync(dir, { recursive: true, force: true });
});
- it('returns the canonical ten-path artifact set when no config.yml exists', () => {
+ it('returns the canonical eleven-path artifact set when no config.yml exists', () => {
const paths = getOkArtifactPaths(dir);
expect(paths).toContain(`${OK_DIR}/`);
expect(paths).toContain('.okignore');
@@ -57,9 +57,10 @@ describe('getOkArtifactPaths', () => {
expect(paths).toContain('opencode.json');
expect(paths).toContain('.claude/skills/open-knowledge/');
expect(paths).toContain('.cursor/skills/open-knowledge/');
- expect(paths).toContain('.agents/skills/open-knowledge/');
+ expect(paths).toContain('.codex/skills/open-knowledge/');
+ expect(paths).toContain('.opencode/skills/open-knowledge/');
expect(paths).toContain('.claude/launch.json');
- expect(paths).toHaveLength(10);
+ expect(paths).toHaveLength(11);
});
it('preserves a stable order so `ok config-sharing status` and unit-test snapshots are deterministic', () => {
@@ -77,7 +78,46 @@ describe('getOkArtifactPaths', () => {
expect(paths).not.toContain('docs/.ok/');
expect(paths).not.toContain('docs/.okignore');
expect(paths.some((p) => p.includes('**'))).toBe(false);
- expect(paths).toHaveLength(10);
+ expect(paths).toHaveLength(11);
+ });
+
+ it('excludes each installed skill projection per the OF3 marker (PRD-6934 C9 fix)', () => {
+ mkdirSync(join(dir, OK_DIR, 'local'), { recursive: true });
+ writeFileSync(
+ join(dir, OK_DIR, 'local', 'installed-skills.json'),
+ JSON.stringify({
+ schema: 1,
+ skills: {
+ 'trip-log': {
+ hosts: ['claude', 'cursor'],
+ contentHash: 'abc',
+ scope: 'project',
+ scripts: false,
+ installedAt: '2026-06-05T00:00:00.000Z',
+ },
+ 'fishing-pack': {
+ hosts: ['codex'],
+ contentHash: 'def',
+ scope: 'project',
+ scripts: true,
+ installedAt: '2026-06-05T00:00:00.000Z',
+ },
+ },
+ }),
+ 'utf-8',
+ );
+ const paths = getOkArtifactPaths(dir);
+ expect(paths).toContain('.claude/skills/trip-log/');
+ expect(paths).toContain('.cursor/skills/trip-log/');
+ expect(paths).toContain('.codex/skills/fishing-pack/'); // codex → .codex
+ expect(paths).toContain('.claude/skills/open-knowledge/');
+ });
+
+ it('falls back to the bundle-only set when the marker is absent or corrupt', () => {
+ mkdirSync(join(dir, OK_DIR, 'local'), { recursive: true });
+ writeFileSync(join(dir, OK_DIR, 'local', 'installed-skills.json'), '{ corrupt', 'utf-8');
+ const paths = getOkArtifactPaths(dir);
+ expect(paths).toHaveLength(11); // corrupt marker → fail-soft, no per-skill paths
});
});
diff --git a/packages/cli/src/sharing/git-exclude.ts b/packages/cli/src/sharing/git-exclude.ts
index 2f9ab5cc5..3c4416ea3 100644
--- a/packages/cli/src/sharing/git-exclude.ts
+++ b/packages/cli/src/sharing/git-exclude.ts
@@ -1,7 +1,13 @@
import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
-import { OK_DIR } from '@inkeep/open-knowledge-core';
+import {
+ EDITOR_PROJECT_SKILL_ROOT,
+ type EditorId,
+ INSTALLED_SKILLS_REL,
+ OK_DIR,
+ parseInstalledSkills,
+} from '@inkeep/open-knowledge-core';
import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { ALL_EDITOR_IDS, EDITOR_TARGETS } from '../commands/editors.ts';
@@ -38,6 +44,21 @@ export function getOkArtifactPaths(projectRoot: string): readonly string[] {
}
paths.push(CLAUDE_LAUNCH_JSON);
+ const markerPath = join(projectRoot, ...INSTALLED_SKILLS_REL);
+ if (existsSync(markerPath)) {
+ try {
+ const marker = parseInstalledSkills(readFileSync(markerPath, 'utf-8'));
+ if (marker) {
+ for (const [name, entry] of Object.entries(marker.skills)) {
+ for (const host of entry.hosts) {
+ const root = EDITOR_PROJECT_SKILL_ROOT[host as EditorId];
+ if (root) paths.push(`${root}/${name}/`);
+ }
+ }
+ }
+ } catch {}
+ }
+
return Array.from(new Set(paths));
}
diff --git a/packages/core/src/constants/cc1.test.ts b/packages/core/src/constants/cc1.test.ts
new file mode 100644
index 000000000..bd9bd108f
--- /dev/null
+++ b/packages/core/src/constants/cc1.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ managedArtifactDocNameFromContentTarget,
+ parseGlobalSkillBundleDoc,
+ parseProjectSkillBundleDoc,
+ resolveSkillBundleWikiTarget,
+} from './cc1.ts';
+
+describe('managedArtifactDocNameFromContentTarget', () => {
+ test('does NOT rewrite project skill file paths — they are content docs', () => {
+ expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/SKILL.md')).toBeNull();
+ expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/SKILL')).toBeNull();
+ expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/SKILL.mdx')).toBeNull();
+ expect(managedArtifactDocNameFromContentTarget('some/dir/.ok/skills/deep/SKILL.md')).toBeNull();
+ });
+
+ test('maps a root-level template to a folderless template doc name', () => {
+ expect(managedArtifactDocNameFromContentTarget('.ok/templates/note.md')).toBe(
+ '__template__/note',
+ );
+ });
+
+ test('maps a template under a folder, preserving the folder segment', () => {
+ expect(managedArtifactDocNameFromContentTarget('docs/.ok/templates/note.md')).toBe(
+ '__template__/docs/note',
+ );
+ expect(managedArtifactDocNameFromContentTarget('docs/guides/.ok/templates/note')).toBe(
+ '__template__/docs/guides/note',
+ );
+ });
+
+ test('returns null for paths that are not skill/template files', () => {
+ expect(managedArtifactDocNameFromContentTarget('docs/getting-started.md')).toBeNull();
+ expect(managedArtifactDocNameFromContentTarget('.ok/skills/my-skill/NOTES.md')).toBeNull();
+ expect(managedArtifactDocNameFromContentTarget('.ok/config.yml')).toBeNull();
+ expect(managedArtifactDocNameFromContentTarget('readme')).toBeNull();
+ expect(managedArtifactDocNameFromContentTarget('')).toBeNull();
+ });
+});
+
+describe('resolveSkillBundleWikiTarget', () => {
+ const skill = '.ok/skills/demo/SKILL';
+
+ test('resolves a references/ wiki-target to the sibling bundle ref', () => {
+ expect(resolveSkillBundleWikiTarget('references/notes', skill)).toBe(
+ '.ok/skills/demo/references/notes',
+ );
+ expect(resolveSkillBundleWikiTarget('references/sub/deep', skill)).toBe(
+ '.ok/skills/demo/references/sub/deep',
+ );
+ });
+
+ test('strips a markdown extension so [[references/x.md]] == [[references/x]]', () => {
+ expect(resolveSkillBundleWikiTarget('references/notes.md', skill)).toBe(
+ '.ok/skills/demo/references/notes',
+ );
+ expect(resolveSkillBundleWikiTarget('references/notes.MDX', skill)).toBe(
+ '.ok/skills/demo/references/notes',
+ );
+ });
+
+ test('resolves a scripts/ wiki-target too', () => {
+ expect(resolveSkillBundleWikiTarget('scripts/run', skill)).toBe('.ok/skills/demo/scripts/run');
+ });
+
+ test('leaves bare names and non-bundle targets to KB-wide resolution', () => {
+ expect(resolveSkillBundleWikiTarget('notes', skill)).toBeNull();
+ expect(resolveSkillBundleWikiTarget('docs/intro', skill)).toBeNull();
+ expect(resolveSkillBundleWikiTarget('references', skill)).toBeNull();
+ expect(resolveSkillBundleWikiTarget('references/', skill)).toBeNull();
+ });
+
+ test('refuses traversal that would escape the skill dir', () => {
+ expect(resolveSkillBundleWikiTarget('references/../../escape', skill)).toBeNull();
+ });
+
+ test('returns null when the source is not a project skill SKILL doc', () => {
+ expect(resolveSkillBundleWikiTarget('references/notes', 'notes/index')).toBeNull();
+ expect(
+ resolveSkillBundleWikiTarget('references/notes', '.ok/skills/demo/references/x'),
+ ).toBeNull();
+ expect(resolveSkillBundleWikiTarget('references/notes', '__skill__/global/demo')).toBeNull();
+ });
+});
+
+describe('parseProjectSkillBundleDoc', () => {
+ test('parses a project SKILL doc', () => {
+ expect(parseProjectSkillBundleDoc('.ok/skills/demo/SKILL')).toEqual({
+ name: 'demo',
+ kind: 'skill',
+ rel: null,
+ });
+ });
+
+ test('parses a project reference doc (flat and nested)', () => {
+ expect(parseProjectSkillBundleDoc('.ok/skills/demo/references/notes')).toEqual({
+ name: 'demo',
+ kind: 'reference',
+ rel: 'notes',
+ });
+ expect(parseProjectSkillBundleDoc('.ok/skills/demo/references/sub/deep')).toEqual({
+ name: 'demo',
+ kind: 'reference',
+ rel: 'sub/deep',
+ });
+ });
+
+ test('rejects non-bundle docs, scripts, global skills, and the bare skill dir', () => {
+ expect(parseProjectSkillBundleDoc('notes/index')).toBeNull();
+ expect(parseProjectSkillBundleDoc('notes/references/x')).toBeNull();
+ expect(parseProjectSkillBundleDoc('.ok/skills/demo/scripts/run')).toBeNull();
+ expect(parseProjectSkillBundleDoc('__skill__/global/demo')).toBeNull();
+ expect(parseProjectSkillBundleDoc('.ok/skills/demo')).toBeNull();
+ expect(parseProjectSkillBundleDoc('.ok/skills/demo/references')).toBeNull();
+ expect(parseProjectSkillBundleDoc('.ok/skills/demo/references/')).toBeNull();
+ });
+});
+
+describe('parseGlobalSkillBundleDoc', () => {
+ test('parses a global SKILL doc', () => {
+ expect(parseGlobalSkillBundleDoc('__skill__/global/demo')).toEqual({
+ name: 'demo',
+ kind: 'skill',
+ rel: null,
+ });
+ });
+
+ test('parses a global reference doc (flat and nested)', () => {
+ expect(parseGlobalSkillBundleDoc('__skill__/global/demo/references/notes')).toEqual({
+ name: 'demo',
+ kind: 'reference',
+ rel: 'notes',
+ });
+ expect(parseGlobalSkillBundleDoc('__skill__/global/demo/references/sub/deep')).toEqual({
+ name: 'demo',
+ kind: 'reference',
+ rel: 'sub/deep',
+ });
+ });
+
+ test('rejects project bundle docs, scripts, the bare dir, and other scopes', () => {
+ expect(parseGlobalSkillBundleDoc('.ok/skills/demo/SKILL')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('.ok/skills/demo/references/notes')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('__skill__/global/demo/scripts/run')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('__skill__/global/demo/references')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('__skill__/global/demo/references/')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('__skill__/project/demo')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('__skill__/project/demo/references/notes')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('__template__/notes/daily')).toBeNull();
+ expect(parseGlobalSkillBundleDoc('notes/index')).toBeNull();
+ });
+});
diff --git a/packages/core/src/constants/cc1.ts b/packages/core/src/constants/cc1.ts
index 43e705173..47efbf51e 100644
--- a/packages/core/src/constants/cc1.ts
+++ b/packages/core/src/constants/cc1.ts
@@ -16,3 +16,129 @@ export const CONFIG_DOC_NAMES = Object.freeze([
CONFIG_DOC_NAME_OKIGNORE,
] as const);
export type ConfigDocName = (typeof CONFIG_DOC_NAMES)[number];
+
+export const MANAGED_ARTIFACT_PREFIX_SKILL = '__skill__/';
+export const MANAGED_ARTIFACT_PREFIX_TEMPLATE = '__template__/';
+
+export const MANAGED_ARTIFACT_SCOPES = ['project', 'global'] as const;
+export type ManagedArtifactScope = (typeof MANAGED_ARTIFACT_SCOPES)[number];
+
+export function isManagedArtifactDocName(name: string): boolean {
+ return (
+ name.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL) ||
+ name.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)
+ );
+}
+
+export const SKILL_CONTENT_ROOT = '.ok/skills';
+
+export function projectSkillContentDocName(name: string): string {
+ return `${SKILL_CONTENT_ROOT}/${name}/SKILL`;
+}
+
+const SKILL_BUNDLE_SUBDIRS = ['references', 'scripts'] as const;
+
+export function resolveSkillBundleWikiTarget(target: string, sourceDocName: string): string | null {
+ const skillDirMatch = /^(\.ok\/skills\/[^/]+)\/SKILL$/.exec(sourceDocName);
+ if (!skillDirMatch) return null;
+ const skillDir = skillDirMatch[1] as string;
+
+ const trimmed = target.trim();
+ const withoutExt = trimmed.replace(/\.mdx?$/i, '');
+ const segments = withoutExt.split('/').filter((s) => s !== '' && s !== '.');
+ const [first] = segments;
+ if (!first || !(SKILL_BUNDLE_SUBDIRS as readonly string[]).includes(first)) return null;
+ if (segments.includes('..')) return null;
+ if (segments.length < 2) return null;
+ return `${skillDir}/${segments.join('/')}`;
+}
+
+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\/.+)$/;
+
+export function parseProjectSkillBundleDoc(docName: string): ParsedProjectSkillBundleDoc | null {
+ const match = PROJECT_SKILL_BUNDLE_DOC_RE.exec(docName);
+ if (!match) return null;
+ const name = match[1] as string;
+ const tail = match[2] as string;
+ if (tail === 'SKILL') return { name, kind: 'skill', rel: null };
+ return { name, kind: 'reference', rel: tail.slice('references/'.length) };
+}
+
+export type ParsedGlobalSkillBundleDoc =
+ | { name: string; kind: 'skill'; rel: null }
+ | { name: string; kind: 'reference'; rel: string };
+
+const GLOBAL_SKILL_BUNDLE_DOC_RE = /^__skill__\/global\/([^/]+)(?:\/(references\/.+))?$/;
+
+export function parseGlobalSkillBundleDoc(docName: string): ParsedGlobalSkillBundleDoc | null {
+ const match = GLOBAL_SKILL_BUNDLE_DOC_RE.exec(docName);
+ if (!match) return null;
+ const name = match[1] as string;
+ const tail = match[2];
+ if (tail === undefined) return { name, kind: 'skill', rel: null };
+ return { name, kind: 'reference', rel: tail.slice('references/'.length) };
+}
+
+export function skillLiveDocName(scope: ManagedArtifactScope, name: string): string {
+ return scope === 'project'
+ ? projectSkillContentDocName(name)
+ : `${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${name}`;
+}
+
+export type ParsedManagedArtifactName =
+ | { kind: 'skill'; scope: ManagedArtifactScope; name: string }
+ | { kind: 'template'; folder: string; name: string };
+
+function decodeManagedSegments(encoded: string): string {
+ if (encoded === '') return '';
+ try {
+ return encoded
+ .split('/')
+ .map((s) => decodeURIComponent(s))
+ .join('/');
+ } catch {
+ return encoded;
+ }
+}
+
+export function parseManagedArtifactName(name: string): ParsedManagedArtifactName | null {
+ if (name.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL)) {
+ const rest = name.slice(MANAGED_ARTIFACT_PREFIX_SKILL.length);
+ const slash = rest.indexOf('/');
+ if (slash < 0) return null;
+ const scope = rest.slice(0, slash);
+ if (scope !== 'global' && scope !== 'project') return null;
+ const encoded = rest.slice(slash + 1);
+ if (!encoded) return null;
+ return { kind: 'skill', scope, name: decodeManagedSegments(encoded) };
+ }
+ if (name.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) {
+ const rest = name.slice(MANAGED_ARTIFACT_PREFIX_TEMPLATE.length);
+ if (!rest) return null;
+ const lastSlash = rest.lastIndexOf('/');
+ const encodedName = lastSlash < 0 ? rest : rest.slice(lastSlash + 1);
+ if (!encodedName) return null;
+ const encodedFolder = lastSlash < 0 ? '' : rest.slice(0, lastSlash);
+ return {
+ kind: 'template',
+ folder: decodeManagedSegments(encodedFolder),
+ name: decodeManagedSegments(encodedName),
+ };
+ }
+ return null;
+}
+
+const TEMPLATE_FILE_TARGET_RE = /^(?:(.+)\/)?\.ok\/templates\/([^/]+?)(?:\.mdx?)?$/;
+
+export function managedArtifactDocNameFromContentTarget(target: string): string | null {
+ const template = TEMPLATE_FILE_TARGET_RE.exec(target);
+ if (template) {
+ const folder = (template[1] ?? '').replace(/^\/+|\/+$/g, '');
+ return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${folder ? `${folder}/` : ''}${template[2]}`;
+ }
+ return null;
+}
diff --git a/packages/core/src/constants/editors.ts b/packages/core/src/constants/editors.ts
index 84c40167d..c22ff9bf2 100644
--- a/packages/core/src/constants/editors.ts
+++ b/packages/core/src/constants/editors.ts
@@ -15,3 +15,67 @@ export const EDITOR_LABELS = {
codex: 'Codex',
opencode: 'OpenCode',
} as const satisfies Record<EditorId, string>;
+
+/**
+ * Project-relative skills root per editor (POSIX, `cwd`-relative), or `null`
+ * for an editor with no project skill surface (Claude Desktop reads
+ * user-global skills only). Authored skills project to `<root>/<name>/`; OK's
+ * shipped bundle lives at `<root>/open-knowledge/`. Single source for the
+ * install-projection fan-out (`skill-projection.ts`) AND the sharing-mode
+ * exclude (`getOkArtifactPaths`), so both stay in lock-step.
+ *
+ * Each editor installs into its OWN primary skills dir so "install on Codex
+ * only" is honest. Codex's is `.codex/skills` (alongside its `.codex/config.toml`
+ * MCP path).
+ *
+ * Why per-editor and NOT a shared `.agents/skills` broadcast at project scope:
+ * `.agents/skills` was Codex's old shared path and conflated Cursor+Codex. At
+ * project scope there is no shared convergence point — each harness reads its
+ * OWN dir (Claude → `.claude/skills`, Cursor → `.cursor/skills`, …) — so
+ * projecting a project skill into `.agents/skills` would
+ * (a) HIDE it from harnesses that don't read `.agents` (Claude, Cursor),
+ * (b) DOUBLE-LOAD it for ones that read both their dir AND `.agents` (OpenCode
+ * reads `.opencode/skills` natively AND `.agents/skills`) → duplicate /
+ * name-collision (the `<name>-<editor>` churn class), and
+ * (c) CLOBBER the symlink where `.codex`/`.cursor` symlink to `.agents`.
+ * The per-editor fan-out already reaches every harness OK supports, so `.agents`
+ * adds NO reach at project scope — only conflation. A genuinely new harness that
+ * adopts the vendor-neutral `.agents/` convention is onboarded by adding it to
+ * this map (one line; flows to every dependent + lock-step test), NOT by
+ * broadcasting into a shared dir.
+ *
+ * The asymmetry with USER/global scope is deliberate: `~/.agents/skills` IS the
+ * right hub there, because the `skills` CLI fans the bundled discovery skill out
+ * from it via `--agent '*'` (see `skill-install.ts`) — a shared convergence
+ * point that exists globally but has no per-project equivalent.
+ *
+ * The CLI's `EDITOR_TARGETS.projectSkillPath` is a second source for the same
+ * map and must move in lock-step.
+ */
+export const EDITOR_PROJECT_SKILL_ROOT = {
+ claude: '.claude/skills',
+ 'claude-desktop': null,
+ cursor: '.cursor/skills',
+ codex: '.codex/skills',
+ opencode: '.opencode/skills',
+} as const satisfies Record<EditorId, string | null>;
+
+export const PROJECT_SKILL_EDITOR_IDS = ALL_EDITOR_IDS.filter(
+ (id) => EDITOR_PROJECT_SKILL_ROOT[id] !== null,
+);
+
+export const HOSTS_WITH_USER_SKILL_DIR: ReadonlyArray<{
+ readonly hostDir: string;
+ readonly editorId: EditorId;
+}> = PROJECT_SKILL_EDITOR_IDS.map((editorId) => ({
+ hostDir: (EDITOR_PROJECT_SKILL_ROOT[editorId] ?? '').split('/')[0],
+ editorId,
+}));
+
+export const EDITOR_PROJECT_CONFIG_PATH = {
+ claude: '.mcp.json',
+ 'claude-desktop': null,
+ cursor: '.cursor/mcp.json',
+ codex: '.codex/config.toml',
+ opencode: 'opencode.json',
+} as const satisfies Record<EditorId, string | null>;
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 965ae9c46..63aa8b8cd 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -247,6 +247,9 @@ interface OkScaffoldPlan {
created: OkScaffoldFileEntry[];
skipped: OkScaffoldSkipEntry[];
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 };
}
interface OkScaffoldApplyError {
path: string;
diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.ts
index 16ac1b4de..1ee579584 100644
--- a/packages/core/src/handoff/index.ts
+++ b/packages/core/src/handoff/index.ts
@@ -13,6 +13,7 @@ export {
composeFilePrompt,
composeFolderPrompt,
composeSelectionPrompt,
+ composeSkillPrompt,
composeTerminalBareLaunchPrompt,
OK_PROJECT_SKILL_POINTER,
OK_TERMINAL_SURFACE_PREAMBLE,
diff --git a/packages/core/src/handoff/prompt-composer.test.ts b/packages/core/src/handoff/prompt-composer.test.ts
index 500623889..c7af2e3de 100644
--- a/packages/core/src/handoff/prompt-composer.test.ts
+++ b/packages/core/src/handoff/prompt-composer.test.ts
@@ -11,6 +11,7 @@ import {
composeFilePrompt,
composeFolderPrompt,
composeSelectionPrompt,
+ composeSkillPrompt,
composeTerminalBareLaunchPrompt,
OK_PROJECT_SKILL_POINTER,
OK_TERMINAL_SURFACE_PREAMBLE,
@@ -40,6 +41,18 @@ test('composeFilePrompt interpolates a deep relative path with autoOpen=false',
);
});
+test('composeSkillPrompt names the write-skill skill + scope, with the autoOpen trailer', () => {
+ expect(composeSkillPrompt('commit-helper', 'project', true)).toBe(
+ 'Use your open-knowledge-write-skill skill to author the project Open Knowledge skill `commit-helper`. Edit it with the Open Knowledge tools. Open the OK editor in web view.',
+ );
+});
+
+test('composeSkillPrompt carries the global scope + drops the trailer when autoOpen=false', () => {
+ expect(composeSkillPrompt('my-notes', 'global', false)).toBe(
+ 'Use your open-knowledge-write-skill skill to author the global Open Knowledge skill `my-notes`. Edit it with the Open Knowledge tools.',
+ );
+});
+
test('composeFilePrompt is deterministic — identical inputs produce identical outputs', () => {
expect(composeFilePrompt('a/b.md', true)).toBe(composeFilePrompt('a/b.md', true));
expect(composeFilePrompt('a/b.md', false)).toBe(composeFilePrompt('a/b.md', false));
diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.ts
index 067fdaefb..7eab9e791 100644
--- a/packages/core/src/handoff/prompt-composer.ts
+++ b/packages/core/src/handoff/prompt-composer.ts
@@ -63,6 +63,16 @@ export function composeFilePrompt(
return appendInstruction(directive, instruction);
}
+export function composeSkillPrompt(
+ skillName: string,
+ scope: 'project' | 'global',
+ autoOpen: boolean,
+): string {
+ const safe = sanitizePathForPrompt(skillName);
+ const base = `Use your open-knowledge-write-skill skill to author the ${scope} Open Knowledge skill \`${safe}\`. Edit it with the Open Knowledge tools.`;
+ return autoOpen ? `${base} Open the OK editor in web view.` : base;
+}
+
export function composeFolderPrompt(
relativeFolderPath: string,
autoOpen: boolean,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index e304ed71b..2f408bf6c 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -172,7 +172,23 @@ export {
CONFIG_DOC_NAME_USER,
CONFIG_DOC_NAMES,
type ConfigDocName,
+ isManagedArtifactDocName,
+ MANAGED_ARTIFACT_PREFIX_SKILL,
+ MANAGED_ARTIFACT_PREFIX_TEMPLATE,
+ MANAGED_ARTIFACT_SCOPES,
+ type ManagedArtifactScope,
+ managedArtifactDocNameFromContentTarget,
+ type ParsedGlobalSkillBundleDoc,
+ type ParsedManagedArtifactName,
+ type ParsedProjectSkillBundleDoc,
+ parseGlobalSkillBundleDoc,
+ parseManagedArtifactName,
+ parseProjectSkillBundleDoc,
+ projectSkillContentDocName,
+ resolveSkillBundleWikiTarget,
+ SKILL_CONTENT_ROOT,
SYSTEM_DOC_NAME,
+ skillLiveDocName,
} from './constants/cc1.ts';
export {
CODE_FILE_BARE_NAMES_TO_LANGUAGE,
@@ -198,7 +214,11 @@ export {
export {
ALL_EDITOR_IDS,
EDITOR_LABELS,
+ EDITOR_PROJECT_CONFIG_PATH,
+ EDITOR_PROJECT_SKILL_ROOT,
type EditorId,
+ HOSTS_WITH_USER_SKILL_DIR,
+ PROJECT_SKILL_EDITOR_IDS,
} from './constants/editors.ts';
export {
detectEmbeddedHostFromBrowser,
@@ -366,6 +386,7 @@ export {
composeFilePrompt,
composeFolderPrompt,
composeSelectionPrompt,
+ composeSkillPrompt,
composeTerminalBareLaunchPrompt,
type DocContext,
type HandoffFailureReason,
@@ -390,6 +411,19 @@ export {
type UrnIpcLookup,
withSkillPointer,
} from './handoff/index.ts';
+export {
+ emptyInstalledSkills,
+ INSTALLED_SKILLS_FILENAME,
+ INSTALLED_SKILLS_REL,
+ INSTALLED_SKILLS_SCHEMA_VERSION,
+ type InstalledSkillEntry,
+ InstalledSkillEntrySchema,
+ type InstalledSkillScope,
+ InstalledSkillScopeSchema,
+ type InstalledSkills,
+ InstalledSkillsSchema,
+ parseInstalledSkills,
+} from './installed-skills/schema.ts';
export type {
BundleManifest,
BundleRedaction,
@@ -550,6 +584,7 @@ export {
type CreatePageSuccess,
CreatePageSuccessSchema,
classifyGitAuthError,
+ containsXmlTag,
type DeadLinkEntry,
DeadLinkEntrySchema,
type DeadLinkSource,
@@ -759,10 +794,67 @@ export {
SharePublishResponseSchema,
type SharePublishVisibility,
SharePublishVisibilitySchema,
+ SKILL_INSTALL_WARNING_CODES,
+ SKILL_NAME_REGEX,
+ type SkillDeleteSuccess,
+ SkillDeleteSuccessSchema,
+ type SkillFileDeleteSuccess,
+ SkillFileDeleteSuccessSchema,
+ type SkillFileGetSuccess,
+ SkillFileGetSuccessSchema,
+ type SkillFileKind,
+ SkillFileKindSchema,
+ type SkillFilePutRequest,
+ SkillFilePutRequestSchema,
+ type SkillFilePutSuccess,
+ SkillFilePutSuccessSchema,
+ type SkillFrontmatter,
+ SkillFrontmatterSchema,
+ type SkillGetSuccess,
+ SkillGetSuccessSchema,
+ type SkillInstallRequest,
+ SkillInstallRequestSchema,
type SkillInstallStateSuccess,
SkillInstallStateSuccessSchema,
+ type SkillInstallSuccess,
+ SkillInstallSuccessSchema,
type SkillInstallTargetState,
SkillInstallTargetStateSchema,
+ type SkillInstallWarningCode,
+ type SkillMoveRequest,
+ SkillMoveRequestSchema,
+ type SkillMoveSuccess,
+ SkillMoveSuccessSchema,
+ type SkillPayload,
+ SkillPayloadSchema,
+ type SkillPutRequest,
+ SkillPutRequestSchema,
+ type SkillPutSuccess,
+ SkillPutSuccessSchema,
+ type SkillRestoreRequest,
+ SkillRestoreRequestSchema,
+ type SkillRestoreSuccess,
+ SkillRestoreSuccessSchema,
+ type SkillScope,
+ SkillScopeSchema,
+ type SkillsListEntry,
+ SkillsListEntrySchema,
+ type SkillsListSuccess,
+ SkillsListSuccessSchema,
+ type SkillTargetsGetSuccess,
+ SkillTargetsGetSuccessSchema,
+ type SkillTargetsPutRequest,
+ SkillTargetsPutRequestSchema,
+ type SkillTargetsPutSuccess,
+ SkillTargetsPutSuccessSchema,
+ type SkillUninstallRequest,
+ SkillUninstallRequestSchema,
+ type SkillUninstallSuccess,
+ SkillUninstallSuccessSchema,
+ type SkillUpdateRequest,
+ SkillUpdateRequestSchema,
+ type SkillUpdateSuccess,
+ SkillUpdateSuccessSchema,
type SpawnCursorRequest,
SpawnCursorRequestSchema,
type SpawnCursorSuccess,
@@ -806,6 +898,7 @@ export {
TagsForNameSuccessSchema,
type TagsListSuccess,
TagsListSuccessSchema,
+ TEMPLATE_NAME_REGEX,
type TemplateDeleteSuccess,
TemplateDeleteSuccessSchema,
type TemplateFrontmatter,
@@ -925,6 +1018,16 @@ export {
type SkillStateTarget,
type SkillStateTargetEntry,
} from './skill-state/schema.ts';
+export {
+ parseSkillTargets,
+ SKILL_TARGETS_FILENAME,
+ SKILL_TARGETS_REL,
+ SKILL_TARGETS_SCHEMA_VERSION,
+ type SkillTargetEditor,
+ SkillTargetEditorSchema,
+ type SkillTargets,
+ SkillTargetsSchema,
+} from './skill-targets/schema.ts';
export {
composeTemplateFile,
instantiateDoc,
diff --git a/packages/core/src/installed-skills/schema.ts b/packages/core/src/installed-skills/schema.ts
new file mode 100644
index 000000000..fbc97a726
--- /dev/null
+++ b/packages/core/src/installed-skills/schema.ts
@@ -0,0 +1,44 @@
+import { z } from 'zod';
+import { MANAGED_ARTIFACT_SCOPES } from '../constants/cc1.ts';
+import { OK_DIR } from '../constants/ok-dir.ts';
+
+export const INSTALLED_SKILLS_FILENAME = 'installed-skills.json';
+
+export const INSTALLED_SKILLS_REL = [OK_DIR, 'local', INSTALLED_SKILLS_FILENAME] as const;
+
+export const INSTALLED_SKILLS_SCHEMA_VERSION = 1;
+
+/** Skill scope — mirrors the MCP skill-target scope (project store vs user store).
+ * Derived from the canonical `MANAGED_ARTIFACT_SCOPES` (cc1.ts) — do not
+ * re-declare the tuple. */
+export const InstalledSkillScopeSchema = z.enum(MANAGED_ARTIFACT_SCOPES);
+export type InstalledSkillScope = z.infer<typeof InstalledSkillScopeSchema>;
+
+export const InstalledSkillEntrySchema = z.looseObject({
+ hosts: z.array(z.string()),
+ scope: InstalledSkillScopeSchema,
+ scripts: z.boolean(),
+ installedAt: z.iso.datetime(),
+});
+export type InstalledSkillEntry = z.infer<typeof InstalledSkillEntrySchema>;
+
+export const InstalledSkillsSchema = z.looseObject({
+ schema: z.literal(INSTALLED_SKILLS_SCHEMA_VERSION),
+ skills: z.record(z.string(), InstalledSkillEntrySchema).default({}),
+});
+export type InstalledSkills = z.infer<typeof InstalledSkillsSchema>;
+
+export function emptyInstalledSkills(): InstalledSkills {
+ return { schema: INSTALLED_SKILLS_SCHEMA_VERSION, skills: {} };
+}
+
+export function parseInstalledSkills(raw: string): InstalledSkills | null {
+ let json: unknown;
+ try {
+ json = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ const parsed = InstalledSkillsSchema.safeParse(json);
+ return parsed.success ? parsed.data : null;
+}
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index 367bc5a1c..b5ba92cc7 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -1,5 +1,7 @@
import type { StandardSchemaV1 } from '@standard-schema/spec';
import { z } from 'zod';
+import { MANAGED_ARTIFACT_SCOPES } from '../../constants/cc1.ts';
+import { SkillTargetEditorSchema } from '../../skill-targets/schema.ts';
import { agentIdentityFields, summaryField } from './_shared.ts';
export const TagSummaryEntrySchema = z
@@ -154,6 +156,286 @@ export const TemplateMoveSuccessSchema = z
.strict() satisfies StandardSchemaV1;
export type TemplateMoveSuccess = z.infer<typeof TemplateMoveSuccessSchema>;
+/** Skill scope: `project` (shared via git) or `global` (user store).
+ * Derived from the canonical `MANAGED_ARTIFACT_SCOPES` (cc1.ts) — do not
+ * re-declare the tuple. */
+export const SkillScopeSchema = z.enum(MANAGED_ARTIFACT_SCOPES);
+export type SkillScope = z.infer<typeof SkillScopeSchema>;
+
+export const SKILL_NAME_REGEX = /^[a-z0-9-]+$/;
+
+const XML_TAG_REGEX = /<\/?[A-Za-z][^>]*>/;
+export function containsXmlTag(s: string): boolean {
+ return XML_TAG_REGEX.test(s);
+}
+
+export const TEMPLATE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;
+
+export const SkillFrontmatterSchema = z
+ .object({
+ name: z.string(),
+ description: z.string(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillFrontmatter = z.infer<typeof SkillFrontmatterSchema>;
+
+export const SkillPayloadSchema = z
+ .object({
+ name: z.string().min(1),
+ scope: SkillScopeSchema,
+ path: z.string().min(1),
+ frontmatter: SkillFrontmatterSchema,
+ body: z.string(),
+ files: z
+ .array(
+ z.object({
+ path: z.string().min(1),
+ text: z.string().nullable(),
+ }),
+ )
+ .optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillPayload = z.infer<typeof SkillPayloadSchema>;
+
+export const SkillGetSuccessSchema = z
+ .object({
+ skill: SkillPayloadSchema,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillGetSuccess = z.infer<typeof SkillGetSuccessSchema>;
+
+export const SkillsListEntrySchema = z
+ .object({
+ name: z.string().min(1),
+ description: z.string().optional(),
+ scope: SkillScopeSchema,
+ path: z.string().min(1),
+ /** Absolute on-disk path to the skill's SKILL.md — drives the desktop
+ * Reveal-in-Finder / Open-in-Terminal / Copy-Path row actions. Always set on
+ * `/api/skills` list entries; omitted on partial entries built client-side
+ * (a cold deep-link before the list loads), where those actions disable. */
+ absolutePath: z.string().min(1).optional(),
+ installed: z.boolean(),
+ hosts: z.array(z.string()),
+ installedVersion: z.string().optional(),
+ bundledVersion: z.string().optional(),
+ updateAvailable: z.boolean().optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillsListEntry = z.infer<typeof SkillsListEntrySchema>;
+
+export const SkillsListSuccessSchema = z
+ .object({
+ skills: z.array(SkillsListEntrySchema),
+ truncated: z.boolean(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillsListSuccess = z.infer<typeof SkillsListSuccessSchema>;
+
+export const SkillPutRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ name: z.string(),
+ body: z.string().optional(),
+ frontmatter: SkillFrontmatterSchema,
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillPutRequest = z.infer<typeof SkillPutRequestSchema>;
+
+export const SkillPutSuccessSchema = z
+ .object({
+ path: z.string().min(1),
+ created: z.boolean(),
+ warnings: z.array(z.string()),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillPutSuccess = z.infer<typeof SkillPutSuccessSchema>;
+
+export const SkillUpdateRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ name: z.string(),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillUpdateRequest = z.infer<typeof SkillUpdateRequestSchema>;
+
+export const SkillUpdateSuccessSchema = z
+ .object({
+ name: z.string().min(1),
+ version: z.string().min(1),
+ previousVersion: z.string().optional(),
+ checkpointRef: z.string().optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillUpdateSuccess = z.infer<typeof SkillUpdateSuccessSchema>;
+
+export const SkillDeleteSuccessSchema = z
+ .object({
+ existed: z.boolean(),
+ path: z.string().min(1),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillDeleteSuccess = z.infer<typeof SkillDeleteSuccessSchema>;
+
+export const SkillMoveRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ fromName: z.string(),
+ toName: z.string(),
+ body: z.string().optional(),
+ frontmatter: SkillFrontmatterSchema.optional(),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillMoveRequest = z.infer<typeof SkillMoveRequestSchema>;
+
+export const SkillMoveSuccessSchema = z
+ .object({
+ from: z.string().min(1),
+ to: z.string().min(1),
+ committed: z.boolean(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillMoveSuccess = z.infer<typeof SkillMoveSuccessSchema>;
+
+export const SkillFileKindSchema = z.enum(['reference', 'script']);
+export type SkillFileKind = z.infer<typeof SkillFileKindSchema>;
+
+export const SkillFilePutRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ name: z.string(),
+ path: z.string().min(1),
+ content: z.string(),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillFilePutRequest = z.infer<typeof SkillFilePutRequestSchema>;
+
+export const SkillFilePutSuccessSchema = z
+ .object({
+ path: z.string().min(1),
+ created: z.boolean(),
+ kind: SkillFileKindSchema,
+ content: z.boolean(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillFilePutSuccess = z.infer<typeof SkillFilePutSuccessSchema>;
+
+export const SkillFileGetSuccessSchema = z
+ .object({
+ path: z.string().min(1),
+ kind: SkillFileKindSchema,
+ text: z.string(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillFileGetSuccess = z.infer<typeof SkillFileGetSuccessSchema>;
+
+export const SkillFileDeleteSuccessSchema = z
+ .object({
+ path: z.string().min(1),
+ existed: z.boolean(),
+ kind: SkillFileKindSchema,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillFileDeleteSuccess = z.infer<typeof SkillFileDeleteSuccessSchema>;
+
+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.',
+ }),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillInstallRequest = z.infer<typeof SkillInstallRequestSchema>;
+
+export const SKILL_INSTALL_WARNING_CODES = ['no-targets', 'scripts-present'] 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)),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillInstallSuccess = z.infer<typeof SkillInstallSuccessSchema>;
+
+export const SkillUninstallRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ name: z.string(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillUninstallRequest = z.infer<typeof SkillUninstallRequestSchema>;
+
+export const SkillUninstallSuccessSchema = z
+ .object({
+ name: z.string().min(1),
+ uninstalled: z.boolean(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillUninstallSuccess = z.infer<typeof SkillUninstallSuccessSchema>;
+
+export const SkillTargetsGetSuccessSchema = z
+ .object({
+ targets: z.array(SkillTargetEditorSchema),
+ configured: z.boolean(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillTargetsGetSuccess = z.infer<typeof SkillTargetsGetSuccessSchema>;
+
+export const SkillTargetsPutRequestSchema = z
+ .object({
+ targets: z.array(SkillTargetEditorSchema),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillTargetsPutRequest = z.infer<typeof SkillTargetsPutRequestSchema>;
+
+export const SkillTargetsPutSuccessSchema = z
+ .object({
+ targets: z.array(SkillTargetEditorSchema),
+ reprojected: z.array(z.object({ name: z.string(), hosts: z.array(z.string()) }).strict()),
+ bundleHosts: z.array(z.string()),
+ removedFrom: z.array(z.string()),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillTargetsPutSuccess = z.infer<typeof SkillTargetsPutSuccessSchema>;
+
+export const SkillRestoreRequestSchema = z
+ .object({
+ scope: SkillScopeSchema.default('project'),
+ name: z.string(),
+ version: z.string().regex(/^[0-9a-f]{40}$/i),
+ ...agentIdentityFields,
+ summary: summaryField,
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillRestoreRequest = z.infer<typeof SkillRestoreRequestSchema>;
+
+export const SkillRestoreSuccessSchema = z
+ .object({
+ name: z.string().min(1),
+ version: z.string(),
+ restoredFiles: z.array(z.string()),
+ warnings: z.array(z.string()),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillRestoreSuccess = z.infer<typeof SkillRestoreSuccessSchema>;
+
export const SearchRequestSchema = z
.object({
query: z.string().optional(),
diff --git a/packages/core/src/skill-targets/editor-single-source.test.ts b/packages/core/src/skill-targets/editor-single-source.test.ts
new file mode 100644
index 000000000..a3b3cda6a
--- /dev/null
+++ b/packages/core/src/skill-targets/editor-single-source.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ ALL_EDITOR_IDS,
+ EDITOR_PROJECT_SKILL_ROOT,
+ HOSTS_WITH_USER_SKILL_DIR,
+ PROJECT_SKILL_EDITOR_IDS,
+} from '../constants/editors.ts';
+import { SkillTargetEditorSchema } from './schema.ts';
+
+describe('project-skill editor-id single source', () => {
+ const asStrings = (xs: readonly string[]) => xs.map(String);
+
+ test('PROJECT_SKILL_EDITOR_IDS = exactly the editors with a non-null project-skill root', () => {
+ const expected = ALL_EDITOR_IDS.filter((id) => EDITOR_PROJECT_SKILL_ROOT[id] !== null);
+ expect(asStrings(PROJECT_SKILL_EDITOR_IDS)).toEqual(asStrings(expected));
+ });
+
+ test('SkillTargetEditorSchema.options is exactly PROJECT_SKILL_EDITOR_IDS (the wire enum derives from it)', () => {
+ expect(asStrings(SkillTargetEditorSchema.options)).toEqual(asStrings(PROJECT_SKILL_EDITOR_IDS));
+ });
+
+ test('HOSTS_WITH_USER_SKILL_DIR derives from the same editors (CLI repair-skills ↔ desktop skill-reclaim share it)', () => {
+ expect(asStrings(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.editorId))).toEqual(
+ asStrings(PROJECT_SKILL_EDITOR_IDS),
+ );
+ for (const { hostDir, editorId } of HOSTS_WITH_USER_SKILL_DIR) {
+ expect(hostDir).toBe((EDITOR_PROJECT_SKILL_ROOT[editorId] ?? '').split('/')[0]);
+ expect(hostDir.startsWith('.')).toBe(true);
+ }
+ });
+
+ test('Claude Desktop is NOT a project-skill install target (user-global only, null root)', () => {
+ expect(EDITOR_PROJECT_SKILL_ROOT['claude-desktop']).toBeNull();
+ expect(SkillTargetEditorSchema.options).not.toContain('claude-desktop');
+ });
+});
diff --git a/packages/core/src/skill-targets/schema.test.ts b/packages/core/src/skill-targets/schema.test.ts
new file mode 100644
index 000000000..dd54a9056
--- /dev/null
+++ b/packages/core/src/skill-targets/schema.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, test } from 'bun:test';
+import { PROJECT_SKILL_EDITOR_IDS } from '../constants/editors.ts';
+import { parseSkillTargets, SkillTargetEditorSchema } from './schema.ts';
+
+describe('SkillTargetEditorSchema', () => {
+ test('matches the derived PROJECT_SKILL_EDITOR_IDS (drift guard)', () => {
+ expect([...SkillTargetEditorSchema.options].sort()).toEqual(
+ [...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
new file mode 100644
index 000000000..b0de6c27d
--- /dev/null
+++ b/packages/core/src/skill-targets/schema.ts
@@ -0,0 +1,32 @@
+import { z } from 'zod';
+import { type EditorId, PROJECT_SKILL_EDITOR_IDS } from '../constants/editors.ts';
+import { OK_DIR } from '../constants/ok-dir.ts';
+
+export const SKILL_TARGETS_FILENAME = 'skill-targets.json';
+
+export const SKILL_TARGETS_REL = [OK_DIR, SKILL_TARGETS_FILENAME] as const;
+
+export const SKILL_TARGETS_SCHEMA_VERSION = 1;
+
+type ProjectSkillEditorId = Exclude<EditorId, 'claude-desktop'>;
+export const SkillTargetEditorSchema = z.enum(
+ PROJECT_SKILL_EDITOR_IDS as unknown as readonly [ProjectSkillEditorId, ...ProjectSkillEditorId[]],
+);
+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>;
+
+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;
+}
diff --git a/packages/desktop/src/main/create-new-project.test.ts b/packages/desktop/src/main/create-new-project.test.ts
index 7d0297e02..1d0a05bf7 100644
--- a/packages/desktop/src/main/create-new-project.test.ts
+++ b/packages/desktop/src/main/create-new-project.test.ts
@@ -461,12 +461,20 @@ describe('runCreateNew — installs the project-local skill (PRD-6733)', () => {
existsSync(join(result.projectDir, '.cursor', 'skills', 'open-knowledge', 'SKILL.md')),
).toBe(true);
expect(
- existsSync(join(result.projectDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md')),
+ existsSync(join(result.projectDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md')),
+ ).toBe(true);
+ expect(
+ existsSync(join(result.projectDir, '.opencode', 'skills', 'open-knowledge', 'SKILL.md')),
).toBe(true);
const skillWrites = result.aiIntegrations.integrations.filter(
(o) => o.integration === 'project-skill' && o.action === 'written',
);
- expect(skillWrites.map((o) => o.editorId).sort()).toEqual(['claude', 'codex', 'cursor']);
+ expect(skillWrites.map((o) => o.editorId).sort()).toEqual([
+ 'claude',
+ 'codex',
+ 'cursor',
+ 'opencode',
+ ]);
});
});
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index d2367bbbc..f2f0743c2 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -41,6 +41,7 @@ import {
} from '@inkeep/open-knowledge-core';
import {
assertGitAvailable,
+ BUNDLE_SKILL_NAME,
classifyFsPath,
createEphemeralProjectDir,
ensureProjectGit,
@@ -58,6 +59,7 @@ import {
recordSkillInstallEvent,
resolveBundledSkillDir,
resolveLockDir,
+ USER_GLOBAL_BUNDLE_IDS,
withSpan,
writeTargetVersion,
} from '@inkeep/open-knowledge-server';
@@ -2749,12 +2751,17 @@ function bootPrimaryInstance(): void {
forceEnv: process.env.OK_M6B_FORCE ?? null,
reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
deps: {
- resolveBundledSkillDir: () =>
- resolveBundledSkillDir('discovery', { checkDesktop: false }),
+ userGlobalBundles: USER_GLOBAL_BUNDLE_IDS.map((id) => ({
+ id,
+ name: BUNDLE_SKILL_NAME[id],
+ })),
+ resolveBundledSkillDir: (bundle) =>
+ resolveBundledSkillDir(bundle, { checkDesktop: false }),
readServerPackageVersion,
writeTargetVersion: (home, target, version, surface) =>
writeTargetVersion(home, target, version, surface),
- recordSkillInstallEvent: (event) => recordSkillInstallEvent(event),
+ recordSkillInstallEvent: (event) =>
+ recordSkillInstallEvent(event as Parameters<typeof recordSkillInstallEvent>[0]),
},
}).catch((err) => {
console.warn('[main] user-skill reclaim failed', {
diff --git a/packages/desktop/src/main/skill-reclaim.test.ts b/packages/desktop/src/main/skill-reclaim.test.ts
index 5bbc8f225..6c892a7e9 100644
--- a/packages/desktop/src/main/skill-reclaim.test.ts
+++ b/packages/desktop/src/main/skill-reclaim.test.ts
@@ -52,13 +52,14 @@ function makeHome(): string {
interface CapturedEvent {
ts: string;
outcome: 'installed' | 'failed';
- bundle?: 'discovery';
+ bundle?: string;
version?: string;
reason?: string;
}
interface FakeDeps {
- resolveBundledSkillDir(): string;
+ userGlobalBundles: ReadonlyArray<{ id: string; name: string }>;
+ resolveBundledSkillDir(bundle: string): string;
readServerPackageVersion(): Promise<string>;
writeTargetVersion(
home: string,
@@ -70,7 +71,7 @@ interface FakeDeps {
ts: string;
surface: 'desktop-direct';
target: 'cli-hosts';
- bundle?: 'discovery';
+ bundle?: string;
outcome: 'installed' | 'failed';
version?: string;
reason?: string;
@@ -79,6 +80,10 @@ interface FakeDeps {
events: CapturedEvent[];
}
+/** Default test bundle set — discovery only, so existing single-bundle
+ * assertions hold; multi-bundle tests pass an explicit list. */
+const DISCOVERY_ONLY_BUNDLES = [{ id: 'discovery', name: 'open-knowledge-discovery' }] as const;
+
function makeDeps(opts: {
bundle: string;
version?: string;
@@ -91,6 +96,7 @@ function makeDeps(opts: {
const stateWrites: Array<{ home: string; version: string }> = [];
const events: CapturedEvent[] = [];
return {
+ userGlobalBundles: DISCOVERY_ONLY_BUNDLES,
resolveBundledSkillDir: () => {
if (opts.resolveThrows) throw opts.resolveThrows;
return opts.bundle;
@@ -157,6 +163,34 @@ describe('reclaimUserSkillsOnLaunch', () => {
]);
});
+ test('installs every user-global bundle (discovery + write-skill) into central + per-host', async () => {
+ const home = makeHome();
+ const bundle = setupBundle();
+ mkdirSync(join(home, '.claude', 'skills'), { recursive: true });
+ const deps = {
+ ...makeDeps({ bundle, version: '1.0.0' }),
+ userGlobalBundles: [
+ { id: 'discovery', name: 'open-knowledge-discovery' },
+ { id: 'write-skill', name: 'open-knowledge-write-skill' },
+ ],
+ };
+ const r = await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ });
+ expect(r.status).toBe('done');
+ for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
+ expect(existsSync(join(home, '.agents', 'skills', name, 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(home, '.claude', 'skills', name, 'SKILL.md'))).toBe(true);
+ }
+ const installed = deps.events.filter((e) => e.outcome === 'installed').map((e) => e.bundle);
+ expect(installed.sort()).toEqual(['discovery', 'write-skill']);
+ expect(deps.stateWrites).toEqual([{ home, version: '1.0.0' }]);
+ });
+
test('central store overwrites existing files even when same path is present', async () => {
const home = makeHome();
const bundle = setupBundle();
@@ -203,8 +237,9 @@ describe('reclaimUserSkillsOnLaunch', () => {
expect(existsSync(join(home, '.cursor', 'skills', 'open-knowledge-discovery'))).toBe(false);
});
- test('codex host (.agents) collapses with central path at user scope — written once, not twice', async () => {
+ test('codex installs to its own .codex host dir, distinct from the .agents central store', async () => {
const home = makeHome();
+ mkdirSync(join(home, '.codex'), { recursive: true });
const bundle = setupBundle();
const deps = makeDeps({ bundle, version: '1.2.3' });
const events: Array<Record<string, unknown>> = [];
@@ -223,15 +258,16 @@ describe('reclaimUserSkillsOnLaunch', () => {
if (r.status === 'done') {
const central = r.entries.find((e) => e.kind === 'central');
expect(central?.status).toBe('written');
+ expect(central?.path).toContain(join('.agents', 'skills'));
const codex = r.entries.find((e) => e.kind === 'host' && e.editorId === 'codex');
- expect(codex).toBeUndefined();
+ expect(codex?.status).toBe('written');
+ expect(codex?.path).toContain(join('.codex', 'skills'));
+ expect(codex?.path).not.toBe(central?.path);
}
- const centralEvents = events.filter((e) => e.event === 'user-skill-reclaim-central-written');
- expect(centralEvents).toHaveLength(1);
- const codexHostEvents = events.filter(
- (e) => e.event === 'user-skill-reclaim-host-written' && e.editorId === 'codex',
- );
- expect(codexHostEvents).toHaveLength(0);
+ expect(events.filter((e) => e.event === 'user-skill-reclaim-central-written')).toHaveLength(1);
+ expect(
+ events.filter((e) => e.event === 'user-skill-reclaim-host-written' && e.editorId === 'codex'),
+ ).toHaveLength(1);
});
test('per-host overwrite when SKILL.md already exists (force-write)', async () => {
@@ -403,10 +439,10 @@ describe('reclaimProjectSkillsOnProjectOpen', () => {
expect(existsSync(join(projectDir, '.agents'))).toBe(false);
});
- test('codex project skill at .agents/skills/open-knowledge is reclaimed when present', async () => {
+ test('codex project skill at .codex/skills/open-knowledge is reclaimed when present', async () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-proj-'));
cleanupPaths.push(projectDir);
- const codexSkill = join(projectDir, '.agents', 'skills', 'open-knowledge');
+ const codexSkill = join(projectDir, '.codex', 'skills', 'open-knowledge');
mkdirSync(codexSkill, { recursive: true });
writeFileSync(join(codexSkill, 'SKILL.md'), '---\nname: open-knowledge\n---\n# v-old\n');
const bundle = setupBundle();
@@ -572,7 +608,7 @@ describe('reclaimProjectSkillsOnProjectOpen — createIfWired (managed heal path
expect(r.entries.find((e) => e.editorId === 'codex')?.status).toBe('created');
expect(r.entries.find((e) => e.editorId === 'claude')?.status).toBe('no-token');
}
- expect(existsSync(join(projectDir, '.agents', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ expect(existsSync(join(projectDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
true,
);
});
diff --git a/packages/desktop/src/main/skill-reclaim.ts b/packages/desktop/src/main/skill-reclaim.ts
index c6b4a04b1..43e6acec6 100644
--- a/packages/desktop/src/main/skill-reclaim.ts
+++ b/packages/desktop/src/main/skill-reclaim.ts
@@ -8,7 +8,11 @@ import {
writeFileSync as fsWriteFileSync,
} from 'node:fs';
import { dirname, join } from 'node:path';
-import { assertProjectPathSafe, EDITOR_TARGETS, type EditorId } from '@inkeep/open-knowledge';
+import {
+ assertProjectPathSafe,
+ EDITOR_TARGETS,
+ HOSTS_WITH_USER_SKILL_DIR,
+} from '@inkeep/open-knowledge';
interface SkillReclaimLogger {
event(payload: { event: string; [key: string]: unknown }): void;
@@ -20,22 +24,10 @@ const DEFAULT_LOGGER: SkillReclaimLogger = {
warn: (message, ctx) => console.warn('[skill-reclaim]', message, ctx ?? ''),
};
-const HOSTS_WITH_USER_SKILL_DIR: ReadonlyArray<{
- readonly hostDir: string;
- readonly editorId: EditorId;
-}> = [
- { hostDir: '.claude', editorId: 'claude' },
- { hostDir: '.cursor', editorId: 'cursor' },
- { hostDir: '.agents', editorId: 'codex' },
- { hostDir: '.agents', editorId: 'opencode' },
-];
-
const OK_MCP_MARKER = '# ok-mcp-v1';
-const USER_SKILL_DIR_NAME = 'open-knowledge-discovery';
const PROJECT_SKILL_DIR_NAME = 'open-knowledge';
const LEGACY_SKILL_DIR_NAME = 'open-knowledge';
-const CENTRAL_USER_SKILL_REL = ['.agents', 'skills', USER_SKILL_DIR_NAME] as const;
interface SkillFsOps {
existsSync(path: string): boolean;
@@ -89,8 +81,9 @@ function copyDirContents(sourceDir: string, destDir: string, fs: SkillFsOps): vo
}
function removeLegacyUserSkillDirs(home: string, fs: SkillFsOps, logger: SkillReclaimLogger): void {
- for (const host of HOSTS_WITH_USER_SKILL_DIR) {
- const legacyDir = join(home, host.hostDir, 'skills', LEGACY_SKILL_DIR_NAME);
+ const legacyHostDirs = [...HOSTS_WITH_USER_SKILL_DIR.map((h) => h.hostDir), '.agents'];
+ for (const hostDir of legacyHostDirs) {
+ const legacyDir = join(home, hostDir, 'skills', LEGACY_SKILL_DIR_NAME);
if (!fs.existsSync(legacyDir)) continue;
try {
fs.rmSync(legacyDir, { recursive: true, force: true });
@@ -128,7 +121,11 @@ interface ReclaimUserSkillsOpts {
forceEnv?: string | null | undefined;
reclaimDisableEnv?: string | null | undefined;
deps: {
- resolveBundledSkillDir(): string;
+ /** The user-global built-in bundles to install (id + install dir name).
+ * Wired from core's `USER_GLOBAL_BUNDLE_IDS` by the caller — this module
+ * stays free of server/core imports. */
+ userGlobalBundles: ReadonlyArray<{ id: string; name: string }>;
+ resolveBundledSkillDir(bundle: string): string;
readServerPackageVersion(): Promise<string>;
writeTargetVersion(
home: string,
@@ -140,7 +137,7 @@ interface ReclaimUserSkillsOpts {
ts: string;
surface: 'desktop-direct';
target: 'cli-hosts';
- bundle?: 'discovery';
+ bundle?: string;
outcome: 'installed' | 'failed';
version?: string;
reason?: string;
@@ -151,73 +148,16 @@ interface ReclaimUserSkillsOpts {
logger?: SkillReclaimLogger;
}
-export async function reclaimUserSkillsOnLaunch(
- opts: ReclaimUserSkillsOpts,
-): Promise<UserSkillReclaimResult> {
- const {
- home,
- isPackaged,
- platform,
- executablePath,
- forceEnv,
- reclaimDisableEnv,
- deps,
- fs = defaultFsOps,
- now,
- logger = DEFAULT_LOGGER,
- } = opts;
- const nowDate = (): Date => (now ? now() : new Date());
-
- if (reclaimDisableEnv === '1') return { status: 'skipped', reason: 'reclaim-disabled' };
- if (platform !== 'darwin') return { status: 'skipped', reason: 'platform' };
- if (!isPackaged && forceEnv !== '1') return { status: 'skipped', reason: 'dev-mode' };
- if (!/\.app\/Contents\/MacOS\/[^/]+$/.test(executablePath)) {
- return { status: 'skipped', reason: 'bad-executable-path' };
- }
-
- let sourceDir: string;
- try {
- sourceDir = deps.resolveBundledSkillDir();
- } catch (err) {
- const error = err instanceof Error ? err.message : String(err);
- logger.event({ event: 'user-skill-reclaim-bundle-missing', error });
- await deps
- .recordSkillInstallEvent({
- ts: nowDate().toISOString(),
- surface: 'desktop-direct',
- target: 'cli-hosts',
- bundle: 'discovery',
- outcome: 'failed',
- reason: `bundle-missing:${error}`,
- })
- .catch(() => {});
- return { status: 'skipped', reason: 'bundle-missing' };
- }
-
- let version: string;
- try {
- version = await deps.readServerPackageVersion();
- } catch (err) {
- const error = err instanceof Error ? err.message : String(err);
- logger.event({ event: 'user-skill-reclaim-version-read-failed', error });
- await deps
- .recordSkillInstallEvent({
- ts: nowDate().toISOString(),
- surface: 'desktop-direct',
- target: 'cli-hosts',
- bundle: 'discovery',
- outcome: 'failed',
- reason: `version-read-failed:${error}`,
- })
- .catch(() => {});
- return { status: 'skipped', reason: 'version-read-failed' };
- }
-
- removeLegacyUserSkillDirs(home, fs, logger);
-
+function installUserBundleToHostDirs(
+ home: string,
+ bundleDirName: string,
+ sourceDir: string,
+ fs: SkillFsOps,
+ logger: SkillReclaimLogger,
+ version: string,
+): UserSkillReclaimEntry[] {
const entries: UserSkillReclaimEntry[] = [];
-
- const centralDest = join(home, ...CENTRAL_USER_SKILL_REL);
+ const centralDest = join(home, '.agents', 'skills', bundleDirName);
const centralExistedBefore = fs.existsSync(centralDest);
try {
replaceDir(sourceDir, centralDest, fs);
@@ -240,7 +180,7 @@ export async function reclaimUserSkillsOnLaunch(
for (const host of HOSTS_WITH_USER_SKILL_DIR) {
const hostRoot = join(home, host.hostDir);
- const hostDest = join(hostRoot, 'skills', USER_SKILL_DIR_NAME);
+ const hostDest = join(hostRoot, 'skills', bundleDirName);
if (hostDest === centralDest) {
continue;
}
@@ -289,36 +229,117 @@ export async function reclaimUserSkillsOnLaunch(
});
}
}
+ return entries;
+}
- const anyWriteSucceeded = entries.some(
- (e) => e.status === 'written' || e.status === 'overwritten',
- );
- if (anyWriteSucceeded) {
- let stateWriteError: string | null = null;
+export async function reclaimUserSkillsOnLaunch(
+ opts: ReclaimUserSkillsOpts,
+): Promise<UserSkillReclaimResult> {
+ const {
+ home,
+ isPackaged,
+ platform,
+ executablePath,
+ forceEnv,
+ reclaimDisableEnv,
+ deps,
+ fs = defaultFsOps,
+ now,
+ logger = DEFAULT_LOGGER,
+ } = opts;
+ const nowDate = (): Date => (now ? now() : new Date());
+
+ if (reclaimDisableEnv === '1') return { status: 'skipped', reason: 'reclaim-disabled' };
+ if (platform !== 'darwin') return { status: 'skipped', reason: 'platform' };
+ if (!isPackaged && forceEnv !== '1') return { status: 'skipped', reason: 'dev-mode' };
+ if (!/\.app\/Contents\/MacOS\/[^/]+$/.test(executablePath)) {
+ return { status: 'skipped', reason: 'bad-executable-path' };
+ }
+
+ const resolvedBundles: Array<{ id: string; name: string; sourceDir: string }> = [];
+ let lastResolveError: string | null = null;
+ for (const bundle of deps.userGlobalBundles) {
try {
- await deps.writeTargetVersion(home, 'cli-hosts', version, 'desktop-direct');
+ resolvedBundles.push({ ...bundle, sourceDir: deps.resolveBundledSkillDir(bundle.id) });
} catch (err) {
- stateWriteError = err instanceof Error ? err.message : String(err);
- logger.warn('writeTargetVersion failed', { error: stateWriteError });
+ lastResolveError = err instanceof Error ? err.message : String(err);
}
+ }
+ if (resolvedBundles.length === 0) {
+ logger.event({
+ event: 'user-skill-reclaim-bundle-missing',
+ error: lastResolveError ?? 'no user-global bundles',
+ });
+ await deps
+ .recordSkillInstallEvent({
+ ts: nowDate().toISOString(),
+ surface: 'desktop-direct',
+ target: 'cli-hosts',
+ outcome: 'failed',
+ reason: `bundle-missing:${lastResolveError}`,
+ })
+ .catch(() => {});
+ return { status: 'skipped', reason: 'bundle-missing' };
+ }
+
+ let version: string;
+ try {
+ version = await deps.readServerPackageVersion();
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ logger.event({ event: 'user-skill-reclaim-version-read-failed', error });
await deps
.recordSkillInstallEvent({
ts: nowDate().toISOString(),
surface: 'desktop-direct',
target: 'cli-hosts',
bundle: 'discovery',
- outcome: stateWriteError === null ? 'installed' : 'failed',
- version,
- ...(stateWriteError === null ? {} : { reason: `state-write-failed:${stateWriteError}` }),
+ outcome: 'failed',
+ reason: `version-read-failed:${error}`,
})
.catch(() => {});
+ return { status: 'skipped', reason: 'version-read-failed' };
+ }
+
+ removeLegacyUserSkillDirs(home, fs, logger);
+
+ const entries: UserSkillReclaimEntry[] = [];
+ for (const bundle of resolvedBundles) {
+ entries.push(
+ ...installUserBundleToHostDirs(home, bundle.name, bundle.sourceDir, fs, logger, version),
+ );
+ }
+
+ const anyWriteSucceeded = entries.some(
+ (e) => e.status === 'written' || e.status === 'overwritten',
+ );
+ if (anyWriteSucceeded) {
+ let stateWriteError: string | null = null;
+ try {
+ await deps.writeTargetVersion(home, 'cli-hosts', version, 'desktop-direct');
+ } catch (err) {
+ stateWriteError = err instanceof Error ? err.message : String(err);
+ logger.warn('writeTargetVersion failed', { error: stateWriteError });
+ }
+ for (const bundle of resolvedBundles) {
+ await deps
+ .recordSkillInstallEvent({
+ ts: nowDate().toISOString(),
+ surface: 'desktop-direct',
+ target: 'cli-hosts',
+ bundle: bundle.id,
+ outcome: stateWriteError === null ? 'installed' : 'failed',
+ version,
+ ...(stateWriteError === null ? {} : { reason: `state-write-failed:${stateWriteError}` }),
+ })
+ .catch(() => {});
+ }
} else {
await deps
.recordSkillInstallEvent({
ts: nowDate().toISOString(),
surface: 'desktop-direct',
target: 'cli-hosts',
- bundle: 'discovery',
outcome: 'failed',
version,
reason: 'all-targets-failed',
diff --git a/packages/server/assets/skills/discovery/SKILL.md b/packages/server/assets/skills/discovery/SKILL.md
index 3d2d8e2df..4ffeb031f 100644
--- a/packages/server/assets/skills/discovery/SKILL.md
+++ b/packages/server/assets/skills/discovery/SKILL.md
@@ -1,6 +1,6 @@
---
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 install-skill` / 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 Open Knowledge is, wants to install it on a repository, wants to share an Open Knowledge project with collaborators, or asks how `ok init` / `ok cowork` / OK Desktop set up a project. Do NOT load to perform Open Knowledge 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."
compatibility: "Any agent host — no MCP server required. Pure discovery + install guidance."
metadata:
version: "0.19.2"
@@ -57,10 +57,10 @@ An OK project travels with its repository. To share one:
Collaboration is real-time once two writers have the project open against the
same content directory.
-## `ok install-skill` — Claude Chat & Cowork
+## `ok cowork` — Claude Chat & Cowork
`ok init`'s editor wiring does not reach Claude Chat or Cowork — those read a
-separate Skills list inside the Claude Desktop App. Run `ok install-skill` to
+separate Skills list inside the Claude Desktop App. Run `ok cowork` to
build `openknowledge.skill` and open Claude Desktop so the user can upload it
(Customize → Skills → + → Create skill → Upload skill).
diff --git a/packages/server/assets/skills/packs/codebase-wiki/SKILL.md b/packages/server/assets/skills/packs/codebase-wiki/SKILL.md
index 355904849..5c0ce427d 100644
--- a/packages/server/assets/skills/packs/codebase-wiki/SKILL.md
+++ b/packages/server/assets/skills/packs/codebase-wiki/SKILL.md
@@ -1,5 +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."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack codebase-wiki`."
metadata:
diff --git a/packages/server/assets/skills/packs/entity-vault/SKILL.md b/packages/server/assets/skills/packs/entity-vault/SKILL.md
index fd2b7a6a5..340d549d0 100644
--- a/packages/server/assets/skills/packs/entity-vault/SKILL.md
+++ b/packages/server/assets/skills/packs/entity-vault/SKILL.md
@@ -1,5 +1,6 @@
---
name: open-knowledge-pack-entity-vault
+version: "0.18.0"
description: "How to work in an Entity vault 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."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack entity-vault`."
metadata:
diff --git a/packages/server/assets/skills/packs/knowledge-base/SKILL.md b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
index e19d087ad..5af9cb00b 100644
--- a/packages/server/assets/skills/packs/knowledge-base/SKILL.md
+++ b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
@@ -1,5 +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."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack knowledge-base`."
metadata:
diff --git a/packages/server/assets/skills/packs/okf/SKILL.md b/packages/server/assets/skills/packs/okf/SKILL.md
index 5414e71f9..e0ab0f42f 100644
--- a/packages/server/assets/skills/packs/okf/SKILL.md
+++ b/packages/server/assets/skills/packs/okf/SKILL.md
@@ -1,5 +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."
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
diff --git a/packages/server/assets/skills/packs/plain-notes/SKILL.md b/packages/server/assets/skills/packs/plain-notes/SKILL.md
index fd0c26090..e465e345b 100644
--- a/packages/server/assets/skills/packs/plain-notes/SKILL.md
+++ b/packages/server/assets/skills/packs/plain-notes/SKILL.md
@@ -1,5 +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."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack plain-notes`."
metadata:
diff --git a/packages/server/assets/skills/packs/software-lifecycle/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
index cf6e0e7a4..d53b2fd91 100644
--- a/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
+++ b/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
@@ -1,5 +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."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack software-lifecycle`."
metadata:
diff --git a/packages/server/assets/skills/packs/worldbuilding/SKILL.md b/packages/server/assets/skills/packs/worldbuilding/SKILL.md
index 839bdffc7..c95335ac5 100644
--- a/packages/server/assets/skills/packs/worldbuilding/SKILL.md
+++ b/packages/server/assets/skills/packs/worldbuilding/SKILL.md
@@ -1,5 +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."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack worldbuilding`."
metadata:
diff --git a/packages/server/assets/skills/packs/writing-pipeline/SKILL.md b/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
index 1186eae81..8cfbd1ae1 100644
--- a/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
+++ b/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
@@ -1,5 +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."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server. Installed project-local by `ok seed --pack writing-pipeline`."
metadata:
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index d1138b9b4..2d70a20ba 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -15,6 +15,8 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th
> Skill version: tracks `@inkeep/open-knowledge-server` package version. Check `cat ~/.ok/skill-state.yml` to see what's installed locally. **Version floor:** `ok seed` (referenced below) requires `@inkeep/open-knowledge` >= 0.4.0. If `ok seed` errors with `unknown command`, upgrade: `npm install -g @inkeep/open-knowledge`.
+> **Setup (not connected yet?).** If the `mcp__open-knowledge__*` tools aren't available in your client, this project isn't wired up on this machine — see [`references/setup.md`](references/setup.md) for the rung ladder (approve `.mcp.json` → `ok start` CLI → optional desktop app) and the canonical quickstart.
+
## TL;DR — the 90% case
1. **Reads:** `exec("cat …")` for a single doc, `exec("ls -A …")` for a directory (with 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`.
@@ -22,20 +24,23 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th
3. **Preview:** every OK read/write response carries a route-only `previewUrl` (`/#/<doc>`, no host:port). If you have a `preview_*` tool, call `preview_start("open-knowledge-ui")`; if you have an in-app browser, call `preview_url` once for the full browser URL and navigate to it; on the Claude Code CLI (no browser tool), run `ok open <doc>` to open it in the OK Desktop app. Surface to the user on a `start-ui` warning (no UI running). Don't `preview_screenshot` to confirm edits — the CRDT tool response is the confirmation.
4. **Workflow guides** — `workflow({ kind: 'ingest' | 'research' | 'consolidate' | 'discover' })` returns a procedural guide, not data. Use it when the work fits the layer; follow the numbered steps.
5. **Direct questions:** a plain business question ("which customers…", "can we use…", "what did we decide about…") routes to `search` / `exec` + a cited answer — no "research" or "report" keyword needed. Persist the answer as a page only when it is durable, spans multiple docs, and isn't already covered — *offer* first, never auto-create. See §Answering direct questions from the corpus.
+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 — don't improvise from this skill, hand-edit `.ok/skills/…`, or narrate internal build steps / repo paths / project codenames to the user. It owns scope choice (project vs global), the SKILL.md contract, evaluation, and install. Use it for *improving* an existing skill too, not just new ones. **Never read, diff, or edit the installed projections under `.claude/skills/` · `.cursor/skills/` · `.codex/skills/` · `.opencode/skills/` · `.agents/skills/`** — those are generated by `install` and overwritten on the next sync; they are NOT a source of truth (a newer projection over an older checkout is expected, not "stale source"). The skill source lives behind the `skill` target / `write-skill`.
Everything below is depth. Read on demand.
-## Tool index — 17 tools
+## Tool index — 19 tools
The full MCP surface, grouped by risk-level. Every tool's `kind` / `action` set is single-risk-level (never a read and a write behind one discriminator).
-- **Reads** — `exec` (primary; shell-style `cat`/`ls`/`grep`/`find` with frontmatter + backlink + history enrichment), `search` (ranked, BM25 + recency), `history` (versions for a doc), `links` (`kind: 'backlinks'|'forward'|'dead'|'orphans'|'hubs'|'suggest'`, or an array of those for a one-call audit, e.g. `links({ kind: ["dead", "orphans", "hubs"] })`), `config` (resolved config), `palette` (markdown-native authoring forms + themed `html preview` embed starters + theme tokens; pass `components` for the canonical component JSX schemas), `preview_url` (browser-reachable preview URL on demand), `share_link` (GitHub-substrate share URL for a doc or folder; read-only against `.git/`, no commits/pushes — returns a clear error when the project has no GitHub remote, since agents do not publish projects).
-- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `asset` (Pattern B: per-target fields nested inside the address key; pass EXACTLY ONE target):
- - `write` — create/overwrite a `document` (supports `document.template` instantiation), create a `folder` (with open-shape frontmatter), create a `template`, or upload an `asset`.
- - `edit` — modify a `document` (body find/replace OR frontmatter merge-patch), a `folder` (frontmatter merge-patch), or a `template`. (No asset — binary has no text body.)
- - `delete` — remove a `document` (name or array), `folder`, `template`, or `asset`.
- - `move` — move/rename a `document`, `folder`, or `asset`; rewrites referrers.
- The OUTPUT mirrors the input: `write`/`edit`/`delete` nest their result under the same target key you passed (`{ document: {…} }` / `{ folder: {…} }` / `{ template: {…} }` / `{ asset: {…} }`, or `{ documents: [...] }` for a batch). The preview envelope (`previewUrl`, `warning`, `previousPreviewUrl`) stays at the top level — same for every tool.
+- **Reads** — `exec` (primary; shell-style `cat`/`ls`/`grep`/`find` with frontmatter + backlink + history enrichment), `search` (ranked, BM25 + recency), `history` (versions for a doc), `links` (`kind: 'backlinks'|'forward'|'dead'|'orphans'|'hubs'|'suggest'`, or an array of those for a one-call audit, e.g. `links({ kind: ["dead", "orphans", "hubs"] })`), `skills` (find + read skills: omit `name` to LIST every skill across Project + Global levels, pass `name` to READ one — addressed by `name`+`scope`, NEVER by path), `config` (resolved config), `palette` (markdown-native authoring forms + themed `html preview` embed starters + theme tokens; pass `components` for the canonical component JSX schemas), `preview_url` (browser-reachable preview URL on demand), `share_link` (GitHub-substrate share URL for a doc or folder; read-only against `.git/`, no commits/pushes — returns a clear error when the project has no GitHub remote, since agents do not publish projects).
+- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `skill` / `asset` (Pattern B: per-target fields nested inside the address key; pass EXACTLY ONE target):
+ - `write` — create/overwrite a `document` (supports `document.template` instantiation), create a `folder` (with open-shape frontmatter), create a `template`, **author a `skill`** (`skill: { name, description, body, scope? }` → writes `.ok/skills/<name>/SKILL.md` — this is how you create a skill; NEVER a raw `document` path under `.ok/skills/`), or upload an `asset`. A newly authored skill is a **Draft** until you `install` it (see below).
+ - `edit` — modify a `document` (body find/replace OR frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. (No asset — binary has no text body.)
+ - `delete` — remove a `document` (name or array), `folder`, `template`, `skill`, or `asset`.
+ - `move` — move/rename a `document`, `folder`, `skill`, or `asset`; rewrites referrers. A skill also takes `scope`/`toScope` to move between the Project and Global levels (history resets; the moved skill is a Draft — re-`install`).
+ - `install` — the explicit Draft → Installed step for a `skill`: projects an authored skill into your editors (`targets?` to choose Claude/Cursor/Codex/OpenCode; defaults to the editors this project is set up for). Run after `write({ skill })` so the skill is live, not just authored.
+ - **Authoring or improving a skill?** Invoke the **`open-knowledge-write-skill`** skill (see TL;DR #6) — it walks the SKILL.md frontmatter + structure contract, picks scope (project vs global), evaluates, and installs it. Don't improvise from this skill. Author skills through the `skill` target above, never as a raw `.ok/skills/...` document.
+ The OUTPUT mirrors the input: `write`/`edit`/`delete` nest their result under the same target key you passed (`{ document: {…} }` / `{ folder: {…} }` / `{ template: {…} }` / `{ skill: {…} }` / `{ asset: {…} }`, or `{ documents: [...] }` for a batch). The preview envelope (`previewUrl`, `warning`, `previousPreviewUrl`) stays at the top level — same for every tool.
Plus `checkpoint` (save a named version) and `restore_version` (roll a doc back to a prior version). A folder's own frontmatter is open-shape exactly like a doc's (self-only, does NOT cascade into child docs); templates are what new docs in a folder start with.
**Self-correcting on misuse:** the few constraints JSON Schema can't express — "pass exactly one target", "`find` needs a `replace`", body-XOR-frontmatter — are enforced by a *teaching error*: a wrong call returns `isError: true` with a one-line message naming the exact corrective shape. Read it and retry with that shape; don't guess.
- **GitHub-sync conflicts** — `conflicts` (`kind: 'list'` to enumerate, `kind: 'content'` for base/ours/theirs stages + lifecycle), `resolve_conflict` (write a chosen resolution + commit; destructive). Mutating writes against a doc in conflict return RFC 9457 `urn:ok:error:doc-in-conflict` (409); `exec("cat …")` returns `lifecycle: {status, reason} | null` so you can detect the state proactively. See *Conflict-aware writes*.
@@ -52,6 +57,7 @@ When this workspace has OpenKnowledge MCP configured, do **not** use your host's
- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `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 `Read` / `Grep` / `Glob` internally and bypass OpenKnowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.
- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.
+- **`ls` / `cat` / `find` on `.ok/skills/` to discover or read a skill** — `.ok/` 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.
Why: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK's tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`) and returns raw stdout plus enriched metadata per file. One command or a pipe (`|`) per call — it is NOT a shell, so `&&` / `;` / redirects are rejected; list several dirs with `ls -A a b c` or make separate calls.
diff --git a/packages/server/assets/skills/project/references/setup.md b/packages/server/assets/skills/project/references/setup.md
new file mode 100644
index 000000000..cd6117558
--- /dev/null
+++ b/packages/server/assets/skills/project/references/setup.md
@@ -0,0 +1,26 @@
+# Setting up Open Knowledge
+
+This repository is an Open Knowledge (OK) project: its `.md` / `.mdx` files are CRDT documents, and agents work with them through the Open Knowledge MCP server. If your agent's `mcp__open-knowledge__*` tools aren't available, the project just isn't connected on this machine yet. Connect it at whatever depth you need — each rung adds capability, and you can stop at the first one that covers your task.
+
+**Canonical, always-current instructions:** <https://openknowledge.ai/docs/get-started/quickstart>. The rungs below are a quick orientation; the docs are authoritative (release channels and download links move, so this file deliberately points there rather than pinning them).
+
+## Rung 1 — Agent tooling, no install
+
+Approve the committed `.mcp.json` in your agent client (Claude Code, Cursor, Codex, …). It launches the OK MCP server on demand via `npx`, so there is nothing to install. This gives you the read tools (`exec`, `search`) over the docs plus the fs-direct write tools (`write` / `edit` for markdown and skills).
+
+This rung does **not** start a collaboration server, so it does not give you live CRDT co-editing or the browser preview — those need rung 2.
+
+## Rung 2 — Full editing + live preview, via the CLI
+
+Install the OK CLI and start a local server:
+
+```bash
+npm install -g @inkeep/open-knowledge # or run it ad hoc with: npx @inkeep/open-knowledge
+ok start
+```
+
+`ok start` runs the collaboration server and serves a browser preview at the URL it prints — no GUI required. Markdown writes now land in the live CRDT and the preview updates as you (or an agent) edit.
+
+## 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.
diff --git a/packages/server/assets/skills/write-skill/SKILL.md b/packages/server/assets/skills/write-skill/SKILL.md
new file mode 100644
index 000000000..c3362020e
--- /dev/null
+++ b/packages/server/assets/skills/write-skill/SKILL.md
@@ -0,0 +1,165 @@
+---
+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 Open Knowledge 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: "Open Knowledge 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.9.1"
+ author: "Inkeep"
+ repository: "https://github.com/inkeep/open-knowledge"
+---
+
+# Writing an Open Knowledge skill
+
+You are helping the user author an **Agent Skill** — a `SKILL.md` file (plus
+optional `references/` and `scripts/`) that teaches an AI agent how to do a
+recurring task. In Open Knowledge a skill is a first-class, versioned,
+installable artifact: you author it with the `write` / `edit` skill verbs, then
+`install` it into the user's editors.
+
+Skills earn their keep by being **recognized at the right moment** and **followed
+faithfully**. Most of the craft is in two places: a `description` that triggers
+reliably, and a body short and concrete enough that the agent actually does what
+it says. Work the stages below in order, but jump to where the user already is.
+
+## Stage 1 — Capture intent and classify the skill
+
+Ask only what you can't infer:
+
+- **What recurring task** should this skill handle? Get one concrete example.
+- **Skill type**, because it sets how much rigor to apply:
+ - **Reference / technique** (most skills) — "how to do X." Prose body, examples.
+ - **Discipline** — enforces a behavior the agent tends to skip under pressure
+ (e.g. "always write a failing test first"). These need the RED baseline +
+ pressure-testing in Stage 4–6; reference skills don't.
+- **Degrees of freedom** (calibrate body precision to task fragility):
+ *high* (free prose — judgment tasks), *medium* (parameterized steps), *low*
+ (a fixed `scripts/` command — when any deviation breaks the result). Don't
+ over-specify a judgment task or under-specify a fragile one.
+
+## Stage 2 — Resolve scope FIRST (never infer silently)
+
+Scope determines where the skill lives and where `install` projects it. This is
+the user's decision and has different blast radius — make it explicit.
+
+| Scope | Lives in | `install` projects 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` |
+
+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
+choice and its consequence before writing.
+
+## Stage 3 — Plan the contents
+
+- **Body** = the durable, reusable instructions — under ~500 lines. If it's
+ growing past that, move depth into `references/<topic>.md` (loaded only when
+ needed) and point at it from the body. For a **project** skill the reference
+ auto-connects in the graph either way, so a backticked `` `references/<topic>.md` ``
+ path is fine; use a `[[references/<topic>]]` wiki-link only when you want the
+ mention to be a clickable inline link. For a **global** skill use a plain
+ backtick path — global references aren't graph docs, so a wiki-link there
+ dangles. Keep references **one level deep**.
+- **Do NOT include**: a README/CHANGELOG/QUICK_REFERENCE, install instructions
+ for the skill itself, version histories, or anything host-specific. The skill
+ is the instructions, not documentation about the instructions.
+- For a **discipline** skill, plan the failure mode you're correcting and how
+ you'll prove the skill fixes it (Stage 4).
+
+## Stage 4 — RED baseline (discipline skills only)
+
+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 && bun run src/server/agent-sim.ts`) as the executor; otherwise
+reason through the baseline transcript with the user. Skip this stage for plain
+reference skills.
+
+## Stage 5 — Draft the skill
+
+Author the source with the skill verb (fs-direct; a live preview updates if a
+server is running):
+
+```
+write({ skill: { name: "<lowercase-hyphen-name>", description: "<triggers>", body: "<markdown>", scope: "project" } })
+```
+
+Frontmatter contract (validated on write — get it right):
+- `name` — lowercase letters, digits, hyphens; ≤64; **equals the directory**.
+- `description` — **≤1024 chars, no XML tags, no `version` field**. See Stage 7.
+- Nothing else. OK never injects its own frontmatter; bookkeeping lives in `.ok/`.
+
+Write the body as direct instructions to the agent (imperative, second person),
+concrete over abstract.
+
+Add depth files — `references/*.md` (loaded on demand) and `scripts/*` (shown as
+text, never executed by OK) — through the skill verbs, never native `Write`/`cat`:
+
+```
+# write one or more bundle files (independent of body — no need to resend SKILL.md)
+write({ skill: { name: "<name>", files: [{ path: "references/tiers.md", content: "..." }] } })
+
+# surgical edit inside one bundle file (mirrors edit({ document }))
+edit({ skill: { name: "<name>", file: "references/tiers.md", find: "...", replace: "..." } })
+
+# list the bundle, then read one file (no native cat)
+skills({ name: "<name>" }) # → files: [{ path, kind }]
+skills({ name: "<name>", file: "references/tiers.md" }) # → { path, kind, text }
+
+# delete specific bundle files (omit `files` to delete the whole skill)
+delete({ skill: { name: "<name>", files: ["references/tiers.md"] } })
+```
+
+Paths are skill-relative and must live under `references/` or `scripts/` (one
+level deep). A project `.md` reference becomes a live content doc that
+auto-connects to its SKILL in the graph regardless of how the body mentions it —
+a backticked `` `references/<name>.md` `` path joins the graph just like a
+`[[references/<name>]]` wiki-link. Reach for a wiki-link (or
+`[label](references/<name>.md)`) only when you want a clickable inline link.
+Global skills are different: their references aren't graph docs, so use a plain
+backtick path there — a wiki-link would dangle.
+
+## Stage 6 — GREEN eval + refactor
+
+Re-run the scenario WITH the skill. For a discipline skill, **pressure-test**:
+combine 2–3 pressures (time, authority, sunk cost) and confirm the agent still
+follows the rule — then patch any loophole and re-test (`references/pressure-testing.md`).
+For a reference skill, confirm the agent now does the task correctly and the body
+isn't longer than it needs to be. Cut anything the agent already knows.
+
+## Stage 7 — Optimize the description (this is what makes the skill fire)
+
+The `description` is the **only** thing the agent sees when deciding whether to
+load the skill. Get it right (`references/description-optimization.md`):
+- **Triggers, not a summary.** Say WHEN to use it, in the user's words and
+ phrasings — NOT a recap of the body. Summarizing the workflow in the
+ description makes the agent follow the description and skip the body.
+- **Concrete and a little pushy** to fight under-triggering: name the situations,
+ verbs, and phrasings that should activate it.
+- 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)
+
+Drafting doesn't change the agent's behavior until you project it:
+
+```
+install({ name: "<name>" })
+```
+
+This fans the validated skill into the project's configured editors
+(`.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/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.
+
+## Reminders
+
+- Prefer ONE good skill over many overlapping ones; split only when triggers diverge.
+- Avoid blanket ALWAYS/NEVER rules without a stated reason — they read as noise and
+ get ignored. Explain the why.
+- A skill that ships executable `scripts/` is projected verbatim into another
+ agent's trust domain — only include scripts the user has reviewed.
diff --git a/packages/server/assets/skills/write-skill/references/description-optimization.md b/packages/server/assets/skills/write-skill/references/description-optimization.md
new file mode 100644
index 000000000..2b2de3c30
--- /dev/null
+++ b/packages/server/assets/skills/write-skill/references/description-optimization.md
@@ -0,0 +1,34 @@
+# Optimizing a skill's `description`
+
+The `description` is the **entire** signal the agent uses to decide whether to
+load a skill. The body doesn't exist until the description fires. Optimize it
+last, deliberately.
+
+## Rules
+
+1. **Triggers, not a summary.** Describe WHEN to reach for the skill, in the
+ user's words. Do NOT recap what the body does — empirically, summarizing the
+ workflow in the description makes the model follow the description and skip
+ the body (the classic "did one review instead of the two the body required").
+2. **Be concrete and slightly pushy.** Under-triggering (the skill never loads)
+ is the common failure. Name the situations, the verbs, and the actual
+ phrasings a user would type. List several; don't rely on one abstract clause.
+3. **Stay inside the contract.** ≤1024 characters, no XML/angle-bracket tags, no
+ `version` field. A tag like `<thing>` breaks the loader.
+4. **Disambiguate from neighbors.** If a sibling skill is close, add a line on
+ when to use THIS one vs the other.
+
+## A lightweight near-miss check
+
+1. Write ~10 phrasings that SHOULD trigger the skill and ~5 adjacent ones that
+ should NOT (they belong to a different skill or no skill).
+2. Read the description cold and predict, for each phrasing, whether it would
+ fire. Every should-fire that you'd miss is a gap; every should-not that fires
+ is over-reach.
+3. Edit the description to close the gaps without grabbing the should-nots.
+ Prefer adding concrete trigger phrasings over broadening vague ones.
+
+## Shape
+
+Lead with the dominant trigger ("Use when the user wants to…"), then enumerate
+concrete situations and phrasings, then any disambiguation. Keep it scannable.
diff --git a/packages/server/assets/skills/write-skill/references/pressure-testing.md b/packages/server/assets/skills/write-skill/references/pressure-testing.md
new file mode 100644
index 000000000..f1f23b1e2
--- /dev/null
+++ b/packages/server/assets/skills/write-skill/references/pressure-testing.md
@@ -0,0 +1,40 @@
+# Pressure-testing a discipline skill
+
+A **discipline** skill enforces a behavior the agent tends to abandon under
+pressure ("write the failing test first", "get review before merging"). A skill
+that holds in the easy case but folds under pressure hasn't done its job. Test
+the hard case.
+
+## The loop (RED → GREEN → harden)
+
+1. **RED — baseline without the skill.** Run the scenario with no skill loaded.
+ Capture what the agent does AND its **rationalizations**, verbatim ("the
+ change is tiny, so skipping the test is fine"). Those exact rationalizations
+ are the loopholes the skill body must name and close.
+2. **GREEN — minimal skill.** Write the smallest body that defeats those specific
+ rationalizations. Re-run; confirm the behavior changed.
+3. **Harden under combined pressure.** Re-run with **2–3 pressures stacked** and
+ force a concrete choice:
+ - *Time*: "this is urgent, ship it now."
+ - *Authority*: "the lead said it's fine to skip."
+ - *Sunk cost*: "you already wrote 200 lines; redoing it wastes the work."
+ - Then: "What DO you do?" — make it choose, don't accept a hedge.
+4. Any new rationalization that slips through → add it to the body's
+ rationalization table and re-test. Repeat until it holds.
+
+## Rationalization table (put this in the skill body)
+
+A short table the agent reads when tempted:
+
+| The agent thinks… | Reality |
+| --- | --- |
+| "This case is too trivial to test." | Trivial code breaks too; the test is cheap. |
+| "I'm confident it works." | Confidence isn't verification; write the test. |
+
+## Running it
+
+With a server: drive the scenarios through the agent simulator
+(`cd packages/app && bun run src/server/agent-sim.ts`). Without 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/scripts/build-skill-bundles.test.ts b/packages/server/scripts/build-skill-bundles.test.ts
index e34b8a641..711c76801 100644
--- a/packages/server/scripts/build-skill-bundles.test.ts
+++ b/packages/server/scripts/build-skill-bundles.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, 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 {
BUNDLE_IDS,
buildPackSkills,
@@ -28,17 +28,26 @@ function fixture(opts: {
discovery: string;
project: string;
shared?: Record<string, string>;
+ references?: Record<string, string>;
}): SkillBundlePaths {
const root = mkdtempSync(join(tmpdir(), 'ok-skill-compose-'));
cleanup.push(root);
const skillsDir = join(root, 'skills');
for (const bundle of BUNDLE_IDS) mkdirSync(join(skillsDir, bundle), { recursive: true });
mkdirSync(join(skillsDir, '_shared'), { recursive: true });
+ for (const bundle of BUNDLE_IDS) {
+ writeFileSync(join(skillsDir, bundle, 'SKILL.md'), `# ${bundle}\n`);
+ }
writeFileSync(join(skillsDir, 'discovery', 'SKILL.md'), opts.discovery);
writeFileSync(join(skillsDir, 'project', 'SKILL.md'), opts.project);
for (const [name, body] of Object.entries(opts.shared ?? {})) {
writeFileSync(join(skillsDir, '_shared', name), body);
}
+ for (const [rel, body] of Object.entries(opts.references ?? {})) {
+ const dest = join(skillsDir, rel);
+ mkdirSync(dirname(dest), { recursive: true });
+ writeFileSync(dest, body);
+ }
return { skillsDir, distDir: join(root, 'dist', 'assets', 'skills') };
}
@@ -74,22 +83,36 @@ describe('composeSkill', () => {
});
describe('buildSkillBundles', () => {
- test('composes both bundles into dist/<bundle>/SKILL.md', () => {
+ test('composes EVERY canonical bundle into dist/<bundle>/SKILL.md and resolves placeholders', () => {
const paths = fixture({
discovery: 'discovery: {{> _shared/intro.md }}\n',
project: 'project: {{> _shared/intro.md }}\n',
shared: { 'intro.md': 'SHARED-INTRO' },
});
const built = buildSkillBundles(paths);
- expect(built.map((b) => b.bundle).sort()).toEqual(['discovery', 'project']);
- for (const b of built) {
- expect(existsSync(b.outputPath)).toBe(true);
- expect(readFileSync(b.outputPath, 'utf-8')).toContain('SHARED-INTRO');
- expect(readFileSync(b.outputPath, 'utf-8')).not.toContain('{{>');
- expect(b.placeholders).toEqual(['intro.md']);
+ expect(built.map((b) => b.bundle).sort()).toEqual([...BUNDLE_IDS].sort());
+ for (const id of ['discovery', 'project'] as const) {
+ const b = built.find((x) => x.bundle === id);
+ expect(b && existsSync(b.outputPath)).toBe(true);
+ const text = readFileSync(b?.outputPath ?? '', 'utf-8');
+ expect(text).toContain('SHARED-INTRO');
+ expect(text).not.toContain('{{>');
+ expect(b?.placeholders).toEqual(['intro.md']);
}
});
+ test('copies a bundle’s references/ into dist so the complete bundle ships (H1)', () => {
+ const paths = fixture({
+ discovery: '# d\n',
+ project: '# p\n',
+ references: { 'project/references/setup.md': 'SETUP-DOC' },
+ });
+ buildSkillBundles(paths);
+ const ref = join(paths.distDir, 'project', 'references', 'setup.md');
+ expect(existsSync(ref)).toBe(true);
+ expect(readFileSync(ref, 'utf-8')).toBe('SETUP-DOC');
+ });
+
test('identity transform when no placeholders are used (v1 case)', () => {
const paths = fixture({ discovery: '# d\n', project: '# p\n' });
const built = buildSkillBundles(paths);
@@ -175,7 +198,7 @@ describe('repo assets — production guard', () => {
expect(result.ok).toBe(true);
});
- test('both real source bundles exist and the _shared directory is present', () => {
+ test('every real source bundle exists and the _shared directory is present', () => {
const { skillsDir } = defaultPaths();
for (const bundle of BUNDLE_IDS) {
expect(existsSync(join(skillsDir, bundle, 'SKILL.md'))).toBe(true);
@@ -183,11 +206,20 @@ describe('repo assets — production guard', () => {
expect(existsSync(join(skillsDir, '_shared'))).toBe(true);
});
- test('the two bundles carry distinct frontmatter name: values (shadow prevention)', () => {
+ test('every bundle carries a distinct frontmatter name: value (shadow prevention)', () => {
const { skillsDir } = defaultPaths();
- const discovery = readFileSync(join(skillsDir, 'discovery', 'SKILL.md'), 'utf-8');
- const project = readFileSync(join(skillsDir, 'project', 'SKILL.md'), 'utf-8');
- expect(/^name:\s*open-knowledge-discovery\s*$/m.test(discovery)).toBe(true);
- expect(/^name:\s*open-knowledge\s*$/m.test(project)).toBe(true);
+ const expected: Record<(typeof BUNDLE_IDS)[number], string> = {
+ discovery: 'open-knowledge-discovery',
+ project: 'open-knowledge',
+ 'write-skill': 'open-knowledge-write-skill',
+ };
+ const names = new Set<string>();
+ for (const bundle of BUNDLE_IDS) {
+ const md = readFileSync(join(skillsDir, bundle, 'SKILL.md'), 'utf-8');
+ const want = expected[bundle];
+ expect(new RegExp(`^name:\\s*${want}\\s*$`, 'm').test(md)).toBe(true);
+ names.add(want);
+ }
+ expect(names.size).toBe(BUNDLE_IDS.length);
});
});
diff --git a/packages/server/scripts/build-skill-bundles.ts b/packages/server/scripts/build-skill-bundles.ts
index 64e31fd85..4646e747b 100644
--- a/packages/server/scripts/build-skill-bundles.ts
+++ b/packages/server/scripts/build-skill-bundles.ts
@@ -1,11 +1,11 @@
#!/usr/bin/env bun
-import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { cpSync, existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
-import type { BundleId } from '../src/build-skill-zip.ts';
+import { BUNDLE_IDS, type BundleId } from '../src/skill-bundles.ts';
-export const BUNDLE_IDS = ['discovery', 'project'] as const satisfies readonly BundleId[];
+export { BUNDLE_IDS };
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = join(SCRIPT_DIR, '..');
@@ -60,12 +60,13 @@ export function buildSkillBundles(paths: SkillBundlePaths = defaultPaths()): Com
const resolve = sharedResolver(paths.skillsDir);
const results: ComposedBundle[] = [];
for (const bundle of BUNDLE_IDS) {
- const sourcePath = join(paths.skillsDir, bundle, 'SKILL.md');
- const source = readFileSync(sourcePath, 'utf-8');
+ const sourceDir = join(paths.skillsDir, bundle);
+ const source = readFileSync(join(sourceDir, 'SKILL.md'), 'utf-8');
const { composed, placeholders } = composeSkill(source, resolve);
- const outputPath = join(paths.distDir, bundle, 'SKILL.md');
- rmSync(join(paths.distDir, bundle), { recursive: true, force: true });
- mkdirSync(dirname(outputPath), { recursive: true });
+ const outDir = join(paths.distDir, bundle);
+ const outputPath = join(outDir, 'SKILL.md');
+ rmSync(outDir, { recursive: true, force: true });
+ cpSync(sourceDir, outDir, { recursive: true });
writeFileSync(outputPath, composed, 'utf-8');
results.push({ bundle, composed, placeholders, outputPath });
}
@@ -79,12 +80,14 @@ export function buildPackSkills(paths: SkillBundlePaths = defaultPaths()): strin
const built: string[] = [];
for (const entry of readdirSync(packsSrc, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
- const sourcePath = join(packsSrc, entry.name, 'SKILL.md');
+ 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 outputPath = join(paths.distDir, 'packs', entry.name, 'SKILL.md');
- rmSync(join(paths.distDir, 'packs', entry.name), { recursive: true, force: true });
- mkdirSync(dirname(outputPath), { recursive: true });
+ const outDir = join(paths.distDir, 'packs', entry.name);
+ const outputPath = join(outDir, 'SKILL.md');
+ rmSync(outDir, { recursive: true, force: true });
+ cpSync(sourceDir, outDir, { recursive: true });
writeFileSync(outputPath, composed, 'utf-8');
built.push(entry.name);
}
diff --git a/packages/server/src/api-backlinks.test.ts b/packages/server/src/api-backlinks.test.ts
index 5bf8fb465..04fcc9fae 100644
--- a/packages/server/src/api-backlinks.test.ts
+++ b/packages/server/src/api-backlinks.test.ts
@@ -585,4 +585,57 @@ describe('POST /api/test-rescan-backlinks', () => {
rmSync(projectDir, { recursive: true, force: true });
}
});
+
+ test('admits skill/template link targets and resolves their titles', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-graph-skill-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+
+ try {
+ writeFileSync(
+ join(contentDir, 'alpha.md'),
+ '# Alpha\n\nSee [[.ok/skills/my-skill/SKILL]].\n',
+ 'utf-8',
+ );
+ const skillDir = join(contentDir, '.ok', 'skills', 'my-skill');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(join(skillDir, 'SKILL.md'), '# My Skill\n\nGuidance.\n', 'utf-8');
+
+ const fileIndex = new Map<string, FileIndexEntry>([
+ [
+ 'alpha',
+ {
+ size: 10,
+ modified: new Date(0).toISOString(),
+ canonicalPath: '',
+ inode: 0,
+ aliases: [],
+ },
+ ],
+ [
+ '.ok/skills/my-skill/SKILL',
+ {
+ size: 10,
+ modified: new Date(0).toISOString(),
+ canonicalPath: join(skillDir, 'SKILL.md'),
+ inode: 0,
+ aliases: [],
+ },
+ ],
+ ]);
+ const backlinkIndex = new BacklinkIndex({ projectDir, contentDir });
+ await backlinkIndex.rebuildFromDisk();
+
+ const forward = JSON.parse(
+ (await callRoute(contentDir, '/api/forward-links?docName=alpha', fileIndex, backlinkIndex))
+ .body,
+ ) as { forwardLinks: Array<{ kind: string; docName: string; title: string }> };
+
+ const skillLink = forward.forwardLinks.find((l) => l.docName === '.ok/skills/my-skill/SKILL');
+ expect(skillLink).toBeDefined();
+ expect(skillLink?.title).toBe('My Skill');
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
});
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 2dec9f57e..d21ff9414 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -67,6 +67,7 @@ import {
DuplicatePathRequestSchema,
DuplicatePathSuccessSchema,
detectFmRegion,
+ type EditorId,
EmbedDetectSuccessSchema,
EmptyRequestSchema,
encodeShareUrl,
@@ -88,6 +89,7 @@ import {
InstallSkillSuccessSchema,
instantiateDoc,
isHiddenDocName,
+ isManagedArtifactDocName,
LINKABLE_ASSET_EXTENSIONS,
type LifecycleStatus,
LinkGraphSuccessSchema,
@@ -102,18 +104,23 @@ import {
LocalOpEmbeddingsSetKeyRequestSchema,
LocalOpOkInitRequestSchema,
LocalOpOkInitResponseSchema,
+ MANAGED_ARTIFACT_PREFIX_SKILL,
+ MANAGED_ARTIFACT_PREFIX_TEMPLATE,
MetricsAgentPresenceSuccessSchema,
MetricsParseHealthSuccessSchema,
MetricsReconciliationSuccessSchema,
mediaKindForSidebarAssetExtension,
+ OK_DIR,
OrphansSuccessSchema,
PageHeadingsSuccessSchema,
PagesSuccessSchema,
+ PROJECT_SKILL_EDITOR_IDS,
type Principal,
PrincipalSuccessSchema,
type ProblemType,
parseTemplateFile,
prependFrontmatter,
+ projectSkillContentDocName,
RenamePathRequestSchema,
RenamePathSuccessSchema,
type RescueEntryFlat,
@@ -143,7 +150,32 @@ import {
SharePublishOwnersResponseSchema,
SharePublishRequestSchema,
SharePublishResponseSchema,
+ SKILL_NAME_REGEX,
+ SkillDeleteSuccessSchema,
+ SkillFileDeleteSuccessSchema,
+ SkillFileGetSuccessSchema,
+ SkillFilePutRequestSchema,
+ SkillFilePutSuccessSchema,
+ SkillGetSuccessSchema,
+ SkillInstallRequestSchema,
SkillInstallStateSuccessSchema,
+ SkillInstallSuccessSchema,
+ type SkillInstallWarningCode,
+ SkillMoveRequestSchema,
+ SkillMoveSuccessSchema,
+ SkillPutRequestSchema,
+ SkillPutSuccessSchema,
+ SkillRestoreRequestSchema,
+ SkillRestoreSuccessSchema,
+ SkillScopeSchema,
+ SkillsListSuccessSchema,
+ SkillTargetsGetSuccessSchema,
+ SkillTargetsPutRequestSchema,
+ SkillTargetsPutSuccessSchema,
+ SkillUninstallRequestSchema,
+ SkillUninstallSuccessSchema,
+ SkillUpdateRequestSchema,
+ SkillUpdateSuccessSchema,
SuggestLinksSuccessSchema,
SYSTEM_DOC_NAME,
SyncConflictContentSuccessSchema,
@@ -154,6 +186,7 @@ import {
SyncTriggerRequestSchema,
SyncTriggerSuccessSchema,
searchWorkspaceCorpus,
+ skillLiveDocName,
stripFrontmatter,
TagsForNameSuccessSchema,
TagsListSuccessSchema,
@@ -172,6 +205,7 @@ import {
TrashCleanupSuccessSchema,
UploadAssetSuccessSchema,
UploadRequestSchema,
+ unwrapFrontmatterFences,
type WorkspaceSearchCorpus,
type WorkspaceSearchDocument,
type WorkspaceSearchIntent,
@@ -189,6 +223,7 @@ import {
import busboy from 'busboy';
import { fileTypeFromFile } from 'file-type';
import { parse as parseYaml } from 'yaml';
+import { z } from 'zod';
import { captureEffect } from './activity-log.ts';
import { listAgentActivity, synthesizeStackItemDiffText } from './agent-activity.ts';
import type { AgentFocusBroadcaster } from './agent-focus.ts';
@@ -210,6 +245,17 @@ import { CONFIG_VALIDATION_REVERT_ORIGIN } from './config-edit-origin.ts';
import { DocInConflictError, isDocInConflict, respondDocInConflict } from './conflict-errors.ts';
import { enrichDirectory } from './content/enrichment.ts';
import { applyFolderFrontmatterPatch } from './content/folder-frontmatter-write.ts';
+import {
+ applySkillBundleFileDelete,
+ applySkillBundleFileWrite,
+ applySkillDelete,
+ applySkillMove,
+ applySkillWrite,
+ BUNDLE_FILE_MAX_BYTES,
+ BUNDLE_MAX_FILES,
+ composeSkillContent,
+ countBundleFiles,
+} from './content/skills-write.ts';
import { applySubstitution, todayIsoUtc } from './content/substitution.ts';
import {
resolveProjectTemplates,
@@ -219,6 +265,7 @@ import {
applyTemplateDelete,
applyTemplateMove,
applyTemplateWrite,
+ composeTemplateContent,
type TemplateFrontmatter,
} from './content/templates-write.ts';
import {
@@ -250,6 +297,11 @@ import {
} from './handoff-api.ts';
import { handleHandoffDispatch } from './handoff-dispatch-api.ts';
import { findHubCandidates } from './hub-candidates.ts';
+import {
+ readInstalledSkills,
+ recordSkillInstall,
+ removeSkillInstall,
+} from './installed-skills-marker.ts';
import { validateMermaidFences } from './mermaid-validator.ts';
import {
extractPageIcon,
@@ -291,7 +343,25 @@ import {
SHARE_PUBLISH_TIMEOUT_MS,
} from './share/publish.ts';
import { buildAndOpenSkill } from './skill-install.ts';
+import { readSkillManagement, writeSkillManagement } from './skill-management.ts';
+import {
+ computePackUpdateStatus,
+ isPackSkillName,
+ readBundledPackSkill,
+ readSkillVersion,
+} from './skill-pack-version.ts';
+import {
+ projectSkill,
+ readSkillBundledFiles,
+ resolvedHosts,
+ resolveSkillTargets,
+ reverseProjectSkill,
+ validateSkillForInstall,
+} from './skill-projection.ts';
+import { countImportableEditorSkills, reconcileSkillInstalls } from './skill-reconcile.ts';
+import { reprojectAllManagedSkills } from './skill-reproject.ts';
import { readSkillInstallStateSnapshot } from './skill-state.ts';
+import { readSkillTargets, writeSkillTargets } from './skill-targets-store.ts';
import { handleSpawnCursor } from './spawn-cursor-api.ts';
import { readUiLock } from './ui-lock.ts';
import {
@@ -405,6 +475,10 @@ import {
} from './local-ops/index.ts';
import { getLogger } from './logger.ts';
import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';
+import {
+ managedArtifactAbsPath,
+ managedArtifactTimelinePaths,
+} from './managed-artifact-persistence.ts';
import {
createManagedRenameRecoveryJournal,
type ManagedRenameSnapshot,
@@ -457,6 +531,7 @@ import {
type WriterIdentity,
} from './shadow-repo.ts';
import { createSingleFlight } from './single-flight.ts';
+import { restoreSkillVersion } from './skill-restore.ts';
import { SuggestLinksTargetNotFoundError, suggestLinks } from './suggest-links.ts';
import type { SyncEngine } from './sync-engine.ts';
import type { TagIndex } from './tag-index.ts';
@@ -602,6 +677,10 @@ function safeDocPath(docName: string, contentRoot: string): { path: string } | {
return { error: 'Invalid document name.' };
}
const normalized = contentRoot === '.' ? '' : contentRoot.replace(/^\.\//, '');
+ const managed = managedArtifactTimelinePaths(docName);
+ if (managed.managed && managed.versioned) {
+ return { path: normalized ? `${normalized}/${managed.filePath}` : managed.filePath };
+ }
const ext = getDocExtension(docName);
const path = normalized ? `${normalized}/${docName}${ext}` : `${docName}${ext}`;
return { path };
@@ -1700,12 +1779,14 @@ export interface ApiExtensionOptions {
projectDir?: string;
resolveEmbed?: (basename: string, sourcePath: string) => string | null;
getPrincipal?: () => Principal | null;
+ homeDirOverride?: string;
contentFilter?: ContentFilter;
installedAgentsProbe?: (scheme: InstalledAgentScheme) => Promise<boolean>;
forceUnloadDocument?: (document: Document) => Promise<void>;
ready?: Promise<void>;
recentlyRemovedDocs?: RecentlyRemovedDocs;
serializeDoc?: (docName: string) => string | null;
+ evictManagedArtifactLkg?: (docName: string) => void;
semanticSearch?: SemanticSearchService;
getSemanticSimilarityFloor?: () => number | undefined;
embeddingsSecretsFile?: string;
@@ -1793,12 +1874,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
localOpCliArgs = ['open-knowledge'],
projectDir,
getPrincipal,
+ homeDirOverride,
contentFilter,
installedAgentsProbe,
forceUnloadDocument,
ready,
recentlyRemovedDocs,
serializeDoc,
+ evictManagedArtifactLkg,
semanticSearch,
getSemanticSimilarityFloor,
embeddingsSecretsFile,
@@ -1888,6 +1971,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
function resolveDocPath(docName: string): string | null {
+ if (isManagedArtifactDocName(docName)) {
+ try {
+ return managedArtifactAbsPath(docName, {
+ projectDir: projectDir ?? contentDir,
+ homedirOverride: homeDirOverride,
+ });
+ } catch {
+ return null;
+ }
+ }
if (!isSafeDocName(docName)) return null;
const resolvedContentDir = resolve(contentDir);
const filePath = resolve(resolvedContentDir, `${docName}${getDocExtension(docName)}`);
@@ -2086,6 +2179,22 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
admitted.add(alias);
}
}
+ try {
+ for (const scope of ['project', 'global'] as const) {
+ const skillsRoot =
+ scope === 'global'
+ ? resolve(skillsHome, '.ok', 'skills')
+ : resolve(contentDir, '.ok', 'skills');
+ for (const skill of resolveSkillsList(skillsRoot, scope).skills) {
+ admitted.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${skill.name}`);
+ }
+ }
+ for (const tpl of resolveProjectTemplates(resolve(contentDir)).templates) {
+ admitted.add(templateDocNameFor(tpl.source_folder, tpl.name));
+ }
+ } catch (err) {
+ log.warn({ err }, '[collectAdmittedDocNames] managed-artifact enumeration failed');
+ }
return admitted;
}
@@ -2195,6 +2304,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
for (const docName of docNames) {
const document = hocuspocus.documents.get(docName);
deleteReconciledBase(docName);
+ evictManagedArtifactLkg?.(docName);
if (!document) continue;
hocuspocus.closeConnections(docName);
await (forceUnloadDocument ?? hocuspocus.unloadDocument.bind(hocuspocus))(document);
@@ -3290,13 +3400,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
function okArtifactKey(
- kind: 'template' | 'folder-frontmatter' | 'folder',
+ kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',
folder: string,
name?: string,
): string {
const base = folder.replace(/\/$/, '');
const prefix = base === '' ? '' : `${base}/`;
if (kind === 'template') return `${prefix}.ok/templates/${name}`;
+ if (kind === 'skill') return `${prefix}.ok/skills/${name}`;
if (kind === 'folder-frontmatter') return `${prefix}.ok/frontmatter`;
return base === '' ? '.' : base;
}
@@ -5479,6 +5590,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
await backlinkIndex.rebuildFromDisk();
+ await backlinkIndex.ingestGlobalSkillBundles([resolve(skillsHome, '.ok', 'skills')]);
void backlinkIndex.saveToDisk().catch((err) => {
console.warn('[backlinks] Failed to persist cache after test-rescan-backlinks:', err);
});
@@ -6651,6 +6763,21 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
+ const firstSegment = filePath.split('/')[0];
+ if (firstSegment === OK_DIR || isManagedArtifactDocName(candidateDocName)) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:reserved-doc-name',
+ `'${candidateDocName}' is a reserved document name.`,
+ {
+ handler: 'create-page',
+ detail:
+ 'Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.',
+ },
+ );
+ return;
+ }
const templateName =
typeof (body as Record<string, unknown>).template === 'string'
? ((body as Record<string, unknown>).template as string).trim()
@@ -9834,6 +9961,19 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return false;
}
+ function checkSkillDocConflictGate(
+ docName: string,
+ handler: string,
+ res: ServerResponse,
+ ): boolean {
+ const doc = hocuspocus.documents.get(docName);
+ if (doc && isDocInConflict(doc)) {
+ respondDocInConflict(res, new DocInConflictError({ file: `${docName}.md` }), handler);
+ return true;
+ }
+ return false;
+ }
+
const handleTemplatesList = withValidation(
EmptyRequestSchema,
async (_req, res) => {
@@ -9880,6 +10020,22 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
}
+ const parseFrontmatterDoc = (
+ raw: string,
+ ): { frontmatter: Record<string, unknown>; body: string } => {
+ const { frontmatter: fenced, body } = stripFrontmatter(raw);
+ let frontmatter: Record<string, unknown> = {};
+ if (fenced !== '') {
+ try {
+ const parsed = parseYaml(unwrapFrontmatterFences(fenced));
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ frontmatter = parsed as Record<string, unknown>;
+ }
+ } catch {}
+ }
+ return { frontmatter, body };
+ };
+
const handleTemplateGet = withValidation(
EmptyRequestSchema,
async (req, res) => {
@@ -9974,33 +10130,60 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (checkTemplateConflictGate(validated.folderRel, name, 'template-put', res)) return;
- const writeInput: Parameters<typeof applyTemplateWrite>[0] = {
- projectDir: validated.resolvedContentDir,
- folder: validated.folderRel,
+ const composed = composeTemplateContent({
name,
body: typeof body.body === 'string' ? body.body : '',
frontmatter: pickFrontmatterFields(body.frontmatter) satisfies TemplateFrontmatter,
- };
- const result = applyTemplateWrite(writeInput);
- if (!result.ok) {
- const status =
- result.error.code === 'WRITE_ERROR' || result.error.code === 'BAD_PROJECT_DIR'
- ? 500
- : 400;
- const urn =
- status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request';
- const title = status === 500 ? 'Failed to write template.' : 'Invalid template request.';
- errorResponse(res, status, urn, title, {
+ });
+ if (!composed.ok) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid template request.', {
handler: 'template-put',
- detail: result.error.code,
- cause: new Error(result.error.message),
+ detail: composed.error.code,
+ cause: new Error(composed.error.message),
});
return;
}
+
+ const templateFilePath = resolve(
+ validated.resolvedContentDir,
+ validated.folderRel,
+ '.ok',
+ 'templates',
+ `${name}.md`,
+ );
+ const templateCreated = !existsSync(templateFilePath);
+ const templateRelPath = relative(validated.resolvedContentDir, templateFilePath)
+ .split(/[\\/]/)
+ .filter(Boolean)
+ .join('/');
+ const templateDocName = templateDocNameFor(validated.folderRel, name);
+
+ const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
+ body as unknown as Record<string, unknown>,
+ );
+ const templateSession = await sessionManager.getSession(templateDocName, agentId, {
+ displayName: agentName,
+ colorSeed,
+ clientName,
+ });
+ templateSession.dc.document.transact(() => {
+ composeAndWriteRawBody(templateSession.dc.document, composed.content, 'agent');
+ }, templateSession.origin);
+
+ const templateFlush = await flushDiskAndDetectOutcome(templateDocName);
+ if (templateFlush?.kind === 'failure') {
+ respondPersistenceFailure(res, templateFlush.failure, 'template-put');
+ return;
+ }
+ if (templateFlush?.kind === 'divergence') {
+ respondDiskDivergence(res, 'template-put');
+ return;
+ }
+
attributeOkArtifactWrite(
actor,
okArtifactKey('template', validated.folderRel, name),
- `${result.created ? 'template-create' : 'template-edit'}: ${result.path}`,
+ `${templateCreated ? 'template-create' : 'template-edit'}: ${templateRelPath}`,
);
await commitOkArtifactWrite('template-put');
successResponse(
@@ -10008,9 +10191,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
200,
TemplatePutSuccessSchema,
{
- path: result.path,
- created: result.created,
- warnings: result.warnings,
+ path: templateRelPath,
+ created: templateCreated,
+ warnings: composed.warnings,
},
{ handler: 'template-put' },
);
@@ -10061,6 +10244,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (checkTemplateConflictGate(validated.folderRel, name, 'template-delete', res)) return;
+ await captureAndCloseDocuments([templateDocNameFor(validated.folderRel, name)]);
+
const deleteInput: Parameters<typeof applyTemplateDelete>[0] = {
projectDir: validated.resolvedContentDir,
folder: validated.folderRel,
@@ -10139,6 +10324,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
+ await captureAndCloseDocuments([
+ templateDocNameFor(fromValidated.folderRel, body.fromName),
+ ]);
+
const result = await applyTemplateMove({
projectDir: fromValidated.resolvedContentDir,
fromFolder: fromValidated.folderRel,
@@ -10272,133 +10461,1624 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'template-move', method: 'POST' },
);
- function deriveFolderSearchDocuments(
- pages: readonly WorkspaceSearchDocument[],
- ): WorkspaceSearchDocument[] {
- const folderModified = new Map<string, number>();
- for (const page of pages) {
- const segments = page.path.split('/').filter(Boolean);
- segments.pop();
- for (let i = 1; i <= segments.length; i++) {
- const folderPath = segments.slice(0, i).join('/');
- folderModified.set(
- folderPath,
- Math.max(folderModified.get(folderPath) ?? 0, page.modifiedTs),
- );
- }
+ const SKILLS_LIST_CAP = 500;
+
+ function validateSkillName(name: string, res: ServerResponse, handler: string): boolean {
+ if (!name || name.length > 64 || !SKILL_NAME_REGEX.test(name)) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).',
+ { handler },
+ );
+ return false;
}
- return [...folderModified.entries()].map(([path, modifiedTs]) =>
- createWorkspaceSearchDocument({ kind: 'folder', path, modifiedTs }),
- );
+ return true;
}
- function buildSearchSnippet(content: string, query: string): string | undefined {
- const normalizedQuery = query.trim().toLowerCase();
- if (!normalizedQuery || !content) return undefined;
- const normalizedContent = content.toLowerCase();
- const index = normalizedContent.indexOf(normalizedQuery);
- if (index < 0) return undefined;
- const start = Math.max(0, index - 80);
- const end = Math.min(content.length, index + normalizedQuery.length + 120);
- const prefix = start > 0 ? '…' : '';
- const suffix = end < content.length ? '…' : '';
- return `${prefix}${content.slice(start, end).replace(/\s+/g, ' ').trim()}${suffix}`;
+ function parseSkillScope(
+ raw: string | null,
+ res: ServerResponse,
+ handler: string,
+ ): 'project' | 'global' | null {
+ const parsed = SkillScopeSchema.safeParse(raw ?? 'project');
+ if (!parsed.success) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Invalid skill scope (expected "project" or "global").',
+ { handler },
+ );
+ return null;
+ }
+ return parsed.data;
}
- function parseSearchIntent(value: unknown): WorkspaceSearchIntent {
- if (value === 'autocomplete' || value === 'full_text' || value === 'omnibar') return value;
- return 'omnibar';
+ const skillsHome = homeDirOverride ?? homedir();
+
+ function resolveSkillsRoot(scope: 'project' | 'global'): string {
+ return scope === 'global'
+ ? resolve(skillsHome, '.ok', 'skills')
+ : resolve(contentDir, '.ok', 'skills');
+ }
+
+ function templateDocNameFor(folderRel: string, name: string): string {
+ const segs = folderRel ? folderRel.split('/').filter(Boolean).map(encodeURIComponent) : [];
+ return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...segs, encodeURIComponent(name)].join('/')}`;
}
function parseSearchRanking(value: unknown): WorkspaceSearchRanking | undefined {
return value === 'navigation' || value === 'relevance' ? value : undefined;
}
- function parseSearchScopes(value: unknown): WorkspaceSearchScope[] | undefined {
- const rawScopes =
- typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : undefined;
- if (!rawScopes) return undefined;
- const scopes = rawScopes.filter(
- (scope): scope is WorkspaceSearchScope =>
- scope === 'page' || scope === 'folder' || scope === 'content' || scope === 'file',
- );
- return scopes.length > 0 ? scopes : undefined;
+ function skillRelPath(abs: string, scope: 'project' | 'global'): string {
+ const base = scope === 'global' ? skillsHome : contentDir;
+ return relative(base, abs).split(/[\\/]/).filter(Boolean).join('/');
}
- function parseSemanticParam(value: unknown): boolean | undefined {
- if (typeof value === 'boolean') return value;
- if (value === 'true') return true;
- if (value === 'false') return false;
- return undefined;
+ function skillInstallBase(scope: 'project' | 'global'): string | undefined {
+ return scope === 'global' ? skillsHome : projectDir;
}
- function parseSearchSource(value: unknown): SearchSource {
- return value === 'omnibar' || value === 'mcp' || value === 'http' ? value : 'http';
+ async function uninstallSkillFromHostDirs(base: string, name: string): Promise<boolean> {
+ const installed = await removeSkillInstall(base, name);
+ reverseProjectSkill(name, base, PROJECT_SKILL_EDITOR_IDS);
+ return installed !== null;
}
- interface SemanticResolution {
- input?: WorkspaceSemanticInput;
- status?: SearchSemanticStatus;
- queryEmbedMs: number | null;
- pageTotal: number;
- capable: boolean;
+ function resolveSkillsList(
+ skillsRoot: string,
+ scope: 'project' | 'global',
+ ): {
+ skills: Array<{
+ name: string;
+ description?: string;
+ scope: 'project' | 'global';
+ path: string;
+ absolutePath: string;
+ installedVersion?: string;
+ }>;
+ truncated: boolean;
+ } {
+ const skills: Array<{
+ name: string;
+ description?: string;
+ scope: 'project' | 'global';
+ path: string;
+ absolutePath: string;
+ installedVersion?: string;
+ }> = [];
+ if (!existsSync(skillsRoot)) return { skills, truncated: false };
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(skillsRoot, { withFileTypes: true });
+ } catch (err) {
+ getLogger('skills').warn(
+ { err, skillsRoot, scope },
+ 'failed to read skills root — returning empty skills list',
+ );
+ return { skills, truncated: false };
+ }
+ let truncated = false;
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (!entry.isDirectory() || !SKILL_NAME_REGEX.test(entry.name)) continue;
+ if (skills.length >= SKILLS_LIST_CAP) {
+ truncated = true;
+ break;
+ }
+ 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;
+ if (typeof frontmatter.version === 'string' && frontmatter.version.trim() !== '') {
+ installedVersion = frontmatter.version;
+ }
+ } catch {}
+ skills.push({
+ name: entry.name,
+ ...(description !== undefined ? { description } : {}),
+ scope,
+ path: skillRelPath(skillMd, scope),
+ absolutePath: skillMd,
+ ...(installedVersion !== undefined ? { installedVersion } : {}),
+ });
+ }
+ return { skills, truncated };
}
- async function resolveSemantic(
- query: string,
- intent: WorkspaceSearchIntent,
- semanticParam: boolean | undefined,
- corpus: WorkspaceSearchCorpus,
- ): Promise<SemanticResolution> {
- const embeddableDocs = corpus.documents.filter((d) => !isHiddenDocName(d.path));
- const pageTotal = embeddableDocs.reduce((n, d) => n + (d.kind === 'page' ? 1 : 0), 0);
- if (!semanticSearch?.isEnabled() || semanticParam !== true) {
- return { queryEmbedMs: null, pageTotal, capable: false };
- }
+ const handleSkillsList = withValidation(
+ EmptyRequestSchema,
+ async (_req, res) => {
+ try {
+ const project = resolveSkillsList(resolveSkillsRoot('project'), 'project');
+ const globalSkills = resolveSkillsList(resolveSkillsRoot('global'), 'global');
+ const projectInstalled = projectDir ? readInstalledSkills(projectDir).skills : {};
+ const globalInstalled = readInstalledSkills(skillsHome).skills;
+ const enrich = (list: typeof project, marker: Record<string, { hosts: string[] }>) =>
+ list.skills.map((skill) => {
+ const record = marker[skill.name];
+ const hosts = record?.hosts ?? [];
+ const update = computePackUpdateStatus(skill.name, skill.installedVersion);
+ return { ...skill, installed: hosts.length > 0, hosts, ...update };
+ });
+ const enriched = {
+ skills: [...enrich(project, projectInstalled), ...enrich(globalSkills, globalInstalled)],
+ truncated: project.truncated || globalSkills.truncated,
+ };
+ successResponse(res, 200, SkillsListSuccessSchema, enriched, { handler: 'skills-list' });
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to list skills.', {
+ handler: 'skills-list',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skills-list', method: 'GET', skipBodyParse: true },
+ );
- void semanticSearch.embedCorpus(embeddableDocs);
+ async function handleSkill(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ if (req.method === 'GET') return handleSkillGet(req, res);
+ if (req.method === 'PUT') return handleSkillPut(req, res);
+ if (req.method === 'POST') return handleSkillMove(req, res);
+ if (req.method === 'DELETE') return handleSkillDelete(req, res);
+ errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {
+ handler: 'skill',
+ extraHeaders: { Allow: 'GET, PUT, POST, DELETE' },
+ });
+ }
- let input: WorkspaceSemanticInput | undefined;
- let queryEmbedMs: number | null = null;
- if (intent === 'full_text' && query.trim().length >= SEMANTIC_MIN_QUERY_LENGTH) {
- const startedAt = performance.now();
- const scores = await semanticSearch.queryScores(query, embeddableDocs);
- queryEmbedMs = performance.now() - startedAt;
- if (scores && scores.size > 0) {
- const similarityFloor = getSemanticSimilarityFloor?.();
- input = similarityFloor !== undefined ? { scores, similarityFloor } : { scores };
+ 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 status = semanticSearch.getStatus();
- return {
- input,
- status: {
- capable: status.capable,
- applied: false, // finalized post-ranking (did any result carry a vector)
- coverage: { embedded: status.embeddedCount, total: pageTotal },
- },
- queryEmbedMs,
- pageTotal,
- capable: status.capable,
- };
+ 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',
+ });
+ 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' },
+ );
+
+ async function handleSkillsManagement(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ if (req.method === 'GET') return handleSkillsManagementGet(req, res);
+ if (req.method === 'PUT') return handleSkillsManagementPut(req, res);
+ errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {
+ handler: 'skills-management',
+ extraHeaders: { Allow: 'GET, PUT' },
+ });
}
- function toSearchResultEntry(
- result: ReturnType<typeof searchWorkspaceCorpus>[number],
- query: string,
- ): {
- kind: WorkspaceSearchScope;
- path: string;
- title: string;
- score: number;
- signals: WorkspaceSearchResult['signals'];
- snippet?: string;
- } {
- return {
- kind: result.document.kind,
- path: result.document.path,
- title: result.document.title,
+ const handleSkillGet = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ try {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const name = url.searchParams.get('name') ?? '';
+ if (!validateSkillName(name, res, 'skill-get')) return;
+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-get');
+ if (scope === null) return;
+ const skillsRoot = resolveSkillsRoot(scope);
+
+ const skillMd = resolve(skillsRoot, name, 'SKILL.md');
+ if (!existsSync(skillMd)) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
+ handler: 'skill-get',
+ detail: `Skill "${name}" not found in ${scope} scope.`,
+ });
+ return;
+ }
+ const { frontmatter, body } = parseFrontmatterDoc(await readFile(skillMd, 'utf-8'));
+ successResponse(
+ res,
+ 200,
+ SkillGetSuccessSchema,
+ {
+ skill: {
+ name,
+ scope,
+ path: skillRelPath(skillMd, scope),
+ frontmatter: {
+ name: typeof frontmatter.name === 'string' ? frontmatter.name : name,
+ description:
+ typeof frontmatter.description === 'string' ? frontmatter.description : '',
+ },
+ body,
+ files: readSkillBundledFiles(resolve(skillsRoot, name)),
+ },
+ },
+ { handler: 'skill-get' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to read skill.', {
+ handler: 'skill-get',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skill-get', method: 'GET', skipBodyParse: true },
+ );
+
+ const handleSkillPut = withValidation(
+ SkillPutRequestSchema,
+ 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-put',
+ });
+ return;
+ }
+ if (!validateSkillName(body.name, res, 'skill-put')) return;
+
+ const composed = composeSkillContent({
+ name: body.name,
+ body: typeof body.body === 'string' ? body.body : '',
+ frontmatter: { name: body.frontmatter.name, description: body.frontmatter.description },
+ });
+ if (!composed.ok) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill request.', {
+ handler: 'skill-put',
+ detail: composed.error.code,
+ cause: new Error(composed.error.message),
+ });
+ return;
+ }
+
+ const skillsRoot = resolveSkillsRoot(body.scope);
+ const filePath = resolve(skillsRoot, body.name, 'SKILL.md');
+ const created = !existsSync(filePath);
+ const relPath = relative(skillsRoot, filePath).split(/[\\/]/).filter(Boolean).join('/');
+ const docName = skillLiveDocName(body.scope, body.name);
+
+ if (checkSkillDocConflictGate(docName, 'skill-put', res)) return;
+
+ const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
+ body as unknown as Record<string, unknown>,
+ );
+ const session = await sessionManager.getSession(docName, agentId, {
+ displayName: agentName,
+ colorSeed,
+ clientName,
+ });
+ session.dc.document.transact(() => {
+ composeAndWriteRawBody(session.dc.document, composed.content, 'agent');
+ }, session.origin);
+
+ const flushOutcome = await flushDiskAndDetectOutcome(docName);
+ if (flushOutcome?.kind === 'failure') {
+ respondPersistenceFailure(res, flushOutcome.failure, 'skill-put');
+ return;
+ }
+ if (flushOutcome?.kind === 'divergence') {
+ respondDiskDivergence(res, 'skill-put');
+ return;
+ }
+
+ if (body.scope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.name),
+ `${created ? 'skill-create' : 'skill-edit'}: ${relPath}`,
+ );
+ await commitOkArtifactWrite('skill-put');
+ }
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillPutSuccessSchema,
+ { path: relPath, created, warnings: composed.warnings },
+ { handler: 'skill-put' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to write skill.', {
+ handler: 'skill-put',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skill-put', method: 'PUT' },
+ );
+
+ const handleSkillDelete = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ try {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const name = url.searchParams.get('name') ?? '';
+ if (!validateSkillName(name, res, 'skill-delete')) return;
+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-delete');
+ if (scope === null) return;
+ const skillsRoot = resolveSkillsRoot(scope);
+
+ 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,
+ );
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'skill-delete',
+ });
+ return;
+ }
+
+ await captureAndCloseDocuments([skillLiveDocName(scope, name)]);
+
+ const result = applySkillDelete({ skillsRoot, name });
+ if (!result.ok) {
+ const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;
+ errorResponse(
+ res,
+ status,
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ status === 500 ? 'Failed to delete skill.' : 'Invalid skill request.',
+ {
+ handler: 'skill-delete',
+ detail: result.error.code,
+ cause: new Error(result.error.message),
+ },
+ );
+ return;
+ }
+ if (result.existed) {
+ if (scope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', name),
+ `skill-delete: ${result.path}`,
+ );
+ await commitOkArtifactWrite('skill-delete');
+ }
+ signalChannel?.('files');
+ }
+ const uninstallBase = skillInstallBase(scope);
+ if (uninstallBase) await uninstallSkillFromHostDirs(uninstallBase, name);
+ successResponse(
+ res,
+ 200,
+ SkillDeleteSuccessSchema,
+ { existed: result.existed, path: result.path },
+ { handler: 'skill-delete' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to delete skill.', {
+ handler: 'skill-delete',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skill-delete', method: 'DELETE', skipBodyParse: true },
+ );
+
+ const handleSkillMove = withValidation(
+ SkillMoveRequestSchema,
+ 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',
+ });
+ return;
+ }
+ if (!validateSkillName(body.fromName, res, 'skill-move')) return;
+ if (!validateSkillName(body.toName, res, 'skill-move')) return;
+ const skillsRoot = resolveSkillsRoot(body.scope);
+
+ await captureAndCloseDocuments([skillLiveDocName(body.scope, body.fromName)]);
+
+ const result = await applySkillMove({
+ skillsRoot,
+ fromName: body.fromName,
+ toName: body.toName,
+ relocate: async (fromAbs, toAbs) => {
+ const movedWithGit = await renameTrackedPathInGit(projectDir, fromAbs, toAbs);
+ if (!movedWithGit) renamePathOnDisk(fromAbs, toAbs);
+ return movedWithGit;
+ },
+ });
+ if (!result.ok) {
+ if (result.error.code === 'SKILL_NOT_FOUND') {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
+ handler: 'skill-move',
+ detail: result.error.message,
+ });
+ return;
+ }
+ if (result.error.code === 'SKILL_EXISTS') {
+ errorResponse(res, 409, 'urn:ok:error:doc-already-exists', result.error.message, {
+ handler: 'skill-move',
+ detail: result.error.code,
+ });
+ return;
+ }
+ const status = result.error.code === 'MOVE_FAILED' ? 500 : 400;
+ errorResponse(
+ res,
+ status,
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ status === 500 ? 'Failed to move skill.' : 'Invalid skill move request.',
+ {
+ handler: 'skill-move',
+ detail: result.error.code,
+ cause: new Error(result.error.message),
+ },
+ );
+ return;
+ }
+
+ let contentEditError: { code: string; message: string } | null = null;
+ const movedSkillMd = resolve(skillsRoot, body.toName, 'SKILL.md');
+ let parsedBody = '';
+ let parsedDescription = '';
+ try {
+ const parsed = parseFrontmatterDoc(readFileSync(movedSkillMd, 'utf-8'));
+ parsedBody = parsed.body;
+ if (typeof parsed.frontmatter.description === 'string') {
+ parsedDescription = parsed.frontmatter.description;
+ }
+ } catch {}
+ const writeBody = typeof body.body === 'string' ? body.body : parsedBody;
+ const writeDescription =
+ body.frontmatter !== undefined ? body.frontmatter.description : parsedDescription;
+ const rewrite = applySkillWrite({
+ skillsRoot,
+ name: body.toName,
+ body: writeBody,
+ frontmatter: { name: body.toName, description: writeDescription },
+ });
+ if (!rewrite.ok) contentEditError = rewrite.error;
+
+ if (body.scope === 'project' && !contentEditError) {
+ try {
+ reindexMovedProjectSkillDocs(skillsRoot, body.fromName, body.toName);
+ } catch (err) {
+ getLogger('skill-move').warn(
+ { err, fromName: body.fromName, toName: body.toName },
+ 'reindex of moved project skill docs failed — rename succeeded, deferring to next rescan',
+ );
+ }
+ }
+
+ const fromKeyPath = skillRelPath(resolve(skillsRoot, body.fromName), body.scope);
+ const toKeyPath = skillRelPath(resolve(skillsRoot, body.toName), body.scope);
+ if (body.scope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.toName),
+ `skill-rename: ${fromKeyPath} -> ${toKeyPath}`,
+ [{ from: fromKeyPath, to: toKeyPath }],
+ );
+ await commitOkArtifactWrite('skill-move');
+ }
+
+ const moveBase = skillInstallBase(body.scope);
+ 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 recordSkillInstall(moveBase, body.toName, {
+ ...prior,
+ hosts: newHosts,
+ });
+ }
+ }
+ signalChannel?.('files');
+
+ if (contentEditError) {
+ const isServerError = contentEditError.code === 'WRITE_ERROR';
+ errorResponse(
+ res,
+ isServerError ? 500 : 400,
+ isServerError ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ `Skill renamed to "${body.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,
+ {
+ handler: 'skill-move',
+ detail: contentEditError.code,
+ cause: new Error(contentEditError.message),
+ },
+ );
+ return;
+ }
+ successResponse(
+ res,
+ 200,
+ SkillMoveSuccessSchema,
+ {
+ from: fromKeyPath,
+ to: toKeyPath,
+ committed: result.committed,
+ },
+ { handler: 'skill-move' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to move skill.', {
+ handler: 'skill-move',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skill-move', method: 'POST' },
+ );
+
+ function classifySkillFilePath(rel: string): 'reference' | 'script' | null {
+ if (rel.includes('\x00')) return null;
+ const segments = rel
+ .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;
+ }
+
+ function isProjectMdReference(
+ scope: 'project' | 'global',
+ kind: 'reference' | 'script',
+ rel: string,
+ ): boolean {
+ return scope === 'project' && kind === 'reference' && rel.toLowerCase().endsWith('.md');
+ }
+
+ function projectRefContentDocName(name: string, rel: string): string {
+ const extLess = rel.replace(/\.md$/i, '');
+ return `${projectSkillContentDocName(name).replace(/\/SKILL$/, '')}/${extLess}`;
+ }
+
+ function listProjectMdReferences(skillsRoot: string, name: string): string[] {
+ const refsDir = resolve(skillsRoot, name, 'references');
+ if (!existsSync(refsDir)) return [];
+ const out: string[] = [];
+ const walk = (dir: string, prefix: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ 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;
+ }
+
+ function reindexMovedProjectSkillDocs(
+ skillsRoot: string,
+ fromName: string,
+ toName: string,
+ ): void {
+ if (!backlinkIndex) return;
+ const reindexOne = (oldDocName: string, newDocName: string, absFile: string): void => {
+ let markdown: string;
+ try {
+ markdown = readFileSync(absFile, 'utf-8');
+ } catch {
+ backlinkIndex.deleteDocument(oldDocName);
+ tagIndex?.deleteDocument(oldDocName);
+ return;
+ }
+ backlinkIndex.renameDocument(oldDocName, newDocName, markdown);
+ tagIndex?.renameDocument(oldDocName, newDocName, markdown);
+ };
+
+ reindexOne(
+ projectSkillContentDocName(fromName),
+ projectSkillContentDocName(toName),
+ resolve(skillsRoot, toName, 'SKILL.md'),
+ );
+ for (const rel of listProjectMdReferences(skillsRoot, toName)) {
+ reindexOne(
+ projectRefContentDocName(fromName, rel),
+ projectRefContentDocName(toName, rel),
+ resolve(skillsRoot, toName, rel),
+ );
+ }
+ signalChannel?.('backlinks');
+ signalChannel?.('graph');
+ }
+
+ const handleSkillFileGet = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ try {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const name = url.searchParams.get('name') ?? '';
+ if (!validateSkillName(name, res, 'skill-file-get')) return;
+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-file-get');
+ if (scope === null) return;
+ const rel = url.searchParams.get('path') ?? '';
+ const kind = 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' },
+ );
+ return;
+ }
+ const skillsRoot = resolveSkillsRoot(scope);
+ const skillDir = resolve(skillsRoot, name);
+ const abs = resolve(skillDir, rel);
+ if (abs !== skillDir && !abs.startsWith(`${skillDir}${sep}`)) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Skill file path escapes the skill dir.',
+ {
+ handler: 'skill-file-get',
+ },
+ );
+ return;
+ }
+ let resolvedAbs = abs;
+ let resolvedRel = rel;
+ if (!existsSync(resolvedAbs)) {
+ const docStem = rel.match(/^(.*)\.(?:md|mdx)$/);
+ const sibling = docStem
+ ? SUPPORTED_DOC_EXTENSIONS.map((ext) => `${docStem[1]}${ext}`).find(
+ (candidate) => candidate !== rel && existsSync(resolve(skillDir, candidate)),
+ )
+ : undefined;
+ if (sibling === undefined) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill file not found.', {
+ handler: 'skill-file-get',
+ detail: `${rel} not found in skill "${name}" (${scope}).`,
+ });
+ return;
+ }
+ resolvedRel = sibling;
+ resolvedAbs = resolve(skillDir, sibling);
+ }
+ const buf = await readFile(resolvedAbs);
+ if (buf.includes(0)) {
+ errorResponse(
+ res,
+ 415,
+ 'urn:ok:error:invalid-request',
+ 'Skill file is binary — only text bundle files are readable via MCP.',
+ { handler: 'skill-file-get' },
+ );
+ return;
+ }
+ successResponse(
+ res,
+ 200,
+ SkillFileGetSuccessSchema,
+ { path: resolvedRel.replace(/\\/g, '/'), kind, text: buf.toString('utf-8') },
+ { handler: 'skill-file-get' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to read skill file.',
+ {
+ handler: 'skill-file-get',
+ cause: e,
+ },
+ );
+ }
+ },
+ { handler: 'skill-file-get', method: 'GET', skipBodyParse: true },
+ );
+
+ const handleSkillFilePut = withValidation(
+ SkillFilePutRequestSchema,
+ 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-file-put',
+ });
+ return;
+ }
+ if (!validateSkillName(body.name, res, 'skill-file-put')) return;
+ const kind = classifySkillFilePath(body.path);
+ if (kind === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Invalid skill file path (must be a file under references/ or scripts/, no `..`).',
+ { handler: 'skill-file-put' },
+ );
+ return;
+ }
+ if (Buffer.byteLength(body.content, 'utf-8') > BUNDLE_FILE_MAX_BYTES) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Skill file exceeds the 256 KB per-file cap.',
+ { handler: 'skill-file-put' },
+ );
+ return;
+ }
+ const skillsRoot = resolveSkillsRoot(body.scope);
+ const skillMd = resolve(skillsRoot, body.name, 'SKILL.md');
+ if (!existsSync(skillMd)) {
+ 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 rel = body.path.replace(/\\/g, '/');
+ const routedThroughContent = isProjectMdReference(body.scope, kind, rel);
+ let created: boolean;
+
+ if (routedThroughContent) {
+ const refDocName = projectRefContentDocName(body.name, rel);
+ if (checkSkillDocConflictGate(refDocName, 'skill-file-put', res)) return;
+ created = !existsSync(resolve(skillsRoot, body.name, rel));
+ if (created && countBundleFiles(resolve(skillsRoot, body.name)) >= BUNDLE_MAX_FILES) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ `Skill "${body.name}" already holds ${BUNDLE_MAX_FILES} bundle files (the cap) — delete one before adding another.`,
+ { handler: 'skill-file-put' },
+ );
+ return;
+ }
+ const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
+ body as unknown as Record<string, unknown>,
+ );
+ const session = await sessionManager.getSession(refDocName, agentId, {
+ displayName: agentName,
+ colorSeed,
+ clientName,
+ });
+ session.dc.document.transact(() => {
+ composeAndWriteRawBody(session.dc.document, body.content, 'agent');
+ }, session.origin);
+ const flushOutcome = await flushDiskAndDetectOutcome(refDocName);
+ if (flushOutcome?.kind === 'failure') {
+ respondPersistenceFailure(res, flushOutcome.failure, 'skill-file-put');
+ return;
+ }
+ if (flushOutcome?.kind === 'divergence') {
+ respondDiskDivergence(res, 'skill-file-put');
+ return;
+ }
+ } else {
+ const fsResult = applySkillBundleFileWrite({
+ skillsRoot,
+ name: body.name,
+ relPath: rel,
+ content: body.content,
+ });
+ if (!fsResult.ok) {
+ const status =
+ fsResult.error.code === 'WRITE_ERROR'
+ ? 500
+ : fsResult.error.code === 'SKILL_NOT_FOUND'
+ ? 404
+ : 400;
+ errorResponse(
+ res,
+ status,
+ status === 500
+ ? 'urn:ok:error:internal-server-error'
+ : status === 404
+ ? 'urn:ok:error:not-found'
+ : 'urn:ok:error:invalid-request',
+ status === 500 ? 'Failed to write skill file.' : 'Invalid skill file request.',
+ {
+ handler: 'skill-file-put',
+ detail: fsResult.error.code,
+ cause: new Error(fsResult.error.message),
+ },
+ );
+ return;
+ }
+ created = fsResult.created;
+ }
+
+ if (body.scope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.name),
+ `${created ? 'skill-file-create' : 'skill-file-edit'}: .ok/skills/${body.name}/${rel}`,
+ );
+ await commitOkArtifactWrite('skill-file-put');
+ }
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillFilePutSuccessSchema,
+ { path: rel, created, kind, content: routedThroughContent },
+ { handler: 'skill-file-put' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to write skill file.',
+ {
+ handler: 'skill-file-put',
+ cause: e,
+ },
+ );
+ }
+ },
+ { handler: 'skill-file-put', method: 'PUT' },
+ );
+
+ const handleSkillFileDelete = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ try {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const sp = url.searchParams;
+ const name = sp.get('name') ?? '';
+ if (!validateSkillName(name, res, 'skill-file-delete')) return;
+ const scope = parseSkillScope(sp.get('scope'), res, 'skill-file-delete');
+ if (scope === null) return;
+ const rel = (sp.get('path') ?? '').replace(/\\/g, '/');
+ const kind = 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-delete' },
+ );
+ 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,
+ );
+ 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);
+
+ if (isProjectMdReference(scope, kind, rel)) {
+ await captureAndCloseDocuments([projectRefContentDocName(name, rel)]);
+ }
+
+ const result = applySkillBundleFileDelete({ skillsRoot, name, relPath: rel });
+ if (!result.ok) {
+ const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;
+ errorResponse(
+ res,
+ status,
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ status === 500 ? 'Failed to delete skill file.' : 'Invalid skill file request.',
+ {
+ handler: 'skill-file-delete',
+ detail: result.error.code,
+ cause: new Error(result.error.message),
+ },
+ );
+ return;
+ }
+ if (result.existed && scope === 'project') {
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', name),
+ `skill-file-delete: .ok/skills/${name}/${rel}`,
+ );
+ await commitOkArtifactWrite('skill-file-delete');
+ }
+ if (result.existed) signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillFileDeleteSuccessSchema,
+ { path: rel, existed: result.existed, kind },
+ { handler: 'skill-file-delete' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to delete skill file.',
+ {
+ handler: 'skill-file-delete',
+ cause: e,
+ },
+ );
+ }
+ },
+ { handler: 'skill-file-delete', method: 'DELETE', skipBodyParse: true },
+ );
+
+ async function handleSkillFile(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ if (req.method === 'GET') return handleSkillFileGet(req, res);
+ if (req.method === 'PUT') return handleSkillFilePut(req, res);
+ if (req.method === 'DELETE') return handleSkillFileDelete(req, res);
+ errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {
+ handler: 'skill-file',
+ extraHeaders: { Allow: 'GET, PUT, DELETE' },
+ });
+ }
+
+ const handleSkillInstall = withValidation(
+ SkillInstallRequestSchema,
+ async (_req, res, body) => {
+ try {
+ const skillsRoot = resolveSkillsRoot(body.scope);
+ if (!validateSkillName(body.name, res, 'skill-install')) return;
+
+ 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;
+
+ 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.`,
+ });
+ return;
+ }
+
+ 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;
+ }
+
+ const targets: EditorId[] =
+ body.scope === 'global'
+ ? body.targets
+ ? // body.targets is the narrower SkillTargetEditor set (no
+ PROJECT_SKILL_EDITOR_IDS.filter((id) => body.targets?.some((t) => t === id))
+ : [...PROJECT_SKILL_EDITOR_IDS]
+ : body.targets !== undefined
+ ? // An EXPLICIT target list from the per-editor menu is set-exact,
+ PROJECT_SKILL_EDITOR_IDS.filter((id) => body.targets?.some((t) => t === id))
+ : resolveSkillTargets(base, readSkillTargets(base) ?? undefined);
+ const warnings: string[] = [];
+ const warningCodes: SkillInstallWarningCode[] = [];
+ if (targets.length === 0 && body.targets === undefined) {
+ warnings.push(
+ body.scope === 'global'
+ ? 'No editor skill folders are configured to install into.'
+ : 'No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`.',
+ );
+ warningCodes.push('no-targets');
+ }
+ if (validity.hasScripts) {
+ warnings.push(
+ 'This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing.',
+ );
+ warningCodes.push('scripts-present');
+ }
+
+ 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 (hosts.length === 0) {
+ await removeSkillInstall(base, body.name);
+ } else {
+ await recordSkillInstall(base, body.name, {
+ hosts,
+ scope: body.scope,
+ scripts: validity.hasScripts,
+ installedAt: new Date().toISOString(),
+ });
+ }
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillInstallSuccessSchema,
+ { name: body.name, hosts, scripts: validity.hasScripts, warnings, warningCodes },
+ { handler: 'skill-install' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to install skill.', {
+ handler: 'skill-install',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skill-install', method: 'POST' },
+ );
+
+ const handleSkillUninstall = withValidation(
+ SkillUninstallRequestSchema,
+ async (_req, res, body) => {
+ try {
+ if (!validateSkillName(body.name, res, 'skill-uninstall')) return;
+ const base = skillInstallBase(body.scope);
+ if (!base) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot uninstall — no project root is resolved for this server.',
+ { handler: 'skill-uninstall', detail: 'NO_PROJECT_ROOT' },
+ );
+ return;
+ }
+ const uninstalled = await uninstallSkillFromHostDirs(base, body.name);
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillUninstallSuccessSchema,
+ { name: body.name, uninstalled },
+ { handler: 'skill-uninstall' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to uninstall skill.',
+ {
+ handler: 'skill-uninstall',
+ cause: e,
+ },
+ );
+ }
+ },
+ { handler: 'skill-uninstall', method: 'POST' },
+ );
+
+ async function handleSkillTargets(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ if (req.method === 'GET') return handleSkillTargetsGet(req, res);
+ if (req.method === 'PUT') return handleSkillTargetsPut(req, res);
+ errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {
+ handler: 'skill-targets',
+ extraHeaders: { Allow: 'GET, PUT' },
+ });
+ }
+
+ const handleSkillTargetsGet = withValidation(
+ EmptyRequestSchema,
+ async (_req, res) => {
+ try {
+ const committed = projectDir ? readSkillTargets(projectDir) : null;
+ const targets = resolveSkillTargets(projectDir ?? '', committed ?? undefined);
+ successResponse(
+ res,
+ 200,
+ SkillTargetsGetSuccessSchema,
+ { targets, configured: committed !== null },
+ { handler: 'skill-targets-get' },
+ );
+ } 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,
+ async (_req, res, body) => {
+ try {
+ if (!projectDir) {
+ errorResponse(
+ 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' },
+ );
+ 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);
+ const { reprojected, bundleHosts } = await reprojectAllManagedSkills({
+ projectDir,
+ skillsRoot,
+ targets: newTargets,
+ });
+
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillTargetsPutSuccessSchema,
+ {
+ targets: newTargets,
+ reprojected,
+ bundleHosts,
+ removedFrom: oldTargets.filter((t) => !newSet.has(t)),
+ },
+ { handler: 'skill-targets-put' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to set skill targets.',
+ { handler: 'skill-targets-put', cause: e },
+ );
+ }
+ },
+ { handler: 'skill-targets-put', method: 'PUT' },
+ );
+
+ const handleSkillRestore = withValidation(
+ SkillRestoreRequestSchema,
+ 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-restore',
+ });
+ return;
+ }
+ if (!validateSkillName(body.name, res, 'skill-restore')) return;
+ if (body.scope === 'global') {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Global skills are unversioned — there is no version history to restore from.',
+ { handler: 'skill-restore', detail: 'GLOBAL_SCOPE_UNVERSIONED' },
+ );
+ return;
+ }
+
+ const shadow = shadowRef?.current;
+ if (!shadow) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:shadow-not-configured',
+ 'No version history available to restore from.',
+ {
+ handler: 'skill-restore',
+ detail: 'NO_SHADOW_REPO',
+ },
+ );
+ return;
+ }
+ const result = await restoreSkillVersion({
+ shadow,
+ contentDir,
+ contentRoot: contentRoot ?? '.',
+ name: body.name,
+ version: body.version,
+ });
+ if (!result.ok) {
+ 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,
+ });
+ return;
+ }
+
+ const warnings: string[] = [];
+ const skillDir = resolve(contentDir, '.ok', 'skills', 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.');
+
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.name),
+ `skill-restore: ${body.name} @ ${body.version.slice(0, 8)}`,
+ );
+ await commitOkArtifactWrite('skill-restore');
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillRestoreSuccessSchema,
+ {
+ name: body.name,
+ version: body.version,
+ restoredFiles: result.restoredFiles,
+ warnings,
+ },
+ { handler: 'skill-restore' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to restore skill.', {
+ handler: 'skill-restore',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skill-restore', method: 'POST' },
+ );
+
+ const handleSkillUpdate = withValidation(
+ SkillUpdateRequestSchema,
+ 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-update',
+ });
+ return;
+ }
+ if (!validateSkillName(body.name, res, 'skill-update')) return;
+ if (!isPackSkillName(body.name)) {
+ 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' },
+ );
+ return;
+ }
+ if (body.scope === 'global') {
+ 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' },
+ );
+ return;
+ }
+
+ const bundled = readBundledPackSkill(body.name);
+ if (bundled === null || bundled.version === undefined) {
+ errorResponse(
+ res,
+ 404,
+ 'urn:ok:error:not-found',
+ 'No bundled version is available for this pack skill.',
+ { handler: 'skill-update', detail: 'NO_BUNDLED_VERSION' },
+ );
+ 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',
+ });
+ return;
+ }
+ let previousVersion: string | undefined;
+ try {
+ previousVersion = readSkillVersion(readFileSync(filePath, 'utf-8'));
+ } catch {}
+
+ 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})`,
+ );
+ checkpointRef = cp.checkpointRef;
+ } catch (err) {
+ getLogger('skills').warn(
+ { err, skill: body.name },
+ 'pre-update checkpoint failed — proceeding with overwrite',
+ );
+ }
+ }
+
+ const docName = skillLiveDocName('project', body.name);
+ if (checkSkillDocConflictGate(docName, 'skill-update', res)) return;
+ const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
+ body as unknown as Record<string, unknown>,
+ );
+ const session = await sessionManager.getSession(docName, agentId, {
+ displayName: agentName,
+ colorSeed,
+ clientName,
+ });
+ session.dc.document.transact(() => {
+ composeAndWriteRawBody(session.dc.document, bundled.content, 'agent');
+ }, session.origin);
+
+ const flushOutcome = await flushDiskAndDetectOutcome(docName);
+ if (flushOutcome?.kind === 'failure') {
+ respondPersistenceFailure(res, flushOutcome.failure, 'skill-update');
+ return;
+ }
+ if (flushOutcome?.kind === 'divergence') {
+ respondDiskDivergence(res, 'skill-update');
+ return;
+ }
+
+ attributeOkArtifactWrite(
+ actor,
+ okArtifactKey('skill', '', body.name),
+ `skill-pack-update: ${body.name} (${previousVersion ?? 'unversioned'} → ${bundled.version})`,
+ );
+ await commitOkArtifactWrite('skill-update');
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillUpdateSuccessSchema,
+ {
+ name: body.name,
+ version: bundled.version,
+ ...(previousVersion !== undefined ? { previousVersion } : {}),
+ ...(checkpointRef !== undefined ? { checkpointRef } : {}),
+ },
+ { handler: 'skill-update' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to update skill.', {
+ handler: 'skill-update',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'skill-update', method: 'POST' },
+ );
+
+ function deriveFolderSearchDocuments(
+ pages: readonly WorkspaceSearchDocument[],
+ ): WorkspaceSearchDocument[] {
+ const folderModified = new Map<string, number>();
+ for (const page of pages) {
+ const segments = page.path.split('/').filter(Boolean);
+ segments.pop();
+ for (let i = 1; i <= segments.length; i++) {
+ const folderPath = segments.slice(0, i).join('/');
+ folderModified.set(
+ folderPath,
+ Math.max(folderModified.get(folderPath) ?? 0, page.modifiedTs),
+ );
+ }
+ }
+ return [...folderModified.entries()].map(([path, modifiedTs]) =>
+ createWorkspaceSearchDocument({ kind: 'folder', path, modifiedTs }),
+ );
+ }
+
+ function buildSearchSnippet(content: string, query: string): string | undefined {
+ const normalizedQuery = query.trim().toLowerCase();
+ if (!normalizedQuery || !content) return undefined;
+ const normalizedContent = content.toLowerCase();
+ const index = normalizedContent.indexOf(normalizedQuery);
+ if (index < 0) return undefined;
+ const start = Math.max(0, index - 80);
+ const end = Math.min(content.length, index + normalizedQuery.length + 120);
+ const prefix = start > 0 ? '…' : '';
+ const suffix = end < content.length ? '…' : '';
+ return `${prefix}${content.slice(start, end).replace(/\s+/g, ' ').trim()}${suffix}`;
+ }
+
+ function parseSearchIntent(value: unknown): WorkspaceSearchIntent {
+ if (value === 'autocomplete' || value === 'full_text' || value === 'omnibar') return value;
+ return 'omnibar';
+ }
+
+ function parseSearchScopes(value: unknown): WorkspaceSearchScope[] | undefined {
+ const rawScopes =
+ typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : undefined;
+ if (!rawScopes) return undefined;
+ const scopes = rawScopes.filter(
+ (scope): scope is WorkspaceSearchScope =>
+ scope === 'page' || scope === 'folder' || scope === 'content' || scope === 'file',
+ );
+ return scopes.length > 0 ? scopes : undefined;
+ }
+
+ function parseSemanticParam(value: unknown): boolean | undefined {
+ if (typeof value === 'boolean') return value;
+ if (value === 'true') return true;
+ if (value === 'false') return false;
+ return undefined;
+ }
+
+ function parseSearchSource(value: unknown): SearchSource {
+ return value === 'omnibar' || value === 'mcp' || value === 'http' ? value : 'http';
+ }
+
+ interface SemanticResolution {
+ input?: WorkspaceSemanticInput;
+ status?: SearchSemanticStatus;
+ queryEmbedMs: number | null;
+ pageTotal: number;
+ capable: boolean;
+ }
+
+ async function resolveSemantic(
+ query: string,
+ intent: WorkspaceSearchIntent,
+ semanticParam: boolean | undefined,
+ corpus: WorkspaceSearchCorpus,
+ ): Promise<SemanticResolution> {
+ const embeddableDocs = corpus.documents.filter((d) => !isHiddenDocName(d.path));
+ const pageTotal = embeddableDocs.reduce((n, d) => n + (d.kind === 'page' ? 1 : 0), 0);
+ if (!semanticSearch?.isEnabled() || semanticParam !== true) {
+ return { queryEmbedMs: null, pageTotal, capable: false };
+ }
+
+ void semanticSearch.embedCorpus(embeddableDocs);
+
+ let input: WorkspaceSemanticInput | undefined;
+ let queryEmbedMs: number | null = null;
+ if (intent === 'full_text' && query.trim().length >= SEMANTIC_MIN_QUERY_LENGTH) {
+ const startedAt = performance.now();
+ const scores = await semanticSearch.queryScores(query, embeddableDocs);
+ queryEmbedMs = performance.now() - startedAt;
+ if (scores && scores.size > 0) {
+ const similarityFloor = getSemanticSimilarityFloor?.();
+ input = similarityFloor !== undefined ? { scores, similarityFloor } : { scores };
+ }
+ }
+
+ const status = semanticSearch.getStatus();
+ return {
+ input,
+ status: {
+ capable: status.capable,
+ applied: false, // finalized post-ranking (did any result carry a vector)
+ coverage: { embedded: status.embeddedCount, total: pageTotal },
+ },
+ queryEmbedMs,
+ pageTotal,
+ capable: status.capable,
+ };
+ }
+
+ function toSearchResultEntry(
+ result: ReturnType<typeof searchWorkspaceCorpus>[number],
+ query: string,
+ ): {
+ kind: WorkspaceSearchScope;
+ path: string;
+ title: string;
+ score: number;
+ signals: WorkspaceSearchResult['signals'];
+ snippet?: string;
+ } {
+ return {
+ kind: result.document.kind,
+ path: result.document.path,
+ title: result.document.title,
score: result.score,
signals: result.signals,
snippet:
@@ -10480,6 +12160,58 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
};
}
+ function enumerateProjectSkillStats(): Array<{
+ name: string;
+ absolutePath: string;
+ mtimeMs: number;
+ size: number;
+ }> {
+ const root = resolveSkillsRoot('project');
+ if (!existsSync(root)) return [];
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(root, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ 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;
+ 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 });
+ } catch {}
+ }
+ return out;
+ }
+
+ function buildSkillSearchDocuments(): WorkspaceSearchDocument[] {
+ const docs: WorkspaceSearchDocument[] = [];
+ for (const skill of enumerateProjectSkillStats()) {
+ let title = skill.name;
+ let content = '';
+ try {
+ const { frontmatter, body } = parseFrontmatterDoc(
+ readFileSync(skill.absolutePath, 'utf-8'),
+ );
+ if (typeof frontmatter.name === 'string' && frontmatter.name) title = frontmatter.name;
+ const desc = typeof frontmatter.description === 'string' ? frontmatter.description : '';
+ content = `${desc}\n\n${body}`.trim();
+ } catch {}
+ docs.push(
+ createWorkspaceSearchDocument({
+ kind: 'page',
+ path: skillLiveDocName('project', skill.name),
+ title,
+ content,
+ modifiedTs: skill.mtimeMs,
+ }),
+ );
+ }
+ return docs;
+ }
+
function entrySearchKey(entry: FileIndexEntry): string {
return `${entry.modified}\0${entry.size}\0${entry.canonicalPath}\0${entry.inode}\0${entry.aliases.join('\0')}`;
}
@@ -10495,6 +12227,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const seenPages: Set<string> = new Set();
for (const [docName, entry] of getAllFilesIndex()) {
if (isSystemDoc(docName) || isConfigDoc(docName)) continue;
+ if (docName.startsWith('.ok/skills/')) continue;
if (entry.kind === 'file') {
files.push(
createWorkspaceSearchDocument({
@@ -10567,21 +12300,28 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
const documents = [
...pages,
+ ...buildSkillSearchDocuments(),
...admittedFiles,
...deriveFolderSearchDocuments([...pages, ...admittedFiles]),
];
return { documents, truncated };
}
+ function skillStatFingerprint(): string {
+ return enumerateProjectSkillStats()
+ .map((s) => `${s.name} ${s.mtimeMs} ${s.size}`)
+ .join('');
+ }
+
function workspaceSearchFingerprint(): string {
if (getFileIndexGeneration) {
- return `gen:${getFileIndexGeneration()}`;
+ return `gen:${getFileIndexGeneration()}|skills${skillStatFingerprint()}`;
}
- return [...getAllFilesIndex()]
+ return `${[...getAllFilesIndex()]
.filter(([docName]) => !isSystemDoc(docName) && !isConfigDoc(docName))
.sort(([a], [b]) => a.localeCompare(b))
.map(([docName, entry]) => `${docName}\0${entrySearchKey(entry)}`)
- .join('');
+ .join('')}|skills${skillStatFingerprint()}`;
}
let bootIndexReady = ready === undefined;
@@ -11537,6 +13277,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/folder-config': handleFolderConfig,
'/api/template': handleTemplate,
'/api/templates': handleTemplatesList,
+ '/api/skill': handleSkill,
+ '/api/skill-file': handleSkillFile,
+ '/api/skills': handleSkillsList,
+ '/api/skills/management': handleSkillsManagement,
+ '/api/skill/install': handleSkillInstall,
+ '/api/skill/uninstall': handleSkillUninstall,
+ '/api/skill/restore': handleSkillRestore,
+ '/api/skill/update': handleSkillUpdate,
+ '/api/skill-targets': handleSkillTargets,
'/api/search': handleSearch,
'/api/semantic-status': handleSemanticStatus,
'/api/suggest-links': handleSuggestLinks,
@@ -11629,6 +13378,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/install-skill',
'/api/folder-config',
'/api/template',
+ '/api/skill',
+ '/api/skill-file',
+ '/api/skill/install',
+ '/api/skill/uninstall',
+ '/api/skill/restore',
+ '/api/skill/update',
+ '/api/skills/management',
+ '/api/skill-targets',
'/api/seed/apply',
'/api/client-logs',
]);
diff --git a/packages/server/src/api-search-semantic-factory.test.ts b/packages/server/src/api-search-semantic-factory.test.ts
index a749f3fb1..fd4e72684 100644
--- a/packages/server/src/api-search-semantic-factory.test.ts
+++ b/packages/server/src/api-search-semantic-factory.test.ts
@@ -26,7 +26,7 @@ const EXCLUDED_FILES: Record<string, string> = {
'# Old Secrets\n\nLegacy notes on credential rotation: re-issue and refresh expired session secrets and login tokens.\n',
};
const HIDDEN_FILES: Record<string, string> = {
- '.cursor/skills/auth-helper.md':
+ '.github/auth-helper.md':
'# Auth Helper\n\nCredential rotation: re-issue and refresh expired session secrets and login tokens.\n',
};
const SERVED_PAGE_COUNT = Object.keys(SERVED_FILES).length;
@@ -172,7 +172,7 @@ describe('createServer boot — flag-ON semantic search (factory glue)', () => {
expect(rotation?.signals.vector ?? 0).toBeGreaterThan(0.3);
expect(result?.results?.find((r) => r.path === 'archive/old-secrets')).toBeUndefined();
- const hiddenHit = result?.results?.find((r) => r.path.startsWith('.cursor/'));
+ const hiddenHit = result?.results?.find((r) => r.path.startsWith('.github/'));
expect(hiddenHit, 'hidden dot-path is searchable').toBeDefined();
expect(hiddenHit?.signals.vector, 'but a hidden dot-path is never embedded').toBeUndefined();
@@ -208,7 +208,7 @@ describe('createServer boot — flag-ON semantic search (factory glue)', () => {
});
for (const r of results ?? []) expect('vector' in r.signals).toBe(false);
expect(results?.find((r) => r.path === 'guides/credential-rotation')).toBeUndefined();
- expect(results?.find((r) => r.path.startsWith('.cursor/'))).toBeDefined();
+ expect(results?.find((r) => r.path.startsWith('.github/'))).toBeDefined();
expect(semantic).toBeUndefined();
});
diff --git a/packages/server/src/api-search.test.ts b/packages/server/src/api-search.test.ts
index 47f86cd97..38e0ba8e5 100644
--- a/packages/server/src/api-search.test.ts
+++ b/packages/server/src/api-search.test.ts
@@ -184,6 +184,31 @@ describe('GET /api/search', () => {
}
});
+ test('indexes project skills under their content-doc path (findable by content)', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-search-'));
+ try {
+ const skillDir = join(dir, '.ok', 'skills', 'data-pipeline');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(
+ join(skillDir, 'SKILL.md'),
+ '---\nname: data-pipeline\ndescription: Ingest and normalize telemetry.\n---\n\nUse this when wrangling zephyrglyph datasets.\n',
+ 'utf-8',
+ );
+
+ const result = await callSearch(dir, '/api/search?query=zephyrglyph&intent=full_text');
+ expect(result.status).toBe(200);
+ const body = JSON.parse(result.body) as {
+ results?: Array<{ kind: string; path: string }>;
+ };
+ const skillHits = (body.results ?? []).filter(
+ (r) => r.path === '.ok/skills/data-pipeline/SKILL',
+ );
+ expect(skillHits).toHaveLength(1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('returns 400 for malformed POST bodies', async () => {
const dir = mkdtempSync(join(tmpdir(), 'ok-search-'));
try {
diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.ts
index f8cd34c90..68b0ad9e0 100644
--- a/packages/server/src/backlink-index.test.ts
+++ b/packages/server/src/backlink-index.test.ts
@@ -185,6 +185,44 @@ describe('BacklinkIndex', () => {
}
});
+ test('normalizes skill file links to the content doc and template links to the artifact', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-artifact-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown(
+ 'work-log',
+ 'Touched [the skill](.ok/skills/my-skill/SKILL.md) and [the tpl](notes/.ok/templates/daily.md).\n',
+ );
+ expect(index.getBacklinks('.ok/skills/my-skill/SKILL')).toEqual([
+ expect.objectContaining({ source: 'work-log' }),
+ ]);
+ expect(index.getBacklinks('__template__/notes/daily')).toEqual([
+ expect.objectContaining({ source: 'work-log' }),
+ ]);
+ expect(index.getBacklinks('__skill__/project/my-skill')).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('indexes a managed-artifact doc (skill) own outgoing links', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown('__skill__/project/my-skill', 'See [[architecture]].\n');
+ expect(index.getForwardLinks('__skill__/project/my-skill')).toEqual(['architecture']);
+ expect(index.getBacklinks('architecture')).toEqual([
+ expect.objectContaining({ source: '__skill__/project/my-skill' }),
+ ]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
test('renameDocument moves edges from old doc name to new', () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-rename-'));
const contentDir = join(projectDir, 'content');
@@ -546,6 +584,290 @@ describe('BacklinkIndex', () => {
});
});
+describe('BacklinkIndex structural skill-bundle edges', () => {
+ const SKILL = '.ok/skills/demo/SKILL';
+ const REF = '.ok/skills/demo/references/notes';
+
+ 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');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown(SKILL, 'See `references/notes.md` for detail.\n');
+ index.updateDocumentFromMarkdown(REF, '# Notes\n\nStandalone body, no links.\n');
+
+ expect(index.getBacklinks(REF)).toEqual([{ source: SKILL, anchor: null, snippet: null }]);
+ expect(index.getBacklinks(SKILL)).toEqual([{ source: REF, anchor: null, snippet: null }]);
+ expect(index.getForwardLinks(SKILL)).toEqual([REF]);
+ expect(index.getForwardLinks(REF)).toEqual([SKILL]);
+ expect(index.getBacklinkCount(REF)).toBe(1);
+
+ const neighborhood = index.getLinkGraphNeighborhood(SKILL, 1);
+ expect(new Set(neighborhood.nodes.map((n) => n.id))).toEqual(new Set([REF, SKILL]));
+ expect(neighborhood.links).toContainEqual({ source: SKILL, target: REF });
+ expect(neighborhood.links).toHaveLength(1);
+
+ expect(index.getOrphans([SKILL, REF])).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('a wiki-link reference still works (no regression, no duplicate edge)', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-wiki-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown(SKILL, 'See [[references/notes]].\n');
+ index.updateDocumentFromMarkdown(REF, '# Notes\n');
+
+ expect(index.getForwardLinks(SKILL)).toEqual([REF]);
+ const backlinks = index.getBacklinks(REF);
+ expect(backlinks).toHaveLength(1);
+ expect(backlinks[0]?.source).toBe(SKILL);
+ expect(backlinks[0]?.snippet).toBe('See references/notes.');
+
+ const neighborhood = index.getLinkGraphNeighborhood(SKILL, 1);
+ expect(neighborhood.links).toEqual([{ source: SKILL, target: REF }]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('NON-skill docs sharing a normal folder are NOT auto-connected (scope control)', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-nonskill-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown('notes/alpha', '# Alpha\n');
+ index.updateDocumentFromMarkdown('notes/beta', '# Beta\n');
+ index.updateDocumentFromMarkdown('notes/references/x', '# X\n');
+
+ expect(index.getBacklinks('notes/beta')).toEqual([]);
+ expect(index.getForwardLinks('notes/alpha')).toEqual([]);
+ expect(index.getBacklinks('notes/references/x')).toEqual([]);
+ expect(index.getOrphans(['notes/alpha', 'notes/beta', 'notes/references/x'])).toEqual([
+ 'notes/alpha',
+ 'notes/beta',
+ 'notes/references/x',
+ ]);
+ const neighborhood = index.getLinkGraphNeighborhood('notes/alpha', 2);
+ expect(neighborhood.links).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('scripts/** and cross-skill refs do not draw structural edges', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-scope2-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown(SKILL, '# Demo\n');
+ index.updateDocumentFromMarkdown('.ok/skills/demo/scripts/run', '# run\n');
+ index.updateDocumentFromMarkdown('.ok/skills/other/references/notes', '# other\n');
+
+ expect(index.getForwardLinks(SKILL)).toEqual([]);
+ expect(index.getBacklinks(SKILL)).toEqual([]);
+ expect(index.getBacklinks('.ok/skills/other/references/notes')).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('deleting a reference removes the structural edge', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-del-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown(SKILL, '# Demo\n');
+ index.updateDocumentFromMarkdown(REF, '# Notes\n');
+ expect(index.getForwardLinks(SKILL)).toEqual([REF]);
+
+ index.deleteDocument(REF);
+ expect(index.getForwardLinks(SKILL)).toEqual([]);
+ expect(index.getBacklinks(SKILL)).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('renaming a reference moves the structural edge to the new name', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-skill-ren-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ const REF2 = '.ok/skills/demo/references/renamed';
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown(SKILL, '# Demo\n');
+ index.updateDocumentFromMarkdown(REF, '# Notes\n');
+ expect(index.getForwardLinks(SKILL)).toEqual([REF]);
+
+ index.renameDocument(REF, REF2, '# Notes\n');
+ expect(index.getForwardLinks(SKILL)).toEqual([REF2]);
+ expect(index.getBacklinks(REF2)).toEqual([{ source: SKILL, anchor: null, snippet: null }]);
+ expect(index.getBacklinks(REF)).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('BacklinkIndex GLOBAL structural skill-bundle edges', () => {
+ const G_SKILL = '__skill__/global/demo';
+ const G_REF = '__skill__/global/demo/references/notes';
+
+ function makeIndex(): { index: BacklinkIndex; projectDir: string } {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-gskill-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ return { index: new BacklinkIndex({ projectDir, contentDir }), projectDir };
+ }
+
+ test('connects a global SKILL doc and its reference via the structural edge', () => {
+ const { index, projectDir } = makeIndex();
+ try {
+ index.registerGlobalSkillBundleNode(G_SKILL);
+ index.registerGlobalSkillBundleNode(G_REF);
+
+ expect(index.getBacklinks(G_REF)).toEqual([{ source: G_SKILL, anchor: null, snippet: null }]);
+ expect(index.getBacklinks(G_SKILL)).toEqual([{ source: G_REF, anchor: null, snippet: null }]);
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF]);
+ expect(index.getForwardLinks(G_REF)).toEqual([G_SKILL]);
+ expect(index.getBacklinkCount(G_REF)).toBe(1);
+
+ const { nodes, links } = index.getLinkGraph();
+ expect(new Set(nodes.map((n) => n.id))).toEqual(new Set([G_SKILL, G_REF]));
+ expect(links).toContainEqual({ source: G_SKILL, target: G_REF });
+ expect(links).toHaveLength(1);
+
+ const neighborhood = index.getLinkGraphNeighborhood(G_SKILL, 1);
+ expect(neighborhood.links).toContainEqual({ source: G_SKILL, target: G_REF });
+ expect(index.getOrphans([G_SKILL, G_REF])).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('NEGATIVE CONTROL: a global reference body NEVER links into the project KB', () => {
+ const { index, projectDir } = makeIndex();
+ try {
+ index.updateDocumentFromMarkdown('architecture', '# Architecture\n');
+ index.registerGlobalSkillBundleNode(G_SKILL);
+ index.updateDocumentFromMarkdown(G_REF, 'See [[architecture]] and [[notes2]].\n');
+
+ expect(index.getBacklinks('architecture')).toEqual([]);
+ expect(index.getForwardLinks(G_REF)).toEqual([G_SKILL]);
+ expect(index.getBacklinks('notes2')).toEqual([]);
+ index.updateDocumentFromMarkdown(G_SKILL, 'Body links [[architecture]].\n');
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF]);
+ expect(index.getBacklinks('architecture')).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('deleting / renaming a global reference moves the structural edge', () => {
+ const { index, projectDir } = makeIndex();
+ const G_REF2 = '__skill__/global/demo/references/renamed';
+ try {
+ index.registerGlobalSkillBundleNode(G_SKILL);
+ index.registerGlobalSkillBundleNode(G_REF);
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF]);
+
+ index.renameDocument(G_REF, G_REF2, '# Notes\n');
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF2]);
+ expect(index.getBacklinks(G_REF)).toEqual([]);
+
+ index.deleteDocument(G_REF2);
+ expect(index.getForwardLinks(G_SKILL)).toEqual([]);
+ expect(index.getBacklinks(G_SKILL)).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('global and project bundles of the same name never cross-connect', () => {
+ const { index, projectDir } = makeIndex();
+ try {
+ index.updateDocumentFromMarkdown('.ok/skills/demo/SKILL', '# Project demo\n');
+ index.updateDocumentFromMarkdown('.ok/skills/demo/references/notes', '# Project notes\n');
+ index.registerGlobalSkillBundleNode(G_SKILL);
+ index.registerGlobalSkillBundleNode(G_REF);
+
+ expect(index.getForwardLinks('.ok/skills/demo/SKILL')).toEqual([
+ '.ok/skills/demo/references/notes',
+ ]);
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF]);
+ expect(index.getBacklinks(G_REF)).toEqual([{ source: G_SKILL, anchor: null, snippet: null }]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('ingestGlobalSkillBundles registers SKILL + references from disk (idempotent)', async () => {
+ const { index, projectDir } = makeIndex();
+ const homeSkills = join(projectDir, 'home', '.ok', 'skills');
+ const demoDir = join(homeSkills, 'demo');
+ mkdirSync(join(demoDir, 'references', 'sub'), { recursive: true });
+ writeFileSync(join(demoDir, 'SKILL.md'), '---\nname: demo\n---\n# Demo\n');
+ writeFileSync(join(demoDir, 'references', 'notes.md'), '# Notes\n');
+ writeFileSync(join(demoDir, 'references', 'sub', 'deep.md'), '# Deep\n');
+ mkdirSync(join(demoDir, 'scripts'), { recursive: true });
+ writeFileSync(join(demoDir, 'scripts', 'run.sh'), '#!/bin/sh\n');
+ try {
+ await index.ingestGlobalSkillBundles([homeSkills]);
+
+ const G_REF_DEEP = '__skill__/global/demo/references/sub/deep';
+ expect(new Set(index.getForwardLinks(G_SKILL))).toEqual(new Set([G_REF, G_REF_DEEP]));
+ expect(index.getBacklinks(G_REF)).toEqual([{ source: G_SKILL, anchor: null, snippet: null }]);
+ expect(index.getBacklinks('__skill__/global/demo/scripts/run')).toEqual([]);
+
+ await index.ingestGlobalSkillBundles([homeSkills]);
+ expect(new Set(index.getForwardLinks(G_SKILL))).toEqual(new Set([G_REF, G_REF_DEEP]));
+
+ rmSync(join(demoDir, 'references', 'notes.md'));
+ await index.ingestGlobalSkillBundles([homeSkills]);
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF_DEEP]);
+ expect(index.getBacklinks(G_REF)).toEqual([]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ test('global nodes survive a content rebuild/reconcile (re-ingest restores them)', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-gskill-rebuild-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ const homeSkills = join(projectDir, 'home', '.ok', 'skills');
+ const demoDir = join(homeSkills, 'demo');
+ mkdirSync(join(demoDir, 'references'), { recursive: true });
+ writeFileSync(join(demoDir, 'SKILL.md'), '# Demo\n');
+ writeFileSync(join(demoDir, 'references', 'notes.md'), '# Notes\n');
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.registerGlobalSkillBundleNode(G_SKILL);
+ index.registerGlobalSkillBundleNode(G_REF);
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF]);
+
+ await index.rebuildFromDisk();
+ expect(index.getForwardLinks(G_SKILL)).toEqual([]);
+ await index.ingestGlobalSkillBundles([homeSkills]);
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF]);
+
+ await index.reconcileWithDisk();
+ expect(index.getForwardLinks(G_SKILL)).toEqual([G_REF]);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+});
+
describe('resolveMarkdownHref', () => {
test('resolves same-directory relative link', () => {
expect(resolveMarkdownHref('./other', 'notes')).toBe('other');
diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.ts
index 796a8ad3e..1ad8313d9 100644
--- a/packages/server/src/backlink-index.ts
+++ b/packages/server/src/backlink-index.ts
@@ -6,12 +6,18 @@ import {
classifyWikiLinkTarget,
getWikiLinkText,
isOrphanMode,
+ MANAGED_ARTIFACT_PREFIX_SKILL,
+ managedArtifactDocNameFromContentTarget,
ORPHAN_MODES,
type OrphanMode,
+ parseGlobalSkillBundleDoc,
+ parseProjectSkillBundleDoc,
resolveInternalHref,
+ resolveSkillBundleWikiTarget,
+ skillLiveDocName,
stripFrontmatter,
} from '@inkeep/open-knowledge-core';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';
import { getLocalDir } from './config/paths.ts';
import type { ContentFilter } from './content-filter.ts';
import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';
@@ -128,6 +134,28 @@ function createEmptyState(): BranchGraphState {
};
}
+function parseSkillBundleDocAnyScope(
+ docName: string,
+): { name: string; kind: 'skill' | 'reference'; skillDocName: string } | null {
+ const project = parseProjectSkillBundleDoc(docName);
+ if (project) {
+ return {
+ name: project.name,
+ kind: project.kind,
+ skillDocName: skillLiveDocName('project', project.name),
+ };
+ }
+ const global = parseGlobalSkillBundleDoc(docName);
+ if (global) {
+ return {
+ name: global.name,
+ kind: global.kind,
+ skillDocName: skillLiveDocName('global', global.name),
+ };
+ }
+ return null;
+}
+
function mergeLinkMeta(
existing: { anchor: string | null; snippet: string | null } | undefined,
next: { anchor: string | null; snippet: string | null },
@@ -252,7 +280,10 @@ function readWikiLink(
};
}
-function extractWikiLinksFromLine(line: string): {
+function extractWikiLinksFromLine(
+ line: string,
+ sourceDocName: string,
+): {
text: string;
occurrences: InlineWikiLinkOccurrence[];
} {
@@ -284,8 +315,10 @@ function extractWikiLinksFromLine(line: string): {
flatText += label;
const classified = classifyWikiLinkTarget(wikiLink.target, wikiLink.anchor);
if (classified?.kind === 'doc') {
+ const target =
+ resolveSkillBundleWikiTarget(wikiLink.target, sourceDocName) ?? classified.docName;
occurrences.push({
- target: classified.docName,
+ target,
anchor: classified.anchor,
start,
end: start + label.length,
@@ -531,7 +564,10 @@ export function extractMarkdownLinksFromMarkdown(
return links;
}
-export function extractWikiLinksFromMarkdown(markdown: string): ExtractedWikiLink[] {
+export function extractWikiLinksFromMarkdown(
+ markdown: string,
+ sourceDocName = '',
+): ExtractedWikiLink[] {
const source = markdown.replaceAll('\r\n', '\n').replaceAll('\r', '\n');
const lines = source.split('\n');
const links: ExtractedWikiLink[] = [];
@@ -547,7 +583,7 @@ export function extractWikiLinksFromMarkdown(markdown: string): ExtractedWikiLin
if (nextFence) {
fence = nextFence;
} else {
- const extracted = extractWikiLinksFromLine(line);
+ const extracted = extractWikiLinksFromLine(line, sourceDocName);
links.push(
...extracted.occurrences.map(({ target, anchor, start, end }) => ({
target,
@@ -738,6 +774,25 @@ export class BacklinkIndex {
return state;
}
+ private structuralBundleNeighbors(docName: string, branch = this.activeBranch): Set<string> {
+ const parsed = parseSkillBundleDocAnyScope(docName);
+ const neighbors = new Set<string>();
+ if (!parsed) return neighbors;
+ const state = this.getState(branch);
+ if (!state.forward.has(docName)) return neighbors;
+ if (parsed.kind === 'skill') {
+ for (const candidate of state.forward.keys()) {
+ const other = parseSkillBundleDocAnyScope(candidate);
+ if (other?.kind === 'reference' && other.skillDocName === docName) {
+ neighbors.add(candidate);
+ }
+ }
+ } else {
+ if (state.forward.has(parsed.skillDocName)) neighbors.add(parsed.skillDocName);
+ }
+ return neighbors;
+ }
+
getActiveBranch(): string {
return this.activeBranch;
}
@@ -751,13 +806,42 @@ export class BacklinkIndex {
return resolve(getLocalDir(this.projectDir), 'cache', branch, 'backlinks.json');
}
+ private registerNodeOnly(docName: string, branch = this.activeBranch): void {
+ const state = this.getState(branch);
+ const priorTargets = state.forward.get(docName) ?? new Set<string>();
+ const priorExternalTargets = state.externalForward.get(docName) ?? new Map();
+ for (const target of priorTargets) {
+ const sources = state.backward.get(target);
+ if (!sources) continue;
+ sources.delete(docName);
+ if (sources.size === 0) state.backward.delete(target);
+ }
+ for (const url of priorExternalTargets.keys()) {
+ const sources = state.externalBackward.get(url);
+ if (!sources) continue;
+ sources.delete(docName);
+ if (sources.size === 0) state.externalBackward.delete(url);
+ }
+ state.forward.set(docName, new Set());
+ state.externalForward.set(docName, new Map());
+ }
+
+ registerGlobalSkillBundleNode(docName: string, branch = this.activeBranch): void {
+ if (!parseGlobalSkillBundleDoc(docName)) return;
+ this.registerNodeOnly(docName, branch);
+ }
+
updateDocument(
docName: string,
links: ExtractedWikiLink[],
externalLinks: ExtractedExternalLink[] = [],
branch = this.activeBranch,
): void {
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isLinkIndexExcludedDoc(docName)) return;
+ if (parseGlobalSkillBundleDoc(docName)) {
+ this.registerNodeOnly(docName, branch);
+ return;
+ }
const state = this.getState(branch);
const priorTargets = state.forward.get(docName) ?? new Set<string>();
const priorExternalTargets = state.externalForward.get(docName) ?? new Map();
@@ -783,11 +867,12 @@ export class BacklinkIndex {
for (const link of links) {
if (!link.target) continue;
- nextTargets.add(link.target);
- let sources = state.backward.get(link.target);
+ const target = managedArtifactDocNameFromContentTarget(link.target) ?? link.target;
+ nextTargets.add(target);
+ let sources = state.backward.get(target);
if (!sources) {
sources = new Map();
- state.backward.set(link.target, sources);
+ state.backward.set(target, sources);
}
sources.set(
docName,
@@ -818,7 +903,7 @@ export class BacklinkIndex {
updateDocumentFromMarkdown(docName: string, markdown: string, branch = this.activeBranch): void {
try {
const { body } = stripFrontmatter(markdown);
- const wikiLinks = extractWikiLinksFromMarkdown(body);
+ const wikiLinks = extractWikiLinksFromMarkdown(body, docName);
const mdLinks = extractMarkdownLinksFromMarkdown(body, docName);
const wikiExternalLinks = extractExternalWikiLinksFromMarkdown(body);
const mdExternalLinks = extractExternalMarkdownLinksFromMarkdown(body, docName);
@@ -837,7 +922,7 @@ export class BacklinkIndex {
}
deleteDocument(docName: string, branch = this.activeBranch): void {
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isLinkIndexExcludedDoc(docName)) return;
const state = this.getState(branch);
const targets = state.forward.get(docName) ?? new Set<string>();
const externalTargets = state.externalForward.get(docName) ?? new Map();
@@ -870,20 +955,34 @@ export class BacklinkIndex {
getBacklinks(target: string, branch = this.activeBranch): BacklinkEntry[] {
const state = this.getState(branch);
const sources = state.backward.get(target);
- if (!sources) return [];
- return [...sources.entries()]
- .map(([source, meta]) => ({ source, anchor: meta.anchor, snippet: meta.snippet }))
- .sort((a, b) => a.source.localeCompare(b.source));
+ const entries = new Map<string, BacklinkEntry>();
+ if (sources) {
+ for (const [source, meta] of sources) {
+ entries.set(source, { source, anchor: meta.anchor, snippet: meta.snippet });
+ }
+ }
+ for (const partner of this.structuralBundleNeighbors(target, branch)) {
+ if (!entries.has(partner))
+ entries.set(partner, { source: partner, anchor: null, snippet: null });
+ }
+ return [...entries.values()].sort((a, b) => a.source.localeCompare(b.source));
}
getBacklinkCount(target: string, branch = this.activeBranch): number {
const state = this.getState(branch);
- return state.backward.get(target)?.size ?? 0;
+ const authored = state.backward.get(target);
+ const structural = this.structuralBundleNeighbors(target, branch);
+ if (structural.size === 0) return authored?.size ?? 0;
+ const union = new Set(authored?.keys() ?? []);
+ for (const partner of structural) union.add(partner);
+ return union.size;
}
getForwardLinks(source: string, branch = this.activeBranch): string[] {
const state = this.getState(branch);
- return [...(state.forward.get(source) ?? new Set<string>())].sort((a, b) => a.localeCompare(b));
+ const targets = new Set(state.forward.get(source) ?? new Set<string>());
+ for (const partner of this.structuralBundleNeighbors(source, branch)) targets.add(partner);
+ return [...targets].sort((a, b) => a.localeCompare(b));
}
getForwardLinkEntries(source: string, branch = this.activeBranch): ForwardLinkEntry[] {
@@ -911,10 +1010,23 @@ export class BacklinkIndex {
getOrphans(allDocs: string[], mode: OrphanMode = 'both', branch = this.activeBranch): string[] {
const state = this.getState(branch);
+ const skillDocsWithReference = new Set<string>();
+ for (const candidate of state.forward.keys()) {
+ const parsed = parseSkillBundleDocAnyScope(candidate);
+ if (parsed?.kind === 'reference') skillDocsWithReference.add(parsed.skillDocName);
+ }
+ const hasStructuralEdge = (docName: string): boolean => {
+ const parsed = parseSkillBundleDocAnyScope(docName);
+ if (!parsed || !state.forward.has(docName)) return false;
+ return parsed.kind === 'skill'
+ ? skillDocsWithReference.has(docName)
+ : state.forward.has(parsed.skillDocName);
+ };
return [...allDocs]
.filter((docName) => {
- const hasInboundEdges = (state.backward.get(docName)?.size ?? 0) > 0;
- const hasOutboundEdges = (state.forward.get(docName)?.size ?? 0) > 0;
+ const structural = hasStructuralEdge(docName);
+ const hasInboundEdges = structural || (state.backward.get(docName)?.size ?? 0) > 0;
+ const hasOutboundEdges = structural || (state.forward.get(docName)?.size ?? 0) > 0;
if (mode === 'incoming') return !hasInboundEdges;
if (mode === 'outgoing') return !hasOutboundEdges;
@@ -1006,6 +1118,29 @@ 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)) {
+ if (state.forward.get(source)?.has(target) || state.forward.get(target)?.has(source)) {
+ continue;
+ }
+ nodes.set(source, {
+ kind: 'doc',
+ id: source,
+ docName: source,
+ anchor: getRepresentativeAnchor(state.backward.get(source)),
+ });
+ nodes.set(target, {
+ kind: 'doc',
+ id: target,
+ docName: target,
+ anchor: getRepresentativeAnchor(state.backward.get(target)),
+ });
+ links.push({ source, target });
+ }
+ }
+
return {
nodes: [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id)),
links,
@@ -1054,6 +1189,9 @@ export class BacklinkIndex {
for (const source of state.backward.get(current.nodeId)?.keys() ?? []) {
neighbors.add(source);
}
+ for (const partner of this.structuralBundleNeighbors(current.nodeId, branch)) {
+ neighbors.add(partner);
+ }
}
for (const neighbor of neighbors) {
@@ -1081,6 +1219,18 @@ 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)) {
+ if (!visited.has(target)) continue;
+ if (state.forward.get(source)?.has(target) || state.forward.get(target)?.has(source)) {
+ continue;
+ }
+ links.push({ source, target });
+ }
+ }
+
const nodes = [...visited].sort().map<GraphNode>((nodeId) => {
const url = externalUrlFromNodeId(nodeId);
if (!url) {
@@ -1172,7 +1322,7 @@ export class BacklinkIndex {
const { docName, mtimeMs, markdown } = result.value;
mtimes.set(docName, mtimeMs);
const { body } = stripFrontmatter(markdown);
- const wikiLinks = extractWikiLinksFromMarkdown(body);
+ const wikiLinks = extractWikiLinksFromMarkdown(body, docName);
const mdLinks = extractMarkdownLinksFromMarkdown(body, docName);
const wikiExternalLinks = extractExternalWikiLinksFromMarkdown(body);
const mdExternalLinks = extractExternalMarkdownLinksFromMarkdown(body, docName);
@@ -1189,11 +1339,12 @@ export class BacklinkIndex {
state.externalForward.set(docName, externalTargets);
for (const link of links) {
if (!link.target) continue;
- targets.add(link.target);
- let sources = state.backward.get(link.target);
+ const target = managedArtifactDocNameFromContentTarget(link.target) ?? link.target;
+ targets.add(target);
+ let sources = state.backward.get(target);
if (!sources) {
sources = new Map();
- state.backward.set(link.target, sources);
+ state.backward.set(target, sources);
}
sources.set(
docName,
@@ -1312,6 +1463,7 @@ export class BacklinkIndex {
let deleted = 0;
const allKnownDocs = new Set([...storedMtimes.keys(), ...this.getState(branch).forward.keys()]);
for (const docName of allKnownDocs) {
+ if (parseGlobalSkillBundleDoc(docName)) continue;
if (!currentDocSet.has(docName)) {
this.deleteDocument(docName, branch);
deleted++;
@@ -1321,4 +1473,72 @@ export class BacklinkIndex {
this.mtimesByBranch.set(branch, newMtimes);
return { added, updated, deleted };
}
+
+ async ingestGlobalSkillBundles(
+ roots: ReadonlyArray<string>,
+ branch = this.activeBranch,
+ ): Promise<void> {
+ const live = new Set<string>();
+ for (const root of roots) {
+ if (!existsSync(root)) continue;
+ let skillDirs: Dirent[];
+ try {
+ skillDirs = await readdir(root, { withFileTypes: true });
+ } catch (err) {
+ console.warn(`[backlinks] Failed to read global skills root ${root}:`, err);
+ continue;
+ }
+ for (const skillDir of skillDirs) {
+ if (!skillDir.isDirectory()) continue;
+ const name = skillDir.name;
+ const dir = join(root, name);
+ const skillDocName = skillLiveDocName('global', name);
+ if (existsSync(join(dir, 'SKILL.md'))) {
+ if (parseGlobalSkillBundleDoc(skillDocName)) {
+ this.registerNodeOnly(skillDocName, branch);
+ live.add(skillDocName);
+ }
+ }
+ const refs: Array<{ docName: string }> = [];
+ await this.walkGlobalSkillReferences(join(dir, 'references'), name, '', refs);
+ for (const { docName } of refs) {
+ this.registerNodeOnly(docName, branch);
+ live.add(docName);
+ }
+ }
+ }
+ const stale: string[] = [];
+ for (const docName of this.getState(branch).forward.keys()) {
+ if (parseGlobalSkillBundleDoc(docName) && !live.has(docName)) stale.push(docName);
+ }
+ for (const docName of stale) this.deleteDocument(docName, branch);
+ }
+
+ private async walkGlobalSkillReferences(
+ dir: string,
+ skillName: string,
+ prefix: string,
+ results: Array<{ docName: string }>,
+ ): Promise<void> {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
+ console.warn(`[backlinks] Failed to read skill references dir ${dir}:`, err);
+ }
+ return;
+ }
+ for (const entry of entries) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) {
+ await this.walkGlobalSkillReferences(join(dir, entry.name), skillName, rel, results);
+ } else if (entry.isFile() && isSupportedDocFile(entry.name)) {
+ const extLess = stripDocExtension(rel);
+ results.push({
+ docName: `${MANAGED_ARTIFACT_PREFIX_SKILL}global/${skillName}/references/${extLess}`,
+ });
+ }
+ }
+ }
}
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 94b6ec5fa..21525c91b 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -34,6 +34,7 @@ import { mountMcpAndApi } from './mcp-mount.ts';
import { MissingOkConfigError } from './missing-ok-config-error.ts';
import { createServer, type ServerInstance, type ServerOptions } from './server-factory.ts';
import { installServerMemoryGauge } from './server-memory-telemetry.ts';
+import { reconcileSkillInstalls } from './skill-reconcile.ts';
import { initTelemetry, shutdownTelemetry, withSpan } from './telemetry.ts';
import {
initToleranceTelemetryWriter,
@@ -520,6 +521,37 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
}
};
+ 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;
+ 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.`,
+ );
+ }
+ } catch (err) {
+ log.warn?.(
+ { event: 'installed-skills-reconcile-failed', error: String(err) },
+ 'Installed-skills reconcile failed (non-fatal).',
+ );
+ }
+
return {
httpServer,
destroy,
diff --git a/packages/server/src/build-skill-zip.ts b/packages/server/src/build-skill-zip.ts
index 1ad88778d..dc687cc18 100644
--- a/packages/server/src/build-skill-zip.ts
+++ b/packages/server/src/build-skill-zip.ts
@@ -6,19 +6,15 @@ 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';
+
+export type { BundleId };
/** Maximum uncompressed + compressed size. Catches accidental binary bloat.
* Current baseline is ~10 KB DEFLATE — 100 KB gives an order of magnitude
* of headroom without permitting a runaway regression. */
const MAX_ZIP_BYTES = 102_400;
-export type BundleId = 'discovery' | 'project';
-
-const BUNDLE_SKILL_NAME: Record<BundleId, string> = {
- discovery: 'open-knowledge-discovery',
- project: 'open-knowledge',
-};
-
export interface BuildSkillZipOptions {
bundle?: BundleId;
sourceDir?: string;
diff --git a/packages/server/src/cc1-broadcast.test.ts b/packages/server/src/cc1-broadcast.test.ts
index fa76a3b70..b21bbfc2f 100644
--- a/packages/server/src/cc1-broadcast.test.ts
+++ b/packages/server/src/cc1-broadcast.test.ts
@@ -19,7 +19,12 @@ import {
CONFIG_DOC_NAMES,
SYSTEM_DOC_NAME,
} from '@inkeep/open-knowledge-core';
-import { CC1Broadcaster, isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import {
+ CC1Broadcaster,
+ isConfigDoc,
+ isLinkIndexExcludedDoc,
+ isSystemDoc,
+} from './cc1-broadcast.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
describe('isSystemDoc', () => {
@@ -550,3 +555,22 @@ describe('CC1Broadcaster', () => {
expect(broadcasts).toHaveLength(0);
});
});
+
+describe('isLinkIndexExcludedDoc', () => {
+ test('excludes system + config docs (never in the link index)', () => {
+ expect(isLinkIndexExcludedDoc(SYSTEM_DOC_NAME)).toBe(true);
+ for (const name of CONFIG_DOC_NAMES) {
+ expect(isLinkIndexExcludedDoc(name)).toBe(true);
+ }
+ });
+
+ test('admits managed-artifact docs — they participate in the link index', () => {
+ expect(isLinkIndexExcludedDoc('__skill__/project/my-skill')).toBe(false);
+ expect(isLinkIndexExcludedDoc('__template__/docs/my-template')).toBe(false);
+ });
+
+ test('admits ordinary documents', () => {
+ expect(isLinkIndexExcludedDoc('docs/getting-started')).toBe(false);
+ expect(isLinkIndexExcludedDoc('readme')).toBe(false);
+ });
+});
diff --git a/packages/server/src/cc1-broadcast.ts b/packages/server/src/cc1-broadcast.ts
index 06f710715..723c808c0 100644
--- a/packages/server/src/cc1-broadcast.ts
+++ b/packages/server/src/cc1-broadcast.ts
@@ -15,6 +15,7 @@ import {
CONFIG_DOC_NAMES,
type ConfigValidationError,
type DerivedViewChannel,
+ isManagedArtifactDocName,
SYSTEM_DOC_NAME,
} from '@inkeep/open-knowledge-core';
import { getLogger } from './logger.ts';
@@ -41,6 +42,20 @@ export function isConfigDoc(documentName: string): boolean {
return CONFIG_DOC_NAME_SET.has(documentName);
}
+export function isManagedArtifactDoc(documentName: string): boolean {
+ return isManagedArtifactDocName(documentName);
+}
+
+export function isReservedForUserTree(documentName: string): boolean {
+ return (
+ isSystemDoc(documentName) || isConfigDoc(documentName) || isManagedArtifactDoc(documentName)
+ );
+}
+
+export function isLinkIndexExcludedDoc(documentName: string): boolean {
+ return isSystemDoc(documentName) || isConfigDoc(documentName);
+}
+
export class CC1Broadcaster {
private readonly hocuspocus: Hocuspocus;
private readonly seqs = new Map<string, number>();
diff --git a/packages/server/src/content-filter.test.ts b/packages/server/src/content-filter.test.ts
index 425e40645..451f61d76 100644
--- a/packages/server/src/content-filter.test.ts
+++ b/packages/server/src/content-filter.test.ts
@@ -189,24 +189,24 @@ describe('ContentFilter', () => {
test('excludes paths matched by .git/info/exclude (per-clone, untracked)', () => {
initGitRepo(projectDir);
- writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.claude/worktrees/\n');
+ writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.scratch/worktrees/\n');
const filter = createContentFilter({ projectDir, contentDir: projectDir });
- expect(filter.isDirExcluded('.claude/worktrees')).toBe(true);
- expect(filter.isExcluded('.claude/worktrees/feature-x/note.md')).toBe(true);
- expect(filter.isExcluded('.claude/skills/foo.md')).toBe(false);
+ expect(filter.isDirExcluded('.scratch/worktrees')).toBe(true);
+ expect(filter.isExcluded('.scratch/worktrees/feature-x/note.md')).toBe(true);
+ expect(filter.isExcluded('.scratch/skills/foo.md')).toBe(false);
});
test('unions .git/info/exclude with project .gitignore', () => {
initGitRepo(projectDir);
writeFileSync(join(projectDir, '.gitignore'), 'drafts/\n');
- writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.claude/worktrees/\n');
+ writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.scratch/worktrees/\n');
const filter = createContentFilter({ projectDir, contentDir: projectDir });
expect(filter.isExcluded('drafts/wip.md')).toBe(true);
- expect(filter.isExcluded('.claude/worktrees/fx/n.md')).toBe(true);
+ expect(filter.isExcluded('.scratch/worktrees/fx/n.md')).toBe(true);
expect(filter.isExcluded('docs/guide.md')).toBe(false);
});
@@ -278,12 +278,12 @@ describe('ContentFilter', () => {
writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '');
const filter = createContentFilter({ projectDir, contentDir: projectDir });
- expect(filter.isExcluded('.claude/worktrees/fx/n.md')).toBe(false);
+ expect(filter.isExcluded('.scratch/worktrees/fx/n.md')).toBe(false);
- writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.claude/worktrees/\n');
+ writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.scratch/worktrees/\n');
const result = await filter.rebuildIgnorePatterns();
expect(result.ok).toBe(true);
- expect(filter.isExcluded('.claude/worktrees/fx/n.md')).toBe(true);
+ expect(filter.isExcluded('.scratch/worktrees/fx/n.md')).toBe(true);
});
});
@@ -332,6 +332,22 @@ describe('ContentFilter', () => {
expect(filter.getWatcherIgnoreGlobs()).toEqual([]);
});
+
+ test('drops blanket .ok globs so the OS watcher can reach .ok/skills (skills-as-content)', () => {
+ mkdirSync(join(projectDir, '.git', 'info'), { recursive: true });
+ writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');
+ writeFileSync(join(projectDir, '.gitignore'), 'dist/\n.ok\nnode_modules/\n');
+
+ const globs = createContentFilter({
+ projectDir,
+ contentDir: projectDir,
+ }).getWatcherIgnoreGlobs();
+
+ expect(globs).not.toContain('.ok');
+ expect(globs).not.toContain('.ok/');
+ expect(globs).toContain('dist/');
+ expect(globs).toContain('node_modules/');
+ });
});
describe('dot-dir scope symmetry', () => {
@@ -357,13 +373,16 @@ describe('ContentFilter', () => {
const filter = createContentFilter({ projectDir, contentDir: projectDir });
- expect(filter.isExcluded('.cursor/skills/SKILL.md')).toBe(false);
- expect(filter.isExcluded('.claude/skills/foo.md')).toBe(false);
- expect(filter.isExcluded('.agents/skills/foo.md')).toBe(false);
- expect(filter.isExcluded('.codex/skills/foo.md')).toBe(false);
+ expect(filter.isExcluded('.cursor/skills/SKILL.md')).toBe(true);
+ expect(filter.isExcluded('.claude/skills/foo.md')).toBe(true);
+ expect(filter.isExcluded('.agents/skills/foo.md')).toBe(true);
+ expect(filter.isExcluded('.codex/skills/foo.md')).toBe(true);
+ expect(filter.isExcluded('.opencode/skills/foo.md')).toBe(true);
+ expect(filter.isExcluded('packages/.cursor/skills/SKILL.md')).toBe(true);
+ expect(filter.isExcluded('.cursor/skills/open-knowledge/diagram.png')).toBe(true);
+
expect(filter.isExcluded('.github/PULL_REQUEST_TEMPLATE.md')).toBe(false);
expect(filter.isExcluded('.vscode/notes.md')).toBe(false);
- expect(filter.isExcluded('packages/.cursor/skills/SKILL.md')).toBe(false);
expect(filter.isExcluded('.git/config')).toBe(true);
expect(filter.isExcluded('.ok/config.yml')).toBe(true);
@@ -376,11 +395,10 @@ describe('ContentFilter', () => {
expect(filter.isExcluded('.cursor/rules/some-rule.mdc')).toBe(true);
expect(filter.isExcluded('.claude/settings.local.json')).toBe(true);
- expect(filter.isExcluded('.cursor/skills/open-knowledge/diagram.png')).toBe(false);
-
- expect(filter.isDirExcluded('.cursor')).toBe(false);
+ expect(filter.isDirExcluded('.cursor')).toBe(true);
expect(filter.isDirExcluded('.git')).toBe(true);
- expect(filter.isDirExcluded('.ok')).toBe(true);
+ expect(filter.isDirExcluded('.ok')).toBe(false);
+ expect(filter.isDirExcluded('.ok/local')).toBe(true);
});
});
@@ -418,7 +436,7 @@ describe('ContentFilter', () => {
expect(filter.isDirExcluded('.turbo')).toBe(true);
expect(filter.isDirExcluded('coverage')).toBe(true);
expect(filter.isDirExcluded('.git')).toBe(true);
- expect(filter.isDirExcluded('.ok')).toBe(true);
+ expect(filter.isDirExcluded('.ok')).toBe(false);
expect(filter.isDirExcluded('.ok/local')).toBe(true);
expect(filter.isDirExcluded('.ok/local/cache')).toBe(true);
expect(filter.isDirExcluded('docs')).toBe(false);
@@ -454,15 +472,17 @@ describe('ContentFilter', () => {
expect(filter.isExcluded('node_modules/logo.png')).toBe(true);
});
- test('does not descend into .ok during populateDirCount (BUILTIN_SKIP_DIRS)', () => {
+ test('admits .ok only down the skills path; non-skill .ok files stay excluded', () => {
mkdirSync(join(projectDir, '.ok'), { recursive: true });
writeFileSync(join(projectDir, '.ok', 'AGENTS.md'), '# Agents\n');
writeFileSync(join(projectDir, 'docs.md'), '# Docs\n');
const filter = createContentFilter({ projectDir, contentDir: projectDir });
- expect(filter.isDirExcluded('.ok')).toBe(true);
+ expect(filter.isDirExcluded('.ok')).toBe(false);
+ expect(filter.isDirExcluded('.ok/local')).toBe(true);
expect(filter.isExcluded('.ok/logo.png')).toBe(true);
+ expect(filter.isExcluded('.ok/AGENTS.md')).toBe(true);
});
test('isExcluded rejects supported docs born inside BUILTIN_SKIP_DIRS', () => {
@@ -487,6 +507,7 @@ describe('ContentFilter', () => {
expect(filter.isDirExcluded('node_modules', BYPASS)).toBe(true);
expect(filter.isDirExcluded('node_modules/some-pkg', BYPASS)).toBe(true);
expect(filter.isDirExcluded('.ok', BYPASS)).toBe(true);
+ expect(filter.isDirExcluded('.ok/local', BYPASS)).toBe(true);
expect(filter.isDirExcluded('.open-knowledge', BYPASS)).toBe(true);
expect(filter.isDirExcluded('.openknowledge', BYPASS)).toBe(true);
expect(filter.isDirExcluded('packages/foo/node_modules', BYPASS)).toBe(true);
@@ -578,6 +599,16 @@ describe('ContentFilter', () => {
expect(filter.isExcluded('docs/.Environment.md', BYPASS)).toBe(false);
expect(filter.isExcluded('docs/KEYMAP.md', BYPASS)).toBe(false);
+ expect(filter.isExcluded('.ok/skills/foo/server.key')).toBe(true);
+ expect(filter.isExcluded('.ok/skills/foo/id_rsa')).toBe(true);
+ expect(filter.isExcluded('.ok/skills/foo/.env')).toBe(true);
+ expect(filter.isPathIgnored('.ok/skills/foo/server.key')).toBe(true);
+ expect(filter.isPathIgnored('.ok/skills/foo/id_rsa')).toBe(true);
+ expect(filter.isPathIgnored('.ok/skills/foo/.env')).toBe(true);
+ expect(filter.isDirExcluded('.ok/skills/foo/.ssh')).toBe(true);
+ expect(filter.isExcluded('.ok/skills/foo/SKILL.md')).toBe(false);
+ expect(filter.isExcluded('.ok/skills/foo/diagram.png')).toBe(false);
+
expect(filter.isDirExcluded('dist', BYPASS)).toBe(false);
expect(filter.isDirExcluded('build', BYPASS)).toBe(false);
expect(filter.isDirExcluded('coverage', BYPASS)).toBe(false);
diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.ts
index 223efbc71..e9a4385e9 100644
--- a/packages/server/src/content-filter.ts
+++ b/packages/server/src/content-filter.ts
@@ -4,9 +4,9 @@ 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 } from '@inkeep/open-knowledge-core';
+import { LINKABLE_ASSET_EXTENSIONS, SKILL_CONTENT_ROOT } from '@inkeep/open-knowledge-core';
import ignore, { type Ignore } from 'ignore';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { isReservedForUserTree } from './cc1-broadcast.ts';
import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';
import { getLogger } from './logger.ts';
import { toPosix } from './path-utils.ts';
@@ -72,6 +72,11 @@ const BUILTIN_SKIP_DIRS = new Set([
'.ok',
'.open-knowledge',
'.openknowledge',
+ '.claude',
+ '.cursor',
+ '.codex',
+ '.agents',
+ '.opencode',
'Library',
'Applications',
'.Trash',
@@ -83,6 +88,11 @@ const ALWAYS_SKIP_DIRS = new Set<string>([
'.ok',
'.open-knowledge',
'.openknowledge',
+ '.claude',
+ '.cursor',
+ '.codex',
+ '.agents',
+ '.opencode',
]);
function pathHasAlwaysSkipSegment(relativePath: string): boolean {
@@ -92,6 +102,23 @@ function pathHasAlwaysSkipSegment(relativePath: string): boolean {
return false;
}
+function isSkillContentFile(relativePath: string): boolean {
+ return relativePath.startsWith(`${SKILL_CONTENT_ROOT}/`);
+}
+
+function isSkillContentAncestorDir(relativePath: string): boolean {
+ return (
+ relativePath === '.ok' ||
+ relativePath === SKILL_CONTENT_ROOT ||
+ relativePath.startsWith(`${SKILL_CONTENT_ROOT}/`)
+ );
+}
+
+function globBlocksSkillContent(pattern: string): boolean {
+ const p = pattern.replace(/^\/+/, '').replace(/\/+$/, '').trim();
+ return p === '.ok' || p === '.ok/**' || p === '**/.ok' || p === '**/.ok/**';
+}
+
const BUILTIN_SKIP_FILES = new Set<string>(['.DS_Store', '.localized']);
function isAlwaysSkipFile(relativePath: string): boolean {
@@ -374,7 +401,7 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
}
const newWatcherGlobs = newRootPatterns.filter(
- (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#'),
+ (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#') && !globBlocksSkillContent(p),
);
ig = newIg;
@@ -410,7 +437,7 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
function isReservedDocName(relativePath: string): boolean {
const docName = stripDocExtension(relativePath);
- return isSystemDoc(docName) || isConfigDoc(docName);
+ return isReservedForUserTree(docName);
}
function isRejectedByConfigurableRules(relativePath: string): boolean {
@@ -426,13 +453,20 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
isExcluded(relativePath: string, opts?: ContentFilterReadOpts): boolean {
if (isReservedDocName(relativePath)) return true;
+ if (isSecretBearingFile(relativePath)) return true;
+ if (pathHasSecretBearingDirSegment(relativePath)) return true;
+
+ if (!opts?.bypassFilters && isSkillContentFile(relativePath)) {
+ if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;
+ if (isSupportedDocFile(relativePath)) return false;
+ const ext = extname(relativePath).slice(1).toLowerCase();
+ return !LINKABLE_ASSET_EXTENSIONS.has(ext);
+ }
+
if (pathHasAlwaysSkipSegment(relativePath)) return true;
if (isAlwaysSkipFile(relativePath)) return true;
- if (isSecretBearingFile(relativePath)) return true;
- if (pathHasSecretBearingDirSegment(relativePath)) return true;
-
if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;
if (opts?.bypassFilters) return false;
@@ -452,8 +486,9 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
},
isDirExcluded(relativePath: string, opts?: ContentFilterReadOpts): boolean {
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
if (pathHasSecretBearingDirSegment(relativePath)) return true;
+ if (!opts?.bypassFilters && isSkillContentAncestorDir(relativePath)) return false;
+ if (pathHasAlwaysSkipSegment(relativePath)) return true;
if (singleDocRelPath !== undefined) {
return !isSingleDocAncestorDir(relativePath, singleDocRelPath);
}
@@ -470,10 +505,11 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
isPathIgnored(relativePath: string, opts?: ContentFilterReadOpts): boolean {
if (isReservedDocName(relativePath)) return true;
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
- if (isAlwaysSkipFile(relativePath)) return true;
if (isSecretBearingFile(relativePath)) return true;
if (pathHasSecretBearingDirSegment(relativePath)) return true;
+ if (isSkillContentFile(relativePath)) return false;
+ if (pathHasAlwaysSkipSegment(relativePath)) return true;
+ if (isAlwaysSkipFile(relativePath)) return true;
if (opts?.bypassFilters) return false;
return isRejectedByConfigurableRules(relativePath);
},
@@ -770,7 +806,7 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
function isReservedDocName(relativePath: string): boolean {
const docName = stripDocExtension(relativePath);
- return isSystemDoc(docName) || isConfigDoc(docName);
+ return isReservedForUserTree(docName);
}
function isRejectedByConfigurableRules(relativePath: string): boolean {
for (const segment of relativePath.split('/')) {
@@ -832,7 +868,7 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
ig = newIg;
watcherIgnoreGlobs = newRootPatterns.filter(
- (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#'),
+ (p) => p.length > 0 && !p.startsWith('!') && !p.startsWith('#') && !globBlocksSkillContent(p),
);
dirCount.clear();
for (const [k, v] of newDirCount) dirCount.set(k, v);
@@ -843,10 +879,16 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
return {
isExcluded(relativePath: string, opts?: ContentFilterReadOpts): boolean {
if (isReservedDocName(relativePath)) return true;
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
- if (isAlwaysSkipFile(relativePath)) return true;
if (isSecretBearingFile(relativePath)) return true;
if (pathHasSecretBearingDirSegment(relativePath)) return true;
+ if (!opts?.bypassFilters && isSkillContentFile(relativePath)) {
+ if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;
+ if (isSupportedDocFile(relativePath)) return false;
+ const skillExt = extname(relativePath).slice(1).toLowerCase();
+ return !LINKABLE_ASSET_EXTENSIONS.has(skillExt);
+ }
+ if (pathHasAlwaysSkipSegment(relativePath)) return true;
+ if (isAlwaysSkipFile(relativePath)) return true;
if (singleDocRelPath !== undefined) return relativePath !== singleDocRelPath;
if (opts?.bypassFilters) return false;
if (isRejectedByConfigurableRules(relativePath)) return true;
@@ -861,8 +903,9 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
},
isDirExcluded(relativePath: string, opts?: ContentFilterReadOpts): boolean {
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
if (pathHasSecretBearingDirSegment(relativePath)) return true;
+ if (!opts?.bypassFilters && isSkillContentAncestorDir(relativePath)) return false;
+ if (pathHasAlwaysSkipSegment(relativePath)) return true;
if (singleDocRelPath !== undefined) {
return !isSingleDocAncestorDir(relativePath, singleDocRelPath);
}
@@ -879,10 +922,11 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
isPathIgnored(relativePath: string, opts?: ContentFilterReadOpts): boolean {
if (isReservedDocName(relativePath)) return true;
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
- if (isAlwaysSkipFile(relativePath)) return true;
if (isSecretBearingFile(relativePath)) return true;
if (pathHasSecretBearingDirSegment(relativePath)) return true;
+ if (isSkillContentFile(relativePath)) return false;
+ if (pathHasAlwaysSkipSegment(relativePath)) return true;
+ if (isAlwaysSkipFile(relativePath)) return true;
if (opts?.bypassFilters) return false;
return isRejectedByConfigurableRules(relativePath);
},
diff --git a/packages/server/src/content/skills-write.test.ts b/packages/server/src/content/skills-write.test.ts
new file mode 100644
index 000000000..521a95a80
--- /dev/null
+++ b/packages/server/src/content/skills-write.test.ts
@@ -0,0 +1,319 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ applySkillBundleFileDelete,
+ applySkillBundleFileWrite,
+ applySkillDelete,
+ applySkillMove,
+ applySkillWrite,
+} from './skills-write.ts';
+
+let root: string;
+let skillsRoot: string;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-skills-'));
+ skillsRoot = join(root, '.ok', 'skills');
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+const fm = (name: string, description = 'Use when testing.') => ({ name, description });
+
+describe('applySkillWrite', () => {
+ test('creates SKILL.md with composed name+description frontmatter', () => {
+ const result = applySkillWrite({
+ skillsRoot,
+ name: 'trip-log',
+ body: '# Steps\n\nDo the thing.',
+ frontmatter: fm('trip-log', 'Use when logging a fishing trip.'),
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.created).toBe(true);
+ expect(result.path).toBe('trip-log/SKILL.md');
+ const raw = readFileSync(join(skillsRoot, 'trip-log', 'SKILL.md'), 'utf-8');
+ expect(raw).toContain('name: trip-log');
+ expect(raw).toContain('description: Use when logging a fishing trip.');
+ expect(raw).toContain('# Steps');
+ expect(raw).not.toContain('version:');
+ expect(raw).not.toContain('title:');
+ });
+
+ test('second write reports created:false (overwrite)', () => {
+ applySkillWrite({ skillsRoot, name: 's', body: 'a', frontmatter: fm('s') });
+ const again = applySkillWrite({ skillsRoot, name: 's', body: 'b', frontmatter: fm('s') });
+ expect(again.ok).toBe(true);
+ if (again.ok) expect(again.created).toBe(false);
+ });
+
+ test('rejects name != directory', () => {
+ const result = applySkillWrite({
+ skillsRoot,
+ name: 'trip-log',
+ body: 'x',
+ frontmatter: fm('different'),
+ });
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.code).toBe('NAME_DIR_MISMATCH');
+ });
+
+ test('rejects XML tag in description', () => {
+ const result = applySkillWrite({
+ skillsRoot,
+ name: 'x',
+ body: 'b',
+ frontmatter: fm('x', 'Use when <folder> appears.'),
+ });
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.code).toBe('XML_TAG_IN_DESCRIPTION');
+ });
+
+ test('rejects an uppercase / dotted / spaced name', () => {
+ for (const bad of ['TripLog', 'trip.log', 'trip log', 'trip/log']) {
+ const result = applySkillWrite({ skillsRoot, name: bad, body: 'b', frontmatter: fm(bad) });
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.code).toBe('BAD_NAME');
+ }
+ });
+
+ test('rejects reserved words in name', () => {
+ const result = applySkillWrite({
+ skillsRoot,
+ name: 'claude-helper',
+ body: 'b',
+ frontmatter: fm('claude-helper'),
+ });
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.code).toBe('RESERVED_NAME');
+ });
+
+ test('rejects empty description and over-long description', () => {
+ 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');
+
+ const long = applySkillWrite({
+ skillsRoot,
+ name: 'a',
+ body: 'b',
+ frontmatter: fm('a', 'x'.repeat(1025)),
+ });
+ expect(long.ok).toBe(false);
+ if (!long.ok) expect(long.error.code).toBe('DESCRIPTION_TOO_LONG');
+ });
+
+ test('warns (not errors) on a >500-line body', () => {
+ const result = applySkillWrite({
+ skillsRoot,
+ name: 'big',
+ body: Array.from({ length: 600 }, (_, i) => `line ${i}`).join('\n'),
+ frontmatter: fm('big'),
+ });
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.warnings.some((w) => w.includes('600 lines'))).toBe(true);
+ });
+});
+
+describe('applySkillDelete', () => {
+ test('removes the whole skill dir and reports existed', () => {
+ applySkillWrite({ skillsRoot, name: 's', body: 'a', frontmatter: fm('s') });
+ expect(existsSync(join(skillsRoot, 's'))).toBe(true);
+ const result = applySkillDelete({ skillsRoot, name: 's' });
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.existed).toBe(true);
+ expect(existsSync(join(skillsRoot, 's'))).toBe(false);
+ });
+
+ test('no-op delete of an absent skill reports existed:false', () => {
+ const result = applySkillDelete({ skillsRoot, name: 'ghost' });
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.existed).toBe(false);
+ });
+
+ test('cleans an emptied .ok/skills then .ok', () => {
+ applySkillWrite({ skillsRoot, name: 'only', body: 'a', frontmatter: fm('only') });
+ applySkillDelete({ skillsRoot, name: 'only' });
+ expect(existsSync(skillsRoot)).toBe(false);
+ expect(existsSync(join(root, '.ok'))).toBe(false);
+ });
+});
+
+describe('applySkillMove', () => {
+ const fsRelocate = async (from: string, to: string) => {
+ const { renameSync } = await import('node:fs');
+ renameSync(from, to);
+ return false; // plain rename (untracked)
+ };
+
+ test('renames the skill dir', async () => {
+ applySkillWrite({ skillsRoot, name: 'old', body: 'a', frontmatter: fm('old') });
+ const result = await applySkillMove({
+ skillsRoot,
+ fromName: 'old',
+ toName: 'new',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(true);
+ expect(existsSync(join(skillsRoot, 'old'))).toBe(false);
+ expect(existsSync(join(skillsRoot, 'new', 'SKILL.md'))).toBe(true);
+ });
+
+ test('refuses a collision with an existing destination', async () => {
+ applySkillWrite({ skillsRoot, name: 'a', body: 'x', frontmatter: fm('a') });
+ applySkillWrite({ skillsRoot, name: 'b', body: 'y', frontmatter: fm('b') });
+ const result = await applySkillMove({
+ skillsRoot,
+ fromName: 'a',
+ toName: 'b',
+ relocate: fsRelocate,
+ });
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.code).toBe('SKILL_EXISTS');
+ });
+
+ test('refuses a missing source and a no-op self-move', async () => {
+ const missing = await applySkillMove({
+ skillsRoot,
+ fromName: 'ghost',
+ toName: 'x',
+ relocate: fsRelocate,
+ });
+ expect(missing.ok).toBe(false);
+ if (!missing.ok) expect(missing.error.code).toBe('SKILL_NOT_FOUND');
+
+ applySkillWrite({ skillsRoot, name: 'same', body: 'x', frontmatter: fm('same') });
+ const noop = await applySkillMove({
+ skillsRoot,
+ fromName: 'same',
+ toName: 'same',
+ relocate: fsRelocate,
+ });
+ expect(noop.ok).toBe(false);
+ if (!noop.ok) expect(noop.error.code).toBe('NOOP');
+ });
+});
+
+describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', () => {
+ const seedSkill = (name = 'trip-log') =>
+ applySkillWrite({ skillsRoot, name, body: '# Steps', frontmatter: fm(name) });
+
+ test('writes a reference + a script into an existing skill (atomic, created flag)', () => {
+ seedSkill();
+ const ref = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/gear.md',
+ content: '# Gear\n\nRods.',
+ });
+ expect(ref.ok).toBe(true);
+ if (ref.ok) {
+ expect(ref.created).toBe(true);
+ expect(ref.path).toBe('trip-log/references/gear.md');
+ }
+ expect(readFileSync(join(skillsRoot, 'trip-log', 'references', 'gear.md'), 'utf-8')).toContain(
+ '# Gear',
+ );
+
+ const script = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'scripts/run.sh',
+ content: '#!/usr/bin/env bash\necho hi\n',
+ });
+ expect(script.ok).toBe(true);
+ if (script.ok) expect(script.created).toBe(true);
+
+ const again = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/gear.md',
+ content: '# Gear v2',
+ });
+ expect(again.ok).toBe(true);
+ if (again.ok) expect(again.created).toBe(false);
+ });
+
+ test('refuses a write into a skill that does not exist', () => {
+ const r = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'ghost',
+ relPath: 'references/x.md',
+ content: 'x',
+ });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error.code).toBe('SKILL_NOT_FOUND');
+ });
+
+ test('rejects an escaping path and an over-cap file', () => {
+ seedSkill();
+ const escaping = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/../../escape.md',
+ content: 'x',
+ });
+ expect(escaping.ok).toBe(false);
+ if (!escaping.ok) expect(escaping.error.code).toBe('BAD_FILE_PATH');
+
+ const tooLarge = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/big.md',
+ content: 'a'.repeat(256 * 1024 + 1),
+ });
+ expect(tooLarge.ok).toBe(false);
+ if (!tooLarge.ok) expect(tooLarge.error.code).toBe('FILE_TOO_LARGE');
+ });
+
+ test('enforces the per-skill file-count cap', () => {
+ seedSkill();
+ for (let i = 0; i < 50; i++) {
+ const r = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: `references/r${i}.md`,
+ content: `# ${i}`,
+ });
+ expect(r.ok).toBe(true);
+ }
+ const overflow = applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/one-too-many.md',
+ content: 'x',
+ });
+ expect(overflow.ok).toBe(false);
+ if (!overflow.ok) expect(overflow.error.code).toBe('TOO_MANY_FILES');
+ });
+
+ test('deletes a bundle file and prunes the emptied dir; no-op reports existed:false', () => {
+ seedSkill();
+ applySkillBundleFileWrite({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/gear.md',
+ content: 'x',
+ });
+ const del = applySkillBundleFileDelete({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/gear.md',
+ });
+ expect(del.ok).toBe(true);
+ if (del.ok) expect(del.existed).toBe(true);
+ expect(existsSync(join(skillsRoot, 'trip-log', 'references'))).toBe(false);
+ expect(existsSync(join(skillsRoot, 'trip-log', 'SKILL.md'))).toBe(true);
+
+ const noop = applySkillBundleFileDelete({
+ skillsRoot,
+ name: 'trip-log',
+ relPath: 'references/gear.md',
+ });
+ expect(noop.ok).toBe(true);
+ if (noop.ok) expect(noop.existed).toBe(false);
+ });
+});
diff --git a/packages/server/src/content/skills-write.ts b/packages/server/src/content/skills-write.ts
new file mode 100644
index 000000000..7735a4fb6
--- /dev/null
+++ b/packages/server/src/content/skills-write.ts
@@ -0,0 +1,561 @@
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ renameSync,
+ rmdirSync,
+ rmSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { isAbsolute, join, normalize, sep } from 'node:path';
+import {
+ containsXmlTag,
+ SKILL_NAME_REGEX,
+ type SkillFrontmatter,
+} from '@inkeep/open-knowledge-core';
+import { stringify as stringifyYaml } from 'yaml';
+
+const NAME_MAX = 64;
+const DESCRIPTION_MAX = 1024;
+const RESERVED_NAME_WORDS = ['anthropic', 'claude'];
+const BODY_SOFT_MAX_LINES = 500;
+const SKILL_FILE = 'SKILL.md';
+
+type SkillWriteResult =
+ | { ok: true; path: string; created: boolean; warnings: string[] }
+ | { ok: false; error: { code: string; message: string } };
+
+export type SkillContentResult =
+ | { ok: true; content: string; warnings: string[] }
+ | { ok: false; error: { code: string; message: string } };
+
+type SkillDeleteResult =
+ | { ok: true; path: string; existed: boolean }
+ | { ok: false; error: { code: string; message: string } };
+
+type SkillMoveResult =
+ | { ok: true; fromPath: string; toPath: string; committed: boolean }
+ | { ok: false; error: { code: string; message: string } };
+
+interface WriteSkillInput {
+ skillsRoot: string;
+ name: string;
+ body: string;
+ frontmatter: SkillFrontmatter;
+}
+
+interface DeleteSkillInput {
+ skillsRoot: string;
+ name: string;
+}
+
+interface MoveSkillInput {
+ skillsRoot: string;
+ fromName: string;
+ toName: string;
+ relocate: (fromAbs: string, toAbs: string) => Promise<boolean>;
+}
+
+export function composeSkillContent(input: {
+ name: string;
+ body: string;
+ frontmatter: SkillFrontmatter;
+}): SkillContentResult {
+ const nameCheck = validateName(input.name);
+ if (!nameCheck.ok) return { ok: false, error: nameCheck.error };
+
+ const fmCheck = validateFrontmatter(input.frontmatter, input.name);
+ if (!fmCheck.ok) return { ok: false, error: fmCheck.error };
+
+ const fmYaml = serializeFrontmatter(input.frontmatter);
+ const content = `---\n${fmYaml}---\n${input.body}`;
+
+ const warnings: string[] = [];
+ const lineCount = input.body.split('\n').length;
+ if (lineCount > BODY_SOFT_MAX_LINES) {
+ warnings.push(
+ `SKILL.md body is ${lineCount} lines — keep it under ${BODY_SOFT_MAX_LINES} for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`,
+ );
+ }
+ return { ok: true, content, warnings };
+}
+
+export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {
+ const base = validateBase(input.skillsRoot);
+ if (!base.ok) return { ok: false, error: base.error };
+
+ const composed = composeSkillContent({
+ name: input.name,
+ body: input.body,
+ frontmatter: input.frontmatter,
+ });
+ if (!composed.ok) return { ok: false, error: composed.error };
+ const { content, warnings } = composed;
+
+ const { skillDir, filePath } = skillPaths(input.skillsRoot, input.name);
+
+ try {
+ mkdirSync(skillDir, { recursive: true });
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'WRITE_ERROR',
+ message: `Failed to create skill directory at ${relPathOf(input.skillsRoot, skillDir)}: ${(err as Error).message}`,
+ },
+ };
+ }
+
+ const created = !existsSync(filePath);
+
+ const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
+ try {
+ writeFileSync(tmpPath, content, 'utf-8');
+ renameSync(tmpPath, filePath);
+ } catch (err) {
+ try {
+ unlinkSync(tmpPath);
+ } catch {}
+ return {
+ ok: false,
+ error: {
+ code: 'WRITE_ERROR',
+ message: `Failed to write skill at ${relPathOf(input.skillsRoot, filePath)}: ${(err as Error).message}`,
+ },
+ };
+ }
+
+ return { ok: true, path: relPathOf(input.skillsRoot, filePath), created, warnings };
+}
+
+/** Per-file byte cap for a skill bundle file. Single source — the API handler
+ * (`/api/skill-file` PUT) imports this rather than re-stating the literal. */
+export const BUNDLE_FILE_MAX_BYTES = 256 * 1024;
+/** Max bundle files (excl. SKILL.md) a single skill may hold. Single source —
+ * enforced by BOTH the fs-direct write (below) and the API handler's content
+ * branch (project `.md` references route through the CRDT content path, not
+ * this writer, so they import this + `countBundleFiles` to enforce the same
+ * cap). */
+export const BUNDLE_MAX_FILES = 50;
+
+interface BundleFileInput {
+ skillsRoot: string;
+ name: string;
+ relPath: string;
+}
+
+type BundleFileWriteResult =
+ | { ok: true; path: string; created: boolean }
+ | { ok: false; error: { code: string; message: string } };
+
+type BundleFileDeleteResult =
+ | { ok: true; path: string; existed: boolean }
+ | { ok: false; error: { code: string; message: string } };
+
+function resolveBundleFileAbs(
+ skillDir: string,
+ relPath: string,
+): { ok: true; abs: string } | { ok: false; error: { code: string; message: string } } {
+ if (typeof relPath !== 'string' || relPath.length === 0 || relPath.includes('\x00')) {
+ return { ok: false, error: { code: 'BAD_FILE_PATH', message: 'Invalid skill file path.' } };
+ }
+ const segments = relPath
+ .replace(/\\/g, '/')
+ .split('/')
+ .filter((s) => s !== '' && s !== '.');
+ if (segments.length < 2 || 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') {
+ return {
+ ok: false,
+ error: {
+ code: 'BAD_FILE_PATH',
+ message: `Skill file must be under references/ or scripts/: ${relPath}`,
+ },
+ };
+ }
+ const abs = join(skillDir, ...segments);
+ if (abs !== skillDir && !abs.startsWith(skillDir + sep)) {
+ return {
+ ok: false,
+ error: { code: 'BAD_FILE_PATH', message: `Skill file escapes the skill dir: ${relPath}` },
+ };
+ }
+ return { ok: true, abs };
+}
+
+export function countBundleFiles(skillDir: string): number {
+ let count = 0;
+ const walk = (dir: string): void => {
+ let names: string[];
+ try {
+ names = readdirSync(dir);
+ } catch {
+ return;
+ }
+ for (const entryName of names) {
+ const abs = join(dir, entryName);
+ let isDir: boolean;
+ try {
+ isDir = statSync(abs).isDirectory();
+ } catch {
+ continue;
+ }
+ if (isDir) walk(abs);
+ else if (!(dir === skillDir && entryName === SKILL_FILE)) count++;
+ }
+ };
+ walk(skillDir);
+ return count;
+}
+
+export function applySkillBundleFileWrite(
+ input: BundleFileInput & { content: string },
+): BundleFileWriteResult {
+ 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, filePath: skillMd } = skillPaths(input.skillsRoot, input.name);
+ if (!existsSync(skillMd)) {
+ return {
+ ok: false,
+ error: {
+ code: 'SKILL_NOT_FOUND',
+ message: `No skill "${input.name}" — create it (write its SKILL.md) before adding bundle files.`,
+ },
+ };
+ }
+ const resolved = resolveBundleFileAbs(skillDir, input.relPath);
+ 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) {
+ 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}.`,
+ },
+ };
+ }
+
+ const created = !existsSync(abs);
+ if (created && countBundleFiles(skillDir) >= BUNDLE_MAX_FILES) {
+ 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.`,
+ },
+ };
+ }
+
+ try {
+ mkdirSync(join(abs, '..'), { recursive: true });
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'WRITE_ERROR',
+ message: `Failed to create directory for ${input.relPath}: ${(err as Error).message}`,
+ },
+ };
+ }
+ const tmpPath = `${abs}.tmp.${process.pid}.${Date.now()}`;
+ try {
+ writeFileSync(tmpPath, input.content, 'utf-8');
+ renameSync(tmpPath, abs);
+ } catch (err) {
+ try {
+ unlinkSync(tmpPath);
+ } catch {}
+ return {
+ ok: false,
+ error: {
+ code: 'WRITE_ERROR',
+ message: `Failed to write skill file ${input.relPath}: ${(err as Error).message}`,
+ },
+ };
+ }
+ return {
+ ok: true,
+ path: relPathOf(input.skillsRoot, abs),
+ created,
+ };
+}
+
+export function applySkillBundleFileDelete(input: BundleFileInput): BundleFileDeleteResult {
+ 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 resolved = resolveBundleFileAbs(skillDir, input.relPath);
+ if (!resolved.ok) return { ok: false, error: resolved.error };
+ const { abs } = resolved;
+
+ const existed = existsSync(abs);
+ if (existed) {
+ try {
+ unlinkSync(abs);
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'UNLINK_FAILED',
+ message: `Failed to delete skill file ${input.relPath}: ${(err as Error).message}`,
+ },
+ };
+ }
+ const parent = join(abs, '..');
+ if (parent !== skillDir && isEmpty(parent)) {
+ try {
+ rmdirSync(parent);
+ } catch {}
+ }
+ }
+ return { ok: true, path: relPathOf(input.skillsRoot, abs), existed };
+}
+
+export function applySkillDelete(input: DeleteSkillInput): SkillDeleteResult {
+ 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 { skillsRoot } = base;
+ const { skillDir } = skillPaths(input.skillsRoot, input.name);
+
+ const existed = existsSync(skillDir);
+ if (existed) {
+ try {
+ rmSync(skillDir, { recursive: true, force: true });
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'UNLINK_FAILED',
+ message: `Failed to delete skill at ${relPathOf(input.skillsRoot, skillDir)}: ${(err as Error).message}`,
+ },
+ };
+ }
+ }
+ cleanEmptyDirs(skillsRoot);
+
+ return { ok: true, path: relPathOf(input.skillsRoot, skillDir), existed };
+}
+
+export async function applySkillMove(input: MoveSkillInput): Promise<SkillMoveResult> {
+ const base = validateBase(input.skillsRoot);
+ if (!base.ok) return { ok: false, error: base.error };
+ const fromCheck = validateName(input.fromName);
+ if (!fromCheck.ok) return { ok: false, error: fromCheck.error };
+ const toCheck = validateName(input.toName);
+ if (!toCheck.ok) return { ok: false, error: toCheck.error };
+
+ const from = skillPaths(input.skillsRoot, input.fromName);
+ const to = skillPaths(input.skillsRoot, input.toName);
+
+ if (from.skillDir === to.skillDir) {
+ return {
+ ok: false,
+ error: { code: 'NOOP', message: 'Source and destination are the same skill.' },
+ };
+ }
+ if (!existsSync(from.skillDir)) {
+ return {
+ ok: false,
+ error: {
+ code: 'SKILL_NOT_FOUND',
+ message: `No skill at ${relPathOf(input.skillsRoot, from.skillDir)}.`,
+ },
+ };
+ }
+ if (existsSync(to.skillDir)) {
+ return {
+ ok: false,
+ error: {
+ code: 'SKILL_EXISTS',
+ message: `A skill already exists at ${relPathOf(input.skillsRoot, to.skillDir)}.`,
+ },
+ };
+ }
+
+ let committed: boolean;
+ try {
+ committed = await input.relocate(from.skillDir, to.skillDir);
+ } catch (err) {
+ return {
+ ok: false,
+ error: { code: 'MOVE_FAILED', message: `Failed to move skill: ${(err as Error).message}` },
+ };
+ }
+
+ return {
+ ok: true,
+ fromPath: relPathOf(input.skillsRoot, from.skillDir),
+ toPath: relPathOf(input.skillsRoot, to.skillDir),
+ committed,
+ };
+}
+
+function validateBase(
+ skillsRoot: string,
+): { ok: true; skillsRoot: string } | { ok: false; error: { code: string; message: string } } {
+ if (!isAbsolute(skillsRoot)) {
+ return {
+ ok: false,
+ error: { code: 'BAD_SKILLS_ROOT', message: 'skillsRoot must be absolute' },
+ };
+ }
+ return { ok: true, skillsRoot };
+}
+
+function validateName(
+ name: string,
+): { ok: true } | { ok: false; error: { code: string; message: string } } {
+ if (typeof name !== 'string' || name.length === 0) {
+ return { ok: false, error: { code: 'BAD_NAME', message: 'Skill name is required.' } };
+ }
+ if (name.length > NAME_MAX) {
+ return {
+ ok: false,
+ error: { code: 'BAD_NAME', message: `Skill name must be ≤${NAME_MAX} characters.` },
+ };
+ }
+ if (!SKILL_NAME_REGEX.test(name)) {
+ return {
+ ok: false,
+ error: {
+ code: 'BAD_NAME',
+ message: `Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(name)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`,
+ },
+ };
+ }
+ if (RESERVED_NAME_WORDS.some((w) => name.includes(w))) {
+ return {
+ ok: false,
+ error: {
+ code: 'RESERVED_NAME',
+ message: `Skill name may not contain reserved words (${RESERVED_NAME_WORDS.join(', ')}).`,
+ },
+ };
+ }
+ return { ok: true };
+}
+
+function validateFrontmatter(
+ fm: SkillFrontmatter,
+ dirName: string,
+): { ok: true } | { ok: false; error: { code: string; message: string } } {
+ if (!fm || typeof fm !== 'object') {
+ return {
+ ok: false,
+ error: {
+ code: 'BAD_FRONTMATTER',
+ message: 'Skill frontmatter (name, description) is required.',
+ },
+ };
+ }
+ if (typeof fm.name !== 'string' || fm.name.length === 0) {
+ return {
+ ok: false,
+ error: { code: 'SKILL_NAME_REQUIRED', message: 'Skill frontmatter.name is required.' },
+ };
+ }
+ if (fm.name !== dirName) {
+ return {
+ ok: false,
+ error: {
+ code: 'NAME_DIR_MISMATCH',
+ message: `Skill frontmatter.name (${JSON.stringify(fm.name)}) must equal the skill directory name (${JSON.stringify(dirName)}).`,
+ },
+ };
+ }
+ if (containsXmlTag(fm.name)) {
+ return {
+ ok: false,
+ error: {
+ code: 'XML_TAG_IN_NAME',
+ message: 'Skill frontmatter.name may not contain XML tags (`<...>`).',
+ },
+ };
+ }
+ if (typeof fm.description !== 'string' || fm.description.length === 0) {
+ 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).',
+ },
+ };
+ }
+ if (fm.description.length > DESCRIPTION_MAX) {
+ return {
+ ok: false,
+ error: {
+ code: 'DESCRIPTION_TOO_LONG',
+ message: `Skill frontmatter.description must be ≤${DESCRIPTION_MAX} characters (got ${fm.description.length}).`,
+ },
+ };
+ }
+ if (containsXmlTag(fm.description)) {
+ return {
+ ok: false,
+ error: {
+ code: 'XML_TAG_IN_DESCRIPTION',
+ message:
+ 'Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader.',
+ },
+ };
+ }
+ return { ok: true };
+}
+
+function skillPaths(skillsRoot: string, name: string): { skillDir: string; filePath: string } {
+ const skillDir = join(skillsRoot, name);
+ const filePath = join(skillDir, SKILL_FILE);
+ return { skillDir, filePath };
+}
+
+function cleanEmptyDirs(skillsRoot: string): void {
+ if (existsSync(skillsRoot) && isEmpty(skillsRoot)) {
+ try {
+ rmdirSync(skillsRoot);
+ } catch {}
+ }
+ const okDir = normalize(join(skillsRoot, '..'));
+ if (okDir.endsWith(`${sep}.ok`) && existsSync(okDir) && isEmpty(okDir)) {
+ try {
+ rmdirSync(okDir);
+ } catch {}
+ }
+}
+
+function relPathOf(base: string, abs: string): string {
+ const rel = abs.startsWith(base + sep) ? abs.slice(base.length + 1) : abs;
+ return normalize(rel).split(sep).join('/');
+}
+
+function serializeFrontmatter(fm: SkillFrontmatter): string {
+ return stringifyYaml({ name: fm.name, description: fm.description });
+}
+
+function isEmpty(absDir: string): boolean {
+ try {
+ return readdirSync(absDir).length === 0;
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/server/src/content/templates-write.ts b/packages/server/src/content/templates-write.ts
index 20d05be66..74a8f6a9b 100644
--- a/packages/server/src/content/templates-write.ts
+++ b/packages/server/src/content/templates-write.ts
@@ -12,6 +12,7 @@ import {
composeTemplateFile,
stripFrontmatter,
TEMPLATE_IDENTITY_KEY,
+ TEMPLATE_NAME_REGEX,
type TemplateIdentity,
unwrapFrontmatterFences,
} from '@inkeep/open-knowledge-core';
@@ -61,12 +62,26 @@ interface DeleteTemplateInput {
name: string;
}
-const NAME_RE = /^[A-Za-z0-9_-]+$/;
+const NAME_RE = TEMPLATE_NAME_REGEX;
-export function applyTemplateWrite(input: WriteTemplateInput): TemplateWriteResult {
- const validation = validateInputs(input.projectDir, input.folder, input.name);
- if (!validation.ok) return { ok: false, error: validation.error };
+export type TemplateContentResult =
+ | { ok: true; content: string; warnings: string[] }
+ | { ok: false; error: { code: string; message: string } };
+export function composeTemplateContent(input: {
+ name: string;
+ body: string;
+ frontmatter: TemplateFrontmatter;
+}): TemplateContentResult {
+ if (!NAME_RE.test(input.name)) {
+ return {
+ ok: false,
+ error: {
+ code: 'BAD_NAME',
+ message: `Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(input.name)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`,
+ },
+ };
+ }
const titleCheck = validateTitle(input.frontmatter.title);
if (!titleCheck.ok) return { ok: false, error: titleCheck.error };
@@ -76,12 +91,6 @@ export function applyTemplateWrite(input: WriteTemplateInput): TemplateWriteResu
const reservedCheck = validateNoReservedDocKey(input.body);
if (!reservedCheck.ok) return { ok: false, error: reservedCheck.error };
- const { templatesDir, filePath } = templatePaths(
- input.projectDir,
- validation.folderRel,
- input.name,
- );
-
const identity: TemplateIdentity = {};
if (input.frontmatter.title !== undefined) identity.title = input.frontmatter.title;
if (input.frontmatter.description !== undefined) {
@@ -92,6 +101,37 @@ export function applyTemplateWrite(input: WriteTemplateInput): TemplateWriteResu
}
const content = composeTemplateFile(identity, input.body);
+ const warnings: string[] = [];
+ if (
+ input.frontmatter.description === undefined ||
+ typeof input.frontmatter.description !== 'string' ||
+ input.frontmatter.description.length === 0
+ ) {
+ warnings.push(
+ 'Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required.',
+ );
+ }
+ return { ok: true, content, warnings };
+}
+
+export function applyTemplateWrite(input: WriteTemplateInput): TemplateWriteResult {
+ const validation = validateInputs(input.projectDir, input.folder, input.name);
+ if (!validation.ok) return { ok: false, error: validation.error };
+
+ const composed = composeTemplateContent({
+ name: input.name,
+ body: input.body,
+ frontmatter: input.frontmatter,
+ });
+ if (!composed.ok) return { ok: false, error: composed.error };
+ const { content, warnings } = composed;
+
+ const { templatesDir, filePath } = templatePaths(
+ input.projectDir,
+ validation.folderRel,
+ input.name,
+ );
+
try {
mkdirSync(templatesDir, { recursive: true });
} catch (err) {
@@ -123,17 +163,6 @@ export function applyTemplateWrite(input: WriteTemplateInput): TemplateWriteResu
};
}
- const warnings: string[] = [];
- if (
- input.frontmatter.description === undefined ||
- typeof input.frontmatter.description !== 'string' ||
- input.frontmatter.description.length === 0
- ) {
- warnings.push(
- 'Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required.',
- );
- }
-
return {
ok: true,
path: relPathOf(input.projectDir, filePath),
diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.ts
index 4865a846a..6b85dbafa 100644
--- a/packages/server/src/file-watcher.ts
+++ b/packages/server/src/file-watcher.ts
@@ -3,7 +3,7 @@ import { type Dirent, lstatSync, readdirSync, realpathSync, type Stats, statSync
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';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { isConfigDoc, isReservedForUserTree, isSystemDoc } from './cc1-broadcast.ts';
import type { ContentFilter } from './content-filter.ts';
import {
forgetDocExtension,
@@ -701,7 +701,7 @@ export function updateFileIndex(event: DiskEvent, fileIndex: Map<string, FileInd
return;
}
const docName = event.kind === 'rename' ? event.newDocName : event.docName;
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isReservedForUserTree(docName)) return;
switch (event.kind) {
case 'create':
case 'update':
diff --git a/packages/server/src/fs-traced.ts b/packages/server/src/fs-traced.ts
index e8feebf29..1774f127b 100644
--- a/packages/server/src/fs-traced.ts
+++ b/packages/server/src/fs-traced.ts
@@ -7,11 +7,13 @@ import {
renameSync,
rmdirSync,
rmSync,
+ symlinkSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
import { mkdir, rename, writeFile } from 'node:fs/promises';
import { basename, sep } from 'node:path';
+import type { AtomicWriteFsAdapter } from '@inkeep/open-knowledge-core/server';
import type { Attributes } from '@opentelemetry/api';
import { withSpan, withSpanSync } from './telemetry.ts';
@@ -169,6 +171,24 @@ export function tracedLinkSync(existingPath: string, newPath: string): void {
);
}
+export function tracedSymlinkSync(
+ target: string,
+ linkPath: string,
+ type?: 'dir' | 'file' | 'junction',
+): void {
+ withSpanSync(
+ 'fs.symlinkSync',
+ {
+ attributes: buildAttrs('symlinkSync', linkPath, {
+ 'fs.source_path': normalizeFsPath(target),
+ }),
+ },
+ () => {
+ symlinkSync(target, linkPath, type);
+ },
+ );
+}
+
export function tracedRmSync(path: string, options?: RmOptions): void {
withSpanSync('fs.rmSync', { attributes: buildAttrs('rmSync', path) }, () => {
rmSync(path, options);
@@ -180,3 +200,8 @@ export function tracedRmdirSync(path: string): void {
rmdirSync(path);
});
}
+
+export const tracedAtomicFs: AtomicWriteFsAdapter = {
+ writeFile: (path, content, opts) => tracedWriteFile(path, content, opts),
+ rename: (from, to) => tracedRename(from, to),
+};
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 42a52f2e9..8e9e4d62c 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -75,6 +75,9 @@ export {
CC1_CONTRACT_VERSION,
CC1Broadcaster,
isConfigDoc,
+ isLinkIndexExcludedDoc,
+ isManagedArtifactDoc,
+ isReservedForUserTree,
isSystemDoc,
SYSTEM_DOC_NAME,
} from './cc1-broadcast.ts';
@@ -421,6 +424,13 @@ export {
SingleFileNotMarkdownError,
type SingleFileOpenPlan,
} from './single-file-open.ts';
+export {
+ BUNDLE_IDS,
+ BUNDLE_SCOPE,
+ BUNDLE_SKILL_NAME,
+ bundleSkillMdPath,
+ USER_GLOBAL_BUNDLE_IDS,
+} from './skill-bundles.ts';
export {
type BuildAndOpenSkillOptions,
type BuildAndOpenSkillResult,
@@ -439,6 +449,13 @@ export {
type SkillInstallEventOutcome,
type SkillInstallEventSurface,
} from './skill-install-events.ts';
+export {
+ isProjectSkillManaged,
+ readSkillManagement,
+ type SkillManagement,
+ skillManagementPath,
+ writeSkillManagement,
+} from './skill-management.ts';
export {
readAllTargets,
readServerPackageVersion,
diff --git a/packages/server/src/installed-skills-marker.test.ts b/packages/server/src/installed-skills-marker.test.ts
new file mode 100644
index 000000000..e22ce2cab
--- /dev/null
+++ b/packages/server/src/installed-skills-marker.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ installedSkillsPath,
+ readInstalledSkills,
+ recordSkillInstall,
+ removeSkillInstall,
+} from './installed-skills-marker.ts';
+
+let projectDir: string;
+
+const entry = (hosts: string[]) => ({
+ hosts,
+ contentHash: 'abc123',
+ scope: 'project' as const,
+ scripts: false,
+ installedAt: '2026-06-05T00:00:00.000Z',
+});
+
+beforeEach(() => {
+ projectDir = mkdtempSync(join(tmpdir(), 'ok-marker-'));
+});
+afterEach(() => {
+ rmSync(projectDir, { recursive: true, force: true });
+});
+
+describe('installed-skills marker', () => {
+ test('absent marker reads as empty (fail-soft)', () => {
+ const state = readInstalledSkills(projectDir);
+ expect(state.schema).toBe(1);
+ expect(state.skills).toEqual({});
+ });
+
+ test('record then read round-trips an entry under .ok/local/', async () => {
+ await recordSkillInstall(projectDir, 'trip-log', entry(['claude', 'cursor']));
+ expect(installedSkillsPath(projectDir)).toContain('/.ok/local/installed-skills.json');
+ const state = readInstalledSkills(projectDir);
+ expect(state.skills['trip-log']?.hosts).toEqual(['claude', 'cursor']);
+ expect(state.skills['trip-log']?.scope).toBe('project');
+ });
+
+ test('record is additive across skills and overwrites same name', async () => {
+ await recordSkillInstall(projectDir, 'a', entry(['claude']));
+ await recordSkillInstall(projectDir, 'b', entry(['cursor']));
+ await recordSkillInstall(projectDir, 'a', entry(['claude', 'codex']));
+ const state = readInstalledSkills(projectDir);
+ expect(Object.keys(state.skills).sort()).toEqual(['a', 'b']);
+ expect(state.skills.a?.hosts).toEqual(['claude', 'codex']);
+ });
+
+ test('remove returns the removed entry and drops it; no-op returns null', async () => {
+ await recordSkillInstall(projectDir, 'gone', entry(['claude']));
+ const removed = await removeSkillInstall(projectDir, 'gone');
+ expect(removed?.hosts).toEqual(['claude']);
+ expect(readInstalledSkills(projectDir).skills.gone).toBeUndefined();
+
+ const noop = await removeSkillInstall(projectDir, 'never');
+ expect(noop).toBeNull();
+ });
+
+ test('corrupt marker JSON reads as empty (fail-soft), never throws', async () => {
+ await recordSkillInstall(projectDir, 'seed', entry(['claude']));
+ writeFileSync(installedSkillsPath(projectDir), '{ not valid json', 'utf-8');
+ const state = readInstalledSkills(projectDir);
+ expect(state.skills).toEqual({});
+ });
+});
diff --git a/packages/server/src/installed-skills-marker.ts b/packages/server/src/installed-skills-marker.ts
new file mode 100644
index 000000000..90776290e
--- /dev/null
+++ b/packages/server/src/installed-skills-marker.ts
@@ -0,0 +1,95 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import {
+ emptyInstalledSkills,
+ INSTALLED_SKILLS_REL,
+ type InstalledSkillEntry,
+ type InstalledSkills,
+ InstalledSkillsSchema,
+ parseInstalledSkills,
+} from '@inkeep/open-knowledge-core';
+import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
+import { tracedMkdir, tracedRename, tracedWriteFile } from './fs-traced.ts';
+import { getLogger } from './logger.ts';
+
+const logger = getLogger('installed-skills-marker');
+
+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),
+};
+
+export function installedSkillsPath(projectDir: string): string {
+ return join(projectDir, ...INSTALLED_SKILLS_REL);
+}
+
+const markerWriteChains = new Map<string, Promise<unknown>>();
+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);
+ markerWriteChains.set(
+ key,
+ run.then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+ return run;
+}
+
+export function readInstalledSkills(projectDir: string): InstalledSkills {
+ const path = installedSkillsPath(projectDir);
+ if (!existsSync(path)) return emptyInstalledSkills();
+ try {
+ return parseInstalledSkills(readFileSync(path, 'utf-8')) ?? emptyInstalledSkills();
+ } catch (err) {
+ logger.warn({ err, path }, 'installed-skills marker unreadable');
+ return emptyInstalledSkills();
+ }
+}
+
+async function writeInstalledSkills(projectDir: string, state: InstalledSkills): Promise<void> {
+ const parsed = InstalledSkillsSchema.safeParse(state);
+ if (!parsed.success) {
+ throw new Error(
+ `Refusing to write invalid installed-skills marker: ${parsed.error.issues
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
+ .join('; ')}`,
+ );
+ }
+ const path = installedSkillsPath(projectDir);
+ await tracedMkdir(dirname(path), { recursive: true });
+ await atomicWriteFile(path, `${JSON.stringify(parsed.data, null, 2)}\n`, {
+ fs: TRACED_FS_ADAPTER,
+ });
+}
+
+export async function recordSkillInstall(
+ projectDir: string,
+ name: string,
+ entry: InstalledSkillEntry,
+): Promise<void> {
+ return withMarkerLock(projectDir, async () => {
+ const state = readInstalledSkills(projectDir);
+ await writeInstalledSkills(projectDir, {
+ ...state,
+ skills: { ...state.skills, [name]: entry },
+ });
+ });
+}
+
+export async function removeSkillInstall(
+ projectDir: string,
+ name: string,
+): Promise<InstalledSkillEntry | null> {
+ return withMarkerLock(projectDir, async () => {
+ const state = readInstalledSkills(projectDir);
+ const removed = state.skills[name] ?? null;
+ if (removed === null) return null;
+ const { [name]: _dropped, ...rest } = state.skills;
+ await writeInstalledSkills(projectDir, { ...state, skills: rest });
+ return removed;
+ });
+}
diff --git a/packages/server/src/live-derived-index.ts b/packages/server/src/live-derived-index.ts
index 169d40517..f64ad912a 100644
--- a/packages/server/src/live-derived-index.ts
+++ b/packages/server/src/live-derived-index.ts
@@ -1,6 +1,6 @@
import type { Document, Extension } from '@hocuspocus/server';
import type { BacklinkIndex } from './backlink-index.ts';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';
import type { TagIndex } from './tag-index.ts';
export const LIVE_DERIVED_INDEX_DEBOUNCE_MS = 100;
@@ -69,7 +69,7 @@ export function createLiveDerivedIndexExtension(options: LiveDerivedIndexOptions
return {
async onChange({ documentName, document, transactionOrigin }) {
- if (isSystemDoc(documentName) || isConfigDoc(documentName)) return;
+ if (isLinkIndexExcludedDoc(documentName)) return;
if (
isLocalOriginLike(transactionOrigin) &&
diff --git a/packages/server/src/managed-artifact-persistence.test.ts b/packages/server/src/managed-artifact-persistence.test.ts
new file mode 100644
index 000000000..e6053b530
--- /dev/null
+++ b/packages/server/src/managed-artifact-persistence.test.ts
@@ -0,0 +1,383 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, 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 * as Y from 'yjs';
+import { FILE_WATCHER_ORIGIN } from './external-change.ts';
+import {
+ applyExternalManagedArtifactChange,
+ loadManagedArtifactDoc,
+ type ManagedArtifactCtx,
+ managedArtifactAbsPath,
+ managedArtifactContributorAttribution,
+ managedArtifactDocNameForPath,
+ managedArtifactSkillsRoots,
+ managedArtifactTimelinePaths,
+ storeManagedArtifactDoc,
+} from './managed-artifact-persistence.ts';
+
+let projectDir: string;
+let home: string;
+let reconciled: Map<string, string>;
+
+function makeCtx(): ManagedArtifactCtx {
+ return {
+ projectDir,
+ homedirOverride: home,
+ lkgCache: new Map<string, string>(),
+ setReconciledBase: (n, c) => reconciled.set(n, c),
+ getReconciledBase: (n) => reconciled.get(n),
+ };
+}
+
+beforeEach(() => {
+ projectDir = mkdtempSync(join(tmpdir(), 'ok-ma-proj-'));
+ home = mkdtempSync(join(tmpdir(), 'ok-ma-home-'));
+ reconciled = new Map();
+});
+afterEach(() => {
+ rmSync(projectDir, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('managedArtifactAbsPath', () => {
+ test('project + global scope resolve under the right .ok/skills root', () => {
+ const ctx = makeCtx();
+ expect(managedArtifactAbsPath('__skill__/project/my-skill', ctx)).toBe(
+ resolve(projectDir, '.ok', 'skills', 'my-skill', 'SKILL.md'),
+ );
+ expect(managedArtifactAbsPath('__skill__/global/my-skill', ctx)).toBe(
+ resolve(home, '.ok', 'skills', 'my-skill', 'SKILL.md'),
+ );
+ });
+
+ test('rejects path-escape + malformed names (security)', () => {
+ const ctx = makeCtx();
+ 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/', // empty name
+ '__skill__/bogus/foo', // bad scope
+ 'notes/foo', // not managed-artifact
+ ]) {
+ expect(() => managedArtifactAbsPath(bad, ctx)).toThrow();
+ }
+ });
+
+ test('templates resolve folder-addressed under <folder>/.ok/templates/<name>.md', () => {
+ const ctx = makeCtx();
+ expect(managedArtifactAbsPath('__template__/daily-note', ctx)).toBe(
+ resolve(projectDir, '.ok', 'templates', 'daily-note.md'),
+ );
+ expect(managedArtifactAbsPath('__template__/notes/sub/meeting', ctx)).toBe(
+ resolve(projectDir, 'notes', 'sub', '.ok', 'templates', 'meeting.md'),
+ );
+ });
+
+ test('rejects template path-escape + malformed names (security)', () => {
+ const ctx = makeCtx();
+ for (const bad of [
+ '__template__/', // empty
+ '__template__/../evil', // folder escape
+ '__template__/notes/../../etc/passwd',
+ '__template__/notes/bad.name', // dot in name
+ '__template__/notes/bad name', // space in name
+ ]) {
+ expect(() => managedArtifactAbsPath(bad, ctx)).toThrow();
+ }
+ });
+});
+
+describe('store/load round-trip', () => {
+ const SRC = '---\nname: demo\ndescription: a demo skill\n---\n\n# Demo\n\nBody line.\n';
+ const docName = '__skill__/global/demo';
+
+ test('store serializes Y.Text("source") verbatim to .ok/skills/<n>/SKILL.md', async () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');
+ const outcome = await storeManagedArtifactDoc(doc, docName, 'agent', ctx);
+ expect(outcome).toBe('persisted');
+ const path = managedArtifactAbsPath(docName, ctx);
+ expect(existsSync(path)).toBe(true);
+ expect(readFileSync(path, 'utf-8')).toBe(SRC); // byte-identical (precedent #38)
+ });
+
+ test('verbatim fidelity: awkward-but-valid markdown survives byte-for-byte', async () => {
+ const ctx = makeCtx();
+ const awkward =
+ '---\nname: demo\ndescription: d\n---\n## Heading\nNo blank line after heading\n\n* weird list spacing\n>quote no space\n';
+ const doc = new Y.Doc();
+ doc.transact(() => doc.getText('source').insert(0, awkward), 'agent');
+ await storeManagedArtifactDoc(doc, docName, 'agent', ctx);
+ expect(readFileSync(managedArtifactAbsPath(docName, ctx), 'utf-8')).toBe(awkward);
+ });
+
+ test('store is a no-op for the load/reconcile origin', async () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');
+ expect(await storeManagedArtifactDoc(doc, docName, FILE_WATCHER_ORIGIN, ctx)).toBe('no-op');
+ expect(existsSync(managedArtifactAbsPath(docName, ctx))).toBe(false);
+ });
+
+ test('project-skill synthetic doc is INERT in load + store (double-doc guard)', async () => {
+ const ctx = makeCtx();
+ const projectDocName = '__skill__/project/demo';
+ const projectPath = managedArtifactAbsPath(projectDocName, ctx);
+
+ const doc = new Y.Doc();
+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');
+ expect(await storeManagedArtifactDoc(doc, projectDocName, 'agent', ctx)).toBe('no-op');
+ expect(existsSync(projectPath)).toBe(false);
+
+ mkdirSync(resolve(projectPath, '..'), { recursive: true });
+ writeFileSync(projectPath, SRC, 'utf-8');
+ const fresh = new Y.Doc();
+ loadManagedArtifactDoc(fresh, projectDocName, ctx);
+ expect(fresh.getText('source').toString()).toBe('');
+ expect(fresh.getXmlFragment('default').length).toBe(0);
+ });
+
+ test('store is a no-op when content equals LKG', async () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');
+ expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('persisted');
+ expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('no-op');
+ });
+
+ test('load seeds Y.Text + XmlFragment from disk (paired-write)', () => {
+ const ctx = makeCtx();
+ const path = managedArtifactAbsPath(docName, ctx);
+ mkdirSync(resolve(path, '..'), { recursive: true });
+ writeFileSync(path, SRC, 'utf-8');
+ const doc = new Y.Doc();
+ loadManagedArtifactDoc(doc, docName, ctx);
+ expect(doc.getText('source').toString()).toBe(SRC);
+ expect(doc.getXmlFragment('default').length).toBeGreaterThan(0);
+ expect(reconciled.get(docName)).toBe(SRC);
+ });
+
+ test('load is lazy — a missing file seeds nothing (no auto-create)', () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ loadManagedArtifactDoc(doc, docName, ctx);
+ expect(doc.getText('source').length).toBe(0);
+ expect(existsSync(managedArtifactAbsPath(docName, ctx))).toBe(false);
+ });
+
+ test('load mints a fresh lineage epoch on each seed-from-disk', () => {
+ const path = managedArtifactAbsPath(docName, makeCtx());
+ mkdirSync(resolve(path, '..'), { recursive: true });
+ writeFileSync(path, SRC, 'utf-8');
+
+ const docA = new Y.Doc();
+ loadManagedArtifactDoc(docA, docName, makeCtx());
+ const epochA = docA.getMap('lifecycle').get(LINEAGE_EPOCH_KEY);
+ expect(typeof epochA).toBe('string');
+ expect((epochA as string).length).toBeGreaterThan(0);
+
+ const docB = new Y.Doc();
+ loadManagedArtifactDoc(docB, docName, makeCtx());
+ expect(docB.getMap('lifecycle').get(LINEAGE_EPOCH_KEY)).not.toBe(epochA);
+ });
+
+ test('project-skill synthetic doc mints NO epoch (guard early-returns before the seed)', () => {
+ const ctx = makeCtx();
+ const projectDocName = '__skill__/project/demo';
+ const projectPath = managedArtifactAbsPath(projectDocName, ctx);
+ mkdirSync(resolve(projectPath, '..'), { recursive: true });
+ writeFileSync(projectPath, SRC, 'utf-8');
+ const doc = new Y.Doc();
+ loadManagedArtifactDoc(doc, projectDocName, ctx);
+ expect(doc.getMap('lifecycle').get(LINEAGE_EPOCH_KEY)).toBeUndefined();
+ });
+});
+
+describe('concurrent-writer reconcile', () => {
+ const docName = '__skill__/global/demo';
+
+ test('store reconciles instead of clobbering when disk diverged from LKG', async () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ doc.transact(
+ () => doc.getText('source').insert(0, '---\nname: demo\ndescription: a\n---\nA\n'),
+ 'agent',
+ );
+ await storeManagedArtifactDoc(doc, docName, 'agent', ctx); // LKG = 'A' version
+
+ const path = managedArtifactAbsPath(docName, ctx);
+ const otherWriter = '---\nname: demo\ndescription: a\n---\nOTHER WRITER\n';
+ writeFileSync(path, otherWriter, 'utf-8');
+
+ doc.transact(
+ () => doc.getText('source').insert(doc.getText('source').length, 'local edit'),
+ 'agent',
+ );
+ const outcome = await storeManagedArtifactDoc(doc, docName, 'agent', ctx);
+ expect(outcome).toBe('reconciled');
+ expect(readFileSync(path, 'utf-8')).toBe(otherWriter); // disk preserved
+ expect(reconciled.get(docName)).toBe(otherWriter);
+ });
+
+ test('applyExternalManagedArtifactChange imports disk bytes into the live doc', () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ const raw = '---\nname: demo\ndescription: a\n---\nEXTERNAL\n';
+ expect(applyExternalManagedArtifactChange(doc, docName, raw, ctx)).toBe('applied');
+ expect(doc.getText('source').toString()).toBe(raw);
+ expect(reconciled.get(docName)).toBe(raw);
+ });
+
+ test('applyExternalManagedArtifactChange is a no-op for a null doc', () => {
+ const ctx = makeCtx();
+ expect(applyExternalManagedArtifactChange(null, docName, 'whatever', ctx)).toBe('no-op');
+ expect(reconciled.has(docName)).toBe(false);
+ });
+
+ test('applyExternalManagedArtifactChange short-circuits a self-write (content === LKG)', () => {
+ const ctx = makeCtx();
+ const doc = new Y.Doc();
+ const raw = '---\nname: demo\ndescription: a\n---\nBODY\n';
+ ctx.lkgCache.set(docName, raw);
+ expect(applyExternalManagedArtifactChange(doc, docName, raw, ctx)).toBe('no-op');
+ expect(doc.getText('source').toString()).toBe('');
+ expect(reconciled.has(docName)).toBe(false);
+ });
+});
+
+describe('managedArtifactDocNameForPath (reverse resolver)', () => {
+ test('maps a global SKILL.md leaf back to its doc name; project paths are content', () => {
+ const ctx = makeCtx();
+ expect(
+ managedArtifactDocNameForPath(resolve(projectDir, '.ok/skills/my-skill/SKILL.md'), ctx),
+ ).toBeNull();
+ expect(
+ managedArtifactDocNameForPath(resolve(home, '.ok/skills/notes-helper/SKILL.md'), ctx),
+ ).toBe('__skill__/global/notes-helper');
+ });
+
+ test('maps a template .md leaf back to its folder-addressed doc name', () => {
+ const ctx = makeCtx();
+ expect(managedArtifactDocNameForPath(resolve(projectDir, '.ok/templates/daily.md'), ctx)).toBe(
+ '__template__/daily',
+ );
+ expect(
+ managedArtifactDocNameForPath(resolve(projectDir, 'notes/sub/.ok/templates/meeting.md'), ctx),
+ ).toBe('__template__/notes/sub/meeting');
+ });
+
+ test('round-trips with managedArtifactAbsPath (skills + templates)', () => {
+ const ctx = makeCtx();
+ for (const name of [
+ '__skill__/global/beta-2',
+ '__template__/daily',
+ '__template__/notes/sub/meeting',
+ ]) {
+ expect(managedArtifactDocNameForPath(managedArtifactAbsPath(name, ctx), ctx)).toBe(name);
+ }
+ });
+
+ test('rejects malformed / false-match template paths', () => {
+ const ctx = makeCtx();
+ for (const bad of [
+ resolve(projectDir, '.ok/templates/a/b.md'), // nested below templates dir
+ resolve(projectDir, '.ok/templates/Bad Name.md'), // space in name
+ resolve(projectDir, 'x.ok/templates/t.md'), // `.ok/templates` not a clean boundary
+ ]) {
+ expect(managedArtifactDocNameForPath(bad, ctx)).toBeNull();
+ }
+ });
+
+ test('returns null for non-leaf / malformed / out-of-root paths', () => {
+ const ctx = makeCtx();
+ for (const bad of [
+ resolve(projectDir, '.ok/skills/SKILL.md'), // no <name> segment
+ resolve(projectDir, '.ok/skills/a/b/SKILL.md'), // nested
+ resolve(projectDir, '.ok/skills/my-skill/OTHER.md'), // not SKILL.md
+ resolve(projectDir, '.ok/skills/Bad/SKILL.md'), // uppercase name
+ resolve(projectDir, '.ok/templates/t/SKILL.md'), // not a skills root
+ resolve(projectDir, 'notes/SKILL.md'), // outside .ok/skills
+ '/etc/passwd',
+ ]) {
+ expect(managedArtifactDocNameForPath(bad, ctx)).toBeNull();
+ }
+ });
+});
+
+describe('managedArtifactContributorAttribution (editor-edit versioning)', () => {
+ test('project skill → .ok/skills key + skill- subject', () => {
+ expect(managedArtifactContributorAttribution('__skill__/project/trip-log')).toEqual({
+ docKey: '.ok/skills/trip-log',
+ subject: 'skill-edit: trip-log/SKILL.md',
+ });
+ });
+
+ test('global skill → null (unversioned — outside any project shadow)', () => {
+ expect(managedArtifactContributorAttribution('__skill__/global/notes')).toBeNull();
+ });
+
+ test('templates → folder-addressed .ok/templates key + template- subject', () => {
+ expect(managedArtifactContributorAttribution('__template__/daily')).toEqual({
+ docKey: '.ok/templates/daily',
+ subject: 'template-edit: .ok/templates/daily.md',
+ });
+ expect(managedArtifactContributorAttribution('__template__/notes/sub/meeting')).toEqual({
+ docKey: 'notes/sub/.ok/templates/meeting',
+ subject: 'template-edit: notes/sub/.ok/templates/meeting.md',
+ });
+ });
+
+ test('non-managed-artifact name → null', () => {
+ expect(managedArtifactContributorAttribution('notes/foo')).toBeNull();
+ });
+});
+
+describe('managedArtifactSkillsRoots', () => {
+ test('returns the global skills root only (project skills are content)', () => {
+ const ctx = makeCtx();
+ expect(managedArtifactSkillsRoots(ctx)).toEqual([resolve(home, '.ok', 'skills')]);
+ });
+});
+
+describe('managedArtifactTimelinePaths', () => {
+ test('project skill → versioned, with the .ok/skills key + SKILL.md leaf', () => {
+ expect(managedArtifactTimelinePaths('__skill__/project/my-skill')).toEqual({
+ managed: true,
+ versioned: true,
+ docKey: '.ok/skills/my-skill',
+ filePath: '.ok/skills/my-skill/SKILL.md',
+ });
+ });
+
+ test('template → versioned, folder-addressed key + <name>.md leaf', () => {
+ expect(managedArtifactTimelinePaths('__template__/docs/guides/note')).toEqual({
+ managed: true,
+ versioned: true,
+ docKey: 'docs/guides/.ok/templates/note',
+ filePath: 'docs/guides/.ok/templates/note.md',
+ });
+ expect(managedArtifactTimelinePaths('__template__/note')).toEqual({
+ managed: true,
+ versioned: true,
+ docKey: '.ok/templates/note',
+ filePath: '.ok/templates/note.md',
+ });
+ });
+
+ test('global skill → managed but unversioned (no shadow history)', () => {
+ expect(managedArtifactTimelinePaths('__skill__/global/my-skill')).toEqual({
+ managed: true,
+ versioned: false,
+ });
+ });
+
+ test('ordinary doc → not managed', () => {
+ expect(managedArtifactTimelinePaths('docs/getting-started')).toEqual({ managed: false });
+ });
+});
diff --git a/packages/server/src/managed-artifact-persistence.ts b/packages/server/src/managed-artifact-persistence.ts
new file mode 100644
index 000000000..3f3ae9e19
--- /dev/null
+++ b/packages/server/src/managed-artifact-persistence.ts
@@ -0,0 +1,275 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { resolve, sep } from 'node:path';
+import {
+ LINEAGE_EPOCH_KEY,
+ MANAGED_ARTIFACT_PREFIX_SKILL,
+ MANAGED_ARTIFACT_PREFIX_TEMPLATE,
+ type ManagedArtifactScope,
+ parseManagedArtifactName,
+ SKILL_CONTENT_ROOT,
+ SKILL_NAME_REGEX,
+ TEMPLATE_NAME_REGEX,
+} from '@inkeep/open-knowledge-core';
+import {
+ atomicWriteFile,
+ FileLockTimeoutError,
+ withFileLock,
+} from '@inkeep/open-knowledge-core/server';
+import type * as Y from 'yjs';
+import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './external-change.ts';
+import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
+import { getLogger } from './logger.ts';
+
+const log = getLogger('managed-artifact-persistence');
+
+export interface ManagedArtifactCtx {
+ projectDir: string;
+ homedirOverride?: string;
+ lkgCache: Map<string, string>;
+ setReconciledBase: (docName: string, content: string) => void;
+ getReconciledBase: (docName: string) => string | undefined;
+}
+
+export type StoreManagedArtifactOutcome = 'persisted' | 'no-op' | 'reconciled' | 'write-failed';
+
+type ManagedArtifactLocation = Pick<ManagedArtifactCtx, 'projectDir' | 'homedirOverride'>;
+
+function homeFor(ctx: Pick<ManagedArtifactCtx, 'homedirOverride'>): string {
+ return ctx.homedirOverride ?? homedir();
+}
+
+export function managedArtifactContributorAttribution(
+ documentName: string,
+): { docKey: string; subject: string } | null {
+ const parsed = parseManagedArtifactName(documentName);
+ if (parsed === null) return null;
+ if (parsed.kind === 'skill') {
+ if (parsed.scope !== 'project') return null; // global = unversioned
+ return {
+ docKey: `${SKILL_CONTENT_ROOT}/${parsed.name}`,
+ subject: `skill-edit: ${parsed.name}/SKILL.md`,
+ };
+ }
+ const folder = parsed.folder.replace(/\/$/, '');
+ const docKey = `${folder ? `${folder}/` : ''}.ok/templates/${parsed.name}`;
+ return { docKey, subject: `template-edit: ${docKey}.md` };
+}
+
+export function managedArtifactTimelinePaths(
+ documentName: string,
+):
+ | { managed: false }
+ | { managed: true; versioned: false }
+ | { managed: true; versioned: true; docKey: string; filePath: string } {
+ const parsed = parseManagedArtifactName(documentName);
+ if (!parsed) return { managed: false };
+ const attr = managedArtifactContributorAttribution(documentName);
+ if (!attr) return { managed: true, versioned: false };
+ const filePath = parsed.kind === 'skill' ? `${attr.docKey}/SKILL.md` : `${attr.docKey}.md`;
+ return { managed: true, versioned: true, docKey: attr.docKey, filePath };
+}
+
+export function managedArtifactSkillsRoots(ctx: ManagedArtifactCtx): string[] {
+ return [resolve(homeFor(ctx), '.ok', 'skills')];
+}
+
+export function managedArtifactAbsPath(documentName: string, ctx: ManagedArtifactLocation): string {
+ const parsed = parseManagedArtifactName(documentName);
+ if (parsed === null) {
+ throw new Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${documentName}`);
+ }
+ if (parsed.kind === 'template') {
+ return templateAbsPath(parsed.folder, parsed.name, ctx, documentName);
+ }
+ if (!SKILL_NAME_REGEX.test(parsed.name) || parsed.name.length > 64) {
+ 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');
+ if (!abs.startsWith(skillsRoot + sep)) {
+ throw new Error(`managedArtifactAbsPath: path escape for ${documentName}`);
+ }
+ return abs;
+}
+
+function normalizeTemplateFolder(folder: string): string {
+ return folder.replace(/^\/+/, '').replace(/\/+$/, '');
+}
+
+function templateAbsPath(
+ folder: string,
+ name: string,
+ ctx: Pick<ManagedArtifactCtx, 'projectDir'>,
+ documentName: string,
+): string {
+ if (!TEMPLATE_NAME_REGEX.test(name) || name.length > 64) {
+ throw new Error(`managedArtifactAbsPath: invalid template name: ${JSON.stringify(name)}`);
+ }
+ const folderRel = normalizeTemplateFolder(folder);
+ if (folderRel.split('/').includes('..')) {
+ throw new Error(`managedArtifactAbsPath: template folder escape for ${documentName}`);
+ }
+ const projectAbs = resolve(ctx.projectDir);
+ const folderAbs = folderRel ? resolve(projectAbs, folderRel) : projectAbs;
+ if (folderAbs !== projectAbs && !folderAbs.startsWith(projectAbs + sep)) {
+ throw new Error(`managedArtifactAbsPath: template folder escape for ${documentName}`);
+ }
+ const templatesDir = resolve(folderAbs, '.ok', 'templates');
+ const abs = resolve(templatesDir, `${name}.md`);
+ if (!abs.startsWith(templatesDir + sep)) {
+ throw new Error(`managedArtifactAbsPath: path escape for ${documentName}`);
+ }
+ return abs;
+}
+
+export function managedArtifactDocNameForPath(
+ absPath: string,
+ ctx: ManagedArtifactCtx,
+): string | null {
+ const norm = resolve(absPath);
+ 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);
+ if (rel.length !== 2 || rel[1] !== 'SKILL.md') continue;
+ const name = rel[0];
+ if (!SKILL_NAME_REGEX.test(name) || name.length > 64) continue;
+ return `${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${name}`;
+ }
+ return null;
+ }
+ if (norm.endsWith('.md')) {
+ const projectAbs = resolve(ctx.projectDir);
+ if (norm !== projectAbs && !norm.startsWith(projectAbs + sep)) return null;
+ const rel = norm === projectAbs ? '' : norm.slice(projectAbs.length + 1);
+ const marker = `.ok${sep}templates${sep}`;
+ const idx = rel.indexOf(marker);
+ if (idx < 0) return null;
+ if (idx > 0 && rel[idx - 1] !== sep) return null;
+ const after = rel.slice(idx + marker.length);
+ if (after.includes(sep) || !after.endsWith('.md')) return null; // single .md leaf
+ const name = after.slice(0, -3);
+ if (!TEMPLATE_NAME_REGEX.test(name) || name.length > 64) return null;
+ const folderRel = idx === 0 ? '' : rel.slice(0, idx - 1);
+ const folderEncoded = folderRel
+ ? folderRel
+ .split(sep)
+ .map((s) => encodeURIComponent(s))
+ .join('/')
+ : '';
+ return `${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${folderEncoded ? `${folderEncoded}/` : ''}${encodeURIComponent(name)}`;
+ }
+ return null;
+}
+
+export function loadManagedArtifactDoc(
+ document: Y.Doc,
+ documentName: string,
+ ctx: ManagedArtifactCtx,
+): void {
+ const parsed = parseManagedArtifactName(documentName);
+ if (parsed?.kind === 'skill' && parsed.scope === 'project') return;
+
+ const xmlFragment = document.getXmlFragment('default');
+ if (xmlFragment.length > 0) return;
+
+ const filePath = managedArtifactAbsPath(documentName, ctx);
+ if (!existsSync(filePath)) return;
+
+ let raw: string;
+ try {
+ raw = readFileSync(filePath, 'utf-8');
+ } catch (e) {
+ log.warn({ documentName, err: (e as Error).message }, 'load: could not read; seeding empty');
+ return;
+ }
+
+ document.transact(() => {
+ applyDiskContentToDoc(document, raw, undefined, documentName);
+ document.getMap('lifecycle').set(LINEAGE_EPOCH_KEY, crypto.randomUUID());
+ }, FILE_WATCHER_ORIGIN);
+
+ ctx.setReconciledBase(documentName, raw);
+ ctx.lkgCache.set(documentName, raw);
+}
+
+export async function storeManagedArtifactDoc(
+ document: Y.Doc,
+ documentName: string,
+ lastTransactionOrigin: unknown,
+ ctx: ManagedArtifactCtx,
+): Promise<StoreManagedArtifactOutcome> {
+ const parsedStore = parseManagedArtifactName(documentName);
+ if (parsedStore?.kind === 'skill' && parsedStore.scope === 'project') return 'no-op';
+
+ if (lastTransactionOrigin === FILE_WATCHER_ORIGIN) return 'no-op';
+
+ const content = document.getText('source').toString();
+ const lkg = ctx.lkgCache.get(documentName);
+ if (content === lkg) return 'no-op';
+
+ const filePath = managedArtifactAbsPath(documentName, ctx);
+
+ try {
+ await tracedMkdir(resolve(filePath, '..'), { recursive: true });
+ return await withFileLock(`${filePath}.lock`, async () => {
+ if (existsSync(filePath)) {
+ let disk: string | null = null;
+ try {
+ disk = readFileSync(filePath, 'utf-8');
+ } catch (readErr) {
+ if ((readErr as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.warn(
+ { documentName, err: (readErr as Error).message },
+ 'store: pre-write disk read failed (non-ENOENT); proceeding to write',
+ );
+ }
+ disk = null;
+ }
+ if (disk !== null && disk !== lkg && disk !== content) {
+ document.transact(() => {
+ applyDiskContentToDoc(document, disk, undefined, documentName);
+ }, FILE_WATCHER_ORIGIN);
+ ctx.setReconciledBase(documentName, disk);
+ ctx.lkgCache.set(documentName, disk);
+ return 'reconciled';
+ }
+ }
+ await atomicWriteFile(filePath, content, { fs: tracedAtomicFs });
+ ctx.lkgCache.set(documentName, content);
+ ctx.setReconciledBase(documentName, content);
+ return 'persisted';
+ });
+ } catch (e) {
+ if (e instanceof FileLockTimeoutError) {
+ log.warn({ documentName }, 'store: file lock timeout; skipping write');
+ return 'write-failed';
+ }
+ log.warn({ documentName, err: (e as Error).message }, 'store: write failed');
+ return 'write-failed';
+ }
+}
+
+export type ApplyExternalManagedArtifactChangeOutcome = 'applied' | 'no-op';
+
+export function applyExternalManagedArtifactChange(
+ document: Y.Doc | null,
+ documentName: string,
+ raw: string,
+ ctx: ManagedArtifactCtx,
+): ApplyExternalManagedArtifactChangeOutcome {
+ if (!document) return 'no-op';
+ const lkg = ctx.lkgCache.get(documentName);
+ if (lkg !== undefined && lkg === raw) return 'no-op';
+ document.transact(() => {
+ applyDiskContentToDoc(document, raw, undefined, documentName);
+ }, FILE_WATCHER_ORIGIN);
+ ctx.setReconciledBase(documentName, raw);
+ ctx.lkgCache.set(documentName, raw);
+ return 'applied';
+}
diff --git a/packages/server/src/managed-artifact-watcher.test.ts b/packages/server/src/managed-artifact-watcher.test.ts
new file mode 100644
index 000000000..4a482d87f
--- /dev/null
+++ b/packages/server/src/managed-artifact-watcher.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import {
+ type ManagedArtifactWatcherUnsubscribe,
+ startManagedArtifactWatcher,
+} from './managed-artifact-watcher.ts';
+
+let root: string;
+let cleanup: ManagedArtifactWatcherUnsubscribe | null = null;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-ma-watch-'));
+});
+afterEach(async () => {
+ if (cleanup) await cleanup();
+ cleanup = null;
+ rmSync(root, { recursive: true, force: true });
+});
+
+async function eventually(predicate: () => boolean, timeoutMs = 20_000): Promise<void> {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ throw new Error('eventually: predicate never became true');
+}
+
+const RUNNING_IN_CI = Boolean(process.env.CI);
+
+describe.skipIf(RUNNING_IN_CI)('startManagedArtifactWatcher', () => {
+ test('fires onChange for a SKILL.md created after start', async () => {
+ const skillsRoot = resolve(root, '.ok', 'skills');
+ const seen: Array<[string, string]> = [];
+ cleanup = await startManagedArtifactWatcher([skillsRoot], (p, c) => seen.push([p, c]));
+
+ const skillDir = resolve(skillsRoot, 'demo');
+ mkdirSync(skillDir, { recursive: true });
+ const leaf = resolve(skillDir, 'SKILL.md');
+ writeFileSync(leaf, 'v1', 'utf-8');
+
+ await eventually(() => seen.some(([p, c]) => p === leaf && c === 'v1'));
+ }, 25_000);
+
+ test('fires onChange on edit; ignores non-SKILL.md siblings', 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 contents: string[] = [];
+ cleanup = await startManagedArtifactWatcher([skillsRoot], (_p, c) => contents.push(c));
+
+ writeFileSync(resolve(skillDir, 'NOTES.md'), 'noise', 'utf-8');
+ writeFileSync(leaf, 'v2', 'utf-8');
+
+ await eventually(() => contents.includes('v2'));
+ expect(contents).not.toContain('noise');
+ }, 25_000);
+});
diff --git a/packages/server/src/managed-artifact-watcher.ts b/packages/server/src/managed-artifact-watcher.ts
new file mode 100644
index 000000000..9fb0965d7
--- /dev/null
+++ b/packages/server/src/managed-artifact-watcher.ts
@@ -0,0 +1,98 @@
+import { readFileSync } from 'node:fs';
+import { basename } from 'node:path';
+import { tracedMkdirSync } from './fs-traced.ts';
+import { getLogger } from './logger.ts';
+
+export type ManagedArtifactWatcherUnsubscribe = () => Promise<void>;
+
+export interface ManagedArtifactWatchOptions {
+ depth: number;
+ acceptLeaf: (absPath: string) => boolean;
+}
+
+const SKILL_WATCH_OPTIONS: ManagedArtifactWatchOptions = {
+ depth: 1,
+ acceptLeaf: (p) => basename(p) === 'SKILL.md',
+};
+
+export const TEMPLATE_WATCH_OPTIONS: ManagedArtifactWatchOptions = {
+ depth: 0,
+ acceptLeaf: (p) => basename(p).endsWith('.md'),
+};
+
+export async function startManagedArtifactWatcher(
+ roots: ReadonlyArray<string>,
+ onChange: (absPath: string, content: string) => void,
+ opts: ManagedArtifactWatchOptions = SKILL_WATCH_OPTIONS,
+): Promise<ManagedArtifactWatcherUnsubscribe> {
+ const log = getLogger('managed-artifact-watcher');
+ const { watch } = await import('chokidar');
+
+ const watchRoots = Array.from(new Set(roots));
+ for (const dir of watchRoots) {
+ try {
+ tracedMkdirSync(dir, { recursive: true });
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'EEXIST') {
+ log.warn({ err, dir }, 'failed to create watch root; watcher may be inert');
+ }
+ }
+ }
+
+ const watcher = watch(watchRoots, {
+ ignoreInitial: true,
+ depth: opts.depth,
+ usePolling: true,
+ interval: 200,
+ awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 },
+ });
+
+ await new Promise<void>((resolve) => {
+ watcher.once('ready', resolve);
+ });
+
+ const lastContent = new Map<string, string | null>();
+
+ const handlePath = (path: string): void => {
+ if (!opts.acceptLeaf(path)) return;
+ let content: string;
+ try {
+ content = readFileSync(path, 'utf-8');
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === 'ENOENT') {
+ log.debug({ path }, 'managed-artifact leaf disappeared between event and read; dropping');
+ return;
+ }
+ log.warn({ err, path }, 'managed-artifact leaf read failed; dropping event');
+ return;
+ }
+ if (content === lastContent.get(path)) return;
+ lastContent.set(path, content);
+ try {
+ onChange(path, content);
+ } catch (err) {
+ log.warn({ err, path }, 'managed-artifact change handler threw');
+ }
+ };
+ const handler = (path: string): void => handlePath(path);
+
+ watcher.on('add', handler);
+ watcher.on('change', handler);
+ watcher.on('unlink', (path) => {
+ if (!opts.acceptLeaf(path)) return;
+ lastContent.delete(path);
+ log.debug({ path }, 'managed-artifact leaf unlinked; live doc retained at current state');
+ });
+ watcher.on('error', (err) => {
+ log.warn({ err, watchRoots }, '[managed-artifact-watcher] chokidar error');
+ });
+
+ let closed = false;
+ return async () => {
+ if (closed) return;
+ closed = true;
+ await watcher.close();
+ };
+}
diff --git a/packages/server/src/mcp/tools/delete.ts b/packages/server/src/mcp/tools/delete.ts
index 3f24c902f..58f8c26b7 100644
--- a/packages/server/src/mcp/tools/delete.ts
+++ b/packages/server/src/mcp/tools/delete.ts
@@ -16,14 +16,22 @@ import {
textPlusStructured,
textResult,
} from './shared.ts';
-import { exactlyOneTargetError, resolveTemplatePath } from './verb-schemas.ts';
+import { deleteSkill, deleteSkillFile, type SkillScope } from './skill-target.ts';
+import {
+ exactlyOneTargetError,
+ resolveSkillFilePath,
+ resolveTemplatePath,
+ SKILL_NAME_DESCRIBE,
+ SkillScopeArg,
+} from './verb-schemas.ts';
const BASE_DESCRIPTION = [
- 'Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset`.',
+ 'Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset`.',
'',
'- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]',
'- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]',
'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]',
+ '- `skill` — `{ name }` deletes a whole SKILL; `{ name, files: ["references/x.md"] }` deletes specific bundle files (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]',
'- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',
'',
'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.',
@@ -104,6 +112,22 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {
.object({ path: z.string().describe('Template path = `<folder>/<name>`.') })
.optional()
.describe('A template to delete.'),
+ skill: z
+ .object({
+ name: z.string().describe(SKILL_NAME_DESCRIBE),
+ files: z
+ .array(z.string())
+ .min(1)
+ .optional()
+ .describe(
+ 'Skill-relative bundle file paths to delete (`references/...`/`scripts/...`). Omit to delete the WHOLE skill (`.ok/skills/<name>/`).',
+ ),
+ scope: SkillScopeArg.optional(),
+ })
+ .optional()
+ .describe(
+ 'A skill to delete — the whole skill (`.ok/skills/<name>/`), or specific bundle files when `files` is set.',
+ ),
asset: z
.object({
path: z
@@ -138,6 +162,16 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {
.object({ ok: z.boolean(), existed: z.boolean() })
.optional()
.describe('Template delete result.'),
+ skill: z
+ .object({
+ ok: z.boolean(),
+ existed: z.boolean().optional(),
+ files: looseObjectArray
+ .optional()
+ .describe('Per-bundle-file delete results `{ path, ok, existed?, error? }`.'),
+ })
+ .optional()
+ .describe('Skill delete result (whole skill or specific bundle files).'),
asset: z
.object({ ok: z.boolean(), path: z.string() })
.optional()
@@ -152,6 +186,7 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {
document?: string | string[] | { path: string | string[] };
folder?: string | { path: string };
template?: { path: string };
+ skill?: { name: string; scope?: SkillScope; files?: string[] };
asset?: { path: string };
cwd?: string;
}) => {
@@ -174,10 +209,56 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {
'document',
'folder',
'template',
+ 'skill',
'asset',
]);
if (teaching) return textResult(`Error: ${teaching}`, true);
+ if (args.skill !== undefined) {
+ const skill = args.skill;
+ if (skill.files !== undefined && skill.files.length > 0) {
+ for (const f of skill.files) {
+ const check = resolveSkillFilePath(f);
+ if (!check.ok) return textResult(`Error: ${check.error}`, true);
+ }
+ const results: Array<{ path: string; ok: boolean; existed?: boolean; error?: string }> =
+ [];
+ for (const f of skill.files) {
+ const r = await deleteSkillFile(url, {
+ name: skill.name,
+ scope: skill.scope,
+ path: f,
+ identity: deps.identityRef?.current,
+ });
+ const struct = (
+ r as { structuredContent?: { skill?: { file?: { existed?: boolean } } } }
+ ).structuredContent;
+ if (r.isError) {
+ results.push({ path: f, ok: false, error: r.content[0]?.text ?? 'delete failed' });
+ } else {
+ results.push({ path: f, ok: true, existed: struct?.skill?.file?.existed === true });
+ }
+ }
+ const okCount = results.filter((r) => r.ok).length;
+ const allOk = okCount === results.length;
+ const lines = results.map((r) =>
+ r.ok
+ ? `${r.existed ? 'Deleted' : 'No-op (absent)'} ${r.path}.`
+ : `Failed ${r.path}: ${r.error}`,
+ );
+ return textPlusStructured(
+ `${okCount}/${results.length} skill file(s) processed.\n${lines.join('\n')}`,
+ { skill: { ok: allOk, files: results } },
+ !allOk,
+ );
+ }
+ return deleteSkill(url, {
+ name: skill.name,
+ scope: skill.scope,
+ identity: deps.identityRef?.current,
+ });
+ }
+
if (args.template !== undefined) {
const resolved = resolveTemplatePath(args.template.path);
if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
index cac227bd6..03d7a0519 100644
--- a/packages/server/src/mcp/tools/edit.ts
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -24,6 +24,7 @@ import {
httpPut,
nestDocResult,
normalizeDocName,
+ okReservedPathRedirect,
outputSchemaWithText,
previewAttachWarningField,
previewUrlOutputField,
@@ -34,20 +35,34 @@ import {
textPlusStructured,
textResult,
} from './shared.ts';
+import {
+ fetchSkill,
+ readSkillFile,
+ type SkillScope,
+ writeSkill,
+ writeSkillFile,
+} from './skill-target.ts';
import {
exactlyOneTargetError,
FrontmatterArg,
+ resolveSkillFilePath,
+ resolveSkillName,
resolveTemplatePath,
+ SKILL_DESCRIPTION_DESCRIBE,
+ SKILL_FILE_DESCRIBE,
+ SKILL_NAME_DESCRIBE,
+ SkillScopeArg,
TEMPLATE_PATH_DESCRIBE,
} from './verb-schemas.ts';
const BASE_DESCRIPTION = [
- 'Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, or `template`. Within each: a body edit (`find` + `replace`) OR a `frontmatter` merge-patch — not both in one call.',
+ 'Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, `template`, or `skill`. Within each: a body edit (`find` + `replace`) OR a metadata patch — not both in one call.',
'',
'- `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`.',
- '- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, or `template` edit. Avoid secrets or PII — persisted to git history.',
+ "- `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.",
+ '- `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');
@@ -124,7 +139,7 @@ async function handleDocBody(
autoOpen: boolean,
) {
const normalized = normalizeDocName(doc.path);
- if (!normalized.ok) return textResult(normalized.error, true);
+ if (!normalized.ok) return textResult(okReservedPathRedirect(doc.path) ?? normalized.error, true);
const identity = deps.identityRef?.current;
let offset: number | undefined;
@@ -189,7 +204,7 @@ async function handleDocFrontmatter(
autoOpen: boolean,
) {
const normalized = normalizeDocName(doc.path);
- if (!normalized.ok) return textResult(normalized.error, true);
+ if (!normalized.ok) return textResult(okReservedPathRedirect(doc.path) ?? normalized.error, true);
const identity = deps.identityRef?.current;
const result = await httpPost(url, '/api/frontmatter-patch', {
docName: normalized.docName,
@@ -387,6 +402,154 @@ async function handleTemplate(
});
}
+async function handleSkillFileEdit(
+ skill: {
+ name: string;
+ scope?: SkillScope;
+ file?: string;
+ find?: string;
+ replace?: string;
+ occurrence?: number;
+ description?: string;
+ },
+ url: string | undefined,
+ summary?: string,
+ identity?: AgentIdentity,
+) {
+ const resolved = resolveSkillName(skill.name);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ const pathCheck = resolveSkillFilePath(skill.file as string);
+ if (!pathCheck.ok) return textResult(`Error: ${pathCheck.error}`, true);
+ if (skill.description !== undefined) {
+ return textResult(
+ 'Error: `description` edits SKILL.md, not a bundle file. Drop `file`, or edit the file body with find+replace.',
+ true,
+ );
+ }
+ if (skill.find === undefined || skill.replace === undefined) {
+ return textResult(
+ 'Error: a bundle-file edit needs `find` + `replace`: { skill: { name, file, find, replace } }.',
+ true,
+ );
+ }
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+
+ const scope = skill.scope ?? 'project';
+ const existing = await readSkillFile(url, scope, skill.name, pathCheck.path);
+ if (!existing.ok) {
+ return textResult(
+ `Error: skill file "${pathCheck.path}" not found in skill "${skill.name}" (${scope} scope). Create it with \`write({ skill: { name, files: [...] } })\` first.`,
+ true,
+ );
+ }
+ const occurrence = skill.occurrence ?? 1;
+ const idx = nthOccurrenceOffset(existing.text, skill.find, occurrence);
+ if (idx === -1) {
+ return textResult(
+ `Error: \`find\` occurs fewer than ${occurrence} time(s) in skill file "${pathCheck.path}".`,
+ true,
+ );
+ }
+ const newText =
+ existing.text.slice(0, idx) + skill.replace + existing.text.slice(idx + skill.find.length);
+ return writeSkillFile(url, {
+ name: skill.name,
+ scope,
+ path: pathCheck.path,
+ content: newText,
+ summary,
+ identity,
+ });
+}
+
+async function handleSkill(
+ skill: {
+ name: string;
+ scope?: SkillScope;
+ file?: string;
+ find?: string;
+ replace?: string;
+ occurrence?: number;
+ description?: string;
+ },
+ summary: string | undefined,
+ url: string | undefined,
+ deps: EditDeps,
+ lockDir: string,
+) {
+ const resolved = resolveSkillName(skill.name);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+
+ if (skill.file !== undefined) {
+ return handleSkillFileEdit(skill, url, summary, deps.identityRef?.current);
+ }
+
+ const hasBody = skill.find !== undefined || skill.replace !== undefined;
+ const hasDesc = skill.description !== undefined;
+ if (skill.find !== undefined && skill.replace === undefined) {
+ return textResult(
+ 'Error: `find` needs a `replace`. Body edit: { skill: { name, find, replace } }.',
+ true,
+ );
+ }
+ if (skill.replace !== undefined && skill.find === undefined) {
+ return textResult(
+ 'Error: `replace` needs a `find`. Body edit: { skill: { name, find, replace } }.',
+ true,
+ );
+ }
+ if (hasBody && hasDesc) {
+ return textResult(
+ 'Error: Pick ONE: edit the body (find+replace) OR the `description`, not both in one call.',
+ true,
+ );
+ }
+ if (!hasBody && !hasDesc) {
+ return textResult(
+ 'Error: Provide either a body edit (find+replace) or a `description` for { skill }.',
+ true,
+ );
+ }
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+
+ const scope = skill.scope ?? 'project';
+ const existing = await fetchSkill(url, scope, skill.name);
+ if (!existing.ok) {
+ return textResult(
+ `Error: skill "${skill.name}" not found in ${scope} scope. Create it with \`write({ skill })\` first.`,
+ true,
+ );
+ }
+
+ let newBody = existing.body;
+ let newDescription = existing.description;
+ if (hasDesc) {
+ newDescription = skill.description as string;
+ } else {
+ const occurrence = skill.occurrence ?? 1;
+ const idx = nthOccurrenceOffset(existing.body, skill.find as string, occurrence);
+ if (idx === -1) {
+ return textResult(
+ `Error: \`find\` occurs fewer than ${occurrence} time(s) in skill "${skill.name}".`,
+ true,
+ );
+ }
+ newBody =
+ existing.body.slice(0, idx) +
+ (skill.replace as string) +
+ existing.body.slice(idx + (skill.find as string).length);
+ }
+ return writeSkill(url, {
+ scope,
+ name: skill.name,
+ description: newDescription,
+ body: newBody,
+ summary,
+ identity: deps.identityRef?.current,
+ lockDir,
+ });
+}
+
async function handleFolder(
folder: { path: string; frontmatter: FrontmatterPatch },
summary: string | undefined,
@@ -467,6 +630,18 @@ export function register(server: ServerInstance, deps: EditDeps): void {
})
.optional()
.describe('Edit a TEMPLATE: body (find+replace) or frontmatter (patch).'),
+ skill: z
+ .object({
+ name: z.string().describe(SKILL_NAME_DESCRIBE),
+ file: z.string().optional().describe(SKILL_FILE_DESCRIBE),
+ ...bodyFields,
+ description: z.string().optional().describe(SKILL_DESCRIPTION_DESCRIBE),
+ scope: SkillScopeArg.optional(),
+ })
+ .optional()
+ .describe(
+ 'Edit a SKILL: SKILL.md body (find+replace) OR its `description`; or pass `file` to find/replace inside ONE `references/**`+`scripts/**` bundle file.',
+ ),
summary: summaryArgSchema,
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
@@ -489,6 +664,25 @@ export function register(server: ServerInstance, deps: EditDeps): void {
.object({ ok: z.boolean(), path: z.string() })
.optional()
.describe('Template edit result.'),
+ skill: z
+ .object({
+ ok: z.boolean(),
+ path: z.string().optional(),
+ created: z
+ .boolean()
+ .optional()
+ .describe('Always false for an edit (the skill already existed).'),
+ file: z
+ .object({
+ path: z.string(),
+ kind: z.string().optional(),
+ created: z.boolean().optional(),
+ })
+ .optional()
+ .describe('Present for a bundle-file edit: the file edited.'),
+ })
+ .optional()
+ .describe('Skill edit result (SKILL.md or a bundle file).'),
previewUrl: previewUrlOutputField.optional(),
previewUrlSource: previewUrlSourceField,
warning: previewAttachWarningField,
@@ -498,6 +692,9 @@ export function register(server: ServerInstance, deps: EditDeps): void {
document?: { path: string } & BodyEdit & { frontmatter?: FrontmatterPatch };
folder?: { path: string; frontmatter: FrontmatterPatch };
template?: { path: string } & BodyEdit & { frontmatter?: FrontmatterPatch };
+ skill?: { name: string; scope?: SkillScope; file?: string } & BodyEdit & {
+ description?: string;
+ };
summary?: string;
cwd?: string;
}) => {
@@ -516,6 +713,7 @@ export function register(server: ServerInstance, deps: EditDeps): void {
'document',
'folder',
'template',
+ 'skill',
]);
if (teaching) return textResult(`Error: ${teaching}`, true);
@@ -536,6 +734,8 @@ export function register(server: ServerInstance, deps: EditDeps): void {
return handleDocBody(args.document, args, cwd, contentDir, url, deps, autoOpen);
}
if (args.folder !== undefined) return handleFolder(args.folder, args.summary, url, deps);
+ if (args.skill !== undefined)
+ return handleSkill(args.skill, args.summary, url, deps, resolveLockDir(cwd));
return handleTemplate(
args.template as NonNullable<typeof args.template>,
args.summary,
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index 828ac7dfa..6fd81865c 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -24,6 +24,7 @@ interface ToolResult {
type ToolHandler = (args: {
document?: string;
folder?: string;
+ skill?: { name: string; scope?: 'project' | 'global' };
armPaneTarget?: boolean;
cwd?: string;
}) => Promise<ToolResult>;
@@ -150,6 +151,42 @@ describe('preview_url tool — UI running', () => {
});
});
+describe('preview_url tool — skill target', () => {
+ test('with skill: composes the __skill__ route (default project scope)', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ const uiBase = bindTestUiLock(cwd);
+ const handler = captureRegistration(cwd);
+ const result = await handler({ skill: { name: 'trip-log' } });
+ expect(result.structuredContent?.url).toBe(`${uiBase}/#/__skill__/project/trip-log`);
+ });
+
+ test('with skill + explicit global scope and a spaced name', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ const uiBase = bindTestUiLock(cwd);
+ const handler = captureRegistration(cwd);
+ const result = await handler({ skill: { name: 'run tests', scope: 'global' } });
+ expect(result.structuredContent?.url).toBe(`${uiBase}/#/__skill__/global/run%20tests`);
+ });
+
+ test('armPaneTarget with a skill arms the skill route', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ bindTestUiLock(cwd);
+ const handler = captureRegistration(cwd);
+ await handler({ skill: { name: 'trip-log' }, armPaneTarget: true });
+ expect(readArmedPaneTarget(resolveLockDir(cwd))).toBe('#/__skill__/project/trip-log');
+ });
+
+ test('skill + document together is rejected (mutually exclusive)', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ bindTestUiLock(cwd);
+ const handler = captureRegistration(cwd);
+ const result = await handler({ skill: { name: 'trip-log' }, document: 'specs/foo/SPEC' });
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain('mutually exclusive');
+ expect(readArmedPaneTarget(resolveLockDir(cwd))).toBeNull();
+ });
+});
+
describe('preview_url tool — no UI running', () => {
test('returns running:false + the ok-start hint when nothing is running', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.ts
index e149d3afa..addee063d 100644
--- a/packages/server/src/mcp/tools/get-preview-url.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.ts
@@ -1,3 +1,4 @@
+import { MANAGED_ARTIFACT_SCOPES, SKILL_NAME_REGEX } from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { AutoStartDisabledError } from '../../autostart.ts';
import { resolveLockDir } from '../../config/paths.ts';
@@ -8,6 +9,7 @@ import {
awaitUiBaseUrl,
encodeDocName,
encodeFolderRoute,
+ encodeSkillRoute,
type PreviewUrlContext,
resolveUiInfo,
} from './preview-url.ts';
@@ -32,7 +34,8 @@ const DESCRIPTION = [
'**Parameters:**',
'- `document` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.',
'- `folder` (optional) — Folder path (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
- '- `armPaneTarget` (optional) — When true with a `document`/`folder`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. Independent of server state; omit it and the call writes nothing.',
+ '- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`.',
+ '- `armPaneTarget` (optional) — When true with a `document`/`folder`/`skill`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. Independent of server state; omit it and the call writes nothing.',
'- `cwd` (optional) — Project root (see `cwd` description below).',
].join('\n');
@@ -60,6 +63,22 @@ const InputSchema = {
.describe(
'Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
),
+ skill: z
+ .object({
+ name: z
+ .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).'),
+ scope: z
+ .enum(MANAGED_ARTIFACT_SCOPES)
+ .optional()
+ .describe('Skill scope; defaults to `project`.'),
+ })
+ .optional()
+ .describe(
+ 'Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`.',
+ ),
armPaneTarget: z
.boolean()
.optional()
@@ -120,14 +139,20 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
idempotentHint: true,
},
},
- async (args: { document?: string; folder?: string; armPaneTarget?: boolean; cwd?: string }) => {
- if (args.document && args.folder) {
+ async (args: {
+ document?: string;
+ folder?: string;
+ skill?: { name: string; scope?: 'project' | 'global' };
+ armPaneTarget?: boolean;
+ cwd?: string;
+ }) => {
+ if ([args.document, args.folder, args.skill].filter((t) => t != null).length > 1) {
return {
isError: true,
content: [
{
type: 'text' as const,
- text: 'Error: document and folder are mutually exclusive — pass exactly one.',
+ text: 'Error: document, folder, and skill are mutually exclusive — pass at most one.',
},
],
};
@@ -147,7 +172,9 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
? `#/${encodeDocName(args.document)}`
: args.folder
? `#/${encodeFolderRoute(args.folder)}`
- : null;
+ : args.skill
+ ? `#/${encodeSkillRoute(args.skill.scope ?? 'project', args.skill.name)}`
+ : null;
if (args.armPaneTarget && routeFragment) {
try {
@@ -157,7 +184,7 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
const armNote =
args.armPaneTarget && !routeFragment
- ? ' (note: armPaneTarget was set but no document/folder was given, so nothing was armed)'
+ ? ' (note: armPaneTarget was set but no document/folder/skill was given, so nothing was armed)'
: '';
const serverWasLive = isServerLive(lockDir);
diff --git a/packages/server/src/mcp/tools/history.ts b/packages/server/src/mcp/tools/history.ts
index c1ece6c72..541de0bfe 100644
--- a/packages/server/src/mcp/tools/history.ts
+++ b/packages/server/src/mcp/tools/history.ts
@@ -1,3 +1,4 @@
+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';
@@ -42,9 +43,10 @@ const DESCRIPTION = [
'Returns timeline entries from the shadow repo, sorted by timestamp descending.',
'Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.',
'',
- '**Parameters (pass EXACTLY ONE of `document` / `folder`):**',
+ '**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 })`.",
'- `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)',
@@ -75,6 +77,12 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
.describe(
'Folder path to query the FOLDER timeline for — attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter): created / edited / renamed / moved / deleted, by whom, when. Mutually exclusive with `document`. Use `""` for the project root.',
),
+ skill: z
+ .string()
+ .optional()
+ .describe(
+ 'Skill name to query version history for (`.ok/skills/<name>/`). Mutually exclusive with `document` / `folder`.',
+ ),
branch: z.string().optional().describe('Branch name (default: current branch)'),
limit: z
.number()
@@ -120,6 +128,7 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
async (args: {
document?: string;
folder?: string;
+ skill?: string;
branch?: string;
limit?: number;
offset?: number;
@@ -138,15 +147,23 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
const { cwd, url } = context;
if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
- const isFolder = args.folder !== undefined;
- if (isFolder === (args.document !== undefined)) {
- return textResult('Error: pass EXACTLY ONE of `document` or `folder`.', true);
+ const targetCount =
+ (args.document !== undefined ? 1 : 0) +
+ (args.folder !== undefined ? 1 : 0) +
+ (args.skill !== undefined ? 1 : 0);
+ if (targetCount !== 1) {
+ return textResult('Error: pass EXACTLY ONE of `document`, `folder`, or `skill`.', true);
}
+ const isFolder = args.folder !== undefined;
const params = new URLSearchParams();
let previewDocName: string | null = null;
if (isFolder) {
params.set('folder', args.folder ?? '');
+ } else if (args.skill !== undefined) {
+ const docName = projectSkillContentDocName(args.skill);
+ params.set('docName', docName);
+ previewDocName = docName;
} else {
const normalized = normalizeDocName(args.document as string);
if (!normalized.ok) return textResult(normalized.error, true);
diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.ts
index 0d3dc43c7..dbbec8f3a 100644
--- a/packages/server/src/mcp/tools/index.ts
+++ b/packages/server/src/mcp/tools/index.ts
@@ -9,6 +9,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 registerInstall } from './install.ts';
import { register as registerLinks } from './links.ts';
import { register as registerMove } from './move.ts';
import { register as registerPalette } from './palette.ts';
@@ -17,6 +18,7 @@ import { register as registerRestoreVersion } from './restore-version.ts';
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';
@@ -98,11 +100,22 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
resolveCwd: named('move'),
identityRef: opts.identityRef,
});
+ registerInstall(registrationServer, {
+ serverUrl: opts.serverUrl,
+ config: opts.config,
+ resolveCwd: named('install'),
+ identityRef: opts.identityRef,
+ });
registerHistory(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
resolveCwd: named('history'),
});
+ registerSkills(registrationServer, {
+ serverUrl: opts.serverUrl,
+ config: opts.config,
+ resolveCwd: named('skills'),
+ });
registerCheckpoint(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
diff --git a/packages/server/src/mcp/tools/install.ts b/packages/server/src/mcp/tools/install.ts
new file mode 100644
index 000000000..87c176ca1
--- /dev/null
+++ b/packages/server/src/mcp/tools/install.ts
@@ -0,0 +1,113 @@
+import {
+ 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,
+ httpPost,
+ outputSchemaWithText,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ summaryArgSchema,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+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.',
+ '',
+ '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>/`). 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.',
+ '',
+ '**Parameters:**',
+ `- \`name\` — ${SKILL_NAME_DESCRIBE}`,
+ '- `targets` — Optional explicit editor ids (`claude` | `cursor` | `codex` | `opencode`). 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).',
+ '',
+ 'After editing a skill, run `install` again to push the new version. After `delete({skill})`, the projection is removed automatically (uninstall).',
+].join('\n');
+
+interface InstallDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+export function register(server: ServerInstance, deps: InstallDeps): void {
+ server.registerTool(
+ 'install',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ name: z.string().describe(SKILL_NAME_DESCRIBE),
+ targets: z
+ .array(SkillTargetEditorSchema)
+ .optional()
+ .describe(
+ 'Explicit editor ids to install into. Omit to use the editors this project is configured for.',
+ ),
+ 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.'),
+ scripts: z
+ .boolean()
+ .optional()
+ .describe('true when the skill ships executable `scripts/` (projected, never auto-run).'),
+ warnings: z.array(z.string()).optional(),
+ }),
+ },
+ async (args: {
+ name: string;
+ targets?: SkillTargetEditor[];
+ scope?: SkillScope;
+ summary?: string;
+ cwd?: string;
+ }) => {
+ const resolved = resolveSkillName(args.name);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ const context = await resolveProjectServerContext(
+ 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);
+
+ 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.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, 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[]) : [];
+ const lines = [
+ hosts.length > 0
+ ? `Installed skill "${args.name}" into: ${hosts.join(', ')}.`
+ : `Skill "${args.name}" was not projected — no target editors.`,
+ ...warnings,
+ ];
+ return textPlusStructured(lines.join('\n'), {
+ name: args.name,
+ hosts,
+ scripts,
+ warnings,
+ });
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/move.ts b/packages/server/src/mcp/tools/move.ts
index ff00c86b7..99983ce7b 100644
--- a/packages/server/src/mcp/tools/move.ts
+++ b/packages/server/src/mcp/tools/move.ts
@@ -1,5 +1,6 @@
import { existsSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import { MANAGED_ARTIFACT_SCOPES } from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
import type { AgentIdentity } from '../agent-identity.ts';
@@ -24,6 +25,7 @@ import {
textPlusStructured,
textResult,
} from './shared.ts';
+import { moveSkill, moveSkillCrossScope, type SkillScope } from './skill-target.ts';
import { resolveTemplatePath } from './verb-schemas.ts';
const DESCRIPTION = [
@@ -33,6 +35,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`.',
'- `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).',
@@ -62,6 +65,7 @@ interface MoveArgs {
from?: string;
to?: string;
template?: { from: string; to: string };
+ skill?: { from: string; to: string; scope?: SkillScope; toScope?: SkillScope };
summary?: string;
cwd?: string;
}
@@ -150,6 +154,27 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
.describe(
'Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.',
),
+ skill: z
+ .object({
+ from: z.string(),
+ to: z.string(),
+ scope: z
+ .enum(MANAGED_ARTIFACT_SCOPES)
+ .optional()
+ .describe(
+ 'Source level (default "project"). "project" = this KB\'s `.ok/skills/`; "global" = the Global `~/.ok/skills/`.',
+ ),
+ 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.',
+ ),
+ })
+ .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`.',
+ ),
summary: summaryArgSchema.describe(
'Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.',
),
@@ -158,10 +183,10 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
outputSchema: outputSchemaWithText({
ok: z.boolean().describe('Whether the move succeeded.'),
kind: z
- .enum(['file', 'folder', 'asset', 'template'])
+ .enum(['file', 'folder', 'asset', 'template', 'skill'])
.optional()
.describe(
- 'What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template` when the `template` target was used).',
+ 'What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template`/`skill` when that nested target was used).',
),
committed: z
.boolean()
@@ -190,6 +215,18 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
colliding: looseObjectArray
.optional()
.describe('On a 409 collision: the conflicting from→to pairs.'),
+ crossScope: z
+ .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`).',
+ ),
+ bothScopes: z
+ .boolean()
+ .optional()
+ .describe(
+ 'Skill cross-level move only: `true` when the destination write succeeded but deleting the source failed, so the skill now exists in BOTH levels and the source copy must be removed manually.',
+ ),
}),
},
async (args: MoveArgs) => {
@@ -239,9 +276,36 @@ export function register(server: ServerInstance, deps: MoveDeps): void {
);
}
+ if (args.skill !== undefined) {
+ if (args.from !== undefined || args.to !== undefined) {
+ return textResult(
+ 'Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `skill: { from, to }` — not both.',
+ true,
+ );
+ }
+ const fromScope = args.skill.scope ?? 'project';
+ if (args.skill.toScope !== undefined && args.skill.toScope !== fromScope) {
+ return moveSkillCrossScope(url, {
+ fromScope,
+ toScope: args.skill.toScope,
+ fromName: args.skill.from,
+ toName: args.skill.to,
+ summary: args.summary,
+ identity: deps.identityRef?.current,
+ });
+ }
+ return moveSkill(url, {
+ fromName: args.skill.from,
+ toName: args.skill.to,
+ scope: args.skill.scope,
+ summary: args.summary,
+ identity: deps.identityRef?.current,
+ });
+ }
+
if (args.from === undefined || args.to === undefined) {
return textResult(
- 'Error: provide both `from` and `to` (or use `template: { from, to }` to move a template).',
+ 'Error: provide both `from` and `to` (or use `template: { from, to }` to move a template, or `skill: { from, to }` to move/rename a skill).',
true,
);
}
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 2bbc6ba63..64ec4c9ff 100644
--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts
+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
@@ -183,3 +183,54 @@ describe('MCP outputSchema strictness — auto-discovered registerTool sweep (no
return validate(probe) as { valid: boolean; errorMessage?: string };
}
});
+
+describe('move outputSchema admits the cross-level skill-move payloads (CORR-1)', () => {
+ function moveOutputJsonSchema(): Record<string, unknown> {
+ const cwd = newProject();
+ const captured: Array<{ name: string; outputSchema?: unknown }> = [];
+ const server = {
+ registerTool(name: string, cfg: { outputSchema?: unknown }) {
+ captured.push({ name, outputSchema: cfg.outputSchema });
+ },
+ tool() {},
+ } as unknown as ServerInstance;
+ registerAllTools(server, {
+ config: BASE_CONFIG,
+ resolveCwd: async () => cwd,
+ serverUrl: undefined,
+ });
+ const move = captured.find((r) => r.name === 'move');
+ if (!move?.outputSchema) throw new Error('move tool did not register an outputSchema');
+ return compileOutputSchemaForClient(move.outputSchema);
+ }
+
+ const crossScopeSuccess = {
+ ok: true,
+ kind: 'skill',
+ committed: false,
+ crossScope: true,
+ text: 'Moved skill "trip-log" (Project) → "trip-log" (Global). …',
+ };
+ const crossScopePartialFailure = {
+ ok: false,
+ kind: 'skill',
+ error: 'source delete failed',
+ bothScopes: true,
+ text: 'Partially moved skill … exists in BOTH levels …',
+ };
+
+ for (const [label, payload] of [
+ ['cross-level success', crossScopeSuccess],
+ ['cross-level partial-failure (both levels)', crossScopePartialFailure],
+ ] as const) {
+ test(`${label} structuredContent validates against the compiled move schema`, () => {
+ const validator = new AjvJsonSchemaValidator();
+ const validate = validator.getValidator(moveOutputJsonSchema());
+ const result = validate(payload) as { valid: boolean; errorMessage?: string };
+ expect(result.valid).toBe(true);
+ if (!result.valid) {
+ expect(result.errorMessage).not.toMatch(/additional propert/i);
+ }
+ });
+ }
+});
diff --git a/packages/server/src/mcp/tools/preview-url.test.ts b/packages/server/src/mcp/tools/preview-url.test.ts
index b7815bcbd..80c2d9b5b 100644
--- a/packages/server/src/mcp/tools/preview-url.test.ts
+++ b/packages/server/src/mcp/tools/preview-url.test.ts
@@ -7,7 +7,7 @@ import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';
import { acquireUiLock, updateUiLockPort } from '../../ui-lock.ts';
-import { resolvePreviewUrl } from './preview-url.ts';
+import { encodeSkillRoute, resolvePreviewUrl, resolveSkillPreviewUrl } from './preview-url.ts';
let tmpDir: string;
let lockDir: string;
@@ -64,6 +64,33 @@ describe('resolvePreviewUrl — lock edges', () => {
});
});
+describe('resolveSkillPreviewUrl', () => {
+ test('returns the route-only __skill__ url when ui.lock is bound', () => {
+ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
+ updateUiLockPort(lockDir, 5173);
+ expect(resolveSkillPreviewUrl('global', 'trip-log', { lockDir })).toEqual({
+ url: '/#/__skill__/global/trip-log',
+ source: 'lock',
+ });
+ });
+
+ test('encodes the skill name per-segment and defaults nothing (scope passed in)', () => {
+ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
+ updateUiLockPort(lockDir, 5173);
+ expect(resolveSkillPreviewUrl('project', 'run tests', { lockDir })?.url).toBe(
+ '/#/__skill__/project/run%20tests',
+ );
+ });
+
+ test('null when no UI is running', () => {
+ expect(resolveSkillPreviewUrl('project', 'x', { lockDir })).toBeNull();
+ });
+
+ test('encodeSkillRoute matches the app hash parser body (no leading #/)', () => {
+ expect(encodeSkillRoute('global', 'trip-log')).toBe('__skill__/global/trip-log');
+ });
+});
+
describe('resolvePreviewUrl — docName encoding (via lock branch)', () => {
beforeEach(() => {
acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
diff --git a/packages/server/src/mcp/tools/preview-url.ts b/packages/server/src/mcp/tools/preview-url.ts
index 012918f1a..4b3e6350b 100644
--- a/packages/server/src/mcp/tools/preview-url.ts
+++ b/packages/server/src/mcp/tools/preview-url.ts
@@ -28,6 +28,10 @@ export function encodeFolderRoute(folder: string): string {
return normalized ? `${encodeDocName(normalized)}/` : '';
}
+export function encodeSkillRoute(scope: string, name: string): string {
+ return `__skill__/${scope}/${encodeDocName(name)}`;
+}
+
type PreviewAttachWarning =
| {
action: 'attach-preview-once';
@@ -133,15 +137,22 @@ export function resolvePreviewUrl(
docName: string,
ctx: PreviewUrlContext,
): PreviewUrlResult | null {
- const hash = `/#/${encodeDocName(docName)}`;
+ return previewForRoute(`/#/${encodeDocName(docName)}`, ctx);
+}
+
+export function resolveSkillPreviewUrl(
+ scope: string,
+ name: string,
+ ctx: PreviewUrlContext,
+): PreviewUrlResult | null {
+ return previewForRoute(`/#/${encodeSkillRoute(scope, name)}`, ctx);
+}
+function previewForRoute(hash: string, ctx: PreviewUrlContext): PreviewUrlResult | null {
try {
const lock = readUiLock(ctx.lockDir);
if (lock && lock.port > 0) {
- return {
- url: hash,
- source: 'lock',
- };
+ return { url: hash, source: 'lock' };
}
} catch (err) {
process.stderr.write(
diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.ts
index cc9e66663..c03e33f8e 100644
--- a/packages/server/src/mcp/tools/registry.test.ts
+++ b/packages/server/src/mcp/tools/registry.test.ts
@@ -13,6 +13,7 @@ const EXPECTED_TOOLS = [
'search',
'history',
'links',
+ 'skills',
'config',
'palette',
'preview_url',
@@ -21,6 +22,7 @@ const EXPECTED_TOOLS = [
'edit',
'delete',
'move',
+ 'install',
'checkpoint',
'restore_version',
'conflicts',
@@ -83,13 +85,13 @@ function captureRegistered(): string[] {
return names;
}
-describe('registerAllTools — 17-tool surface (SPEC.md §9.1 / AC8)', () => {
- test('registers exactly 17 tools', () => {
+describe('registerAllTools — 19-tool surface (SPEC.md §9.1 / AC8 + PRD-6935 install + skills read)', () => {
+ test('registers exactly 19 tools', () => {
const names = captureRegistered();
- expect(names.length).toBe(17);
+ expect(names.length).toBe(19);
});
- test('the 17 expected tool names are all present', () => {
+ test('the 19 expected tool names are all present', () => {
const names = new Set(captureRegistered());
for (const expected of EXPECTED_TOOLS) {
expect(names).toContain(expected);
diff --git a/packages/server/src/mcp/tools/restore-version.ts b/packages/server/src/mcp/tools/restore-version.ts
index 849f99f49..11c766c4b 100644
--- a/packages/server/src/mcp/tools/restore-version.ts
+++ b/packages/server/src/mcp/tools/restore-version.ts
@@ -23,12 +23,13 @@ import {
} from './shared.ts';
export const DESCRIPTION = [
- '[Requires: Hocuspocus server] Restore a single document to a historical version via the CRDT layer — append-only (creates a new version with the old content; all connected editors see the change live).',
+ '[Requires: Hocuspocus server] Restore a DOCUMENT (CRDT, append-only) or a SKILL (fs-direct) to a historical version. Pass EXACTLY ONE of `document` or `skill`.',
'',
'**Parameters:**',
- '- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped).',
+ '- `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.',
'- `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). Defaults to "Restored to <sha-short>". Avoid secrets or PII — persisted to git history.',
+ '- `summary` — Optional one-line summary (≤80 chars). Avoid secrets or PII — persisted to git history.',
'',
'A response may include `structuredContent.warnings` (kind `content-divergence`) when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.',
].join('\n');
@@ -46,7 +47,16 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
{
description: DESCRIPTION,
inputSchema: {
- document: z.string().describe('Document to restore (path, no extension).'),
+ document: z
+ .string()
+ .optional()
+ .describe('Document to restore (path, no extension). Mutually exclusive with `skill`.'),
+ skill: z
+ .string()
+ .optional()
+ .describe(
+ 'Skill name to restore (`.ok/skills/<name>/`). 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).",
),
@@ -56,23 +66,34 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
outputSchema: outputSchemaWithText({
- document: z.string().describe('The document that was restored (echo of the input).'),
- version: z
+ document: z
.string()
- .describe('The version the document was restored to (echo of the input).'),
+ .optional()
+ .describe('The document that was restored (echo of the input).'),
+ skill: z.string().optional().describe('The skill that was restored (echo of the input).'),
+ version: z.string().describe('The version that was restored to (echo of the input).'),
+ restoredFiles: z
+ .array(z.string())
+ .optional()
+ .describe('Skill restore only: the skill-dir-relative files rewritten.'),
previewUrl: previewUrlOutputField,
previewUrlSource: previewUrlSourceField,
summary: summaryOutputSchema.optional(),
warnings: z
- .array(AdvisoryWarningSchema)
- .min(1)
+ .union([z.array(z.string()), z.array(AdvisoryWarningSchema)])
.optional()
.describe(
- 'Advisory entries (kind `content-divergence`): present only when the restored Y.Text did not byte-match the target version.',
+ 'Skill restore: plain warning strings. Document restore: advisory entries (kind `content-divergence`) present only when the restored Y.Text did not byte-match the target version.',
),
}),
},
- async (args: { document: string; version: string; summary?: string; cwd?: string }) => {
+ async (args: {
+ document?: string;
+ skill?: string;
+ version: string;
+ summary?: string;
+ cwd?: string;
+ }) => {
const context = await resolveProjectServerContext(
deps.resolveCwd,
deps.config,
@@ -83,7 +104,37 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
const { cwd, url } = context;
if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
- const normalized = normalizeDocName(args.document);
+ if ((args.document !== undefined) === (args.skill !== undefined)) {
+ return textResult('Error: pass EXACTLY ONE of `document` or `skill`.', true);
+ }
+
+ if (args.skill !== undefined) {
+ const result = await httpPost(url, '/api/skill/restore', {
+ scope: 'project',
+ name: args.skill,
+ version: args.version,
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const restoredFiles = Array.isArray(result.restoredFiles)
+ ? (result.restoredFiles as string[])
+ : [];
+ const warnings = Array.isArray(result.warnings) ? (result.warnings as string[]) : [];
+ const lines = [
+ `Restored skill "${args.skill}" to version ${args.version.slice(0, 8)} (${restoredFiles.length} file(s)).`,
+ ...warnings,
+ ];
+ return textPlusStructured(lines.join('\n'), {
+ skill: args.skill,
+ version: args.version,
+ restoredFiles,
+ warnings,
+ previewUrl: null,
+ });
+ }
+
+ const normalized = normalizeDocName(args.document as string);
if (!normalized.ok) return textResult(normalized.error, true);
const docName = normalized.docName;
diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.ts
index dd08cf9b6..31129c62f 100644
--- a/packages/server/src/mcp/tools/shared.test.ts
+++ b/packages/server/src/mcp/tools/shared.test.ts
@@ -7,6 +7,7 @@ import {
httpGet,
httpPost,
normalizeDocName,
+ okReservedPathRedirect,
outputSchemaWithText,
parseRenameCollidingPairs,
resolveProjectConfigContext,
@@ -616,3 +617,29 @@ describe('parseRenameCollidingPairs — defensive parsing at trust boundary', ()
expect(parseRenameCollidingPairs([])).toEqual([]);
});
});
+
+describe('okReservedPathRedirect', () => {
+ test('.ok/skills/ path → skill-verb redirect naming write-skill', () => {
+ const msg = okReservedPathRedirect('.ok/skills/research/SKILL');
+ expect(msg).not.toBeNull();
+ expect(msg).toContain('`skill` target');
+ expect(msg).toContain('open-knowledge-write-skill');
+ });
+
+ test('leading slash is tolerated', () => {
+ expect(okReservedPathRedirect('/.ok/skills/x/SKILL')).toContain('`skill` target');
+ });
+
+ test('.ok/templates/ path → template-verb redirect', () => {
+ expect(okReservedPathRedirect('.ok/templates/note')).toContain('`template` target');
+ });
+
+ test('other .ok/ path → generic .ok redirect', () => {
+ expect(okReservedPathRedirect('.ok/config/whatever')).toContain('not addressable as documents');
+ });
+
+ test('non-.ok path → null (normal docName error stands)', () => {
+ expect(okReservedPathRedirect('meetings/standup')).toBeNull();
+ expect(okReservedPathRedirect('docs/.hidden/x')).toBeNull();
+ });
+});
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 5745fea13..105b0cddf 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -261,6 +261,18 @@ export async function resolveProjectServerContext(
}
}
+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.';
+ }
+ if (p.startsWith('.ok/templates/')) {
+ return 'Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.';
+ }
+ return 'Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target.';
+}
+
export function normalizeDocName(
raw: string,
): { ok: true; docName: string } | { ok: false; error: string } {
@@ -339,15 +351,17 @@ export async function httpGet(
if (res.ok) {
return {
ok: false,
+ httpStatus: res.status,
error: `Server returned 2xx response with non-JSON body: ${detail}`,
};
}
return {
ok: false,
+ httpStatus: res.status,
error: `Server returned HTTP ${res.status} with non-JSON body: ${detail}`,
};
}
- return normalizeResponse(res, body);
+ return { ...normalizeResponse(res, body), httpStatus: res.status };
}
async function httpSend(
diff --git a/packages/server/src/mcp/tools/skill-target.test.ts b/packages/server/src/mcp/tools/skill-target.test.ts
new file mode 100644
index 000000000..59cfaefc6
--- /dev/null
+++ b/packages/server/src/mcp/tools/skill-target.test.ts
@@ -0,0 +1,241 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';
+import { deleteSkill, moveSkill, moveSkillCrossScope, writeSkill } from './skill-target.ts';
+
+interface ToolResult {
+ content: Array<{ type: 'text'; text: string }>;
+ isError?: boolean;
+}
+
+const text = (r: ToolResult) => r.content[0]?.text ?? '';
+
+describe('skill verb tools — server-required contract', () => {
+ test('writeSkill with no server URL returns the not-running error', async () => {
+ const r = (await writeSkill(undefined, {
+ name: 'trip-log',
+ description: 'Use when logging a trip.',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
+ });
+
+ test('deleteSkill with no server URL returns the not-running error', async () => {
+ const r = (await deleteSkill(undefined, { name: 'trip-log' })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
+ });
+
+ test('moveSkill with no server URL returns the not-running error', async () => {
+ const r = (await moveSkill(undefined, {
+ fromName: 'trip-log',
+ toName: 'fishing-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
+ });
+});
+
+describe('skill verb tools — name grammar short-circuits before the network', () => {
+ const UNREACHABLE = 'http://127.0.0.1:1';
+
+ test('writeSkill rejects an invalid name with the teaching error', async () => {
+ const r = (await writeSkill(UNREACHABLE, {
+ name: 'Bad Name!',
+ description: 'd',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('lowercase letters');
+ });
+
+ test('moveSkill rejects an invalid fromName with the teaching error', async () => {
+ const r = (await moveSkill(UNREACHABLE, {
+ fromName: 'Bad From!',
+ toName: 'fishing-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('lowercase letters');
+ });
+
+ test('moveSkillCrossScope with no server URL returns the not-running error', async () => {
+ const r = (await moveSkillCrossScope(undefined, {
+ fromScope: 'project',
+ toScope: 'global',
+ fromName: 'trip-log',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
+ });
+
+ test('moveSkillCrossScope rejects an invalid name before the network', async () => {
+ const r = (await moveSkillCrossScope(UNREACHABLE, {
+ fromScope: 'project',
+ toScope: 'global',
+ fromName: 'Bad Name!',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('lowercase letters');
+ });
+});
+
+describe('moveSkillCrossScope — write-dest-then-delete-source compose', () => {
+ const realFetch = globalThis.fetch;
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ });
+
+ function mockFetch(handler: (method: string, path: string) => Record<string, unknown>) {
+ const calls: Array<{ method: string; path: string }> = [];
+ globalThis.fetch = (async (input: string, init?: { method?: string }) => {
+ const method = init?.method ?? 'GET';
+ const url = new URL(input);
+ const path = url.pathname + url.search;
+ calls.push({ method, path });
+ const body = handler(method, path);
+ if (body.ok === false) {
+ return new Response(JSON.stringify({ error: body.error ?? 'error' }), {
+ status: typeof body.status === 'number' ? body.status : 500,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }) as typeof fetch;
+ return calls;
+ }
+
+ const getSourceExistsDestAbsent =
+ (destScope: 'global' | 'project') => (method: string, path: string) => {
+ if (method === 'GET') {
+ if (path.includes(`scope=${destScope}`))
+ return { ok: false, status: 404, error: 'not found' };
+ return { ok: true, skill: { frontmatter: { description: 'd' }, body: '## When\n\nx.' } };
+ }
+ return { ok: false, error: 'unexpected' };
+ };
+
+ test('reads source, writes destination, THEN deletes source — and prompts re-install', async () => {
+ const base = getSourceExistsDestAbsent('global');
+ const calls = mockFetch((method, path) => {
+ if (method === 'PUT') return { ok: true, created: true, path: 'trip-log/SKILL.md' };
+ if (method === 'DELETE') return { ok: true, existed: true };
+ return base(method, path);
+ });
+ const r = (await moveSkillCrossScope('http://127.0.0.1:9', {
+ fromScope: 'project',
+ toScope: 'global',
+ fromName: 'trip-log',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBeUndefined();
+ expect(calls.map((c) => c.method)).toEqual(['GET', 'GET', 'PUT', 'DELETE']);
+ expect(calls.findIndex((c) => c.method === 'PUT')).toBeLessThan(
+ calls.findIndex((c) => c.method === 'DELETE'),
+ );
+ expect(text(r)).toContain('install');
+ expect(text(r)).toContain('Global');
+ });
+
+ test('refuses to overwrite an existing destination-scope skill (collision guard)', async () => {
+ const calls = mockFetch((method) => {
+ if (method === 'GET')
+ return { ok: true, skill: { frontmatter: { description: 'd' }, body: 'x' } };
+ return { ok: false, error: 'unexpected' };
+ });
+ const r = (await moveSkillCrossScope('http://127.0.0.1:9', {
+ fromScope: 'project',
+ toScope: 'global',
+ fromName: 'trip-log',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('already exists');
+ expect(calls.some((c) => c.method === 'PUT' || c.method === 'DELETE')).toBe(false);
+ });
+
+ test('aborts before any write when the destination scope read fails transiently', async () => {
+ const calls = mockFetch((method, path) => {
+ if (method === 'GET') {
+ if (path.includes('scope=global')) return { ok: false, status: 500, error: 'db down' };
+ return { ok: true, skill: { frontmatter: { description: 'd' }, body: 'x' } };
+ }
+ return { ok: false, error: 'unexpected' };
+ });
+ const r = (await moveSkillCrossScope('http://127.0.0.1:9', {
+ fromScope: 'project',
+ toScope: 'global',
+ fromName: 'trip-log',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('could not verify');
+ expect(calls.some((c) => c.method === 'PUT' || c.method === 'DELETE')).toBe(false);
+ });
+
+ test('skips a binary bundle file (415) with a warning instead of aborting', async () => {
+ const calls = mockFetch((method, path) => {
+ if (method === 'GET') {
+ if (path.includes('/api/skill-file'))
+ return { ok: false, status: 415, error: 'unsupported media type' };
+ if (path.includes('scope=global')) return { ok: false, status: 404, error: 'not found' };
+ return {
+ ok: true,
+ skill: {
+ frontmatter: { description: 'd' },
+ body: '## When\n\nx.',
+ files: [{ path: 'references/diagram.png' }],
+ },
+ };
+ }
+ if (method === 'PUT') return { ok: true, created: true, path: 'trip-log/SKILL.md' };
+ if (method === 'DELETE') return { ok: true, existed: true };
+ return { ok: false, error: 'unexpected' };
+ });
+ const r = (await moveSkillCrossScope('http://127.0.0.1:9', {
+ fromScope: 'project',
+ toScope: 'global',
+ fromName: 'trip-log',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBeUndefined();
+ expect(text(r)).toContain('binary');
+ expect(text(r)).toContain('references/diagram.png');
+ expect(calls.some((c) => c.method === 'DELETE')).toBe(true);
+ });
+
+ test('a failed source delete reports the skill now lives in BOTH levels', async () => {
+ const base = getSourceExistsDestAbsent('global');
+ mockFetch((method, path) => {
+ if (method === 'PUT') return { ok: true, created: true };
+ if (method === 'DELETE') return { ok: false, error: 'locked' };
+ return base(method, path);
+ });
+ const r = (await moveSkillCrossScope('http://127.0.0.1:9', {
+ fromScope: 'project',
+ toScope: 'global',
+ fromName: 'trip-log',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('BOTH');
+ });
+
+ test('a failed destination write aborts WITHOUT deleting the source', async () => {
+ const base = getSourceExistsDestAbsent('project');
+ const calls = mockFetch((method, path) => {
+ if (method === 'PUT') return { ok: false, error: 'disk full' };
+ return base(method, path);
+ });
+ const r = (await moveSkillCrossScope('http://127.0.0.1:9', {
+ fromScope: 'global',
+ toScope: 'project',
+ fromName: 'trip-log',
+ toName: 'trip-log',
+ })) as ToolResult;
+ expect(r.isError).toBe(true);
+ expect(calls.some((c) => c.method === 'DELETE')).toBe(false);
+ });
+});
diff --git a/packages/server/src/mcp/tools/skill-target.ts b/packages/server/src/mcp/tools/skill-target.ts
new file mode 100644
index 000000000..dca1e814c
--- /dev/null
+++ b/packages/server/src/mcp/tools/skill-target.ts
@@ -0,0 +1,342 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+import type { AgentIdentity } from '../agent-identity.ts';
+import { resolveSkillPreviewUrl } from './preview-url.ts';
+import {
+ agentIdentityFields,
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpDelete,
+ httpGet,
+ httpPost,
+ httpPut,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+import { resolveSkillName } from './verb-schemas.ts';
+
+export type { SkillScope };
+
+interface SkillIdentity {
+ summary?: string;
+ identity?: AgentIdentity;
+}
+
+function appendIdentityParams(params: URLSearchParams, identity: AgentIdentity | undefined): void {
+ for (const [key, value] of Object.entries(agentIdentityFields(identity))) {
+ if (typeof value === 'string' && value.length > 0) params.set(key, value);
+ }
+}
+
+export async function writeSkill(
+ url: string | undefined,
+ input: {
+ scope?: SkillScope;
+ name: string;
+ description: string;
+ body?: string;
+ lockDir?: string;
+ } & SkillIdentity,
+) {
+ const resolved = resolveSkillName(input.name);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const result = await httpPut(url, '/api/skill', {
+ ...(input.scope !== undefined ? { scope: input.scope } : {}),
+ name: input.name,
+ body: input.body ?? '',
+ frontmatter: { name: input.name, description: input.description },
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
+ ...agentIdentityFields(input.identity),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const created = result.created === true;
+ 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.`,
+ ...warnings,
+ ];
+ const preview = input.lockDir
+ ? resolveSkillPreviewUrl(input.scope ?? 'project', input.name, { lockDir: input.lockDir })
+ : null;
+ return textPlusStructured(lines.join('\n'), {
+ skill: { ok: true, path, created },
+ ...(preview ? { previewUrl: preview.url, previewUrlSource: preview.source } : {}),
+ });
+}
+
+export async function fetchSkill(
+ url: string,
+ scope: SkillScope,
+ name: string,
+): Promise<
+ | { ok: true; description: string; body: string; files: Array<{ path: string }> }
+ | { ok: false; error: string; notFound: boolean }
+> {
+ const params = new URLSearchParams({ name, scope });
+ const result = await httpGet(url, `/api/skill?${params.toString()}`);
+ if (!result.ok)
+ return { ok: false, error: String(result.error), notFound: result.httpStatus === 404 };
+ const skill = result.skill as
+ | {
+ frontmatter?: { description?: unknown };
+ body?: unknown;
+ files?: Array<{ path?: unknown }>;
+ }
+ | undefined;
+ const files = Array.isArray(skill?.files)
+ ? skill.files
+ .map((f) => (typeof f?.path === 'string' ? { path: f.path } : null))
+ .filter((f): f is { path: string } => f !== null)
+ : [];
+ return {
+ ok: true,
+ description:
+ typeof skill?.frontmatter?.description === 'string' ? skill.frontmatter.description : '',
+ body: typeof skill?.body === 'string' ? skill.body : '',
+ files,
+ };
+}
+
+export async function writeSkillFile(
+ url: string | undefined,
+ input: { scope?: SkillScope; name: string; path: string; content: string } & SkillIdentity,
+) {
+ const resolved = resolveSkillName(input.name);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const result = await httpPut(url, '/api/skill-file', {
+ ...(input.scope !== undefined ? { scope: input.scope } : {}),
+ name: input.name,
+ path: input.path,
+ content: input.content,
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
+ ...agentIdentityFields(input.identity),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const created = result.created === true;
+ 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.`,
+ { skill: { ok: true, file: { path, kind, created } } },
+ );
+}
+
+export async function readSkillFile(
+ url: string,
+ scope: SkillScope,
+ name: string,
+ path: string,
+): Promise<
+ | { ok: true; path: string; kind: 'reference' | 'script'; text: string }
+ | { ok: false; error: string; status: number | undefined }
+> {
+ const params = new URLSearchParams({ name, scope, path });
+ const result = await httpGet(url, `/api/skill-file?${params.toString()}`);
+ if (!result.ok)
+ return {
+ ok: false,
+ error: String(result.error),
+ status: result.httpStatus as number | undefined,
+ };
+ return {
+ ok: true,
+ path: typeof result.path === 'string' ? result.path : path,
+ kind: result.kind === 'script' ? 'script' : 'reference',
+ text: typeof result.text === 'string' ? result.text : '',
+ };
+}
+
+export async function deleteSkillFile(
+ url: string | undefined,
+ input: { scope?: SkillScope; name: string; path: string } & SkillIdentity,
+) {
+ const resolved = resolveSkillName(input.name);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const params = new URLSearchParams({
+ name: input.name,
+ scope: input.scope ?? 'project',
+ path: input.path,
+ });
+ if (input.summary !== undefined) params.set('summary', input.summary);
+ appendIdentityParams(params, input.identity);
+ const result = await httpDelete(url, `/api/skill-file?${params.toString()}`);
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const existed = result.existed === true;
+ return textPlusStructured(
+ existed
+ ? `Deleted skill file "${input.path}" from "${input.name}".`
+ : `Skill file "${input.path}" did not exist in "${input.name}" — nothing to delete.`,
+ { skill: { ok: true, file: { path: input.path, existed } } },
+ );
+}
+
+export async function deleteSkill(
+ url: string | undefined,
+ input: { scope?: SkillScope; name: string } & SkillIdentity,
+) {
+ const resolved = resolveSkillName(input.name);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const params = new URLSearchParams({ name: input.name, scope: input.scope ?? 'project' });
+ if (input.summary !== undefined) params.set('summary', input.summary);
+ appendIdentityParams(params, input.identity);
+ const result = await httpDelete(url, `/api/skill?${params.toString()}`);
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const existed = result.existed === true;
+ return textPlusStructured(
+ existed
+ ? `Deleted skill "${input.name}".`
+ : `Skill "${input.name}" did not exist — nothing to delete.`,
+ { skill: { ok: true, existed } },
+ );
+}
+
+export async function moveSkill(
+ url: string | undefined,
+ input: { scope?: SkillScope; fromName: string; toName: string } & SkillIdentity,
+) {
+ const rf = resolveSkillName(input.fromName);
+ if (!rf.ok) return textResult(`Error: ${rf.error}`, true);
+ const rt = resolveSkillName(input.toName);
+ if (!rt.ok) return textResult(`Error: ${rt.error}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const result = await httpPost(url, '/api/skill', {
+ ...(input.scope !== undefined ? { scope: input.scope } : {}),
+ fromName: input.fromName,
+ toName: input.toName,
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
+ ...agentIdentityFields(input.identity),
+ });
+ if (!result.ok) {
+ const error = typeof result.error === 'string' ? result.error : 'Skill move failed';
+ return textPlusStructured(`Error: ${error}`, { ok: false, kind: 'skill', error }, true);
+ }
+ const committed = result.committed === true;
+ const from = typeof result.from === 'string' ? result.from : input.fromName;
+ const to = typeof result.to === 'string' ? result.to : input.toName;
+ 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.`,
+ { ok: true, kind: 'skill', committed },
+ );
+}
+
+export async function moveSkillCrossScope(
+ url: string | undefined,
+ input: {
+ fromScope: SkillScope;
+ toScope: SkillScope;
+ fromName: string;
+ toName: string;
+ } & SkillIdentity,
+) {
+ const rf = resolveSkillName(input.fromName);
+ if (!rf.ok) return textResult(`Error: ${rf.error}`, true);
+ const rt = resolveSkillName(input.toName);
+ if (!rt.ok) return textResult(`Error: ${rt.error}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+
+ const src = await fetchSkill(url, input.fromScope, input.fromName);
+ if (!src.ok) {
+ return textPlusStructured(
+ `Error: ${src.error}`,
+ { ok: false, kind: 'skill', error: src.error },
+ true,
+ );
+ }
+
+ const dest = await fetchSkill(url, input.toScope, input.toName);
+ if (dest.ok) {
+ const label = input.toScope === 'global' ? 'Global' : 'Project';
+ return textPlusStructured(
+ `Error: a ${label} skill named "${input.toName}" already exists — delete or rename it first (cross-level move will not overwrite it).`,
+ { ok: false, kind: 'skill', error: 'destination already exists' },
+ true,
+ );
+ }
+ if (!dest.notFound) {
+ return textPlusStructured(
+ `Error: could not verify the ${input.toScope} destination "${input.toName}" is free (${dest.error}); aborting before any write so an existing skill can't be overwritten. Retry once the server is reachable.`,
+ { ok: false, kind: 'skill', error: dest.error },
+ true,
+ );
+ }
+
+ const put = await httpPut(url, '/api/skill', {
+ scope: input.toScope,
+ name: input.toName,
+ body: src.body,
+ frontmatter: { name: input.toName, description: src.description },
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
+ ...agentIdentityFields(input.identity),
+ });
+ if (!put.ok) {
+ const error = typeof put.error === 'string' ? put.error : 'Skill move failed';
+ return textPlusStructured(`Error: ${error}`, { ok: false, kind: 'skill', error }, true);
+ }
+
+ const skippedBinary: string[] = [];
+ for (const file of src.files) {
+ const read = await readSkillFile(url, input.fromScope, input.fromName, file.path);
+ if (!read.ok) {
+ if (read.status === 415) {
+ skippedBinary.push(file.path);
+ continue;
+ }
+ return textPlusStructured(
+ `Error: copied skill "${input.toName}" into ${input.toScope} scope, but reading its bundle file "${file.path}" from the source failed (${read.error}); aborting before deleting the source. The original ${input.fromScope} skill is intact — retry or fix the file, then move again. (A partial ${input.toScope} copy may exist; delete it first.)`,
+ { ok: false, kind: 'skill', error: read.error },
+ true,
+ );
+ }
+ const copy = await httpPut(url, '/api/skill-file', {
+ scope: input.toScope,
+ name: input.toName,
+ path: file.path,
+ content: read.text,
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
+ ...agentIdentityFields(input.identity),
+ });
+ if (!copy.ok) {
+ const error = typeof copy.error === 'string' ? copy.error : 'bundle-file copy failed';
+ return textPlusStructured(
+ `Error: copied skill "${input.toName}" into ${input.toScope} scope, but copying its bundle file "${file.path}" failed (${error}); aborting before deleting the source. The original ${input.fromScope} skill is intact — retry. (A partial ${input.toScope} copy may exist; delete it first.)`,
+ { ok: false, kind: 'skill', error },
+ true,
+ );
+ }
+ }
+
+ const params = new URLSearchParams({ name: input.fromName, scope: input.fromScope });
+ if (input.summary !== undefined) params.set('summary', input.summary);
+ appendIdentityParams(params, input.identity);
+ const del = await httpDelete(url, `/api/skill?${params.toString()}`);
+ if (!del.ok) {
+ const error = typeof del.error === 'string' ? del.error : 'source delete failed';
+ return textPlusStructured(
+ `Partially moved skill "${input.fromName}" → ${input.toScope} scope as "${input.toName}", but deleting the ${input.fromScope}-scope original failed (${error}). The skill now exists in BOTH scopes — delete the ${input.fromScope} copy manually. Run \`install\` to project the new ${input.toScope} skill.`,
+ { ok: false, kind: 'skill', error, bothScopes: true },
+ true,
+ );
+ }
+
+ const fromLabel = input.fromScope === 'global' ? 'Global' : 'Project';
+ const toLabel = input.toScope === 'global' ? 'Global' : 'Project';
+ const skippedNote =
+ skippedBinary.length > 0
+ ? ` ${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}`,
+ {
+ ok: true,
+ kind: 'skill',
+ committed: false,
+ crossScope: true,
+ ...(skippedBinary.length > 0 ? { skippedBinaryFiles: skippedBinary } : {}),
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/skills.test.ts b/packages/server/src/mcp/tools/skills.test.ts
new file mode 100644
index 000000000..c851e03b4
--- /dev/null
+++ b/packages/server/src/mcp/tools/skills.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, test } from 'bun:test';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import type { ServerInstance } from './shared.ts';
+import { register as registerSkills, type SkillsToolDeps } from './skills.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 captureSkills(serverUrl: string | undefined): Handler {
+ let handler: Handler | undefined;
+ const server = {
+ registerTool(_name: string, _cfg: unknown, h: Handler) {
+ handler = h;
+ },
+ } as unknown as ServerInstance;
+ registerSkills(server, {
+ serverUrl,
+ config: BASE_CONFIG,
+ resolveCwd: async () => process.cwd(),
+ } as unknown as SkillsToolDeps);
+ if (!handler) throw new Error('tool did not register');
+ return handler;
+}
+
+const text = (r: ToolResult) => r.content.map((c) => c.text).join('\n');
+
+describe('skills read tool — bundle-file gating short-circuits before the network', () => {
+ const UNREACHABLE = 'http://127.0.0.1:1';
+
+ test('`file` without `name` returns the teaching error', async () => {
+ const handler = captureSkills(UNREACHABLE);
+ const r = await handler({ file: 'references/x.md' });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('pass `name` too');
+ });
+
+ test('`file` with an escaping path is rejected by the allowlist', async () => {
+ const handler = captureSkills(UNREACHABLE);
+ const r = await handler({ name: 'trip-log', file: 'references/../../etc/passwd' });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('..');
+ });
+
+ test('`file` outside references/ or scripts/ is rejected', async () => {
+ const handler = captureSkills(UNREACHABLE);
+ const r = await handler({ name: 'trip-log', file: 'notes/x.md' });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('references/');
+ });
+});
+
+describe('skills read tool — server-required', () => {
+ test('no server URL returns the not-running error', async () => {
+ const handler = captureSkills(undefined);
+ const r = await handler({ name: 'trip-log' });
+ expect(r.isError).toBe(true);
+ expect(text(r)).toContain('Hocuspocus server is not running');
+ });
+});
diff --git a/packages/server/src/mcp/tools/skills.ts b/packages/server/src/mcp/tools/skills.ts
new file mode 100644
index 000000000..9233a1781
--- /dev/null
+++ b/packages/server/src/mcp/tools/skills.ts
@@ -0,0 +1,187 @@
+import { z } from 'zod';
+import {
+ type ConfigOrResolver,
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpGet,
+ outputSchemaWithText,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ type ServerInstance,
+ type ServerUrlOrResolver,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+import { fetchSkill, readSkillFile, type SkillScope } from './skill-target.ts';
+import { resolveSkillFilePath, SkillScopeArg } from './verb-schemas.ts';
+
+function bundleFileKind(path: string): 'reference' | 'script' {
+ return path.replace(/\\/g, '/').startsWith('scripts/') ? 'script' : 'reference';
+}
+
+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).";
+
+/** 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. */
+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
+ .boolean()
+ .optional()
+ .describe('Starter-pack skills only: a newer bundled version is available.'),
+});
+
+const SkillBundleFileEntrySchema = z.object({
+ path: z.string().describe('Skill-relative path (e.g. "references/tiers.md").'),
+ kind: z
+ .enum(['reference', 'script'])
+ .describe('`reference` (under references/) or `script` (under scripts/).'),
+});
+
+const SkillReadOutputSchema = z.object({
+ name: z.string().describe('Skill name (its identity).'),
+ scope: z.enum(['project', 'global']).describe(SCOPE_FIELD_DESCRIBE),
+ description: z.string().describe("The skill's one-line description (empty if none)."),
+ body: z.string().describe('The SKILL.md body (markdown, frontmatter stripped).'),
+ files: z
+ .array(SkillBundleFileEntrySchema)
+ .describe('Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.'),
+});
+
+const SkillFileReadOutputSchema = z.object({
+ path: z.string().describe('Skill-relative path read.'),
+ kind: z.enum(['reference', 'script']).describe('`reference` or `script`.'),
+ text: z.string().describe('Full text of the bundle file.'),
+});
+
+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.',
+ '',
+ '**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`.',
+ "- **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');
+
+export interface SkillsToolDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+}
+
+export function register(server: ServerInstance, deps: SkillsToolDeps): void {
+ server.registerTool(
+ 'skills',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ name: z
+ .string()
+ .optional()
+ .describe('Omit to LIST all skills; pass a skill name to READ that skill.'),
+ file: z
+ .string()
+ .optional()
+ .describe(
+ 'With `name`: read ONE bundle file by its skill-relative path (`references/...`/`scripts/...`).',
+ ),
+ scope: SkillScopeArg.optional(),
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ skills: z
+ .array(SkillListEntryOutputSchema)
+ .optional()
+ .describe('Present in LIST mode: every skill across Project + Global levels.'),
+ skill: SkillReadOutputSchema.optional().describe(
+ 'Present in READ-skill mode: the named skill (description, body, files list).',
+ ),
+ file: SkillFileReadOutputSchema.optional().describe(
+ 'Present in READ-file mode: one bundle file (path, kind, text).',
+ ),
+ }),
+ },
+ async (args: { name?: string; file?: string; scope?: SkillScope; cwd?: string }) => {
+ const context = await resolveProjectServerContext(
+ deps.resolveCwd,
+ deps.config,
+ deps.serverUrl,
+ args.cwd,
+ );
+ if (!context.ok) return textResult(`Error: ${context.error}`, true);
+ const { url } = context;
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+
+ if (args.file !== undefined && args.name === undefined) {
+ return textResult(
+ 'Error: `file` reads ONE bundle file of a skill — pass `name` too: skills({ name, file: "references/x.md" }).',
+ true,
+ );
+ }
+ if (args.file !== undefined) {
+ const check = resolveSkillFilePath(args.file);
+ if (!check.ok) return textResult(`Error: ${check.error}`, true);
+ }
+
+ 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 skills = rawSkills.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 } : {}),
+ }));
+ return textPlusStructured(JSON.stringify({ skills }, null, 2), { skills });
+ }
+
+ 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 matches = rows.filter((s) => s.name === args.name);
+ if (matches.length === 0) {
+ return textResult(`Error: no skill named "${args.name}" (Project or Global).`, true);
+ }
+ scope =
+ matches.find((s) => s.scope === 'project') !== undefined
+ ? 'project'
+ : (matches[0]?.scope as SkillScope);
+ }
+
+ if (args.file !== undefined) {
+ const fileRead = await readSkillFile(url, scope, args.name, 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 });
+ }
+
+ const read = await fetchSkill(url, scope, args.name);
+ if (!read.ok) return textResult(`Error: ${read.error}`, true);
+ const skill = {
+ name: args.name,
+ scope,
+ description: read.description,
+ body: read.body,
+ files: read.files.map((f) => ({ path: f.path, kind: bundleFileKind(f.path) })),
+ };
+ return textPlusStructured(JSON.stringify({ skill }, null, 2), { skill });
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/verb-schemas.test.ts b/packages/server/src/mcp/tools/verb-schemas.test.ts
index 74c17255d..d105c3ead 100644
--- a/packages/server/src/mcp/tools/verb-schemas.test.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
-import { DocExtensionArg, FrontmatterArg } from './verb-schemas.ts';
+import { DocExtensionArg, FrontmatterArg, resolveSkillFilePath } from './verb-schemas.ts';
describe('FrontmatterArg — recursive value contract (PRD-6947)', () => {
test('flat scalar values still parse (regression guard for the pre-PRD-6947 contract)', () => {
@@ -90,3 +90,51 @@ describe('DocExtensionArg — explicit on-create file format', () => {
expect(description).toContain('default');
});
});
+
+describe('resolveSkillFilePath — bundle-file path allowlist', () => {
+ test('accepts references/** and scripts/** with a leaf, reporting kind', () => {
+ const ref = resolveSkillFilePath('references/tiers.md');
+ expect(ref.ok).toBe(true);
+ if (ref.ok) {
+ expect(ref.path).toBe('references/tiers.md');
+ expect(ref.kind).toBe('reference');
+ }
+ const script = resolveSkillFilePath('scripts/run.sh');
+ expect(script.ok).toBe(true);
+ if (script.ok) expect(script.kind).toBe('script');
+ const nested = resolveSkillFilePath('references/topic/deep.md');
+ expect(nested.ok).toBe(true);
+ if (nested.ok) expect(nested.kind).toBe('reference');
+ });
+
+ test('rejects `..` traversal, absolute paths, and other top-level dirs', () => {
+ for (const bad of [
+ 'references/../../etc/passwd',
+ '../escape.md',
+ 'references/../scripts/../../x',
+ '/abs/path.md',
+ 'C:\\windows\\system32',
+ 'SKILL.md',
+ 'notes/x.md',
+ 'assets/img.png',
+ ]) {
+ expect(resolveSkillFilePath(bad).ok).toBe(false);
+ }
+ });
+
+ test('rejects a bare allowed root with no leaf, empty, and NUL', () => {
+ expect(resolveSkillFilePath('references').ok).toBe(false);
+ expect(resolveSkillFilePath('scripts/').ok).toBe(false);
+ expect(resolveSkillFilePath('').ok).toBe(false);
+ expect(resolveSkillFilePath('references/a\x00b.md').ok).toBe(false);
+ });
+
+ test('normalizes `./` and backslash separators', () => {
+ const a = resolveSkillFilePath('./references/x.md');
+ expect(a.ok).toBe(true);
+ if (a.ok) expect(a.path).toBe('references/x.md');
+ const b = resolveSkillFilePath('scripts\\run.sh');
+ expect(b.ok).toBe(true);
+ if (b.ok) expect(b.path).toBe('scripts/run.sh');
+ });
+});
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
index f7f598526..d690cfa53 100644
--- a/packages/server/src/mcp/tools/verb-schemas.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -1,4 +1,9 @@
-import { FrontmatterValueSchema } from '@inkeep/open-knowledge-core';
+import {
+ FrontmatterValueSchema,
+ MANAGED_ARTIFACT_SCOPES,
+ SKILL_NAME_REGEX,
+ TEMPLATE_NAME_REGEX,
+} from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
@@ -38,7 +43,6 @@ export function splitTargetPath(path: string): { folder: string; name: string }
: { folder: clean.slice(0, idx), name: clean.slice(idx + 1) };
}
-const TEMPLATE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;
export const TEMPLATE_PATH_DESCRIBE =
'Template path = `<folder>/<name>` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name (letters, digits, `_`, `-` only — no dots/spaces). Stored at `<folder>/.ok/templates/<name>.md`.';
export const TEMPLATE_CONTENT_DESCRIBE =
@@ -57,6 +61,90 @@ export function resolveTemplatePath(
return { ok: true, folder, name };
}
+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".';
+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/`.';
+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.';
+
+export const SkillScopeArg = z.enum(MANAGED_ARTIFACT_SCOPES).describe(SKILL_SCOPE_DESCRIBE);
+
+export function resolveSkillName(
+ name: string,
+): { ok: true; name: string } | { ok: false; error: string } {
+ if (
+ typeof name !== 'string' ||
+ name.length === 0 ||
+ name.length > 64 ||
+ !SKILL_NAME_REGEX.test(name)
+ ) {
+ return {
+ ok: false,
+ error: `a skill name must be lowercase letters, digits, and hyphens (≤64 chars, no slashes/dots/spaces/uppercase) — ${JSON.stringify(name)} is invalid. e.g. { skill: { name: "trip-log" } }.`,
+ };
+ }
+ return { ok: true, name };
+}
+
+export const SKILL_FILES_DESCRIBE =
+ 'Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). ' +
+ '`path` is SKILL-RELATIVE and MUST live under `references/` or `scripts/` (e.g. "references/tiers.md", "scripts/run.sh") — ' +
+ 'no `../`, no absolute paths, no other top-level dir. `content` is the full text. Text only (no binary). ' +
+ 'Independent of `body`: write one reference without resending SKILL.md.';
+export const SKILL_FILE_DESCRIBE =
+ 'A single SKILL-RELATIVE bundle file path under `references/` or `scripts/` (e.g. "references/tiers.md"). ' +
+ 'For `edit`, names the one bundle file to find/replace in; for `skills`, the one file to read.';
+
+export type SkillFileKind = 'reference' | 'script';
+
+export function resolveSkillFilePath(
+ path: string,
+): { ok: true; path: string; kind: SkillFileKind } | { ok: false; error: string } {
+ if (typeof path !== 'string' || path.length === 0) {
+ return { ok: false, error: 'a skill file `path` is required (e.g. "references/tiers.md").' };
+ }
+ if (path.includes('\x00')) {
+ return { ok: false, error: 'a skill file `path` may not contain a NUL byte.' };
+ }
+ if (path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path)) {
+ return {
+ ok: false,
+ error: `a skill file \`path\` must be skill-relative, not absolute — "${path}" is rejected. e.g. { path: "references/tiers.md" }.`,
+ };
+ }
+ const segments = path
+ .replace(/\\/g, '/')
+ .split('/')
+ .filter((s) => s !== '' && s !== '.');
+ if (segments.some((s) => s === '..')) {
+ return {
+ ok: false,
+ error: `a skill file \`path\` may not contain ".." — "${path}" could escape the skill dir. Allowed roots: references/, scripts/.`,
+ };
+ }
+ const top = segments[0];
+ if (top !== 'references' && top !== 'scripts') {
+ return {
+ ok: false,
+ error: `a skill file \`path\` must start with \`references/\` or \`scripts/\` — "${path}" is not allowed. SKILL.md is authored via \`body\`.`,
+ };
+ }
+ if (segments.length < 2) {
+ return {
+ ok: false,
+ error: `a skill file \`path\` needs a file under \`${top}/\` (e.g. "${top}/notes.md") — "${path}" names only the directory.`,
+ };
+ }
+ return {
+ ok: true,
+ path: segments.join('/'),
+ kind: top === 'scripts' ? 'script' : 'reference',
+ };
+}
+
export function exactlyOneTargetError(
args: Record<string, unknown>,
keys: readonly string[],
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index bbd34947c..f63b78f62 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -38,6 +38,7 @@ import {
looseObjectArray,
nestDocResult,
normalizeDocName,
+ okReservedPathRedirect,
outputSchemaWithText,
previewAttachWarningField,
previewUrlOutputField,
@@ -48,23 +49,31 @@ import {
textPlusStructured,
textResult,
} from './shared.ts';
+import { writeSkill, writeSkillFile } from './skill-target.ts';
import {
DocExtensionArg,
exactlyOneTargetError,
FrontmatterArg,
PositionArg,
+ resolveSkillFilePath,
resolveTemplatePath,
+ SKILL_BODY_DESCRIBE,
+ SKILL_DESCRIPTION_DESCRIBE,
+ SKILL_FILES_DESCRIBE,
+ SKILL_NAME_DESCRIBE,
+ SkillScopeArg,
splitTargetPath,
TEMPLATE_CONTENT_DESCRIBE,
TEMPLATE_PATH_DESCRIBE,
} from './verb-schemas.ts';
const BASE_DESCRIPTION = [
- 'Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset` (or `documents` for a batch of docs).',
+ 'Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset` (or `documents` for a batch of docs).',
'',
'- `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..." } }`.',
'- `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.',
@@ -172,7 +181,13 @@ async function writeOneDoc(
deps: WriteDeps,
): Promise<WriteOneResult> {
const normalized = normalizeDocName(spec.path);
- if (!normalized.ok) return { docName: spec.path, ok: false, error: normalized.error };
+ if (!normalized.ok) {
+ return {
+ docName: spec.path,
+ ok: false,
+ error: okReservedPathRedirect(spec.path) ?? normalized.error,
+ };
+ }
const docName = normalized.docName;
const identity = deps.identityRef?.current;
@@ -466,6 +481,108 @@ async function handleAsset(
});
}
+async function handleSkillWrite(
+ skill: {
+ name: string;
+ scope?: 'project' | 'global';
+ description?: string;
+ body?: string;
+ files?: Array<{ path: string; content: string }>;
+ },
+ summary: string | undefined,
+ url: string | undefined,
+ deps: WriteDeps,
+ lockDir: string,
+) {
+ const identity = deps.identityRef?.current;
+ const hasSkillMd = skill.description !== undefined;
+ const files = skill.files ?? [];
+ if (!hasSkillMd && files.length === 0) {
+ return textResult(
+ 'Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.',
+ true,
+ );
+ }
+ if (skill.body !== undefined && !hasSkillMd) {
+ return textResult(
+ 'Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',
+ true,
+ );
+ }
+ for (const f of files) {
+ const resolved = resolveSkillFilePath(f.path);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ }
+
+ const fileResults: Array<{
+ path: string;
+ ok: boolean;
+ kind?: string;
+ created?: boolean;
+ error?: string;
+ }> = [];
+
+ let skillMdResult: Awaited<ReturnType<typeof writeSkill>> | null = null;
+ if (hasSkillMd) {
+ skillMdResult = await writeSkill(url, {
+ name: skill.name,
+ scope: skill.scope,
+ description: skill.description as string,
+ body: skill.body,
+ summary,
+ identity,
+ lockDir,
+ });
+ if (skillMdResult.isError) return skillMdResult;
+ }
+
+ for (const f of files) {
+ const r = await writeSkillFile(url, {
+ name: skill.name,
+ scope: skill.scope,
+ path: f.path,
+ content: f.content,
+ summary,
+ identity,
+ });
+ const struct = (r as { structuredContent?: { skill?: { file?: Record<string, unknown> } } })
+ .structuredContent;
+ if (r.isError) {
+ fileResults.push({ path: f.path, ok: false, error: r.content[0]?.text ?? 'write failed' });
+ } else {
+ const file = struct?.skill?.file ?? {};
+ fileResults.push({
+ path: f.path,
+ ok: true,
+ ...(typeof file.kind === 'string' ? { kind: file.kind } : {}),
+ ...(typeof file.created === 'boolean' ? { created: file.created } : {}),
+ });
+ }
+ }
+
+ const fileOk = fileResults.filter((r) => r.ok).length;
+ const anyFileFailed = fileResults.some((r) => !r.ok);
+ const baseStructured =
+ ((skillMdResult as { structuredContent?: Record<string, unknown> } | null)?.structuredContent as
+ | Record<string, unknown>
+ | undefined) ?? {};
+ const baseSkill = (baseStructured.skill as Record<string, unknown> | undefined) ?? { ok: true };
+ const structured: Record<string, unknown> = {
+ ...baseStructured,
+ skill: { ...baseSkill, ...(files.length > 0 ? { files: fileResults } : {}) },
+ };
+
+ const lines: string[] = [];
+ if (hasSkillMd && skillMdResult) lines.push(skillMdResult.content[0]?.text ?? '');
+ if (files.length > 0) {
+ lines.push(`${fileOk}/${files.length} bundle file(s) written.`);
+ for (const r of fileResults) {
+ lines.push(r.ok ? ` ${r.path} (${r.kind ?? 'file'})` : ` Failed ${r.path}: ${r.error}`);
+ }
+ }
+ return textPlusStructured(lines.filter(Boolean).join('\n'), structured, anyFileFailed);
+}
+
async function handleBatch(
documents: DocSpec[],
cwd: string,
@@ -664,6 +781,33 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
.describe(
'Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }',
),
+ skill: z
+ .object({
+ name: z.string().describe(SKILL_NAME_DESCRIBE),
+ description: z
+ .string()
+ .optional()
+ .describe(
+ `${SKILL_DESCRIPTION_DESCRIBE} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`,
+ ),
+ body: z.string().optional().describe(SKILL_BODY_DESCRIBE),
+ files: z
+ .array(
+ z.object({
+ path: z
+ .string()
+ .describe('Skill-relative path under `references/` or `scripts/`.'),
+ content: z.string().describe('Full text of the bundle file.'),
+ }),
+ )
+ .optional()
+ .describe(SKILL_FILES_DESCRIBE),
+ scope: SkillScopeArg.optional(),
+ })
+ .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: "..." }] } }',
+ ),
asset: z
.object({
path: z
@@ -722,6 +866,20 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
})
.optional()
.describe('Template-create result.'),
+ skill: z
+ .object({
+ ok: z.boolean(),
+ path: z.string().optional(),
+ created: z
+ .boolean()
+ .optional()
+ .describe('true if created, false if an existing skill was overwritten.'),
+ files: looseObjectArray
+ .optional()
+ .describe('Per-bundle-file results `{ path, kind, created, ok, error? }`.'),
+ })
+ .optional()
+ .describe('Skill-create result (SKILL.md and/or bundle files).'),
asset: z
.object({
ok: z.boolean(),
@@ -752,6 +910,13 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
content: string;
frontmatter: { title: string } & Record<string, unknown>;
};
+ skill?: {
+ name: string;
+ scope?: 'project' | 'global';
+ description?: string;
+ body?: string;
+ files?: Array<{ path: string; content: string }>;
+ };
asset?: { path: string; content?: string; source?: string };
documents?: DocSpec[];
summary?: string;
@@ -774,6 +939,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
'document',
'folder',
'template',
+ 'skill',
'asset',
'documents',
]);
@@ -786,6 +952,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
'document',
'folder',
'template',
+ 'skill',
'asset',
]);
if (teaching) return textResult(`Error: ${teaching}`, true);
@@ -805,6 +972,8 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
if (args.folder !== undefined) return handleFolder(args.folder, args.summary, url, deps);
if (args.template !== undefined)
return handleTemplate(args.template, args.summary, url, deps);
+ if (args.skill !== undefined)
+ return handleSkillWrite(args.skill, args.summary, url, deps, lockDir);
return handleAsset(args.asset as NonNullable<typeof args.asset>, cwd, url, deps);
},
);
diff --git a/packages/server/src/paired-write-enforcement.test.ts b/packages/server/src/paired-write-enforcement.test.ts
index e9e578b3e..07fb69f3c 100644
--- a/packages/server/src/paired-write-enforcement.test.ts
+++ b/packages/server/src/paired-write-enforcement.test.ts
@@ -38,7 +38,11 @@ const KNOWN_PAIRED_WRITE_ORIGINS = new Set<string>([
'undoOrigin',
]);
-const KNOWN_PAIRED_WRITE_ORIGIN_PROPS = new Set<string>(['session.origin', 'session.undoOrigin']);
+const KNOWN_PAIRED_WRITE_ORIGIN_PROPS = new Set<string>([
+ 'session.origin',
+ 'session.undoOrigin',
+ 'templateSession.origin',
+]);
interface TransactCall {
readonly file: string;
diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.ts
index 4163b3b66..e04a7a2cc 100644
--- a/packages/server/src/persistence.ts
+++ b/packages/server/src/persistence.ts
@@ -27,7 +27,7 @@ import { LINEAGE_EPOCH_KEY } from './auth-token-schema.ts';
import type { BacklinkIndex } from './backlink-index.ts';
import { getMsSinceLastUserTx, isDocQuiescent } from './bridge-quiescence.ts';
import { assertBridgeInvariant } from './bridge-watchdog.ts';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { isConfigDoc, isManagedArtifactDoc, isSystemDoc } from './cc1-broadcast.ts';
import { type ConfigPersistenceCtx, loadConfigDoc, storeConfigDoc } from './config-persistence.ts';
import type { ContributorEntry } from './contributor-tracker.ts';
import {
@@ -43,6 +43,12 @@ import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './external-change.ts
import { contentHash, registerWrite } from './file-watcher.ts';
import { tracedMkdir, tracedRename, tracedUnlinkSync, tracedWriteFile } from './fs-traced.ts';
import { getLogger } from './logger.ts';
+import {
+ loadManagedArtifactDoc,
+ type ManagedArtifactCtx,
+ managedArtifactContributorAttribution,
+ storeManagedArtifactDoc,
+} from './managed-artifact-persistence.ts';
import { mdManager, schema } from './md-manager.ts';
import {
incrementDeferredStoreFailures,
@@ -309,6 +315,7 @@ export interface PersistenceHandle {
flushContributors: () => Promise<void>;
waitForPendingCommits: () => Promise<void>;
readonly configPersistenceCtx: ConfigPersistenceCtx;
+ readonly managedArtifactCtx: ManagedArtifactCtx;
}
export function createPersistenceExtension(options?: PersistenceOptions): PersistenceHandle {
@@ -340,6 +347,15 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
ephemeral,
};
+ const managedArtifactLkgCache = new Map<string, string>();
+ const managedArtifactCtx: ManagedArtifactCtx = {
+ projectDir,
+ homedirOverride: options?.configHomedirOverride,
+ lkgCache: managedArtifactLkgCache,
+ setReconciledBase,
+ getReconciledBase,
+ };
+
const tripwireResetFailedDocs = new Set<string>();
const applyDiskContent = options?.applyDiskContentToDoc ?? applyDiskContentToDoc;
let pendingDeferredStoreFlushMode: 'within-branch' | 'discard-stale' | null = null;
@@ -1181,6 +1197,10 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
loadConfigDoc(document, documentName, configPersistenceCtx);
return;
}
+ if (isManagedArtifactDoc(documentName)) {
+ loadManagedArtifactDoc(document, documentName, managedArtifactCtx);
+ return;
+ }
ensureHistograms();
const started = Date.now();
return withSpan(
@@ -1275,6 +1295,31 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
await storeConfigDoc(document, documentName, lastTransactionOrigin, configPersistenceCtx);
return;
}
+ if (isManagedArtifactDoc(documentName)) {
+ const outcome = await storeManagedArtifactDoc(
+ document,
+ documentName,
+ lastTransactionOrigin,
+ managedArtifactCtx,
+ );
+ if (outcome === 'persisted') {
+ const writer = resolveWriterFromOrigin(lastTransactionOrigin, getPrincipal);
+ if (writer && writer.id !== SERVICE_WRITER.id && !writer.id.startsWith('agent-')) {
+ const attribution = managedArtifactContributorAttribution(documentName);
+ if (attribution) {
+ recordContributor(
+ attribution.docKey,
+ writer.id,
+ writer.name,
+ writer.id,
+ attribution.subject,
+ );
+ scheduleGitCommit();
+ }
+ }
+ }
+ return;
+ }
if (isBatchInProgress()) {
deferStore({ document, documentName, lastTransactionOrigin });
return;
@@ -1333,5 +1378,6 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
takeStoreDivergence,
markAgentWriteStore,
configPersistenceCtx,
+ managedArtifactCtx,
};
}
diff --git a/packages/server/src/removal-redirect-guard.ts b/packages/server/src/removal-redirect-guard.ts
index ad26f89be..e900e6b2a 100644
--- a/packages/server/src/removal-redirect-guard.ts
+++ b/packages/server/src/removal-redirect-guard.ts
@@ -1,5 +1,5 @@
import { HocuspocusAuthRejection } from './auth-token-schema.ts';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { isReservedForUserTree } from './cc1-broadcast.ts';
import {
incrementAuthDocDeleted,
incrementAuthRemovalGuardError,
@@ -25,7 +25,7 @@ export async function runRemovalRedirectGuard(
deps: RemovalRedirectGuardDeps,
): Promise<void> {
try {
- if (isSystemDoc(documentName) || isConfigDoc(documentName)) return;
+ if (isReservedForUserTree(documentName)) return;
const originEntry = deps.recentlyRemovedDocs.get(documentName);
if (originEntry === undefined) {
diff --git a/packages/server/src/seed/apply.ts b/packages/server/src/seed/apply.ts
index 97bc4dc55..ab35aa6bc 100644
--- a/packages/server/src/seed/apply.ts
+++ b/packages/server/src/seed/apply.ts
@@ -91,7 +91,7 @@ export async function applySeed(plan: ScaffoldPlan, opts: SeedOptions = {}): Pro
}
}
- const packSkillsInstalled = installPackSkill(projectDir, pack.id);
+ const packSkillsInstalled = await installPackSkill(projectDir, pack.id);
return {
applied,
diff --git a/packages/server/src/seed/install-pack-skill.test.ts b/packages/server/src/seed/install-pack-skill.test.ts
index 0366011f9..7adde17bd 100644
--- a/packages/server/src/seed/install-pack-skill.test.ts
+++ b/packages/server/src/seed/install-pack-skill.test.ts
@@ -1,7 +1,15 @@
import { describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { readInstalledSkills } from '../installed-skills-marker.ts';
import { installPackSkill } from './install-pack-skill.ts';
function setUpEditor(proj: string, editorDir: string): void {
@@ -15,54 +23,92 @@ function tmpProject(): string {
}
describe('installPackSkill', () => {
- test('installs the pack skill next to the platform skill for a set-up editor', () => {
+ test('authors the pack skill into .ok/skills + installs it for a set-up editor', async () => {
const proj = tmpProject();
setUpEditor(proj, '.claude');
- const installed = installPackSkill(proj, 'knowledge-base');
+ const installed = await installPackSkill(proj, 'knowledge-base');
expect(installed).toEqual(['Claude Code']);
+ expect(
+ existsSync(join(proj, '.ok', 'skills', 'open-knowledge-pack-knowledge-base', 'SKILL.md')),
+ ).toBe(true);
expect(
existsSync(join(proj, '.claude', 'skills', 'open-knowledge-pack-knowledge-base', 'SKILL.md')),
).toBe(true);
+ const marker = readInstalledSkills(proj).skills['open-knowledge-pack-knowledge-base'];
+ expect(marker).toBeDefined();
+ expect(marker?.scope).toBe('project');
+ expect(marker?.hosts).toEqual(['claude']);
});
- test('installs for every set-up editor (claude + cursor + codex)', () => {
+ test('installs for every set-up editor (claude + cursor + codex)', async () => {
const proj = tmpProject();
setUpEditor(proj, '.claude');
setUpEditor(proj, '.cursor');
- setUpEditor(proj, '.agents');
- expect(installPackSkill(proj, 'entity-vault').sort()).toEqual([
+ setUpEditor(proj, '.codex');
+ expect((await installPackSkill(proj, 'entity-vault')).sort()).toEqual([
'Claude Code',
'Codex',
'Cursor',
]);
+ const marker = readInstalledSkills(proj).skills['open-knowledge-pack-entity-vault'];
+ expect(marker?.hosts.sort()).toEqual(['claude', 'codex', 'cursor']);
});
- test('installs the codebase-wiki pack skill from the source assets', () => {
+ test('installs the codebase-wiki pack skill from the source assets', async () => {
const proj = tmpProject();
setUpEditor(proj, '.claude');
- expect(installPackSkill(proj, 'codebase-wiki')).toEqual(['Claude Code']);
+ expect(await installPackSkill(proj, 'codebase-wiki')).toEqual(['Claude Code']);
expect(
existsSync(join(proj, '.claude', 'skills', 'open-knowledge-pack-codebase-wiki', 'SKILL.md')),
).toBe(true);
});
- test('no-op when no editor is set up (no platform skill present)', () => {
- expect(installPackSkill(tmpProject(), 'knowledge-base')).toEqual([]);
+ test('no-op when no editor is set up (no platform skill present)', async () => {
+ const proj = tmpProject();
+ expect(await installPackSkill(proj, 'knowledge-base')).toEqual([]);
+ expect(readInstalledSkills(proj).skills['open-knowledge-pack-knowledge-base']).toBeUndefined();
+ });
+
+ test('no-op for a pack that ships no skill', async () => {
+ const proj = tmpProject();
+ setUpEditor(proj, '.claude');
+ expect(await installPackSkill(proj, 'no-such-pack')).toEqual([]);
+ expect(existsSync(join(proj, '.ok', 'skills', 'open-knowledge-pack-no-such-pack'))).toBe(false);
});
- test('no-op for a pack that ships no skill', () => {
+ test('re-seed preserves a user-edited pack skill (no rm+cp clobber)', async () => {
const proj = tmpProject();
setUpEditor(proj, '.claude');
- expect(installPackSkill(proj, 'no-such-pack')).toEqual([]);
+ await installPackSkill(proj, 'knowledge-base');
+ const sourcePath = join(
+ proj,
+ '.ok',
+ 'skills',
+ 'open-knowledge-pack-knowledge-base',
+ 'SKILL.md',
+ );
+ expect(existsSync(sourcePath)).toBe(true);
+
+ const edited =
+ '---\nname: open-knowledge-pack-knowledge-base\ndescription: my edit\n---\nmine\n';
+ writeFileSync(sourcePath, edited, 'utf-8');
+
+ const installed = await installPackSkill(proj, 'knowledge-base');
+ expect(installed).toEqual(['Claude Code']);
+ expect(readFileSync(sourcePath, 'utf-8')).toBe(edited);
+ expect(
+ existsSync(join(proj, '.claude', 'skills', 'open-knowledge-pack-knowledge-base', 'SKILL.md')),
+ ).toBe(true);
});
- test('refuses to install through an editor dir that symlinks outside the project', () => {
+ test('refuses to install through an editor dir that symlinks outside the project', async () => {
const proj = tmpProject();
const outside = tmpProject();
symlinkSync(outside, join(proj, '.claude'));
mkdirSync(join(outside, 'skills', 'open-knowledge'), { recursive: true });
writeFileSync(join(outside, 'skills', 'open-knowledge', 'SKILL.md'), '# platform\n');
- expect(installPackSkill(proj, 'knowledge-base')).toEqual([]);
+ expect(await installPackSkill(proj, 'knowledge-base')).toEqual([]);
expect(existsSync(join(outside, 'skills', 'open-knowledge-pack-knowledge-base'))).toBe(false);
+ 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 c8a200c04..50e5d6900 100644
--- a/packages/server/src/seed/install-pack-skill.ts
+++ b/packages/server/src/seed/install-pack-skill.ts
@@ -1,47 +1,73 @@
-import { existsSync, realpathSync } from 'node:fs';
-import { join, relative } from 'node:path';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ EDITOR_PROJECT_SKILL_ROOT,
+ type EditorId,
+ 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 { getLogger } from '../logger.ts';
+import { BUNDLE_SKILL_NAME } from '../skill-bundles.ts';
+import { projectSkill } from '../skill-projection.ts';
-const EDITOR_SKILL_DIRS: ReadonlyArray<{ label: string; rel: string }> = [
- { label: 'Claude Code', rel: '.claude/skills' },
- { label: 'Cursor', rel: '.cursor/skills' },
- { label: 'Codex', rel: '.agents/skills' },
-];
+const PROJECT_SKILL_EDITOR_LABELS: Partial<Record<EditorId, string>> = {
+ claude: 'Claude Code',
+ cursor: 'Cursor',
+ codex: 'Codex',
+};
-const PLATFORM_SKILL_NAME = 'open-knowledge';
+const PLATFORM_SKILL_NAME = BUNDLE_SKILL_NAME.project;
-function isContained(parent: string, child: string): boolean {
+export function resolvePackSkillSource(packId: string): { name: string; sourceDir: string } | null {
+ let sourceDir: string;
try {
- const rel = relative(realpathSync(parent), realpathSync(child));
- return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/'));
+ sourceDir = resolveBundledSkillDir(`packs/${packId}`, { checkDesktop: true });
} catch {
- return false;
+ return null;
}
+ return { name: `open-knowledge-pack-${packId}`, sourceDir };
}
-export function installPackSkill(projectDir: string, packId: string): string[] {
- let sourceDir: string;
- try {
- sourceDir = resolveBundledSkillDir(`packs/${packId}`, { checkDesktop: true });
- } catch {
- return [];
+export async function installPackSkill(projectDir: string, packId: string): Promise<string[]> {
+ const resolved = resolvePackSkillSource(packId);
+ if (!resolved) return [];
+ const { name, sourceDir } = resolved;
+
+ 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) {
+ getLogger('seed').warn(
+ { err, packId, okSkillDir },
+ 'pack skill source authoring failed — skill not installed',
+ );
+ return [];
+ }
}
- const installed: string[] = [];
- for (const { label, rel } of EDITOR_SKILL_DIRS) {
- const skillsRoot = join(projectDir, rel);
- const platformSkill = join(skillsRoot, PLATFORM_SKILL_NAME, 'SKILL.md');
- if (!existsSync(platformSkill)) continue;
- if (existsSync(skillsRoot) && !isContained(projectDir, skillsRoot)) continue;
+ 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);
- const targetDir = join(skillsRoot, `open-knowledge-pack-${packId}`);
+ if (hosts.length > 0) {
try {
- tracedRmSync(targetDir, { recursive: true, force: true });
- tracedMkdirSync(skillsRoot, { recursive: true });
- tracedCpSync(sourceDir, targetDir, { recursive: true });
- installed.push(label);
+ await recordSkillInstall(projectDir, name, {
+ hosts,
+ scope: 'project',
+ scripts: existsSync(join(okSkillDir, 'scripts')),
+ installedAt: new Date().toISOString(),
+ });
} catch {}
}
+
return installed;
}
diff --git a/packages/server/src/seed/plan.ts b/packages/server/src/seed/plan.ts
index 3240a69ca..5dc925b58 100644
--- a/packages/server/src/seed/plan.ts
+++ b/packages/server/src/seed/plan.ts
@@ -2,6 +2,7 @@ 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 { 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';
@@ -135,5 +136,13 @@ export async function planSeed(opts: SeedOptions = {}): Promise<ScaffoldPlan> {
}
}
- return { created, skipped, warnings };
+ 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 } : {}) };
}
diff --git a/packages/server/src/seed/types.ts b/packages/server/src/seed/types.ts
index 5fc01a1fe..b4ef82454 100644
--- a/packages/server/src/seed/types.ts
+++ b/packages/server/src/seed/types.ts
@@ -16,6 +16,7 @@ export interface ScaffoldPlan {
created: FileEntry[];
skipped: SkipEntry[];
warnings: string[];
+ packSkill?: { name: string; pending: boolean };
}
export interface ApplyResult {
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 79c35f398..aeb78aa71 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -15,6 +15,7 @@ import {
humanFormat,
type MarkdownManager,
type Principal,
+ parseGlobalSkillBundleDoc,
} from '@inkeep/open-knowledge-core';
import {
readConfigSafely,
@@ -32,7 +33,13 @@ import { seedBasenameIndex, seedSingleDirBasenameIndex } from './asset-walk.ts';
import { HocuspocusAuthRejection, parseHocuspocusAuthToken } from './auth-token-schema.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { shellEscape } from './bash/shell-escape.ts';
-import { CC1Broadcaster, isConfigDoc, isSystemDoc, SYSTEM_DOC_NAME } from './cc1-broadcast.ts';
+import {
+ CC1Broadcaster,
+ isConfigDoc,
+ isManagedArtifactDoc,
+ isReservedForUserTree,
+ SYSTEM_DOC_NAME,
+} from './cc1-broadcast.ts';
import { getLocalDir } from './config/paths.ts';
import {
type ConfigFileWatcherUnsubscribe,
@@ -42,6 +49,7 @@ import {
import { applyExternalConfigChange } from './config-persistence.ts';
import { isDocInConflict } from './conflict-errors.ts';
import { createConflictLifecycleSeedExtension } from './conflict-lifecycle-seed.ts';
+import { resolveProjectTemplates } from './content/templates-resolver.ts';
import { type ContentFilter, createContentFilter } from './content-filter.ts';
import { getDocExtension, stripDocExtension } from './doc-extensions.ts';
import { runDocLineageGuard } from './doc-lineage-guard.ts';
@@ -84,6 +92,12 @@ import {
createMaintenanceCoordinator,
type MaintenanceCoordinator,
} from './maintenance-coordinator.ts';
+import {
+ applyExternalManagedArtifactChange,
+ managedArtifactDocNameForPath,
+ managedArtifactSkillsRoots,
+} from './managed-artifact-persistence.ts';
+import { startManagedArtifactWatcher, TEMPLATE_WATCH_OPTIONS } from './managed-artifact-watcher.ts';
import { recoverPendingManagedRename } from './managed-rename-journal.ts';
import { mdManager, schema } from './md-manager.ts';
import {
@@ -379,11 +393,11 @@ export function createServer(options: ServerOptions): ServerInstance {
onSizeChange: (size) => setRecentlyRemovedDocsSize(size),
});
const onUpstreamRename = (oldDocName: string, newDocName: string): void => {
- if (isSystemDoc(oldDocName) || isConfigDoc(oldDocName)) return;
+ if (isReservedForUserTree(oldDocName)) return;
recentlyRemovedDocs.setRenamed(oldDocName, newDocName);
};
const onUpstreamDelete = (docName: string): void => {
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isReservedForUserTree(docName)) return;
if (recentlyRemovedDocs.peek(docName)?.kind === 'renamed') {
console.info(
JSON.stringify({
@@ -397,7 +411,7 @@ export function createServer(options: ServerOptions): ServerInstance {
recentlyRemovedDocs.setDeleted(docName);
};
const onUpstreamAdd = (docName: string): void => {
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isReservedForUserTree(docName)) return;
recentlyRemovedDocs.delete(docName);
};
@@ -498,7 +512,7 @@ export function createServer(options: ServerOptions): ServerInstance {
onFlushCommit: () => maintenanceCoordinator?.noteFlushCommit(),
onDiskFlush: (docName, sv, persistedMarkdown, previousMarkdown) => {
cc1Broadcaster?.emitDiskAck(docName, sv);
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isReservedForUserTree(docName)) return;
if (!assetReferencesChanged(previousMarkdown, persistedMarkdown)) return;
invalidateReferencedAssetsCache?.();
signalChannel('files');
@@ -526,7 +540,7 @@ export function createServer(options: ServerOptions): ServerInstance {
return true;
}
const name = document.name;
- if (isSystemDoc(name) || isConfigDoc(name)) return false;
+ if (isReservedForUserTree(name)) return false;
if (getReconciledBase(name) !== undefined) return false;
if (document.getXmlFragment('default').length !== 0) return false;
if (document.getText('source').length !== 0) return false;
@@ -609,7 +623,9 @@ export function createServer(options: ServerOptions): ServerInstance {
const configDocAdmissionGuard: Extension & { __kind: 'config-doc-admission-guard' } = {
__kind: 'config-doc-admission-guard',
async onAuthenticate(payload) {
- if (!isConfigDoc(payload.documentName)) return;
+ if (!isConfigDoc(payload.documentName) && !isManagedArtifactDoc(payload.documentName)) {
+ return;
+ }
const req = payload.request as unknown as {
socket?: { remoteAddress?: string };
headers?: { host?: string };
@@ -717,10 +733,14 @@ export function createServer(options: ServerOptions): ServerInstance {
projectDir,
resolveEmbed,
getPrincipal: () => loadedPrincipal,
+ homeDirOverride: configHomedirOverride,
forceUnloadDocument,
ready,
recentlyRemovedDocs,
serializeDoc,
+ evictManagedArtifactLkg: (docName: string) => {
+ persistence.managedArtifactCtx.lkgCache.delete(docName);
+ },
semanticSearch,
getSemanticSimilarityFloor: () => readSemanticSearchConfig().similarityFloor,
embeddingsSecretsFile: secretsFilePath(configHomedirOverride),
@@ -795,7 +815,7 @@ export function createServer(options: ServerOptions): ServerInstance {
if (!assetBasename) return;
const needle = `[[${assetBasename}]]`;
for (const [docName] of hocuspocus.documents) {
- if (isSystemDoc(docName) || isConfigDoc(docName)) continue;
+ if (isReservedForUserTree(docName)) continue;
const document = hocuspocus.documents.get(docName);
if (!document) continue;
const source = document.getText('source').toString();
@@ -1225,7 +1245,7 @@ export function createServer(options: ServerOptions): ServerInstance {
const rescueFailed: string[] = [];
if (shadowRef.current) {
for (const docName of stillLoaded) {
- if (isSystemDoc(docName) || isConfigDoc(docName)) continue;
+ if (isReservedForUserTree(docName)) continue;
try {
const ours = serializeDoc(docName);
if (ours === null) {
@@ -1767,6 +1787,75 @@ export function createServer(options: ServerOptions): ServerInstance {
}
}
+ if (!ephemeral) {
+ const reconcileManagedArtifactDisk = (absPath: string, content: string): void => {
+ const docName = managedArtifactDocNameForPath(absPath, persistence.managedArtifactCtx);
+ if (!docName) return;
+ const document = hocuspocus.documents.get(docName);
+ const outcome = applyExternalManagedArtifactChange(
+ document ?? null,
+ docName,
+ content,
+ persistence.managedArtifactCtx,
+ );
+ log.info({ docName, outcome }, '[managed-artifact-watcher] external change');
+ if (parseGlobalSkillBundleDoc(docName)) {
+ void backlinkIndex
+ .ingestGlobalSkillBundles(
+ managedArtifactSkillsRoots(persistence.managedArtifactCtx),
+ getActiveBranch(),
+ )
+ .then(() => {
+ signalChannel('backlinks');
+ signalChannel('graph');
+ })
+ .catch((err) => {
+ log.warn({ err, docName }, '[backlinks] global skill bundle re-ingest failed');
+ });
+ }
+ };
+
+ try {
+ const skillsRoots = managedArtifactSkillsRoots(persistence.managedArtifactCtx);
+ const skillsCleanup = await startManagedArtifactWatcher(
+ skillsRoots,
+ reconcileManagedArtifactDisk,
+ );
+ configFileWatcherCleanups.push({ docName: '__skill-files__', cleanup: skillsCleanup });
+ log.info({ roots: skillsRoots }, '[managed-artifact-watcher] skills started');
+ } catch (err) {
+ log.warn({ err }, '[managed-artifact-watcher] skills failed to start');
+ degraded.push('managed-artifact-watcher:skills');
+ }
+
+ try {
+ const templateFolders = new Set<string>(['']);
+ try {
+ for (const t of resolveProjectTemplates(projectDir).templates) {
+ templateFolders.add(t.source_folder);
+ }
+ } catch (err) {
+ log.warn({ err }, '[managed-artifact-watcher] template enumeration failed; root only');
+ }
+ const templateRoots = [...templateFolders].map((f) =>
+ f ? resolve(projectDir, f, '.ok', 'templates') : resolve(projectDir, '.ok', 'templates'),
+ );
+ const templateCleanup = await startManagedArtifactWatcher(
+ templateRoots,
+ reconcileManagedArtifactDisk,
+ TEMPLATE_WATCH_OPTIONS,
+ );
+ configFileWatcherCleanups.push({ docName: '__template-files__', cleanup: templateCleanup });
+ log.info(
+ { rootCount: templateRoots.length },
+ '[managed-artifact-watcher] templates started',
+ );
+ } catch (err) {
+ log.warn({ err }, '[managed-artifact-watcher] templates failed to start');
+ degraded.push('managed-artifact-watcher:templates');
+ }
+ }
+
try {
const okignorePath = resolve(contentDir, '.okignore');
const gitignorePath = resolve(projectDir, '.gitignore');
@@ -1876,6 +1965,14 @@ export function createServer(options: ServerOptions): ServerInstance {
} else {
await backlinkIndex.rebuildFromDisk(branch);
}
+ try {
+ await backlinkIndex.ingestGlobalSkillBundles(
+ managedArtifactSkillsRoots(persistence.managedArtifactCtx),
+ branch,
+ );
+ } catch (err) {
+ log.warn({ err, branch }, '[backlinks] global skill bundle ingest failed');
+ }
void backlinkIndex.saveToDisk().catch((err) => {
console.warn(`[backlinks] Failed to persist startup cache for ${branch}:`, err);
});
@@ -1959,7 +2056,7 @@ export function createServer(options: ServerOptions): ServerInstance {
: currentBranch;
const docs: ParkableDoc[] = [];
for (const [docName, document] of hocuspocus.documents) {
- if (isSystemDoc(docName) || isConfigDoc(docName)) continue;
+ if (isReservedForUserTree(docName)) continue;
let markdown: string | null = null;
document.transact(() => {
markdown = serializeDoc(docName);
@@ -2057,7 +2154,7 @@ export function createServer(options: ServerOptions): ServerInstance {
}
for (const [docName, document] of hocuspocus.documents) {
- if (isSystemDoc(docName) || isConfigDoc(docName)) continue;
+ if (isReservedForUserTree(docName)) continue;
try {
const filePath = safeContentPath(docName, contentDir);
if (!existsSync(filePath)) {
@@ -2124,6 +2221,17 @@ export function createServer(options: ServerOptions): ServerInstance {
} else {
await backlinkIndex.rebuildFromDisk(newBranch);
}
+ try {
+ await backlinkIndex.ingestGlobalSkillBundles(
+ managedArtifactSkillsRoots(persistence.managedArtifactCtx),
+ newBranch,
+ );
+ } catch (err) {
+ log.warn(
+ { err, branch: newBranch },
+ '[backlinks] branch-switch global skill bundle ingest failed',
+ );
+ }
void backlinkIndex.saveToDisk(newBranch).catch((err) => {
console.warn(`[backlinks] Failed to persist branch cache for ${newBranch}:`, err);
});
@@ -2138,7 +2246,7 @@ export function createServer(options: ServerOptions): ServerInstance {
if (shadowRef.current && info.batchKind === 'cross-branch') {
let restoredCount = 0;
for (const [docName] of hocuspocus.documents) {
- if (isSystemDoc(docName) || isConfigDoc(docName)) continue;
+ if (isReservedForUserTree(docName)) continue;
try {
const parked = await readParkedState(
shadowRef.current,
diff --git a/packages/server/src/skill-bundles.test.ts b/packages/server/src/skill-bundles.test.ts
new file mode 100644
index 000000000..fc7e64939
--- /dev/null
+++ b/packages/server/src/skill-bundles.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { BUNDLE_IDS, BUNDLE_SKILL_NAME, bundleSkillMdPath } from './skill-bundles.ts';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
+
+describe('skill-bundles (single source of truth)', () => {
+ test('declares the three shipped bundles', () => {
+ expect([...BUNDLE_IDS].sort()).toEqual(['discovery', 'project', 'write-skill']);
+ });
+
+ test('bundleSkillMdPath derives from the id (= source dir name)', () => {
+ expect(bundleSkillMdPath('write-skill')).toBe(
+ 'packages/server/assets/skills/write-skill/SKILL.md',
+ );
+ });
+
+ test('every bundle has a SKILL.md on disk whose frontmatter name matches', () => {
+ for (const id of BUNDLE_IDS) {
+ const abs = join(REPO_ROOT, bundleSkillMdPath(id));
+ expect(existsSync(abs)).toBe(true);
+ const raw = readFileSync(abs, 'utf-8');
+ const nameLine = /^name:\s*(.+)$/m.exec(raw)?.[1]?.trim();
+ expect(nameLine).toBe(BUNDLE_SKILL_NAME[id]);
+ }
+ });
+
+ test('write-skill description is within the skill contract (≤1024, no XML tags)', () => {
+ const raw = readFileSync(join(REPO_ROOT, bundleSkillMdPath('write-skill')), 'utf-8');
+ const desc = /description:\s*"([\s\S]*?)"\n/.exec(raw)?.[1] ?? '';
+ expect(desc.length).toBeGreaterThan(0);
+ expect(desc.length).toBeLessThanOrEqual(1024);
+ expect(/<\/?[A-Za-z][^>]*>/.test(desc)).toBe(false);
+ });
+});
diff --git a/packages/server/src/skill-bundles.ts b/packages/server/src/skill-bundles.ts
new file mode 100644
index 000000000..661211f98
--- /dev/null
+++ b/packages/server/src/skill-bundles.ts
@@ -0,0 +1,21 @@
+export type BundleId = 'discovery' | 'project' | 'write-skill';
+
+export const BUNDLE_SKILL_NAME: Record<BundleId, string> = {
+ discovery: 'open-knowledge-discovery',
+ project: 'open-knowledge',
+ 'write-skill': 'open-knowledge-write-skill',
+};
+
+export const BUNDLE_IDS = Object.keys(BUNDLE_SKILL_NAME) as BundleId[];
+
+export const BUNDLE_SCOPE: Record<BundleId, 'user' | 'project'> = {
+ discovery: 'user',
+ project: 'project',
+ 'write-skill': 'user',
+};
+
+export const USER_GLOBAL_BUNDLE_IDS = BUNDLE_IDS.filter((id) => BUNDLE_SCOPE[id] === 'user');
+
+export function bundleSkillMdPath(id: BundleId): string {
+ return `packages/server/assets/skills/${id}/SKILL.md`;
+}
diff --git a/packages/server/src/skill-management.test.ts b/packages/server/src/skill-management.test.ts
new file mode 100644
index 000000000..287c3f960
--- /dev/null
+++ b/packages/server/src/skill-management.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+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
new file mode 100644
index 000000000..c0da3fffe
--- /dev/null
+++ b/packages/server/src/skill-management.ts
@@ -0,0 +1,73 @@
+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');
+
+const SKILL_MANAGEMENT_REL = ['.ok', 'local', 'skill-management.json'] as const;
+const SCHEMA_VERSION = 1;
+
+export interface SkillManagement {
+ version: number;
+ manageEditorSkills: boolean;
+ decidedAt?: string;
+ surface?: string;
+}
+
+export function skillManagementPath(projectDir: string): string {
+ return join(projectDir, ...SKILL_MANAGEMENT_REL);
+}
+
+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;
+ }
+}
+
+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 });
+}
+
+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-pack-version.test.ts b/packages/server/src/skill-pack-version.test.ts
new file mode 100644
index 000000000..57f0891ed
--- /dev/null
+++ b/packages/server/src/skill-pack-version.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+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');
+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');
+ 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
new file mode 100644
index 000000000..6810b0e4a
--- /dev/null
+++ b/packages/server/src/skill-pack-version.ts
@@ -0,0 +1,78 @@
+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';
+
+export function isPackSkillName(name: string): boolean {
+ return name.startsWith(PACK_SKILL_PREFIX);
+}
+
+export function packIdFromSkillName(name: string): string | null {
+ return isPackSkillName(name) ? name.slice(PACK_SKILL_PREFIX.length) : null;
+}
+
+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;
+}
+
+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;
+ }
+}
+
+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;
+ }
+}
+
+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) };
+}
+
+export function packUpdateAvailable(
+ installedVersion: string | undefined,
+ bundledVersion: string,
+): boolean {
+ return installedVersion === undefined
+ ? true
+ : compareSemver(bundledVersion, installedVersion) > 0;
+}
+
+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-projection.test.ts b/packages/server/src/skill-projection.test.ts
new file mode 100644
index 000000000..1f4bf5266
--- /dev/null
+++ b/packages/server/src/skill-projection.test.ts
@@ -0,0 +1,194 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readlinkSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ hostSkillsRootEscapes,
+ projectSkill,
+ readSkillBundledFiles,
+ reverseProjectSkill,
+ skillHostDir,
+ validateSkillForInstall,
+} from './skill-projection.ts';
+
+let root: string;
+
+function makeSkill(
+ name: string,
+ body: string,
+ frontmatter = `name: ${name}\ndescription: Use when testing.`,
+) {
+ const dir = join(root, '.ok', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), `---\n${frontmatter}\n---\n${body}`, 'utf-8');
+ return dir;
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-projection-'));
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('validateSkillForInstall', () => {
+ test('valid skill passes', () => {
+ const dir = makeSkill('trip-log', '# Steps');
+ const v = validateSkillForInstall(dir, 'trip-log');
+ expect(v.ok).toBe(true);
+ expect(v.errors).toEqual([]);
+ expect(v.hasScripts).toBe(false);
+ });
+
+ test('rejects git conflict markers', () => {
+ const dir = makeSkill('conflicted', '<<<<<<< HEAD\nmine\n=======\ntheirs\n>>>>>>> branch');
+ const v = validateSkillForInstall(dir, 'conflicted');
+ expect(v.ok).toBe(false);
+ expect(v.errors.some((e) => e.includes('conflict markers'))).toBe(true);
+ });
+
+ test('rejects reserved open-knowledge* prefix unless allowed', () => {
+ const dir = makeSkill(
+ 'open-knowledge-mine',
+ '# x',
+ 'name: open-knowledge-mine\ndescription: d',
+ );
+ expect(validateSkillForInstall(dir, 'open-knowledge-mine').ok).toBe(false);
+ expect(
+ validateSkillForInstall(dir, 'open-knowledge-mine', { allowReservedName: true }).ok,
+ ).toBe(true);
+ });
+
+ test('allows open-knowledge-pack-* (shipped pack skills) to reinstall', () => {
+ const name = 'open-knowledge-pack-knowledge-base';
+ const dir = makeSkill(name, '# x', `name: ${name}\ndescription: d`);
+ expect(validateSkillForInstall(dir, name).ok).toBe(true);
+ });
+
+ test('rejects name != frontmatter.name and XML tags + missing frontmatter', () => {
+ expect(
+ validateSkillForInstall(makeSkill('a', 'b', 'name: other\ndescription: d'), 'a').ok,
+ ).toBe(false);
+ expect(
+ validateSkillForInstall(makeSkill('b', 'x', 'name: b\ndescription: Use <folder> here.'), 'b')
+ .ok,
+ ).toBe(false);
+ const noFm = join(root, '.ok', 'skills', 'nofm');
+ mkdirSync(noFm, { recursive: true });
+ writeFileSync(join(noFm, 'SKILL.md'), '# no frontmatter', 'utf-8');
+ expect(validateSkillForInstall(noFm, 'nofm').ok).toBe(false);
+ });
+
+ test('flags a scripts/ dir', () => {
+ const dir = makeSkill('with-scripts', '# x');
+ mkdirSync(join(dir, 'scripts'));
+ writeFileSync(join(dir, 'scripts', 'run.sh'), 'echo hi', 'utf-8');
+ expect(validateSkillForInstall(dir, 'with-scripts').hasScripts).toBe(true);
+ });
+});
+
+describe('projectSkill / reverseProjectSkill', () => {
+ 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, [
+ 'claude',
+ 'cursor',
+ 'codex',
+ 'claude-desktop',
+ ]);
+ expect(written.sort()).toEqual(['claude', 'codex', 'cursor']);
+ for (const host of ['.claude', '.cursor', '.codex']) {
+ const link = join(root, host, 'skills', 'trip-log');
+ expect(lstatSync(link).isSymbolicLink()).toBe(true);
+ expect(existsSync(join(link, 'SKILL.md'))).toBe(true);
+ expect(readlinkSync(link).startsWith('..')).toBe(true);
+ }
+
+ const removed = reverseProjectSkill('trip-log', root, ['claude', 'cursor', 'codex']);
+ expect(removed.sort()).toEqual(['claude', 'codex', 'cursor']);
+ expect(existsSync(join(root, '.claude', 'skills', 'trip-log'))).toBe(false);
+ expect(existsSync(join(dir, 'SKILL.md'))).toBe(true);
+ });
+
+ test('reverse removes a DANGLING projection symlink (source already gone) — B4', () => {
+ const dir = makeSkill('orphan', '# Steps');
+ projectSkill(dir, 'orphan', root, ['claude', 'cursor', 'codex']);
+ rmSync(dir, { recursive: true, force: true }); // links now dangle
+ const link = join(root, '.claude', 'skills', 'orphan');
+ expect(lstatSync(link).isSymbolicLink()).toBe(true); // still on disk
+ expect(existsSync(link)).toBe(false); // ...but follows to a missing target
+
+ const removed = reverseProjectSkill('orphan', root, ['claude', 'cursor', 'codex']);
+ expect(removed.sort()).toEqual(['claude', 'codex', 'cursor']);
+ for (const host of ['.claude', '.cursor', '.codex']) {
+ expect(() => lstatSync(join(root, host, 'skills', 'orphan'))).toThrow();
+ }
+ });
+
+ test('install is authoritative — replaces a legacy real-dir copy with a symlink', () => {
+ const dir = makeSkill('s', '# v1');
+ const dest = skillHostDir(root, 'claude', 's') as string;
+ mkdirSync(dest, { recursive: true });
+ writeFileSync(join(dest, 'stale.md'), 'leftover', 'utf-8');
+ expect(lstatSync(dest).isSymbolicLink()).toBe(false);
+
+ projectSkill(dir, 's', root, ['claude']);
+ expect(lstatSync(dest).isSymbolicLink()).toBe(true);
+ expect(existsSync(join(dest, 'stale.md'))).toBe(false);
+ expect(existsSync(join(dest, 'SKILL.md'))).toBe(true);
+ });
+
+ test('skillHostDir returns null for claude-desktop', () => {
+ expect(skillHostDir(root, 'claude-desktop', 'x')).toBeNull();
+ expect(skillHostDir(root, 'claude', 'x')).toContain('/.claude/skills/x');
+ });
+});
+
+describe('readSkillBundledFiles', () => {
+ test('lists bundled files as text, excludes SKILL.md, sorts, nulls binary', () => {
+ const dir = makeSkill('bundle', '# Body');
+ mkdirSync(join(dir, 'scripts'), { recursive: true });
+ mkdirSync(join(dir, 'reference'), { recursive: true });
+ writeFileSync(join(dir, 'scripts', 'run.py'), 'print("hi")\n', 'utf-8');
+ writeFileSync(join(dir, 'reference', 'notes.md'), '# Notes', 'utf-8');
+ writeFileSync(join(dir, 'logo.bin'), Buffer.from([0x89, 0x00, 0x01, 0x02]));
+
+ const files = readSkillBundledFiles(dir);
+ expect(files.map((f) => f.path)).toEqual(['logo.bin', 'reference/notes.md', 'scripts/run.py']);
+ expect(files.find((f) => f.path === 'scripts/run.py')?.text).toBe('print("hi")\n');
+ expect(files.find((f) => f.path === 'reference/notes.md')?.text).toBe('# Notes');
+ expect(files.find((f) => f.path === 'logo.bin')?.text).toBeNull();
+ });
+
+ test('absent skill dir returns empty', () => {
+ expect(readSkillBundledFiles(join(root, 'nope'))).toEqual([]);
+ });
+});
+
+describe('hostSkillsRootEscapes', () => {
+ test('false for a missing host root (created inside the project) and a normal dir', () => {
+ expect(hostSkillsRootEscapes(root, join(root, '.claude', 'skills'))).toBe(false);
+ mkdirSync(join(root, '.claude', 'skills'), { recursive: true });
+ expect(hostSkillsRootEscapes(root, join(root, '.claude', 'skills'))).toBe(false);
+ });
+
+ test('true when the host root is a symlink escaping the project', () => {
+ const outside = mkdtempSync(join(tmpdir(), 'ok-outside-'));
+ try {
+ mkdirSync(join(root, '.claude'), { recursive: true });
+ symlinkSync(outside, join(root, '.claude', 'skills'));
+ expect(hostSkillsRootEscapes(root, join(root, '.claude', 'skills'))).toBe(true);
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/src/skill-projection.ts b/packages/server/src/skill-projection.ts
new file mode 100644
index 000000000..93e6901ac
--- /dev/null
+++ b/packages/server/src/skill-projection.ts
@@ -0,0 +1,242 @@
+import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
+import {
+ containsXmlTag,
+ EDITOR_PROJECT_CONFIG_PATH,
+ EDITOR_PROJECT_SKILL_ROOT,
+ type EditorId,
+ PROJECT_SKILL_EDITOR_IDS,
+} from '@inkeep/open-knowledge-core';
+import { parse as parseYaml } from 'yaml';
+import { resolveBundledSkillDir } from './build-skill-zip.ts';
+import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedSymlinkSync } from './fs-traced.ts';
+
+export function resolvedHosts(hosts: readonly string[]): EditorId[] {
+ const valid = PROJECT_SKILL_EDITOR_IDS as readonly string[];
+ return hosts.filter((h): h is EditorId => valid.includes(h));
+}
+
+const RESERVED_SKILL_PREFIX = 'open-knowledge';
+
+export const PACK_SKILL_PREFIX = 'open-knowledge-pack-';
+
+const SHIPPED_SKILL_NAME = 'open-knowledge';
+
+const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
+const CONFLICT_MARKER_RES = [/^<{7} /m, /^={7}$/m, /^>{7} /m];
+
+function parseFrontmatter(raw: string): Record<string, unknown> | null {
+ const m = raw.match(FRONTMATTER_RE);
+ if (!m) return null;
+ try {
+ const parsed = parseYaml(m[1] ?? '');
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+export interface SkillValidity {
+ ok: boolean;
+ errors: string[];
+ hasScripts: boolean;
+}
+
+export function validateSkillForInstall(
+ skillDir: string,
+ name: string,
+ opts?: { allowReservedName?: boolean },
+): SkillValidity {
+ const errors: string[] = [];
+ const skillMd = join(skillDir, 'SKILL.md');
+ const hasScripts =
+ existsSync(join(skillDir, 'scripts')) && statSync(join(skillDir, 'scripts')).isDirectory();
+
+ const usesReservedName =
+ name.startsWith(RESERVED_SKILL_PREFIX) && !name.startsWith(PACK_SKILL_PREFIX);
+ if (!opts?.allowReservedName && usesReservedName) {
+ errors.push(
+ `"${name}" uses the reserved \`${RESERVED_SKILL_PREFIX}*\` prefix (reserved for OK's shipped skills) — choose another name.`,
+ );
+ }
+ if (!existsSync(skillMd)) {
+ errors.push(`No SKILL.md found at ${skillDir}.`);
+ return { ok: errors.length === 0, errors, 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 };
+ }
+ if (CONFLICT_MARKER_RES.some((re) => re.test(raw))) {
+ errors.push(
+ 'SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.',
+ );
+ }
+ const fm = parseFrontmatter(raw);
+ if (fm === null) {
+ errors.push('SKILL.md has no valid `---` frontmatter block (name + description required).');
+ } else {
+ const fmName = fm.name;
+ const fmDesc = fm.description;
+ if (typeof fmName !== 'string' || fmName.length === 0) {
+ errors.push('SKILL.md frontmatter.name is missing or empty.');
+ } else if (fmName !== name) {
+ errors.push(
+ `SKILL.md frontmatter.name ("${fmName}") must equal the skill directory ("${name}").`,
+ );
+ }
+ if (typeof fmDesc !== 'string' || fmDesc.length === 0) {
+ errors.push('SKILL.md frontmatter.description is missing or empty.');
+ }
+ if (
+ (typeof fmName === 'string' && containsXmlTag(fmName)) ||
+ (typeof fmDesc === 'string' && containsXmlTag(fmDesc))
+ ) {
+ errors.push(
+ 'SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.',
+ );
+ }
+ }
+ return { ok: errors.length === 0, errors, hasScripts };
+}
+
+function detectProjectConfiguredTargets(cwd: string): EditorId[] {
+ return PROJECT_SKILL_EDITOR_IDS.filter((id) => {
+ const rel = EDITOR_PROJECT_CONFIG_PATH[id];
+ return rel !== null && existsSync(resolve(cwd, rel));
+ });
+}
+
+export function resolveSkillTargets(cwd: string, explicit?: readonly string[]): EditorId[] {
+ if (explicit && explicit.length > 0) {
+ const valid = new Set<string>(PROJECT_SKILL_EDITOR_IDS);
+ return explicit.filter((id): id is EditorId => valid.has(id));
+ }
+ return detectProjectConfiguredTargets(cwd);
+}
+
+export function skillHostDir(cwd: string, editor: EditorId, name: string): string | null {
+ const root = EDITOR_PROJECT_SKILL_ROOT[editor];
+ return root === null ? null : resolve(cwd, root, name);
+}
+
+export function hostSkillsRootEscapes(cwd: string, hostRoot: string): boolean {
+ if (!existsSync(hostRoot)) return false;
+ try {
+ const rel = relative(realpathSync(cwd), realpathSync(hostRoot));
+ return rel.startsWith('..') || isAbsolute(rel);
+ } catch {
+ return true;
+ }
+}
+
+function skillLinkTarget(cwd: string, hostRoot: string, skillDir: string): string {
+ const absSkill = resolve(skillDir);
+ const fromCwd = relative(resolve(cwd), absSkill);
+ const insideProject = fromCwd !== '' && !fromCwd.startsWith('..') && !isAbsolute(fromCwd);
+ return insideProject ? relative(hostRoot, absSkill) : absSkill;
+}
+
+export function projectSkill(
+ skillDir: string,
+ name: string,
+ cwd: string,
+ targets: readonly EditorId[],
+): EditorId[] {
+ const written: EditorId[] = [];
+ for (const editor of targets) {
+ const dest = skillHostDir(cwd, editor, name);
+ if (dest === null) continue;
+ const hostRoot = dirname(dest);
+ if (hostSkillsRootEscapes(cwd, hostRoot)) continue;
+ tracedRmSync(dest, { recursive: true, force: true });
+ tracedMkdirSync(hostRoot, { recursive: true });
+ tracedSymlinkSync(skillLinkTarget(cwd, hostRoot, skillDir), dest, 'dir');
+ written.push(editor);
+ }
+ return written;
+}
+
+export function reverseProjectSkill(
+ name: string,
+ cwd: string,
+ targets: readonly EditorId[],
+): EditorId[] {
+ const removed: EditorId[] = [];
+ for (const editor of targets) {
+ const dest = skillHostDir(cwd, editor, name);
+ if (dest === null) continue;
+ let present = false;
+ try {
+ lstatSync(dest);
+ present = true;
+ } catch {
+ present = false;
+ }
+ if (!present) continue;
+ tracedRmSync(dest, { recursive: true, force: true });
+ removed.push(editor);
+ }
+ return removed;
+}
+
+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;
+}
+
+export function reverseBundleSkill(cwd: string, targets: readonly EditorId[]): EditorId[] {
+ return reverseProjectSkill(SHIPPED_SKILL_NAME, cwd, targets);
+}
+
+const MAX_BUNDLED_FILE_BYTES = 256 * 1024;
+
+function listSkillFiles(dir: string, prefix = ''): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) out.push(...listSkillFiles(join(dir, entry.name), rel));
+ else if (entry.isFile()) out.push(rel);
+ }
+ return out.sort();
+}
+
+export function readSkillBundledFiles(
+ skillDir: string,
+): Array<{ path: string; text: string | null }> {
+ if (!existsSync(skillDir)) return [];
+ const out: Array<{ path: string; text: string | null }> = [];
+ for (const rel of listSkillFiles(skillDir)) {
+ if (rel === 'SKILL.md') continue;
+ let text: string | null = null;
+ try {
+ const buf = readFileSync(join(skillDir, rel));
+ if (buf.length <= MAX_BUNDLED_FILE_BYTES && !buf.includes(0)) {
+ text = buf.toString('utf-8');
+ }
+ } catch {
+ text = null;
+ }
+ out.push({ path: rel, text });
+ }
+ return out;
+}
diff --git a/packages/server/src/skill-reconcile.test.ts b/packages/server/src/skill-reconcile.test.ts
new file mode 100644
index 000000000..62b0b9262
--- /dev/null
+++ b/packages/server/src/skill-reconcile.test.ts
@@ -0,0 +1,296 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative } from 'node:path';
+import { readInstalledSkills } from './installed-skills-marker.ts';
+import { countImportableEditorSkills, reconcileSkillInstalls } from './skill-reconcile.ts';
+
+let root: string;
+let skillsRoot: string;
+
+function makeSource(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;
+}
+
+function makeEditorCopy(editorRel: string, name: string, body = '# Steps'): string {
+ const dir = join(root, editorRel, name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: Use when testing.\n---\n${body}`,
+ );
+ return dir;
+}
+
+function isLinkToSource(editorRel: string, name: string, sourceName = name): boolean {
+ const link = join(root, editorRel, name);
+ if (!lstatSync(link).isSymbolicLink()) return false;
+ return existsSync(join(link, 'SKILL.md')) && existsSync(join(skillsRoot, sourceName, 'SKILL.md'));
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ok-reconcile-'));
+ skillsRoot = join(root, '.ok', 'skills');
+ mkdirSync(skillsRoot, { recursive: true });
+ process.env.OK_SKILL_MANAGE = '1';
+});
+afterEach(() => {
+ delete process.env.OK_SKILL_MANAGE;
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('reconcileSkillInstalls', () => {
+ test('leaves a correct managed symlink untouched', async () => {
+ const src = makeSource('trip-log');
+ mkdirSync(join(root, '.claude', 'skills'), { recursive: true });
+ const link = join(root, '.claude', 'skills', 'trip-log');
+ symlinkSync(relative(join(root, '.claude', 'skills'), src), link, 'dir');
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.healed).toEqual([]);
+ expect(r.adopted).toEqual([]);
+ expect(isLinkToSource('.claude/skills', 'trip-log')).toBe(true);
+ });
+
+ test('heals a broken / wrong-target link to point at the source', async () => {
+ makeSource('trip-log');
+ mkdirSync(join(root, '.claude', 'skills'), { recursive: true });
+ const link = join(root, '.claude', 'skills', 'trip-log');
+ symlinkSync('/nonexistent/elsewhere', link, 'dir'); // drifted link
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.healed).toContainEqual({ name: 'trip-log', editor: 'claude' });
+ expect(isLinkToSource('.claude/skills', 'trip-log')).toBe(true);
+ });
+
+ test('removes an orphan link whose source is gone', async () => {
+ mkdirSync(join(root, '.claude', 'skills'), { recursive: true });
+ const link = join(root, '.claude', 'skills', 'ghost');
+ symlinkSync('/nonexistent/elsewhere', link, 'dir');
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.orphansRemoved).toContainEqual({ name: 'ghost', editor: 'claude' });
+ expect(existsSync(link)).toBe(false);
+ });
+
+ 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' });
+ expect(readFileSync(join(skillsRoot, 'recipe', 'SKILL.md'), 'utf-8')).toContain(
+ '# Foreign body',
+ );
+ expect(isLinkToSource('.codex/skills', 'recipe')).toBe(true);
+ 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
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.replaced).toContainEqual({ name: 'dup', editor: 'claude' });
+ expect(isLinkToSource('.claude/skills', 'dup')).toBe(true);
+ });
+
+ test('frontmatter serialization-only diff → redundant (symlink), not a collision', async () => {
+ mkdirSync(join(skillsRoot, 'route-plan'), { recursive: true });
+ writeFileSync(
+ join(skillsRoot, 'route-plan', 'SKILL.md'),
+ '---\nname: route-plan\ndescription: "A long value here."\n---\n# Body\n',
+ );
+ mkdirSync(join(root, '.codex', 'skills', 'route-plan'), { recursive: true });
+ writeFileSync(
+ join(root, '.codex', 'skills', 'route-plan', 'SKILL.md'),
+ '---\nname: route-plan\ndescription: >-\n A long value\n here.\n---\n# Body\n',
+ );
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.collided).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 () => {
+ mkdirSync(join(skillsRoot, 'dx'), { recursive: true });
+ writeFileSync(
+ join(skillsRoot, 'dx', 'SKILL.md'),
+ '---\nname: dx\ndescription: Use it.\n---\n# Body\n', // source lacks argument-hint
+ );
+ mkdirSync(join(root, '.cursor', 'skills', 'dx'), { recursive: true });
+ writeFileSync(
+ join(root, '.cursor', 'skills', 'dx', 'SKILL.md'),
+ '---\nname: dx\ndescription: Use it.\nargument-hint: "[add|list]"\n---\n# Body\n', // host adds it
+ );
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.collided).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 });
+ writeFileSync(
+ join(root, '.cursor', 'skills', 'tool', 'SKILL.md'),
+ '---\nname: tool\ndescription: A different meaning entirely.\n---\n# Body\n',
+ );
+
+ 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);
+ });
+
+ test('differing sibling file (scripts/) → genuine collision even when SKILL.md matches', async () => {
+ mkdirSync(join(skillsRoot, 'gizmo', 'scripts'), { recursive: true });
+ writeFileSync(
+ join(skillsRoot, 'gizmo', 'SKILL.md'),
+ '---\nname: gizmo\ndescription: g.\n---\n# Body\n',
+ );
+ writeFileSync(join(skillsRoot, 'gizmo', 'scripts', 'run.sh'), 'echo source\n');
+ mkdirSync(join(root, '.cursor', 'skills', 'gizmo', 'scripts'), { recursive: true });
+ writeFileSync(
+ join(root, '.cursor', 'skills', 'gizmo', 'SKILL.md'),
+ '---\nname: gizmo\ndescription: g.\n---\n# Body\n', // identical manifest
+ );
+ writeFileSync(
+ join(root, '.cursor', 'skills', 'gizmo', 'scripts', 'run.sh'),
+ 'echo HOST DIFFERENT\n', // sibling code genuinely differs
+ );
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+ expect(r.collided).toContainEqual({ name: 'gizmo', editor: 'cursor' });
+ });
+
+ 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' });
+ 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', () => {
+ makeEditorCopy('.codex/skills', 'recipe', '# A');
+ makeEditorCopy('.agents/skills', 'recipe', '# A');
+ makeEditorCopy('.cursor/skills', 'planner', '# B');
+ 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');
+ mkdirSync(join(root, '.claude', 'skills'), { recursive: true });
+ symlinkSync('/nonexistent', join(root, '.claude', 'skills', 'trip-log'), 'dir');
+ 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' });
+ expect(readFileSync(join(skillsRoot, 'clash', 'SKILL.md'), 'utf-8')).toContain(
+ '# OK managed version',
+ );
+ 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);
+ expect(existsSync(join(root, '.cursor', 'skills', 'clash'))).toBe(false);
+ expect(readInstalledSkills(root).skills['clash-cursor']?.hosts).toEqual(['cursor']);
+ });
+
+ test('leaves the foreign copy untouched when the suffixed collision slot is already occupied', async () => {
+ 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 });
+
+ expect(r.collided).toEqual([]);
+ 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(readFileSync(join(skillsRoot, 'clash-cursor', 'SKILL.md'), 'utf-8')).toContain(
+ '# Already present in the suffixed slot',
+ );
+ });
+
+ test('skips a host-dir entry whose name is not a valid skill id (never adopted)', async () => {
+ makeEditorCopy('.codex/skills', 'Invalid_Name', '# Not a skill');
+ makeEditorCopy('.codex/skills', 'valid-skill', '# Real foreign skill');
+
+ const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });
+
+ expect(r.adopted).not.toContainEqual({ name: 'Invalid_Name', editor: 'codex' });
+ expect(existsSync(join(skillsRoot, 'Invalid_Name'))).toBe(false);
+ expect(lstatSync(join(root, '.codex', 'skills', 'Invalid_Name')).isDirectory()).toBe(true);
+ expect(r.adopted).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);
+ 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];
+ expect(all.find((a) => a.name === 'open-knowledge')).toBeUndefined();
+ expect(lstatSync(bundle).isSymbolicLink()).toBe(false);
+ });
+});
diff --git a/packages/server/src/skill-reconcile.ts b/packages/server/src/skill-reconcile.ts
new file mode 100644
index 000000000..6d4a27287
--- /dev/null
+++ b/packages/server/src/skill-reconcile.ts
@@ -0,0 +1,337 @@
+import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs';
+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
+import {
+ EDITOR_PROJECT_SKILL_ROOT,
+ type EditorId,
+ PROJECT_SKILL_EDITOR_IDS,
+ SKILL_NAME_REGEX,
+ stripFrontmatter,
+ unwrapFrontmatterFences,
+} from '@inkeep/open-knowledge-core';
+import { parse as parseYaml } from 'yaml';
+import {
+ tracedCpSync,
+ tracedMkdirSync,
+ tracedRenameSync,
+ tracedRmSync,
+ tracedSymlinkSync,
+} from './fs-traced.ts';
+import { readInstalledSkills, recordSkillInstall } from './installed-skills-marker.ts';
+import { getLogger } from './logger.ts';
+import { isProjectSkillManaged } from './skill-management.ts';
+import { hostSkillsRootEscapes, validateSkillForInstall } from './skill-projection.ts';
+
+const logger = getLogger('skill-reconcile');
+
+const SHIPPED_BUNDLE_NAMES = new Set(['open-knowledge', 'open-knowledge-discovery']);
+
+interface ReconcileAction {
+ name: string;
+ editor: EditorId | null;
+}
+
+export interface ReconcileResult {
+ healed: ReconcileAction[];
+ adopted: ReconcileAction[];
+ replaced: ReconcileAction[];
+ collided: ReconcileAction[];
+ orphansRemoved: ReconcileAction[];
+ skipped: ReconcileAction[];
+}
+
+interface DetectionRoot {
+ rel: string;
+ editor: EditorId | null;
+}
+
+function detectionRoots(): DetectionRoot[] {
+ const roots: DetectionRoot[] = [];
+ for (const id of PROJECT_SKILL_EDITOR_IDS) {
+ const rel = EDITOR_PROJECT_SKILL_ROOT[id];
+ if (rel !== null) roots.push({ rel, editor: id });
+ }
+ roots.push({ rel: '.agents/skills', editor: null });
+ return roots;
+}
+
+function relativeLinkTarget(hostRoot: string, sourceDir: string): string {
+ const rel = relative(hostRoot, resolve(sourceDir));
+ return isAbsolute(rel) ? resolve(sourceDir) : rel;
+}
+
+/** Beyond this total byte size we skip the byte-compare and treat the dirs as
+ * NOT equal (a collision) — runs at boot, so we don't block startup reading a
+ * multi-MB reference dataset. "Not equal" is the safe default: the collision
+ * path preserves both copies (suffix-adopt), never deletes. */
+const DIRS_EQUAL_MAX_BYTES = 1_048_576;
+
+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;
+}
+
+function parseSkillManifest(md: string): { fm: Record<string, unknown>; body: string } {
+ const { frontmatter: fenced, body } = stripFrontmatter(md);
+ let fm: Record<string, unknown> = {};
+ if (fenced !== '') {
+ try {
+ const parsed = parseYaml(unwrapFrontmatterFences(fenced));
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ fm = parsed as Record<string, unknown>;
+ }
+ } catch {}
+ }
+ return { fm, body };
+}
+
+function skillManifestsSame(mdA: string, mdB: string): boolean {
+ const a = parseSkillManifest(mdA);
+ const b = parseSkillManifest(mdB);
+ if (a.body !== b.body) return false;
+ for (const key of Object.keys(a.fm)) {
+ if (key in b.fm && JSON.stringify(a.fm[key]) !== JSON.stringify(b.fm[key])) return false;
+ }
+ return true;
+}
+
+function sameSkillModuloFrontmatter(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 compare cheaply → not-same (safe)
+ const bufA = readFileSync(fileA);
+ const bufB = readFileSync(fileB);
+ if (bufA.equals(bufB)) continue;
+ if (rel !== 'SKILL.md') return false;
+ if (!skillManifestsSame(bufA.toString('utf8'), bufB.toString('utf8'))) return false;
+ }
+ return true;
+}
+
+function listFiles(dir: string, prefix = ''): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) out.push(...listFiles(join(dir, entry.name), rel));
+ else if (entry.isFile()) out.push(rel);
+ }
+ return out.sort();
+}
+
+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 });
+ }
+}
+
+function linkInto(hostRoot: string, linkPath: string, sourceDir: string): void {
+ tracedRmSync(linkPath, { recursive: true, force: true });
+ tracedMkdirSync(hostRoot, { recursive: true });
+ tracedSymlinkSync(relativeLinkTarget(hostRoot, sourceDir), linkPath, 'dir');
+}
+
+function pointsAtSource(linkPath: string, sourceDir: string): boolean {
+ try {
+ const raw = readlinkSync(linkPath);
+ const resolved = isAbsolute(raw) ? raw : resolve(dirname(linkPath), raw);
+ return resolve(resolved) === resolve(sourceDir);
+ } catch {
+ return false;
+ }
+}
+
+export function countImportableEditorSkills(opts: {
+ projectDir: string;
+ skillsRoot: string;
+}): number {
+ 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[];
+ try {
+ entries = readdirSync(hostRoot);
+ } catch (err) {
+ logger.warn(
+ { hostRoot, err: (err as Error).message },
+ '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;
+ }
+ if (stat.isSymbolicLink() || !stat.isDirectory()) continue;
+ const sourceDir = resolve(skillsRoot, name);
+ if (
+ existsSync(sourceDir) &&
+ (dirsEqual(entryPath, sourceDir) || sameSkillModuloFrontmatter(entryPath, sourceDir))
+ ) {
+ continue;
+ }
+ importable.add(name);
+ }
+ }
+ return importable.size;
+}
+
+export async function reconcileSkillInstalls(opts: {
+ projectDir: string;
+ skillsRoot: string;
+}): Promise<ReconcileResult> {
+ const { projectDir, skillsRoot } = opts;
+ const result: ReconcileResult = {
+ healed: [],
+ adopted: [],
+ replaced: [],
+ collided: [],
+ orphansRemoved: [],
+ skipped: [],
+ };
+ const managed = isProjectSkillManaged(projectDir);
+ const markerAdds = new Map<string, Set<EditorId>>();
+ const addMarkerHost = (name: string, editor: EditorId | null) => {
+ if (editor === null) return;
+ const set = markerAdds.get(name) ?? new Set<EditorId>();
+ set.add(editor);
+ markerAdds.set(name, set);
+ };
+
+ for (const { rel, editor } of detectionRoots()) {
+ const hostRoot = resolve(projectDir, rel);
+ if (!existsSync(hostRoot)) continue;
+ if (hostSkillsRootEscapes(projectDir, hostRoot)) continue;
+
+ let entries: string[];
+ try {
+ entries = readdirSync(hostRoot);
+ } catch (err) {
+ logger.warn(
+ { hostRoot, err: (err as Error).message },
+ 'reconcile: skipped unreadable host skills root',
+ );
+ continue;
+ }
+
+ for (const name of entries) {
+ if (SHIPPED_BUNDLE_NAMES.has(name)) continue;
+ const entryPath = join(hostRoot, name);
+ const sourceDir = resolve(skillsRoot, name);
+ const sourceExists = existsSync(sourceDir);
+ try {
+ const stat = lstatSync(entryPath);
+ if (stat.isSymbolicLink()) {
+ if (pointsAtSource(entryPath, sourceDir) && sourceExists) continue; // managed, OK
+ if (sourceExists) {
+ linkInto(hostRoot, entryPath, sourceDir); // heal drifted link
+ result.healed.push({ name, editor });
+ } else {
+ tracedRmSync(entryPath, { recursive: true, force: true }); // orphan link
+ result.orphansRemoved.push({ name, editor });
+ }
+ continue;
+ }
+ if (!stat.isDirectory()) continue; // ignore stray files
+
+ if (!SKILL_NAME_REGEX.test(name)) {
+ logger.warn(
+ { skill: name, editor },
+ 'reconcile: skipping host-dir entry with a non-skill name',
+ );
+ continue;
+ }
+
+ if (
+ sourceExists &&
+ (dirsEqual(entryPath, sourceDir) || sameSkillModuloFrontmatter(entryPath, sourceDir))
+ ) {
+ linkInto(hostRoot, entryPath, sourceDir);
+ result.replaced.push({ name, editor });
+ addMarkerHost(name, editor);
+ continue;
+ }
+
+ if (!managed) {
+ result.skipped.push({ name, editor });
+ continue;
+ }
+
+ if (!sourceExists) {
+ moveDir(entryPath, sourceDir);
+ linkInto(hostRoot, entryPath, sourceDir);
+ result.adopted.push({ name, editor });
+ addMarkerHost(name, editor);
+ } else {
+ const suffixed = `${name}-${editor ?? 'agents'}`;
+ const suffixedSource = resolve(skillsRoot, suffixed);
+ if (existsSync(suffixedSource)) {
+ 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);
+ }
+ } catch (err) {
+ logger.warn({ err, skill: name, editor }, 'reconcile skipped one skill entry after error');
+ }
+ }
+ }
+
+ if (markerAdds.size > 0) {
+ const marker = readInstalledSkills(projectDir);
+ for (const [name, editors] of markerAdds) {
+ const sourceDir = resolve(skillsRoot, name);
+ if (!existsSync(sourceDir)) continue;
+ const prior = marker.skills[name];
+ const hosts = Array.from(new Set([...(prior?.hosts ?? []), ...editors]));
+ try {
+ await recordSkillInstall(projectDir, name, {
+ hosts,
+ scope: prior?.scope ?? 'project',
+ scripts: prior?.scripts ?? validateSkillForInstall(sourceDir, name).hasScripts,
+ installedAt: prior?.installedAt ?? new Date().toISOString(),
+ });
+ } catch (err) {
+ logger.warn({ err, skill: name }, 'reconcile marker update failed (non-fatal)');
+ }
+ }
+ }
+
+ return result;
+}
diff --git a/packages/server/src/skill-reproject.test.ts b/packages/server/src/skill-reproject.test.ts
new file mode 100644
index 000000000..a06d67895
--- /dev/null
+++ b/packages/server/src/skill-reproject.test.ts
@@ -0,0 +1,118 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+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;
+
+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;
+}
+
+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);
+ rmSync(join(skillsRoot, 'beta'), { recursive: true, force: true });
+
+ 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']);
+ makeSource('mismatch', 'totally-different');
+ await install('mismatch', ['claude', 'cursor']);
+
+ const r = await reprojectAllManagedSkills({
+ projectDir: root,
+ skillsRoot,
+ targets: ['claude', 'cursor'],
+ });
+
+ 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);
+ 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
new file mode 100644
index 000000000..cf5b22119
--- /dev/null
+++ b/packages/server/src/skill-reproject.ts
@@ -0,0 +1,72 @@
+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 {
+ reprojected: Array<{ name: string; hosts: string[] }>;
+ bundleHosts: EditorId[];
+}
+
+export async function reprojectAllManagedSkills(opts: {
+ projectDir: string;
+ 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) {
+ 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)',
+ );
+ }
+ reverseProjectSkill(name, projectDir, recordedHosts);
+ await recordSkillInstall(projectDir, name, { ...entry, hosts: [] });
+ reprojected.push({ name, hosts: [] });
+ continue;
+ }
+
+ 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) {
+ logger.warn({ err, skill: name }, 'reproject skipped one skill after error');
+ }
+ }
+
+ 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
new file mode 100644
index 000000000..4d9e3336e
--- /dev/null
+++ b/packages/server/src/skill-restore.ts
@@ -0,0 +1,87 @@
+import { existsSync } from 'node:fs';
+import { dirname, resolve, sep } from 'node:path';
+import { tracedMkdirSync, tracedRmSync, tracedWriteFileSync } from './fs-traced.ts';
+import { type ShadowHandle, shadowGit } from './shadow-repo.ts';
+
+function skillShadowPath(contentRoot: string, name: string): string {
+ const root = contentRoot === '.' ? '' : contentRoot.replace(/^\.\//, '');
+ return root ? `${root}/.ok/skills/${name}` : `.ok/skills/${name}`;
+}
+
+export type RestoreSkillResult =
+ | { ok: true; restoredFiles: string[] }
+ | {
+ ok: false;
+ code: 'no-shadow' | 'version-not-found' | 'skill-absent' | 'io-error' | 'path-escape';
+ error: string;
+ };
+
+export async function restoreSkillVersion(opts: {
+ shadow: ShadowHandle;
+ contentDir: string;
+ contentRoot: string;
+ name: string;
+ version: string;
+}): Promise<RestoreSkillResult> {
+ const { shadow, contentDir, contentRoot, name, version } = opts;
+ 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 fileList: string;
+ try {
+ fileList = await sg.raw('ls-tree', '-r', '--name-only', version, '--', shadowPath);
+ } catch {
+ return {
+ ok: false,
+ code: 'version-not-found',
+ error: `Version ${version.slice(0, 8)} not found.`,
+ };
+ }
+ const files = fileList
+ .split('\n')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ if (files.length === 0) {
+ return {
+ ok: false,
+ code: 'skill-absent',
+ error: `Skill "${name}" did not exist at version ${version.slice(0, 8)}.`,
+ };
+ }
+
+ const skillDirAbs = resolve(contentDir, '.ok', 'skills', name);
+ const containmentPrefix = skillDirAbs + sep;
+ const staged: Array<{ rel: string; destAbs: string; content: string }> = [];
+ for (const shadowFile of files) {
+ const rel = shadowFile.slice(shadowPath.length).replace(/^\//, '');
+ const destAbs = resolve(skillDirAbs, rel);
+ if (destAbs !== skillDirAbs && !destAbs.startsWith(containmentPrefix)) {
+ return {
+ ok: false,
+ code: 'path-escape',
+ error: `Refusing to restore path outside skill dir: ${rel}`,
+ };
+ }
+ try {
+ staged.push({ rel, destAbs, content: await sg.raw('show', `${version}:${shadowFile}`) });
+ } catch (e) {
+ return {
+ ok: false,
+ code: 'io-error',
+ error: `Failed reading ${rel} at ${version.slice(0, 8)}: ${(e as Error).message}`,
+ };
+ }
+ }
+
+ tracedRmSync(skillDirAbs, { recursive: true, force: true });
+ const restoredFiles: string[] = [];
+ for (const { rel, destAbs, content } of staged) {
+ tracedMkdirSync(dirname(destAbs), { recursive: true });
+ tracedWriteFileSync(destAbs, content, 'utf-8');
+ restoredFiles.push(rel);
+ }
+ return { ok: true, restoredFiles };
+}
diff --git a/packages/server/src/skill-state.ts b/packages/server/src/skill-state.ts
index 71a18683d..6fc94910e 100644
--- a/packages/server/src/skill-state.ts
+++ b/packages/server/src/skill-state.ts
@@ -14,7 +14,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
import { type ParsedNode, parseDocument } from 'yaml';
-import { tracedMkdir, tracedRename, tracedWriteFile } from './fs-traced.ts';
+import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
const readFileAsync = promisify(readFile);
@@ -37,12 +37,6 @@ const DEFAULT_LOGGER: SkillStateLogger = {
warn: (data, message) => console.warn(message, data),
};
-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),
-};
-
export async function readSkillStateFile(
home: string,
logger: SkillStateLogger = DEFAULT_LOGGER,
@@ -116,7 +110,7 @@ async function writeSkillStateFile(home: string, state: SkillState): Promise<voi
doc.contents = doc.createNode(parsed.data) as ParsedNode;
const serialized = doc.toString();
- await atomicWriteFile(path, serialized, { fs: TRACED_FS_ADAPTER });
+ await atomicWriteFile(path, serialized, { fs: tracedAtomicFs });
}
export async function readTargetVersion(
diff --git a/packages/server/src/skill-targets-store.test.ts b/packages/server/src/skill-targets-store.test.ts
new file mode 100644
index 000000000..c0fedd4e2
--- /dev/null
+++ b/packages/server/src/skill-targets-store.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+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
new file mode 100644
index 000000000..c49626676
--- /dev/null
+++ b/packages/server/src/skill-targets-store.ts
@@ -0,0 +1,53 @@
+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');
+
+export function skillTargetsPath(projectDir: string): string {
+ return join(projectDir, ...SKILL_TARGETS_REL);
+}
+
+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) {
+ logger.warn({ err, path }, 'skill-targets store unreadable');
+ return null;
+ }
+}
+
+export async function writeSkillTargets(
+ projectDir: string,
+ targets: SkillTargetEditor[],
+): Promise<void> {
+ 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/tag-index.test.ts b/packages/server/src/tag-index.test.ts
index 3e345cd1b..e7fbc63d6 100644
--- a/packages/server/src/tag-index.test.ts
+++ b/packages/server/src/tag-index.test.ts
@@ -235,6 +235,21 @@ describe('TagIndex', () => {
}
});
+ test('managed-artifact docs are indexed for tags', () => {
+ const { contentDir, cleanup } = tempContentDir();
+ try {
+ const idx = new TagIndex({ contentDir });
+ idx.updateDocumentFromMarkdown('__skill__/project/my-skill', '#authoring guidance\n');
+ idx.updateDocumentFromMarkdown('__template__/docs/my-template', '#scaffold note\n');
+ expect(idx.getDocsForTag('authoring')).toEqual(['__skill__/project/my-skill']);
+ expect(idx.getDocsForTag('scaffold')).toEqual(['__template__/docs/my-template']);
+ idx.deleteDocument('__skill__/project/my-skill');
+ expect(idx.getDocsForTag('authoring')).toEqual([]);
+ } finally {
+ cleanup();
+ }
+ });
+
test("getDocsForTagWithMatches surfaces each doc's authored tags under the prefix", () => {
const { contentDir, cleanup } = tempContentDir();
try {
diff --git a/packages/server/src/tag-index.ts b/packages/server/src/tag-index.ts
index f4ec064fe..72039ab7a 100644
--- a/packages/server/src/tag-index.ts
+++ b/packages/server/src/tag-index.ts
@@ -9,7 +9,7 @@ import {
tagsMatchingPrefix,
unwrapFrontmatterFences,
} from '@inkeep/open-knowledge-core';
-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';
import type { ContentFilter } from './content-filter.ts';
import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';
import { toPosix } from './path-utils.ts';
@@ -97,7 +97,7 @@ export class TagIndex {
}
updateDocumentFromMarkdown(docName: string, markdown: string): void {
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isLinkIndexExcludedDoc(docName)) return;
try {
const { frontmatter, body } = stripFrontmatter(markdown);
const yamlBody = frontmatter ? unwrapFrontmatterFences(frontmatter) : '';
@@ -121,7 +121,7 @@ export class TagIndex {
}
deleteDocument(docName: string): void {
- if (isSystemDoc(docName) || isConfigDoc(docName)) return;
+ if (isLinkIndexExcludedDoc(docName)) return;
const prior = this.state.byDoc.get(docName);
if (!prior) return;
for (const tag of prior) {
diff --git a/packages/server/src/timeline-query.test.ts b/packages/server/src/timeline-query.test.ts
index b21e97917..37ab2049a 100644
--- a/packages/server/src/timeline-query.test.ts
+++ b/packages/server/src/timeline-query.test.ts
@@ -360,6 +360,55 @@ describe('getDocumentHistory', () => {
expect(bShas).not.toContain(a1);
});
+ test('resolves a skill timeline queried by its synthetic doc name', async () => {
+ const { contentDir, shadow } = await setup();
+
+ const writer: WriterIdentity = {
+ id: 'agent-cccccccc-cccc-4ccc-cccc-cccccccccccc',
+ name: 'claude-code',
+ email: '[email protected]',
+ };
+
+ const skillDir = resolve(contentDir, '.ok', 'skills', 'my-skill');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(resolve(skillDir, 'SKILL.md'), '# My Skill v1\n');
+
+ const treeSha = await buildWipTree(shadow, 'content/docs');
+ const actor: OkActorEntry = {
+ v: 1,
+ writer_id: writer.id,
+ principal: null,
+ agent_session: writer.id.slice(6),
+ agent_type: null,
+ client_name: writer.name,
+ client_version: null,
+ label: null,
+ display_name: writer.name,
+ color_seed: writer.id,
+ docs: ['.ok/skills/my-skill'],
+ };
+ const sha = await commitWipFromTree(
+ shadow,
+ writer,
+ treeSha,
+ `wip: skill-edit: my-skill/SKILL.md\n\n${formatOkActor(actor)}`,
+ );
+
+ const result = await getDocumentHistory(
+ shadow,
+ { docName: '__skill__/project/my-skill' },
+ 'content/docs',
+ );
+ expect(result.entries.map((e) => e.sha)).toContain(sha);
+
+ const personal = await getDocumentHistory(
+ shadow,
+ { docName: '__skill__/global/my-skill' },
+ 'content/docs',
+ );
+ expect(personal.entries).toHaveLength(0);
+ });
+
test('deduplicates entries that appear in multiple ref walks', async () => {
const { contentDir, shadow } = await setup();
diff --git a/packages/server/src/timeline-query.ts b/packages/server/src/timeline-query.ts
index 2b9c54348..eab387033 100644
--- a/packages/server/src/timeline-query.ts
+++ b/packages/server/src/timeline-query.ts
@@ -6,6 +6,7 @@ import {
readContributors,
} from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { getDocExtension } from './doc-extensions.ts';
+import { managedArtifactTimelinePaths } from './managed-artifact-persistence.ts';
import {
type AncestorShaSetCache,
batchCheckExistence,
@@ -246,13 +247,27 @@ export async function getDocumentHistory(
normalizedRoot
? `${normalizedRoot}/${name}${getDocExtension(name)}`
: `${name}${getDocExtension(name)}`;
- const docPath = query.docName ? pathFor(query.docName) : undefined;
+
+ const managed = query.docName
+ ? managedArtifactTimelinePaths(query.docName)
+ : ({ managed: false } as const);
+ if (managed.managed && !managed.versioned) return EMPTY;
+ const managedFilePath = managed.managed && managed.versioned ? managed.filePath : undefined;
+ const effectiveDocName = managed.managed && managed.versioned ? managed.docKey : query.docName;
+
+ const docPath = query.docName
+ ? managedFilePath
+ ? normalizedRoot
+ ? `${normalizedRoot}/${managedFilePath}`
+ : managedFilePath
+ : pathFor(query.docName)
+ : undefined;
try {
const renameLogIndex = options?.renameLogIndex ?? getOrLoadRenameLogIndex(shadow.gitDir);
const { chain, skipped } = await withSpan('rename.expandPredecessors', undefined, async () =>
query.docName
- ? expandPredecessors(query.docName, branch, renameLogIndex)
+ ? expandPredecessors(effectiveDocName, branch, renameLogIndex)
: { chain: [], skipped: 0 },
);
const hasRenameHistory = chain.length > 1;
diff --git a/turbo.json b/turbo.json
index e99d47c58..a179d7728 100644
--- a/turbo.json
+++ b/turbo.json
@@ -59,6 +59,32 @@
"../../biome-plugins/**"
]
},
+ "test:integration:shard1": {
+ "dependsOn": ["^build"],
+ "cache": true,
+ "inputs": [
+ "src/editor/**/*.ts",
+ "src/editor/**/*.tsx",
+ "tests/integration/**/*.ts",
+ "tests/meta/**/*.ts",
+ "tests/lint-plugins/**/*.ts",
+ "../server/src/**/*.ts",
+ "../core/src/**/*.ts"
+ ]
+ },
+ "test:integration:shard2": {
+ "dependsOn": ["^build"],
+ "cache": true,
+ "inputs": [
+ "src/editor/**/*.ts",
+ "src/editor/**/*.tsx",
+ "tests/integration/**/*.ts",
+ "tests/meta/**/*.ts",
+ "tests/lint-plugins/**/*.ts",
+ "../server/src/**/*.ts",
+ "../core/src/**/*.ts"
+ ]
+ },
"test:conversion": {
"dependsOn": ["^build"],
"cache": true,