Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): copy skills when Windows refuses symlinks (PRD-8928) (#5454)

tim-inkeepfc95707e468a
diff --git a/.changeset/windows-skill-symlink-copy-fallback.md b/.changeset/windows-skill-symlink-copy-fallback.md
new file mode 100644
index 000000000..8cfc389d8
--- /dev/null
+++ b/.changeset/windows-skill-symlink-copy-fallback.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+On Windows without symlink rights (no admin or Developer Mode), adding a skill to another location now creates a copy instead of failing. Converting a location to a link explains why it can't and keeps the existing copy.
diff --git a/docs/content/features/skills/find-and-install.mdx b/docs/content/features/skills/find-and-install.mdx
index 876d633ed..a96ecd2cb 100644
--- a/docs/content/features/skills/find-and-install.mdx
+++ b/docs/content/features/skills/find-and-install.mdx
@@ -37,7 +37,7 @@ Open the skill's **Install** menu and check the tools that should use it, or **A
<Image src="/images/skills-studio/install-destinations.png" alt="The Install menu lists Claude Code, Cursor, Codex, and the shared source folder, with an All control at the top." width={1600} height={860} />
-Each checked location points at the same source, so your tools cannot drift. [Symlink skills](./symlink-skills.mdx) covers sharing a whole folder instead.
+Each checked location points at the same source, so your tools cannot drift. Where the system does not allow symlinks, such as Windows without administrator rights or Developer Mode, a location gets a copy that refreshes from the source while unedited. [Symlink skills](./symlink-skills.mdx) covers sharing a whole folder instead.
</Step>
diff --git a/docs/content/features/skills/install-team-skills.mdx b/docs/content/features/skills/install-team-skills.mdx
index 1fb9ce085..7a0d95223 100644
--- a/docs/content/features/skills/install-team-skills.mdx
+++ b/docs/content/features/skills/install-team-skills.mdx
@@ -43,7 +43,7 @@ Adding the repository does not install everything in it. Import the skills that
### Choose which AI tools get each skill
-Open a skill's **Install** menu and check the tools that should read it. Each checked location points at the same source, so the skill cannot drift between your tools.
+Open a skill's **Install** menu and check the tools that should read it. Each checked location points at the same source, so the skill cannot drift between your tools. Where the system does not allow symlinks, such as Windows without administrator rights or Developer Mode, a location gets a copy that refreshes from the source while unedited.
<Image src="/images/skills-studio/install-destinations.png" alt="The Install menu listing Claude Code, Cursor, Codex, and the shared source folder, with an All control." width={1600} height={860} />
diff --git a/docs/content/features/skills/reference.mdx b/docs/content/features/skills/reference.mdx
index 893699124..ecb60fc08 100644
--- a/docs/content/features/skills/reference.mdx
+++ b/docs/content/features/skills/reference.mdx
@@ -23,7 +23,7 @@ A new skill goes into a skills folder the project already has. OpenKnowledge nev
| Project | The project's existing skills folder (`.agents/skills/<name>/` when `.agents/` is there, else `.claude/skills/<name>/` and so on) | Other project-local editor skills directories |
| Global | The same, under your home directory | Other home editor skills directories |
-OpenKnowledge keeps one source folder per skill. Other locations use symlinks by default, so they read the same bytes. The install menu can convert a location to a copy. OpenKnowledge refreshes a recorded, unedited copy from the source when the skill watcher runs or the server starts; a source edit may reach the copy after a delay. Editing the copy directly forks it, so later refreshes preserve those edits.
+OpenKnowledge keeps one source folder per skill. Other locations use symlinks by default, so they read the same bytes. Where the system does not allow symlinks (on Windows, creating them needs administrator rights or Developer Mode), a location gets a copy instead (the API response and the `install` tool report it with `links-not-permitted`), and converting a location to a link is refused and keeps the copy. The install menu can convert a location to a copy. OpenKnowledge refreshes a recorded, unedited copy from the source when the skill watcher runs or the server starts; a source edit may reach the copy after a delay. Editing the copy directly forks it, so later refreshes preserve those edits.
**Make source** relocates the real folder. Moving between Project and Global re-creates the skill in the destination scope: history does not transfer, and the editor locations the destination scope can host are re-projected there. Its `.agents/skills` hub entry, any **Add custom path** locations, and any AI tool with no skills folder at that scope are removed at the source and not re-created at the destination; add the ones the destination scope can hold again from the destination skill. That applies to a move that succeeded: if the move fails, the same list names locations it had already removed at the source, so adding them from the destination would spread the copy the failure left behind. Project skills are versioned with project content. Global skills outside a base carry no version history.
diff --git a/docs/content/features/skills/symlink-skills.mdx b/docs/content/features/skills/symlink-skills.mdx
index 163566922..e269099bc 100644
--- a/docs/content/features/skills/symlink-skills.mdx
+++ b/docs/content/features/skills/symlink-skills.mdx
@@ -14,7 +14,7 @@ Link at whichever level matches what you want.
## Link one skill
-Open the skill's **Install** menu and check the tools that should read it, as in [Find and install skills](./find-and-install.mdx#choose-your-ai-tools). Each checked location points at the one real folder, so it cannot drift.
+Open the skill's **Install** menu and check the tools that should read it, as in [Find and install skills](./find-and-install.mdx#choose-your-ai-tools). Each checked location points at the one real folder, so it cannot drift. Where the system does not allow symlinks, such as Windows without administrator rights or Developer Mode, a location gets a copy that refreshes from the source while unedited.
## Link a whole folder
diff --git a/knip.config.ts b/knip.config.ts
index 8bf09fa19..95ee750fd 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -146,11 +146,15 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: ['yjs'],
+ ignoreDependencies: [
+ 'yjs',
+ ],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 8a60e5826..a28cc2b18 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 6fcdc23f2..4fc2c11f9 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 40b5cdfd6..9f2f6feb6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 93666af70..2a085742b 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 867598d34..878d5196b 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 0970ac12f..4ada3cf26 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index b632185e1..cbe2b705f 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,3 +1,4 @@
+
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index c530ce4ba..89bc9b4d9 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index d3767adc9..a78aeb0e4 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,3 +1,4 @@
+
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index b076f955c..e7cc69c3f 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 7935e35f8..9ddcd0730 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.ts
index aff3c3c62..07cf920ce 100644
--- a/packages/core/src/handoff/urn-ipc-registry.ts
+++ b/packages/core/src/handoff/urn-ipc-registry.ts
@@ -39,6 +39,7 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>([
'urn:ok:error:request-timeout',
'urn:ok:error:internal-server-error',
'urn:ok:error:symlink-refused',
+ 'urn:ok:error:links-not-permitted',
'urn:ok:error:derived-index-unavailable',
'urn:ok:error:loopback-required',
'urn:ok:error:invalid-origin',
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fc267cbea..fb0ba5a7c 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.ts
index c3ffd559d..d04c5e0d6 100644
--- a/packages/core/src/schemas/api/_envelope.ts
+++ b/packages/core/src/schemas/api/_envelope.ts
@@ -55,6 +55,7 @@ export const ProblemTypeSchema = z.enum([
'urn:ok:error:no-file-received',
'urn:ok:error:path-escape',
'urn:ok:error:symlink-refused',
+ 'urn:ok:error:links-not-permitted',
'urn:ok:error:method-not-allowed',
'urn:ok:error:invalid-request',
'urn:ok:error:unsupported-media-type',
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index 9c005a4c4..06b346fa5 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -837,6 +837,7 @@ export const SKILL_INSTALL_WARNING_CODES = [
'skill-fork-name-unpatched',
'place-path-invalid',
'place-fork-refused',
+ 'links-not-permitted',
] as const;
export type SkillInstallWarningCode = (typeof SKILL_INSTALL_WARNING_CODES)[number];
diff --git a/packages/server/src/api-skill-install-custom-root-reform.test.ts b/packages/server/src/api-skill-install-custom-root-reform.test.ts
new file mode 100644
index 000000000..305ef3a1a
--- /dev/null
+++ b/packages/server/src/api-skill-install-custom-root-reform.test.ts
@@ -0,0 +1,87 @@
+import { lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
+import { afterAll, beforeAll, expect, test, vi } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
+import { readSkillPlacements } from './skill-placements.ts';
+
+const isolated = vi.hoisted(() => ({ home: '' }));
+vi.mock('node:os', async (original) => ({
+ ...(await original<typeof import('node:os')>()),
+ homedir: () => isolated.home,
+}));
+
+let root: string;
+let server: BootedServer;
+beforeAll(async () => {
+ isolated.home = mkdtempSync(join(tmpdir(), 'ok-reform-home-'));
+ root = mkdtempSync(join(tmpdir(), 'ok-reform-project-'));
+ mkdirSync(join(root, '.claude'));
+ server = await bootCompositionRig(root, { configHomedirOverride: isolated.home });
+ await server.ready;
+}, 60_000);
+afterAll(async () => {
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+ rmSync(isolated.home, { recursive: true, force: true });
+});
+
+async function request(method: 'POST' | 'PUT', path: string, body: object) {
+ return rawRequest(server.port, path, {
+ method,
+ headers: { 'Content-Type': 'application/json', 'X-Request-Id': 'custom-root-reform' },
+ body: JSON.stringify(body),
+ });
+}
+
+async function setUp(name: string, customRoot: string): Promise<string> {
+ const source = join(root, '.claude/skills', name);
+ mkdirSync(source, { recursive: true });
+ writeFileSync(join(source, 'SKILL.md'), `---\nname: ${name}\ndescription: d\n---\n\nBody.\n`);
+ const declared = await request('PUT', '/api/skill-targets', {
+ folderAction: { action: 'add-root', scope: 'project', root: customRoot },
+ });
+ expect(declared.status, declared.body).toBe(200);
+ return source;
+}
+
+async function addAs(name: string, customRoot: string, mode: 'link' | 'copy') {
+ const res = await request('POST', '/api/skill/install', {
+ scope: 'project',
+ name,
+ add: [customRoot],
+ mode,
+ });
+ expect(res.status, res.body).toBe(200);
+}
+
+function placement(name: string, path: string) {
+ return readSkillPlacements(root)[name]?.find((p) => p.path === path);
+}
+
+test('re-adding a custom-root copy as a link records the link', async () => {
+ const name = 'reform-to-link';
+ await setUp(name, '.ra/skills');
+ await addAs(name, '.ra/skills', 'copy');
+ expect(placement(name, `.ra/skills/${name}`)).toMatchObject({ mode: 'copy' });
+
+ await addAs(name, '.ra/skills', 'link');
+ expect(lstatSync(join(root, '.ra/skills', name)).isSymbolicLink()).toBe(true);
+ expect(placement(name, `.ra/skills/${name}`)).toMatchObject({ mode: 'link' });
+}, 60_000);
+
+test('re-adding a custom-root link as a copy records the copy and its hash', async () => {
+ const name = 'reform-to-copy';
+ const source = await setUp(name, '.rb/skills');
+ await addAs(name, '.rb/skills', 'link');
+ expect(placement(name, `.rb/skills/${name}`)).toMatchObject({ mode: 'link' });
+
+ await addAs(name, '.rb/skills', 'copy');
+ expect(lstatSync(join(root, '.rb/skills', name)).isSymbolicLink()).toBe(false);
+ expect(placement(name, `.rb/skills/${name}`)).toMatchObject({
+ mode: 'copy',
+ hash: parseSkillDir(source)?.contentHash,
+ });
+}, 60_000);
diff --git a/packages/server/src/api-skill-install-symlink-eperm.test.ts b/packages/server/src/api-skill-install-symlink-eperm.test.ts
new file mode 100644
index 000000000..aee815abe
--- /dev/null
+++ b/packages/server/src/api-skill-install-symlink-eperm.test.ts
@@ -0,0 +1,164 @@
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
+import { afterAll, beforeAll, expect, test, vi } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
+import { readSkillPlacements } from './skill-placements.ts';
+
+const isolated = vi.hoisted(() => ({ home: '' }));
+vi.mock('node:os', async (original) => ({
+ ...(await original<typeof import('node:os')>()),
+ homedir: () => isolated.home,
+}));
+
+vi.mock('./fs-traced.ts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('./fs-traced.ts')>();
+ return {
+ ...actual,
+ tracedSymlinkSync: (): void => {
+ throw Object.assign(new Error('EPERM: operation not permitted, symlink'), {
+ code: 'EPERM',
+ syscall: 'symlink',
+ });
+ },
+ };
+});
+
+let root: string;
+let server: BootedServer;
+beforeAll(async () => {
+ isolated.home = mkdtempSync(join(tmpdir(), 'ok-eperm-home-'));
+ root = mkdtempSync(join(tmpdir(), 'ok-eperm-project-'));
+ mkdirSync(join(root, '.claude'));
+ mkdirSync(join(root, '.cursor'));
+ server = await bootCompositionRig(root, { configHomedirOverride: isolated.home });
+ await server.ready;
+}, 60_000);
+afterAll(async () => {
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+ rmSync(isolated.home, { recursive: true, force: true });
+});
+
+async function request(method: 'POST' | 'PUT', path: string, body: object) {
+ return rawRequest(server.port, path, {
+ method,
+ headers: { 'Content-Type': 'application/json', 'X-Request-Id': 'symlink-eperm' },
+ body: JSON.stringify(body),
+ });
+}
+
+async function install(body: object) {
+ return request('POST', '/api/skill/install', { scope: 'project', ...body });
+}
+
+function seed(name: string): string {
+ const source = join(root, '.claude/skills', name);
+ mkdirSync(source, { recursive: true });
+ writeFileSync(join(source, 'SKILL.md'), `---\nname: ${name}\ndescription: d\n---\n\nBody.\n`);
+ return source;
+}
+
+function isRealDirWithSkill(path: string): boolean {
+ return existsSync(join(path, 'SKILL.md')) && !lstatSync(path).isSymbolicLink();
+}
+
+function placement(name: string, path: string) {
+ return readSkillPlacements(root)[name]?.find((p) => p.path === path);
+}
+
+function warningCodes(body: string): string[] {
+ return (JSON.parse(body) as { warningCodes?: string[] }).warningCodes ?? [];
+}
+
+test('without symlink rights, add falls back to a copy and convert-to-link keeps it', async () => {
+ const name = 'eperm-skill';
+ const source = seed(name);
+ const added = join(root, '.cursor/skills', name);
+ const hash = parseSkillDir(source)?.contentHash;
+
+ const add = await install({ name, add: ['cursor'] });
+ expect(add.status, add.body).toBe(200);
+ expect(warningCodes(add.body)).toContain('links-not-permitted');
+ expect(isRealDirWithSkill(added)).toBe(true);
+ expect(placement(name, `.cursor/skills/${name}`)).toMatchObject({ mode: 'copy', hash });
+
+ const toCopy = await install({ name, convert: { target: 'cursor', mode: 'copy' } });
+ expect(toCopy.status, toCopy.body).toBe(200);
+
+ const toLink = await install({ name, convert: { target: 'cursor', mode: 'link' } });
+ expect(toLink.status, toLink.body).toBe(403);
+ expect(JSON.parse(toLink.body)).toMatchObject({
+ type: 'urn:ok:error:links-not-permitted',
+ title:
+ 'This system does not allow creating symlinks, so that location was left as a copy. On Windows, creating symlinks needs administrator rights or Developer Mode.',
+ });
+ expect(isRealDirWithSkill(added)).toBe(true);
+ expect(placement(name, `.cursor/skills/${name}`)).toMatchObject({ mode: 'copy', hash });
+}, 60_000);
+
+test('an explicit link add reports that it made a copy', async () => {
+ const name = 'eperm-explicit';
+ seed(name);
+ const add = await install({ name, add: ['cursor'], mode: 'link' });
+ expect(add.status, add.body).toBe(200);
+ expect(warningCodes(add.body)).toContain('links-not-permitted');
+ expect(isRealDirWithSkill(join(root, '.cursor/skills', name))).toBe(true);
+}, 60_000);
+
+test('place with mode link records the copy it made, with its hash', async () => {
+ const name = 'eperm-place';
+ const source = seed(name);
+ const placed = await install({ name, place: { dir: 'team/bundles/', mode: 'link' } });
+ expect(placed.status, placed.body).toBe(200);
+ expect(warningCodes(placed.body)).toContain('links-not-permitted');
+ expect((JSON.parse(placed.body) as { warnings: string[] }).warnings).toEqual([
+ 'This system does not allow creating symlinks, so team/bundles got a copy instead of a link. On Windows, creating symlinks needs administrator rights or Developer Mode.',
+ ]);
+ expect(isRealDirWithSkill(join(root, 'team/bundles', name))).toBe(true);
+ expect(placement(name, `team/bundles/${name}`)).toMatchObject({
+ mode: 'copy',
+ hash: parseSkillDir(source)?.contentHash,
+ });
+}, 60_000);
+
+test('a custom-root add records the copy it made, with its hash', async () => {
+ const name = 'eperm-root';
+ const source = seed(name);
+ const declared = await request('PUT', '/api/skill-targets', {
+ folderAction: { action: 'add-root', scope: 'project', root: '.team/skills' },
+ });
+ expect(declared.status, declared.body).toBe(200);
+ const add = await install({ name, add: ['.team/skills'] });
+ expect(add.status, add.body).toBe(200);
+ expect(warningCodes(add.body)).toContain('links-not-permitted');
+ expect(isRealDirWithSkill(join(root, '.team/skills', name))).toBe(true);
+ expect(placement(name, `.team/skills/${name}`)).toMatchObject({
+ mode: 'copy',
+ hash: parseSkillDir(source)?.contentHash,
+ });
+}, 60_000);
+
+test('a link request over an existing custom-root copy keeps it recorded as a copy', async () => {
+ const name = 'eperm-relink';
+ const source = seed(name);
+ const declared = await request('PUT', '/api/skill-targets', {
+ folderAction: { action: 'add-root', scope: 'project', root: '.relink/skills' },
+ });
+ expect(declared.status, declared.body).toBe(200);
+ const asCopy = await install({ name, add: ['.relink/skills'], mode: 'copy' });
+ expect(asCopy.status, asCopy.body).toBe(200);
+ const hash = parseSkillDir(source)?.contentHash;
+ expect(placement(name, `.relink/skills/${name}`)).toMatchObject({ mode: 'copy', hash });
+
+ const asLink = await install({ name, add: ['.relink/skills'], mode: 'link' });
+ expect(asLink.status, asLink.body).toBe(200);
+ expect(warningCodes(asLink.body)).toContain('links-not-permitted');
+ expect((JSON.parse(asLink.body) as { warnings: string[] }).warnings).toContain(
+ 'This system does not allow creating symlinks, so .relink/skills got a copy instead of a link. On Windows, creating symlinks needs administrator rights or Developer Mode.',
+ );
+ expect(isRealDirWithSkill(join(root, '.relink/skills', name))).toBe(true);
+ expect(placement(name, `.relink/skills/${name}`)).toMatchObject({ mode: 'copy', hash });
+}, 60_000);
diff --git a/packages/server/src/http/skills-install-routes.ts b/packages/server/src/http/skills-install-routes.ts
index 245deabb1..3a73ff28f 100644
--- a/packages/server/src/http/skills-install-routes.ts
+++ b/packages/server/src/http/skills-install-routes.ts
@@ -27,6 +27,7 @@ import type { SkillPlacementOpsService } from '../services/skill-placement-ops.t
import { isInternalBundleSkillName } from '../skill-bundles.ts';
import { detectUserSkillHosts } from '../skill-install.ts';
import {
+ linksNotPermittedWarning,
projectSkill,
resolvedHosts,
resolveSkillTargets,
@@ -385,8 +386,12 @@ export function createSkillsInstallRoutes(deps: SkillsInstallRouteDeps): ApiRout
name: body.name,
hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],
scripts: validity.hasScripts,
- warnings: [],
- warningCodes: [],
+ ...('copiedInsteadOfLinked' in placed && placed.copiedInsteadOfLinked
+ ? {
+ warnings: [linksNotPermittedWarning([dirname(placed.placedAt)])],
+ warningCodes: ['links-not-permitted' as const],
+ }
+ : { warnings: [], warningCodes: [] }),
placedAt: placed.placedAt,
},
{ handler: 'skill-install' },
@@ -538,6 +543,15 @@ export function createSkillsInstallRoutes(deps: SkillsInstallRouteDeps): ApiRout
{ handler: 'skill-install', detail: target },
);
return;
+ case 'links-not-permitted':
+ errorResponse(
+ res,
+ 403,
+ 'urn:ok:error:links-not-permitted',
+ 'This system does not allow creating symlinks, so that location was left as a copy. On Windows, creating symlinks needs administrator rights or Developer Mode.',
+ { handler: 'skill-install', detail: target },
+ );
+ return;
default: {
const _exhaustive: never = converted;
throw new Error(
diff --git a/packages/server/src/mcp/tools/install.ts b/packages/server/src/mcp/tools/install.ts
index 2b227e639..196a11387 100644
--- a/packages/server/src/mcp/tools/install.ts
+++ b/packages/server/src/mcp/tools/install.ts
@@ -35,7 +35,7 @@ const DESCRIPTION = [
'Manage where a SKILL is available: `{name, add?, remove?, convert?, mode?, source?, scope?}` or `{skillFolders: {...}}` alone. Requires the Hocuspocus server. One real source folder plus managed copies/symlinks; the source still loads with no extra locations. Use delete to remove the skill everywhere.',
"name is the bundle identity: lowercase letters/digits/hyphens, ≤64 chars. Locations: claude/cursor/codex/copilot/opencode/pi, agents (.agents/skills), or custom root containing '/' such as .team/skills. Custom roots are project-relative, home-relative at global scope. scope: project (default, shared via git) or global (user-wide).",
'add/remove change membership; omitting both installs to configured editors. remove cannot remove the source; folder aliases unfollow minus this skill and keep others. Differing copies are preserved; editor removal may succeed and leave them in place.',
- 'mode: link = live symlink for source updates; copy = separate folder, refreshed on watcher/startup sync while unedited. Hand-edited copies fork; differing copies are preserved and cannot be converted. Requires add or convert; affects named locations only, no skill-wide default. Omit mode on add to inherit form. convert requires mode and changes form without membership; name all locations for uniformity.',
+ 'mode: link = live symlink for source updates (copy where the OS refuses symlinks); copy = separate folder, refreshed on watcher/startup sync while unedited. Hand-edited copies fork; differing copies are preserved and cannot be converted. Requires add or convert; affects named locations only, no skill-wide default. Omit mode on add to inherit form. convert requires mode and changes form without membership; name all locations for uniformity.',
'source moves the real folder; its old location becomes a symlink. Run alone, not with add/remove. Source SKILL.md with conflict markers, invalid/missing frontmatter, XML in name/description or reserved open-knowledge* names is refused before projection.',
"skillFolders runs alone without name. link: {action:'link', scope, root, target}; target required, merge then symlink root; equal entries deduplicate, differing skills abort, interrupted merges can rerun. unlink: {action:'unlink', scope, root, exclude?}; makes a real directory of per-skill symlinks, excluding named skills and retaining others. add-root: {action:'add-root', scope, root}; declares a custom root for install/link.",
].join('\n');
diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.ts
index 8fa998836..ab062a2f3 100644
--- a/packages/server/src/mcp/tools/shared.test.ts
+++ b/packages/server/src/mcp/tools/shared.test.ts
@@ -1,4 +1,7 @@
-import { summarizeLintPluginFailures } from '@inkeep/open-knowledge-core';
+import {
+ SKILL_INSTALL_WARNING_CODES,
+ summarizeLintPluginFailures,
+} from '@inkeep/open-knowledge-core';
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
import { z } from 'zod';
@@ -16,6 +19,7 @@ import {
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpGet,
httpPost,
+ INSTALL_WARNING_CODE_GLOSS,
normalizeDocName,
okReservedPathRedirect,
outputSchemaWithText,
@@ -907,3 +911,9 @@ describe('okReservedPathRedirect', () => {
expect(okReservedPathRedirect('docs/.hidden/x')).toBeNull();
});
});
+
+describe('INSTALL_WARNING_CODE_GLOSS', () => {
+ test.each([...SKILL_INSTALL_WARNING_CODES])('defines %s', (code) => {
+ expect(INSTALL_WARNING_CODE_GLOSS).toContain(`\`${code}\`:`);
+ });
+});
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 964677ea8..38697369e 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -604,7 +604,7 @@ export const AUTHORING_WARNING_CODE_GLOSS =
'`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.';
export const INSTALL_WARNING_CODE_GLOSS =
- '`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.';
+ '`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md. `links-not-permitted`: the OS refused symlinks, so the named locations are copies that refresh while unedited and fork when edited.';
export const AUDIT_FILE_CAP = 10;
export const AUDIT_FILE_DIAGNOSTIC_CAP = 10;
diff --git a/packages/server/src/services/skill-install-ops.ts b/packages/server/src/services/skill-install-ops.ts
index f36653d6b..3fe058599 100644
--- a/packages/server/src/services/skill-install-ops.ts
+++ b/packages/server/src/services/skill-install-ops.ts
@@ -12,13 +12,7 @@ import {
import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { parseSkillDir, type SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';
import { applySkillDirNameSync } from '../content/skills-write.ts';
-import {
- tracedCpSync,
- tracedMkdirSync,
- tracedRenameSync,
- tracedRmSync,
- tracedSymlinkSync,
-} from '../fs-traced.ts';
+import { tracedCpSync, tracedMkdirSync, tracedRenameSync, tracedRmSync } from '../fs-traced.ts';
import {
scanGlobalInPlaceSkills,
scanHostRootAliases,
@@ -39,6 +33,8 @@ import {
import {
classifyInPlaceDest,
hostSlotPaths,
+ linkOrCopySkillDir,
+ linksNotPermittedWarning,
projectInPlaceSkill,
relocateInPlaceCanonical,
removeInPlaceSkillCopies,
@@ -488,6 +484,7 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
convertCopies: input.linkModeReq === true,
roots: skillProjectionRoots(scope),
});
+ const linkFallbacks = new Set<string>(fanned.linkFallbacks);
for (const editor of fanned.conflicted) {
warnings.push(
`A different skill named "${name}" already exists in the ${editor} skills folder — left untouched.`,
@@ -495,25 +492,26 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
warningCodes.push('name-conflict');
}
if (input.linkModeReq !== undefined && prefBase && input.rootAdds.length > 0) {
- const adding = new Set(input.rootAdds.map((r) => `${r}/${name}`));
- for (const p of (readSkillPlacements(prefBase)[name] ?? []).filter((p) =>
- adding.has(p.path),
- )) {
- const abs = resolve(prefBase, p.path);
+ const recorded = new Set((readSkillPlacements(prefBase)[name] ?? []).map((p) => p.path));
+ for (const rootRel of input.rootAdds) {
+ if (!recorded.has(`${rootRel}/${name}`)) continue;
+ const abs = resolve(prefBase, rootRel, name);
if (abs === resolve(skillDir)) continue;
const cls = classifyInPlaceDest(abs, resolve(skillDir), inPlaceEntry.contentHash);
if (input.linkModeReq === true && cls === 'same-copy') {
tracedRmSync(abs, { recursive: true, force: true });
- tracedSymlinkSync(relative(dirname(abs), resolve(skillDir)), abs, 'dir');
- await recordSkillPlacement(prefBase, name, { path: p.path, mode: 'link' });
+ if (
+ linkOrCopySkillDir(
+ relative(dirname(abs), resolve(skillDir)),
+ abs,
+ resolve(skillDir),
+ ) === 'copy'
+ ) {
+ linkFallbacks.add(rootRel);
+ }
} else if (input.linkModeReq === false && cls === 'link-to-canonical') {
tracedRmSync(abs, { recursive: true, force: true });
tracedCpSync(resolve(skillDir), abs, { recursive: true, dereference: true });
- await recordSkillPlacement(prefBase, name, {
- path: p.path,
- mode: 'copy',
- hash: inPlaceEntry.contentHash,
- });
}
}
}
@@ -569,15 +567,18 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
if (cls === 'absent') {
tracedMkdirSync(parentAbs, { recursive: true });
if (input.installMode === 'link') {
- tracedSymlinkSync(relative(parentAbs, canonAbs), destAbs, 'dir');
+ if (linkOrCopySkillDir(relative(parentAbs, canonAbs), destAbs, canonAbs) === 'copy') {
+ linkFallbacks.add(rootRel);
+ }
} else {
tracedCpSync(canonAbs, destAbs, { recursive: true, dereference: true });
}
}
+ const placedMode: 'link' | 'copy' = lstatSync(destAbs).isSymbolicLink() ? 'link' : 'copy';
await recordSkillPlacement(prefBase, name, {
path: `${rootRel}/${name}`,
- mode: input.installMode,
- ...(input.installMode === 'copy' ? { hash: inPlaceEntry.contentHash } : {}),
+ mode: placedMode,
+ ...(placedMode === 'copy' ? { hash: inPlaceEntry.contentHash } : {}),
});
}
for (const rootRel of input.rootRemoves) {
@@ -604,6 +605,11 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
}
}
+ if (linkFallbacks.size > 0) {
+ warnings.push(linksNotPermittedWarning([...linkFallbacks]));
+ warningCodes.push('links-not-permitted');
+ }
+
const postEntry = scanScope(scope).find((s) => s.name === name);
const hosts = postEntry ? [...postEntry.hosts] : fanned.hosts;
return {
diff --git a/packages/server/src/services/skill-placement-ops.ts b/packages/server/src/services/skill-placement-ops.ts
index 4bc39388e..7c3da60f6 100644
--- a/packages/server/src/services/skill-placement-ops.ts
+++ b/packages/server/src/services/skill-placement-ops.ts
@@ -3,7 +3,7 @@ import { dirname, relative, resolve, sep } from 'node:path';
import type { EditorId } from '@inkeep/open-knowledge-core';
import { AGENTS_SKILLS_ROOT, isSkillInstallTarget } from '@inkeep/open-knowledge-core';
import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
-import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedSymlinkSync } from '../fs-traced.ts';
+import { tracedCpSync, tracedMkdirSync, tracedRmSync } from '../fs-traced.ts';
import {
isRefusedOkPlacementRoot,
readSkillPlacements,
@@ -11,10 +11,14 @@ import {
removeSkillPlacement,
resolveSkillPlacementPath,
} from '../skill-placements.ts';
-import { classifyInPlaceDest, skillProjectionRoots } from '../skill-projection.ts';
+import {
+ classifyInPlaceDest,
+ linkOrCopySkillDir,
+ skillProjectionRoots,
+} from '../skill-projection.ts';
type PlaceOutcome =
- | { ok: true; placedAt: string }
+ | { ok: true; placedAt: string; copiedInsteadOfLinked?: true }
| { ok: true; alreadyAtSource: true; placedAt: string }
| { ok: false; kind: 'invalid-path' }
| { ok: false; kind: 'dest-exists' };
@@ -31,7 +35,8 @@ type ConvertOutcome =
| { ok: false; kind: 'invalid-location' }
| { ok: false; kind: 'canonical-dir' }
| { ok: false; kind: 'forked' }
- | { ok: false; kind: 'not-installed' };
+ | { ok: false; kind: 'not-installed' }
+ | { ok: false; kind: 'links-not-permitted' };
export interface SkillPlacementOpsService {
place(input: {
@@ -85,17 +90,28 @@ export function createSkillPlacementOpsService(): SkillPlacementOpsService {
return { ok: false, kind: 'dest-exists' };
}
tracedMkdirSync(parentAbs, { recursive: true });
+ let placedMode = input.mode;
if (input.mode === 'link') {
- tracedSymlinkSync(relative(parentAbs, resolve(input.skillDir)), destAbs, 'dir');
+ placedMode = linkOrCopySkillDir(
+ relative(parentAbs, resolve(input.skillDir)),
+ destAbs,
+ resolve(input.skillDir),
+ );
} else {
tracedCpSync(input.skillDir, destAbs, { recursive: true, dereference: true });
}
await recordSkillPlacement(input.placeBase, input.name, {
path: placementRel,
- mode: input.mode,
- ...(input.mode === 'copy' ? { hash: parseSkillDir(input.skillDir)?.contentHash } : {}),
+ mode: placedMode,
+ ...(placedMode === 'copy' ? { hash: parseSkillDir(input.skillDir)?.contentHash } : {}),
});
- return { ok: true, placedAt: placementRel };
+ return {
+ ok: true,
+ placedAt: placementRel,
+ ...(input.mode === 'link' && placedMode === 'copy'
+ ? { copiedInsteadOfLinked: true as const }
+ : {}),
+ };
},
async unplace(input) {
@@ -165,7 +181,11 @@ export function createSkillPlacementOpsService(): SkillPlacementOpsService {
tracedRmSync(absDir, { recursive: true, force: true });
tracedMkdirSync(hostRoot, { recursive: true });
if (input.mode === 'link') {
- tracedSymlinkSync(relative(hostRoot, canonicalAbs), absDir, 'dir');
+ if (
+ linkOrCopySkillDir(relative(hostRoot, canonicalAbs), absDir, canonicalAbs) === 'copy'
+ ) {
+ return { ok: false, kind: 'links-not-permitted' };
+ }
} else {
tracedCpSync(canonicalAbs, absDir, { recursive: true, dereference: true });
}
diff --git a/packages/server/src/skill-projection.symlink-fallback.test.ts b/packages/server/src/skill-projection.symlink-fallback.test.ts
new file mode 100644
index 000000000..c51e94248
--- /dev/null
+++ b/packages/server/src/skill-projection.symlink-fallback.test.ts
@@ -0,0 +1,108 @@
+import {
+ cpSync,
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { AGENTS_SKILLS_ROOT } from '@inkeep/open-knowledge-core';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { createSkillPlacementOpsService } from './services/skill-placement-ops.ts';
+import { projectInPlaceSkill, projectSkill } from './skill-projection.ts';
+
+const symlinkFailure = vi.hoisted(() => ({ code: undefined as string | undefined }));
+
+vi.mock('./fs-traced.ts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('./fs-traced.ts')>();
+ return {
+ ...actual,
+ tracedSymlinkSync: (...args: Parameters<typeof actual.tracedSymlinkSync>): void => {
+ if (symlinkFailure.code !== undefined) {
+ throw Object.assign(new Error(`${symlinkFailure.code}: operation not permitted, symlink`), {
+ code: symlinkFailure.code,
+ syscall: 'symlink',
+ });
+ }
+ actual.tracedSymlinkSync(...args);
+ },
+ };
+});
+
+let cwd: string;
+
+function makeCanonical(name: string): string {
+ const dir = join(cwd, AGENTS_SKILLS_ROOT, name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: d\n---\n\nBody.\n`);
+ return dir;
+}
+
+function isRealDirWithSkill(path: string): boolean {
+ return (
+ existsSync(join(path, 'SKILL.md')) &&
+ !lstatSync(path).isSymbolicLink() &&
+ lstatSync(path).isDirectory()
+ );
+}
+
+beforeEach(() => {
+ cwd = mkdtempSync(join(tmpdir(), 'ok-symlink-fallback-'));
+ symlinkFailure.code = undefined;
+});
+afterEach(() => {
+ rmSync(cwd, { recursive: true, force: true });
+});
+
+describe('projection when symlinks are not permitted', () => {
+ test.each(['EPERM', 'EACCES'])('projectSkill falls back to a copy on %s', (code) => {
+ const src = makeCanonical('demo');
+ symlinkFailure.code = code;
+ expect(projectSkill(src, 'demo', cwd, ['claude'])).toEqual(['claude']);
+ expect(isRealDirWithSkill(join(cwd, '.claude', 'skills', 'demo'))).toBe(true);
+ });
+
+ test('projectSkill still throws other symlink failures', () => {
+ const src = makeCanonical('demo');
+ symlinkFailure.code = 'ENOSPC';
+ expect(() => projectSkill(src, 'demo', cwd, ['claude'])).toThrow('ENOSPC');
+ });
+
+ test.each(['EPERM', 'EACCES'])('projectInPlaceSkill link falls back to a copy on %s', (code) => {
+ const canonicalAbs = makeCanonical('demo');
+ symlinkFailure.code = code;
+ const result = projectInPlaceSkill({
+ canonicalAbs,
+ canonicalHash: parseSkillDir(canonicalAbs)?.contentHash ?? '',
+ canonicalRootRel: AGENTS_SKILLS_ROOT,
+ name: 'demo',
+ cwd,
+ targets: ['claude'],
+ mode: 'link',
+ });
+ expect(result.hosts).toContain('claude');
+ expect(isRealDirWithSkill(join(cwd, '.claude', 'skills', 'demo'))).toBe(true);
+ });
+
+ test('converting a copy to a link keeps the copy and says why', async () => {
+ const canonicalAbs = makeCanonical('demo');
+ const copy = join(cwd, '.claude', 'skills', 'demo');
+ cpSync(canonicalAbs, copy, { recursive: true });
+ symlinkFailure.code = 'EPERM';
+ const outcome = await createSkillPlacementOpsService().convert({
+ ledgerBase: cwd,
+ scope: 'project',
+ name: 'demo',
+ target: 'claude',
+ mode: 'link',
+ skillDir: canonicalAbs,
+ canonicalHash: parseSkillDir(canonicalAbs)?.contentHash ?? '',
+ });
+ expect(outcome).toEqual({ ok: false, kind: 'links-not-permitted' });
+ expect(isRealDirWithSkill(copy)).toBe(true);
+ });
+});
diff --git a/packages/server/src/skill-projection.ts b/packages/server/src/skill-projection.ts
index 3a23454e8..ad1f8c7c4 100644
--- a/packages/server/src/skill-projection.ts
+++ b/packages/server/src/skill-projection.ts
@@ -181,6 +181,31 @@ function isAliasOfCanonicalRoot(hostRoot: string, canonicalRoot: string): boolea
}
}
+function isSymlinkNotPermitted(err: unknown): boolean {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return code === 'EPERM' || code === 'EACCES';
+}
+
+export function linkOrCopySkillDir(
+ linkTarget: string,
+ dest: string,
+ source: string,
+): 'link' | 'copy' {
+ try {
+ tracedSymlinkSync(linkTarget, dest, 'dir');
+ return 'link';
+ } catch (err) {
+ if (!isSymlinkNotPermitted(err)) throw err;
+ tracedRmSync(dest, { recursive: true, force: true });
+ tracedCpSync(source, dest, { recursive: true, dereference: true });
+ return 'copy';
+ }
+}
+
+export function linksNotPermittedWarning(locations: readonly string[]): string {
+ return `This system does not allow creating symlinks, so ${locations.join(', ')} got a copy instead of a link. On Windows, creating symlinks needs administrator rights or Developer Mode.`;
+}
+
function skillLinkTarget(cwd: string, hostRoot: string, skillDir: string): string {
const absSkill = resolve(skillDir);
const fromCwd = relative(resolve(cwd), absSkill);
@@ -223,7 +248,7 @@ export function projectSkill(
if (mode === 'copy') {
tracedCpSync(skillDir, dest, { recursive: true, dereference: true });
} else {
- tracedSymlinkSync(skillLinkTarget(cwd, hostRoot, skillDir), dest, 'dir');
+ linkOrCopySkillDir(skillLinkTarget(cwd, hostRoot, skillDir), dest, skillDir);
}
written.push(editor);
}
@@ -270,17 +295,23 @@ export function projectInPlaceSkill(opts: {
convertLinks?: boolean;
convertCopies?: boolean;
roots?: SkillProjectionRoots;
-}): { hosts: SkillHostId[]; conflicted: SkillHostId[] } {
+}): { hosts: SkillHostId[]; conflicted: SkillHostId[]; linkFallbacks: SkillHostId[] } {
const { canonicalAbs, canonicalHash, canonicalRootRel, name, cwd, targets } = opts;
const roots = opts.roots ?? EDITOR_PROJECT_SKILL_ROOT;
const mode = opts.mode ?? 'copy';
const hosts: SkillHostId[] = [];
const conflicted: SkillHostId[] = [];
- const materialize = (dest: string, hostRoot: string): void => {
+ const linkFallbacks: SkillHostId[] = [];
+ const materialize = (dest: string, hostRoot: string, editor: SkillHostId): void => {
tracedRmSync(dest, { recursive: true, force: true });
tracedMkdirSync(hostRoot, { recursive: true });
if (mode === 'link') {
- tracedSymlinkSync(skillLinkTarget(cwd, hostRoot, canonicalAbs), dest, 'dir');
+ if (
+ linkOrCopySkillDir(skillLinkTarget(cwd, hostRoot, canonicalAbs), dest, canonicalAbs) ===
+ 'copy'
+ ) {
+ linkFallbacks.push(editor);
+ }
} else {
tracedCpSync(canonicalAbs, dest, { recursive: true, dereference: true });
}
@@ -298,7 +329,7 @@ export function projectInPlaceSkill(opts: {
(mode === 'link' && opts.convertCopies === true && cls === 'same-copy') ||
(mode === 'copy' && opts.convertLinks === true && cls === 'link-to-canonical')
) {
- materialize(own, dirname(own));
+ materialize(own, dirname(own), editor);
}
}
hosts.push(editor);
@@ -317,16 +348,16 @@ export function projectInPlaceSkill(opts: {
hosts.push(editor);
break;
case 'link-to-canonical':
- if (mode === 'copy' && opts.convertLinks === true) materialize(dest, hostRoot);
+ if (mode === 'copy' && opts.convertLinks === true) materialize(dest, hostRoot, editor);
hosts.push(editor);
break;
case 'same-copy':
- if (mode === 'link' && opts.convertCopies === true) materialize(dest, hostRoot);
+ if (mode === 'link' && opts.convertCopies === true) materialize(dest, hostRoot, editor);
hosts.push(editor);
break;
case 'different':
if (isStaleBundleProjection(dest, name)) {
- materialize(dest, hostRoot);
+ materialize(dest, hostRoot, editor);
hosts.push(editor);
break;
}
@@ -334,12 +365,12 @@ export function projectInPlaceSkill(opts: {
break;
case 'link':
case 'absent':
- materialize(dest, hostRoot);
+ materialize(dest, hostRoot, editor);
hosts.push(editor);
break;
}
}
- return { hosts, conflicted };
+ return { hosts, conflicted, linkFallbacks };
}
export function relocateInPlaceCanonical(opts: {