Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix: contain skill refresh paths (PRD-10107) (#7860)

Andrew Mikofalvy9dd00bbebe1b
diff --git a/.changeset/skill-refresh-containment.md b/.changeset/skill-refresh-containment.md
new file mode 100644
index 000000000..77bc60e96
--- /dev/null
+++ b/.changeset/skill-refresh-containment.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Skill creation, import, refresh and rename now refuse out-of-scope or private-state destinations and linked `SKILL.md` files. Supporting-file changes reject links on the affected path, while refresh checks every file it would write or remove; in-scope linked skill roots remain supported.
diff --git a/docs/content/features/skills/reference.mdx b/docs/content/features/skills/reference.mdx
index 1c87bfe1f..f3c138734 100644
--- a/docs/content/features/skills/reference.mdx
+++ b/docs/content/features/skills/reference.mdx
@@ -25,6 +25,8 @@ A new skill goes into a skills folder the project already has. OpenKnowledge nev
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.
+Skill creation, import, refresh and rename require the source folder to resolve inside the project or home directory, never into private repository state, and refuse a linked `SKILL.md`. Supporting-file mutations refuse links on the affected path; refresh checks every file it would write or remove. Read-only access still supports linked files; see [writable linked layouts](./symlink-skills.mdx#writable-linked-layouts) for the supported arrangements and repair steps.
+
**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.
## Existing skills
diff --git a/docs/content/features/skills/symlink-skills.mdx b/docs/content/features/skills/symlink-skills.mdx
index e269099bc..674a8e70d 100644
--- a/docs/content/features/skills/symlink-skills.mdx
+++ b/docs/content/features/skills/symlink-skills.mdx
@@ -28,4 +28,12 @@ The panel appears at both scopes: **Settings → User → Skills Studio** links
Linking refuses when the two folders hold different versions of the same skill. Resolve that first, then link.
+## Writable linked layouts
+
+Linked skill roots remain writable when the real folder stays inside the project for project skills, or inside the home directory for global skills. A link into private repository state, such as `.git`, is not a writable skill location.
+
+Creating, importing, refreshing or renaming a skill refuses a root outside that boundary or a linked `SKILL.md` file.
+
+Supporting-file writes, renames and deletions refuse the affected path when the file itself or a parent directory inside the skill folder is a link, even when its target is inside the project. Unrelated links do not block changes to other files. Refresh applies this check to every file it would write or remove, including `SKILL.md`. Replace a blocked link with a real file or directory before changing that path. Reading linked files remains supported.
+
For copies, relocating the source folder, and what OpenKnowledge writes where, see the [developer reference](./reference.mdx#file-layout).
diff --git a/packages/cli/src/commands/skills-import-containment.uncached.test.ts b/packages/cli/src/commands/skills-import-containment.uncached.test.ts
new file mode 100644
index 000000000..2391f0efc
--- /dev/null
+++ b/packages/cli/src/commands/skills-import-containment.uncached.test.ts
@@ -0,0 +1,52 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { expect, test, vi } from 'vitest';
+import { bootCompositionRig } from '../../../server/src/composition-rig.test-helper.ts';
+import { skillsCommand } from './skills.ts';
+
+test('CLI import prints the server refusal remedy together with its diagnostic code', async () => {
+ const fixture = mkdtempSync(join(tmpdir(), 'ok-cli-skill-refusal-'));
+ const root = join(fixture, 'project');
+ const upstream = join(fixture, 'upstream', 'blocked-cli');
+ const outside = join(fixture, 'outside');
+ mkdirSync(join(root, '.claude/skills'), { recursive: true });
+ mkdirSync(upstream, { recursive: true });
+ mkdirSync(outside);
+ writeFileSync(
+ join(upstream, 'SKILL.md'),
+ '---\nname: blocked-cli\ndescription: Fixture\n---\nBody\n',
+ );
+ writeFileSync(join(outside, 'sentinel.txt'), 'outside sentinel');
+ symlinkSync(outside, join(root, '.claude/skills/blocked-cli'), 'junction');
+ const server = await bootCompositionRig(root);
+ try {
+ await server.ready;
+ vi.spyOn(process, 'cwd').mockReturnValue(root);
+ const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
+ await skillsCommand().parseAsync(['import', upstream], { from: 'user' });
+ const line = stderr.mock.calls
+ .map(([text]) => String(text))
+ .join('')
+ .split('\n')
+ .find((text) => text.includes('Import failed:'));
+ expect(line).toContain('replace the link');
+ expect(line).toContain('SKILL_PATH_OUTSIDE_HOME');
+ expect(process.exitCode).toBe(1);
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+ expect(existsSync(join(outside, 'SKILL.md'))).toBe(false);
+ } finally {
+ vi.restoreAllMocks();
+ process.exitCode = undefined;
+ await server.destroy();
+ rmSync(fixture, { recursive: true, force: true });
+ }
+});
diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts
index 018e12033..4bdf51684 100644
--- a/packages/cli/src/commands/skills.ts
+++ b/packages/cli/src/commands/skills.ts
@@ -89,8 +89,14 @@ export function skillsCommand(): Command {
}
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (!res.ok) {
- const detail = (body.detail as string) ?? (body.title as string) ?? `HTTP ${res.status}`;
- process.stderr.write(`${errorColor('Import failed:')} ${detail}\n`);
+ const title = typeof body.title === 'string' ? body.title : undefined;
+ const detail = typeof body.detail === 'string' ? body.detail : undefined;
+ const message = title
+ ? detail
+ ? `${title} (${detail})`
+ : title
+ : (detail ?? `HTTP ${res.status}`);
+ process.stderr.write(`${errorColor('Import failed:')} ${message}\n`);
process.exitCode = 1;
return;
}
diff --git a/packages/server/src/api-skill-reimport-containment.test.ts b/packages/server/src/api-skill-reimport-containment.test.ts
new file mode 100644
index 000000000..7fcdf6712
--- /dev/null
+++ b/packages/server/src/api-skill-reimport-containment.test.ts
@@ -0,0 +1,255 @@
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ renameSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, beforeAll, expect, test } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
+
+let fixture: string;
+let root: string;
+let source: string;
+let server: BootedServer;
+
+const markdown = (name: string, revision: string) =>
+ `---\nname: ${name}\ndescription: Refresh containment fixture\n---\n\n${revision}\n`;
+
+beforeAll(async () => {
+ fixture = realpathSync(mkdtempSync(join(tmpdir(), 'ok-refresh-containment-')));
+ root = join(fixture, 'project');
+ source = join(fixture, 'upstream');
+ mkdirSync(join(root, '.claude/skills'), { recursive: true });
+ mkdirSync(source);
+ server = await bootCompositionRig(root);
+ await server.ready;
+}, 60_000);
+
+afterAll(async () => {
+ await server?.destroy();
+ rmSync(fixture, { recursive: true, force: true });
+});
+
+async function post(path: string, body: object) {
+ return rawRequest(server.port, path, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+}
+
+async function importSkill(name: string, withReference = false) {
+ const upstream = join(source, name);
+ mkdirSync(join(upstream, 'assets'), { recursive: true });
+ writeFileSync(join(upstream, 'SKILL.md'), markdown(name, 'old'));
+ writeFileSync(join(upstream, 'assets/sentinel.txt'), 'outside sentinel');
+ if (withReference) {
+ mkdirSync(join(upstream, 'references'));
+ writeFileSync(join(upstream, 'references/gone.md'), 'Old reference.\n');
+ }
+ const imported = await post('/api/skill/import', { source: upstream, install: false });
+ expect(imported.status, imported.body).toBe(200);
+ return { upstream, installed: join(root, '.claude/skills', name) };
+}
+
+test.each([false, true])('refresh refuses an outside-linked skill (dryRun: %s)', async (dryRun) => {
+ const name = `outside-linked-${dryRun}`;
+ const { installed, upstream } = await importSkill(name);
+ const outside = join(fixture, name);
+ renameSync(installed, outside);
+ symlinkSync(outside, installed, 'dir');
+ writeFileSync(join(upstream, 'SKILL.md'), markdown(name, 'new'));
+ rmSync(join(upstream, 'assets/sentinel.txt'));
+
+ const refreshed = await post('/api/skill/reimport', { name, scope: 'project', dryRun });
+
+ expect.soft(readFileSync(join(outside, 'SKILL.md'), 'utf8')).toBe(markdown(name, 'old'));
+ expect.soft(existsSync(join(outside, 'assets/sentinel.txt'))).toBe(true);
+ expect(refreshed.status, refreshed.body).toBe(400);
+});
+
+test.each([false, true])('refresh refuses a nested directory link (dryRun: %s)', async (dryRun) => {
+ const name = `nested-linked-${dryRun}`;
+ const { installed, upstream } = await importSkill(name);
+ const outside = join(fixture, name);
+ renameSync(join(installed, 'assets'), outside);
+ symlinkSync(outside, join(installed, 'assets'), 'dir');
+ writeFileSync(join(upstream, 'assets/sentinel.txt'), 'upstream replacement');
+ writeFileSync(join(upstream, 'SKILL.md'), markdown(name, 'new'));
+
+ const refreshed = await post('/api/skill/reimport', { name, scope: 'project', dryRun });
+
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+ expect(refreshed.status, refreshed.body).toBe(400);
+ expect(JSON.parse(refreshed.body).detail).toContain('SKILL_SYMLINK_REFUSED');
+ expect(JSON.parse(refreshed.body).detail).toContain('assets/sentinel.txt');
+ expect(readFileSync(join(installed, 'SKILL.md'), 'utf8')).toBe(markdown(name, 'old'));
+});
+
+test('refresh preserves an explicitly in-project linked skill root', async () => {
+ const name = 'inside-linked';
+ const { installed, upstream } = await importSkill(name);
+ const owned = join(root, 'team-skills', name);
+ mkdirSync(join(root, 'team-skills'));
+ renameSync(installed, owned);
+ symlinkSync(owned, installed, 'dir');
+ writeFileSync(join(upstream, 'SKILL.md'), markdown(name, 'new'));
+ rmSync(join(upstream, 'assets/sentinel.txt'));
+
+ const refreshed = await post('/api/skill/reimport', { name, scope: 'project' });
+
+ expect(refreshed.status, refreshed.body).toBe(200);
+ expect(readFileSync(join(owned, 'SKILL.md'), 'utf8')).toBe(markdown(name, 'new'));
+ expect(existsSync(join(owned, 'assets/sentinel.txt'))).toBe(false);
+});
+
+test.each(['root', 'manifest'] as const)(
+ 'rename refuses an outside-linked %s before relocating the skill',
+ async (linked) => {
+ const name = `rename-linked-${linked}`;
+ const { installed } = await importSkill(name);
+ const outside = join(fixture, name);
+ const sourcePath = linked === 'root' ? installed : join(installed, 'SKILL.md');
+ renameSync(sourcePath, outside);
+ symlinkSync(outside, sourcePath, linked === 'root' ? 'dir' : 'file');
+
+ const renamed = await post('/api/skill', {
+ fromName: name,
+ toName: `${name}-renamed`,
+ scope: 'project',
+ });
+
+ expect(renamed.status, renamed.body).toBe(400);
+ expect(lstatSync(sourcePath).isSymbolicLink()).toBe(true);
+ expect(existsSync(join(root, '.claude/skills', `${name}-renamed`))).toBe(false);
+ expect(readFileSync(linked === 'root' ? join(outside, 'SKILL.md') : outside, 'utf8')).toBe(
+ markdown(name, 'old'),
+ );
+ },
+);
+
+test.each(['delete', 'rename'] as const)(
+ 'bundle %s refuses an in-skill directory link before closing its document',
+ async (operation) => {
+ const name = `bundle-${operation}`;
+ const { installed } = await importSkill(name);
+ mkdirSync(join(installed, 'references'));
+ writeFileSync(join(installed, 'references/notes.md'), 'Keep this document.\n');
+ symlinkSync('references', join(installed, 'linked'), 'dir');
+ const docName = `.claude/skills/${name}/linked/notes`;
+ const session = await server.serverInstance.sessionManager.getSession(docName, 'agent-reader', {
+ displayName: 'Reader',
+ colorSeed: 'reader',
+ });
+ const document = session.dc.document;
+ const statusBefore = document.getMap('lifecycle').get('status');
+
+ const response =
+ operation === 'delete'
+ ? await rawRequest(
+ server.port,
+ `/api/skill-file?${new URLSearchParams({ name, scope: 'project', path: 'linked' })}`,
+ { method: 'DELETE' },
+ )
+ : await post('/api/skill-file/rename', {
+ name,
+ scope: 'project',
+ from: 'linked',
+ to: 'renamed',
+ });
+
+ expect(response.status, response.body).toBe(400);
+ expect(document.getMap('lifecycle').get('status')).toBe(statusBefore);
+ expect(lstatSync(join(installed, 'linked')).isSymbolicLink()).toBe(true);
+ expect(readFileSync(join(installed, 'references/notes.md'), 'utf8')).toBe(
+ 'Keep this document.\n',
+ );
+ },
+);
+
+test('bulk refresh reports the remedy together with the refused path and code', async () => {
+ const name = 'bulk-refusal';
+ const { installed, upstream } = await importSkill(name);
+ const outside = join(fixture, name);
+ renameSync(join(installed, 'assets'), outside);
+ symlinkSync(outside, join(installed, 'assets'), 'dir');
+ writeFileSync(join(upstream, 'SKILL.md'), markdown(name, 'new'));
+ const response = await post('/api/skills/reimport-bulk', { scope: 'project', names: [name] });
+ expect(response.status, response.body).toBe(200);
+ const result = JSON.parse(response.body).results[0];
+ expect(result.status).toBe('failed');
+ expect(result.error).toContain('replace it with a real file or directory');
+ expect(result.error).toContain('assets/sentinel.txt');
+ expect(result.error).toContain('SKILL_SYMLINK_REFUSED');
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+});
+
+test('skill creation reports a failed destination lookup as a server error', async () => {
+ const name = 'unverifiable-destination';
+ writeFileSync(join(root, '.claude/skills', name), 'not a directory');
+ const response = await rawRequest(server.port, '/api/skill', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name,
+ scope: 'project',
+ body: 'Replacement',
+ frontmatter: { name, description: 'Fixture' },
+ }),
+ });
+ expect(response.status, response.body).toBe(500);
+ expect(JSON.parse(response.body).detail).toBe('SKILL_PATH_CHECK_FAILED');
+ expect(readFileSync(join(root, '.claude/skills', name), 'utf8')).toBe('not a directory');
+});
+
+test('bulk import reports the refusal remedy and diagnostic code', async () => {
+ const name = 'bulk-import-refusal';
+ const upstream = join(source, name);
+ const outside = join(fixture, name);
+ mkdirSync(upstream);
+ mkdirSync(outside);
+ writeFileSync(join(upstream, 'SKILL.md'), markdown(name, 'new'));
+ writeFileSync(join(outside, 'sentinel.txt'), 'outside sentinel');
+ symlinkSync(outside, join(root, '.claude/skills', name), 'junction');
+ const response = await post('/api/skills/import-bulk', {
+ source,
+ skills: [name],
+ install: false,
+ });
+ expect(response.status, response.body).toBe(200);
+ const result = JSON.parse(response.body).results[0];
+ expect(result.status).toBe('failed');
+ expect(result.error).toContain('replace the link');
+ expect(result.error).toContain('SKILL_PATH_OUTSIDE_HOME');
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+});
+
+test('a lookup failure after refresh preflight retains its server-error classification', async () => {
+ const name = 'post-preflight-lookup';
+ const { installed, upstream } = await importSkill(name, true);
+ const session = await server.serverInstance.sessionManager.getSession(
+ `.claude/skills/${name}/references/gone`,
+ 'agent-reader',
+ { displayName: 'Reader', colorSeed: 'reader' },
+ );
+ const backup = join(fixture, `${name}-before`);
+ session.dc.document.on('destroy', () => {
+ renameSync(installed, backup);
+ symlinkSync(name, installed, 'dir');
+ });
+ writeFileSync(join(upstream, 'SKILL.md'), markdown(name, 'new'));
+ rmSync(join(upstream, 'references/gone.md'));
+ const response = await post('/api/skill/reimport', { name, scope: 'project' });
+ expect(response.status, response.body).toBe(500);
+ expect(JSON.parse(response.body).detail).toBe('SKILL_PATH_CHECK_FAILED');
+ expect(readFileSync(join(backup, 'SKILL.md'), 'utf8')).toBe(markdown(name, 'old'));
+});
diff --git a/packages/server/src/content/skills-write-containment.test.ts b/packages/server/src/content/skills-write-containment.test.ts
new file mode 100644
index 000000000..5fbd99830
--- /dev/null
+++ b/packages/server/src/content/skills-write-containment.test.ts
@@ -0,0 +1,149 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, expect, test } from 'vitest';
+import {
+ applySkillBundleFileDelete,
+ applySkillBundleFileRename,
+ applySkillBundleFileWrite,
+ applySkillWrite,
+} from './skills-write.ts';
+
+let fixture: string;
+let boundary: string;
+let skillsRoot: string;
+let outside: string;
+
+beforeEach(() => {
+ fixture = realpathSync(mkdtempSync(join(tmpdir(), 'ok-skill-mutations-')));
+ boundary = join(fixture, 'project');
+ skillsRoot = join(boundary, '.claude/skills');
+ outside = join(fixture, 'outside');
+ mkdirSync(join(skillsRoot, 'helper'), { recursive: true });
+ mkdirSync(outside);
+ writeFileSync(join(skillsRoot, 'helper/SKILL.md'), '# Helper');
+ writeFileSync(join(outside, 'sentinel.txt'), 'outside sentinel');
+});
+
+afterEach(() => rmSync(fixture, { recursive: true, force: true }));
+
+test.each(['write', 'delete', 'rename-from', 'rename-to'] as const)(
+ '%s refuses a nested parent link at the shared mutation boundary',
+ (operation) => {
+ symlinkSync(outside, join(skillsRoot, 'helper/assets'), 'dir');
+ const input = { boundary, skillsRoot, name: 'helper', relPath: 'assets/sentinel.txt' };
+ writeFileSync(join(skillsRoot, 'helper/local.txt'), 'local sentinel');
+ const result =
+ operation === 'write'
+ ? applySkillBundleFileWrite({ ...input, content: 'replacement' })
+ : operation === 'delete'
+ ? applySkillBundleFileDelete(input)
+ : applySkillBundleFileRename({
+ ...input,
+ ...(operation === 'rename-to'
+ ? { relPath: 'local.txt', toRelPath: 'assets/new.txt' }
+ : { toRelPath: 'moved.txt' }),
+ });
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+ expect(readFileSync(join(skillsRoot, 'helper/local.txt'), 'utf8')).toBe('local sentinel');
+ expect(result.ok).toBe(false);
+ },
+);
+
+test('skill writes refuse an escaping host ancestor', () => {
+ rmSync(join(boundary, '.claude'), { recursive: true });
+ symlinkSync(outside, join(boundary, '.claude'), 'dir');
+ const input = {
+ boundary,
+ skillsRoot,
+ name: 'helper',
+ body: '# Replacement',
+ frontmatter: { name: 'helper', description: 'Fixture' },
+ };
+ expect(applySkillWrite(input).ok).toBe(false);
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+});
+
+test('bundle deletion refuses a skill root linked outside the project', () => {
+ rmSync(join(skillsRoot, 'helper'), { recursive: true });
+ symlinkSync(outside, join(skillsRoot, 'helper'), 'dir');
+ expect(
+ applySkillBundleFileDelete({ boundary, skillsRoot, name: 'helper', relPath: 'sentinel.txt' })
+ .ok,
+ ).toBe(false);
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+});
+
+test.each(['sentinel.txt', 'missing.txt'])('bundle writes refuse a %s leaf symlink', (target) => {
+ symlinkSync(join(outside, target), join(skillsRoot, 'helper/linked.txt'), 'file');
+ expect(
+ applySkillBundleFileWrite({
+ boundary,
+ skillsRoot,
+ name: 'helper',
+ relPath: 'linked.txt',
+ content: 'replacement',
+ }).ok,
+ ).toBe(false);
+ expect(readFileSync(join(outside, 'sentinel.txt'), 'utf8')).toBe('outside sentinel');
+});
+
+test('a linked root inside the project cannot target private Git state', () => {
+ const gitDir = join(boundary, '.git');
+ mkdirSync(gitDir);
+ writeFileSync(join(gitDir, 'config'), 'private sentinel');
+ rmSync(join(skillsRoot, 'helper'), { recursive: true });
+ symlinkSync(gitDir, join(skillsRoot, 'helper'), 'dir');
+
+ expect(
+ applySkillWrite({
+ boundary,
+ skillsRoot,
+ name: 'helper',
+ body: 'Replacement',
+ frontmatter: { name: 'helper', description: 'Fixture' },
+ }).ok,
+ ).toBe(false);
+ expect(readFileSync(join(gitDir, 'config'), 'utf8')).toBe('private sentinel');
+ expect(existsSync(join(gitDir, 'SKILL.md'))).toBe(false);
+});
+
+test('unverifiable bundle paths preserve their lookup errno', () => {
+ writeFileSync(join(skillsRoot, 'helper/assets'), 'not a directory');
+ const result = applySkillBundleFileWrite({
+ boundary,
+ skillsRoot,
+ name: 'helper',
+ relPath: 'assets/sentinel.txt',
+ content: 'replacement',
+ });
+ expect(result).toMatchObject({ ok: false, error: { code: 'SKILL_PATH_CHECK_FAILED' } });
+ if (!result.ok) expect(result.error.message).toContain('ENOTDIR');
+ expect(readFileSync(join(skillsRoot, 'helper/assets'), 'utf8')).toBe('not a directory');
+});
+
+test('a skill-directory lookup failure names the directory rather than a file component', () => {
+ rmSync(join(skillsRoot, 'helper'), { recursive: true });
+ symlinkSync('helper', join(skillsRoot, 'helper'), 'dir');
+ const result = applySkillWrite({
+ boundary,
+ skillsRoot,
+ name: 'helper',
+ body: 'Replacement',
+ frontmatter: { name: 'helper', description: 'Fixture' },
+ });
+ expect(result).toMatchObject({ ok: false, error: { code: 'SKILL_PATH_CHECK_FAILED' } });
+ if (!result.ok) {
+ expect(result.error.message).toContain('skill directory');
+ expect(result.error.message).toContain('ELOOP');
+ }
+});
diff --git a/packages/server/src/content/skills-write.test.ts b/packages/server/src/content/skills-write.test.ts
index 90315c3bf..16afc33ea 100644
--- a/packages/server/src/content/skills-write.test.ts
+++ b/packages/server/src/content/skills-write.test.ts
@@ -34,6 +34,7 @@ const fm = (name: string, description = 'Use when testing.') => ({ name, descrip
describe('applySkillWrite', () => {
test('creates SKILL.md with composed name+description frontmatter', () => {
const result = applySkillWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
body: '# Steps\n\nDo the thing.',
@@ -52,14 +53,21 @@ describe('applySkillWrite', () => {
});
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') });
+ applySkillWrite({ boundary: root, skillsRoot, name: 's', body: 'a', frontmatter: fm('s') });
+ const again = applySkillWrite({
+ boundary: root,
+ 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({
+ boundary: root,
skillsRoot,
name: 'trip-log',
body: 'x',
@@ -71,6 +79,7 @@ describe('applySkillWrite', () => {
test('rejects XML tag in description', () => {
const result = applySkillWrite({
+ boundary: root,
skillsRoot,
name: 'x',
body: 'b',
@@ -82,7 +91,13 @@ describe('applySkillWrite', () => {
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) });
+ const result = applySkillWrite({
+ boundary: root,
+ skillsRoot,
+ name: bad,
+ body: 'b',
+ frontmatter: fm(bad),
+ });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('BAD_NAME');
}
@@ -90,6 +105,7 @@ describe('applySkillWrite', () => {
test('vendor words in name warn but never block — the marketplace is full of claude-* skills', () => {
const result = applySkillWrite({
+ boundary: root,
skillsRoot,
name: 'claude-helper',
body: 'b',
@@ -103,10 +119,17 @@ describe('applySkillWrite', () => {
});
test('allows empty description (draft) and rejects over-long description', () => {
- const empty = applySkillWrite({ skillsRoot, name: 'a', body: 'b', frontmatter: fm('a', '') });
+ const empty = applySkillWrite({
+ boundary: root,
+ skillsRoot,
+ name: 'a',
+ body: 'b',
+ frontmatter: fm('a', ''),
+ });
expect(empty.ok).toBe(true);
const long = applySkillWrite({
+ boundary: root,
skillsRoot,
name: 'a',
body: 'b',
@@ -118,6 +141,7 @@ describe('applySkillWrite', () => {
test('warns (not errors) on a >500-line body', () => {
const result = applySkillWrite({
+ boundary: root,
skillsRoot,
name: 'big',
body: Array.from({ length: 600 }, (_, i) => `line ${i}`).join('\n'),
@@ -132,6 +156,7 @@ describe('applySkillWrite', () => {
test('two warnings on one write keep codes positionally aligned with their text', () => {
const result = applySkillWrite({
+ boundary: root,
skillsRoot,
name: 'claude-helper',
body: Array.from({ length: 600 }, (_, i) => `line ${i}`).join('\n'),
@@ -149,7 +174,7 @@ describe('applySkillWrite', () => {
describe('applySkillDelete', () => {
test('removes the whole skill dir and reports existed', () => {
- applySkillWrite({ skillsRoot, name: 's', body: 'a', frontmatter: fm('s') });
+ applySkillWrite({ boundary: root, 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);
@@ -164,7 +189,13 @@ describe('applySkillDelete', () => {
});
test('cleans an emptied .ok/skills then .ok', () => {
- applySkillWrite({ skillsRoot, name: 'only', body: 'a', frontmatter: fm('only') });
+ applySkillWrite({
+ boundary: root,
+ skillsRoot,
+ name: 'only',
+ body: 'a',
+ frontmatter: fm('only'),
+ });
applySkillDelete({ skillsRoot, name: 'only' });
expect(existsSync(skillsRoot)).toBe(false);
expect(existsSync(join(root, '.ok'))).toBe(false);
@@ -179,7 +210,7 @@ describe('applySkillMove', () => {
};
test('renames the skill dir', async () => {
- applySkillWrite({ skillsRoot, name: 'old', body: 'a', frontmatter: fm('old') });
+ applySkillWrite({ boundary: root, skillsRoot, name: 'old', body: 'a', frontmatter: fm('old') });
const result = await applySkillMove({
skillsRoot,
fromName: 'old',
@@ -192,8 +223,8 @@ describe('applySkillMove', () => {
});
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') });
+ applySkillWrite({ boundary: root, skillsRoot, name: 'a', body: 'x', frontmatter: fm('a') });
+ applySkillWrite({ boundary: root, skillsRoot, name: 'b', body: 'y', frontmatter: fm('b') });
const result = await applySkillMove({
skillsRoot,
fromName: 'a',
@@ -214,7 +245,13 @@ describe('applySkillMove', () => {
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') });
+ applySkillWrite({
+ boundary: root,
+ skillsRoot,
+ name: 'same',
+ body: 'x',
+ frontmatter: fm('same'),
+ });
const noop = await applySkillMove({
skillsRoot,
fromName: 'same',
@@ -228,11 +265,12 @@ describe('applySkillMove', () => {
describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', () => {
const seedSkill = (name = 'trip-log') =>
- applySkillWrite({ skillsRoot, name, body: '# Steps', frontmatter: fm(name) });
+ applySkillWrite({ boundary: root, skillsRoot, name, body: '# Steps', frontmatter: fm(name) });
test('writes a reference + a script into an existing skill (atomic, created flag)', () => {
seedSkill();
const ref = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/gear.md',
@@ -248,6 +286,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
);
const script = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'scripts/run.sh',
@@ -257,6 +296,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
if (script.ok) expect(script.created).toBe(true);
const again = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/gear.md',
@@ -268,6 +308,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
test('refuses a write into a skill that does not exist', () => {
const r = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'ghost',
relPath: 'references/x.md',
@@ -280,6 +321,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
test('rejects an escaping path and an over-cap file', () => {
seedSkill();
const escaping = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/../../escape.md',
@@ -289,6 +331,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
if (!escaping.ok) expect(escaping.error.code).toBe('BAD_FILE_PATH');
const tooLarge = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/big.md',
@@ -303,6 +346,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
const skillDir = join(skillsRoot, 'trip-log');
const rootFile = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'config.json',
@@ -312,6 +356,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
expect(readFileSync(join(skillDir, 'config.json'), 'utf-8')).toBe('{"a":1}');
const asset = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'assets/note.txt',
@@ -321,6 +366,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
const png = new Uint8Array([0x89, 0x50, 0x00, 0xff]);
const bin = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'assets/logo.png',
@@ -331,6 +377,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
expect(Array.from(readFileSync(join(skillDir, 'assets', 'logo.png')))).toEqual(Array.from(png));
const skillMd = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'SKILL.md',
@@ -344,6 +391,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
seedSkill();
for (let i = 0; i < 50; i++) {
const r = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: `references/r${i}.md`,
@@ -352,6 +400,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
expect(r.ok).toBe(true);
}
const overflow = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/one-too-many.md',
@@ -376,6 +425,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
const writes: string[] = [];
for (let i = 0; i < 51; i++) {
const r = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: `references/r${i}.md`,
@@ -391,6 +441,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
for (let i = 0; i < 50; i++) {
expect(
applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: `references/r${i}.md`,
@@ -400,6 +451,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
}
const imported = applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'assets/large.bin',
@@ -413,12 +465,14 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
test('deletes a bundle file and prunes the emptied dir; no-op reports existed:false', () => {
seedSkill();
applySkillBundleFileWrite({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/gear.md',
content: 'x',
});
const del = applySkillBundleFileDelete({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/gear.md',
@@ -429,6 +483,7 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
expect(existsSync(join(skillsRoot, 'trip-log', 'SKILL.md'))).toBe(true);
const noop = applySkillBundleFileDelete({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/gear.md',
@@ -440,8 +495,15 @@ describe('applySkillBundleFileWrite / applySkillBundleFileDelete (fs-direct)', (
test('deletes a bundle FOLDER recursively, leaving the skill intact', () => {
seedSkill();
for (const rel of ['references/deep/a.md', 'references/deep/nested/b.md', 'references/keep.md'])
- applySkillBundleFileWrite({ skillsRoot, name: 'trip-log', relPath: rel, content: 'x' });
+ applySkillBundleFileWrite({
+ boundary: root,
+ skillsRoot,
+ name: 'trip-log',
+ relPath: rel,
+ content: 'x',
+ });
const del = applySkillBundleFileDelete({
+ boundary: root,
skillsRoot,
name: 'trip-log',
relPath: 'references/deep',
diff --git a/packages/server/src/content/skills-write.ts b/packages/server/src/content/skills-write.ts
index 88f9a23fa..dd80d4f34 100644
--- a/packages/server/src/content/skills-write.ts
+++ b/packages/server/src/content/skills-write.ts
@@ -1,5 +1,5 @@
-import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
-import { basename, dirname, isAbsolute, join, normalize, sep } from 'node:path';
+import { type Dirent, existsSync, lstatSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { basename, dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
import {
applyPatchToFm,
containsXmlTag,
@@ -13,6 +13,7 @@ import {
import { ATOMIC_TEMP_INFIX, atomicTempPath } from '@inkeep/open-knowledge-core/server';
import { stringify as stringifyYaml } from 'yaml';
import { isSkillBundlePathWithheld } from '../content-filter.ts';
+import { resolveExistingNativeAncestor, resolveNativePath } from '../directory-root.ts';
/*
* STOP: every disk write in this module goes through `fs-traced.ts` so it
* carries an `fs.*` span. A bare `node:fs` call here drops the span.
@@ -25,6 +26,9 @@ import {
tracedUnlinkSync,
tracedWriteFileSync,
} from '../fs-traced.ts';
+import { errnoCode } from '../http/handler-utils.ts';
+import { symlinkReachesPrivateState } from '../incoming-symlink-guard.ts';
+import { isWithinDir } from '../path-utils.ts';
const NAME_MAX = 64;
const DESCRIPTION_MAX = 1024;
@@ -40,7 +44,7 @@ type SkillWriteResult =
warnings: string[];
warningCodes: SkillAuthoringWarningCode[];
}
- | { ok: false; error: { code: string; message: string } };
+ | { ok: false; error: { code: string; message: string; cause?: unknown } };
export type SkillContentResult =
| {
@@ -60,6 +64,7 @@ type SkillMoveResult =
| { ok: false; error: { code: string; message: string } };
interface WriteSkillInput {
+ boundary: string;
skillsRoot: string;
name: string;
body: string;
@@ -134,6 +139,8 @@ export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {
const { content, warnings, warningCodes } = composed;
const { skillDir, filePath } = skillPaths(input.skillsRoot, input.name);
+ const pathCheck = validateSkillMutationPath(input.boundary, skillDir, filePath);
+ if (!pathCheck.ok) return pathCheck;
try {
tracedMkdirSync(skillDir, { recursive: true });
@@ -152,7 +159,7 @@ export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {
sweepStaleTmpSiblings(filePath);
const tmpPath = atomicTempPath(filePath);
try {
- tracedWriteFileSync(tmpPath, content, 'utf-8');
+ tracedWriteFileSync(tmpPath, content, { encoding: 'utf-8', flag: 'wx' });
tracedRenameSync(tmpPath, filePath);
} catch (err) {
try {
@@ -225,6 +232,7 @@ export interface BundleFileWriteLimits {
}
interface BundleFileInput {
+ boundary: string;
skillsRoot: string;
name: string;
relPath: string;
@@ -238,6 +246,72 @@ type BundleFileDeleteResult =
| { ok: true; path: string; existed: boolean }
| { ok: false; error: { code: string; message: string } };
+export function skillMutationErrorStatus(code: string): 400 | 500 {
+ return code === 'SKILL_PATH_CHECK_FAILED' ? 500 : 400;
+}
+
+export function validateSkillMutationPath(
+ boundary: string,
+ skillDir: string,
+ abs: string,
+): { ok: true } | { ok: false; error: { code: string; message: string; cause?: unknown } } {
+ if (!isAbsolute(boundary) || !isWithinDir(skillDir, boundary) || !isWithinDir(abs, skillDir)) {
+ return {
+ ok: false,
+ error: {
+ code: 'SKILL_PATH_OUTSIDE_HOME',
+ message: `Skill ${relative(boundary, skillDir)} must stay inside its project or home directory.`,
+ },
+ };
+ }
+ let component = skillDir;
+ let operation = 'resolve the project or home directory';
+ try {
+ const realBoundary = resolveNativePath(boundary);
+ operation = `resolve skill directory ${relative(boundary, skillDir)}`;
+ const { ancestor, missingSegments } = resolveExistingNativeAncestor(skillDir);
+ const realSkillDir = join(ancestor, ...missingSegments);
+ const privateState = symlinkReachesPrivateState(
+ relative(boundary, skillDir).split(sep).join('/'),
+ relative(realBoundary, realSkillDir).split(sep).join('/'),
+ );
+ if (!isWithinDir(realSkillDir, realBoundary) || privateState) {
+ return {
+ ok: false,
+ error: {
+ code: privateState ? 'SKILL_PATH_PRIVATE_STATE' : 'SKILL_PATH_OUTSIDE_HOME',
+ message: `Skill ${relative(boundary, skillDir)} resolves ${privateState ? 'into private repository state' : 'outside its project or home directory'}; replace the link with an authorized skill directory.`,
+ },
+ };
+ }
+ for (const segment of relative(skillDir, abs).split(sep)) {
+ component = join(component, segment);
+ operation = `inspect skill path ${relative(skillDir, component)}`;
+ const stat = lstatSync(component, { throwIfNoEntry: false });
+ if (stat === undefined) break;
+ if (stat.isSymbolicLink()) {
+ return {
+ ok: false,
+ error: {
+ code: 'SKILL_SYMLINK_REFUSED',
+ message: `Skill path ${relative(skillDir, component)} is a symlink; replace it with a real file or directory before changing it.`,
+ },
+ };
+ }
+ }
+ } catch (cause) {
+ return {
+ ok: false,
+ error: {
+ code: 'SKILL_PATH_CHECK_FAILED',
+ message: `Could not ${operation} (${errnoCode(cause) ?? 'unknown error'}).`,
+ cause,
+ },
+ };
+ }
+ return { ok: true };
+}
+
function resolveBundleFileAbs(
skillDir: string,
relPath: string,
@@ -317,6 +391,8 @@ export function applySkillBundleFileWrite(
const resolved = resolveBundleFileAbs(skillDir, input.relPath);
if (!resolved.ok) return { ok: false, error: resolved.error };
const { abs } = resolved;
+ const pathCheck = validateSkillMutationPath(input.boundary, skillDir, abs);
+ if (!pathCheck.ok) return pathCheck;
const byteLength =
typeof payload === 'string' ? Buffer.byteLength(payload, 'utf-8') : payload.length;
@@ -357,8 +433,7 @@ export function applySkillBundleFileWrite(
sweepStaleTmpSiblings(abs);
const tmpPath = atomicTempPath(abs);
try {
- if (typeof payload === 'string') tracedWriteFileSync(tmpPath, payload, 'utf-8');
- else tracedWriteFileSync(tmpPath, payload);
+ tracedWriteFileSync(tmpPath, payload, { encoding: 'utf-8', flag: 'wx' });
tracedRenameSync(tmpPath, abs);
} catch (err) {
try {
@@ -396,6 +471,10 @@ export function applySkillBundleFileRename(
if (!from.ok) return { ok: false, error: from.error };
const to = resolveBundleFileAbs(skillDir, input.toRelPath);
if (!to.ok) return { ok: false, error: to.error };
+ for (const abs of [from.abs, to.abs]) {
+ const pathCheck = validateSkillMutationPath(input.boundary, skillDir, abs);
+ if (!pathCheck.ok) return pathCheck;
+ }
if (!existsSync(from.abs)) {
return {
@@ -444,6 +523,9 @@ export function applySkillBundleFileDelete(input: BundleFileInput): BundleFileDe
if (!resolved.ok) return { ok: false, error: resolved.error };
const { abs } = resolved;
+ const pathCheck = validateSkillMutationPath(input.boundary, skillDir, abs);
+ if (!pathCheck.ok) return pathCheck;
+
const existed = existsSync(abs);
if (existed) {
try {
diff --git a/packages/server/src/content/skills-write.windows-path.test.ts b/packages/server/src/content/skills-write.windows-path.test.ts
new file mode 100644
index 000000000..02fd57d9e
--- /dev/null
+++ b/packages/server/src/content/skills-write.windows-path.test.ts
@@ -0,0 +1,38 @@
+import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { expect, test, vi } from 'vitest';
+import { withTempDir } from '../../../../test-support/temp-dir.test-helper.ts';
+import { applySkillWrite } from './skills-write.ts';
+
+vi.mock('node:path', async (importOriginal) => {
+ const path = await importOriginal<typeof import('node:path')>();
+ return { ...path, relative: path.win32.relative, sep: path.win32.sep };
+});
+
+test.each(['.git', '.git/hooks', '.git/skills/helper', '.ok/local'])(
+ 'Win32 relative paths refuse a skill root linked into %s',
+ async (target) => {
+ await withTempDir('ok-skill-win32-', async (root) => {
+ const boundary = join(root, 'project');
+ const skillsRoot = join(boundary, '.claude/skills');
+ const privateDir = join(boundary, target);
+ mkdirSync(privateDir, { recursive: true });
+ mkdirSync(skillsRoot, { recursive: true });
+ writeFileSync(join(privateDir, 'sentinel.txt'), 'private sentinel');
+ symlinkSync(privateDir, join(skillsRoot, 'helper'), 'junction');
+ expect(relative(boundary, privateDir)).toBe(target.replaceAll('/', '\\'));
+
+ const result = applySkillWrite({
+ boundary,
+ skillsRoot,
+ name: 'helper',
+ body: 'Replacement',
+ frontmatter: { name: 'helper', description: 'Fixture' },
+ });
+
+ expect(result).toMatchObject({ ok: false, error: { code: 'SKILL_PATH_PRIVATE_STATE' } });
+ expect(existsSync(join(privateDir, 'SKILL.md'))).toBe(false);
+ expect(readFileSync(join(privateDir, 'sentinel.txt'), 'utf8')).toBe('private sentinel');
+ });
+ },
+);
diff --git a/packages/server/src/http/skills-document-routes.ts b/packages/server/src/http/skills-document-routes.ts
index e8a97ccf9..1b58a6a10 100644
--- a/packages/server/src/http/skills-document-routes.ts
+++ b/packages/server/src/http/skills-document-routes.ts
@@ -49,6 +49,8 @@ import {
applySkillMove,
applySkillWrite,
composeSkillContent,
+ skillMutationErrorStatus,
+ validateSkillMutationPath,
} from '../content/skills-write.ts';
import type { ContentFilter } from '../content-filter.ts';
import type {
@@ -551,6 +553,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo
return;
}
const wr = applySkillWrite({
+ boundary: putBase,
skillsRoot: resolve(putBase, homeRel),
name: body.name,
body: typeof body.body === 'string' ? body.body : '',
@@ -560,11 +563,20 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo
},
});
if (!wr.ok) {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill request.', {
- handler: 'skill-put',
- detail: wr.error.code,
- cause: new Error(wr.error.message),
- });
+ const status = skillMutationErrorStatus(wr.error.code);
+ errorResponse(
+ res,
+ status,
+ status === 500
+ ? 'urn:ok:error:internal-server-error'
+ : 'urn:ok:error:invalid-request',
+ wr.error.message,
+ {
+ handler: 'skill-put',
+ detail: wr.error.code,
+ cause: wr.error.cause ?? new Error(wr.error.message),
+ },
+ );
return;
}
if (body.scope === 'project') {
@@ -874,6 +886,28 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo
body.scope,
body.fromName,
);
+ const fromScanBase = body.scope === 'project' ? contentDir : skillsHome;
+ const sourceSkillDir = resolve(skillsRoot, body.fromName);
+ const pathCheck = validateSkillMutationPath(
+ fromScanBase,
+ sourceSkillDir,
+ resolve(sourceSkillDir, 'SKILL.md'),
+ );
+ if (!pathCheck.ok) {
+ const status = skillMutationErrorStatus(pathCheck.error.code);
+ errorResponse(
+ res,
+ status,
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ pathCheck.error.message,
+ {
+ handler: 'skill-move',
+ detail: pathCheck.error.code,
+ cause: pathCheck.error.cause,
+ },
+ );
+ return;
+ }
const occupiedToDir = resolveSkillDirForRead(body.scope, body.toName);
if (occupiedToDir !== null) {
const retentionBase = skillInstallBase(body.scope);
@@ -915,7 +949,6 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo
const priorInstall = moveBase
? readInstalledSkills(moveBase).skills[body.fromName]
: undefined;
- const fromScanBase = body.scope === 'project' ? contentDir : skillsHome;
const renameScanEntry = (
body.scope === 'project'
? scanInPlaceSkills(contentDir)
@@ -984,7 +1017,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo
return;
}
- let contentEditError: { code: string; message: string } | null = null;
+ let contentEditError: { code: string; message: string; cause?: unknown } | null = null;
const movedSkillMd = resolve(skillsRoot, body.toName, 'SKILL.md');
let parsedBody = '';
let parsedDescription = '';
@@ -999,6 +1032,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo
const writeDescription =
body.frontmatter !== undefined ? body.frontmatter.description : parsedDescription;
const rewrite = applySkillWrite({
+ boundary: fromScanBase,
skillsRoot,
name: body.toName,
body: writeBody,
@@ -1113,16 +1147,19 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo
signalChannel?.('files');
if (contentEditError) {
- const isServerError = contentEditError.code === 'WRITE_ERROR';
+ const status =
+ contentEditError.code === 'WRITE_ERROR'
+ ? 500
+ : skillMutationErrorStatus(contentEditError.code);
errorResponse(
res,
- isServerError ? 500 : 400,
- isServerError ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ status,
+ status === 500 ? '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),
+ cause: contentEditError.cause ?? new Error(contentEditError.message),
},
);
return;
diff --git a/packages/server/src/http/skills-file-routes.ts b/packages/server/src/http/skills-file-routes.ts
index 4c718af8f..a58d78a81 100644
--- a/packages/server/src/http/skills-file-routes.ts
+++ b/packages/server/src/http/skills-file-routes.ts
@@ -29,6 +29,8 @@ import {
BUNDLE_FILE_MAX_BYTES,
BUNDLE_MAX_FILES,
countBundleFiles,
+ skillMutationErrorStatus,
+ validateSkillMutationPath,
} from '../content/skills-write.ts';
import { isSkillBundlePathWithheld } from '../content-filter.ts';
import type {
@@ -158,13 +160,26 @@ function bundleTargetVerdict(skillDir: string, abs: string): 'admitted' | 'withh
function rejectUnadmittedBundleTarget(
res: ServerResponse,
+ boundary: string,
skillDir: string,
rel: string,
handler: string,
escapeTitle: string,
): boolean {
const verdict = bundleTargetVerdict(skillDir, resolve(skillDir, rel));
- if (verdict === 'admitted') return false;
+ if (verdict === 'admitted') {
+ const pathCheck = validateSkillMutationPath(boundary, skillDir, resolve(skillDir, rel));
+ if (pathCheck.ok) return false;
+ const status = skillMutationErrorStatus(pathCheck.error.code);
+ errorResponse(
+ res,
+ status,
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ pathCheck.error.message,
+ { handler, detail: `${rel}: ${pathCheck.error.code}`, cause: pathCheck.error.cause },
+ );
+ return true;
+ }
errorResponse(
res,
400,
@@ -403,6 +418,7 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
if (
rejectUnadmittedBundleTarget(
res,
+ fileBase,
skillDirAbs,
rel,
'skill-file-put',
@@ -459,6 +475,7 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
}
} else {
const fsResult = applySkillBundleFileWrite({
+ boundary: fileBase,
skillsRoot: dirname(skillDirAbs),
name: body.name,
relPath: rel,
@@ -470,7 +487,7 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
? 500
: fsResult.error.code === 'SKILL_NOT_FOUND'
? 404
- : 400;
+ : skillMutationErrorStatus(fsResult.error.code);
errorResponse(
res,
status,
@@ -561,12 +578,14 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
}
const realDir = resolveSkillDirForRead(scope, name);
const skillsRoot = realDir !== null ? dirname(realDir) : resolveSkillsRoot(scope);
+ const fileBase = scope === 'project' ? contentDir : skillsHome;
const bundleDir = realDir ?? join(skillsRoot, name);
const bundleAbs = resolve(bundleDir, rel);
if (
rejectUnadmittedBundleTarget(
res,
+ fileBase,
bundleDir,
rel,
'skill-file-delete',
@@ -591,9 +610,17 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
if (docs.length > 0) await captureAndCloseDocuments(docs, 'deleted-upstream');
}
- const result = applySkillBundleFileDelete({ skillsRoot, name, relPath: rel });
+ const result = applySkillBundleFileDelete({
+ boundary: fileBase,
+ skillsRoot,
+ name,
+ relPath: rel,
+ });
if (!result.ok) {
- const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;
+ const status =
+ result.error.code === 'UNLINK_FAILED'
+ ? 500
+ : skillMutationErrorStatus(result.error.code);
errorResponse(
res,
status,
@@ -685,10 +712,12 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
return;
}
const skillsRoot = dirname(realDir);
+ const fileBase = body.scope === 'project' ? contentDir : skillsHome;
if (
[from, to].some((rel) =>
rejectUnadmittedBundleTarget(
res,
+ fileBase,
realDir,
rel,
'skill-file-rename',
@@ -720,13 +749,17 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
}
const result = applySkillBundleFileRename({
+ boundary: fileBase,
skillsRoot,
name: body.name,
relPath: from,
toRelPath: to,
});
if (!result.ok) {
- const status = result.error.code === 'RENAME_FAILED' ? 500 : 400;
+ const status =
+ result.error.code === 'RENAME_FAILED'
+ ? 500
+ : skillMutationErrorStatus(result.error.code);
errorResponse(
res,
status,
diff --git a/packages/server/src/http/skills-import-routes.ts b/packages/server/src/http/skills-import-routes.ts
index 3013039c6..b5f8f255b 100644
--- a/packages/server/src/http/skills-import-routes.ts
+++ b/packages/server/src/http/skills-import-routes.ts
@@ -398,7 +398,7 @@ export function createSkillsImportRoutes(deps: SkillsImportRouteDeps): ApiRouteG
status: 'failed',
warnings: [],
warningCodes: [],
- error: outcome.detail ?? outcome.title,
+ error: outcome.detail ? `${outcome.title} (${outcome.detail})` : outcome.title,
});
continue;
}
diff --git a/packages/server/src/http/skills-recovery-routes.ts b/packages/server/src/http/skills-recovery-routes.ts
index 8054711a9..84c752585 100644
--- a/packages/server/src/http/skills-recovery-routes.ts
+++ b/packages/server/src/http/skills-recovery-routes.ts
@@ -646,7 +646,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRo
source: entry.source,
warnings: [],
warningCodes: [],
- error: outcome.detail ?? outcome.title,
+ error: outcome.detail ? `${outcome.title} (${outcome.detail})` : outcome.title,
});
continue;
}
diff --git a/packages/server/src/services/skill-import.ts b/packages/server/src/services/skill-import.ts
index 10b0635ef..2493f4ef6 100644
--- a/packages/server/src/services/skill-import.ts
+++ b/packages/server/src/services/skill-import.ts
@@ -20,6 +20,7 @@ import {
applySkillBundleFileWrite,
applySkillDelete,
applySkillWrite,
+ skillMutationErrorStatus,
} from '../content/skills-write.ts';
import type { extractActorIdentity } from '../extract-actor-identity.ts';
import { sanitizeFilename } from '../filename-sanitize.ts';
@@ -204,6 +205,7 @@ export function createSkillImportService(deps: SkillImportDeps): SkillImportServ
const skillBody = acquiredDoc.body;
const pack = packMarkerOf(acquiredDoc.frontmatter);
const wr = applySkillWrite({
+ boundary: importBase,
skillsRoot: importRoot,
name: targetName,
body: skillBody,
@@ -214,18 +216,21 @@ export function createSkillImportService(deps: SkillImportDeps): SkillImportServ
},
});
if (!wr.ok) {
+ const status = skillMutationErrorStatus(wr.error.code);
return {
ok: false,
- status: 400,
- urn: 'urn:ok:error:invalid-request',
- title: 'Failed to write imported skill.',
+ status,
+ urn:
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ title: wr.error.message,
detail: wr.error.code,
- cause: new Error(wr.error.message),
+ cause: wr.error.cause ?? new Error(wr.error.message),
};
}
const warnings = [...wr.warnings];
for (const f of acquired.files) {
const br = applySkillBundleFileWrite({
+ boundary: importBase,
skillsRoot: importRoot,
name: targetName,
relPath: f.relPath,
@@ -235,12 +240,14 @@ export function createSkillImportService(deps: SkillImportDeps): SkillImportServ
});
if (!br.ok) {
const rollback = applySkillDelete({ skillsRoot: importRoot, name: targetName });
+ const status = rollback.ok ? skillMutationErrorStatus(br.error.code) : 500;
return {
ok: false,
- status: rollback.ok ? 400 : 500,
- urn: rollback.ok
- ? 'urn:ok:error:invalid-request'
- : 'urn:ok:error:internal-server-error',
+ status,
+ urn:
+ status === 400
+ ? 'urn:ok:error:invalid-request'
+ : 'urn:ok:error:internal-server-error',
title: 'Failed to write the complete imported skill bundle.',
detail: `${f.relPath}: ${br.error.code}`,
cause: new Error(
diff --git a/packages/server/src/services/skill-reimport.ts b/packages/server/src/services/skill-reimport.ts
index 4591c82c8..8579a965c 100644
--- a/packages/server/src/services/skill-reimport.ts
+++ b/packages/server/src/services/skill-reimport.ts
@@ -19,6 +19,8 @@ import {
applySkillBundleFileDelete,
applySkillBundleFileWrite,
applySkillWrite,
+ skillMutationErrorStatus,
+ validateSkillMutationPath,
} from '../content/skills-write.ts';
import type { extractActorIdentity } from '../extract-actor-identity.ts';
import { mutateSkillsLock } from '../skills-lock-store.ts';
@@ -240,6 +242,33 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpo
const skillBody = acquiredDoc.body;
const acquiredPack = packMarkerOf(acquiredDoc.frontmatter);
+ const skillDir = resolve(skillsRoot, name);
+ for (const relPath of [
+ 'SKILL.md',
+ ...acquired.files.map((f) => f.relPath),
+ ...removedUpstream,
+ ]) {
+ const pathCheck = validateSkillMutationPath(
+ reimportBase,
+ skillDir,
+ resolve(skillDir, relPath),
+ );
+ if (!pathCheck.ok) {
+ const status = skillMutationErrorStatus(pathCheck.error.code);
+ return {
+ ok: false,
+ status,
+ urn:
+ status === 500
+ ? 'urn:ok:error:internal-server-error'
+ : 'urn:ok:error:invalid-request',
+ title: pathCheck.error.message,
+ detail: `${relPath}: ${pathCheck.error.code}`,
+ cause: pathCheck.error.cause ?? new Error(pathCheck.error.message),
+ };
+ }
+ }
+
if (params.dryRun) {
let gitTracked: boolean | undefined;
if (scope === 'project' && deps.projectDir) {
@@ -275,6 +304,7 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpo
}
}
const wr = applySkillWrite({
+ boundary: reimportBase,
skillsRoot,
name,
body: skillBody,
@@ -285,18 +315,21 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpo
},
});
if (!wr.ok) {
+ const status = skillMutationErrorStatus(wr.error.code);
return {
ok: false,
- status: 400,
- urn: 'urn:ok:error:invalid-request',
- title: 'Failed to write skill.',
+ status,
+ urn:
+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
+ title: wr.error.message,
detail: wr.error.code,
- cause: new Error(wr.error.message),
+ cause: wr.error.cause ?? new Error(wr.error.message),
};
}
const warnings = [...wr.warnings];
for (const f of acquired.files) {
const br = applySkillBundleFileWrite({
+ boundary: reimportBase,
skillsRoot,
name,
relPath: f.relPath,
@@ -316,7 +349,12 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpo
}
}
for (const relPath of removedUpstream) {
- const deleted = applySkillBundleFileDelete({ skillsRoot, name, relPath });
+ const deleted = applySkillBundleFileDelete({
+ boundary: reimportBase,
+ skillsRoot,
+ name,
+ relPath,
+ });
if (!deleted.ok) {
return {
ok: false,
diff --git a/packages/server/src/shadow-repo.test.ts b/packages/server/src/shadow-repo.test.ts
index a56d338e5..8426f186c 100644
--- a/packages/server/src/shadow-repo.test.ts
+++ b/packages/server/src/shadow-repo.test.ts
@@ -2329,6 +2329,7 @@ describe('shadow repo excludes OpenKnowledge machine-local state', () => {
fsTracedRecorder.renameSources.length = 0;
const written = applySkillWrite({
+ boundary: projectRoot,
skillsRoot,
name: 'trip-log',
body: '# Steps\n\nDo the thing.',