Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): stop creating agent host folders without consent (PRD-7984) (#3443)

tim-inkeep2c01b7d4a5e8
diff --git a/.changeset/orange-pots-taste.md b/.changeset/orange-pots-taste.md
new file mode 100644
index 000000000..665b4b9d0
--- /dev/null
+++ b/.changeset/orange-pots-taste.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+OpenKnowledge no longer creates agent integration folders for tools you do not have. Project setup, launch-time skill maintenance, store migration, import, starter-pack seeding and repair now write only into agent folders that already exist, and skip cleanly when none do. Creating a project pre-selects the agents detected on your machine rather than every agent OpenKnowledge knows about, and `.agents` is treated like any other agent folder instead of always being written. Explicit choices are still honored, including installing into `.agents` when you select it.
diff --git a/knip.config.ts b/knip.config.ts
index f9179f2d4..78162ec09 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -123,9 +123,7 @@ 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'],
diff --git a/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx b/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx
index 83fd72fe4..486aa2ac3 100644
--- a/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx
+++ b/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx
@@ -179,6 +179,16 @@ function makeStubBridge(
return currentPickedParent;
},
},
+ integrations: {
+ // CreateProjectDialog seeds its editor checkboxes off this on open.
+ status: async () => ({
+ available: false,
+ editors: [],
+ path: { shellDetected: false, rcFilesToTouch: [], installed: false },
+ skills: [],
+ detectedEditorIds: [],
+ }),
+ },
project: {
recordCreateNewBannerShown: async () => undefined,
createNew: async () => undefined,
diff --git a/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx b/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
index a072159bc..ab504524d 100644
--- a/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
+++ b/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
@@ -66,8 +66,17 @@ const PARENT = '/Users/test/Projects';
const PROJECT_NAME = 'Runtime Project';
const SECOND_PARENT = '/Users/test/OtherProjects';
+// The tools the fake machine "has installed". Deliberately a strict, non-empty
+// subset of ALL_EDITOR_IDS so the seeded default is distinguishable from both
+// the empty set and the everything set.
+const DETECTED: OkMcpWiringEditorId[] = ['claude', 'cursor'];
+// An editor the fake machine does NOT have — must never be pre-checked, and
+// must never reach the createNew payload unless the user ticks it.
+const UNDETECTED: OkMcpWiringEditorId = 'codex';
+
function makeBridge() {
let pickedParent: string | null = PARENT;
+ let detectedEditorIdsImpl = (): Promise<OkMcpWiringEditorId[]> => Promise.resolve([...DETECTED]);
let defaultRootImpl = (): Promise<string> => Promise.resolve(PARENT);
let folderStateImpl = async (_path: string): Promise<OkFolderState> => 'free';
let createNewImpl = (): Promise<void> => Promise.resolve();
@@ -99,6 +108,18 @@ function makeBridge() {
return Promise.resolve(pickedParent);
}),
},
+ integrations: {
+ // The dialog reads only `detectedEditorIds` off this snapshot; the rest of
+ // the shape exists so the fake matches the real status contract.
+ status: vi.fn(async () => ({
+ available: true,
+ editors: [],
+ path: { shellDetected: false, rcFilesToTouch: [], installed: false },
+ skills: [],
+ detectedEditorIds: await detectedEditorIdsImpl(),
+ })),
+ setComponent: vi.fn(),
+ },
project: {
recordCreateNewBannerShown: vi.fn((banner: string) => {
bannerCalls.push(banner);
@@ -129,6 +150,9 @@ function makeBridge() {
setPickedParent: (next: string | null) => {
pickedParent = next;
},
+ setDetectedEditorsImpl: (next: () => Promise<OkMcpWiringEditorId[]>) => {
+ detectedEditorIdsImpl = next;
+ },
setDefaultProjectsRootImpl: (next: () => Promise<string>) => {
defaultRootImpl = next;
},
@@ -184,7 +208,7 @@ describe('CreateProjectDialog runtime wiring', () => {
cleanup();
});
- test('name input is first and submit posts {parent, name} derived from the two fields', async () => {
+ test('detected agent harnesses start selected, undetected ones do not, and edits ride along', async () => {
const stub = await renderDialog();
const form = screen.getByTestId('create-project-form') as HTMLFormElement;
@@ -219,12 +243,26 @@ describe('CreateProjectDialog runtime wiring', () => {
fireEvent.click(screen.getByTestId('create-advanced-trigger'));
expect(screen.getByTestId('create-sharing')).not.toBeNull();
+ // Every editor still renders a labelled row; only the DETECTED ones come
+ // pre-checked. A tool whose host root does not exist is never pre-selected,
+ // so we never create a config dir for something the user doesn't have.
+ await waitFor(() => {
+ expect(screen.getByTestId('create-editor-claude').getAttribute('aria-checked')).toBe('true');
+ });
for (const id of ALL_EDITOR_IDS) {
const checkbox = screen.getByTestId(`create-editor-${id}`);
expect(checkbox.closest('label')?.textContent).toContain(EDITOR_LABELS[id]);
- expect(checkbox.getAttribute('aria-checked')).toBe('true');
+ expect(checkbox.getAttribute('aria-checked')).toBe(DETECTED.includes(id) ? 'true' : 'false');
}
+ expect(screen.getByTestId(`create-editor-${UNDETECTED}`).getAttribute('aria-checked')).toBe(
+ 'false',
+ );
+ // Ticking an undetected tool adds it; unticking a detected one drops it.
+ fireEvent.click(screen.getByTestId(`create-editor-${UNDETECTED}`));
+ expect(screen.getByTestId(`create-editor-${UNDETECTED}`).getAttribute('aria-checked')).toBe(
+ 'true',
+ );
fireEvent.click(screen.getByTestId('create-editor-cursor'));
expect(screen.getByTestId('create-editor-cursor').getAttribute('aria-checked')).toBe('false');
@@ -238,18 +276,94 @@ describe('CreateProjectDialog runtime wiring', () => {
fireEvent.click(submit);
await waitFor(() => {
- expect(stub.createNewCalls).toEqual([
- {
- parent: PARENT,
- name: PROJECT_NAME,
- editors: ALL_EDITOR_IDS.filter((id) => id !== 'cursor'),
- sharing: 'shared',
- },
- ]);
+ expect(stub.createNewCalls).toHaveLength(1);
});
+ const submitted = stub.createNewCalls[0];
+ expect(submitted?.parent).toBe(PARENT);
+ expect(submitted?.name).toBe(PROJECT_NAME);
+ expect(submitted?.sharing).toBe('shared');
+ expect([...(submitted?.editors ?? [])].sort()).toEqual(['claude', UNDETECTED].sort());
expect(stub.onOpenChange).toHaveBeenLastCalledWith(false);
});
+ test('submitting without ever opening Advanced settings wires the detected editors', async () => {
+ // The regression this pins: the editor checkboxes live behind a collapsed
+ // "Advanced settings" section, so the overwhelmingly common path is
+ // name → Create. That path must still produce MCP config + the project
+ // skill for the tools the user actually has — an empty `editors` array
+ // silently yields a project wired to nothing, and nothing back-fills it.
+ const stub = await renderDialog();
+ await waitForLocationHydrate();
+
+ // Advanced is never expanded in this test.
+ expect(screen.queryByTestId('create-editor-claude')).toBeNull();
+
+ await typeProjectName(PROJECT_NAME);
+ await waitForSubmitEnabled();
+ fireEvent.click(screen.getByTestId('create-submit'));
+
+ await waitFor(() => {
+ expect(stub.createNewCalls).toHaveLength(1);
+ });
+ expect([...(stub.createNewCalls[0]?.editors ?? [])].sort()).toEqual([...DETECTED].sort());
+ });
+
+ test('a failed detection probe leaves the selection empty rather than guessing', async () => {
+ // Degrade toward writing nothing, never toward creating host roots for
+ // tools we could not confirm. Advanced settings remains the manual escape.
+ const stub = makeBridge();
+ stub.setDetectedEditorsImpl(() => Promise.reject(new Error('detection blew up')));
+ await renderDialog(stub);
+ await waitForLocationHydrate();
+
+ await typeProjectName(PROJECT_NAME);
+ await waitForSubmitEnabled();
+ fireEvent.click(screen.getByTestId('create-submit'));
+
+ await waitFor(() => {
+ expect(stub.createNewCalls).toHaveLength(1);
+ });
+ expect(stub.createNewCalls[0]?.editors).toEqual([]);
+ });
+
+ test('a detection probe that lands after the user ticks does not clobber the selection', async () => {
+ // Seeding is an async round-trip the user can beat: Advanced is one click
+ // away and the checkboxes are live well before `integrations.status()`
+ // resolves. Whatever the checkboxes show after the user's click is what
+ // gets submitted — a late seed neither replaces nor merges into it.
+ let releaseDetection = (): void => {};
+ const stub = makeBridge();
+ stub.setDetectedEditorsImpl(
+ () =>
+ new Promise<OkMcpWiringEditorId[]>((resolve) => {
+ releaseDetection = () => resolve([...DETECTED]);
+ }),
+ );
+ await renderDialog(stub);
+ await waitForLocationHydrate();
+
+ fireEvent.click(screen.getByTestId('create-advanced-trigger'));
+ fireEvent.click(screen.getByTestId(`create-editor-${UNDETECTED}`));
+ expect(screen.getByTestId(`create-editor-${UNDETECTED}`).getAttribute('aria-checked')).toBe(
+ 'true',
+ );
+
+ releaseDetection();
+
+ await typeProjectName(PROJECT_NAME);
+ await waitForSubmitEnabled();
+ expect(screen.getByTestId(`create-editor-${UNDETECTED}`).getAttribute('aria-checked')).toBe(
+ 'true',
+ );
+ expect(screen.getByTestId('create-editor-claude').getAttribute('aria-checked')).toBe('false');
+
+ fireEvent.click(screen.getByTestId('create-submit'));
+ await waitFor(() => {
+ expect(stub.createNewCalls).toHaveLength(1);
+ });
+ expect(stub.createNewCalls[0]?.editors).toEqual([UNDETECTED]);
+ });
+
test('reopening the dialog re-collapses Advanced so sharing is hidden again', async () => {
// Sharing now lives inside Advanced, so "the dialog leads with just name +
// location" depends on the on-open reset collapsing Advanced every time.
diff --git a/packages/app/src/components/CreateProjectDialog.tsx b/packages/app/src/components/CreateProjectDialog.tsx
index 9cb81d2d4..5de74a4ea 100644
--- a/packages/app/src/components/CreateProjectDialog.tsx
+++ b/packages/app/src/components/CreateProjectDialog.tsx
@@ -9,8 +9,9 @@
* on open) followed by a Location field (read-only display + Browse button
* that picks the PARENT directory). A live "Will be created at: …" caption
* shows the resolved target before submit. The config-sharing posture
- * (side-by-side radio cards) and the editor-checkbox group (all default ON)
- * both collapse under an "Advanced settings" section. Cancel +
+ * (side-by-side radio cards) and the editor-checkbox group (pre-checked from
+ * `bridge.integrations.status().detectedEditorIds` on open) both collapse under
+ * an "Advanced settings" section. Cancel +
* Create footer. Create stays enabled with an empty name — a click then
* surfaces an "Enter a project name" toast (see onSubmit) rather than sitting
* disabled with no hint. The two fields (`location`, `name`) are the source of
@@ -324,9 +325,15 @@ export function CreateProjectDialog({
// Project name typed into the always-present <Input>. The creation target
// is `joinPathPreview(location, sanitizeFolderName(name))`.
const [name, setName] = useState('');
- const [editorIds, setEditorIds] = useState<ReadonlySet<OkMcpWiringEditorId>>(
- () => new Set(ALL_EDITOR_IDS),
- );
+ // AI tools that get wired on submit. Seeded on each open from
+ // `bridge.integrations.status().detectedEditorIds` — the tools whose host root
+ // already exists on this machine — because the checkboxes live behind a collapsed
+ // "Advanced settings" section: a user who types a name and clicks Create
+ // never sees them, so an empty default would silently produce a project with
+ // no MCP config and no project skill for tools they DO have. Seeding from
+ // detection keeps the other half of that contract too: we never create a
+ // host root for a tool the user doesn't have.
+ const [editorIds, setEditorIds] = useState<ReadonlySet<OkMcpWiringEditorId>>(() => new Set());
// OK config sharing mode. Defaults to `'shared'` (encourages team
// adoption). Rendered via SharingModeField inside "Advanced settings" — the
// greenfield dialog tucks the choice away (sensible default already set),
@@ -370,6 +377,12 @@ export function CreateProjectDialog({
// banner, so a result that arrives after the banner has moved on would
// otherwise be lost without UX feedback).
const removeGitCallIdRef = useRef(0);
+ // True once the user has toggled an editor checkbox during the current open.
+ // The on-open detection probe is async, so a user who expands Advanced and
+ // ticks a box before it resolves would otherwise have their choice silently
+ // overwritten by the seed landing late. What the checkboxes show right after
+ // their click is the truth; a late probe never overrides it.
+ const editorsTouchedRef = useRef(false);
// Hydrate Location + focus the Name input on dialog open. Reset transient
// state (banner-fired set, error, busy, name, editors, removeGitState) so
@@ -387,7 +400,8 @@ export function CreateProjectDialog({
setProbeLifecycle('idle');
setBusy(false);
setName('');
- setEditorIds(new Set(ALL_EDITOR_IDS));
+ setEditorIds(new Set());
+ editorsTouchedRef.current = false;
setSharing('shared');
setAdvancedOpen(false);
setRemoveGitState({ kind: 'idle' });
@@ -397,6 +411,22 @@ export function CreateProjectDialog({
removeGitCallIdRef.current += 1;
let cancelled = false;
+ // Re-probe detection on every open (the user may have installed a tool
+ // since last time). A selection the user has already edited wins over the
+ // seed: this probe is a round-trip the user can beat.
+ bridge.integrations
+ .status()
+ .then((status) => {
+ if (!cancelled && !editorsTouchedRef.current) {
+ setEditorIds(new Set(status.detectedEditorIds));
+ }
+ })
+ .catch((err) => {
+ // Best-effort: leave the selection empty so we never create a host
+ // root for a tool we could not confirm. Advanced settings still works.
+ console.warn('[CreateProjectDialog] editor-detection probe failed:', err);
+ });
+
// Reset Location before refetching — second-open after a first-open
// success leaves a stale value visible if defaultProjectsRoot() rejects
// this time. The catch handler's "leave location empty on failure"
@@ -651,6 +681,7 @@ export function CreateProjectDialog({
const submitDisabled = busy || (rawName !== '' && !canSubmit);
function toggleEditor(id: OkMcpWiringEditorId) {
+ editorsTouchedRef.current = true;
setEditorIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
diff --git a/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx b/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx
index 136894849..37b35e125 100644
--- a/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx
+++ b/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx
@@ -65,6 +65,16 @@ function makeBridge(): OkDesktopBridge {
fs: {
defaultProjectsRoot: async (): Promise<string> => '/Users/test/Projects',
},
+ integrations: {
+ // CreateProjectDialog seeds its editor checkboxes off this on open.
+ status: async () => ({
+ available: false,
+ editors: [],
+ path: { shellDetected: false, rcFilesToTouch: [], installed: false },
+ skills: [],
+ detectedEditorIds: [],
+ }),
+ },
project: {
recordCreateNewBannerShown: async () => undefined,
createNew: async () => undefined,
diff --git a/packages/app/src/components/NavigatorApp.dom.test.tsx b/packages/app/src/components/NavigatorApp.dom.test.tsx
index 053851bda..2e87b1a6a 100644
--- a/packages/app/src/components/NavigatorApp.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.dom.test.tsx
@@ -98,6 +98,16 @@ function createBridge() {
projectName: 'Project Navigator',
mode: 'navigator',
},
+ integrations: {
+ // CreateProjectDialog seeds its editor checkboxes off this on open.
+ status: async () => ({
+ available: false,
+ editors: [],
+ path: { shellDetected: false, rcFilesToTouch: [], installed: false },
+ skills: [],
+ detectedEditorIds: [],
+ }),
+ },
project: {
listRecent: vi.fn(() =>
Promise.resolve([{ path: '/projects/recent', name: 'Recent Project' }]),
diff --git a/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx b/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx
index 9f15afe1b..16f8ed4e2 100644
--- a/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx
@@ -139,6 +139,16 @@ function createBridge(recents: unknown[]) {
onMenuAction: vi.fn(() => () => {}),
onRecentRemovedMissing: vi.fn(() => () => {}),
config: { mode: 'navigator' },
+ integrations: {
+ // CreateProjectDialog seeds its editor checkboxes off this on open.
+ status: async () => ({
+ available: false,
+ editors: [],
+ path: { shellDetected: false, rcFilesToTouch: [], installed: false },
+ skills: [],
+ detectedEditorIds: [],
+ }),
+ },
project: {
listRecent: vi.fn(() => Promise.resolve(recents)),
removeRecent: vi.fn(() => Promise.resolve()),
diff --git a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
index a6d7779c5..400ba9ea1 100644
--- a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
@@ -92,6 +92,16 @@ function makeNavigatorBridge(): NavigatorBridgeStub {
},
onMenuAction: () => () => {},
onRecentRemovedMissing: () => () => {},
+ integrations: {
+ // CreateProjectDialog seeds its editor checkboxes off this on open.
+ status: async () => ({
+ available: false,
+ editors: [],
+ path: { shellDetected: false, rcFilesToTouch: [], installed: false },
+ skills: [],
+ detectedEditorIds: [],
+ }),
+ },
project: {
listRecent: async () => [],
removeRecent: async () => undefined,
diff --git a/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts b/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
index e13e85c6a..8c8bbab84 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
@@ -17,7 +17,7 @@
* live under `<home>/.{host}/skills/`.
*/
-import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
@@ -100,6 +100,13 @@ async function moveCrossScope(
beforeAll(async () => {
tmpHome = mkdtempSync(join(tmpdir(), 'ok-xscope-uninstall-home-'));
+ // Adopt the vendor-neutral `.agents` hub in the throwaway home. A
+ // caller-supplied `configHomedirOverride` owns its own host set, and skill
+ // destinations resolve via `resolveDefaultSkillHomeRel`, which refuses (400
+ // `NO_USABLE_SKILL_HOME`) when the home has adopted none — OK never creates
+ // one on the user's behalf. The hub, not `.claude`, keeps the global source
+ // dir distinct from the claude PROJECTION dir this file asserts on.
+ mkdirSync(join(tmpHome, '.agents', 'skills'), { recursive: true });
server = await createTestServer({ configHomedirOverride: tmpHome });
}, HARNESS_BOOT_TIMEOUT_MS);
afterAll(async () => {
diff --git a/packages/app/tests/integration/api-error-envelope/skill-move-scope-symlinked-source.test.ts b/packages/app/tests/integration/api-error-envelope/skill-move-scope-symlinked-source.test.ts
index 78811a8a3..4545918c8 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-move-scope-symlinked-source.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-move-scope-symlinked-source.test.ts
@@ -53,6 +53,12 @@ const moveScope = (name: string, fromScope: string, toScope: string) =>
beforeEach(async () => {
tmpHome = mkdtempSync(join(tmpdir(), 'ok-move-symlink-home-'));
+ // Adopt a harness in the throwaway home. A caller-supplied
+ // `configHomedirOverride` owns its own host set, and skill destinations
+ // resolve via `resolveDefaultSkillHomeRel`, which refuses (400
+ // `NO_USABLE_SKILL_HOME`) when the home has adopted none — OK never creates
+ // one on the user's behalf.
+ mkdirSync(join(tmpHome, '.claude', 'skills'), { recursive: true });
server = await createTestServer({ configHomedirOverride: tmpHome });
}, HARNESS_BOOT_TIMEOUT_MS);
afterEach(async () => {
diff --git a/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts b/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
index 7b62c9dcd..41c643a14 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
@@ -126,6 +126,12 @@ async function scopeOf(name: string): Promise<string | undefined> {
beforeAll(async () => {
tmpHome = mkdtempSync(join(tmpdir(), 'ok-scope-move-home-'));
+ // Adopt a harness in the throwaway home. A caller-supplied
+ // `configHomedirOverride` owns its own host set, and skill destinations
+ // resolve via `resolveDefaultSkillHomeRel`, which refuses (400
+ // `NO_USABLE_SKILL_HOME`) when the home has adopted none — OK never creates
+ // one on the user's behalf.
+ mkdirSync(join(tmpHome, '.claude', 'skills'), { recursive: true });
server = await createTestServer({ configHomedirOverride: tmpHome });
}, HARNESS_BOOT_TIMEOUT_MS);
afterAll(async () => {
diff --git a/packages/app/tests/integration/skill-import.test.ts b/packages/app/tests/integration/skill-import.test.ts
index 47dda3d37..0df67294a 100644
--- a/packages/app/tests/integration/skill-import.test.ts
+++ b/packages/app/tests/integration/skill-import.test.ts
@@ -1,6 +1,7 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { EDITOR_USER_SKILL_ROOT } from '@inkeep/open-knowledge-core';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import {
createTestServer,
@@ -38,6 +39,7 @@ describe('POST /api/skill/import', () => {
let server: TestServer;
beforeEach(async () => {
server = await createTestServer();
+ mkdirSync(join(server.contentDir, '.claude'), { recursive: true });
});
afterEach(async () => {
await server.cleanup();
@@ -51,6 +53,32 @@ describe('POST /api/skill/import', () => {
body: JSON.stringify(payload),
});
+ test('project import reports no usable target without creating a host root', async () => {
+ rmSync(join(server.contentDir, '.claude'), { recursive: true, force: true });
+ rmSync(join(server.contentDir, '.agents'), { recursive: true, force: true });
+ const dir = join(srcRoot, 'project-no-host');
+ writeSkillDir(dir, 'project-no-host', 'No implicit host');
+
+ const res = await importSkill({ source: dir });
+ const body = (await res.json()) as { detail?: string; title?: string };
+
+ expect({
+ status: res.status,
+ detail: body.detail,
+ claudeRootExists: existsSync(join(server.contentDir, '.claude')),
+ agentsRootExists: existsSync(join(server.contentDir, '.agents')),
+ }).toEqual({
+ status: 400,
+ detail: 'NO_USABLE_SKILL_HOME',
+ claudeRootExists: false,
+ agentsRootExists: false,
+ });
+ // The refusal has to be actionable, not merely correct: name the folders
+ // OK would accept and what to do, since it never creates one itself.
+ expect(body.title).toContain('.claude/');
+ expect(body.title).toContain('Create the folder your agent uses');
+ });
+
test('imports a local skill-dir as content + records provenance; scripts not executed', async () => {
const dir = join(srcRoot, 'single');
writeSkillDir(dir, 'cool-skill', 'Does cool things', '# Cool\n');
@@ -234,6 +262,7 @@ describe('POST /api/skill/import at global scope', () => {
homeDir = mkdtempSync(join(tmpdir(), 'ok-global-import-home-'));
sourceDir = mkdtempSync(join(tmpdir(), 'ok-global-import-source-'));
writeSkillDir(sourceDir, 'global-copy', 'Global plugin copy');
+ mkdirSync(join(homeDir, '.claude'), { recursive: true });
server = await createTestServer({ configHomedirOverride: homeDir });
});
@@ -277,12 +306,40 @@ describe('POST /api/skill/import at global scope', () => {
?.source,
).toBe(sourceDir);
});
+
+ test('global import reports no usable target without creating a host root', async () => {
+ for (const root of Object.values(EDITOR_USER_SKILL_ROOT)) {
+ const hostRoot = root?.split('/')[0];
+ if (hostRoot !== undefined) rmSync(join(homeDir, hostRoot), { recursive: true, force: true });
+ }
+ rmSync(join(homeDir, '.agents'), { recursive: true, force: true });
+
+ const res = await fetch(`${server.baseUrl}/api/skill/import`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ source: sourceDir, scope: 'global' }),
+ });
+ const body = (await res.json()) as { detail?: string };
+
+ expect({
+ status: res.status,
+ detail: body.detail,
+ claudeRootExists: existsSync(join(homeDir, '.claude')),
+ agentsRootExists: existsSync(join(homeDir, '.agents')),
+ }).toEqual({
+ status: 400,
+ detail: 'NO_USABLE_SKILL_HOME',
+ claudeRootExists: false,
+ agentsRootExists: false,
+ });
+ });
});
describe('POST /api/skill/reimport', () => {
let server: TestServer;
beforeEach(async () => {
server = await createTestServer();
+ mkdirSync(join(server.contentDir, '.claude'), { recursive: true });
});
afterEach(async () => {
await server.cleanup();
diff --git a/packages/app/tests/integration/skill-installable-editors.test.ts b/packages/app/tests/integration/skill-installable-editors.test.ts
index a81b7f50e..8723e943b 100644
--- a/packages/app/tests/integration/skill-installable-editors.test.ts
+++ b/packages/app/tests/integration/skill-installable-editors.test.ts
@@ -1,7 +1,11 @@
-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
+import {
+ PROJECT_SKILL_EDITOR_IDS,
+ SkillInstallSuccessSchema,
+ SkillsListSuccessSchema,
+} from '@inkeep/open-knowledge-core';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness';
@@ -25,6 +29,11 @@ beforeAll(async () => {
// the vendor-neutral authoring hub for a fresh global skill.
mkdirSync(join(tmpHome, '.agents', 'skills'), { recursive: true });
mkdirSync(join(tmpHome, '.claude', 'skills'), { recursive: true });
+ // `.gemini` is a DETECTED user skill host (Antigravity's user root is
+ // `~/.gemini/skills`) that has no project skill root, so it is not an
+ // install target. It also belongs to the standalone Gemini CLI, so its
+ // presence is not even evidence Antigravity is installed.
+ mkdirSync(join(tmpHome, '.gemini'), { recursive: true });
server = await createTestServer({ configHomedirOverride: tmpHome });
}, HARNESS_BOOT_TIMEOUT_MS);
afterAll(async () => {
@@ -64,3 +73,36 @@ describe('installableEditors gating (PRD-7600)', () => {
expect(project?.installableEditors).toContain('copilot');
});
});
+
+describe('default global install targets stay in the install-target vocabulary', () => {
+ /**
+ * Detection (`~/.gemini` → antigravity) is WIDER than the install-target
+ * vocabulary: an editor with no project skill root has no checkbox in the
+ * picker and is filtered out of `resolvedHosts`, so a projection there could
+ * never be seen or removed by a later set-exact install. Omitting `targets`
+ * must therefore yield the same vocabulary an explicit list is filtered to.
+ *
+ */
+ test('omitting targets never projects into a detected non-target host', async () => {
+ const name = 'vocab-skill';
+ expect((await putSkill('global', name)).status).toBe(200);
+
+ // `targets` OMITTED → the defaults branch under test.
+ const res = await fetch(`${base()}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'global', name }),
+ });
+ expect(res.status).toBe(200);
+ const parsed = SkillInstallSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (!parsed.success) return;
+
+ // Detection really ran: `.claude` is detected AND a valid target.
+ expect(parsed.data.hosts).toContain('claude');
+ // …and every emitted host round-trips (`agents` is the hub, not an editor).
+ const vocabulary = new Set<string>([...PROJECT_SKILL_EDITOR_IDS, 'agents']);
+ expect(parsed.data.hosts.filter((h) => !vocabulary.has(h))).toEqual([]);
+ expect(existsSync(join(tmpHome, '.gemini', 'skills', name))).toBe(false);
+ });
+});
diff --git a/packages/app/tests/integration/skill-scope-move-preserves-hosts.test.ts b/packages/app/tests/integration/skill-scope-move-preserves-hosts.test.ts
index ab8527b1d..b029aa4da 100644
--- a/packages/app/tests/integration/skill-scope-move-preserves-hosts.test.ts
+++ b/packages/app/tests/integration/skill-scope-move-preserves-hosts.test.ts
@@ -53,6 +53,12 @@ const globalProjection = (editor: (typeof EDITORS)[number], name: string) =>
beforeAll(async () => {
tmpHome = mkdtempSync(join(tmpdir(), 'ok-scope-move-hosts-home-'));
+ // Adopt a harness in the throwaway home. A caller-supplied
+ // `configHomedirOverride` owns its own host set, and skill destinations
+ // resolve via `resolveDefaultSkillHomeRel`, which refuses (400
+ // `NO_USABLE_SKILL_HOME`) when the home has adopted none — OK never creates
+ // one on the user's behalf.
+ mkdirSync(join(tmpHome, '.claude', 'skills'), { recursive: true });
server = await createTestServer({ configHomedirOverride: tmpHome });
}, HARNESS_BOOT_TIMEOUT_MS);
afterAll(async () => {
diff --git a/packages/app/tests/integration/skills-in-place-list.test.ts b/packages/app/tests/integration/skills-in-place-list.test.ts
index 63d7bba3b..068df1a08 100644
--- a/packages/app/tests/integration/skills-in-place-list.test.ts
+++ b/packages/app/tests/integration/skills-in-place-list.test.ts
@@ -460,6 +460,71 @@ describe('in-place skill install fan-out (R13 inversion)', () => {
}
});
+ test('global omitted targets project only into host roots that already exist', async () => {
+ const gContent = mkdtempSync(join(tmpdir(), 'ok-global-default-targets-content-'));
+ const home = mkdtempSync(join(tmpdir(), 'ok-global-default-targets-home-'));
+ writeSkill(home, '.codex/skills/globby', '# Native global');
+ mkdirSync(join(home, '.cursor'), { recursive: true });
+ const gServer = await createTestServer({
+ contentDir: gContent,
+ configHomedirOverride: home,
+ });
+ try {
+ // The harness bootstraps its own Claude platform bundle. Remove that
+ // fixture-created root so this request starts from the intended host set.
+ rmSync(join(home, '.claude'), { recursive: true, force: true });
+ rmSync(join(home, '.agents'), { recursive: true, force: true });
+ const res = await fetch(`http://127.0.0.1:${gServer.port}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'globby', scope: 'global' }),
+ });
+
+ expect(res.status).toBe(200);
+ expect(existsSync(join(home, '.codex/skills/globby/SKILL.md'))).toBe(true);
+ expect(existsSync(join(home, '.cursor/skills/globby/SKILL.md'))).toBe(true);
+ expect(existsSync(join(home, '.claude'))).toBe(false);
+ expect(existsSync(join(home, '.agents'))).toBe(false);
+ } finally {
+ await gServer.cleanup();
+ rmSync(gContent, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('global explicit targets may create a host root that does not exist yet', async () => {
+ const gContent = mkdtempSync(join(tmpdir(), 'ok-global-explicit-target-content-'));
+ const home = mkdtempSync(join(tmpdir(), 'ok-global-explicit-target-home-'));
+ writeSkill(home, '.codex/skills/globby', '# Native global');
+ const gServer = await createTestServer({
+ contentDir: gContent,
+ configHomedirOverride: home,
+ });
+ try {
+ // Keep the explicit-target precondition honest despite the harness's
+ // platform-skill bootstrap.
+ rmSync(join(home, '.claude'), { recursive: true, force: true });
+ rmSync(join(home, '.agents'), { recursive: true, force: true });
+ const res = await fetch(`http://127.0.0.1:${gServer.port}/api/skill/install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'globby',
+ scope: 'global',
+ targets: ['codex', 'agents'],
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ expect(existsSync(join(home, '.agents/skills/globby/SKILL.md'))).toBe(true);
+ expect(existsSync(join(home, '.claude'))).toBe(false);
+ } finally {
+ await gServer.cleanup();
+ rmSync(gContent, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
test('install copies the canonical to a new editor; uncheck removes only the copy', async () => {
// Check codex: canonical (.claude) stays, .codex gets a real copy.
const res = await install(['claude', 'codex']);
diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.ts
index f44a72bb8..a13e61102 100644
--- a/packages/app/tests/integration/test-harness.ts
+++ b/packages/app/tests/integration/test-harness.ts
@@ -216,6 +216,17 @@ export interface CreateTestServerOptions {
* retry within the test budget.
*/
agentSessionOptions?: ServerOptions['agentSessionOptions'];
+ /**
+ * Seed a `.claude/skills` host root in the fresh contentDir and the owned
+ * throwaway home. Skill create / import / duplicate / move resolve their
+ * destination via `resolveDefaultSkillHomeRel`, which refuses (`null` →
+ * HTTP 400 `NO_USABLE_SKILL_HOME`) when no harness home exists — OK never
+ * creates one on the user's behalf. A project that has adopted a harness is
+ * the normal shape for these tests, so the harness seeds one, exactly as it
+ * already seeds `.ok/config.yml`. Pass `false` to exercise the no-host
+ * refusal. Fresh contentDirs / owned homes only.
+ */
+ seedSkillHostRoot?: boolean;
}
export async function createTestServer(options: CreateTestServerOptions = {}): Promise<TestServer> {
@@ -236,6 +247,12 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
? realpathSync(mkdtempSync(join(tmpdir(), 'ok-test-home-')))
: null;
const homeOverride = options.configHomedirOverride ?? (ownedHomeDir as string);
+ // Same rationale as the contentDir host-root seed below, for global scope.
+ // Only the harness-owned home is seeded — a caller-supplied override owns its
+ // own host set (detection tests depend on that).
+ if (ownedHomeDir !== null && (options.seedSkillHostRoot ?? true)) {
+ mkdirSync(join(ownedHomeDir, '.claude', 'skills'), { recursive: true });
+ }
// No-project ephemeral shape: `.ok/local/` runtime state lives in a
// throwaway projectDir distinct from contentDir (the user's real dir). The
@@ -272,6 +289,14 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
writeFileSync(join(contentDir, '.ok', 'config.yml'), seedConfig, 'utf-8');
}
+ // Seed a harness home so skill destinations resolve. `.claude` is the
+ // highest-precedence concrete host, so this reproduces the paths these
+ // tests already assert without pinning them to a fallback OK no longer
+ // invents.
+ if (options.contentDir === undefined && (options.seedSkillHostRoot ?? true)) {
+ mkdirSync(join(contentDir, '.claude', 'skills'), { recursive: true });
+ }
+
// Mirror the production auto-git-init path: every fresh tmpDir gets a real
// .git/ so resolveShadowDir (which delegates to resolveGitDir) can locate
// the shadow under the project's gitdir. Tests in this harness use a
diff --git a/packages/app/tests/stress/_helpers/fixtures.ts b/packages/app/tests/stress/_helpers/fixtures.ts
index 4501d9b23..a057e360c 100644
--- a/packages/app/tests/stress/_helpers/fixtures.ts
+++ b/packages/app/tests/stress/_helpers/fixtures.ts
@@ -363,6 +363,12 @@ function seedRequiredFixtureFiles(contentDir: string): void {
writeFileSync(join(contentDir, 'test-doc.md'), '', 'utf-8');
mkdirSync(join(contentDir, 'sidebar-folder'), { recursive: true });
writeFileSync(join(contentDir, 'sidebar-folder', 'nested-doc.md'), '', 'utf-8');
+ // Adopt a harness so project skill create resolves a home. OK never creates
+ // an agent dir on the user's behalf, so a project with no adopted harness
+ // refuses skill authoring with `NO_USABLE_SKILL_HOME`. `.claude` is the
+ // highest-precedence concrete host. Same precedent as the integration
+ // harness's `seedSkillHostRoot` in tests/integration/test-harness.ts.
+ mkdirSync(join(contentDir, '.claude', 'skills'), { recursive: true });
}
export const test = base.extend<TestFixtures, WorkerFixtures>({
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index adbfcb6f8..7a2eb1001 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -530,6 +530,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
editors: [],
path: { shellDetected: false, rcFilesToTouch: [], installed: false },
skills: [],
+ detectedEditorIds: [],
}),
setComponent: async () => ({
ok: false as const,
@@ -539,6 +540,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
editors: [],
path: { shellDetected: false, rcFilesToTouch: [], installed: false },
skills: [],
+ detectedEditorIds: [],
},
}),
},
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index 2dff63217..f7847b6d5 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -116,6 +116,10 @@ describe('runInit', () => {
cwd: testDir,
home: fakeHome,
installUserSkill: defaultInstallUserSkill,
+ // Most tests in this suite predate the opt-in flag and exercise unrelated
+ // init behavior. Keep their install path explicit; consent-default tests
+ // override this with `skills: undefined`.
+ skills: true,
// Default to user scope so existing tests remain focused on user-scope
// behavior. New scope tests set scope explicitly.
scope: 'user',
@@ -682,6 +686,38 @@ describe('runInit', () => {
});
describe('multi-editor', () => {
+ it('omitted editors create project skills only for detected hosts', async () => {
+ rmSync(join(fakeHome, '.claude'), { recursive: true, force: true });
+
+ const noneDetected = await runInitForTest({ mcp: false });
+ expect(noneDetected.projectSkills).toEqual([]);
+ expect(existsSync(join(testDir, '.claude'))).toBe(false);
+ expect(existsSync(join(testDir, '.cursor'))).toBe(false);
+ expect(existsSync(join(testDir, '.agents'))).toBe(false);
+
+ mkdirSync(join(fakeHome, '.claude'), { recursive: true });
+ const claudeDetected = await runInitForTest({ mcp: false });
+ expect(claudeDetected.projectSkills.map((skill) => skill.editorId)).toEqual(['claude']);
+ expect(existsSync(join(testDir, '.claude', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ true,
+ );
+ expect(existsSync(join(testDir, '.cursor'))).toBe(false);
+ expect(existsSync(join(testDir, '.agents'))).toBe(false);
+ });
+
+ it('explicit editors remain authoritative when their roots do not exist yet', async () => {
+ rmSync(join(fakeHome, '.claude'), { recursive: true, force: true });
+
+ const result = await runInitForTest({ editors: ['cursor'], mcp: false });
+
+ expect(result.projectSkills.map((skill) => skill.editorId)).toEqual(['cursor']);
+ expect(existsSync(join(testDir, '.cursor', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ true,
+ );
+ expect(existsSync(join(testDir, '.claude'))).toBe(false);
+ expect(existsSync(join(testDir, '.agents'))).toBe(false);
+ });
+
it('writes Claude + Cursor configs in a single run', async () => {
mkdirSync(dirname(cursorConfigPath()), { recursive: true });
const result = await runInitForTest({ editors: ['claude', 'cursor'] });
@@ -1005,18 +1041,21 @@ describe('runInit', () => {
expect(capturedHome).toBe(fakeHome);
});
- it('FR6/D8: installs BOTH user-global bundles by default and records both enabled', async () => {
+ it('an omitted skill choice enables every bundle', async () => {
+ // Enabling is not writing. The folder-creation bug this change fixes
+ // lives in `installUserSkill`, which refuses every destination whose host
+ // root is absent, so a machine with no agent tooling still gets nothing
+ // from this path. Making the bundles opt-in instead would be a product
+ // change rather than a fix, so the flag semantics stay as they were.
const installed: (string | undefined)[] = [];
await runInitForTest({
+ skills: undefined,
installUserSkill: async (opts) => {
installed.push(opts?.bundleId);
return 'installed';
},
});
- expect(installed.sort()).toEqual(['discovery', 'write-skill']);
- // Decisions persisted so the desktop / start reclaim gates agree.
- expect(await readBundleDecision(fakeHome, 'open-knowledge-discovery')).toBe(true);
- expect(await readBundleDecision(fakeHome, 'open-knowledge-write-skill')).toBe(true);
+ expect([...installed].sort()).toEqual(['discovery', 'write-skill']);
});
it('--no-skills installs nothing and records NOTHING', async () => {
@@ -3262,7 +3301,10 @@ describe('resolveInitSkillEnablement — --skills / --no-skills flag parsing', (
const sorted = (skills: string | boolean | undefined): string[] =>
[...resolveInitSkillEnablement(skills)].sort();
- it('undefined (no flag) enables every user-global bundle', () => {
+ // Enabling is not writing: `installUserSkill` still refuses every destination
+ // whose host root is absent, so a machine with no agent tooling gets nothing
+ // regardless of what this returns.
+ it('undefined (no flag) enables every bundle', () => {
expect(sorted(undefined)).toEqual(['discovery', 'write-skill']);
});
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 856113d59..9f08e7a58 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -755,6 +755,10 @@ export class ContentDirError extends Error {
* / `--no-skills` flag: `undefined`/`true` → every bundle; `false`
* (`--no-skills`) → none; a comma list (`--skills discovery`) → only the named
* bundle ids (unknown tokens ignored — the known-id set wins).
+ *
+ * Enabling a bundle is not the same as writing it: `installUserSkill` still
+ * refuses every destination whose host root is absent, so a machine with no
+ * agent tooling gets nothing regardless of what this returns.
*/
export function resolveInitSkillEnablement(skills: string | boolean | undefined): Set<BundleId> {
if (skills === undefined || skills === true) return new Set(USER_GLOBAL_BUNDLE_IDS);
@@ -1703,17 +1707,11 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
// 2. Wire MCP config per editor (unless --no-mcp). Defaults are scope-aware:
// user-level writes stay limited to editors detected on this machine, while
- // project-level targets include every host with either a config or a skill
- // surface. That lets a global-MCP host such as Copilot receive its project
- // skill without duplicating its server into a shared workspace config.
+ // project-level targets use the same detected set unless the caller supplied
+ // an explicit selection. This keeps an omitted editor choice from creating
+ // host roots that did not already exist while preserving explicit targets.
const userEditorIds = options.editors ?? detectInstalledEditors(projectRoot, options.home);
- const projectEditorIds =
- options.editors ??
- ALL_EDITOR_IDS.filter(
- (id) =>
- EDITOR_TARGETS[id].projectConfigPath !== undefined ||
- EDITOR_TARGETS[id].projectSkillPath !== undefined,
- );
+ const projectEditorIds = options.editors ?? userEditorIds;
const userTargets = resolveEditorTargets(userEditorIds as EditorId[]);
const projectTargets = resolveEditorTargets(projectEditorIds as EditorId[]);
const skipMcp = options.mcp === false || scope === null;
diff --git a/packages/cli/src/commands/repair-skills.test.ts b/packages/cli/src/commands/repair-skills.test.ts
index 0a96bec11..847326e99 100644
--- a/packages/cli/src/commands/repair-skills.test.ts
+++ b/packages/cli/src/commands/repair-skills.test.ts
@@ -625,6 +625,7 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
it('AC-B2: refreshes central + per-host and advances skill-state when version mismatches', async () => {
// Seed the per-host roots so they aren't `skipped-host-absent`.
+ mkdirSync(join(scratch.home, '.agents'), { recursive: true });
mkdirSync(join(scratch.home, '.claude'), { recursive: true });
mkdirSync(join(scratch.home, '.cursor'), { recursive: true });
mkdirSync(join(scratch.home, '.codex'), { recursive: true });
@@ -688,7 +689,11 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
if (result.status !== 'done' || result.user.outcome !== 'done') throw new Error('unreachable');
const centralPath = join(scratch.home, '.agents', 'skills', USER_SKILL_DIR_NAME);
- expect(existsSync(join(centralPath, 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(centralPath, 'SKILL.md'))).toBe(false);
+ expect(existsSync(join(scratch.home, '.agents'))).toBe(false);
+ expect(
+ existsSync(join(scratch.home, '.claude', 'skills', USER_SKILL_DIR_NAME, 'SKILL.md')),
+ ).toBe(true);
expect(written).toEqual([{ home: scratch.home, version: '9.9.9' }]);
});
@@ -698,6 +703,7 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
// skill-state.yml, and the next boot's version-current fast path would
// permanently skip the central retry until the next CLI release.
mkdirSync(join(scratch.home, '.claude'), { recursive: true });
+ mkdirSync(join(scratch.home, '.agents'), { recursive: true });
const realFs = await import('node:fs');
const customFs: import('./repair-skills.ts').RepairSkillsFsOps = {
existsSync: (p) => realFs.existsSync(p),
@@ -790,8 +796,7 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
expect(written).toEqual([{ home: scratch.home, version: '9.9.9' }]);
});
- it('AC-B4: skips per-host writes when ~/.{host}/ root is absent (no spurious mkdir)', async () => {
- // Don't create .claude or .cursor — central still writes; per-host skips.
+ it('AC-B4: no existing user-skill host means no host is fabricated', async () => {
const written: Array<{ home: string; version: string }> = [];
const result = await repairSkills({
projectDir: scratch.project,
@@ -806,7 +811,7 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
}),
});
- if (result.status !== 'done' || result.user.outcome !== 'done') throw new Error('unreachable');
+ if (result.status !== 'done') throw new Error('unreachable');
const claudeEntry = result.user.entries.find(
(e) => e.kind === 'host' && e.editorId === 'claude',
@@ -820,11 +825,59 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
// The host roots stay absent — we don't author them.
expect(existsSync(join(scratch.home, '.claude'))).toBe(false);
expect(existsSync(join(scratch.home, '.cursor'))).toBe(false);
+ expect(existsSync(join(scratch.home, '.agents'))).toBe(false);
+
+ expect(written).toEqual([]);
+ });
- // Central still wrote — version advanced.
+ it('repairs an existing Pi user root without creating .agents', async () => {
+ mkdirSync(join(scratch.home, '.pi'), { recursive: true });
+ const written: Array<{ home: string; version: string }> = [];
+ const result = await repairSkills({
+ projectDir: scratch.project,
+ home: scratch.home,
+ deps: depsBuilder({
+ projectBundleDir,
+ discoveryBundleDir,
+ bundledVersion: '9.9.9',
+ recordedVersion: '0.6.0',
+ writtenVersions: written,
+ }),
+ });
+
+ if (result.status !== 'done' || result.user.outcome !== 'done') throw new Error('unreachable');
+ expect(
+ existsSync(join(scratch.home, '.pi', 'agent', 'skills', USER_SKILL_DIR_NAME, 'SKILL.md')),
+ ).toBe(true);
+ expect(existsSync(join(scratch.home, '.agents'))).toBe(false);
expect(written).toEqual([{ home: scratch.home, version: '9.9.9' }]);
});
+ it('recognizes current bundles installed only in a concrete Pi root', async () => {
+ for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
+ const dir = join(scratch.home, '.pi', 'agent', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), '# existing');
+ }
+ const written: Array<{ home: string; version: string }> = [];
+ const result = await repairSkills({
+ projectDir: scratch.project,
+ home: scratch.home,
+ deps: depsBuilder({
+ projectBundleDir,
+ discoveryBundleDir,
+ bundledVersion: '9.9.9',
+ recordedVersion: '9.9.9',
+ writtenVersions: written,
+ }),
+ });
+
+ if (result.status !== 'done') throw new Error('unreachable');
+ expect(result.user).toEqual({ outcome: 'skipped', reason: 'version-current' });
+ expect(existsSync(join(scratch.home, '.agents'))).toBe(false);
+ expect(written).toEqual([]);
+ });
+
it('reports skipped:bundle-missing when the discovery bundle dir resolve throws', async () => {
const written: Array<{ home: string; version: string }> = [];
const result = await repairSkills({
@@ -1151,7 +1204,7 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
expect(recordedEvents).toHaveLength(0);
});
- it('emits outcome=failed reason=central-write-failed when central fails AND no per-host dirs exist', async () => {
+ it('emits no failure when no user-skill host exists', async () => {
// Strictly synthetic existsSync — only paths we name as "present" return
// true. Lets the test assert "no host dirs visible" deterministically
// without depending on what the central-write side effects leave on disk.
@@ -1196,13 +1249,10 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
}),
});
- // No host dirs are present, so every host (claude, cursor, codex) hits
- // skipped-host-absent. The only failure is the central write itself, so
- // `central-write-failed` is the precise reason.
+ // No host dirs are present, so every host is skipped. `.agents` is not an
+ // implicit destination, so no write is attempted and no failure is emitted.
expect(presentPaths.size).toBe(0); // sanity: no host dirs marked present
- expect(recordedEvents).toHaveLength(1);
- expect(recordedEvents[0]?.outcome).toBe('failed');
- expect(recordedEvents[0]?.reason).toBe('central-write-failed');
+ expect(recordedEvents).toHaveLength(0);
});
it('emits outcome=failed reason=all-writes-failed when central AND per-host writes all throw', async () => {
@@ -1248,9 +1298,68 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
}),
});
- expect(recordedEvents).toHaveLength(1);
- expect(recordedEvents[0]?.outcome).toBe('failed');
- expect(recordedEvents[0]?.reason).toBe('all-writes-failed');
+ // One event per bundle — every gated bundle failed, and each names itself.
+ expect(recordedEvents).toHaveLength(2);
+ expect(recordedEvents.map((e) => e.outcome)).toEqual(['failed', 'failed']);
+ expect(recordedEvents.map((e) => e.reason)).toEqual(['all-writes-failed', 'all-writes-failed']);
+ expect(recordedEvents.map((e) => e.bundle).sort()).toEqual(['discovery', 'write-skill']);
+ });
+
+ it('a bundle that lands nowhere reports failed even when a sibling bundle succeeds', async () => {
+ // `.agents` absent (no central destination) and exactly one host root, so
+ // each bundle has exactly one candidate destination: `~/.claude/skills/…`.
+ mkdirSync(join(scratch.home, '.claude'), { recursive: true });
+ const realFs = await import('node:fs');
+ const failingBundleDir = 'open-knowledge-write-skill';
+ const customFs: import('./repair-skills.ts').RepairSkillsFsOps = {
+ existsSync: (p) => realFs.existsSync(p),
+ isDirectory: (p) => {
+ try {
+ return realFs.statSync(p).isDirectory();
+ } catch {
+ return false;
+ }
+ },
+ readdirSync: (p) => realFs.readdirSync(p),
+ readFileSync: (p) => realFs.readFileSync(p),
+ // Only the write-skill bundle's writes throw; discovery lands normally.
+ writeFileSync: (p, c) => {
+ if (p.includes(failingBundleDir)) throw new Error('synthetic: EACCES');
+ realFs.writeFileSync(p, c);
+ },
+ mkdirSync: (p, o) => {
+ realFs.mkdirSync(p, o);
+ },
+ rmSync: (p, o) => {
+ realFs.rmSync(p, o);
+ },
+ };
+
+ const written: Array<{ home: string; version: string }> = [];
+ const recordedEvents: SkillInstallEvent[] = [];
+
+ await repairSkills({
+ projectDir: scratch.project,
+ home: scratch.home,
+ fs: customFs,
+ deps: depsBuilder({
+ projectBundleDir,
+ discoveryBundleDir,
+ bundledVersion: '9.9.9',
+ recordedVersion: '0.6.0',
+ writtenVersions: written,
+ recordedEvents,
+ }),
+ });
+
+ // The sibling landed, but this bundle reached no destination at all.
+ const writeSkillEvents = recordedEvents.filter((e) => e.bundle === 'write-skill');
+ expect(writeSkillEvents).toHaveLength(1);
+ expect(writeSkillEvents[0]?.outcome).toBe('failed');
+ expect(writeSkillEvents[0]?.reason).toBe('all-writes-failed');
+ expect(recordedEvents.some((e) => e.outcome === 'skip-current')).toBe(false);
+ // Version stays unrecorded so the next boot retries the failed bundle.
+ expect(written).toEqual([]);
});
it('JSONL emission failures never propagate (telemetry must not affect install outcomes)', async () => {
diff --git a/packages/cli/src/commands/repair-skills.ts b/packages/cli/src/commands/repair-skills.ts
index 2b07d9a4d..382feda73 100644
--- a/packages/cli/src/commands/repair-skills.ts
+++ b/packages/cli/src/commands/repair-skills.ts
@@ -31,6 +31,7 @@ import {
import { homedir } from 'node:os';
import { dirname, join, relative, resolve as resolvePath } from 'node:path';
import { createInterface } from 'node:readline/promises';
+import { USER_SKILL_HOSTS } from '@inkeep/open-knowledge-core';
import {
BUNDLE_SKILL_NAME,
type BundleId,
@@ -282,12 +283,24 @@ function copyDirContents(sourceDir: string, destDir: string, fs: RepairSkillsFsO
}
}
+function userBundleExists(home: string, bundleName: string, fs: RepairSkillsFsOps): boolean {
+ return (
+ fs.existsSync(join(home, '.agents', 'skills', bundleName)) ||
+ USER_SKILL_HOSTS.some((host) => fs.existsSync(join(home, host.skillsRoot, bundleName)))
+ );
+}
+
/**
- * Install ONE user-global bundle into the central store + each per-host dir,
- * under its own `bundleDirName`. Returns the per-write entries and whether the
- * CENTRAL write landed (a fresh seed, for the outcome telemetry). Looped over
- * `USER_GLOBAL_BUNDLE_IDS` by `runUserSweep` so each user-global built-in
- * (discovery + write-skill) is seeded when absent.
+ * Install ONE user-global bundle into each existing user-skill host root,
+ * under its own `bundleDirName`. Returns the per-write entries, whether any
+ * write landed (a fresh seed, for the outcome telemetry), and whether the
+ * bundle reached any destination at all. Looped over `USER_GLOBAL_BUNDLE_IDS`
+ * by `runUserSweep` so each user-global built-in (discovery + write-skill) is
+ * seeded when absent.
+ *
+ * Both flags are PER BUNDLE by construction: the version-advance gate and the
+ * outcome event must not read them off a pooled entry list, or one bundle's
+ * success answers for a sibling that landed nowhere.
*/
function installUserBundleToHostDirs(
home: string,
@@ -296,20 +309,19 @@ function installUserBundleToHostDirs(
fs: RepairSkillsFsOps,
logger: (event: RepairSkillsLogEvent) => void,
version: string,
-): { entries: UserSkillEntry[]; centralWritten: boolean } {
+): { entries: UserSkillEntry[]; anyWritten: boolean; anyDestinationSucceeded: boolean } {
const entries: UserSkillEntry[] = [];
const centralDest = join(home, '.agents', 'skills', bundleDirName);
- let centralWritten = false;
// SEED-IF-ABSENT: guarantee the built-in is PRESENT
// but never OVERWRITE an existing copy — that copy may be a user-applied
// skills.sh update. Updates flow through the manual "update available" path,
// not this sweep. Matches the desktop reclaim's gate exactly.
- if (fs.existsSync(centralDest)) {
+ const centralRootExists = fs.existsSync(join(home, '.agents'));
+ if (centralRootExists && fs.existsSync(centralDest)) {
entries.push({ kind: 'central', path: centralDest, outcome: 'skipped-present' });
- } else {
+ } else if (centralRootExists) {
try {
replaceDir(sourceDir, centralDest, fs);
- centralWritten = true;
entries.push({ kind: 'central', path: centralDest, outcome: 'written' });
logger({
event: 'user-skill-reclaim-central-written',
@@ -330,9 +342,9 @@ function installUserBundleToHostDirs(
}
}
- for (const host of HOSTS_WITH_USER_SKILL_DIR) {
+ for (const host of USER_SKILL_HOSTS) {
const hostRoot = join(home, host.hostDir);
- const hostDest = join(hostRoot, 'skills', bundleDirName);
+ const hostDest = join(home, host.skillsRoot, bundleDirName);
if (hostDest === centralDest) {
// Defensive: a per-host dest that resolves to the central store's own
// path would be a redundant double-write. No host root currently
@@ -405,7 +417,13 @@ function installUserBundleToHostDirs(
});
}
}
- return { entries, centralWritten };
+ return {
+ entries,
+ anyWritten: entries.some((entry) => entry.outcome === 'written'),
+ anyDestinationSucceeded: entries.some(
+ (entry) => entry.outcome === 'written' || entry.outcome === 'skipped-present',
+ ),
+ };
}
/**
@@ -633,7 +651,7 @@ async function runUserSweep(
const gatedBundles: Array<{ id: BundleId; sourceDir: string }> = [];
for (const bundle of resolvedBundles) {
const name = BUNDLE_SKILL_NAME[bundle.id];
- const onDisk = fs.existsSync(join(home, '.agents', 'skills', name));
+ const onDisk = userBundleExists(home, name, fs);
const decision = await deps.readBundleDecision(home, name).catch(() => null);
if (!resolveBundleEnabled(decision, { installedOnDisk: onDisk })) {
if (onDisk) {
@@ -680,7 +698,7 @@ async function runUserSweep(
// AND every enabled bundle is already on disk (a freshly-enabled bundle must
// install even at the current version).
const allEnabledOnDisk = gatedBundles.every((b) =>
- fs.existsSync(join(home, '.agents', 'skills', BUNDLE_SKILL_NAME[b.id])),
+ userBundleExists(home, BUNDLE_SKILL_NAME[b.id], fs),
);
if (recordedVersion !== null && recordedVersion === bundledVersion && allEnabledOnDisk) {
logger({
@@ -702,8 +720,17 @@ async function runUserSweep(
// the version unrecorded so the next boot retries. Declined bundles are
// excluded by choice, not failure, so they don't block the advance.
const allBundlesResolved = resolvedBundles.length === USER_GLOBAL_BUNDLE_IDS.length;
- // (2) Every gated bundle's central write landed.
- const bundleResults: Array<{ id: BundleId; centralWritten: boolean }> = [];
+ // (2) At least one authorized destination accepted EACH gated bundle —
+ // tracked per bundle, never over the pooled entry list. Pooled, a sibling's
+ // `skipped-present` satisfies the gate for a bundle whose only write threw,
+ // and that bundle then reports `skip-current` instead of `failed`.
+ const bundleResults: Array<{
+ id: BundleId;
+ anyWritten: boolean;
+ landed: boolean;
+ centralFailed: boolean;
+ hostFailed: boolean;
+ }> = [];
for (const { id, sourceDir } of gatedBundles) {
const result = installUserBundleToHostDirs(
home,
@@ -714,17 +741,21 @@ async function runUserSweep(
bundledVersion,
);
entries.push(...result.entries);
- bundleResults.push({ id, centralWritten: result.centralWritten });
+ bundleResults.push({
+ id,
+ anyWritten: result.anyWritten,
+ landed: result.anyDestinationSucceeded,
+ centralFailed: result.entries.some((e) => e.kind === 'central' && e.outcome === 'failed'),
+ hostFailed: result.entries.some((e) => e.kind === 'host' && e.outcome === 'failed'),
+ });
}
- // Seed-if-absent: a present built-in is left untouched (updates flow through
- // the skills.sh path, not this sweep). A clean reconcile — every enabled
- // built-in now present, whether freshly seeded or already there, with no
- // central-write failure — advances the recorded version so the version
- // fast-path can skip next launch. Only a genuine central-write failure holds
- // the version back for a retry; per-host failures don't roll back.
- const anyCentralFailed = entries.some((e) => e.kind === 'central' && e.outcome === 'failed');
- if (allBundlesResolved && !anyCentralFailed) {
+ // Seed-if-absent: advance only after every gated bundle reached a usable
+ // destination and no central write failed. Otherwise a no-host pass would
+ // record the version and prevent repair when an editor is installed later.
+ const anyCentralFailed = bundleResults.some((b) => b.centralFailed);
+ const allBundlesLanded = bundleResults.every((b) => b.landed);
+ if (allBundlesResolved && allBundlesLanded && !anyCentralFailed) {
let stateWriteError: string | null = null;
try {
await deps.writeRecordedVersion(home, bundledVersion);
@@ -744,14 +775,13 @@ async function runUserSweep(
}
// One outcome event per bundle, gated on the state-file write: `installed`
// for a fresh seed, `skip-current` for a built-in that was already present.
- for (const { id, centralWritten } of bundleResults) {
+ for (const { id, anyWritten } of bundleResults) {
recordEventSoft({
ts: nowIso(),
surface: 'cli-start',
target: 'cli-hosts',
bundle: id,
- outcome:
- stateWriteError !== null ? 'failed' : centralWritten ? 'installed' : 'skip-current',
+ outcome: stateWriteError !== null ? 'failed' : anyWritten ? 'installed' : 'skip-current',
version: bundledVersion,
...(stateWriteError === null ? {} : { reason: `state-write-failed:${stateWriteError}` }),
});
@@ -759,21 +789,32 @@ async function runUserSweep(
} else {
// Two independent causes land here and the reason has to name which: a
// bundle whose assets never resolved (nothing was even attempted for it —
- // partially-present assets, so retry next boot) or a central write that
- // threw. The write case then splits on whether any HOST write also threw.
- const anyHostFailed = entries.some((e) => e.kind === 'host' && e.outcome === 'failed');
- recordEventSoft({
- ts: nowIso(),
- surface: 'cli-start',
- target: 'cli-hosts',
- outcome: 'failed',
- version: bundledVersion,
- reason: !allBundlesResolved
- ? 'bundle-unresolved'
- : anyHostFailed
- ? 'all-writes-failed'
- : 'central-write-failed',
- });
+ // partially-present assets, so retry next boot) or a write that threw. The
+ // write case is reported per bundle, because a bundle that landed nowhere
+ // must not be masked by a sibling that did. A bundle that landed cleanly
+ // gets no event: the version was not recorded, so nothing may claim it was.
+ if (!allBundlesResolved) {
+ recordEventSoft({
+ ts: nowIso(),
+ surface: 'cli-start',
+ target: 'cli-hosts',
+ outcome: 'failed',
+ version: bundledVersion,
+ reason: 'bundle-unresolved',
+ });
+ }
+ for (const { id, centralFailed, hostFailed } of bundleResults) {
+ if (!centralFailed && !hostFailed) continue;
+ recordEventSoft({
+ ts: nowIso(),
+ surface: 'cli-start',
+ target: 'cli-hosts',
+ bundle: id,
+ outcome: 'failed',
+ version: bundledVersion,
+ reason: hostFailed ? 'all-writes-failed' : 'central-write-failed',
+ });
+ }
}
return { outcome: 'done', version: bundledVersion, entries };
@@ -1021,6 +1062,7 @@ async function confirmLegacyCleanup(
export const __testing = {
HOSTS_WITH_USER_SKILL_DIR,
+ USER_SKILL_HOSTS,
USER_SKILL_DIR_NAME,
PROJECT_SKILL_DIR_NAME,
CENTRAL_USER_SKILL_REL,
diff --git a/packages/cli/src/commands/seed.test.ts b/packages/cli/src/commands/seed.test.ts
index 17a2e22a4..65d287974 100644
--- a/packages/cli/src/commands/seed.test.ts
+++ b/packages/cli/src/commands/seed.test.ts
@@ -1,4 +1,13 @@
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
@@ -134,21 +143,69 @@ describe('runSeed — no-op', () => {
expect(second.message).toContain('already seeded');
});
- test('is NOT a no-op when folders exist but a pack skill is missing', async () => {
+ test('is NOT a no-op when a pack skill was deleted from a project that has an agent folder', async () => {
// A project whose pack skill was deleted has every folder yet no skill.
// Re-seeding must re-author it, not report "already seeded, nothing to do".
- // Pack skills land in-place (editor skill dirs) with the legacy `.ok/skills`
- // store still honored — remove every home so the skill is truly gone.
+ // The agent folder stays: it is what lets OK author a skill at all, so
+ // deleting it would make re-authoring impossible (next test covers that).
scaffoldOkDir(testDir);
+ mkdirSync(join(testDir, '.claude'), { recursive: true });
await runSeed({ cwd: testDir, yes: true });
+ // Pack skills land in-place (editor skill dirs) with the legacy `.ok/skills`
+ // store still honored — clear both so the skill is truly gone.
+ rmSync(join(testDir, '.claude', 'skills'), { recursive: true, force: true });
rmSync(join(testDir, OK_DIR, 'skills'), { recursive: true, force: true });
- for (const dir of ['.agents', '.claude', '.cursor', '.codex', '.opencode', '.pi']) {
- rmSync(join(testDir, dir), { recursive: true, force: true });
+
+ const preview = await runSeed({ cwd: testDir, dryRun: true });
+ expect(preview.status).not.toBe('no-op');
+ const pending = preview.plan?.packSkills?.filter((s) => s.pending) ?? [];
+ expect(pending.length).toBeGreaterThan(0);
+
+ // …and the promised work actually happens: the skill is re-authored.
+ const applied = await runSeed({ cwd: testDir, yes: true });
+ expect(applied.status).toBe('applied');
+ for (const skill of pending) {
+ expect(existsSync(join(testDir, '.claude', 'skills', skill.name, 'SKILL.md'))).toBe(true);
}
+ });
- const second = await runSeed({ cwd: testDir, dryRun: true });
- expect(second.status).not.toBe('no-op');
- expect(second.plan?.packSkills?.some((s) => s.pending)).toBe(true);
+ test('with no agent folder, pack skills are not pending and re-runs stay a no-op', async () => {
+ // OK never creates an agent home, so a harness-free project can never
+ // receive pack skills. Reporting them pending promised work apply always
+ // declines, which made every `ok seed` re-run claim it applied something.
+ scaffoldOkDir(testDir);
+ await runSeed({ cwd: testDir, yes: true });
+
+ const second = await runSeed({ cwd: testDir, yes: true });
+ expect(second.status).toBe('no-op');
+ expect(second.plan?.packSkills?.some((s) => s.pending)).toBe(false);
+ expect(second.plan?.packSkillHomeRefusal).toBe('no-agent-folder');
+ // Honest, not merely stable: it says the skills were not installed and why.
+ expect(second.message).toContain('skills were not installed');
+ expect(second.message).toContain('.claude/');
+ });
+
+ test('an agent folder symlinked outside the project gets the symlink-specific guidance', async () => {
+ // The second refusal class. Its guidance differs from the no-agent-folder
+ // one — "create the folder your agent uses" is wrong advice here, the
+ // folder exists and points out of the repo — so the run must reach the
+ // user with the symlink wording, not the generic one.
+ scaffoldOkDir(testDir);
+ const outside = mkdtempSync(join(tmpdir(), 'ok-seed-outside-'));
+ try {
+ symlinkSync(outside, join(testDir, '.claude'));
+ mkdirSync(join(outside, 'skills'), { recursive: true });
+
+ const result = await runSeed({ cwd: testDir, yes: true });
+
+ expect(result.plan?.packSkillHomeRefusal).toBe('home-escapes-project');
+ expect(result.message).toContain('symlink pointing outside the project');
+ expect(result.message).not.toContain('no agent folder for them');
+ // Refused, not quietly redirected: nothing was authored through the link.
+ expect(readdirSync(join(outside, 'skills'))).toEqual([]);
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
});
});
diff --git a/packages/cli/src/commands/seed.ts b/packages/cli/src/commands/seed.ts
index e7bdb8e80..f3190eec0 100644
--- a/packages/cli/src/commands/seed.ts
+++ b/packages/cli/src/commands/seed.ts
@@ -10,6 +10,12 @@
import { relative, resolve } from 'node:path';
import { createInterface } from 'node:readline/promises';
+import {
+ AGENTS_SKILLS_ROOT,
+ EDITOR_PROJECT_SKILL_ROOT,
+ PROJECT_SKILL_EDITOR_IDS,
+ skillRootActivationPath,
+} from '@inkeep/open-knowledge-core';
import {
applySeed,
DEFAULT_PACK_ID,
@@ -44,6 +50,30 @@ interface SeedCommandOptions {
confirmStream?: NodeJS.ReadableStream;
}
+/**
+ * Spell out why the pack's skills were not installed — and cannot be, until the
+ * user changes something. `planSeed` sets `packSkillHomeRefusal` only when the
+ * pack ships skills and no usable skill home exists, so this is never
+ * hypothetical: apply refuses every run. Without it "already seeded" reads as a
+ * complete setup while the pack's skills are silently absent.
+ */
+function skillHomeRefusalNote(plan: ScaffoldPlan, packName: string): string {
+ if (plan.packSkillHomeRefusal === undefined) return '';
+ if (plan.packSkillHomeRefusal === 'home-escapes-project') {
+ return `\n${warning('!')} The ${packName} skills were not installed: this project's skill folder is a symlink pointing outside the project, and Open Knowledge will not write through it. Replace it with a real directory inside the project, then run \`ok seed\` again.`;
+ }
+ // Derived from the editor registry, so a newly onboarded host lands in this
+ // list for free rather than making the message quietly wrong.
+ const homes = [
+ ...new Set(
+ [AGENTS_SKILLS_ROOT, ...PROJECT_SKILL_EDITOR_IDS.map((id) => EDITOR_PROJECT_SKILL_ROOT[id])]
+ .filter((root): root is string => root !== null)
+ .map(skillRootActivationPath),
+ ),
+ ].map((home) => `${home}/`);
+ return `\n${warning('!')} The ${packName} skills were not installed: this project has no agent folder for them. Open Knowledge only writes skills into a folder that already exists (${homes.join(', ')}) and never creates one for you. Create the folder your agent uses, then run \`ok seed\` again to install them.`;
+}
+
function isPackId(value: unknown): value is PackId {
return typeof value === 'string' && STARTER_PACK_IDS.includes(value as PackId);
}
@@ -102,6 +132,8 @@ export async function runSeed(opts: SeedCommandOptions = {}): Promise<SeedComman
// A pending pack skill is outstanding work even when every folder/template
// already exists (see ScaffoldPlan.packSkills) — `applySeed` would still author
// and install it, so this is not a no-op. SeedDialog folds the same two signals.
+ // Nothing is pending when the project has no usable skill home: apply declines
+ // there, so this stays a no-op run after run and the message says why.
if (plan.created.length === 0 && !plan.packSkills?.some((s) => s.pending)) {
const packName = STARTER_PACKS[packId].name;
// A conflicted skill is present-but-not-ours: "already seeded" would
@@ -113,9 +145,12 @@ export async function runSeed(opts: SeedCommandOptions = {}): Promise<SeedComman
`\n${warning('!')} Skill "${s.name}" is your own — the pack's version is not installed. Rename yours to install the pack's version.`,
)
.join('');
+ // "Nothing to do" is false when the refusal note just told the user what to
+ // do (create an agent folder, re-run) — drop it rather than contradict it.
+ const refusalNote = skillHomeRefusalNote(plan, packName);
return {
status: 'no-op',
- message: `${success(`Your ${packName} pack is already seeded.`)}${conflictNote}\n${dim('Nothing to do.')}`,
+ message: `${success(`Your ${packName} pack is already seeded.`)}${refusalNote}${conflictNote}${refusalNote === '' ? `\n${dim('Nothing to do.')}` : ''}`,
plan,
exitCode: 0,
};
@@ -191,7 +226,7 @@ export async function runSeed(opts: SeedCommandOptions = {}): Promise<SeedComman
return {
status: 'applied',
- message: `${success(`✓ Seeded ${packName}`)} ${dim(`(${applyResult.applied} entries, ${applyResult.durationMs}ms)`)}${skillLine}${conflictLines}`,
+ message: `${success(`✓ Seeded ${packName}`)} ${dim(`(${applyResult.applied} entries, ${applyResult.durationMs}ms)`)}${skillLine}${skillHomeRefusalNote(plan, packName)}${conflictLines}`,
plan,
exitCode: 0,
};
diff --git a/packages/cli/src/integrations/skill-teardown.test.ts b/packages/cli/src/integrations/skill-teardown.test.ts
index 64fcc2a26..16f34f788 100644
--- a/packages/cli/src/integrations/skill-teardown.test.ts
+++ b/packages/cli/src/integrations/skill-teardown.test.ts
@@ -1,6 +1,7 @@
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, sep } from 'node:path';
+import { USER_SKILL_HOSTS } from '@inkeep/open-knowledge-core';
import { BUNDLE_SKILL_NAME, USER_GLOBAL_BUNDLE_IDS } from '@inkeep/open-knowledge-server';
import { describe, expect, test } from 'vitest';
import { HOSTS_WITH_USER_SKILL_DIR } from '../commands/editors.ts';
@@ -17,7 +18,7 @@ describe('userGlobalSkillBundleTargets', () => {
test('targets the central store + every per-host dir for each user-global bundle', () => {
const targets = userGlobalSkillBundleTargets(HOME);
// One central + N host dirs per user-global bundle.
- const expectedCount = USER_GLOBAL_BUNDLE_IDS.length * (1 + HOSTS_WITH_USER_SKILL_DIR.length);
+ const expectedCount = USER_GLOBAL_BUNDLE_IDS.length * (1 + USER_SKILL_HOSTS.length);
expect(targets.length).toBe(expectedCount);
for (const bundleId of USER_GLOBAL_BUNDLE_IDS) {
@@ -29,15 +30,21 @@ describe('userGlobalSkillBundleTargets', () => {
scope: 'central',
});
// Each per-host dir.
- for (const host of HOSTS_WITH_USER_SKILL_DIR) {
+ for (const host of USER_SKILL_HOSTS) {
expect(targets).toContainEqual({
- path: join(HOME, host.hostDir, 'skills', name),
+ path: join(HOME, host.skillsRoot, name),
bundleId,
scope: 'host',
hostDir: host.hostDir,
});
}
}
+ expect(targets.map((target) => target.path)).toContain(
+ join(HOME, '.pi', 'agent', 'skills', 'open-knowledge-discovery'),
+ );
+ expect(targets.map((target) => target.path)).toContain(
+ join(HOME, '.copilot', 'skills', 'open-knowledge-discovery'),
+ );
});
test('includes both built-in bundles by name (discovery + write-skill)', () => {
diff --git a/packages/cli/src/integrations/skill-teardown.ts b/packages/cli/src/integrations/skill-teardown.ts
index dc3f70842..aec5c0f88 100644
--- a/packages/cli/src/integrations/skill-teardown.ts
+++ b/packages/cli/src/integrations/skill-teardown.ts
@@ -6,12 +6,11 @@
* OK force-installs its user-global bundles (`open-knowledge-discovery` +
* `open-knowledge-write-skill`) into:
* - the central store `~/.agents/skills/<name>/`, and
- * - each per-host dir `~/<hostDir>/skills/<name>/` (claude / cursor / codex /
- * opencode).
+ * - each concrete user-skill root, including nested Pi and Copilot layouts.
*
* This computes the identical set from the SAME single sources the installer
* loops over — `USER_GLOBAL_BUNDLE_IDS`, `BUNDLE_SKILL_NAME`, and
- * `HOSTS_WITH_USER_SKILL_DIR` — so the teardown can never remove more or less
+ * `USER_SKILL_HOSTS` — so the teardown can never remove more or less
* than what was installed (a new user-global bundle or host flows to both sides
* automatically). Only the specific `open-knowledge-*` bundle dirs are targeted,
* never the shared `~/.agents/skills/` root, so a user's other skills survive.
@@ -25,12 +24,12 @@
import { existsSync, lstatSync, readdirSync, rmdirSync, rmSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { USER_SKILL_HOSTS } from '@inkeep/open-knowledge-core';
import {
BUNDLE_SKILL_NAME,
type BundleId,
USER_GLOBAL_BUNDLE_IDS,
} from '@inkeep/open-knowledge-server';
-import { HOSTS_WITH_USER_SKILL_DIR } from '../commands/editors.ts';
/**
* The agent homes a pre-0.42 `ok init` created skill copies in, for tools OK
@@ -397,9 +396,9 @@ export function userGlobalSkillBundleTargets(homeInput: string): SkillBundleTarg
bundleId,
scope: 'central',
});
- for (const host of HOSTS_WITH_USER_SKILL_DIR) {
+ for (const host of USER_SKILL_HOSTS) {
targets.push({
- path: join(home, host.hostDir, 'skills', name),
+ path: join(home, host.skillsRoot, name),
bundleId,
scope: 'host',
hostDir: host.hostDir,
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index dfd95ef49..d7a845280 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,4 +1,3 @@
-
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 8bfdb40cd..005627195 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,4 +1,3 @@
-
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
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 01ef76a9f..8fb428b90 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
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/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 463e89595..9d9c244b0 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,4 +1,3 @@
-
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index 0939885bb..c43fdd7e7 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,4 +1,3 @@
-
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index c0dc65705..251560a35 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,7 +65,6 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
-
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index dcc5b0690..01ac80099 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 0be5203e4..754dc5cc2 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
-
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
-
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
-
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index dca644141..af20de1e2 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,4 +1,3 @@
-
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/constants/editors.ts b/packages/core/src/constants/editors.ts
index e3990e348..6297b35bd 100644
--- a/packages/core/src/constants/editors.ts
+++ b/packages/core/src/constants/editors.ts
@@ -84,8 +84,9 @@ export const EDITOR_LABELS = {
* The asymmetry with USER/global scope is deliberate: `~/.agents/skills` IS the
* right hub there — several hosts (Codex, OpenCode, Cursor) read it natively at
* user scope, so it is a real convergence point with no per-project equivalent.
- * The user-global writer (`installUserSkill`) writes it ALONGSIDE the per-host
- * dirs of detected hosts, and only when at least one host is detected.
+ * The user-global writer (`installUserSkill`) writes it only when the
+ * `~/.agents` root already exists. Otherwise it writes only to detected
+ * concrete host roots.
*
* The CLI's `EDITOR_TARGETS.projectSkillPath` is a second source for the same
* map and must move in lock-step.
@@ -149,6 +150,27 @@ export const EDITOR_USER_SKILL_ROOT = {
hermes: null,
} as const satisfies Record<EditorId, string | null>;
+/**
+ * Repo/home dirs that hold a skills root but are NOT owned by an agent.
+ * `.github` carries workflows, CODEOWNERS and issue templates in nearly every
+ * git repo, so its presence says nothing about whether the project adopted
+ * Copilot skills. Every other skills root sits under a dotdir a single agent
+ * owns. Copilot's USER root (`.copilot/skills`) is agent-owned and absent here.
+ */
+const NON_AGENT_SKILL_ROOT_DIRS: ReadonlySet<string> = new Set(['.github']);
+
+/**
+ * The base-relative path whose existence activates `skillsRoot` as a write
+ * target. Normally the host's dotdir — a project with `.claude` but no
+ * `.claude/skills` has still adopted Claude, so OK may create the skills dir.
+ * For a root under a shared non-agent dir the whole root must already exist:
+ * only `.github/skills` itself proves adoption, `.github` alone does not.
+ */
+export function skillRootActivationPath(skillsRoot: string): string {
+ const dotdir = skillsRoot.split('/')[0] ?? skillsRoot;
+ return NON_AGENT_SKILL_ROOT_DIRS.has(dotdir) ? skillsRoot : dotdir;
+}
+
/** Editor ids that have a project skill surface (valid install-projection targets). */
export const PROJECT_SKILL_EDITOR_IDS = ALL_EDITOR_IDS.filter(
(id) => EDITOR_PROJECT_SKILL_ROOT[id] !== null,
@@ -199,8 +221,8 @@ export const PROJECT_SKILL_PROJECTION_IGNORE_PATHS: readonly string[] = ALL_EDIT
* Pi and Copilot are carve-outs: Pi's user-global skills dir is
* `~/.pi/agent/skills` (the agent home is nested one level below the `.pi`
* dotdir), while Copilot's is `~/.copilot/skills`, not `~/.github/skills`.
- * Both natively read the central `~/.agents/skills` hub that the user-bundle
- * installer already writes, so including either here would create a dead path.
+ * Both are handled by `USER_SKILL_HOSTS` at user scope; including either in
+ * this project-shaped list would fabricate the wrong global path.
*/
export const HOSTS_WITH_USER_SKILL_DIR: ReadonlyArray<{
readonly hostDir: string;
@@ -213,6 +235,23 @@ export const HOSTS_WITH_USER_SKILL_DIR: ReadonlyArray<{
}),
);
+/**
+ * Every editor with a concrete user-global skill location. Unlike
+ * `HOSTS_WITH_USER_SKILL_DIR`, this preserves the full user-root shape, so Pi
+ * (`.pi/agent/skills`) and Copilot (`.copilot/skills`) can be addressed without
+ * relying on an implicitly-created `.agents` hub.
+ */
+export const USER_SKILL_HOSTS: ReadonlyArray<{
+ readonly hostDir: string;
+ readonly skillsRoot: string;
+ readonly editorId: EditorId;
+}> = ALL_EDITOR_IDS.flatMap((editorId) => {
+ const skillsRoot = EDITOR_USER_SKILL_ROOT[editorId];
+ if (skillsRoot === null) return [];
+ const hostDir = skillsRoot.split('/')[0];
+ return hostDir === undefined ? [] : [{ hostDir, skillsRoot, editorId }];
+});
+
/**
* OpenKnowledge integration-doc slug per editor — the setup guide at
* `https://openknowledge.ai/docs/integrations/<slug>`. Consumed by the
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index e267ecc42..d7b7686e5 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -558,6 +558,15 @@ export interface OkIntegrationsStatus {
readonly installed: boolean;
readonly paths: readonly string[];
}[];
+ /**
+ * Every editor whose host root already exists on this machine — a SUPERSET
+ * of the ids in `editors[]`, which is filtered to targets with a user-global
+ * MCP surface. The Create-new-project dialog seeds its editor checkboxes
+ * from this so a user who never opens "Advanced settings" still gets MCP
+ * config + the project skill for the tools they actually have, and none for
+ * the ones they don't.
+ */
+ readonly detectedEditorIds: readonly OkMcpWiringEditorId[];
}
/** One toggle for `integrations.setComponent`. */
@@ -1460,8 +1469,8 @@ export interface OkDesktopBridge {
/**
* Atomically scaffold a new project under `parent/name` with the
* user-chosen `editors` set. `editors` is the renderer's exact selection
- * (default-all unless the user unchecked entries); main never widens or
- * narrows it.
+ * (seeded from `integrations.status().detectedEditorIds`, minus/plus
+ * anything the user toggled); main never widens or narrows it.
*/
createNew(args: {
parent: string;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5c3e2d88f..2d8c092ae 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -345,6 +345,8 @@ export {
PROJECT_SKILL_EDITOR_IDS,
PROJECT_SKILL_PROJECTION_IGNORE_PATHS,
RESERVED_PROJECT_SKILL_NAME,
+ skillRootActivationPath,
+ USER_SKILL_HOSTS,
} from './constants/editors.ts';
export {
detectEmbeddedHostFromBrowser,
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index a363dfd54..83d47404a 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,4 +1,3 @@
-
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 4499dbc92..9807a7e82 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,4 +1,3 @@
-
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 34704165b..7415c474a 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
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/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index b6299a948..ece5c02a1 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,4 +1,3 @@
-
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index acd398aa6..54774764a 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index ba9b56384..43ecdc709 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 4513da9bb..6d3f3643e 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,4 +1,3 @@
-
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 6931623c7..00f5771ee 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
-
interface GfmExample {
section: string;
markdown: string;
@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
-
interface MdxCrashEntry {
id: string;
input: string;
@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
-
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
-
export interface NgPinnedCase {
id: string;
name: string;
@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
-
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index daa3ef82b..8b1eb8519 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
-
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
-
const WORDS = [
'lorem',
'ipsum',
@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
-
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
-
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 32c055c5b..420dc0fe5 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,7 +7,6 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
-
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 283913255..2653473da 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,4 +1,3 @@
-
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index 5d1000cc4..da0a81d23 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 9681c0056..787315157 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,4 +1,3 @@
-
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified()
- .use(rehypeParse, { fragment: true });
+ const processor = unified().use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 994eb6917..706fa9afb 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index ec1ac1b7e..779e27500 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -207,7 +206,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -256,7 +254,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -279,7 +276,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
-
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index b79e9aef7..fa0be9e86 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,4 +1,3 @@
-
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 94b34dee1..312c9c74b 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,4 +1,3 @@
-
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 1e3ad29c6..c400441b2 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -39,7 +39,6 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
-
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index a51f2ffb0..d48eea5e4 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
-
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index 9c9542661..ef478e268 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,4 +1,3 @@
-
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index b96d19182..0d4c9a0df 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,4 +1,3 @@
-
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 1ca263610..af38c2ae2 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,4 +1,3 @@
-
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index be5871ed9..5e832aa19 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,4 +1,3 @@
-
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -14,7 +13,6 @@ import {
type MarkdownlintSlice,
} from './types.ts';
-
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 3dae5c031..01ce4a5af 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,4 +1,3 @@
-
import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;
@@ -99,7 +98,6 @@ export interface FrontmatterSlice {
schemas: ResolvedFrontmatterSchemaEntry[];
}
-
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 437cc539a..98238656e 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,4 +1,3 @@
-
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index bd79424c7..a5b511f25 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index 00fbc0035..ed89371d0 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index df788a80d..8ce2b2492 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
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/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 17ed2b829..1a897fca8 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 4aa0490c4..d988f4b8b 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,7 +168,6 @@ export function parseRecursive(
}
}
-
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
-
interface Region {
start: number;
end: number;
@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
-
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
-
interface SourceBlock {
src: string;
start: number;
@@ -456,7 +452,6 @@ function tryPerBlockFallback(
};
}
-
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index 43d420187..e6ab4fd57 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,4 +1,3 @@
-
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 55736041c..0e3224206 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index ccf06e94d..91cdf658f 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,4 +1,3 @@
-
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index e5b4c9eba..0f399d34c 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- }
- else if (first === '[') {
+ } else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index ca225ce9b..db10fa54b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 3a2524a9a..34068d103 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 2279a0189..93151d43b 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index a0f467c42..188f02d83 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4e8542a21..4ba2c3418 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index a3c96b24a..1a74b1272 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index e95cf43d6..de35e7b79 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index ffdb4d5b5..b4be1b2ea 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index e2a96d1a7..3c8d88b7c 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index 0389575ac..cf2c9da8e 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,4 +1,3 @@
-
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
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/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 96304e7a5..0dd54070e 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,4 +1,3 @@
-
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 93798cf83..7cac5b042 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,4 +1,3 @@
-
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index 8c08b7a04..b012a5aff 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 959cc0bd2..3e79f8cb6 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 6e6d73400..0f1b0f27d 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 932d7d2a8..1a082bda7 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,4 +1,3 @@
-
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index ac9f5239b..d578476a7 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,4 +1,3 @@
-
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index afd9936fe..6dad26200 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {
}
}
-
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {
};
}
-
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
-
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/core/src/skill-targets/editor-single-source.test.ts b/packages/core/src/skill-targets/editor-single-source.test.ts
index 312cbd0c7..eceb8b82f 100644
--- a/packages/core/src/skill-targets/editor-single-source.test.ts
+++ b/packages/core/src/skill-targets/editor-single-source.test.ts
@@ -18,8 +18,10 @@ import { describe, expect, test } from 'vitest';
import {
ALL_EDITOR_IDS,
EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
HOSTS_WITH_USER_SKILL_DIR,
PROJECT_SKILL_EDITOR_IDS,
+ USER_SKILL_HOSTS,
} from '../constants/editors.ts';
import { SkillTargetEditorSchema } from './schema.ts';
@@ -42,8 +44,8 @@ describe('project-skill editor-id single source', () => {
// Single source for the host-dir sweep both the CLI and desktop run.
// editorId set === PROJECT_SKILL_EDITOR_IDS minus the documented Pi and
// Copilot carve-outs. Their user-global skills dirs do not follow the
- // `~/<hostDir>/skills` layout this sweep assumes; both read the central
- // `~/.agents/skills` hub natively. hostDir === the root's top-level dotdir.
+ // `~/<hostDir>/skills` layout this project-shaped sweep assumes. Their
+ // concrete global roots are covered separately by USER_SKILL_HOSTS.
expect(asStrings(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.editorId))).toEqual(
asStrings(PROJECT_SKILL_EDITOR_IDS.filter((id) => id !== 'pi' && id !== 'copilot')),
);
@@ -57,7 +59,7 @@ describe('project-skill editor-id single source', () => {
// Pi scans project `.pi/skills` natively (trust-gated), so it belongs in
// the install-projection enum; its user-global layout (`~/.pi/agent/skills`
// + the central `~/.agents/skills` hub) has no `~/.pi/skills`, so the
- // user-bundle sweep must not fabricate one.
+ // project-shaped sweep must not fabricate one.
expect(SkillTargetEditorSchema.options).toContain('pi');
expect(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.editorId)).not.toContain('pi');
expect(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.hostDir)).not.toContain('.pi');
@@ -65,12 +67,27 @@ describe('project-skill editor-id single source', () => {
test('Copilot IS a project-skill install target but NOT a user-global host-dir sweep member', () => {
// Copilot scans `.github/skills` per project, but keeps global skills at
- // `~/.copilot/skills`; it also reads the central `~/.agents/skills` hub.
+ // `~/.copilot/skills`, which USER_SKILL_HOSTS preserves directly.
expect(SkillTargetEditorSchema.options).toContain('copilot');
expect(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.editorId)).not.toContain('copilot');
expect(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.hostDir)).not.toContain('.github');
});
+ test('USER_SKILL_HOSTS preserves every concrete user-global root', () => {
+ const expected = ALL_EDITOR_IDS.filter((id) => EDITOR_USER_SKILL_ROOT[id] !== null);
+ expect(asStrings(USER_SKILL_HOSTS.map((host) => host.editorId))).toEqual(asStrings(expected));
+ for (const { editorId, hostDir, skillsRoot } of USER_SKILL_HOSTS) {
+ expect(skillsRoot).toBe(EDITOR_USER_SKILL_ROOT[editorId]);
+ expect(hostDir).toBe(skillsRoot.split('/')[0]);
+ }
+ expect(USER_SKILL_HOSTS.find((host) => host.editorId === 'pi')?.skillsRoot).toBe(
+ '.pi/agent/skills',
+ );
+ expect(USER_SKILL_HOSTS.find((host) => host.editorId === 'copilot')?.skillsRoot).toBe(
+ '.copilot/skills',
+ );
+ });
+
test('Claude Desktop is NOT a project-skill install target (user-global only, null root)', () => {
// Regression: the install menu / picker must not offer claude-desktop —
// it has no project skill surface (reads user-global skills only).
diff --git a/packages/desktop/src/main/create-new-project.test.ts b/packages/desktop/src/main/create-new-project.test.ts
index 8ff5d5418..f8a5a5a7a 100644
--- a/packages/desktop/src/main/create-new-project.test.ts
+++ b/packages/desktop/src/main/create-new-project.test.ts
@@ -177,14 +177,27 @@ const makeDiscoverDeps = (
}),
});
+/**
+ * Pin the editor set the dialog "proposed" so the telemetry variant does not
+ * depend on which AI tools happen to be installed on the machine running the
+ * suite. Production reads the same set from `detectInstalledEditors`.
+ */
+const withDetected = (
+ detected: readonly string[],
+ base: RunCreateNewDeps = {},
+): RunCreateNewDeps => ({ ...base, detectInstalledEditors: () => detected });
+
describe('runCreateNew — happy paths', () => {
test('scaffolds .ok/config.yml and reports default variant', async () => {
const parent = tmpRoot;
- const result = await runCreateNew({
- parent,
- name: 'My Notes',
- editors: [...ALL_EDITOR_IDS],
- });
+ const result = await runCreateNew(
+ {
+ parent,
+ name: 'My Notes',
+ editors: [...ALL_EDITOR_IDS],
+ },
+ withDetected(ALL_EDITOR_IDS),
+ );
expect(result.target).toBe(join(parent, 'My Notes'));
// projectDir == realpath(target). macOS aliases /tmp → /private/tmp so
// the realpath equality holds even though the raw strings differ.
@@ -228,12 +241,31 @@ describe('runCreateNew — happy paths', () => {
).not.toThrow();
});
- test('records customized variant when a subset of editors is supplied', async () => {
- const result = await runCreateNew({
- parent: tmpRoot,
- name: 'Customized',
- editors: ['codex'],
- });
+ test('reports default variant when the submitted set is the detected set, even though it is not every editor', async () => {
+ // The dialog seeds its checkboxes from detection, so "default" means
+ // "unchanged from what we proposed" — NOT "every editor". Pinning this
+ // against a two-editor machine is the whole point: under the old
+ // all-editors baseline every real create would have read as customized.
+ const result = await runCreateNew(
+ { parent: tmpRoot, name: 'Detected Only', editors: ['codex', 'cursor'] },
+ withDetected(['codex', 'cursor']),
+ );
+ expect(result.variant).toBe('create-new-default');
+ });
+
+ test('records customized variant when the user narrows the detected set', async () => {
+ const result = await runCreateNew(
+ { parent: tmpRoot, name: 'Narrowed', editors: ['codex'] },
+ withDetected(['codex', 'cursor']),
+ );
+ expect(result.variant).toBe('create-new-customized');
+ });
+
+ test('records customized variant when the user adds an undetected editor', async () => {
+ const result = await runCreateNew(
+ { parent: tmpRoot, name: 'Widened', editors: ['codex', 'claude'] },
+ withDetected(['codex']),
+ );
expect(result.variant).toBe('create-new-customized');
});
@@ -296,7 +328,7 @@ describe('runCreateNew — git-root promotion', () => {
writeFileSync(resolve(repo, '.git/HEAD'), 'ref: refs/heads/main\n');
const target = resolve(notes, 'MyProj');
- const deps = makeDiscoverDeps(fakeHome, { [target]: repo });
+ const deps = withDetected(ALL_EDITOR_IDS, makeDiscoverDeps(fakeHome, { [target]: repo }));
const result = await runCreateNew(
{ parent: notes, name: 'MyProj', editors: [...ALL_EDITOR_IDS] },
diff --git a/packages/desktop/src/main/create-new-project.ts b/packages/desktop/src/main/create-new-project.ts
index f4d8ffc89..74e90f1d8 100644
--- a/packages/desktop/src/main/create-new-project.ts
+++ b/packages/desktop/src/main/create-new-project.ts
@@ -16,6 +16,7 @@ import { existsSync, readdirSync, statSync } from 'node:fs';
import { resolve } from 'node:path';
import {
addOkPathsToGitExclude,
+ detectInstalledEditors,
getOkArtifactPaths,
type ProjectAiIntegrationsResult,
writeProjectAiIntegrations,
@@ -132,9 +133,9 @@ interface CreateNewProjectSuccess {
/** Per-(editor × integration) outcomes from `writeProjectAiIntegrations`
* (caller forwards to the `logAiIntegrationOutcomes` log helper). */
readonly aiIntegrations: ProjectAiIntegrationsResult;
- /** Telemetry flow-kind variant: `'create-new-default'`
- * when every available editor was selected, `'create-new-customized'`
- * otherwise. */
+ /** Telemetry flow-kind variant: `'create-new-default'` when the submitted
+ * editor set is exactly the one the dialog proposed (the detected set),
+ * `'create-new-customized'` when the user edited it. */
readonly variant: 'create-new-default' | 'create-new-customized';
/**
* Outcome of the post-scaffold sharing
@@ -202,6 +203,13 @@ export interface RunCreateNewDeps {
pickedPath: string,
opts: DiscoverProjectOptions,
) => Promise<DiscoverProjectResult>;
+ /**
+ * The editor set the dialog proposed (what `detectInstalledEditors` reports
+ * for this machine). Read only to classify the telemetry variant as
+ * "unchanged from what we proposed" vs "user edited the selection", so tests
+ * can pin the classification without depending on the host's real `$HOME`.
+ */
+ readonly detectInstalledEditors?: () => readonly string[];
}
/**
@@ -506,8 +514,25 @@ export async function runCreateNew(
}
}
+ // Telemetry variant answers "did the user edit the selection we proposed?".
+ // The dialog seeds its checkboxes from the DETECTED set (it reads
+ // `bridge.integrations.status().detectedEditorIds` on open), so the baseline is
+ // that set, not `ALL_EDITOR_IDS` — against which almost every real create
+ // would read as customized.
+ const detectEditors = deps.detectInstalledEditors ?? (() => detectInstalledEditors(''));
+ let proposed: Set<string> | null = null;
+ try {
+ proposed = new Set(detectEditors());
+ } catch (err) {
+ // Telemetry must never fail a create. An unknown baseline cannot prove
+ // "unchanged from what we proposed", so it classifies as customized.
+ console.warn('[create-new-project] editor detection failed; variant is customized:', err);
+ }
+ const baseline = proposed;
const variant: CreateNewProjectSuccess['variant'] =
- editors.length === ALL_EDITOR_IDS.length ? 'create-new-default' : 'create-new-customized';
+ baseline !== null && editors.length === baseline.size && editors.every((id) => baseline.has(id))
+ ? 'create-new-default'
+ : 'create-new-customized';
return {
target,
diff --git a/packages/desktop/src/main/integrations-settings.ts b/packages/desktop/src/main/integrations-settings.ts
index 6c32d8161..b62dcaecf 100644
--- a/packages/desktop/src/main/integrations-settings.ts
+++ b/packages/desktop/src/main/integrations-settings.ts
@@ -154,13 +154,24 @@ export function registerIntegrationsSettings(
const { home, available, ipcMain, cli, path, skills, fs, now, logger = DEFAULT_LOGGER } = opts;
const nowDate = (): Date => (now ? now() : new Date());
- function computeEditorStatuses(): IntegrationsEditorStatus[] {
- let detected: Set<McpWiringEditorId>;
+ /**
+ * Every editor with a host root on this machine. Home-scoped (cwd `''`)
+ * because a project-relative probe is meaningless for a user-global surface
+ * — and for the Create-new-project dialog, which reads this off the status
+ * snapshot, the project does not exist yet. NOT narrowed by
+ * `cli.allEditorIds`: that list is filtered to user-global targets, while
+ * this set must stay honest about project-scope-only ones (Pi) too.
+ */
+ function computeDetectedEditors(): Set<McpWiringEditorId> {
try {
- detected = new Set(cli.detectInstalledEditors('', home));
+ return new Set(cli.detectInstalledEditors('', home));
} catch {
- detected = new Set();
+ return new Set();
}
+ }
+
+ function computeEditorStatuses(): IntegrationsEditorStatus[] {
+ const detected = computeDetectedEditors();
return cli.allEditorIds.map((id) => {
let state: IntegrationsEditorState;
try {
@@ -204,7 +215,13 @@ export function registerIntegrationsSettings(
});
skillStatuses = [];
}
- return { available, editors: computeEditorStatuses(), path: pathStatus, skills: skillStatuses };
+ return {
+ available,
+ editors: computeEditorStatuses(),
+ path: pathStatus,
+ skills: skillStatuses,
+ detectedEditorIds: [...computeDetectedEditors()],
+ };
}
/**
diff --git a/packages/desktop/src/main/skill-reclaim.test.ts b/packages/desktop/src/main/skill-reclaim.test.ts
index 97f34f546..5764a47ae 100644
--- a/packages/desktop/src/main/skill-reclaim.test.ts
+++ b/packages/desktop/src/main/skill-reclaim.test.ts
@@ -2,8 +2,10 @@ import {
existsSync,
mkdirSync,
mkdtempSync,
+ readdirSync,
readFileSync,
rmSync,
+ statSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
@@ -190,6 +192,7 @@ describe('reclaimUserSkillsOnLaunch', () => {
test('linux deb install reaches done through the install-shape gate', async () => {
const home = makeHome();
+ mkdirSync(join(home, '.agents'), { recursive: true });
const bundle = setupBundle();
const deps = makeDeps({ bundle, version: '1.0.0' });
const r = await reclaimUserSkillsOnLaunch({
@@ -205,35 +208,66 @@ describe('reclaimUserSkillsOnLaunch', () => {
).toBe(true);
});
- test('central store always force-written even when nothing existed', async () => {
+ test('launch repair does not create an absent .agents host', async () => {
const home = makeHome();
const bundle = setupBundle();
const deps = makeDeps({ bundle, version: '0.5.0-beta.41' });
- const r = await reclaimUserSkillsOnLaunch({
+ await reclaimUserSkillsOnLaunch({
home,
isPackaged: true,
platform: 'darwin',
executablePath: EXE,
deps,
});
- expect(r.status).toBe('done');
const central = join(home, '.agents', 'skills', 'open-knowledge-discovery', 'SKILL.md');
- expect(existsSync(central)).toBe(true);
- expect(readFileSync(central, 'utf8')).toContain('v-new');
- expect(deps.stateWrites).toEqual([{ home, version: '0.5.0-beta.41' }]);
- expect(deps.events).toEqual([
- {
- ts: deps.events[0]?.ts ?? '',
- outcome: 'installed',
- bundle: 'discovery',
- version: '0.5.0-beta.41',
- },
+ expect(existsSync(central)).toBe(false);
+ expect(existsSync(join(home, '.agents'))).toBe(false);
+ });
+
+ test('launch repair uses an existing Pi root without creating .agents', async () => {
+ const home = makeHome();
+ mkdirSync(join(home, '.pi'), { recursive: true });
+ const bundle = setupBundle();
+ const deps = makeDeps({ bundle, version: '0.5.0-beta.41' });
+ await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ });
+
+ expect(
+ existsSync(join(home, '.pi', 'agent', 'skills', 'open-knowledge-discovery', 'SKILL.md')),
+ ).toBe(true);
+ expect(existsSync(join(home, '.agents'))).toBe(false);
+ });
+
+ test('grandfathers a bundle installed only in a concrete Pi root', async () => {
+ const home = makeHome();
+ const skillDir = join(home, '.pi', 'agent', 'skills', 'open-knowledge-discovery');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(join(skillDir, 'SKILL.md'), '# existing');
+ const bundle = setupBundle();
+ const deps = makeDeps({ bundle, version: '0.5.0-beta.41', bundleDecision: null });
+ await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ });
+
+ expect(deps.decisionWrites).toEqual([
+ { bundleName: 'open-knowledge-discovery', enabled: true },
]);
+ expect(existsSync(join(home, '.agents'))).toBe(false);
});
test('installs every user-global bundle (discovery + write-skill) into central + per-host', async () => {
const home = makeHome();
const bundle = setupBundle();
+ mkdirSync(join(home, '.agents'), { recursive: true });
// A `.claude` host so a per-host (non-central) write also happens.
mkdirSync(join(home, '.claude', 'skills'), { recursive: true });
const deps = {
@@ -320,6 +354,7 @@ describe('reclaimUserSkillsOnLaunch', () => {
// store and codex's per-host copy are distinct paths — both get written,
// no collapse.
const home = makeHome();
+ mkdirSync(join(home, '.agents'), { recursive: true });
mkdirSync(join(home, '.codex'), { recursive: true });
const bundle = setupBundle();
const deps = makeDeps({ bundle, version: '1.2.3' });
@@ -407,6 +442,7 @@ describe('reclaimUserSkillsOnLaunch', () => {
test('every write failing → JSONL records outcome:failed reason:all-targets-failed', async () => {
const home = makeHome();
+ mkdirSync(join(home, '.agents'), { recursive: true });
const deps = makeDeps({ bundle: setupBundle(), version: '3.2.1' });
// Inject an fs whose every write throws — central + per-host replaceDir
// all fail, so no write succeeds and the state file is never advanced.
@@ -417,7 +453,7 @@ describe('reclaimUserSkillsOnLaunch', () => {
executablePath: EXE,
deps,
fs: {
- existsSync: () => false,
+ existsSync: (path) => existsSync(path),
isDirectory: () => false,
readdirSync: () => [],
readFileSync: () => Buffer.from(''),
@@ -437,6 +473,65 @@ describe('reclaimUserSkillsOnLaunch', () => {
expect(failed?.version).toBe('3.2.1');
});
+ test('a bundle that lands nowhere reports failed even when a sibling bundle succeeds', async () => {
+ const home = makeHome();
+ // `.agents` absent (no central destination) and exactly one host root, so
+ // each bundle has exactly one candidate destination: `~/.claude/skills/…`.
+ mkdirSync(join(home, '.claude'), { recursive: true });
+ const bundle = setupBundle();
+ const deps = {
+ ...makeDeps({ bundle, version: '4.5.6' }),
+ userGlobalBundles: [
+ { id: 'discovery', name: 'open-knowledge-discovery' },
+ { id: 'write-skill', name: 'open-knowledge-write-skill' },
+ ],
+ };
+ const failingBundleDir = 'open-knowledge-write-skill';
+ const r = await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ fs: {
+ existsSync: (path) => existsSync(path),
+ isDirectory: (path) => {
+ try {
+ return statSync(path).isDirectory();
+ } catch {
+ return false;
+ }
+ },
+ readdirSync: (path) => readdirSync(path),
+ readFileSync: (path) => readFileSync(path),
+ // Only the write-skill bundle's writes throw; discovery lands normally.
+ writeFileSync: (path, content) => {
+ if (path.includes(failingBundleDir)) throw new Error('synthetic: EACCES');
+ writeFileSync(path, content);
+ },
+ mkdirSync: (path, options) => {
+ mkdirSync(path, options);
+ },
+ rmSync: (path, options) => {
+ rmSync(path, options);
+ },
+ },
+ });
+
+ expect(r.status).toBe('done');
+ expect(
+ existsSync(join(home, '.claude', 'skills', 'open-knowledge-discovery', 'SKILL.md')),
+ ).toBe(true);
+ // The sibling landed, but this bundle reached no destination at all.
+ const writeSkillEvents = deps.events.filter((e) => e.bundle === 'write-skill');
+ expect(writeSkillEvents).toHaveLength(1);
+ expect(writeSkillEvents[0]?.outcome).toBe('failed');
+ expect(writeSkillEvents[0]?.reason).toBe('all-targets-failed');
+ expect(deps.events.some((e) => e.outcome === 'installed')).toBe(false);
+ // Version stays unrecorded so the next launch retries the failed bundle.
+ expect(deps.stateWrites).toEqual([]);
+ });
+
test('bundle-missing surfaces as skipped with failed event', async () => {
const home = makeHome();
const deps = makeDeps({
@@ -477,6 +572,7 @@ describe('reclaimUserSkillsOnLaunch', () => {
// this whole module is fixing. Gate the JSONL outcome on the state
// write so the diagnostic trail stays coherent.
const home = makeHome();
+ mkdirSync(join(home, '.agents'), { recursive: true });
const deps = makeDeps({
bundle: setupBundle(),
version: '1.2.3',
diff --git a/packages/desktop/src/main/skill-reclaim.ts b/packages/desktop/src/main/skill-reclaim.ts
index cd4eec5fb..997be55a5 100644
--- a/packages/desktop/src/main/skill-reclaim.ts
+++ b/packages/desktop/src/main/skill-reclaim.ts
@@ -57,7 +57,7 @@ import {
EDITOR_TARGETS,
HOSTS_WITH_USER_SKILL_DIR,
} from '@inkeep/open-knowledge';
-import { resolveBundleEnabled } from '@inkeep/open-knowledge-core';
+import { resolveBundleEnabled, USER_SKILL_HOSTS } from '@inkeep/open-knowledge-core';
import { classifyInstallShape } from './install-shape.ts';
interface SkillReclaimLogger {
@@ -302,9 +302,15 @@ interface ReclaimUserSkillsOpts {
/**
* Force-write ONE user-global bundle into the central store + every detected
* per-host directory, under its own `bundleDirName`. Returns the per-write
- * entries (the version-advance gate keys off `anyWriteSucceeded` across all
- * bundles). Looped over `deps.userGlobalBundles` so discovery + write-skill
- * both land.
+ * entries plus this bundle's own `anyWritten` / `anyDestinationSucceeded`
+ * flags. Looped over `deps.userGlobalBundles` so discovery + write-skill both
+ * land.
+ *
+ * Both flags are PER BUNDLE by construction: the version-advance gate and the
+ * outcome event must not read them off a pooled entry list, or one bundle's
+ * success answers for a sibling that landed nowhere. Sibling of the CLI's
+ * `installUserBundleToHostDirs` in `packages/cli/src/commands/repair-skills.ts`
+ * — keep the shape aligned.
*/
function installUserBundleToHostDirs(
home: string,
@@ -313,7 +319,7 @@ function installUserBundleToHostDirs(
fs: SkillFsOps,
logger: SkillReclaimLogger,
version: string,
-): UserSkillReclaimEntry[] {
+): { entries: UserSkillReclaimEntry[]; anyWritten: boolean; anyDestinationSucceeded: boolean } {
const entries: UserSkillReclaimEntry[] = [];
const centralDest = join(home, '.agents', 'skills', bundleDirName);
// SEED-IF-ABSENT: the reclaim guarantees the
@@ -321,9 +327,10 @@ function installUserBundleToHostDirs(
// that copy may be a user-applied skills.sh update, and force-refreshing it
// would clobber the update + churn a version string every launch. Updates now
// flow through the manual "update available" path, not this launch hook.
- if (fs.existsSync(centralDest)) {
+ const centralRootExists = fs.existsSync(join(home, '.agents'));
+ if (centralRootExists && fs.existsSync(centralDest)) {
entries.push({ kind: 'central', path: centralDest, status: 'skipped-present' });
- } else {
+ } else if (centralRootExists) {
try {
replaceDir(sourceDir, centralDest, fs);
entries.push({ kind: 'central', path: centralDest, status: 'written' });
@@ -340,9 +347,9 @@ function installUserBundleToHostDirs(
}
}
- for (const host of HOSTS_WITH_USER_SKILL_DIR) {
+ for (const host of USER_SKILL_HOSTS) {
const hostRoot = join(home, host.hostDir);
- const hostDest = join(hostRoot, 'skills', bundleDirName);
+ const hostDest = join(home, host.skillsRoot, bundleDirName);
if (hostDest === centralDest) {
// Defensive: skip a per-host write that resolves to the central store's
// own path (would be a redundant double-write of the same bytes). No
@@ -406,7 +413,20 @@ function installUserBundleToHostDirs(
});
}
}
- return entries;
+ return {
+ entries,
+ anyWritten: entries.some((entry) => entry.status === 'written'),
+ anyDestinationSucceeded: entries.some(
+ (entry) => entry.status === 'written' || entry.status === 'skipped-present',
+ ),
+ };
+}
+
+function userBundleExists(home: string, bundleName: string, fs: SkillFsOps): boolean {
+ return (
+ fs.existsSync(join(home, '.agents', 'skills', bundleName)) ||
+ USER_SKILL_HOSTS.some((host) => fs.existsSync(join(home, host.skillsRoot, bundleName)))
+ );
}
/**
@@ -510,7 +530,7 @@ export async function reclaimUserSkillsOnLaunch(
// the identical gate.
const gatedBundles: typeof resolvedBundles = [];
for (const bundle of resolvedBundles) {
- const onDisk = fs.existsSync(join(home, '.agents', 'skills', bundle.name));
+ const onDisk = userBundleExists(home, bundle.name, fs);
const decision = await deps.readBundleDecision(home, bundle.name).catch(() => null);
if (!resolveBundleEnabled(decision, { installedOnDisk: onDisk })) {
if (onDisk) {
@@ -557,8 +577,12 @@ export async function reclaimUserSkillsOnLaunch(
// not an install and reporting it would turn an install counter into a launch
// counter. Collected per bundle because the entry rows do not carry a name.
const installedBundleNames: string[] = [];
+ // Per-bundle outcome flags. Read off the pooled `entries` list instead, one
+ // bundle's success answers for a sibling whose only write threw, and that
+ // sibling then reports `installed`. Mirrors the CLI sweep's `bundleResults`.
+ const bundleResults: Array<{ id: string; landed: boolean; failed: boolean }> = [];
for (const bundle of gatedBundles) {
- const bundleEntries = installUserBundleToHostDirs(
+ const result = installUserBundleToHostDirs(
home,
bundle.name,
bundle.sourceDir,
@@ -566,16 +590,24 @@ export async function reclaimUserSkillsOnLaunch(
logger,
version,
);
- if (bundleEntries.some((e) => e.status === 'written')) installedBundleNames.push(bundle.name);
- entries.push(...bundleEntries);
+ if (result.anyWritten) installedBundleNames.push(bundle.name);
+ entries.push(...result.entries);
+ bundleResults.push({
+ id: bundle.id,
+ landed: result.anyDestinationSucceeded,
+ failed: result.entries.some((e) => e.status === 'failed'),
+ });
}
// Machine-scoped, matching the CLI's user-global install: these bundles live
// once per machine, so a second project must not re-count them.
if (installedBundleNames.length > 0) deps.reportInstalled?.(installedBundleNames);
- const anyWriteSucceeded = entries.some((e) => e.status === 'written');
- const anyFailed = entries.some((e) => e.status === 'failed');
- if (anyWriteSucceeded) {
+ const anyWriteSucceeded = installedBundleNames.length > 0;
+ // Every gated bundle has to have reached a destination of its own before the
+ // shared state file may advance — otherwise the failing bundle rides its
+ // sibling's success into an `installed` event.
+ const allBundlesLanded = bundleResults.every((b) => b.landed);
+ if (anyWriteSucceeded && allBundlesLanded) {
let stateWriteError: string | null = null;
try {
await deps.writeTargetVersion(home, 'cli-hosts', version, 'desktop-direct');
@@ -605,20 +637,28 @@ export async function reclaimUserSkillsOnLaunch(
})
.catch(() => {});
}
- } else if (anyFailed) {
- await deps
- .recordSkillInstallEvent({
- ts: nowDate().toISOString(),
- surface: 'desktop-direct',
- target: 'cli-hosts',
- outcome: 'failed',
- version,
- reason: 'all-targets-failed',
- })
- .catch(() => {});
+ } else {
+ // One event per bundle that actually threw, naming the bundle: a pooled
+ // event would let a sibling's success hide it. A bundle that landed gets no
+ // event — the state file was not advanced, so nothing may claim it was.
+ for (const { id, failed } of bundleResults) {
+ if (!failed) continue;
+ await deps
+ .recordSkillInstallEvent({
+ ts: nowDate().toISOString(),
+ surface: 'desktop-direct',
+ target: 'cli-hosts',
+ bundle: id,
+ outcome: 'failed',
+ version,
+ reason: 'all-targets-failed',
+ })
+ .catch(() => {});
+ }
}
- // else: seed-if-absent no-op — every target was already present. Nothing was
- // written and nothing failed, so no state advance and no outcome event.
+ // Seed-if-absent no-op — every target already present — falls through the
+ // loop above with nothing written and nothing failed: no state advance and
+ // no outcome event.
return { status: 'done', version, entries };
}
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 887322075..fc79a87cc 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -563,6 +563,15 @@ export interface IntegrationsStatus {
readonly editors: readonly IntegrationsEditorStatus[];
readonly path: IntegrationsPathStatus;
readonly skills: readonly IntegrationsSkillStatus[];
+ /**
+ * Every editor whose host root already exists on this machine
+ * (`detectInstalledEditors`, home-scoped) — a SUPERSET of the ids in
+ * `editors[]`, which is filtered to targets with a user-global MCP surface.
+ * Carried here rather than on its own channel so project-scope-only targets
+ * (Pi) are still representable; consumed by the Create-new-project dialog to
+ * seed its editor checkboxes.
+ */
+ readonly detectedEditorIds: readonly McpWiringEditorId[];
}
/** One toggleable component in Settings → AI tools. */
diff --git a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
index b73230b46..2036ab25b 100644
--- a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
+++ b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
@@ -12,6 +12,11 @@
* not here — it needs an in-flight createNew the DOM tier can hold open
* deterministically.
*
+ * The editor checkboxes are seeded from `integrations.status().detectedEditorIds`
+ * on each open, and every spec here runs under a freshly-minted tmp HOME with
+ * no agent tool installed — so the deterministic baseline is "nothing checked",
+ * and a spec that wants an editor wired ticks it explicitly.
+ *
* Name-first model. Browse picks the **parent**; the project
* basename is supplied by typing into the Name <Input>. Tests set
* `OK_DESKTOP_TEST_PICKED_PATH = parent` and use the `typeProjectName`
@@ -34,6 +39,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { ALL_EDITOR_IDS } from '@inkeep/open-knowledge-core';
import type { ElectronApplication, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { typeProjectName } from './_helpers/create-new-dialog';
@@ -199,15 +205,18 @@ test.describe('QA extended create-new-project', () => {
{ timeout: 5_000 },
);
- // Uncheck cursor + codex. EDITOR IDs from cli (NOT 'claude-code').
+ // The selection is seeded from detection, and the seeded tmp HOME has no
+ // agent tool installed on it — so the baseline is nothing checked. Tick
+ // cursor and only cursor. EDITOR IDs from cli (NOT 'claude-code').
await expandCreateAdvanced(navigator);
- await navigator.locator('[data-testid="create-editor-cursor"]').click();
- await navigator.locator('[data-testid="create-editor-codex"]').click();
- // Verify state: claude + claude-desktop checked; cursor + codex unchecked.
- await expect(navigator.locator('[data-testid="create-editor-claude"]')).toBeChecked();
- await expect(navigator.locator('[data-testid="create-editor-claude-desktop"]')).toBeChecked();
- await expect(navigator.locator('[data-testid="create-editor-cursor"]')).not.toBeChecked();
+ const cursorBox = navigator.locator('[data-testid="create-editor-cursor"]');
+ await expect(cursorBox).not.toBeChecked();
+ await expect(navigator.locator('[data-testid="create-editor-codex"]')).not.toBeChecked();
+ await expect(navigator.locator('[data-testid="create-editor-claude"]')).not.toBeChecked();
+ await cursorBox.click();
+ await expect(cursorBox).toBeChecked();
await expect(navigator.locator('[data-testid="create-editor-codex"]')).not.toBeChecked();
+ await expect(navigator.locator('[data-testid="create-editor-claude"]')).not.toBeChecked();
const submit = navigator.locator('[data-testid="create-submit"]');
await expect(submit).toBeEnabled();
@@ -221,13 +230,17 @@ test.describe('QA extended create-new-project', () => {
.poll(() => existsSync(join(expected, '.ok', 'config.yml')), { timeout: 15_000 })
.toBe(true);
- // assertion: cursor + codex NOT present on disk.
- expect(existsSync(join(expected, '.cursor'))).toBe(false);
+ // The ticked editor is wired; the unticked ones leave nothing behind.
+ await expect
+ .poll(() => existsSync(join(expected, '.cursor', 'mcp.json')), { timeout: 15_000 })
+ .toBe(true);
expect(existsSync(join(expected, '.codex'))).toBe(false);
+ expect(existsSync(join(expected, '.claude'))).toBe(false);
+ expect(existsSync(join(expected, '.mcp.json'))).toBe(false);
});
// dialog UX: name input is focused on open, Location is hydrated,
- // all 4 editors visible.
+ // every editor row is visible and tickable under Advanced settings.
test('QA-010 dialog UX — focus, location, checkboxes, ARIA', async ({ captureStderrFor }) => {
const tmpHome = seedTmpHome('uxshape');
const parent = join(tmpHome, 'projects');
@@ -258,12 +271,19 @@ test.describe('QA extended create-new-project', () => {
const ariaLive = await caption.getAttribute('aria-live');
expect(ariaLive).toBe('polite');
- // All 4 editors visible + checked initially (under Advanced settings).
+ // Every known editor renders a row under Advanced settings. None starts
+ // checked: the selection is seeded from detection and nothing is installed
+ // under the seeded tmp HOME.
await expandCreateAdvanced(navigator);
- await expect(navigator.locator('[data-testid="create-editor-claude"]')).toBeChecked();
- await expect(navigator.locator('[data-testid="create-editor-claude-desktop"]')).toBeChecked();
- await expect(navigator.locator('[data-testid="create-editor-cursor"]')).toBeChecked();
- await expect(navigator.locator('[data-testid="create-editor-codex"]')).toBeChecked();
+ for (const id of ALL_EDITOR_IDS) {
+ const checkbox = navigator.locator(`[data-testid="create-editor-${id}"]`);
+ await expect(checkbox).toBeVisible();
+ await expect(checkbox).not.toBeChecked();
+ }
+ // The rows are interactive, not merely rendered.
+ const codexBox = navigator.locator('[data-testid="create-editor-codex"]');
+ await codexBox.click();
+ await expect(codexBox).toBeChecked();
// Type the name + Browse → caption shows the resolved target.
await typeProjectName(navigator, projectName);
@@ -325,6 +345,17 @@ test.describe('QA extended create-new-project', () => {
.poll(() => countWindowsByMode(app1, 'editor'), { timeout: 30_000 })
.toBeGreaterThanOrEqual(1);
+ // Advanced settings is never opened here, so this submits the
+ // detection-seeded selection — empty, since nothing is installed under the
+ // seeded tmp HOME. That still creates a real project; it just wires no
+ // editor integrations.
+ const firstProject = join(parent, projectName);
+ await expect
+ .poll(() => existsSync(join(firstProject, '.ok', 'config.yml')), { timeout: 15_000 })
+ .toBe(true);
+ expect(existsSync(join(firstProject, '.cursor'))).toBe(false);
+ expect(existsSync(join(firstProject, '.mcp.json'))).toBe(false);
+
// First → second launch hand-off. Both launches share the same `tmpHome` →
// same Electron `userData` dir. Two Electron processes against the
// same userData would contend on Chromium's lockfile; the first must be
@@ -362,7 +393,8 @@ test.describe('QA extended create-new-project', () => {
rmSync(join(userDataDir, 'bug-report-dirty-shutdown.json'), { force: true });
// Second launch: relaunch. Location prefills from lastUsedProjectParent;
- // the Name input resets to empty; editor checkboxes reset to checked.
+ // the Name input resets to empty; the editor selection re-seeds from
+ // detection (still empty under the seeded tmp HOME).
const app2 = await launchApp(tmpHome);
captureStderrFor(app2);
const navigator2 = await findWindowByMode(app2, 'navigator', 30_000);
@@ -380,10 +412,12 @@ test.describe('QA extended create-new-project', () => {
{ timeout: 15_000 },
);
await expandCreateAdvanced(navigator2);
- await expect(navigator2.locator('[data-testid="create-editor-claude"]')).toBeChecked();
- await expect(navigator2.locator('[data-testid="create-editor-claude-desktop"]')).toBeChecked();
- await expect(navigator2.locator('[data-testid="create-editor-cursor"]')).toBeChecked();
- await expect(navigator2.locator('[data-testid="create-editor-codex"]')).toBeChecked();
+ await expect(navigator2.locator('[data-testid="create-editor-claude"]')).not.toBeChecked();
+ await expect(
+ navigator2.locator('[data-testid="create-editor-claude-desktop"]'),
+ ).not.toBeChecked();
+ await expect(navigator2.locator('[data-testid="create-editor-cursor"]')).not.toBeChecked();
+ await expect(navigator2.locator('[data-testid="create-editor-codex"]')).not.toBeChecked();
});
// Create stays enabled even before the user types a name — a disabled
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 0a588b02f..103663fad 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -15050,6 +15050,16 @@ export function createApiExtension(
// fs-direct spine as import (the live re-scan admits the new dir,
// after which it IS a content doc).
const homeRel = resolveDefaultSkillHomeRel(putBase, body.scope);
+ if (homeRel === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'No agent skill host is available.',
+ { handler: 'skill-put', detail: 'NO_USABLE_SKILL_HOME' },
+ );
+ return;
+ }
const wr = applySkillWrite({
skillsRoot: resolve(putBase, homeRel),
name: body.name,
@@ -15741,7 +15751,18 @@ export function createApiExtension(
// Destination: the target scope's default skill home (store retirement —
// moved skills land in-place like creates/imports do).
const toBase2 = toScope === 'project' ? contentDir : skillsHome;
- const toRoot = resolve(toBase2, resolveDefaultSkillHomeRel(toBase2, toScope));
+ const toHomeRel = resolveDefaultSkillHomeRel(toBase2, toScope);
+ if (toHomeRel === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'No agent skill host is available in the destination scope.',
+ { handler: 'skill-move-scope', detail: 'NO_USABLE_SKILL_HOME' },
+ );
+ return;
+ }
+ const toRoot = resolve(toBase2, toHomeRel);
const toDir = resolve(toRoot, name);
if (realDir === null || !existsSync(fromDir)) {
errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {
@@ -16040,7 +16061,18 @@ export function createApiExtension(
return;
}
const base = body.scope === 'project' ? contentDir : skillsHome;
- const targetRoot = resolve(base, resolveDefaultSkillHomeRel(base, body.scope));
+ const targetHomeRel = resolveDefaultSkillHomeRel(base, body.scope);
+ if (targetHomeRel === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'No agent skill host is available.',
+ { handler: 'skill-duplicate', detail: 'NO_USABLE_SKILL_HOME' },
+ );
+ return;
+ }
+ const targetRoot = resolve(base, targetHomeRel);
const targetDir = resolve(targetRoot, body.toName);
if (resolveSkillDirForRead(body.scope, body.toName) !== null || existsSync(targetDir)) {
errorResponse(
@@ -18261,18 +18293,26 @@ export function createApiExtension(
return;
}
- // Targets: global installs into every editor that has a skill folder
- // ("all your editors, every project"), honoring an explicit
- // `targets` filter; project resolves the committed
+ // Targets: omitted global installs use only host roots already present
+ // on this machine; an explicit list remains authoritative and may
+ // create the named roots. Project resolves the committed
// `.ok/skill-targets.json` set → detected project-configured editors.
const targets: EditorId[] =
body.scope === 'global'
- ? targetsReq
+ ? targetsReq !== undefined
? // targetsReq is the narrower SkillTargetEditor set (no
// claude-desktop, which shares claude's host dir); match by
// value so the EditorId/SkillTargetEditor widths don't clash.
PROJECT_SKILL_EDITOR_IDS.filter((id) => targetsReq?.some((t) => t === id))
- : [...PROJECT_SKILL_EDITOR_IDS]
+ : // Detection (`USER_SKILL_HOSTS`) is WIDER than the install-target
+ // vocabulary: `antigravity` has a user skill root (`~/.gemini/skills`)
+ // but no project one, so it is absent from PROJECT_SKILL_EDITOR_IDS,
+ // from the picker's checkbox set, and from `resolvedHosts` — a copy
+ // projected there could never be shown or dropped by a later
+ // set-exact install. Intersect, as the explicit branches do.
+ detectUserSkillHosts(skillsHome)
+ .map((host) => host.editorId)
+ .filter((id) => PROJECT_SKILL_EDITOR_IDS.includes(id))
: targetsReq !== undefined
? // An EXPLICIT target list from the per-editor menu is set-exact,
// INCLUDING `[]` (unchecking the last editor = install nowhere =
@@ -18323,7 +18363,10 @@ export function createApiExtension(
const canonicalRootRel = inPlaceEntry.dir.split('/').slice(0, -1).join('/');
// The `.agents` hub is a first-class install target for in-place
// skills (the editors-only resolver above drops it from `targets`).
- const hubTargeted = targetsReq?.includes('agents') === true;
+ const hubTargeted =
+ targetsReq !== undefined
+ ? targetsReq.includes('agents')
+ : body.scope === 'global' && existsSync(join(skillsHome, '.agents'));
const inPlaceTargets: SkillHostId[] = hubTargeted ? [...targets, 'agents'] : [...targets];
// Install-mode default chain: explicit request > per-skill preference
// (scope-local) > project-committed default > this machine's
diff --git a/packages/server/src/in-place-skills.test.ts b/packages/server/src/in-place-skills.test.ts
index 4705d9bab..685e827c8 100644
--- a/packages/server/src/in-place-skills.test.ts
+++ b/packages/server/src/in-place-skills.test.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createContentFilter } from './content-filter.ts';
import {
removableSkillOccurrenceDirs,
+ resolveDefaultSkillHomeRel,
resolveGlobalNativeSkillDir,
scanGlobalInPlaceSkills,
scanHostRootAliases,
@@ -13,6 +14,50 @@ import {
scanInPlaceSkills,
} from './in-place-skills.ts';
+describe('resolveDefaultSkillHomeRel', () => {
+ let base: string;
+ beforeEach(() => {
+ base = mkdtempSync(join(tmpdir(), 'ok-default-skill-home-'));
+ });
+ afterEach(() => {
+ rmSync(base, { recursive: true, force: true });
+ });
+
+ test.each([
+ 'project',
+ 'global',
+ ] as const)('returns no %s home and creates nothing when no host root exists', (scope) => {
+ expect(resolveDefaultSkillHomeRel(base, scope)).toBeNull();
+ expect(existsSync(join(base, '.claude'))).toBe(false);
+ expect(existsSync(join(base, '.agents'))).toBe(false);
+ });
+
+ test('keeps existing hub and concrete roots selectable by precedence', () => {
+ mkdirSync(join(base, '.codex'), { recursive: true });
+ mkdirSync(join(base, '.claude'), { recursive: true });
+ expect(resolveDefaultSkillHomeRel(base, 'project')).toBe('.claude/skills');
+
+ mkdirSync(join(base, '.agents'), { recursive: true });
+ expect(resolveDefaultSkillHomeRel(base, 'project')).toBe('.agents/skills');
+ expect(resolveDefaultSkillHomeRel(base, 'global')).toBe('.agents/skills');
+ });
+
+ test('does not claim `.github` as a project home on its mere presence', () => {
+ mkdirSync(join(base, '.github', 'workflows'), { recursive: true });
+ expect(resolveDefaultSkillHomeRel(base, 'project')).toBeNull();
+ });
+
+ test('claims `.github/skills` once the project actually adopted it', () => {
+ mkdirSync(join(base, '.github', 'skills'), { recursive: true });
+ expect(resolveDefaultSkillHomeRel(base, 'project')).toBe('.github/skills');
+ });
+
+ test('claims the user-global Copilot home from its own dotdir', () => {
+ mkdirSync(join(base, '.copilot'), { recursive: true });
+ expect(resolveDefaultSkillHomeRel(base, 'global')).toBe('.copilot/skills');
+ });
+});
+
function writeSkill(root: string, rel: string, body: string): void {
const dir = join(root, rel);
mkdirSync(dir, { recursive: true });
diff --git a/packages/server/src/in-place-skills.ts b/packages/server/src/in-place-skills.ts
index 03793c055..847a6d320 100644
--- a/packages/server/src/in-place-skills.ts
+++ b/packages/server/src/in-place-skills.ts
@@ -26,6 +26,7 @@ import {
type EditorId,
LEGACY_SKILL_STORE_ROOT,
type SkillScope,
+ skillRootActivationPath,
} from '@inkeep/open-knowledge-core';
import {
buildSkillRegistry,
@@ -269,9 +270,10 @@ export function aliasedSourceRoots(
* The DEFAULT home for a NEW skill bundle at `base` — existence-activated:
* `.agents/skills` only when the project already adopted the hub (OK never
* creates `.agents` on its own — that's the team's call, not ours), else the
- * highest-precedence editor root that already exists, else `.claude/skills`.
+ * highest-precedence editor root that already exists. `null` means no host has
+ * granted a usable location.
*/
-export function resolveDefaultSkillHomeRel(base: string, scope: SkillScope): string {
+export function resolveDefaultSkillHomeRel(base: string, scope: SkillScope): string | null {
const roots = scope === 'project' ? EDITOR_SKILL_ROOTS : USER_SKILL_ROOTS;
if (existsSync(join(base, '.agents'))) return AGENTS_SKILLS_ROOT;
const byPrecedence = [...roots]
@@ -285,10 +287,20 @@ export function resolveDefaultSkillHomeRel(base: string, scope: SkillScope): str
);
});
for (const { root } of byPrecedence) {
- if (existsSync(join(base, root))) return root;
+ if (existsSync(join(base, skillRootActivationPath(root)))) return root;
}
- // No existing host dir: default to `.claude/skills` (same for both scopes).
- return '.claude/skills';
+ return null;
+}
+
+/**
+ * The folders {@link resolveDefaultSkillHomeRel} would accept at `scope`, as the
+ * activation paths a user actually creates (`.claude/`, `.agents/`, …). Lives
+ * beside the resolver so a refusal message naming them cannot drift from the
+ * set the resolver really consults when a new host is onboarded.
+ */
+export function skillHomeCandidateFolders(scope: SkillScope): string[] {
+ const roots = scope === 'project' ? EDITOR_SKILL_ROOTS : USER_SKILL_ROOTS;
+ return [...new Set(roots.map((r) => `${skillRootActivationPath(r.root)}/`))];
}
/**
diff --git a/packages/server/src/managed-artifact-persistence.test.ts b/packages/server/src/managed-artifact-persistence.test.ts
index 56d8f485a..f633a58e1 100644
--- a/packages/server/src/managed-artifact-persistence.test.ts
+++ b/packages/server/src/managed-artifact-persistence.test.ts
@@ -40,6 +40,19 @@ function makeCtx(): ManagedArtifactCtx {
};
}
+/**
+ * Give the throwaway home an adopted `.claude` harness. Global skill
+ * destinations resolve via `resolveDefaultSkillHomeRel`, which returns null
+ * when the home has adopted no harness at all — OK never creates one on the
+ * user's behalf. A user who has Claude Code installed is the normal shape for
+ * the blocks that resolve a global skill path, so they opt in here; the blocks
+ * that assert on the bare-home shape are left bare. Mirrors the
+ * `seedSkillHostRoot` option in `packages/app/tests/integration/test-harness.ts`.
+ */
+function adoptClaudeHost(): void {
+ mkdirSync(join(home, '.claude', 'skills'), { recursive: true });
+}
+
beforeEach(() => {
projectDir = mkdtempSync(join(tmpdir(), 'ok-ma-proj-'));
home = mkdtempSync(join(tmpdir(), 'ok-ma-home-'));
@@ -51,6 +64,8 @@ afterEach(() => {
});
describe('managedArtifactAbsPath', () => {
+ beforeEach(adoptClaudeHost);
+
test('global with no native/store resolves to the IN-PLACE default home, never the store', () => {
const ctx = makeCtx();
// Project managed docs keep the legacy `.ok/skills` content path (project
@@ -61,8 +76,8 @@ describe('managedArtifactAbsPath', () => {
// Store retirement: a global skill with neither a native copy nor a store
// resident resolves to the in-place default home — NEVER `~/.ok/skills`.
// Defaulting to the store re-created the remnant on every stray global write
- // (a global doc autosaving after the skill was moved away). Fresh home has no
- // editor dirs → `.claude/skills`.
+ // (a global doc autosaving after the skill was moved away). The fixture's
+ // only adopted host is `.claude`, so that is the default home.
expect(managedArtifactAbsPath('__skill__/global/my-skill', ctx)).toBe(
resolve(home, '.claude', 'skills', 'my-skill', 'SKILL.md'),
);
@@ -115,7 +130,7 @@ describe('managedArtifactAbsPath', () => {
test('resolves a bundle FILE (rel) inside the resolved skill dir (per-file editability)', () => {
const ctx = makeCtx();
// Store retirement: with no native/store, a global skill resolves under the
- // in-place default home (`.claude/skills` in a fresh home), not `.ok/skills`.
+ // in-place default home (the fixture's adopted `.claude`), not `.ok/skills`.
// Not-yet-created file → ext-less doc name binds to `.md` by default.
expect(managedArtifactAbsPath('__skill__/global/demo/references/patterns', ctx)).toBe(
resolve(home, '.claude', 'skills', 'demo', 'references', 'patterns.md'),
@@ -172,6 +187,7 @@ describe('store/load round-trip', () => {
// guard), so seed the dir here and let these tests exercise what they are
// about: round-trip fidelity and reconcile, not bundle creation.
beforeEach(() => {
+ adoptClaudeHost();
mkdirSync(dirname(managedArtifactAbsPath(docName, makeCtx())), { recursive: true });
});
@@ -340,6 +356,7 @@ describe('concurrent-writer reconcile', () => {
// guard), so seed the dir here and let these tests exercise what they are
// about: round-trip fidelity and reconcile, not bundle creation.
beforeEach(() => {
+ adoptClaudeHost();
mkdirSync(dirname(managedArtifactAbsPath(docName, makeCtx())), { recursive: true });
});
@@ -470,6 +487,8 @@ describe('concurrent-writer reconcile', () => {
});
describe('managedArtifactDocNameForPath (reverse resolver)', () => {
+ beforeEach(adoptClaudeHost);
+
test('maps a global SKILL.md leaf back to its doc name; project paths are content', () => {
const ctx = makeCtx();
// Project skills are content docs now — a project skill path no longer maps
@@ -578,6 +597,9 @@ describe('managedArtifactContributorAttribution (editor-edit versioning)', () =>
describe('managedArtifactSkillsRoots', () => {
test('covers every native user root, with the legacy store included but not privileged', () => {
+ // A root is a watch target only once its host dotdir exists (the watcher
+ // mkdir -p's what it is handed), so adopt the hosts this block asserts on.
+ for (const d of ['.claude', '.agents', '.ok']) mkdirSync(join(home, d), { recursive: true });
const ctx = makeCtx();
const roots = managedArtifactSkillsRoots(ctx);
// Global skills live IN PLACE, so the native roots are what matters here.
@@ -591,6 +613,26 @@ describe('managedArtifactSkillsRoots', () => {
// All under the ctx home — no absolute leaks from another machine state.
expect(roots.every((r) => r.startsWith(home))).toBe(true);
});
+
+ /**
+ * OK never creates a harness home. Every root here is `mkdir -p`'d by the
+ * managed-artifact watcher at boot, so an ungated list grew `~/.codex`,
+ * `~/.copilot`, `~/.cursor`, `~/.opencode` and `~/.pi` in a real `$HOME`
+ * belonging to a user who has none of those tools installed.
+ */
+ test('omits roots whose host dotdir does not exist', () => {
+ expect(managedArtifactSkillsRoots(makeCtx())).toEqual([]);
+ mkdirSync(join(home, '.claude'), { recursive: true });
+ expect(managedArtifactSkillsRoots(makeCtx())).toEqual([resolve(home, '.claude', 'skills')]);
+ });
+
+ test('a nested user layout activates on the host dotdir, not the leaf parent', () => {
+ // Pi keeps its skills at `.pi/agent/skills`; `.pi` alone is proof enough.
+ mkdirSync(join(home, '.pi'), { recursive: true });
+ expect(managedArtifactSkillsRoots(makeCtx())).toContain(
+ resolve(home, '.pi', 'agent', 'skills'),
+ );
+ });
});
describe('managedArtifactTimelinePaths', () => {
@@ -705,6 +747,8 @@ describe('a skill doc never RESURRECTS a bundle that is gone', () => {
// that every scanner then reads as real.
const docName = '__skill__/global/code-mode';
+ beforeEach(adoptClaudeHost);
+
function seedGlobalBundle(ctx: ManagedArtifactCtx): string {
// Ask the resolver where this skill lives rather than hardcoding the
// default home, so the test follows the same resolution order as the code.
diff --git a/packages/server/src/managed-artifact-persistence.ts b/packages/server/src/managed-artifact-persistence.ts
index d21486042..854265e07 100644
--- a/packages/server/src/managed-artifact-persistence.ts
+++ b/packages/server/src/managed-artifact-persistence.ts
@@ -28,7 +28,7 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
-import { dirname, resolve, sep } from 'node:path';
+import { dirname, relative, resolve, sep } from 'node:path';
import {
LEGACY_SKILL_STORE_ROOT,
LINEAGE_EPOCH_KEY,
@@ -38,6 +38,7 @@ import {
parseExternalSkillDocName,
parseManagedArtifactName,
SKILL_NAME_REGEX,
+ skillRootActivationPath,
} from '@inkeep/open-knowledge-core';
import {
atomicWriteFile,
@@ -184,9 +185,20 @@ export function managedArtifactTimelinePaths(
* would double-index every `SKILL.md`. Global skills live at
* `<home>/.ok/skills`, OUTSIDE contentDir, so this dedicated watch stays their
* only disk→doc reconcile path.
+ *
+ * Gated on the host dotdir ALREADY existing. The watcher `mkdir -p`s every root
+ * it is handed, so the ungated vocabulary conjured `~/.codex`, `~/.copilot`,
+ * `~/.cursor`, `~/.opencode`, `~/.pi` on a machine with none of those tools
+ * installed — just by booting OK. OK never creates a harness home; an existing
+ * dotdir means the tool IS installed, and creating its `skills/` leaf under it
+ * is expected. A root that appears later is picked up on the next boot, and a
+ * skill installed into it is materialized by the projection path regardless.
*/
export function managedArtifactSkillsRoots(ctx: ManagedArtifactCtx): string[] {
- return globalSkillGraphRoots(homeFor(ctx));
+ const home = homeFor(ctx);
+ return globalSkillGraphRoots(home).filter((abs) =>
+ existsSync(resolve(home, skillRootActivationPath(relative(home, abs).split(sep).join('/')))),
+ );
}
/**
@@ -223,7 +235,7 @@ function managedSkillBundleDir(
scope: ManagedArtifactScope,
name: string,
ctx: ManagedArtifactLocation,
-): string {
+): string | null {
// Guard 1: slug grammar (rejects `..`, slashes, dots, uppercase, empty).
if (!SKILL_NAME_REGEX.test(name) || name.length > 64) {
throw new Error(`managedSkillBundleDir: invalid skill name: ${JSON.stringify(name)}`);
@@ -248,12 +260,10 @@ function managedSkillBundleDir(
// the bundle-existence check in `storeManagedArtifactDoc`.
const native = resolveGlobalNativeSkillDir(base, name);
const storeDir = resolve(base, '.ok', 'skills', name);
- return (
- native ??
- (existsSync(resolve(storeDir, 'SKILL.md'))
- ? storeDir
- : resolve(base, resolveDefaultSkillHomeRel(base, 'global'), name))
- );
+ if (native !== null) return native;
+ if (existsSync(resolve(storeDir, 'SKILL.md'))) return storeDir;
+ const homeRel = resolveDefaultSkillHomeRel(base, 'global');
+ return homeRel === null ? null : resolve(base, homeRel, name);
}
/**
@@ -312,6 +322,9 @@ export function managedArtifactAbsPath(documentName: string, ctx: ManagedArtifac
throw new Error(`managedArtifactAbsPath: not a managed skill doc name: ${documentName}`);
}
const skillDir = managedSkillBundleDir(parsed.scope, parsed.name, ctx);
+ if (skillDir === null) {
+ throw new Error(`managedArtifactAbsPath: no usable skill home for ${documentName}`);
+ }
let abs: string;
if (parsed.rel === null) {
abs = resolve(skillDir, 'SKILL.md');
@@ -562,7 +575,8 @@ export async function storeManagedArtifactDoc(
// debounce fires against the old path afterwards. This stat is the last thing
// between a stale doc and a resurrected artifact.
const containerDir = managedArtifactContainerDir(documentName, ctx);
- if (containerDir !== null && !existsSync(containerDir)) {
+ if (containerDir === null) return 'no-op';
+ if (!existsSync(containerDir)) {
log.warn(
{ documentName, containerDir },
'store: artifact container is gone (deleted or moved); dropping the write rather than resurrecting it',
diff --git a/packages/server/src/managed-artifact-watcher.test.ts b/packages/server/src/managed-artifact-watcher.test.ts
index fd540a46e..1813bec94 100644
--- a/packages/server/src/managed-artifact-watcher.test.ts
+++ b/packages/server/src/managed-artifact-watcher.test.ts
@@ -1,7 +1,8 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { managedArtifactSkillsRoots } from './managed-artifact-persistence.ts';
import {
type ManagedArtifactWatcherUnsubscribe,
startManagedArtifactWatcher,
@@ -92,3 +93,34 @@ describe.skipIf(RUNNING_IN_CI)('startManagedArtifactWatcher', () => {
expect(contents).not.toContain('noise');
}, 25_000);
});
+
+/**
+ * The branch invariant: OK never CREATES a harness home, it only writes into
+ * one that already exists. This watcher is where that broke — it `mkdir -p`s
+ * every root handed to it, and the roots list was the full vocabulary, so
+ * booting a server against a home with only `.claude` grew `.codex`,
+ * `.copilot`, `.cursor`, `.opencode` and `.pi` before a single skill was
+ * written. Asserted as "no dotdir the home did not start with", not as a list
+ * of the five that leaked, so a newly onboarded editor is covered too.
+ */
+describe('managed-artifact watch roots never conjure a harness home', () => {
+ test('booting the watcher against a home with only .claude adds no host dotdir', async () => {
+ mkdirSync(join(root, '.claude'));
+ const before = readdirSync(root).sort();
+
+ cleanup = await startManagedArtifactWatcher(
+ managedArtifactSkillsRoots({
+ projectDir: root,
+ homedirOverride: root,
+ lkgCache: new Map<string, string>(),
+ setReconciledBase: () => {},
+ getReconciledBase: () => undefined,
+ }),
+ () => {},
+ );
+
+ expect(readdirSync(root).sort()).toEqual(before);
+ // …and the one host that IS installed still gets its watchable skills leaf.
+ expect(existsSync(resolve(root, '.claude', 'skills'))).toBe(true);
+ }, 25_000);
+});
diff --git a/packages/server/src/seed/apply.test.ts b/packages/server/src/seed/apply.test.ts
index 5457a809c..522846ed8 100644
--- a/packages/server/src/seed/apply.test.ts
+++ b/packages/server/src/seed/apply.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -144,6 +144,30 @@ describe('applySeed — nested .ok/ era', () => {
expect(existsSync(join(projectDir, 'brain', 'log.md'))).toBe(true);
});
+ test('no adopted agent host: pack skills are skipped cleanly, not reported as errors', async () => {
+ // OK never creates `.claude` / `.agents` / … on the user's behalf, so a
+ // project that has adopted no host gets no pack skills — a consented
+ // refusal, not an authoring failure. It must not surface on `errors`.
+ const plan = await planSeed({ projectDir });
+ const result = await applySeed(plan, { projectDir });
+
+ expect(result.errors).toEqual([]);
+ expect(result.packSkillsInstalled).toEqual([]);
+ expect(existsSync(join(projectDir, '.claude'))).toBe(false);
+ expect(existsSync(join(projectDir, '.agents'))).toBe(false);
+ });
+
+ test('an adopted agent host receives the pack skills', async () => {
+ // The counterpart: with a host root already on disk the skills DO land, so
+ // the guard above suppresses only the no-host case, not real failures.
+ mkdirSync(join(projectDir, '.claude', 'skills'), { recursive: true });
+ const plan = await planSeed({ projectDir });
+ const result = await applySeed(plan, { projectDir });
+
+ expect(result.errors).toEqual([]);
+ expect(readdirSync(join(projectDir, '.claude', 'skills')).length).toBeGreaterThan(0);
+ });
+
test('reports an error for unknown template ids without crashing', async () => {
// Hand-craft a plan with an entry that points at a template id we don't
// ship — apply should record an error rather than write empty content.
diff --git a/packages/server/src/seed/apply.ts b/packages/server/src/seed/apply.ts
index 8cc2107f9..416a26530 100644
--- a/packages/server/src/seed/apply.ts
+++ b/packages/server/src/seed/apply.ts
@@ -1,7 +1,11 @@
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { scanInPlaceSkills } from '../in-place-skills.ts';
-import { installPackSkill, resolvePackSkillSources } from './install-pack-skill.ts';
+import {
+ installPackSkill,
+ resolvePackSkillHome,
+ resolvePackSkillSources,
+} from './install-pack-skill.ts';
import { assertEntryPathInProject } from './path-safety.ts';
import { buildStarterFolderFrontmatterYaml, DEFAULT_PACK_ID, resolvePack } from './starter.ts';
import type { ApplyError, ApplyResult, FileEntry, ScaffoldPlan, SeedOptions } from './types.ts';
@@ -156,11 +160,21 @@ export async function applySeed(plan: ScaffoldPlan, opts: SeedOptions = {}): Pro
// channel as file entries: a partial install must not read as a clean seed.
// The skill can live at ANY root under the in-place model — the scan is the
// presence truth (a legacy `.ok/skills` resident counts too).
- const presentNames = new Set(scanInPlaceSkills(projectDir).map((sk) => sk.name));
- for (const { name } of resolvePackSkillSources(pack.id)) {
- const inStore = existsSync(join(projectDir, '.ok', 'skills', name, 'SKILL.md'));
- if (!presentNames.has(name) && !inStore) {
- errors.push({ path: name, error: 'skill source could not be authored' });
+ //
+ // Skipped entirely when the project has no usable skill home (no adopted
+ // agent host — OK never creates one on the user's behalf — or a home
+ // symlinked out of the project), so `installPackSkill` deliberately no-ops.
+ // That consented refusal is not an authoring failure — reporting it per skill
+ // turned a clean seed into N user-facing `✗ … skill source could not be
+ // authored` lines on the CLI. Same resolver `planSeed` previews with, so plan
+ // and apply cannot disagree about whether a skill is installable.
+ if (!('refusal' in resolvePackSkillHome(projectDir))) {
+ const presentNames = new Set(scanInPlaceSkills(projectDir).map((sk) => sk.name));
+ for (const { name } of resolvePackSkillSources(pack.id)) {
+ const inStore = existsSync(join(projectDir, '.ok', 'skills', name, 'SKILL.md'));
+ if (!presentNames.has(name) && !inStore) {
+ errors.push({ path: name, error: 'skill source could not be authored' });
+ }
}
}
diff --git a/packages/server/src/seed/install-pack-skill.test.ts b/packages/server/src/seed/install-pack-skill.test.ts
index 403097895..6b81889bd 100644
--- a/packages/server/src/seed/install-pack-skill.test.ts
+++ b/packages/server/src/seed/install-pack-skill.test.ts
@@ -131,13 +131,15 @@ describe('installPackSkill', () => {
}
});
- test('no editor set up: the source is still authored at the fallback home', async () => {
+ test('no editor set up: skips skill materialization without creating a host root', async () => {
const proj = tmpProject();
const name = orientationName('knowledge-base');
- // No set-up editor → nothing fanned/labelled, but the source still lands
- // (default fallback home) so the skill lists for that folder's agent.
- expect((await installPackSkill(proj, 'knowledge-base')).editors).toEqual([]);
- expect(existsSync(join(proj, '.claude', 'skills', name, 'SKILL.md'))).toBe(true);
+ const result = await installPackSkill(proj, 'knowledge-base');
+
+ expect(result).toEqual({ editors: [], conflicts: [] });
+ expect(existsSync(join(proj, '.claude'))).toBe(false);
+ expect(existsSync(join(proj, '.agents'))).toBe(false);
+ expect(existsSync(join(proj, '.ok', 'skills', name))).toBe(false);
expect(readInstalledSkills(proj).skills[name]).toBeUndefined();
});
diff --git a/packages/server/src/seed/install-pack-skill.ts b/packages/server/src/seed/install-pack-skill.ts
index c0fe87fab..c2ae6aa5f 100644
--- a/packages/server/src/seed/install-pack-skill.ts
+++ b/packages/server/src/seed/install-pack-skill.ts
@@ -174,6 +174,33 @@ function packIdFromSkillMd(md: string): string | null {
return /^[ \t]+pack:[ \t]*"?([a-z0-9-]+)"?[ \t]*$/m.exec(frontmatter)?.[1] ?? null;
}
+/**
+ * Why a project cannot receive pack skills at all:
+ * - `no-agent-folder` — the project has adopted no agent host, and OK never
+ * creates one on the user's behalf.
+ * - `home-escapes-project` — the default home is an editor dir symlinked out
+ * of the project; authoring through it would write outside the repo.
+ */
+export type PackSkillHomeRefusal = 'no-agent-folder' | 'home-escapes-project';
+
+/**
+ * The project-local dir pack skills would be authored into, or the reason no
+ * install is possible. Single source of truth for the three surfaces that must
+ * agree: `planSeed` (preview), `applySeed` (post-install reconciliation) and
+ * `installPackSkill` (the write). Split them and a plan promises installs apply
+ * declines forever.
+ */
+export function resolvePackSkillHome(
+ projectDir: string,
+): { homeRel: string } | { refusal: PackSkillHomeRefusal } {
+ const homeRel = resolveDefaultSkillHomeRel(projectDir, 'project');
+ if (homeRel === null) return { refusal: 'no-agent-folder' };
+ if (hostSkillsRootEscapes(projectDir, join(projectDir, homeRel))) {
+ return { refusal: 'home-escapes-project' };
+ }
+ return { homeRel };
+}
+
export async function installPackSkill(
projectDir: string,
packId: string,
@@ -220,18 +247,26 @@ export async function installPackSkill(
const scanDirByName = new Map(scan.map((sk) => [sk.name, join(projectDir, sk.dir)]));
const lock = readSkillsLockFile(join(projectDir, ...SKILLS_LOCK_REL));
const conflicts: PackSkillConflict[] = [];
- const homeRel = resolveDefaultSkillHomeRel(projectDir, 'project');
- // The default home can be an editor dir that SYMLINKS OUT of the project
- // (the escape class the projection guard refuses) — authoring through it
- // would write outside the repo. Refuse the whole pack-skill install then;
- // the old `.ok/skills` landing was only incidentally immune.
- if (hostSkillsRootEscapes(projectDir, join(projectDir, homeRel))) {
- getLogger('seed').warn(
- { packId, homeRel },
- 'default skill home escapes the project (symlinked out) — pack skills not installed',
- );
+ // Both refusals (no adopted host; a default home that SYMLINKS OUT of the
+ // project — the escape class the projection guard refuses, which the old
+ // `.ok/skills` landing was only incidentally immune to) come from the shared
+ // resolver, so the plan can decline in exactly the same cases.
+ const home = resolvePackSkillHome(projectDir);
+ if ('refusal' in home) {
+ if (home.refusal === 'home-escapes-project') {
+ getLogger('seed').warn(
+ { packId },
+ 'default skill home escapes the project (symlinked out) — pack skills not installed',
+ );
+ } else {
+ getLogger('seed').info(
+ { packId },
+ 'no existing agent host is available — pack skills not installed',
+ );
+ }
return { editors: [], conflicts: [] };
}
+ const homeRel = home.homeRel;
// The editor whose root HOLDS the source loads it directly — it counts as
// installed even though fan-out (rightly) skips the canonical's own root.
const homeHost = (Object.entries(EDITOR_PROJECT_SKILL_ROOT) as [EditorId, string | null][]).find(
diff --git a/packages/server/src/seed/plan.test.ts b/packages/server/src/seed/plan.test.ts
index a06a3a889..7054a6c87 100644
--- a/packages/server/src/seed/plan.test.ts
+++ b/packages/server/src/seed/plan.test.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, writeFileSync } from 'node:fs';
+import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -134,6 +134,47 @@ describe('planSeed — nested .ok/ era', () => {
test('rootDir rejects path traversal', async () => {
await expect(planSeed({ projectDir, rootDir: '../escape' })).rejects.toThrow(SeedRootDirError);
});
+
+ // OK never creates an agent home, so `installPackSkill` declines outright in a
+ // project that adopted none. A plan reporting the skills pending there
+ // promises work apply refuses on every run — the seed then claims it did
+ // something forever while doing nothing.
+ test('no agent folder: pack skills are not pending, and the plan says why', async () => {
+ const plan = await planSeed({ projectDir, packId: 'plain-notes' });
+ expect(plan.packSkills?.length).toBeGreaterThan(0);
+ expect(plan.packSkills?.some((s) => s.pending)).toBe(false);
+ expect(plan.packSkillHomeRefusal).toBe('no-agent-folder');
+ });
+
+ test('with an adopted agent folder, an absent pack skill is pending', async () => {
+ mkdirSync(join(projectDir, '.claude'), { recursive: true });
+ const plan = await planSeed({ projectDir, packId: 'plain-notes' });
+ expect(plan.packSkills?.some((s) => s.pending)).toBe(true);
+ expect(plan.packSkillHomeRefusal).toBeUndefined();
+ });
+
+ // The OTHER refusal: an agent folder DOES exist, but it symlinks out of the
+ // project, so authoring through it would write outside the repo. Kept
+ // distinct from `no-agent-folder` because the two need different user
+ // guidance (replace the symlink vs. create a folder), so the plan must
+ // report which one it is rather than collapse both into "no home".
+ test('an agent folder symlinked outside the project refuses with home-escapes-project', async () => {
+ const outside = await mkdtemp(join(tmpdir(), 'seed-outside-'));
+ try {
+ // `.claude` resolves outside the project and its `skills` root exists —
+ // the shape `resolveDefaultSkillHomeRel` picks and the escape guard then
+ // refuses.
+ symlinkSync(outside, join(projectDir, '.claude'));
+ mkdirSync(join(outside, 'skills'), { recursive: true });
+
+ const plan = await planSeed({ projectDir, packId: 'plain-notes' });
+
+ expect(plan.packSkillHomeRefusal).toBe('home-escapes-project');
+ expect(plan.packSkills?.some((s) => s.pending)).toBe(false);
+ } finally {
+ await rm(outside, { recursive: true, force: true });
+ }
+ });
});
describe('planSeed — codebase-wiki nested paths', () => {
diff --git a/packages/server/src/seed/plan.ts b/packages/server/src/seed/plan.ts
index e2ab71a1e..7e6fb08a2 100644
--- a/packages/server/src/seed/plan.ts
+++ b/packages/server/src/seed/plan.ts
@@ -8,6 +8,8 @@ import { readSkillsLockFile } from '../skills-lock-store.ts';
import {
classifyPresentPackSkill,
OLD_PACK_SKILL_NAME,
+ type PackSkillHomeRefusal,
+ resolvePackSkillHome,
resolvePackSkillSources,
} from './install-pack-skill.ts';
import { assertEntryPathInProject } from './path-safety.ts';
@@ -216,7 +218,14 @@ export async function planSeed(opts: SeedOptions = {}): Promise<ScaffoldPlan> {
// Presence is scan-based (in-place editor-dir skills, same source of truth
// `installPackSkill` dedups against), with the legacy `.ok/skills` store
// still honored for pre-inversion projects.
+ // Nothing is pending when the project has no usable skill home: OK never
+ // creates an agent folder, so `installPackSkill` declines and re-running
+ // the seed would change nothing. Reporting work that can never happen made
+ // every `ok seed` re-run in such a project claim it did something.
const sources = resolvePackSkillSources(pack.id);
+ const home = sources.length > 0 ? resolvePackSkillHome(projectDir) : null;
+ const homeRefusal: PackSkillHomeRefusal | undefined =
+ home !== null && 'refusal' in home ? home.refusal : undefined;
const scan = sources.length > 0 ? scanInPlaceSkills(projectDir) : [];
const inPlaceDirByName = new Map(scan.map((sk) => [sk.name, join(projectDir, sk.dir)]));
const lock = sources.length > 0 ? readSkillsLockFile(join(projectDir, ...SKILLS_LOCK_REL)) : null;
@@ -252,8 +261,20 @@ export async function planSeed(opts: SeedOptions = {}): Promise<ScaffoldPlan> {
presentDir !== null &&
lock !== null &&
classifyPresentPackSkill(pack.id, presentName, presentDir, lock) === 'foreign';
- return { name, pending: presentDir === null, ...(conflict ? { conflict: true } : {}) };
+ return {
+ name,
+ pending: presentDir === null && homeRefusal === undefined,
+ ...(conflict ? { conflict: true } : {}),
+ };
});
- return { created, skipped, warnings, ...(packSkills.length > 0 ? { packSkills } : {}) };
+ return {
+ created,
+ skipped,
+ warnings,
+ ...(packSkills.length > 0 ? { packSkills } : {}),
+ ...(packSkills.length > 0 && homeRefusal !== undefined
+ ? { packSkillHomeRefusal: homeRefusal }
+ : {}),
+ };
}
diff --git a/packages/server/src/seed/types.ts b/packages/server/src/seed/types.ts
index 3f09ac15a..49bfa9354 100644
--- a/packages/server/src/seed/types.ts
+++ b/packages/server/src/seed/types.ts
@@ -69,8 +69,19 @@ export interface ScaffoldPlan {
* provenance (the user's own skill happens to share the name): apply will
* neither install nor clobber it, and callers must surface it instead of
* reading the pack as already set up.
+ *
+ * `pending` is always false when `packSkillHomeRefusal` is set — see below.
*/
packSkills?: { name: string; pending: boolean; conflict?: boolean }[];
+ /**
+ * Set when the pack ships skills but this project has no usable skill home,
+ * so apply cannot install any of them (OK never creates an agent folder on
+ * the user's behalf). Nothing is pending in that case — a plan that promised
+ * work apply always declines made `ok seed` report "applied" on every re-run
+ * while doing nothing. Callers should say the skills were not installed and
+ * why, rather than report a clean, complete seed.
+ */
+ packSkillHomeRefusal?: 'no-agent-folder' | 'home-escapes-project';
}
/**
diff --git a/packages/server/src/services/skill-import.ts b/packages/server/src/services/skill-import.ts
index e266eebe7..42de79a82 100644
--- a/packages/server/src/services/skill-import.ts
+++ b/packages/server/src/services/skill-import.ts
@@ -22,7 +22,7 @@ import {
} from '../content/skills-write.ts';
import type { extractActorIdentity } from '../extract-actor-identity.ts';
import { sanitizeFilename } from '../filename-sanitize.ts';
-import { resolveDefaultSkillHomeRel } from '../in-place-skills.ts';
+import { resolveDefaultSkillHomeRel, skillHomeCandidateFolders } from '../in-place-skills.ts';
import { getLogger } from '../logger.ts';
import {
projectInPlaceSkill,
@@ -184,6 +184,20 @@ export function createSkillImportService(deps: SkillImportDeps): SkillImportServ
// residents; existing store bundles keep working until their migration.
const importBase = scope === 'project' ? deps.contentDir : deps.skillsHome;
const importHomeRel = resolveDefaultSkillHomeRel(importBase, scope);
+ if (importHomeRel === null) {
+ // Actionable, not just accurate: this refusal is reachable by anyone
+ // importing into a project (or home) that has adopted no agent folder,
+ // and "no host available" leaves them with nothing to do about it. The
+ // folder list comes from the resolver's own candidate set, so onboarding
+ // a new host cannot leave this message naming a stale one.
+ return {
+ ok: false,
+ status: 400,
+ urn: 'urn:ok:error:invalid-request',
+ title: `Open Knowledge only writes skills into an agent folder that already exists (${skillHomeCandidateFolders(scope).join(', ')}) and never creates one for you. Create the folder your agent uses, then import again.`,
+ detail: 'NO_USABLE_SKILL_HOME',
+ };
+ }
const importRoot = resolve(importBase, importHomeRel);
const dupName = findByContentHash(lock, acquired.contentHash);
if (dupName && deps.resolveSkillDirForRead(scope, dupName) !== null) {
diff --git a/packages/server/src/skill-install.test.ts b/packages/server/src/skill-install.test.ts
index 990b19bc4..d58985028 100644
--- a/packages/server/src/skill-install.test.ts
+++ b/packages/server/src/skill-install.test.ts
@@ -201,8 +201,8 @@ describe('installUserSkill — scope discipline', () => {
await installUserSkill({ home });
- // `.claude` (installed) + `.agents` (central store) + `.ok` (state) only.
- expect(homeEntries(home)).toEqual(['.agents', '.claude', '.ok']);
+ expect(homeEntries(home)).toEqual(['.claude', '.ok']);
+ expect(existsSync(centralSkillDirFor(home))).toBe(false);
for (const hostDir of ALL_HOST_DIRS.filter((d) => d !== '.claude')) {
expect(existsSync(join(home, hostDir))).toBe(false);
}
@@ -218,7 +218,7 @@ describe('installUserSkill — scope discipline', () => {
expect(result).toBe('installed');
expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);
expect(existsSync(join(hostSkillDirFor(home, '.cursor'), 'SKILL.md'))).toBe(true);
- expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(false);
for (const hostDir of ALL_HOST_DIRS.filter((d) => d !== '.claude' && d !== '.cursor')) {
expect(existsSync(hostSkillDirFor(home, hostDir))).toBe(false);
}
@@ -291,10 +291,31 @@ describe('installUserSkill — scope discipline', () => {
const home = freshHome();
installHost(home, '.claude');
+ expect(await installUserSkill({ home })).toBe('installed');
+ expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(false);
+ });
+
+ test('an existing .agents root receives the shared copy', async () => {
+ const home = freshHome();
+ installHost(home, '.claude');
+ installHost(home, '.agents');
+
expect(await installUserSkill({ home })).toBe('installed');
expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(true);
});
+ test('Pi uses its existing nested user skill root without creating .agents', async () => {
+ const home = freshHome();
+ installHost(home, '.pi');
+
+ expect(await installUserSkill({ home })).toBe('installed');
+ expect(
+ existsSync(join(home, '.pi', 'agent', 'skills', 'open-knowledge-discovery', 'SKILL.md')),
+ ).toBe(true);
+ expect(existsSync(join(home, '.agents'))).toBe(false);
+ });
+
test('detectUserSkillHosts reports only the hosts present on disk', () => {
const home = freshHome();
expect(detectUserSkillHosts(home)).toEqual([]);
@@ -405,6 +426,15 @@ describe('installUserSkill — idempotency (skip-current)', () => {
expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);
});
+ test('a concrete-host-only install is current on the next run', async () => {
+ const home = freshHome();
+ installHost(home, '.claude');
+
+ expect(await installUserSkill({ home })).toBe('installed');
+ expect(existsSync(centralSkillDirFor(home))).toBe(false);
+ expect(await installUserSkill({ home })).toBe('skip-current');
+ });
+
test('sidecar without trailing newline still matches (tolerant parse)', async () => {
const home = freshHome();
installHost(home, '.claude');
@@ -414,7 +444,7 @@ describe('installUserSkill — idempotency (skip-current)', () => {
expect(await installUserSkill({ home })).toBe('skip-current');
});
- test('sidecar matches but central skill dir is missing → reinstall fires', async () => {
+ test('sidecar matches but the existing host skill is missing → reinstall fires', async () => {
const home = freshHome();
installHost(home, '.claude');
writeSidecar(home, currentVersion);
@@ -422,10 +452,11 @@ describe('installUserSkill — idempotency (skip-current)', () => {
const result = await installUserSkill({ home });
expect(result).toBe('installed');
- expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);
+ expect(existsSync(centralSkillDirFor(home))).toBe(false);
});
- test('the gate runs before detection — no host + matching sidecar still skips', async () => {
+ test('an existing central host + matching sidecar still skips', async () => {
const home = freshHome();
writeSidecar(home, currentVersion);
writeCentralSkill(home);
diff --git a/packages/server/src/skill-install.ts b/packages/server/src/skill-install.ts
index e629483a4..91a70e4eb 100644
--- a/packages/server/src/skill-install.ts
+++ b/packages/server/src/skill-install.ts
@@ -5,8 +5,8 @@ import { homedir, platform as osPlatform } from 'node:os';
import { dirname, isAbsolute, join, resolve as resolvePath } from 'node:path';
import {
type EditorId,
- HOSTS_WITH_USER_SKILL_DIR,
OPENKNOWLEDGE_SKILLS_REPO,
+ USER_SKILL_HOSTS,
} from '@inkeep/open-knowledge-core';
import {
type BuildSkillZipResult,
@@ -54,8 +54,9 @@ export interface InstallUserSkillOptions {
/**
* Override `$HOME`. The per-target install-state lives in
* `${home}/.ok/skill-state.yml` under target key `cli-hosts`; the skill
- * copies land under `${home}/.agents/skills/` and `${home}/.<host>/skills/`.
- * Tests pass a tmpdir here.
+ * copies land under the agent-host roots that already exist, including
+ * `${home}/.agents/skills/` when `.agents` is present. Tests pass a tmpdir
+ * here.
*/
home?: string;
/** Optional logger. Falls back to `console.warn` / `console.info`. */
@@ -98,10 +99,8 @@ export type InstallUserSkillResult = 'installed' | 'skip-current' | 'failed' | '
const LEGACY_USER_SKILL_NAME = 'open-knowledge';
/**
- * Vendor-neutral central store. Written only when at least one host is
- * detected — it is a convergence point FOR installed hosts (Codex, OpenCode,
- * Cursor read it natively), not a destination in its own right, so a machine
- * with no agent host gets nothing at all.
+ * Vendor-neutral central store. `.agents` follows the same consent boundary as
+ * every other host root: it is written only when that root already exists.
*/
const CENTRAL_HOST_DIR = '.agents';
@@ -113,6 +112,8 @@ function centralSkillDir(home: string, bundleName: string): string {
export interface DetectedSkillHost {
/** Home-relative dotdir whose presence means the host is installed. */
readonly hostDir: string;
+ /** Home-relative directory that contains this host's skill bundles. */
+ readonly skillsRoot: string;
readonly editorId: EditorId;
}
@@ -124,20 +125,29 @@ export interface DetectedSkillHost {
* both clutter and a scope-of-consent violation (issue #820, where a single
* `ok init` created 51 tool-config dirs in a real `$HOME`). Every user-global
* write site MUST filter through this. Host set comes from core's
- * `HOSTS_WITH_USER_SKILL_DIR`, derived from `EDITOR_PROJECT_SKILL_ROOT`, so it
- * can't drift from the editors OK actually supports.
+ * `USER_SKILL_HOSTS`, derived from `EDITOR_USER_SKILL_ROOT`, so it preserves
+ * nested user layouts such as Pi's `.pi/agent/skills`.
*/
export function detectUserSkillHosts(home: string): DetectedSkillHost[] {
- return HOSTS_WITH_USER_SKILL_DIR.filter((host) => existsSync(join(home, host.hostDir)));
+ return USER_SKILL_HOSTS.filter((host) => existsSync(join(home, host.hostDir)));
}
-async function centralSkillExists(home: string, bundleName: string): Promise<boolean> {
- try {
- const info = await stat(centralSkillDir(home, bundleName));
- return info.isDirectory();
- } catch {
- return false;
+async function installedUserSkillExists(home: string, bundleName: string): Promise<boolean> {
+ const candidates = detectUserSkillHosts(home).map((host) =>
+ join(home, host.skillsRoot, bundleName),
+ );
+ if (existsSync(join(home, CENTRAL_HOST_DIR))) {
+ candidates.push(centralSkillDir(home, bundleName));
+ }
+
+ for (const candidate of candidates) {
+ try {
+ if ((await stat(candidate)).isDirectory()) return true;
+ } catch {
+ // A missing or unreadable destination cannot satisfy the disk-presence gate.
+ }
}
+ return false;
}
/**
@@ -152,9 +162,9 @@ function removeLegacyUserSkillDirs(
hosts: readonly DetectedSkillHost[],
logger: SkillInstallLogger,
): void {
- const legacyHostDirs = [...hosts.map((h) => h.hostDir), CENTRAL_HOST_DIR];
- for (const hostDir of legacyHostDirs) {
- const legacyDir = join(home, hostDir, 'skills', LEGACY_USER_SKILL_NAME);
+ const legacySkillRoots = [...hosts.map((host) => host.skillsRoot), `${CENTRAL_HOST_DIR}/skills`];
+ for (const skillsRoot of legacySkillRoots) {
+ const legacyDir = join(home, skillsRoot, LEGACY_USER_SKILL_NAME);
if (!existsSync(legacyDir)) continue;
try {
tracedRmSync(legacyDir, { recursive: true, force: true });
@@ -189,22 +199,23 @@ interface SkillWriteEntry {
}
/**
- * Copy one bundle into the central store plus every detected host dir.
- * Callers pass an already-filtered `hosts` — this never probes for, or creates,
- * a dir belonging to an absent tool.
+ * Copy one bundle into every usable destination. Callers pass an
+ * already-filtered host set and whether the ordinary `.agents` host exists, so
+ * this never turns its own writes into future host-detection evidence.
*/
function writeBundleToHosts(
home: string,
bundleName: string,
sourceDir: string,
hosts: readonly DetectedSkillHost[],
+ includeCentral: boolean,
): SkillWriteEntry[] {
const entries: SkillWriteEntry[] = [];
const centralDest = centralSkillDir(home, bundleName);
const destinations = [
- centralDest,
+ ...(includeCentral ? [centralDest] : []),
...hosts
- .map((host) => join(home, host.hostDir, 'skills', bundleName))
+ .map((host) => join(home, host.skillsRoot, bundleName))
// Defensive: a host dest that collapses onto the central store would be a
// redundant double-write of the same bytes. No host root is `.agents`
// today, but the guard keeps the central write authoritative if that
@@ -242,19 +253,20 @@ function writeBundleToHosts(
* also cost a floating-range `npx -y` fetch-and-execute at init time and
* third-party telemetry OK never opted out of.
*
- * Destinations: the central `${home}/.agents/skills/<name>/` store plus
- * `${home}/.<host>/skills/<name>/` for each detected host — and NOTHING when no
- * host is detected (`'no-hosts'`), so a machine with no agent tooling gets no
- * dirs at all. See `detectUserSkillHosts` for why that gate is load-bearing.
+ * Destinations: `${home}/.<host>/skills/<name>/` for each detected host,
+ * including the central `${home}/.agents/skills/<name>/` store only when its
+ * root already exists — and NOTHING when no host is detected (`'no-hosts'`),
+ * so a machine with no agent tooling gets no dirs at all. See
+ * `detectUserSkillHosts` for why that gate is load-bearing.
*
* Idempotency: the `cli-hosts` entry in `${home}/.ok/skill-state.yml` gates
* re-install. Nothing is written (and `'skip-current'` is returned) only when
* BOTH the recorded version matches the current
- * `@inkeep/open-knowledge-server` package version AND the central skill
- * directory at `${home}/.agents/skills/open-knowledge-discovery` is still on
- * disk. The disk-presence check exists because a manual `rm` of the skill
- * leaves the state file untouched, which would otherwise wedge the next
- * `ok init` into a no-op despite the skill being gone.
+ * `@inkeep/open-knowledge-server` package version AND the skill directory is
+ * still present under at least one currently installed host root. The
+ * disk-presence check exists because a manual `rm` of the skill leaves the
+ * state file untouched, which would otherwise wedge the next `ok init` into a
+ * no-op despite the skill being gone.
*
* Always resolves (never throws). Returns `'failed'` when no usable install
* could be RECORDED — every destination write errored, a pre-write dependency
@@ -376,7 +388,7 @@ export async function installUserSkill(
return null;
});
if (!opts.force && existingVersion !== null && existingVersion === currentVersion) {
- if (await centralSkillExists(home, bundleName)) {
+ if (await installedUserSkillExists(home, bundleName)) {
logger.info?.(
{ event: 'skill-install.skip-current', version: currentVersion },
'OpenKnowledge skill already installed at current version; skipping.',
@@ -388,7 +400,6 @@ export async function installUserSkill(
{
event: 'skill-install.reinstall-missing',
version: currentVersion,
- path: centralSkillDir(home, bundleName),
},
'Sidecar matches current version but skill files are missing; reinstalling.',
);
@@ -411,10 +422,12 @@ export async function installUserSkill(
await report('failed', currentVersion, 'bundled-asset-missing');
return 'failed';
}
- // Detect BEFORE writing anything. No detected host ⇒ no destinations ⇒ we
- // write nothing at all, not even the central store.
+ // Detect BEFORE writing anything. `.agents` is an ordinary host: it receives
+ // a copy only when its root already exists, and does not authorize creating
+ // itself merely because another editor is installed.
const hosts = detectUserSkillHosts(home);
- if (hosts.length === 0) {
+ const includeCentral = existsSync(join(home, CENTRAL_HOST_DIR));
+ if (hosts.length === 0 && !includeCentral) {
logger.info?.(
{ event: 'skill-install.no-hosts', version: currentVersion },
'No supported agent host detected; skipping user-global skill install.',
@@ -427,7 +440,7 @@ export async function installUserSkill(
// fresh machine). Fail-soft — the writes below are what the result gates on.
removeLegacyUserSkillDirs(home, hosts, logger);
- const entries = writeBundleToHosts(home, bundleName, bundleDir, hosts);
+ const entries = writeBundleToHosts(home, bundleName, bundleDir, hosts, includeCentral);
const written = entries.filter((e) => e.status === 'written');
const failed = entries.filter((e) => e.status === 'failed');
diff --git a/packages/server/src/skill-migrate.test.ts b/packages/server/src/skill-migrate.test.ts
index 406d93716..f46c3be1e 100644
--- a/packages/server/src/skill-migrate.test.ts
+++ b/packages/server/src/skill-migrate.test.ts
@@ -74,15 +74,25 @@ describe('migrateStoreSkillsInPlace', () => {
expect(readInstalledSkills(root).skills.foo).toBeUndefined();
});
- test('an unprojected (draft) skill lands in a concrete editor dir, never inventing .agents', async () => {
+ test('an unprojected skill with no usable host stays in the legacy store', async () => {
makeStore('draft', '# D');
const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
- // No editor roots exist and no `.agents` adoption — the fallback is the
- // top-precedence concrete harness dir, NOT an OK-invented hub.
- expect(r.migrated).toContainEqual({ name: 'draft', to: '.claude/skills/draft' });
- expect(existsSync(join(root, '.claude/skills/draft/SKILL.md'))).toBe(true);
+ expect(r.migrated).toEqual([]);
+ expect(r.skipped).toContainEqual(expect.objectContaining({ name: 'draft' }));
+ expect(existsSync(join(root, '.claude'))).toBe(false);
expect(existsSync(join(root, '.agents'))).toBe(false);
- expect(existsSync(join(skillsRoot, 'draft'))).toBe(false);
+ expect(existsSync(join(skillsRoot, 'draft', 'SKILL.md'))).toBe(true);
+ });
+
+ test('an existing .agents skills root is an ordinary usable migration host', async () => {
+ makeStore('adopted', '# A');
+ mkdirSync(join(root, '.agents', 'skills'), { recursive: true });
+
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+
+ expect(r.migrated).toContainEqual({ name: 'adopted', to: '.agents/skills/adopted' });
+ expect(existsSync(join(root, '.agents', 'skills', 'adopted', 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(root, '.claude'))).toBe(false);
});
test('a same-hash real copy at a host becomes the canonical; store dir removed', async () => {
@@ -98,7 +108,7 @@ describe('migrateStoreSkillsInPlace', () => {
expect(readFileSync(join(hostDir, 'SKILL.md'), 'utf-8')).toContain('# Same');
});
- test('NEVER clobbers: a differing real dir at the only target skips the skill', async () => {
+ test('a differing real dir at the only existing host skips without fabricating a fallback', async () => {
makeStore('clash', '# Store version');
// The hub slot is occupied by a genuinely different skill; no projections.
const hub = join(root, '.agents/skills/clash');
@@ -106,15 +116,57 @@ describe('migrateStoreSkillsInPlace', () => {
writeFileSync(join(hub, 'SKILL.md'), '---\nname: clash\ndescription: other.\n---\n# DIFFERENT');
const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
- // The occupied hub slot is never clobbered; the store version lands at a
- // FREE concrete root instead (the fork then surfaces as a conflict).
- expect(r.migrated).toContainEqual({ name: 'clash', to: '.claude/skills/clash' });
- expect(readFileSync(join(root, '.claude/skills/clash/SKILL.md'), 'utf-8')).toContain(
+ expect(r.migrated).toEqual([]);
+ // Pin WHY it skipped: the hub root exists so it is the authorized target,
+ // and its slot is occupied by a different skill. A `no-usable-target` here
+ // would mean the hub was never considered, which is a different bug.
+ expect(r.skipped).toContainEqual({
+ name: 'clash',
+ reason: expect.stringContaining('target-occupied:.agents/skills'),
+ });
+ expect(existsSync(join(root, '.claude'))).toBe(false);
+ expect(readFileSync(join(skillsRoot, 'clash', 'SKILL.md'), 'utf-8')).toContain(
'# Store version',
);
expect(readFileSync(join(hub, 'SKILL.md'), 'utf-8')).toContain('# DIFFERENT');
});
+ test('a free lower-precedence host does NOT rescue an occupied higher one', async () => {
+ // DELIBERATE INVERSION. Target selection now takes the highest-precedence
+ // host whose ROOT exists, regardless of whether that host's skill slot is
+ // free; it used to walk past an occupied slot to the next host that had a
+ // free one. So `.claude` occupied while `.cursor` exists and is free is a
+ // reported conflict, not a migration into `.cursor`.
+ //
+ // Fail closed on purpose: scattering the skill to whichever host happened
+ // to be free lands it somewhere the user never chose and never looks, and
+ // it silently diverges from the canonical the rest of the system resolves.
+ // Reporting `target-occupied` leaves the store bundle intact and the
+ // conflict visible in the boot log for the user to resolve.
+ makeStore('crowded', '# Store version');
+ const claude = join(root, '.claude/skills/crowded');
+ mkdirSync(claude, { recursive: true });
+ writeFileSync(
+ join(claude, 'SKILL.md'),
+ '---\nname: crowded\ndescription: theirs.\n---\n# DIFFERENT',
+ );
+ // Exists, free, lower precedence — and must NOT be picked.
+ mkdirSync(join(root, '.cursor/skills'), { recursive: true });
+
+ const r = await migrateStoreSkillsInPlace({ projectDir: root, skillsRoot });
+
+ expect(r.migrated).toEqual([]);
+ expect(r.skipped).toContainEqual({
+ name: 'crowded',
+ reason: 'target-occupied:.claude/skills (different)',
+ });
+ expect(existsSync(join(root, '.cursor/skills/crowded'))).toBe(false);
+ expect(readFileSync(join(skillsRoot, 'crowded', 'SKILL.md'), 'utf-8')).toContain(
+ '# Store version',
+ );
+ expect(readFileSync(join(claude, 'SKILL.md'), 'utf-8')).toContain('# DIFFERENT');
+ });
+
test('a foreign symlink at a host is never touched (D7)', async () => {
makeStore('linked', '# L');
// Foreign symlink in .claude pointing somewhere else entirely.
@@ -155,6 +207,23 @@ describe('migrateStoreSkillsInPlace', () => {
expect(readFileSync(join(piDir, 'SKILL.md'), 'utf-8')).toContain('# G');
});
+ test('GLOBAL roots: residue with no existing user host stays put', async () => {
+ const { USER_HOST_ROOTS_BY_PRECEDENCE } = await import('./skill-migrate.ts');
+ makeStore('global-residue', '# G');
+
+ const r = await migrateStoreSkillsInPlace({
+ projectDir: root,
+ skillsRoot,
+ hostRoots: USER_HOST_ROOTS_BY_PRECEDENCE,
+ });
+
+ expect(r.migrated).toEqual([]);
+ expect(r.skipped).toContainEqual(expect.objectContaining({ name: 'global-residue' }));
+ expect(existsSync(join(root, '.claude'))).toBe(false);
+ expect(existsSync(join(root, '.agents'))).toBe(false);
+ expect(existsSync(join(skillsRoot, 'global-residue', 'SKILL.md'))).toBe(true);
+ });
+
test('a placement of an in-place skill (inPlaceNames) is never migrated', async () => {
makeStore('placed', '# P');
const r = await migrateStoreSkillsInPlace({
diff --git a/packages/server/src/skill-migrate.ts b/packages/server/src/skill-migrate.ts
index 3614196a0..32f55a7ef 100644
--- a/packages/server/src/skill-migrate.ts
+++ b/packages/server/src/skill-migrate.ts
@@ -27,6 +27,7 @@ import {
EDITOR_USER_SKILL_ROOT,
type EditorId,
SKILL_NAME_REGEX,
+ skillRootActivationPath,
} from '@inkeep/open-knowledge-core';
import {
parseSkillDir,
@@ -67,6 +68,10 @@ const HOST_ROOTS_BY_PRECEDENCE = rootsByPrecedence(EDITOR_PROJECT_SKILL_ROOT);
/** The GLOBAL tier's roots: user-home editor dirs (`~/.claude/skills`, …). */
export const USER_HOST_ROOTS_BY_PRECEDENCE = rootsByPrecedence(EDITOR_USER_SKILL_ROOT);
+function hostRootExists(base: string, skillsRoot: string): boolean {
+ return existsSync(resolve(base, skillRootActivationPath(skillsRoot)));
+}
+
/** Move a directory; copy+remove fallback ONLY on a cross-device rename. */
function moveDir(from: string, to: string): void {
tracedMkdirSync(dirname(to), { recursive: true });
@@ -244,15 +249,13 @@ export async function migrateStoreSkillsInPlace(opts: {
// Target = highest-precedence host already carrying the skill (store link
// or same-hash copy); an unprojected skill falls back to the first root that
- // ALREADY EXISTS (never inventing `.agents` — hub adoption is the team's
- // call), else `.claude/skills`.
+ // ALREADY EXISTS. No existing host means the legacy bundle stays put.
const target =
states.find((s) => s.state.kind === 'store-link' || s.state.kind === 'same-copy') ??
- // Reaching here means no root carries the skill, so `absent` is the only
- // writable kind left. Tested positively, not as "not occupied", so a
- // state added later fails closed instead of inheriting a write.
- states.find((s) => s.state.kind === 'absent' && existsSync(resolve(projectDir, s.root))) ??
- states.find((s) => s.host === 'claude');
+ // An existing host root is authorized even when its skill slot is
+ // occupied; the branch below reports that conflict without inventing a
+ // fallback host.
+ states.find((s) => hostRootExists(projectDir, s.root));
if (!target) {
result.skipped.push({ name, reason: 'no-usable-target' });
continue;