Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): bound project skills plugin enumeration (#4567)
Nick Gomez18b04fee3177
diff --git a/.changeset/bound-skills-plugin-enumeration.md b/.changeset/bound-skills-plugin-enumeration.mdnew file mode 100644index 000000000..4b1711523--- /dev/null+++ b/.changeset/bound-skills-plugin-enumeration.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Opening a project no longer stalls while the skills list scans plugin installs registered to other projects, and directory marketplace sources that resolve outside their marketplace root no longer contribute skills.diff --git a/packages/core/src/skills-catalog/adapters/claude-plugins.test.ts b/packages/core/src/skills-catalog/adapters/claude-plugins.test.tsindex 5f0c6e1df..51782131a 100644--- a/packages/core/src/skills-catalog/adapters/claude-plugins.test.ts+++ b/packages/core/src/skills-catalog/adapters/claude-plugins.test.ts@@ -1,7 +1,16 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import fs, {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ renameSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { syncBuiltinESMExports } from 'node:module';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { enumerateClaudePlugins } from './claude-plugins.ts';let root: string;@@ -10,6 +19,7 @@ beforeEach(() => {root = mkdtempSync(join(tmpdir(), 'ok-claude-plugins-'));});afterEach(() => {+ vi.restoreAllMocks();rmSync(root, { recursive: true, force: true });});@@ -83,10 +93,34 @@ describe('enumerateClaudePlugins — repository URL stamp', () => {});});+test('project plugin selection matches Windows drive-letter and separator variants', () => {+ seedPlugin('toolkit@market');+ const installedPath = join(root, 'installed_plugins.json');+ const installed = JSON.parse(readFileSync(installedPath, 'utf-8')) as {+ plugins: Record<string, Array<Record<string, string>>>;+ };+ const entry = installed.plugins['toolkit@market']?.[0];+ if (entry === undefined) throw new Error('fixture entry was not created');+ entry.scope = 'project';+ entry.projectPath = 'C:\\Users\\me\\project\\';+ writeFileSync(installedPath, JSON.stringify(installed));++ expect(enumerateClaudePlugins(root, 'claude', 'c:/Users/me/project')).toHaveLength(1);+ expect(enumerateClaudePlugins(root, 'claude', 'c:/Users/me/Project')).toHaveLength(0);+});+describe('directory-sourced marketplaces', () => {- function seedDirectoryMarketplace(): string {+ function seedDirectoryMarketplace({+ source = './tools/plugins/oktools',+ metadataPluginRoot,+ pluginRelativePath = 'tools/plugins/oktools',+ }: {+ source?: string;+ metadataPluginRoot?: string;+ pluginRelativePath?: string;+ } = {}): string {const repo = join(root, 'repo');- const pluginRoot = join(repo, 'tools', 'plugins', 'oktools');+ const pluginRoot = join(repo, pluginRelativePath);const skill = join(pluginRoot, 'skills', 'linux-vm');mkdirSync(skill, { recursive: true });writeFileSync(join(skill, 'SKILL.md'), '---\nname: linux-vm\ndescription: VM\n---\n');@@ -95,7 +129,10 @@ describe('directory-sourced marketplaces', () => {join(repo, '.claude-plugin', 'marketplace.json'),JSON.stringify({name: 'local-market',- plugins: [{ name: 'oktools', source: './tools/plugins/oktools', version: '0.1.0' }],+ ...(metadataPluginRoot !== undefined+ ? { metadata: { pluginRoot: metadataPluginRoot } }+ : {}),+ plugins: [{ name: 'oktools', source, version: '0.1.0' }],}),);writeFileSync(@@ -125,6 +162,7 @@ describe('directory-sourced marketplaces', () => {test('an install whose cache path was never written resolves through the marketplace dir', () => {const pluginRoot = seedDirectoryMarketplace();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const bundles = enumerateClaudePlugins(root, 'claude');expect(bundles).toHaveLength(1);@@ -136,13 +174,285 @@ describe('directory-sourced marketplaces', () => {expect(skill?.provenance.plugin).toBe('oktools');expect(skill?.provenance.marketplace).toBe('local-market');expect(skill?.provenance.scope).toBe('project');+ expect(warn).not.toHaveBeenCalled();+ });++ test('an in-root source resolves when the marketplace directory is a symlink', () => {+ seedDirectoryMarketplace();+ const marketplaceDir = join(root, 'repo');+ const canonicalMarketplaceDir = join(root, 'canonical-repo');+ renameSync(marketplaceDir, canonicalMarketplaceDir);+ symlinkSync(+ canonicalMarketplaceDir,+ marketplaceDir,+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(1);+ });++ test('scoped enumeration does not read a foreign directory marketplace manifest', () => {+ seedDirectoryMarketplace();+ const manifestPath = join(root, 'repo', '.claude-plugin', 'marketplace.json');+ const descriptor = Object.getOwnPropertyDescriptor(fs, 'readFileSync');+ if (descriptor === undefined) throw new Error('readFileSync descriptor is unavailable');+ const original = fs.readFileSync.bind(fs);+ const reads: string[] = [];+ Object.defineProperty(fs, 'readFileSync', {+ ...descriptor,+ value: (...args: Parameters<typeof fs.readFileSync>) => {+ reads.push(String(args[0]));+ return original(...args);+ },+ });+ syncBuiltinESMExports();+ try {+ expect(enumerateClaudePlugins(root, 'claude', join(root, 'another-project'))).toHaveLength(0);+ expect(reads).not.toContain(manifestPath);+ } finally {+ Object.defineProperty(fs, 'readFileSync', descriptor);+ syncBuiltinESMExports();+ }+ });++ test('metadata.pluginRoot resolves a bare source beneath the declared base', () => {+ const pluginRoot = seedDirectoryMarketplace({+ source: 'oktools',+ metadataPluginRoot: './tools/plugins',+ });+ const bundles = enumerateClaudePlugins(root, 'claude');++ expect(bundles).toHaveLength(1);+ expect((bundles[0]?.skills[0] as { home?: string } | undefined)?.home).toBe(+ join(pluginRoot, 'skills', 'linux-vm'),+ );+ });++ test('an absolute metadata.pluginRoot inside the marketplace is rejected', () => {+ const pluginRoot = join(root, 'repo', 'tools', 'plugins');+ seedDirectoryMarketplace({ source: 'oktools', metadataPluginRoot: pluginRoot });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: 'metadata.pluginRoot must be a relative path inside the marketplace',+ }),+ );+ });++ test('a bare source without metadata.pluginRoot is rejected', () => {+ seedDirectoryMarketplace({ source: 'oktools', pluginRelativePath: 'oktools' });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: 'metadata.pluginRoot is required for a bare source',+ }),+ );+ });++ test.each([+ {+ separator: 'slash',+ source: 'nested/oktools',+ pluginRelativePath: 'tools/plugins/nested/oktools',+ },+ {+ separator: 'backslash',+ source: 'nested\\oktools',+ pluginRelativePath: 'tools/plugins/nested\\oktools',+ },+ ])(+ 'rejects a $separator-bearing source that omits the explicit relative prefix',+ ({ source, pluginRelativePath }) => {+ seedDirectoryMarketplace({+ source,+ metadataPluginRoot: './tools/plugins',+ pluginRelativePath,+ });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: 'unsupported source form',+ }),+ );+ },+ );++ test('does not report invalid sources for unrelated marketplace plugins', () => {+ seedDirectoryMarketplace();+ const manifestPath = join(root, 'repo', '.claude-plugin', 'marketplace.json');+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as {+ plugins: Array<Record<string, unknown>>;+ };+ manifest.plugins.push({ name: 'unrelated', source: 'nested/unrelated' });+ writeFileSync(manifestPath, JSON.stringify(manifest));+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(1);+ expect(warn).not.toHaveBeenCalled();+ });++ test.each([+ { kind: 'missing', source: undefined },+ { kind: 'non-string', source: 42 },+ ])('reports a $kind selected source', ({ source }) => {+ seedDirectoryMarketplace();+ const manifestPath = join(root, 'repo', '.claude-plugin', 'marketplace.json');+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as {+ plugins: Array<Record<string, unknown>>;+ };+ const selected = manifest.plugins[0];+ if (selected === undefined) throw new Error('fixture plugin was not created');+ if (source === undefined) selected.name = 'another-plugin';+ else selected.source = source;+ writeFileSync(manifestPath, JSON.stringify(manifest));+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: 'missing or invalid source',+ }),+ );+ });++ test('an explicit relative source ignores a valid relative pluginRoot', () => {+ const pluginRoot = seedDirectoryMarketplace({ metadataPluginRoot: './other-plugins' });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const bundles = enumerateClaudePlugins(root, 'claude');++ expect(bundles).toHaveLength(1);+ expect((bundles[0]?.skills[0] as { home?: string } | undefined)?.home).toBe(+ join(pluginRoot, 'skills', 'linux-vm'),+ );+ expect(warn).not.toHaveBeenCalled();+ });++ test('an explicit relative source ignores an invalid absolute pluginRoot', () => {+ const pluginRoot = seedDirectoryMarketplace({ metadataPluginRoot: join(root, 'outside') });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const bundles = enumerateClaudePlugins(root, 'claude');++ expect(bundles).toHaveLength(1);+ expect((bundles[0]?.skills[0] as { home?: string } | undefined)?.home).toBe(+ join(pluginRoot, 'skills', 'linux-vm'),+ );+ expect(warn).not.toHaveBeenCalled();+ });++ test('a parent-relative pluginRoot is rejected by its field contract', () => {+ seedDirectoryMarketplace({+ source: 'oktools',+ metadataPluginRoot: '../outside',+ pluginRelativePath: '../outside/oktools',+ });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: 'metadata.pluginRoot must be a relative path inside the marketplace',+ }),+ );+ });++ test('an unresolvable candidate reports a bounded filesystem cause', () => {+ seedDirectoryMarketplace({+ source: './missing/oktools',+ pluginRelativePath: 'present/oktools',+ });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: expect.stringContaining('ENOENT'),+ }),+ );+ const warningContext = warn.mock.calls[0]?.[1] as { cause?: unknown } | undefined;+ if (typeof warningContext?.cause !== 'string') throw new Error('warning cause was not emitted');+ expect(warningContext.cause.length).toBeLessThanOrEqual(500);+ });++ test('an unsupported parent-relative source contributes nothing', () => {+ seedDirectoryMarketplace({+ source: '../outside/oktools',+ pluginRelativePath: '../outside/oktools',+ });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: 'unsupported source form',+ }),+ );+ });++ test('a source symlink that escapes the marketplace is rejected', () => {+ seedDirectoryMarketplace({+ source: './plugins/oktools',+ pluginRelativePath: '../outside/oktools',+ });+ mkdirSync(join(root, 'repo', 'plugins'), { recursive: true });+ symlinkSync(+ join(root, 'outside', 'oktools'),+ join(root, 'repo', 'plugins', 'oktools'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] rejected directory marketplace plugin source',+ expect.objectContaining({+ marketplaceDir: join(root, 'repo'),+ plugin: 'oktools',+ cause: 'source resolves outside marketplace',+ }),+ );});test('a directory marketplace whose manifest is unreadable contributes nothing', () => {- const pluginRoot = seedDirectoryMarketplace();- writeFileSync(join(root, 'repo', '.claude-plugin', 'marketplace.json'), '{not json');+ seedDirectoryMarketplace();+ const marketplaceDir = join(root, 'repo');+ writeFileSync(join(marketplaceDir, '.claude-plugin', 'marketplace.json'), '{not json');+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+expect(enumerateClaudePlugins(root, 'claude')).toHaveLength(0);- void pluginRoot;+ expect(warn).toHaveBeenCalledWith(+ '[skills-catalog] failed to read directory marketplace manifest',+ expect.objectContaining({+ marketplaceDir,+ cause: expect.any(String),+ }),+ );});test('a relative registry path is refused rather than resolved against cwd', () => {diff --git a/packages/core/src/skills-catalog/adapters/claude-plugins.ts b/packages/core/src/skills-catalog/adapters/claude-plugins.tsindex ccb93e08c..13614d5fc 100644--- a/packages/core/src/skills-catalog/adapters/claude-plugins.ts+++ b/packages/core/src/skills-catalog/adapters/claude-plugins.ts@@ -1,6 +1,7 @@-import { existsSync, readFileSync } from 'node:fs';-import { isAbsolute, join, resolve } from 'node:path';+import { existsSync, readFileSync, realpathSync } from 'node:fs';+import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { SkillProvenance } from '../schema.ts';+import { isDetectedSkillInProject } from '../scope.ts';import {detectInert,type RawSkill,@@ -45,8 +46,8 @@ function activeEntries(return [...bySite.values()];}-function readDirectoryMarketplaces(pluginsDir: string): Map<string, Map<string, string>> {- const out = new Map<string, Map<string, string>>();+function readDirectoryMarketplaceLocations(pluginsDir: string): Map<string, string> {+ const out = new Map<string, string>();let registry: Record<string,{ source?: { source?: string; path?: string }; installLocation?: string }@@ -60,21 +61,143 @@ function readDirectoryMarketplaces(pluginsDir: string): Map<string, Map<string,if (entry?.source?.source !== 'directory') continue;const dir = entry.source.path ?? entry.installLocation;if (typeof dir !== 'string' || dir.length === 0 || !isAbsolute(dir)) continue;- try {- const manifest = JSON.parse(- readFileSync(join(dir, '.claude-plugin', 'marketplace.json'), 'utf-8'),- ) as { plugins?: { name?: string; source?: string }[] };- const roots = new Map<string, string>();- for (const p of manifest.plugins ?? []) {- if (typeof p?.name !== 'string' || typeof p?.source !== 'string') continue;- roots.set(p.name, resolve(dir, p.source));- }- if (roots.size > 0) out.set(name, roots);- } catch {}+ out.set(name, dir);}return out;}+interface DirectoryMarketplace {+ directory: string;+ canonicalDirectory: string;+ pluginRoot?: string;+ plugins: Array<{ name?: unknown; source?: unknown }>;+ resolvedRoots: Map<string, string | null>;+}++function readDirectoryMarketplace(dir: string): DirectoryMarketplace | null {+ let manifest: { metadata?: { pluginRoot?: unknown }; plugins?: unknown };+ try {+ const parsed = JSON.parse(+ readFileSync(join(dir, '.claude-plugin', 'marketplace.json'), 'utf-8'),+ );+ manifest = parsed && typeof parsed === 'object' ? parsed : {};+ } catch (err) {+ console.warn('[skills-catalog] failed to read directory marketplace manifest', {+ marketplaceDir: dir,+ cause: boundedCause(err),+ });+ return null;+ }+ const pluginRoot =+ typeof manifest.metadata?.pluginRoot === 'string' ? manifest.metadata.pluginRoot : undefined;+ let canonicalDirectory: string;+ try {+ canonicalDirectory = realpathSync(dir);+ } catch (err) {+ console.warn('[skills-catalog] failed to resolve directory marketplace', {+ marketplaceDir: dir,+ cause: boundedCause(err),+ });+ return null;+ }+ return {+ directory: dir,+ canonicalDirectory,+ ...(pluginRoot === undefined ? {} : { pluginRoot }),+ plugins: Array.isArray(manifest.plugins) ? manifest.plugins : [],+ resolvedRoots: new Map(),+ };+}++function resolveDirectoryMarketplaceRoot(+ marketplace: DirectoryMarketplace,+ plugin: string,+): string | null {+ if (marketplace.resolvedRoots.has(plugin)) {+ return marketplace.resolvedRoots.get(plugin) ?? null;+ }+ let selected: { name?: unknown; source?: unknown } | undefined;+ for (const candidate of marketplace.plugins) {+ if (candidate?.name === plugin) selected = candidate;+ }+ if (typeof selected?.source !== 'string') {+ return rejectDirectoryMarketplaceSource(marketplace, plugin, 'missing or invalid source');+ }+ const source = selected.source;+ const sourceIsExplicitRelative = source.startsWith('./') && !source.includes('\\');+ const sourceIsBare =+ source.length > 0 && source !== '.' && source !== '..' && !/[\\/]/.test(source);+ if (!sourceIsExplicitRelative && !sourceIsBare) {+ return rejectDirectoryMarketplaceSource(marketplace, plugin, 'unsupported source form');+ }+ let base = marketplace.directory;+ if (sourceIsBare) {+ const pluginRoot = marketplace.pluginRoot;+ if (pluginRoot === undefined) {+ return rejectDirectoryMarketplaceSource(+ marketplace,+ plugin,+ 'metadata.pluginRoot is required for a bare source',+ );+ }+ const resolvedPluginRoot = resolve(marketplace.directory, pluginRoot);+ const pluginRootFromMarketplace = relative(marketplace.directory, resolvedPluginRoot);+ if (+ isAbsolute(pluginRoot) ||+ pluginRootFromMarketplace === '..' ||+ pluginRootFromMarketplace.startsWith(`..${sep}`) ||+ isAbsolute(pluginRootFromMarketplace)+ ) {+ return rejectDirectoryMarketplaceSource(+ marketplace,+ plugin,+ 'metadata.pluginRoot must be a relative path inside the marketplace',+ );+ }+ base = resolvedPluginRoot;+ }+ const root = resolve(base, source);+ let canonicalRoot: string;+ try {+ canonicalRoot = realpathSync(root);+ } catch (err) {+ return rejectDirectoryMarketplaceSource(marketplace, plugin, boundedCause(err));+ }+ const fromMarketplace = relative(marketplace.canonicalDirectory, canonicalRoot);+ if (+ fromMarketplace === '..' ||+ fromMarketplace.startsWith(`..${sep}`) ||+ isAbsolute(fromMarketplace)+ ) {+ return rejectDirectoryMarketplaceSource(+ marketplace,+ plugin,+ 'source resolves outside marketplace',+ );+ }+ marketplace.resolvedRoots.set(plugin, root);+ return root;+}++function rejectDirectoryMarketplaceSource(+ marketplace: DirectoryMarketplace,+ plugin: string,+ cause: string,+): null {+ console.warn('[skills-catalog] rejected directory marketplace plugin source', {+ marketplaceDir: marketplace.directory,+ plugin,+ cause,+ });+ marketplace.resolvedRoots.set(plugin, null);+ return null;+}++function boundedCause(err: unknown): string {+ const cause = err instanceof Error ? err.message : String(err);+ return cause.slice(0, 500);+}+function readPluginJson(installPath: string): {description?: string;version?: string;@@ -106,7 +229,11 @@ function readMarketplaceRepos(pluginsDir: string): Map<string, string> {return out;}-export function enumerateClaudePlugins(pluginsDir: string, harness: string): SkillBundle[] {+export function enumerateClaudePlugins(+ pluginsDir: string,+ harness: string,+ projectDir?: string,+): SkillBundle[] {const manifestPath = join(pluginsDir, 'installed_plugins.json');if (!existsSync(manifestPath)) return [];let manifest: { plugins?: Record<string, PluginEntry[]> };@@ -122,17 +249,35 @@ export function enumerateClaudePlugins(pluginsDir: string, harness: string): Skiconst plugins = manifest?.plugins;if (!plugins || typeof plugins !== 'object') return [];const repoByMarketplace = readMarketplaceRepos(pluginsDir);- const dirMarketplaces = readDirectoryMarketplaces(pluginsDir);+ const dirMarketplaceLocations = readDirectoryMarketplaceLocations(pluginsDir);+ const dirMarketplaces = new Map<string, DirectoryMarketplace | null>();const bundles: SkillBundle[] = [];for (const [key, entries] of Object.entries(plugins)) {if (!Array.isArray(entries)) continue;const { plugin, marketplace } = splitPluginKey(key);+ const selectedEntries =+ projectDir === undefined+ ? entries+ : entries.filter((entry) =>+ isDetectedSkillInProject(+ { scope: entry.scope, projectPath: entry.projectPath },+ projectDir,+ ),+ );const resolveDirInstall = (_entry: PluginEntry): string | null => {- const root = marketplace ? (dirMarketplaces.get(marketplace)?.get(plugin) ?? null) : null;+ if (!marketplace) return null;+ const location = dirMarketplaceLocations.get(marketplace);+ if (location === undefined) return null;+ if (!dirMarketplaces.has(marketplace)) {+ dirMarketplaces.set(marketplace, readDirectoryMarketplace(location));+ }+ const directoryMarketplace = dirMarketplaces.get(marketplace);+ if (directoryMarketplace == null) return null;+ const root = resolveDirectoryMarketplaceRoot(directoryMarketplace, plugin);return root !== null && existsSync(root) ? root : null;};- for (const entry of activeEntries(entries, resolveDirInstall)) {+ for (const entry of activeEntries(selectedEntries, resolveDirInstall)) {const installPath = entry.installPath as string;const inert = detectInert(installPath);const meta = readPluginJson(installPath);diff --git a/packages/core/src/skills-catalog/enumerate.ts b/packages/core/src/skills-catalog/enumerate.tsindex 0e84a3cd5..4bfe5e64e 100644--- a/packages/core/src/skills-catalog/enumerate.ts+++ b/packages/core/src/skills-catalog/enumerate.ts@@ -125,7 +125,7 @@ export function enumerateInstalledSkills(opts: EnumerateOptions = {}): Installedtry {switch (h.kind) {case 'plugin-provider':- bundles.push(...enumeratePluginProvider(h.provider, h.dir, h.harness));+ bundles.push(...enumeratePluginProvider(h.provider, h.dir, h.harness, opts.projectDir));break;case 'skill-dir':bundles.push(...enumerateSkillDir(h.dir, h.harness));diff --git a/packages/core/src/skills-catalog/plugin-providers/registry.ts b/packages/core/src/skills-catalog/plugin-providers/registry.tsindex 81f0091a6..3d61f3a4b 100644--- a/packages/core/src/skills-catalog/plugin-providers/registry.ts+++ b/packages/core/src/skills-catalog/plugin-providers/registry.ts@@ -45,10 +45,11 @@ export function enumeratePluginProvider(provider: PluginProviderId,home: string,harness: string = provider,+ projectDir?: string,): SkillBundle[] {const adapter = providerById(provider);if (!adapter) throw new Error(`unknown plugin provider: ${provider}`);- return adapter.enumerate(home, harness).map((bundle) => ({+ return adapter.enumerate(home, harness, projectDir).map((bundle) => ({...bundle,skills: bundle.skills.map((skill) => ({...skill,diff --git a/packages/core/src/skills-catalog/plugin-providers/types.ts b/packages/core/src/skills-catalog/plugin-providers/types.tsindex 0ef0d976d..89aa57b98 100644--- a/packages/core/src/skills-catalog/plugin-providers/types.ts+++ b/packages/core/src/skills-catalog/plugin-providers/types.ts@@ -36,7 +36,7 @@ export interface PluginBundleInspection {export interface PluginProviderAdapter {readonly id: PluginProviderId;homes(home: string): readonly PluginProviderHome[];- enumerate(home: string, harness: string): SkillBundle[];+ enumerate(home: string, harness: string, projectDir?: string): SkillBundle[];inspectSource(source: string): Omit<PluginSourceInspection, 'provider' | 'repositoryUrl'> | null;repositoryUrl(source: string): string | null;resolveUpdateSource(source: string): string;diff --git a/packages/core/src/skills-catalog/scope.test.ts b/packages/core/src/skills-catalog/scope.test.tsindex 9e0e60097..0eb8712ac 100644--- a/packages/core/src/skills-catalog/scope.test.ts+++ b/packages/core/src/skills-catalog/scope.test.ts@@ -63,6 +63,22 @@ describe('isDetectedSkillInProject', () => {isDetectedSkillInProject(prov({ scope: 'project', projectPath: '/Users/me/other' }), MAIN),).toBe(false);});++ it('matches Windows drive-letter and separator variants without folding path segments', () => {+ const owner = 'C:\\Users\\me\\project\\';+ expect(+ isDetectedSkillInProject(+ prov({ scope: 'project', projectPath: owner }),+ 'c:/Users/me/project',+ ),+ ).toBe(true);+ expect(+ isDetectedSkillInProject(+ prov({ scope: 'project', projectPath: owner }),+ 'c:/Users/me/Project',+ ),+ ).toBe(false);+ });});describe('isSkillOutsideOpenProject', () => {diff --git a/packages/core/src/skills-catalog/scope.ts b/packages/core/src/skills-catalog/scope.tsindex 7176a8afc..628b015d7 100644--- a/packages/core/src/skills-catalog/scope.ts+++ b/packages/core/src/skills-catalog/scope.ts@@ -13,6 +13,17 @@ export function catalogRawScopeToOkScope(rawScope: string | undefined): SkillSco}function samePath(a: string, b: string): boolean {+ const isWindowsDrivePath = (path: string): boolean => /^[A-Za-z]:[\\/]/.test(path);+ const aIsWindowsDrivePath = isWindowsDrivePath(a);+ const bIsWindowsDrivePath = isWindowsDrivePath(b);+ if (aIsWindowsDrivePath || bIsWindowsDrivePath) {+ if (!aIsWindowsDrivePath || !bIsWindowsDrivePath) return false;+ const normalizeWindowsDrivePath = (path: string): string => {+ const normalized = path.replace(/[\\/]+/g, '/').replace(/\/+$/, '');+ return `${normalized.slice(0, 1).toLowerCase()}${normalized.slice(1)}`;+ };+ return normalizeWindowsDrivePath(a) === normalizeWindowsDrivePath(b);+ }const norm = (p: string) => p.replace(/\/+$/, '');return norm(a) === norm(b);}diff --git a/packages/server/src/api-skills-plugin-scope.test.ts b/packages/server/src/api-skills-plugin-scope.test.tsnew file mode 100644index 000000000..380f2777e--- /dev/null+++ b/packages/server/src/api-skills-plugin-scope.test.ts@@ -0,0 +1,710 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import type { IncomingMessage } from 'node:http';+import { syncBuiltinESMExports } from 'node:module';+import { tmpdir } from 'node:os';+import { join, relative, sep } from 'node:path';+import { Readable } from 'node:stream';+import { resolveProjectIdentity } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';+import type { BootedServer } from './boot.ts';+import { createSkillsRecoveryRoutes } from './http/skills-recovery-routes.ts';++interface Observation {+ advancePerReadMs: number;+ advancePathPrefix?: string;+ hashes: number;+ reads: string[];+}++interface SkillsResponse {+ skills: Array<{+ name: string;+ provenance?: { projectPath?: string; scope?: string };+ }>;+}++interface LinkedFixture {+ bundleRoot: string;+ contentDir: string;+ home: string;+ mainDir: string;+ siblingDir: string;+}++const FOREIGN_PROJECT_COUNT = 20;+const MAIN_VERSION = '3.0.0';+const OWN_VERSION = '2.0.0';+const SIBLING_VERSION = '4.0.0';+const USER_VERSION = '9.0.0';+const originalReadFileSync = fs.readFileSync.bind(fs);+const originalCreateHash = crypto.createHash.bind(crypto);+const readFileSyncDescriptor = Object.getOwnPropertyDescriptor(fs, 'readFileSync');+const createHashDescriptor = Object.getOwnPropertyDescriptor(crypto, 'createHash');+let observation: Observation | null = null;+let fakeNow: number | null = null;+let root: string;+let server: BootedServer;+let createApiExtension: typeof import('./api-extension.test-helper.ts').createApiExtension;+let createSkillsCatalogCache: typeof import('./skills-catalog-cache.ts').createSkillsCatalogCache;+let getLogger: typeof import('./logger.ts').getLogger;+let makeCaptureRes: typeof import('./composition-rig.test-helper.ts').makeCaptureRes;+let makeSyntheticReq: typeof import('./composition-rig.test-helper.ts').makeSyntheticReq;++function installObservers(): void {+ if (readFileSyncDescriptor === undefined || createHashDescriptor === undefined) {+ throw new Error('Node builtin descriptors are unavailable');+ }+ Object.defineProperty(fs, 'readFileSync', {+ ...readFileSyncDescriptor,+ value: (...args: Parameters<typeof fs.readFileSync>) => {+ const result = originalReadFileSync(...args);+ if (observation !== null) {+ const path = String(args[0]);+ observation.reads.push(path);+ if (+ fakeNow !== null &&+ (observation.advancePathPrefix === undefined ||+ path.startsWith(observation.advancePathPrefix))+ ) {+ fakeNow += observation.advancePerReadMs;+ }+ }+ return result;+ },+ });+ Object.defineProperty(crypto, 'createHash', {+ ...createHashDescriptor,+ value: (...args: Parameters<typeof crypto.createHash>) => {+ if (observation !== null) observation.hashes += 1;+ return originalCreateHash(...args);+ },+ });+ syncBuiltinESMExports();+}++function restoreObservers(): void {+ if (readFileSyncDescriptor !== undefined) {+ Object.defineProperty(fs, 'readFileSync', readFileSyncDescriptor);+ }+ if (createHashDescriptor !== undefined) {+ Object.defineProperty(crypto, 'createHash', createHashDescriptor);+ }+ syncBuiltinESMExports();+}++beforeAll(async () => {+ root = fs.mkdtempSync(join(tmpdir(), 'ok-skills-plugin-scope-'));+ installObservers();+ ({ createApiExtension } = await import('./api-extension.test-helper.ts'));+ ({ createSkillsCatalogCache } = await import('./skills-catalog-cache.ts'));+ ({ getLogger } = await import('./logger.ts'));+ const composition = await import('./composition-rig.test-helper.ts');+ ({ makeCaptureRes, makeSyntheticReq } = composition);+ const runtime = fs.mkdtempSync(join(root, 'runtime-'));+ server = await composition.bootCompositionRig(runtime);+ await server.ready;+}, 60_000);++afterEach(() => {+ observation = null;+ fakeNow = null;+ vi.restoreAllMocks();+});++afterAll(async () => {+ await server?.destroy();+ restoreObservers();+ fs.rmSync(root, { recursive: true, force: true });+});++function startObservation(advancePerReadMs = 0, advancePathPrefix?: string): void {+ observation = {+ advancePerReadMs,+ ...(advancePathPrefix !== undefined ? { advancePathPrefix } : {}),+ hashes: 0,+ reads: [],+ };+}++function finishObservation(): Observation {+ if (observation === null) throw new Error('observation was not started');+ const completed = observation;+ observation = null;+ return completed;+}++function writeSkill(installPath: string, version: string): void {+ const skillDir = join(installPath, 'skills', 'fixture-skill');+ fs.mkdirSync(join(skillDir, 'references'), { recursive: true });+ fs.mkdirSync(join(skillDir, 'scripts'), { recursive: true });+ fs.mkdirSync(join(skillDir, 'assets'), { recursive: true });+ fs.mkdirSync(join(installPath, '.claude-plugin'), { recursive: true });+ fs.writeFileSync(+ join(skillDir, 'SKILL.md'),+ `---\nname: fixture-skill\ndescription: Fixture ${version}\n---\n\nBody ${version}\n`,+ );+ fs.writeFileSync(join(skillDir, 'references', 'guide.md'), `guide ${version}\n`);+ fs.writeFileSync(join(skillDir, 'scripts', 'run.mjs'), `export const version = '${version}';\n`);+ fs.writeFileSync(join(skillDir, 'assets', 'payload.txt'), `payload ${version}\n`);+ fs.writeFileSync(+ join(installPath, '.claude-plugin', 'plugin.json'),+ JSON.stringify({ name: 'toolkit', version }),+ );+}++function createLinkedProject(): {+ contentDir: string;+ mainDir: string;+ siblingDir: string;+} {+ const mainDir = fs.mkdtempSync(join(root, 'linked-main-'));+ const contentDir = fs.mkdtempSync(join(root, 'linked-request-'));+ const siblingDir = fs.mkdtempSync(join(root, 'linked-sibling-'));+ for (const [name, worktreeDir] of [+ ['request', contentDir],+ ['sibling', siblingDir],+ ] as const) {+ const adminDir = join(mainDir, '.git', 'worktrees', name);+ fs.mkdirSync(adminDir, { recursive: true });+ fs.writeFileSync(join(adminDir, 'commondir'), '../..\n');+ fs.writeFileSync(join(worktreeDir, '.git'), `gitdir: ${adminDir}\n`);+ }+ return { contentDir, mainDir, siblingDir };+}++function seedLinkedFixture(withInPlaceSkill: boolean, withForeignSites: boolean): LinkedFixture {+ const { contentDir, mainDir, siblingDir } = createLinkedProject();+ const home = fs.mkdtempSync(join(root, 'linked-home-'));+ const pluginsDir = join(home, '.claude', 'plugins');+ const bundleRoot = join(pluginsDir, 'cache', 'fixture', 'toolkit');+ const entries: Array<Record<string, string>> = [];+ const mainInstallPath = join(bundleRoot, MAIN_VERSION);+ writeSkill(mainInstallPath, MAIN_VERSION);+ entries.push({+ scope: 'project',+ projectPath: mainDir,+ installPath: mainInstallPath,+ version: MAIN_VERSION,+ lastUpdated: '2026-09-14T00:00:00Z',+ });+ if (withForeignSites) {+ for (const [projectPath, version, lastUpdated] of [+ [contentDir, OWN_VERSION, '2026-09-14T00:02:00Z'],+ [siblingDir, SIBLING_VERSION, '2026-09-14T00:01:00Z'],+ ] as const) {+ const installPath = join(bundleRoot, version);+ writeSkill(installPath, version);+ entries.push({ scope: 'project', projectPath, installPath, version, lastUpdated });+ }+ }+ const userInstallPath = join(bundleRoot, USER_VERSION);+ writeSkill(userInstallPath, USER_VERSION);+ entries.push({+ scope: 'user',+ installPath: userInstallPath,+ version: USER_VERSION,+ lastUpdated: '2026-09-14T00:03:00Z',+ });+ fs.mkdirSync(pluginsDir, { recursive: true });+ fs.writeFileSync(+ join(pluginsDir, 'installed_plugins.json'),+ JSON.stringify({ version: 2, plugins: { 'toolkit@fixture': entries } }),+ );+ fs.writeFileSync(+ join(pluginsDir, 'known_marketplaces.json'),+ JSON.stringify({ fixture: { source: { source: 'github', repo: 'fixture/toolkit' } } }),+ );+ if (withInPlaceSkill) {+ const inPlace = join(contentDir, '.claude', 'skills', 'fixture-skill');+ fs.mkdirSync(inPlace, { recursive: true });+ fs.writeFileSync(+ join(inPlace, 'SKILL.md'),+ '---\nname: fixture-skill\ndescription: In place\n---\n\nBody.\n',+ );+ }+ return { bundleRoot, contentDir, home, mainDir, siblingDir };+}++function expectLinkedWorktreeParentIdentity(fixture: LinkedFixture): void {+ expect(resolveProjectIdentity(fixture.contentDir)).toBe(fixture.mainDir);+ expect(resolveProjectIdentity(fixture.contentDir)).not.toBe(fixture.contentDir);+}++function seedFixture(+ withInPlaceSkill: boolean,+ foreignProjectCount = FOREIGN_PROJECT_COUNT,+): {+ bundleRoot: string;+ contentDir: string;+ home: string;+} {+ const contentDir = fs.mkdtempSync(join(root, 'project-'));+ const home = fs.mkdtempSync(join(root, 'home-'));+ const pluginsDir = join(home, '.claude', 'plugins');+ const bundleRoot = join(pluginsDir, 'cache', 'fixture', 'toolkit');+ const entries: Array<Record<string, string>> = [];+ for (let index = 0; index < foreignProjectCount; index += 1) {+ const version = `1.0.${String(index).padStart(2, '0')}`;+ const installPath = join(bundleRoot, version);+ const projectPath = fs.mkdtempSync(join(root, 'foreign-project-'));+ writeSkill(installPath, version);+ entries.push({+ scope: 'project',+ projectPath,+ installPath,+ version,+ lastUpdated: `2026-09-14T00:00:${String(index).padStart(2, '0')}Z`,+ });+ }+ const ownInstallPath = join(bundleRoot, OWN_VERSION);+ writeSkill(ownInstallPath, OWN_VERSION);+ entries.push({+ scope: 'project',+ projectPath: contentDir,+ installPath: ownInstallPath,+ version: OWN_VERSION,+ lastUpdated: '2026-09-14T00:01:00Z',+ });+ const userInstallPath = join(bundleRoot, USER_VERSION);+ writeSkill(userInstallPath, USER_VERSION);+ entries.push({+ scope: 'user',+ installPath: userInstallPath,+ version: USER_VERSION,+ lastUpdated: '2026-09-14T00:02:00Z',+ });+ fs.mkdirSync(pluginsDir, { recursive: true });+ fs.writeFileSync(+ join(pluginsDir, 'installed_plugins.json'),+ JSON.stringify({ version: 2, plugins: { 'toolkit@fixture': entries } }),+ );+ fs.writeFileSync(+ join(pluginsDir, 'known_marketplaces.json'),+ JSON.stringify({ fixture: { source: { source: 'github', repo: 'fixture/toolkit' } } }),+ );+ if (withInPlaceSkill) {+ const inPlace = join(contentDir, '.claude', 'skills', 'fixture-skill');+ fs.mkdirSync(inPlace, { recursive: true });+ fs.writeFileSync(+ join(inPlace, 'SKILL.md'),+ '---\nname: fixture-skill\ndescription: In place\n---\n\nBody.\n',+ );+ }+ return { bundleRoot, contentDir, home };+}++function addForeignDirectoryMarketplace(fixture: { contentDir: string; home: string }): string {+ const pluginsDir = join(fixture.home, '.claude', 'plugins');+ const marketplaceDir = fs.mkdtempSync(join(root, 'foreign-directory-marketplace-'));+ const marketplaceManifest = join(marketplaceDir, '.claude-plugin', 'marketplace.json');+ fs.mkdirSync(join(marketplaceDir, '.claude-plugin'), { recursive: true });+ fs.writeFileSync(+ marketplaceManifest,+ JSON.stringify({+ name: 'foreign-directory',+ plugins: [{ name: 'foreign-toolkit', source: './plugins/foreign-toolkit' }],+ }),+ );+ const knownPath = join(pluginsDir, 'known_marketplaces.json');+ const known = JSON.parse(fs.readFileSync(knownPath, 'utf-8')) as Record<string, unknown>;+ known['foreign-directory'] = {+ source: { source: 'directory', path: marketplaceDir },+ installLocation: marketplaceDir,+ };+ fs.writeFileSync(knownPath, JSON.stringify(known));+ const installedPath = join(pluginsDir, 'installed_plugins.json');+ const installed = JSON.parse(fs.readFileSync(installedPath, 'utf-8')) as {+ plugins: Record<string, Array<Record<string, string>>>;+ };+ installed.plugins['foreign-toolkit@foreign-directory'] = [+ {+ scope: 'project',+ projectPath: fs.mkdtempSync(join(root, 'foreign-directory-owner-')),+ installPath: join(root, 'missing-foreign-directory-cache'),+ version: '1.0.0',+ lastUpdated: '2026-09-14T00:00:00Z',+ },+ ];+ fs.writeFileSync(installedPath, JSON.stringify(installed));+ return marketplaceManifest;+}++function newCache(home: string) {+ return createSkillsCatalogCache({+ homeDirOverride: home,+ log: getLogger('skills-plugin-scope-test'),+ });+}++function versionsRead(result: Observation, bundleRoot: string): string[] {+ const prefix = `${bundleRoot}${sep}`;+ return [+ ...new Set(+ result.reads+ .filter((path) => path.startsWith(prefix))+ .map((path) => relative(bundleRoot, path).split(sep)[0])+ .filter((version): version is string => version !== undefined && version !== ''),+ ),+ ].sort();+}++async function request(+ extension: ReturnType<typeof createApiExtension>,+ path: string,+): Promise<SkillsResponse> {+ const req = makeSyntheticReq({ method: 'GET', url: path });+ const { res, captured } = makeCaptureRes();+ await extension.onRequest({ request: req, response: res });+ expect(captured.status, captured.body).toBe(200);+ return JSON.parse(captured.body) as SkillsResponse;+}++function extensionFor(contentDir: string, home: string) {+ return createApiExtension({+ contentDir,+ projectDir: contentDir,+ homeDirOverride: home,+ hocuspocus: server.serverInstance.hocuspocus,+ sessionManager: server.serverInstance.sessionManager,+ });+}++function unexpectedCall(): never {+ throw new Error('Unexpected recovery dependency call');+}++function makeJsonRequest(path: string, body: object): IncomingMessage {+ const base = makeSyntheticReq({ method: 'POST', url: path });+ return Object.assign(Readable.from([Buffer.from(JSON.stringify(body))]), {+ method: 'POST',+ url: path,+ headers: { ...base.headers, 'content-type': 'application/json' },+ socket: base.socket,+ }) as IncomingMessage;+}++test('installed catalog TTL starts when a build longer than five seconds completes', () => {+ const fixture = seedFixture(false);+ const cache = newCache(fixture.home);+ fakeNow = 100_000;+ vi.spyOn(Date, 'now').mockImplementation(() => fakeNow ?? 0);+ startObservation(1_000);+ try {+ const first = cache.enumerateInstalledSkillsCached({+ home: fixture.home,+ projectDir: fixture.contentDir,+ });+ const completionTime = fakeNow;+ expect(completionTime - 100_000).toBeGreaterThan(5_000);+ expect(first.skills.filter((skill) => skill.name === 'fixture-skill')).toHaveLength(2);+ startObservation(1_000);+ const immediate = cache.enumerateInstalledSkillsCached({+ home: fixture.home,+ projectDir: fixture.contentDir,+ });+ const immediateWork = finishObservation();+ expect(immediate).toBe(first);+ expect(immediateWork.reads).toHaveLength(0);+ fakeNow = completionTime + 4_999;+ expect(+ cache.enumerateInstalledSkillsCached({+ home: fixture.home,+ projectDir: fixture.contentDir,+ }),+ ).toBe(first);+ fakeNow = completionTime + 5_000;+ expect(+ cache.enumerateInstalledSkillsCached({+ home: fixture.home,+ projectDir: fixture.contentDir,+ }),+ ).not.toBe(first);+ } finally {+ observation = null;+ fakeNow = null;+ }+});++test('plugin index TTL starts when a build longer than thirty seconds completes', () => {+ const fixture = seedFixture(false);+ const cache = newCache(fixture.home);+ fakeNow = 100_000;+ vi.spyOn(Date, 'now').mockImplementation(() => fakeNow ?? 0);+ startObservation(5_000);+ try {+ const first = cache.pluginSkillsByName(fixture.contentDir);+ const completionTime = fakeNow;+ expect(completionTime - 100_000).toBeGreaterThan(30_000);+ expect(first.get('fixture-skill')).toBeDefined();+ startObservation(5_000);+ const immediate = cache.pluginSkillsByName(fixture.contentDir);+ const immediateWork = finishObservation();+ expect(immediate).toBe(first);+ expect(immediateWork.reads).toHaveLength(0);+ fakeNow = completionTime + 29_999;+ expect(cache.pluginSkillsByName(fixture.contentDir)).toBe(first);+ fakeNow = completionTime + 30_000;+ expect(cache.pluginSkillsByName(fixture.contentDir)).not.toBe(first);+ } finally {+ observation = null;+ fakeNow = null;+ }+});++test('/api/skills keeps its catalog reusable by an immediate /api/skills/installed request', async () => {+ const fixture = seedFixture(true, 0);+ const extension = extensionFor(fixture.contentDir, fixture.home);+ fakeNow = 100_000;+ vi.spyOn(Date, 'now').mockImplementation(() => fakeNow ?? 0);+ startObservation(1_000, fixture.bundleRoot);+ try {+ const listBody = await request(extension, '/api/skills');+ const listWork = finishObservation();+ expect(listBody.skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'fixture-skill' })]),+ );+ expect(fakeNow - 100_000).toBeGreaterThan(5_000);+ expect(versionsRead(listWork, fixture.bundleRoot)).toEqual([OWN_VERSION, USER_VERSION]);+ startObservation(1_000, fixture.bundleRoot);+ const installedBody = await request(extension, '/api/skills/installed');+ const installedWork = finishObservation();+ expect(installedBody.skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'fixture-skill' })]),+ );+ expect(versionsRead(installedWork, fixture.bundleRoot)).toEqual([]);+ } finally {+ observation = null;+ fakeNow = null;+ }+});++test('/api/skills reads and hashes only user and requesting-project plugin bundles', async () => {+ const baseline = seedFixture(true, 0);+ const fixture = seedFixture(true);+ const baselineExtension = extensionFor(baseline.contentDir, baseline.home);+ const extension = extensionFor(fixture.contentDir, fixture.home);+ startObservation();+ const baselineBody = await request(baselineExtension, '/api/skills');+ const baselineWork = finishObservation();+ startObservation();+ const body = await request(extension, '/api/skills');+ const work = finishObservation();+ expect(baselineBody.skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'fixture-skill' })]),+ );+ expect(versionsRead(baselineWork, baseline.bundleRoot)).toEqual([OWN_VERSION, USER_VERSION]);+ expect(body.skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'fixture-skill' })]),+ );+ expect.soft(versionsRead(work, fixture.bundleRoot)).toEqual([OWN_VERSION, USER_VERSION]);+ expect.soft(work.reads).toHaveLength(baselineWork.reads.length);+ expect.soft(work.hashes).toBe(baselineWork.hashes);+});++test('/api/skills does not read a directory marketplace owned only by another project', async () => {+ const fixture = seedFixture(true, 0);+ const marketplaceManifest = addForeignDirectoryMarketplace(fixture);+ const extension = extensionFor(fixture.contentDir, fixture.home);+ startObservation();+ const body = await request(extension, '/api/skills');+ const work = finishObservation();+ expect(body.skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'fixture-skill' })]),+ );+ expect(work.reads).not.toContain(marketplaceManifest);+});++test('/api/skills/installed reads metadata only for user and requesting-project plugin bundles', async () => {+ const baseline = seedFixture(false, 0);+ const fixture = seedFixture(false);+ const baselineExtension = extensionFor(baseline.contentDir, baseline.home);+ const extension = extensionFor(fixture.contentDir, fixture.home);+ startObservation();+ const baselineBody = await request(baselineExtension, '/api/skills/installed');+ const baselineWork = finishObservation();+ startObservation();+ const body = await request(extension, '/api/skills/installed');+ const work = finishObservation();+ expect(baselineBody.skills).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({ scope: 'user' }),+ }),+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({+ scope: 'project',+ projectPath: baseline.contentDir,+ }),+ }),+ ]),+ );+ expect(versionsRead(baselineWork, baseline.bundleRoot)).toEqual([OWN_VERSION, USER_VERSION]);+ expect(body.skills).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({ scope: 'user' }),+ }),+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({+ scope: 'project',+ projectPath: fixture.contentDir,+ }),+ }),+ ]),+ );+ expect.soft(versionsRead(work, fixture.bundleRoot)).toEqual([OWN_VERSION, USER_VERSION]);+ expect.soft(work.reads).toHaveLength(baselineWork.reads.length);+ expect.soft(work.hashes).toBe(baselineWork.hashes);+});++test('/api/skills uses the canonical parent project registry site for a linked worktree', async () => {+ const baseline = seedLinkedFixture(true, false);+ const fixture = seedLinkedFixture(true, true);+ expectLinkedWorktreeParentIdentity(baseline);+ expectLinkedWorktreeParentIdentity(fixture);+ const baselineExtension = extensionFor(baseline.contentDir, baseline.home);+ const extension = extensionFor(fixture.contentDir, fixture.home);+ startObservation();+ const baselineBody = await request(baselineExtension, '/api/skills');+ const baselineWork = finishObservation();+ startObservation();+ const body = await request(extension, '/api/skills');+ const work = finishObservation();+ expect(baselineBody.skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'fixture-skill' })]),+ );+ expect(versionsRead(baselineWork, baseline.bundleRoot)).toEqual([MAIN_VERSION, USER_VERSION]);+ expect(body.skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'fixture-skill' })]),+ );+ expect.soft(versionsRead(work, fixture.bundleRoot)).toEqual([MAIN_VERSION, USER_VERSION]);+ expect.soft(work.reads).toHaveLength(baselineWork.reads.length);+ expect.soft(work.hashes).toBe(baselineWork.hashes);+});++test('/api/skills/installed uses the canonical parent project registry site for a linked worktree', async () => {+ const baseline = seedLinkedFixture(false, false);+ const fixture = seedLinkedFixture(false, true);+ expectLinkedWorktreeParentIdentity(baseline);+ expectLinkedWorktreeParentIdentity(fixture);+ const baselineExtension = extensionFor(baseline.contentDir, baseline.home);+ const extension = extensionFor(fixture.contentDir, fixture.home);+ startObservation();+ const baselineBody = await request(baselineExtension, '/api/skills/installed');+ const baselineWork = finishObservation();+ startObservation();+ const body = await request(extension, '/api/skills/installed');+ const work = finishObservation();+ expect.soft(baselineBody.skills).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({ scope: 'user' }),+ }),+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({+ scope: 'project',+ projectPath: baseline.mainDir,+ }),+ }),+ ]),+ );+ expect(versionsRead(baselineWork, baseline.bundleRoot)).toEqual([MAIN_VERSION, USER_VERSION]);+ expect.soft(body.skills).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({ scope: 'user' }),+ }),+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({+ scope: 'project',+ projectPath: fixture.mainDir,+ }),+ }),+ ]),+ );+ expect.soft(body.skills).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({+ scope: 'project',+ projectPath: fixture.contentDir,+ }),+ }),+ ]),+ );+ expect.soft(body.skills).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'fixture-skill',+ provenance: expect.objectContaining({+ scope: 'project',+ projectPath: fixture.siblingDir,+ }),+ }),+ ]),+ );+ expect.soft(versionsRead(work, fixture.bundleRoot)).toEqual([MAIN_VERSION, USER_VERSION]);+ expect.soft(work.reads).toHaveLength(baselineWork.reads.length);+ expect.soft(work.hashes).toBe(baselineWork.hashes);+});++test('skill recovery resolves plugin origin from the canonical parent project registry site', async () => {+ const fixture = seedLinkedFixture(false, true);+ expectLinkedWorktreeParentIdentity(fixture);+ const name = 'fixture-skill';+ const skillsRoot = join(fixture.contentDir, '.claude', 'skills');+ const bundleDir = join(skillsRoot, name);+ fs.mkdirSync(bundleDir, { recursive: true });+ fs.writeFileSync(+ join(bundleDir, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Fixture\n---\n\nBody.\n`,+ );+ const synthPluginLockEntry = vi.fn(() => null);+ const group = createSkillsRecoveryRoutes({+ synthPluginLockEntry,+ synthBuiltinLockEntry: () => null,+ isValidSkillName: () => true,+ getPrincipal: undefined,+ validateSkillName: () => true,+ rejectReservedBuiltinSkill: () => false,+ shadowRef: undefined,+ contentDir: fixture.contentDir,+ contentRoot: undefined,+ projectDir: fixture.contentDir,+ skillsHome: join(fixture.home, '.claude', 'skills'),+ projectSkillDirRel: (skillName) => `.claude/skills/${skillName}`,+ attributeOkArtifactWrite: () => {},+ okArtifactKey: () => '',+ commitOkArtifactWrite: () => Promise.resolve(),+ signalChannel: undefined,+ bumpSkillsCatalogGen: () => {},+ contentFilter: undefined,+ scheduleDeferredIgnoreRebuild: () => {},+ effectiveSkillRoot: (_scope, skillName) => ({+ root: skillsRoot,+ dirRel: `.claude/skills/${skillName}`,+ realDir: join(skillsRoot, skillName),+ }),+ skillReimportService: { runSkillReimport: unexpectedCall },+ localSkillHash: () => undefined,+ resolveSkillsRoot: () => skillsRoot,+ projectImportedSkillCopy: unexpectedCall,+ });+ const dispatch = group.table.resolve('/api/skill/reimport')?.dispatch;+ expect(dispatch).toBeDefined();+ const { res, captured } = makeCaptureRes();+ await dispatch?.(makeJsonRequest('/api/skill/reimport', { name, scope: 'project' }), res);+ expect(captured.status, captured.body).toBe(400);+ expect(JSON.parse(captured.body)).toMatchObject({ detail: 'NOT_IMPORTED' });+ expect(synthPluginLockEntry).toHaveBeenCalledWith(name, fixture.mainDir, bundleDir);+});diff --git a/packages/server/src/http/skills-list-routes.ts b/packages/server/src/http/skills-list-routes.tsindex fefd30ba3..fc54e006d 100644--- a/packages/server/src/http/skills-list-routes.ts+++ b/packages/server/src/http/skills-list-routes.ts@@ -244,7 +244,7 @@ export function createSkillsListRoutes(deps: SkillsListRouteDeps): ApiRouteGroupconst projectAliasRoots = aliasedSourceRoots(projectAliases, 'project');const underRoots = (path: string, roots: ReadonlySet<string>): boolean =>[...roots].some((r) => path === r || path.startsWith(`${r}/`));- const detectedIdentity = resolveProjectIdentity(projectDir ?? contentDir);+ const projectIdentity = resolveProjectIdentity(projectDir ?? contentDir);const pluginBaselines = openPluginBaselines(contentDir);const stdRootsProject = standardSkillRoots('project');const stdRootsGlobal = standardSkillRoots('global');@@ -274,14 +274,14 @@ export function createSkillsListRoutes(deps: SkillsListRouteDeps): ApiRouteGroupprojectNameSeen.add(s.name);const skillAbsDir = resolve(contentDir, s.dir);const selfPlugin = tracked- ? (pluginSelfIdentity(s.name, detectedIdentity, skillAbsDir) ??+ ? (pluginSelfIdentity(s.name, projectIdentity, skillAbsDir) ??repoPluginIdentity(skillAbsDir)): null;const entry =tracked && selfPlugin === null? (lock?.skills[s.name] ??synthBuiltinLockEntry(contentDir, s.name, 'project') ??- synthPluginLockEntry(s.name, detectedIdentity, skillAbsDir))+ synthPluginLockEntry(s.name, projectIdentity, skillAbsDir)): undefined;const origin = entry ? skillOrigin(entry) : undefined;const modified =@@ -289,7 +289,7 @@ export function createSkillsListRoutes(deps: SkillsListRouteDeps): ApiRouteGroup? s.contentHash !== entry.localHash: (() => {if (!entry || !tracked) return false;- const up = pluginUpstreamHash(s.name, detectedIdentity);+ const up = pluginUpstreamHash(s.name, projectIdentity);return (up !== null &&pluginBaselines.isModified('project', s.name, s.contentHash, up)@@ -391,18 +391,18 @@ export function createSkillsListRoutes(deps: SkillsListRouteDeps): ApiRouteGroup...(() => {if (!tracked) return {};const globalAbsDir = resolve(skillsHome, s.dir);- const selfPluginGlobal = pluginSelfIdentity(s.name, detectedIdentity, globalAbsDir);+ const selfPluginGlobal = pluginSelfIdentity(s.name, projectIdentity, globalAbsDir);if (selfPluginGlobal !== null) return { plugin: selfPluginGlobal };const entry =globalLock.skills[s.name] ??synthBuiltinLockEntry(skillsHome, s.name, 'global') ??- synthPluginLockEntry(s.name, detectedIdentity, globalAbsDir);+ synthPluginLockEntry(s.name, projectIdentity, globalAbsDir);if (!entry) return {};const globallyModified =entry.localHash !== undefined? s.contentHash !== entry.localHash: (() => {- const up = pluginUpstreamHash(s.name, detectedIdentity);+ const up = pluginUpstreamHash(s.name, projectIdentity);return (up !== null &&pluginBaselines.isModified('global', s.name, s.contentHash, up)diff --git a/packages/server/src/http/skills-read-routes.ts b/packages/server/src/http/skills-read-routes.tsindex 4237ffb11..9279e71e1 100644--- a/packages/server/src/http/skills-read-routes.ts+++ b/packages/server/src/http/skills-read-routes.ts@@ -60,9 +60,10 @@ export function createSkillsReadRoutes(deps: SkillsReadRouteDeps): SkillsReadRouEmptyRequestSchema,async (_req, res) => {try {- const identity = resolveProjectIdentity(projectDir ?? contentDir);+ const projectIdentity = resolveProjectIdentity(projectDir ?? contentDir);+ const physicalProjectDir = resolve(projectDir ?? contentDir);const catalog = enumerateInstalledSkillsCached({- projectDir: identity,+ projectDir: projectIdentity,...(homeDirOverride !== undefined ? { home: homeDirOverride } : {}),});const inPlaceNames = new Set(scanInPlaceSkills(contentDir).map((s) => s.name));@@ -72,13 +73,13 @@ export function createSkillsReadRoutes(deps: SkillsReadRouteDeps): SkillsReadRouskills: catalog.skills.filter((s) =>- isDetectedSkillInProject(s.provenance, identity) &&+ isDetectedSkillInProject(s.provenance, projectIdentity) &&!(s.provenance.scope === 'project'? inPlaceNames.has(s.name): globalInPlaceNames.has(s.name)),).map((s) =>- isSkillOutsideOpenProject(s.provenance, s.home, projectDir ?? contentDir)+ isSkillOutsideOpenProject(s.provenance, s.home, physicalProjectDir)? { ...s, outsideProject: true }: s,),diff --git a/packages/server/src/skills-catalog-cache.test.ts b/packages/server/src/skills-catalog-cache.test.tsindex dd0dd3956..65988086e 100644--- a/packages/server/src/skills-catalog-cache.test.ts+++ b/packages/server/src/skills-catalog-cache.test.ts@@ -132,3 +132,14 @@ test('plugin content refreshes only on identity change or its independent thirtyconst changedIdentity = c.pluginSkillsByName('project-b');expect(changedIdentity.get('alpha')?.contentHash).not.toBe(expired.get('alpha')?.contentHash);});++test('plugin indexing does not extend an installed catalog cache hit', () => {+ installPlugin('before');+ const c = cache();+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ const catalog = c.enumerateInstalledSkillsCached({ home, projectDir: home });+ clock.mockReturnValue(104_999);+ expect(c.pluginSkillsByName(home).get('alpha')).toBeDefined();+ clock.mockReturnValue(105_000);+ expect(c.enumerateInstalledSkillsCached({ home, projectDir: home })).not.toBe(catalog);+});diff --git a/packages/server/src/skills-catalog-cache.ts b/packages/server/src/skills-catalog-cache.tsindex 3a1273238..5c1b520a9 100644--- a/packages/server/src/skills-catalog-cache.ts+++ b/packages/server/src/skills-catalog-cache.ts@@ -26,9 +26,11 @@ export function createSkillsCatalogCache({function bumpSkillsCatalogGen(): void {skillsCatalogGen += 1;}- function enumerateInstalledSkillsCached(- opts: Parameters<typeof enumerateInstalledSkills>[0],- ): ReturnType<typeof enumerateInstalledSkills> {+ function lookupInstalledSkillsCached(opts: Parameters<typeof enumerateInstalledSkills>[0]): {+ freshBuild: boolean;+ key: string;+ value: ReturnType<typeof enumerateInstalledSkills>;+ } {const key = `${opts?.projectDir ?? ''}|${opts && 'home' in opts ? opts.home : ''}`;const now = Date.now();if (@@ -37,11 +39,17 @@ export function createSkillsCatalogCache({installedCatalogCache.key === key &&now - installedCatalogCache.at < 5_000) {- return installedCatalogCache.value;+ return { freshBuild: false, key, value: installedCatalogCache.value };}const value = enumerateInstalledSkills(opts);- installedCatalogCache = { at: now, gen: skillsCatalogGen, key, value };- return value;+ installedCatalogCache = { at: Date.now(), gen: skillsCatalogGen, key, value };+ return { freshBuild: true, key, value };+ }++ function enumerateInstalledSkillsCached(+ opts: Parameters<typeof enumerateInstalledSkills>[0],+ ): ReturnType<typeof enumerateInstalledSkills> {+ return lookupInstalledSkillsCached(opts).value;}function readList(inPlaceFp: string): { readonly body: unknown } | null {@@ -81,17 +89,30 @@ export function createSkillsCatalogCache({)return pluginIndex.byName;let byName = new Map<string, PluginUpstream>();+ let catalogLookup: ReturnType<typeof lookupInstalledSkillsCached> | null = null;try {+ catalogLookup = lookupInstalledSkillsCached(+ homeDirOverride !== undefined+ ? { home: homeDirOverride, projectDir: identity }+ : { projectDir: identity },+ );byName = pluginUpstreamsByName(- enumerateInstalledSkillsCached(- homeDirOverride !== undefined ? { home: homeDirOverride } : {},- ).skills,+ catalogLookup.value.skills,(home) => parseSkillDir(home)?.contentHash,);} catch (err) {log.warn({ err }, 'plugin upstream index failed; origins will be omitted');}- pluginIndex = { at: now, identity, byName };+ const completedAt = Date.now();+ if (+ catalogLookup?.freshBuild === true &&+ installedCatalogCache?.gen === skillsCatalogGen &&+ installedCatalogCache.key === catalogLookup.key &&+ installedCatalogCache.value === catalogLookup.value+ ) {+ installedCatalogCache.at = completedAt;+ }+ pluginIndex = { at: completedAt, identity, byName };return byName;}