Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 隔离 Skill 目录扫描避免客户端卡死 (#5858)
nanaco9d666e611865
diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjsindex ec57839e6a..c4e5680f4d 100644--- a/apps/desktop/eslint.config.mjs+++ b/apps/desktop/eslint.config.mjs@@ -11,7 +11,7 @@ export default tseslint.config(},{files: ['src/main/**/*.{ts,tsx}'],- // watcher-host、Review PDF、Ghost Node broker 与 Pi Subagent+ // watcher-host、Review PDF、Skill discovery、Ghost Node broker 与 Pi Subagent// 后台宿主是受测的 utilityProcess 基建,和 localDb 一样属于“进程边界基建”,// 只对精确入口豁免导入限制。ignores: [@@ -19,6 +19,7 @@ export default tseslint.config('src/main/watcher-host/**/*.{ts,tsx}','src/main/mcp-integrations/forgeIconConversionHost.ts','src/main/reviewer/reviewPdfProcess.ts',+ 'src/main/skillhub/customizationScanHost.ts','src/main/cindy-brain/nodeRuntimeBroker.ts','src/main/cindy-brain/piSubagentRunnerHost.ts','src/main/__spike__/**/*.{ts,tsx}',diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 880d0fe112..6b3abc7ec7 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -2087,6 +2087,13 @@ const config: ForgeConfig = {// realpath 与 write/rename 之间被 symlink 替换。target: 'preload',},+ {+ entry: 'src/main/skillhub/customizationScanProcess.ts',+ config: 'vite.contacts-sync-codec-worker.config.ts',+ // File approvals can stall native scandir indefinitely. Keep discovery+ // in a killable utility process so Main can time out and recover.+ target: 'preload',+ },{entry: 'src/main/watcher-host/watcherHostProcess.ts',config: 'vite.watcher-host.config.ts',diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.tsindex 62353d710d..a9d5ef8ba0 100644--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts@@ -15,10 +15,14 @@ import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import ts from 'typescript';+import { EventEmitter } from 'node:events';++const scanFork = vi.hoisted(() => vi.fn());// lifecycle.ts 里 import { app } from 'electron' —— 用最小 stub 喂给它。// 真实退出路径 (信号 / before-quit) 不在本文件覆盖。vi.mock('electron', () => ({+ utilityProcess: { fork: scanFork },app: {on: vi.fn(),isReady: () => false,@@ -140,6 +144,21 @@ function snapshotProcessListeners(events: ProcessEventName[]) {}describe('runQuitDisposers', () => {+ it('disposes pending Skill discovery through the real quit registry', async () => {+ const lifecycle = await freshLifecycle();+ const child = new EventEmitter();+ const kill = vi.fn(() => true);+ scanFork.mockReturnValue(Object.assign(child, { kill, postMessage: vi.fn() }));+ const { scanLocalCustomizations } = await import('../skillhub/customizationScanHost');+ const scan = scanLocalCustomizations('pi', {});+ expect(kill).not.toHaveBeenCalled();+ await lifecycle.runQuitDisposers();+ expect((await scan).errors[0].message).toContain('stopped');+ expect(kill).toHaveBeenCalledOnce();+ expect((await scanLocalCustomizations('pi', {})).errors[0].message).toContain('stopped');+ expect(scanFork).toHaveBeenCalledOnce();+ });+it('keeps the bootstrap quit budget open for an in-flight mode write and restoration', async () => {vi.useFakeTimers();const { onQuit, runQuitDisposers, SHUTDOWN_HARD_KILL_GRACE_SECONDS } = await freshLifecycle();diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skill-activation.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skill-activation.test.tsnew file mode 100644index 0000000000..51b5ceb382--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/built-in-skill-activation.test.ts@@ -0,0 +1,62 @@+import fs from 'node:fs';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { canonicalBuiltInSkillActivationPath } from '../built-in-skill-activation';++// Exercise Windows path semantics on every CI host, without real filesystem I/O.+vi.mock('node:path', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:path')>();+ return { default: actual.win32 };+});+vi.mock('node:fs', () => ({+ default: { realpathSync: Object.assign(vi.fn(), { native: vi.fn() }) },+}));++afterEach(() => {+ vi.resetAllMocks();+ vi.unstubAllGlobals();+});++describe('Windows built-in Skill activation identity', () => {+ it.each(['realpath', 'missing'] as const)(+ 'preserves intent across version revisions with case differences (%s)',+ (mode) => {+ vi.stubGlobal('process', { ...process, platform: 'win32' });+ const resolve = (value: fs.PathLike) => {+ if (mode === 'missing') throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ return path.normalize(String(value));+ };+ vi.mocked(fs.realpathSync).mockImplementation(resolve);+ vi.mocked(fs.realpathSync.native).mockImplementation(resolve);+ const appData = path.join('C:\\', 'Users', 'Example', 'AppData', 'Roaming');+ const sourceRoot = path.join(appData.toLowerCase(), 'cindy', 'shared-system-skills');+ const sources = [+ 'v6-0123456789abcdef-11111111-1111-1111-1111-111111111111',+ 'v7-fedcba9876543210-22222222-2222-2222-2222-222222222222',+ ].map((version) => path.join(sourceRoot, '.versions', version, 'learn'));+ const keys = sources.map((source) => canonicalBuiltInSkillActivationPath(+ source, path.join(appData, 'CindyGlobal'), appData,+ ));+ expect(keys).toEqual([path.join(sourceRoot, 'learn'), path.join(sourceRoot, 'learn')]);+ },+ );++ it.each(['drive', 'unc'] as const)('matches a %s namespace realpath with a lexical root', (kind) => {+ vi.stubGlobal('process', { ...process, platform: 'win32' });+ const appData = kind === 'drive'+ ? path.join('C:\\', 'Users', 'Example', 'AppData')+ : path.join('\\\\server\\share', 'Users', 'Example', 'AppData');+ const root = path.join(appData, 'Cindy', 'shared-system-skills');+ const resolve = (value: fs.PathLike) => path.normalize(String(value));+ vi.mocked(fs.realpathSync).mockImplementation(resolve);+ vi.mocked(fs.realpathSync.native).mockImplementation(resolve);+ const sourceRoot = path.toNamespacedPath(root).toLowerCase();+ const source = path.join(sourceRoot, '.active', 'learn');+ expect(canonicalBuiltInSkillActivationPath(source, path.join(appData, 'CindyGlobal'), appData))+ .toBe(path.join(sourceRoot, 'learn'));+ const foreignRoot = path.join(appData, 'project', 'shared-system-skills');+ const foreignSource = path.join(foreignRoot, '.active', 'learn');+ expect(canonicalBuiltInSkillActivationPath(foreignSource, path.join(appData, 'CindyGlobal'), appData))+ .toBe(foreignSource);+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.tsindex 8ad48666a0..c54f9352e2 100644--- a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts@@ -5,6 +5,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { Maker } from '@cindy/maker-core';import { scanAllSkills } from '../../skillhub/scanner';+vi.mock('../../skillhub/customizationScanHost', async () => {+ const { buildSkillList } = await import('../../skillhub/skillListProjection');+ return { projectSkillList: vi.fn(async (input) => buildSkillList(input)) };+});+vi.mock('../../skillhub/registry', () => ({registryService: { listAllInstalls: vi.fn(async () => []), getInstall: vi.fn(async () => null) },}));diff --git a/apps/desktop/src/main/maker-host/built-in-skill-activation.ts b/apps/desktop/src/main/maker-host/built-in-skill-activation.tsnew file mode 100644index 0000000000..e6287129d7--- /dev/null+++ b/apps/desktop/src/main/maker-host/built-in-skill-activation.ts@@ -0,0 +1,58 @@+import fs from 'node:fs';+import path from 'node:path';+import { CINDY_LEARN_NAME, CINDY_SKILL_CREATOR_NAME } from '../../shared/cindyBuiltInSkills';+const BUILT_IN_SKILL_NAMES = [CINDY_SKILL_CREATOR_NAME, CINDY_LEARN_NAME];+const ACTIVE_BUNDLE_LINK = '.active';+const VERSIONS_DIRECTORY = '.versions';+function normalizeForCompare(value: string): string {+ const withoutWindowsNamespace = process.platform === 'win32'+ ? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')+ : value;+ const resolved = path.resolve(withoutWindowsNamespace);+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;+}++function realPathOrNormalized(value: string): string {+ try { return normalizeForCompare(fs.realpathSync.native(value)); }+ catch { return normalizeForCompare(value); }+}+export function validActiveBundle(value: unknown): value is string {+ return typeof value === 'string' && /^v[1-9][0-9]*-[a-f0-9]{16}-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);+}+export function builtInSkillsRoot(userDataDir: string): string {+ return path.join(userDataDir, 'system-skills');+}++/** Profile-independent storage shared by Global, China, dev, and isolated profiles. */+export function sharedBuiltInSkillsRoot(appDataDir: string): string {+ return path.join(appDataDir, 'Cindy', 'shared-system-skills');+}++/** Keep enable/disable intent stable while immutable built-in bundle revisions change. */+export function canonicalBuiltInSkillActivationPath(+ source: string,+ userDataDir: string,+ appDataDir?: string,+): string {+ const name = path.basename(source);+ if (!(BUILT_IN_SKILL_NAMES as readonly string[]).includes(name)) return source;+ const bundleRoot = path.dirname(source);+ const managedRoots = [+ builtInSkillsRoot(userDataDir),+ ...(appDataDir ? [sharedBuiltInSkillsRoot(appDataDir)] : []),+ ];+ if (+ path.basename(bundleRoot) === ACTIVE_BUNDLE_LINK+ && managedRoots.some((root) => realPathOrNormalized(path.dirname(bundleRoot)) === realPathOrNormalized(root))+ ) {+ return path.join(path.dirname(bundleRoot), name);+ }+ const versionsRoot = path.dirname(bundleRoot);+ const stableRoot = path.dirname(versionsRoot);+ if (+ path.basename(versionsRoot) !== VERSIONS_DIRECTORY ||+ !validActiveBundle(path.basename(bundleRoot)) ||+ !managedRoots.some((root) => realPathOrNormalized(stableRoot) === realPathOrNormalized(root))+ ) return source;+ return path.join(stableRoot, name);+}diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.tsindex 85067d4106..6e8f024dc5 100644--- a/apps/desktop/src/main/maker-host/built-in-skills.ts+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts@@ -1,3 +1,5 @@+import { builtInSkillsRoot, sharedBuiltInSkillsRoot, validActiveBundle } from './built-in-skill-activation';+export { builtInSkillsRoot, sharedBuiltInSkillsRoot, canonicalBuiltInSkillActivationPath } from './built-in-skill-activation';import { createHash, randomUUID } from 'node:crypto';import fs from 'node:fs';import { promises as fsp } from 'node:fs';@@ -103,15 +105,6 @@ export function builtInSkillPluginRoot(userDataDir: string): string {return path.join(userDataDir, 'managed-agent-skills', 'cindy');}-export function builtInSkillsRoot(userDataDir: string): string {- return path.join(userDataDir, 'system-skills');-}--/** Profile-independent storage shared by Global, China, dev, and isolated profiles. */-export function sharedBuiltInSkillsRoot(appDataDir: string): string {- return path.join(appDataDir, 'Cindy', 'shared-system-skills');-}-export function builtInSkillDescriptors(userDataDir: string,appDataDir?: string,@@ -165,40 +158,6 @@ function stableBuiltInSkillDescriptors(return builtInSkillDescriptorsAtRoot(path.join(root, ACTIVE_BUNDLE_LINK), userDataDir);}-function validActiveBundle(value: unknown): value is string {- return typeof value === 'string'- && /^v[1-9][0-9]*-[a-f0-9]{16}-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);-}--/** Keep enable/disable intent stable while immutable built-in bundle revisions change. */-export function canonicalBuiltInSkillActivationPath(- source: string,- userDataDir: string,- appDataDir?: string,-): string {- const name = path.basename(source);- if (!(BUILT_IN_SKILL_NAMES as readonly string[]).includes(name)) return source;- const bundleRoot = path.dirname(source);- const managedRoots = [- builtInSkillsRoot(userDataDir),- ...(appDataDir ? [sharedBuiltInSkillsRoot(appDataDir)] : []),- ];- if (- path.basename(bundleRoot) === ACTIVE_BUNDLE_LINK- && managedRoots.some((root) => realPathOrNormalized(path.dirname(bundleRoot)) === realPathOrNormalized(root))- ) {- return path.join(path.dirname(bundleRoot), name);- }- const versionsRoot = path.dirname(bundleRoot);- const stableRoot = path.dirname(versionsRoot);- if (- path.basename(versionsRoot) !== VERSIONS_DIRECTORY ||- !validActiveBundle(path.basename(bundleRoot)) ||- !managedRoots.some((root) => realPathOrNormalized(stableRoot) === realPathOrNormalized(root))- ) return source;- return path.join(stableRoot, name);-}-function parseManifest(raw: string): MaterializationManifest | null {const parsed = JSON.parse(raw) as Partial<MaterializationManifest>;const commonShapeIsValid =diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex fc38968218..b4456987e1 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -1,5 +1,6 @@import { readAgentCapabilityCatalog, RUNTIME_MCP_NAMES_KEY, type AgentCapabilityQuery } from './agentCapabilityCatalog.js';import { listCindyManagedSkills, prepareCindyCodexSkills } from './managed-skills.js';+import { scanLocalCustomizations } from '../skillhub/customizationScanHost';import { createCompanionImportProvider } from '../bot-import/importProvider.js';import { createCompanionConnectionsProvider } from '../bot-import/connectionProvider.js';import { resolveCompanionRuntimeEnvironment } from '../bot-import/runtime.js';@@ -1288,6 +1289,7 @@ export function getMaker(): Maker {resolveSessionEnvironment: resolveCompanionRuntimeEnvironment,getDisabledSkillPaths: readDisabledSkillPaths,getManagedSkills: listCindyManagedSkills,+ scanLocalCustomizations,auth: desktopClaudeAuthAdapter,runtimeConfig: buildDesktopClaudeRuntimeConfig(getClaudeEndpoint),binaryPath: claudePath,@@ -1616,6 +1618,7 @@ export function getMaker(): Maker {resolveSessionEnvironment: resolveCompanionRuntimeEnvironment,getDisabledSkillPaths: readDisabledSkillPaths,getManagedSkills: listCindyManagedSkills,+ scanLocalCustomizations,prepareCodexSkills: prepareCindyCodexSkills,auth: desktopCodexAuthAdapter,runtimeConfig: desktopCodexRuntimeConfig,diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 95ce9cc985..eeb0797e5c 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -1,4 +1,5 @@import { listCindyManagedSkills } from './managed-skills.js';+import { scanLocalCustomizations } from '../skillhub/customizationScanHost';import { resolveCompanionRuntimeEnvironment } from '../bot-import/runtime.js';import { readCachedGenericOAuthAccessToken } from './generic-oauth.js';import { providerPresetModelRecord, providerModelAdapterId } from '@cindy/model-providers';@@ -1876,7 +1877,8 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {return new PiAgent({resolveSessionEnvironment: resolveCompanionRuntimeEnvironment,getDisabledSkillPaths: readDisabledSkillPaths,- getManagedSkills: listCindyManagedSkills,+ getManagedSkills: listCindyManagedSkills,+ scanLocalCustomizations,resolveModelContextLimit: (providerId, modelId) => {const catalog = getActiveCatalog();const source = resolveModelContextProviderId(catalog, 'pi', providerId, modelId);diff --git a/apps/desktop/src/main/skillhub/__tests__/customizationScanClient.test.ts b/apps/desktop/src/main/skillhub/__tests__/customizationScanClient.test.tsnew file mode 100644index 0000000000..eb630cef08--- /dev/null+++ b/apps/desktop/src/main/skillhub/__tests__/customizationScanClient.test.ts@@ -0,0 +1,170 @@+import { EventEmitter } from 'node:events';+import matter from 'gray-matter';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { CustomizationScanClient, type CustomizationScanChild } from '../customizationScanClient';+import type { CustomizationScanRequest } from '../customizationScanProtocol';++class FakeScanner extends EventEmitter implements CustomizationScanChild {+ postMessage = vi.fn<(message: CustomizationScanRequest) => void>();+ autoExit = true;+ kill = vi.fn(() => {+ if (this.autoExit) queueMicrotask(() => this.emit('exit', 0));+ return true;+ });++ reply(result = { items: [], errors: [] }): void {+ const request = this.postMessage.mock.calls.at(-1)![0];+ this.emit('message', { kind: 'result', id: request.id, result });+ }+}++afterEach(() => vi.useRealTimers());++describe('bounded customization discovery', () => {+ it('accepts cyclic YAML metadata in list projection requests', async () => {+ const child = new FakeScanner();+ const client = new CustomizationScanClient({ fork: () => child });+ const expected = { skills: [], sources: [] };+ child.postMessage.mockImplementation((request) => {+ const packet = structuredClone(request);+ queueMicrotask(() => child.emit('message', { kind: 'result', id: packet.id, result: expected }));+ });+ const frontmatter = matter('---\na: &a { b: *a }\n---\nskill').data;+ const input = { projects: [], listed: { items: [{ engine: 'pi' as const, kind: 'skill', scope: 'user',+ name: 'cyclic', absolutePath: '/tmp/.agents/skills/cyclic', frontmatter }], errors: [] },+ registryEntries: [], managedSkillRoots: [], builtInSkills: [], disabledPaths: [],+ userDataDir: '/tmp/profile', appDataDir: '/tmp/appdata' };+ await expect(client.request({ kind: 'project', input },+ (value): value is typeof expected => value !== null && typeof value === 'object',+ () => expected)).resolves.toEqual(expected);+ expect(child.postMessage).toHaveBeenCalledOnce();+ expect(child.kill).toHaveBeenCalledOnce();+ });++ it('returns an error and kills an unresponsive scanner while Main timers still run', async () => {+ vi.useFakeTimers();+ const child = new FakeScanner();+ const client = new CustomizationScanClient({ fork: () => child, timeoutMs: 100 });+ const scan = client.scan('pi', { workingDirs: ['/project'] });+ const heartbeat = vi.fn();+ setTimeout(heartbeat, 10);++ await vi.advanceTimersByTimeAsync(10);+ expect(heartbeat).toHaveBeenCalledOnce();+ expect(child.kill).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(90);+ expect(await scan).toEqual({+ items: [], errors: [{ message: '[pi] Customization scan timed out' }],+ });+ expect(child.kill).toHaveBeenCalledOnce();++ // A hung/failed run must not poison the next refresh.+ const refresh = client.scan('pi', { workingDirs: ['/project'] });+ child.reply();+ expect(await refresh).toEqual({ items: [], errors: [] });+ expect(child.kill).toHaveBeenCalledTimes(2);+ });++ it('coalesces duplicate scans but gives each caller its own mutable result', async () => {+ const child = new FakeScanner();+ const fork = vi.fn(() => child);+ const client = new CustomizationScanClient({ fork });+ const options = { workingDirs: ['/project'], kinds: ['skill'] };+ const first = client.scan('claude-code', options);+ const second = client.scan('claude-code', options);+ expect(fork).toHaveBeenCalledOnce();+ expect(child.postMessage.mock.calls[0][0]).toMatchObject({+ kind: 'scan', engine: 'claude-code', options,+ });+ child.reply();+ const a = await first;+ const b = await second;+ a.errors.push({ message: 'Caller-local managed skill failure' });+ expect(b.errors).toEqual([]);+ expect(child.kill).toHaveBeenCalledOnce();+ });++ it('isolates failures between engines and ignores late responses from a timed-out child', async () => {+ vi.useFakeTimers();+ const children: FakeScanner[] = [];+ const client = new CustomizationScanClient({+ fork: () => { const child = new FakeScanner(); children.push(child); return child; },+ timeoutMs: 100,+ });+ const pi = client.scan('pi', {});+ const codex = client.scan('codex', {});+ children[1].reply();+ expect(await codex).toEqual({ items: [], errors: [] });+ await vi.advanceTimersByTimeAsync(100);+ expect((await pi).errors[0].message).toContain('timed out');+ const refresh = client.scan('pi', {});+ children[0].reply();+ children[2].reply();+ expect(await refresh).toEqual({ items: [], errors: [] });+ expect(children.every((child) => child.kill.mock.calls.length === 1)).toBe(true);+ });++ it.each(['exit', 'error', 'postMessage', 'fork', 'invalid result'])(+ 'settles and cleans up when the scanner fails at %s', async (failure) => {+ const child = new FakeScanner();+ const client = new CustomizationScanClient({+ fork: () => {+ if (failure === 'fork') throw new Error('cannot start');+ return child;+ },+ });+ if (failure === 'postMessage') child.postMessage.mockImplementation(() => { throw new Error('closed'); });+ const scan = client.scan('codex', {});+ if (failure === 'exit') child.emit('exit', 1);+ if (failure === 'error') child.emit('error', 'crashed');+ if (failure === 'invalid result') {+ child.emit('message', { kind: 'result', id: child.postMessage.mock.calls[0][0].id, result: null });+ }+ expect((await scan).errors).toHaveLength(1);+ expect(child.kill).toHaveBeenCalledTimes(failure === 'fork' || failure === 'exit' ? 0 : 1);+ client.dispose();+ expect(child.kill).toHaveBeenCalledTimes(failure === 'fork' || failure === 'exit' ? 0 : 1);+ },+ );++ it('retains terminating children in the limit until exit, even when kill fails', async () => {+ vi.useFakeTimers();+ const children: FakeScanner[] = [];+ const client = new CustomizationScanClient({+ maxConcurrent: 2, timeoutMs: 100,+ fork: () => { const child = new FakeScanner(); child.autoExit = false; children.push(child); return child; },+ });+ const first = client.scan('pi', {});+ const second = client.scan('codex', {});+ children[1].kill.mockImplementation(() => false);+ await vi.advanceTimersByTimeAsync(100);+ expect((await first).errors[0].message).toContain('timed out');+ expect((await second).errors[0].message).toContain('timed out');+ for (let i = 0; i < 10; i++) expect((await client.scan('pi', {})).errors[0].message).toContain('busy');+ expect(children).toHaveLength(2);+ children[0].emit('exit', 0);+ const refreshed = client.scan('pi', {});+ expect(children).toHaveLength(3);+ children[2].reply();+ expect((await refreshed).errors).toEqual([]);+ expect((await client.scan('pi', {})).errors[0].message).toContain('busy');+ children[2].emit('exit', 0);+ client.dispose();+ expect(children.every((child) => child.kill.mock.calls.length === 1)).toBe(true);+ });++ it('bounds concurrent children and cancels pending work on shutdown', async () => {+ const child = new FakeScanner();+ const fork = vi.fn(() => child);+ const client = new CustomizationScanClient({ fork, maxConcurrent: 1 });+ const scan = client.scan('pi', {});+ const overflow = await client.scan('pi', { workingDirs: ['/other'] });+ expect(overflow.errors[0].message).toContain('busy');+ expect(fork).toHaveBeenCalledOnce();+ client.dispose();+ expect((await scan).errors[0].message).toContain('stopped');+ expect(child.kill).toHaveBeenCalledOnce();+ expect((await client.scan('pi', {})).errors).toHaveLength(1);+ expect(fork).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/skillhub/__tests__/customizationScanHost.test.ts b/apps/desktop/src/main/skillhub/__tests__/customizationScanHost.test.tsnew file mode 100644index 0000000000..e7f54efe8b--- /dev/null+++ b/apps/desktop/src/main/skillhub/__tests__/customizationScanHost.test.ts@@ -0,0 +1,62 @@+import { EventEmitter } from 'node:events';+import os from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { CustomizationScanRequest } from '../customizationScanProtocol';++const { fork, onQuit, warn } = vi.hoisted(() => ({ fork: vi.fn(), onQuit: vi.fn(), warn: vi.fn() }));+vi.mock('electron', () => ({ utilityProcess: { fork } }));+vi.mock('../../lifecycle', () => ({ onQuit }));+vi.mock('../../logger', () => ({ createLogger: () => ({ warn }) }));++afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs(); vi.clearAllMocks(); vi.resetModules(); });++describe('Desktop customization scan host', () => {+ it('forks only the bundled entry with home/system variables, no credentials, and disposes on quit', async () => {+ vi.stubEnv('CINDY_TEST_SECRET', 'must-not-reach-the-scanner');+ const child = new EventEmitter();+ const kill = vi.fn(() => true);+ const postMessage = vi.fn((request: CustomizationScanRequest) => {+ queueMicrotask(() => child.emit('message', {+ kind: 'result', id: request.id, result: { items: [], errors: [] },+ }));+ });+ fork.mockReturnValue(Object.assign(child, { kill, postMessage }));+ const { scanLocalCustomizations } = await import('../customizationScanHost');+ expect(fork).not.toHaveBeenCalled();+ expect(onQuit).not.toHaveBeenCalled();+ expect(await scanLocalCustomizations('pi', { kinds: ['skill'] })).toEqual({ items: [], errors: [] });+ const [entry, args, options] = fork.mock.calls[0];+ expect(path.basename(entry)).toBe('customizationScanProcess.js');+ expect(args).toEqual([]);+ expect(options.cwd).toBe(os.tmpdir());+ expect(options.env.CINDY_TEST_SECRET).toBeUndefined();+ expect(options.env.HOME).toBe(process.env.HOME);+ expect(options.env.USERPROFILE).toBe(process.env.USERPROFILE);+ expect(options.stdio).toBe('ignore');+ expect(kill).toHaveBeenCalledOnce();+ expect(onQuit).toHaveBeenCalledExactlyOnceWith('skillhub-discovery', expect.any(Function));++ onQuit.mock.calls[0][1]();+ expect((await scanLocalCustomizations('pi', {})).errors[0].message).toContain('stopped');+ expect(fork).toHaveBeenCalledOnce();+ });+ it('returns a list error but no grants when isolated path inspection times out', async () => {+ vi.useFakeTimers();+ const child = Object.assign(new EventEmitter(), { kill: vi.fn(() => true), postMessage: vi.fn() });+ fork.mockReturnValue(child);+ const { projectSkillList, inspectSkillListGrants } = await import('../customizationScanHost');+ const projection = projectSkillList({ projects: [], listed: { items: [], errors: [] },+ registryEntries: [], managedSkillRoots: [], builtInSkills: [], disabledPaths: [],+ userDataDir: os.tmpdir(), appDataDir: os.tmpdir() });+ await vi.advanceTimersByTimeAsync(15_000);+ expect(await projection).toMatchObject({ skills: [], sources: [{ status: { state: 'error', message: expect.stringContaining('timed out') } }] });+ child.emit('exit', 0);+ const grants = inspectSkillListGrants({ skills: [], managedSkillRoots: [], builtInSkills: [] });+ const rejected = expect(grants).rejects.toThrow('timed out');+ await vi.advanceTimersByTimeAsync(15_000);+ await rejected;+ child.emit('exit', 0);+ });++});diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.tsindex b6e5cb9770..a2e32e8df2 100644--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts@@ -13,6 +13,7 @@ const setCindySkillEnabled = vi.fn(async () => undefined);const isCindyLearnSkillEnabled = vi.fn(() => true);vi.mock('../activationPreferences', () => ({isCindyLearnSkillEnabled,+ isCindyLearnSkillEnabledForListing: isCindyLearnSkillEnabled,setCindySkillEnabled,}));@@ -114,6 +115,13 @@ vi.mock('../scanner', () => ({writeSkillFile,}));+const inspectSkillListGrants = vi.fn();+vi.mock('../customizationScanHost', async () => {+ const { prepareSkillScanGrants } = await import('../skillScanGrants');+ inspectSkillListGrants.mockImplementation(async (input) => prepareSkillScanGrants(input, resolveExistingSkillPathForGrant));+ return { inspectSkillListGrants };+});+vi.mock('../folderHash', () => ({computeFolderHashDetailed: vi.fn(),}));@@ -234,6 +242,21 @@ describe('registerSkillhubIpc usage handlers', () => {},);+ it('does not publish grants when the owner changes during isolated grant preparation', async () => {+ let finish!: (value: { entries: Array<{ root: string }>; records: never[] }) => void;+ inspectSkillListGrants.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ scanAllSkills.mockResolvedValueOnce({ skills: [], sources: [] });+ const event = { sender: { id: 222, once: vi.fn(), on: vi.fn() } };+ const scan = handlers.get('skillhub:scan')!(event, {});+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));+ ownerState.pending = true;+ finish({ entries: [{ root: path.join(fixtureRoot, 'stale') }], records: [] });+ await scan;+ expect(await handlers.get('skillhub:read-skill')!(event, { mdPath: path.join(fixtureRoot, 'stale', 'SKILL.md') }))+ .toMatchObject({ success: false });+ expect(readSkillContent).not.toHaveBeenCalled();+ });+it('delivers private publication feedback only to currently trusted app windows', async () => {const { BrowserWindow } = await import('electron');const { registerSkillhubIpc } = await import('../registerIpc');diff --git a/apps/desktop/src/main/skillhub/__tests__/scanIsolation.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanIsolation.test.tsnew file mode 100644index 0000000000..fc072db742--- /dev/null+++ b/apps/desktop/src/main/skillhub/__tests__/scanIsolation.test.ts@@ -0,0 +1,35 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import type { Maker } from '@cindy/maker-core';++const { project, listAllInstalls, readDisabled } = vi.hoisted(() => ({+ project: vi.fn(), listAllInstalls: vi.fn(), readDisabled: vi.fn(() => []),+}));+vi.mock('electron', () => ({ app: { getPath: () => os.tmpdir() } }));+vi.mock('../customizationScanHost', () => ({ projectSkillList: project }));+vi.mock('../registry', () => ({ registryService: { listAllInstalls } }));+vi.mock('../activationPreferences', () => ({ readDisabledSkillPathsForListing: readDisabled, renameSkillWithActivation: vi.fn() }));+vi.mock('../registryReconciliation', () => ({ reconcileScannedInstall: () => { throw new Error('Scan must not maintain installs'); } }));+import { scanAllSkills } from '../scanner';++describe('Main scan isolation', () => {+ it('passes offline registry paths to the bounded projection without touching them on Main', async () => {+ const offline = path.join(os.tmpdir(), 'offline-volume', '.agents', 'skills', 'offline');+ const record = { skillName: 'offline', installPath: offline, entry: { version: '1' } };+ listAllInstalls.mockResolvedValue([record]);+ const error = { message: '[pi] Customization scan timed out' };+ const listed = { items: [], errors: [error] };+ const maker = { listCustomizations: vi.fn(async () => listed) } as unknown as Maker;+ const expected = { skills: [], sources: [{ kind: 'skill', scope: 'global', path: '', status: { state: 'error', message: error.message } }] };+ project.mockResolvedValue(expected);+ const realpath = vi.spyOn(fs, 'realpathSync').mockImplementation(() => { throw new Error('Main must not resolve paths'); });+ try {+ expect(await scanAllSkills({}, maker)).toBe(expected);+ expect(listAllInstalls).toHaveBeenCalledExactlyOnceWith({ readOnly: true });+ expect(project).toHaveBeenCalledWith(expect.objectContaining({ listed, registryEntries: [record] }));+ expect(realpath).not.toHaveBeenCalled();+ } finally { realpath.mockRestore(); }+ });+});diff --git a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanner.test.tsindex c621090355..04e495d2ff 100644--- a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts@@ -11,6 +11,11 @@ vi.mock('../registry', () => ({},}));+vi.mock('../customizationScanHost', async () => {+ const { buildSkillList } = await import('../skillListProjection');+ return { projectSkillList: vi.fn(async (input) => buildSkillList(input)) };+});+import {isExistingSkillPathGranted,listSkillFolderChildren,diff --git a/apps/desktop/src/main/skillhub/activationPreferences.ts b/apps/desktop/src/main/skillhub/activationPreferences.tsindex 577179755f..3b6bad9100 100644--- a/apps/desktop/src/main/skillhub/activationPreferences.ts+++ b/apps/desktop/src/main/skillhub/activationPreferences.ts@@ -1,3 +1,4 @@+import { builtInSkillsRoot, sharedBuiltInSkillsRoot } from '../maker-host/built-in-skill-activation';import fs from 'node:fs';import path from 'node:path';import { randomUUID } from 'node:crypto';@@ -81,10 +82,26 @@ export function readDisabledSkillPaths(): readonly string[] {return [...new Set(paths)];}+/** Listing receives stored intent; resolving user aliases happens in its worker. */+export function readDisabledSkillPathsForListing(): readonly string[] {+ store.invalidateIfChanged();+ return [...store.read().disabledPaths];+}+export function isCindySkillEnabled(source: string): boolean {return !readDisabledSkillPaths().includes(skillActivationKey(source));}+/** Listing fallback reads stored intent only; never walks user discovery aliases. */+export function isCindyLearnSkillEnabledForListing(descriptors: readonly { name: string }[]): boolean {+ if (!descriptors.some((skill) => skill.name === BUILT_IN_LEARN_SKILL_NAME)) return false;+ const disabled = readDisabledSkillPathsForListing();+ return ![+ path.join(builtInSkillsRoot(app.getPath('userData')), BUILT_IN_LEARN_SKILL_NAME),+ path.join(sharedBuiltInSkillsRoot(app.getPath('appData')), BUILT_IN_LEARN_SKILL_NAME),+ ].some((value) => disabled.includes(process.platform === 'win32' ? value.toLowerCase() : value));+}+export function isCindyLearnSkillEnabled(): boolean {const descriptor = builtInSkillDescriptors(app.getPath('userData'),diff --git a/apps/desktop/src/main/skillhub/customizationScanClient.ts b/apps/desktop/src/main/skillhub/customizationScanClient.tsnew file mode 100644index 0000000000..923767947b--- /dev/null+++ b/apps/desktop/src/main/skillhub/customizationScanClient.ts@@ -0,0 +1,125 @@+import { randomUUID } from 'node:crypto';+import type { AgentCustomization, ListCustomizationsOptions, ListCustomizationsResult } from '@cindy/maker-core';+import type { CustomizationScanRequest, CustomizationScanResponse, EngineScanRequest } from './customizationScanProtocol';++export interface CustomizationScanChild {+ postMessage(message: CustomizationScanRequest): void;+ on(event: 'message', listener: (message: unknown) => void): void;+ on(event: 'exit', listener: (code: number) => void): void;+ on(event: 'error', listener: (type: string) => void): void;+ kill(): boolean;+}++interface ScanJob {+ result: Promise<unknown>;+ stop: () => void;+}++function isResult(value: unknown, engine: AgentCustomization['engine']): value is ListCustomizationsResult {+ if (!value || typeof value !== 'object') return false;+ const result = value as Partial<ListCustomizationsResult>;+ return Array.isArray(result.items) && result.items.every((item) =>+ item && item.engine === engine && typeof item.name === 'string' &&+ typeof item.kind === 'string' && typeof item.scope === 'string' &&+ typeof item.absolutePath === 'string',+ ) && Array.isArray(result.errors) && result.errors.every((error) =>+ error && typeof error.message === 'string' &&+ (error.path === undefined || typeof error.path === 'string'),+ );+}++/** Only discovery runs here. Main still owns managed Skills and all file-operation grants. */+export class CustomizationScanClient {+ private readonly jobs = new Map<string, ScanJob>();+ private disposed = false;+ // kill() requests termination; native I/O can delay the actual exit.+ private readonly children = new Set<CustomizationScanChild>();+ private readonly killRequested = new Set<CustomizationScanChild>();++ constructor(private readonly options: {+ fork: () => CustomizationScanChild;+ timeoutMs?: number;+ maxConcurrent?: number;+ }) {}++ async scan(engine: AgentCustomization['engine'], options: ListCustomizationsOptions): Promise<ListCustomizationsResult> {+ const failure = (message: string): ListCustomizationsResult => ({+ items: [], errors: [{ message: `[${engine}] ${message}` }],+ });+ return this.request<ListCustomizationsResult>({ kind: 'scan', engine, options },+ (value): value is ListCustomizationsResult => isResult(value, engine), failure);+ }++ async request<T>(+ task: Omit<EngineScanRequest, 'id'>+ | { kind: 'project'; input: import('./skillListProjection').SkillListProjectionInput }+ | { kind: 'grants'; input: import('./skillScanGrants').SkillScanGrantInput },+ validate: (value: unknown) => value is T,+ failure: (message: string) => T,+ ): Promise<T> {+ if (this.disposed) return failure('Customization scanner stopped');+ // YAML anchors may create cycles; the utility-process packet supports them.+ let key: string;+ try { key = JSON.stringify(task); } catch { key = randomUUID(); }+ const existing = this.jobs.get(key);+ // Agents append host-managed Skills. Never share their mutable result arrays.+ if (existing) return structuredClone(await existing.result) as T;+ if (this.children.size >= (this.options.maxConcurrent ?? 6)) {+ return failure('Customization scanner busy; retry after the pending scan');+ }++ let resolve!: (result: T) => void;+ const result = new Promise<T>((complete) => { resolve = complete; });+ let child: CustomizationScanChild | undefined;+ let settled = false;+ let exited = false;+ const finish = (value: T): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ this.jobs.delete(key);+ if (child && !exited) this.killChild(child);+ resolve(value);+ };+ // File approval can wait indefinitely inside native scandir/open. Main owns+ // the timer and kills the isolated process, rather than racing uncancellable+ // I/O on Main's event loop or its shared libuv pool.+ const timer = setTimeout(() => finish(failure('Customization scan timed out')), this.options.timeoutMs ?? 15_000);+ timer.unref?.();+ this.jobs.set(key, { result, stop: () => finish(failure('Customization scanner stopped')) });+ const id = randomUUID();+ try {+ child = this.options.fork();+ this.children.add(child);+ child.on('message', (value) => {+ if (!value || typeof value !== 'object') return;+ const response = value as Partial<CustomizationScanResponse>;+ if (response.kind !== 'result' || response.id !== id) return;+ finish(validate(response.result) ? response.result : failure('Customization scanner returned an invalid result'));+ });+ child.on('exit', () => {+ exited = true;+ this.children.delete(child!);+ this.killRequested.delete(child!);+ finish(failure('Customization scanner exited before completing'));+ });+ child.on('error', () => finish(failure('Customization scanner failed')));+ child.postMessage({ ...task, id });+ } catch {+ finish(failure('Could not start customization scanner'));+ }+ return structuredClone(await result);+ }++ private killChild(child: CustomizationScanChild): void {+ if (this.killRequested.has(child)) return;+ this.killRequested.add(child);+ try { child.kill(); } catch { /* Retain the slot until exit confirms cleanup. */ }+ }++ dispose(): void {+ this.disposed = true;+ for (const job of this.jobs.values()) job.stop();+ for (const child of this.children) this.killChild(child);+ }+}diff --git a/apps/desktop/src/main/skillhub/customizationScanHost.ts b/apps/desktop/src/main/skillhub/customizationScanHost.tsnew file mode 100644index 0000000000..d2053c6520--- /dev/null+++ b/apps/desktop/src/main/skillhub/customizationScanHost.ts@@ -0,0 +1,68 @@+import { onQuit } from '../lifecycle';+import type { ScanResult } from './scanner';+import type { SkillListProjectionInput } from './skillListProjection';+import type { SkillScanGrantInput, SkillScanGrants } from './skillScanGrants';+import os from 'node:os';+import path from 'node:path';+import { utilityProcess } from 'electron';+import type { AgentCustomization, ListCustomizationsOptions, ListCustomizationsResult } from '@cindy/maker-core';+import { createLogger } from '../logger';+import { CustomizationScanClient } from './customizationScanClient';++const log = createLogger('skillhub:discovery');+const client = new CustomizationScanClient({+ fork: () => {+ const env: NodeJS.ProcessEnv = {};+ for (const key of [+ 'PATH', 'SystemRoot', 'WINDIR', 'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH',+ 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL',+ ]) {+ if (process.env[key] !== undefined) env[key] = process.env[key];+ }+ return utilityProcess.fork(path.join(__dirname, 'customizationScanProcess.js'), [], {+ serviceName: 'cindy-skill-discovery',+ env,+ cwd: os.tmpdir(),+ stdio: 'ignore',+ });+ },+});++let shutdownRegistered = false;++export async function scanLocalCustomizations(+ engine: AgentCustomization['engine'], options: ListCustomizationsOptions,+): Promise<ListCustomizationsResult> {+ registerShutdown();+ const result = await client.scan(engine, options);+ if (result.errors.length > 0) log.warn('Customization discovery returned errors', { engine, count: result.errors.length });+ return result;+}++function registerShutdown(): void {+ if (!shutdownRegistered) {+ onQuit('skillhub-discovery', () => client.dispose());+ shutdownRegistered = true;+ }+}++/** Projection reads user paths only in the same bounded, killable process. */+export async function projectSkillList(input: SkillListProjectionInput): Promise<ScanResult> {+ registerShutdown();+ return client.request({ kind: 'project', input }, (value): value is ScanResult => {+ const result = value as ScanResult | null;+ return !!result && Array.isArray(result.skills) && Array.isArray(result.sources);+ }, (message) => ({ skills: [], sources: [{ kind: 'skill', scope: 'global', path: '',+ status: { state: 'error', message } }] }));+}++/** Private snapshots remain on Main; renderer/account checks stay in the IPC handler. */+export async function inspectSkillListGrants(input: SkillScanGrantInput): Promise<SkillScanGrants> {+ registerShutdown();+ const result = await client.request({ kind: 'grants', input }, (value): value is SkillScanGrants => {+ const result = value as SkillScanGrants | null;+ return !!result && Array.isArray(result.entries) && Array.isArray(result.records);+ }, (error) => ({ entries: [], records: [], error }));+ if (result.error) throw new Error(result.error);+ return result;+}diff --git a/apps/desktop/src/main/skillhub/customizationScanProcess.ts b/apps/desktop/src/main/skillhub/customizationScanProcess.tsnew file mode 100644index 0000000000..aa983b880a--- /dev/null+++ b/apps/desktop/src/main/skillhub/customizationScanProcess.ts@@ -0,0 +1,45 @@+import { buildSkillList } from './skillListProjection';+import { prepareSkillScanGrants } from './skillScanGrants';+import {+ scanClaudeCustomizations, scanCodexCustomizations, scanPiCustomizations,+} from '@cindy/maker-core/customization-scanner';+import type { CustomizationScanRequest, CustomizationScanResponse } from './customizationScanProtocol';++interface ParentPort {+ postMessage(message: CustomizationScanResponse): void;+ once(event: 'message', listener: (event: { data: CustomizationScanRequest }) => void): void;+}++// A fixed, one-shot utility entry. It has no renderer bridge, credentials,+// managed-plugin resolver or write commands; discovery semantics stay in core.+const parentPort = (process as unknown as { parentPort?: ParentPort }).parentPort;+parentPort?.once('message', async ({ data: request }) => {+ if (!request || typeof request.id !== 'string') return;+ if (request.kind === 'project' || request.kind === 'grants') {+ try {+ const result = request.kind === 'project' ? buildSkillList(request.input) : prepareSkillScanGrants(request.input);+ parentPort.postMessage({ kind: 'result', id: request.id, result });+ } catch {+ parentPort.postMessage({ kind: 'result', id: request.id, result: request.kind === 'project'+ ? { skills: [], sources: [{ kind: 'skill', scope: 'global', path: '', status: { state: 'error', message: 'Skill list projection failed' } }] }+ : { entries: [], records: [], error: 'Skill grant inspection failed' } });+ }+ return;+ }+ if (request.kind !== 'scan') return;+ const scanners = {+ 'claude-code': scanClaudeCustomizations,+ codex: scanCodexCustomizations,+ pi: scanPiCustomizations,+ };+ if (!Object.hasOwn(scanners, request.engine)) return;+ try {+ const result = await scanners[request.engine](request.options);+ parentPort.postMessage({ kind: 'result', id: request.id, result });+ } catch {+ parentPort.postMessage({+ kind: 'result', id: request.id,+ result: { items: [], errors: [{ message: `[${request.engine}] Customization discovery failed` }] },+ });+ }+});diff --git a/apps/desktop/src/main/skillhub/customizationScanProtocol.ts b/apps/desktop/src/main/skillhub/customizationScanProtocol.tsnew file mode 100644index 0000000000..0db437d8e6--- /dev/null+++ b/apps/desktop/src/main/skillhub/customizationScanProtocol.ts@@ -0,0 +1,18 @@+import type { AgentCustomization, ListCustomizationsOptions, ListCustomizationsResult } from '@cindy/maker-core';++export interface EngineScanRequest {+ kind: 'scan';+ id: string;+ engine: AgentCustomization['engine'];+ options: ListCustomizationsOptions;+}++export interface CustomizationScanResponse {+ kind: 'result';+ id: string;+ result: ListCustomizationsResult | import('./scanner').ScanResult | import('./skillScanGrants').SkillScanGrants;+}++export type CustomizationScanRequest = EngineScanRequest+ | { kind: 'project'; id: string; input: import('./skillListProjection').SkillListProjectionInput }+ | { kind: 'grants'; id: string; input: import('./skillScanGrants').SkillScanGrantInput };diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.tsindex 573ecbb05b..cdd41898f9 100644--- a/apps/desktop/src/main/skillhub/registerIpc.ts+++ b/apps/desktop/src/main/skillhub/registerIpc.ts@@ -1,8 +1,9 @@+import { inspectSkillListGrants } from './customizationScanHost';import fs from 'node:fs';import { t } from '../i18n.js';import { throwIpcError } from '../utils/ipcValidate';-import { isCindyLearnSkillEnabled, setCindySkillEnabled } from './activationPreferences';-import { inspectLocalSkillTarget, isLocalSkillTargetCurrent, isPluginManagedSkillPath, type LocalSkillTarget } from './localSkillTarget';+import { isCindyLearnSkillEnabledForListing, setCindySkillEnabled } from './activationPreferences';+import { isLocalSkillTargetCurrent, isPluginManagedSkillPath, type LocalSkillTarget } from './localSkillTarget';import { tryAcquireSkillInstallLock } from './installLock';import { randomUUID } from 'node:crypto';import path from 'node:path';@@ -230,71 +231,18 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {});};- const rememberScannedSkillRoots = (+ const rememberScannedSkillRoots = async (event: Electron.IpcMainInvokeEvent,ownerId: string,+ generation: number,skills: import('./scanner').Skill[],) => {- const entries: ScannedSkillGrant['entries'] = [];- const seenEntries = new Set<string>();- for (const skill of skills) {- const skillProjectRootKey = skill.scope === 'project'- ? projectRootKey(skill.projectRoot)- : undefined;- if (skill.scope === 'project' && !skillProjectRootKey) continue;- // A built-in discovered through ~/.agents/skills still resolves to the- // app-owned physical root. Keep Main's built-in attestation instead of- // downgrading it to an ordinary discovery grant, otherwise the later- // read handlers re-apply the lexical user-skill whitelist and reject the- // exact path that the scan returned.- if (skill.builtIn === true) {- const root = configuredBuiltInRoot(skill.absolutePath);- const entryKey = root ? `${root}\0built-in` : null;- if (root && entryKey && !seenEntries.has(entryKey)) {- seenEntries.add(entryKey);- entries.push({ root, builtIn: true });- }- continue;- }- // discoveredPath preserves an allowed lexical alias when absolutePath was- // canonicalized through a parent-directory symlink.- for (const candidate of [skill.discoveredPath, skill.absolutePath]) {- const root = resolveExistingSkillPathForGrant(candidate);- if (root) {- const entryKey = `${root}\0${skillProjectRootKey ?? ''}`;- if (!seenEntries.has(entryKey)) {- seenEntries.add(entryKey);- entries.push({- root,- ...(skillProjectRootKey ? { projectRootKey: skillProjectRootKey } : {}),- });- }- break;- }- }- }- scannedSkillRootsBySender.set(event.sender.id, { ownerId, entries });- const records = skills.flatMap((skill) => {- if (skill.kind !== 'skill') return [];- try {- return [{ skill, physicalIdentity: physicalIdentity(skill.absolutePath),- target: inspectLocalSkillTarget(skill.absolutePath, skill.discoveryPaths ?? [skill.discoveredPath], options.getManagedSkillRoots()) }];- } catch { return []; }- });- const aliasesByIdentity = new Map<string, Set<string>>();- for (const record of records) {- const aliases = aliasesByIdentity.get(record.physicalIdentity) ?? new Set<string>();- for (const alias of record.target?.aliases ?? []) aliases.add(alias);- aliasesByIdentity.set(record.physicalIdentity, aliases);- }- for (const record of records) {- // Removing the physical entity must clean every scanned scope's links.- // Removing an external import keeps its scope-local operation/aliases.- if (record.target && !record.target.linkOnly) {- record.target.aliases = [...aliasesByIdentity.get(record.physicalIdentity)!];- }- }- localSkillsBySender.set(event.sender.id, records);+ const snapshot = await inspectSkillListGrants({ skills,+ managedSkillRoots: options.getManagedSkillRoots(), builtInSkills: options.getBuiltInSkills?.() ?? [] });+ if (scanGenerationBySender.get(event.sender.id) !== generation+ || isAppSessionBoundaryPending() || getCurrentDataOwnerId() !== ownerId) return;+ scannedSkillRootsBySender.set(event.sender.id, { ownerId, entries: snapshot.entries });+ localSkillsBySender.set(event.sender.id, snapshot.records);};const findScannedSkillGrant = async (@@ -369,13 +317,6 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {&& !path.isAbsolute(relative));};- const configuredBuiltInRoot = (source: string): string | null => {- const physicalSource = realPathOrResolved(source);- const descriptor = (options.getBuiltInSkills?.() ?? []).find((skill) => (- realPathOrResolved(skill.absolutePath) === physicalSource- ));- return descriptor ? realPathOrResolved(descriptor.absolutePath) : null;- };const isBuiltInSkillPath = (targetPath: string): boolean => ((options.getBuiltInSkills?.() ?? []).some((skill) => {const root = realPathOrResolved(skill.absolutePath);@@ -507,6 +448,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {// A new scan attempt supersedes the previous snapshot immediately. If// discovery fails, stale paths must not remain authorized.scannedSkillRootsBySender.delete(event.sender.id);+ localSkillsBySender.delete(event.sender.id);try {const scanOwnerId = getCurrentDataOwnerId();if (!scanOwnerId || isAppSessionBoundaryPending()) {@@ -527,7 +469,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {&& !isAppSessionBoundaryPending()&& getCurrentDataOwnerId() === scanOwnerId) {- rememberScannedSkillRoots(event, scanOwnerId, result.skills);+ await rememberScannedSkillRoots(event, scanOwnerId, scanGeneration, result.skills);+ if (scanGenerationBySender.get(event.sender.id) !== scanGeneration+ || isAppSessionBoundaryPending() || getCurrentDataOwnerId() !== scanOwnerId) {+ return { success: true, ...result };+ }const pendingCleanups = installService.listPendingUninstallCleanups();for (const { token } of pendingCleanups) {cleanupGrants.set(cleanupGrantKey(event.sender.id, token), { ownerId: scanOwnerId, senderId: event.sender.id });@@ -536,17 +482,17 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {success: true,...result,pendingCleanups,- learnSkillEnabled: isCindyLearnSkillEnabled(),+ learnSkillEnabled: result.learnSkillEnabled ?? isCindyLearnSkillEnabledForListing(options.getBuiltInSkills?.() ?? []),};}- return { success: true, ...result, learnSkillEnabled: isCindyLearnSkillEnabled() };+ return { success: true, ...result, learnSkillEnabled: result.learnSkillEnabled ?? isCindyLearnSkillEnabledForListing(options.getBuiltInSkills?.() ?? []) };} catch (err) {const message = err instanceof Error ? err.message : String(err);log.error('[skillhub:scan] failed:', err);return {success: false,error: message,- learnSkillEnabled: isCindyLearnSkillEnabled(),+ learnSkillEnabled: isCindyLearnSkillEnabledForListing(options.getBuiltInSkills?.() ?? []),};}},diff --git a/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts b/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.tsindex a213db8e76..426fe180bd 100644--- a/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts+++ b/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts@@ -420,3 +420,23 @@ describe('并发安全', () => {expect(Object.keys(manifest.installs)).toHaveLength(installCount);});});++describe('read-only scan listing', () => {+ it('lists backup metadata without probing install paths or restoring/writing manifests', async () => {+ const installPath = path.join(userDataDir, 'unresponsive-volume', '.agents', 'skills', 'offline');+ const entry = makeEntry({ catalogScope: 'market', catalogScopeMigrated: true });+ fs.mkdirSync(path.dirname(backupManifestPath('offline')), { recursive: true });+ fs.writeFileSync(backupManifestPath('offline'), JSON.stringify({+ schemaVersion: 1, skillName: 'offline', installs: { [installPath]: entry },+ }));+ const access = vi.spyOn(fs.promises, 'access');+ const write = vi.spyOn(fs.promises, 'writeFile');+ try {+ const listed = await listAllInstalls({ readOnly: true });+ expect(listed).toEqual([{ skillName: 'offline', installPath, entry }]);+ expect(access).not.toHaveBeenCalled();+ expect(write).not.toHaveBeenCalled();+ expect(fs.existsSync(manifestPath('offline'))).toBe(false);+ } finally { access.mockRestore(); write.mockRestore(); }+ });+});diff --git a/apps/desktop/src/main/skillhub/registry/registryService.ts b/apps/desktop/src/main/skillhub/registry/registryService.tsindex 249d64f639..d5df2ff62c 100644--- a/apps/desktop/src/main/skillhub/registry/registryService.ts+++ b/apps/desktop/src/main/skillhub/registry/registryService.ts@@ -243,13 +243,16 @@ export async function getInstall(/*** 一次性扫描 manifests/ 目录,展平所有 install 记录。* 单文件 JSON 损坏 → 跳过 + 记日志,不影响其他文件读取+ * readOnly 仅消费 profile 内主/备份元数据,不探测 installPath 或执行恢复写入。*/-export async function listAllInstalls(): Promise<+export async function listAllInstalls(options: { readOnly?: boolean } = {}): Promise<Array<{ skillName: string; installPath: string; entry: StoredInstall }>> {const filesByName = new Map<string, StoredManifest>();for (const { skillName } of await manifestIO.listAllFiles()) {- const manifest = await withLock(skillName, () => readManifestWithBackup(skillName)).catch((err) => {+ const manifest = await (options.readOnly+ ? manifestIO.readFile(skillName).then((value) => value ? migrateStoredManifest(value).manifest : null)+ : withLock(skillName, () => readManifestWithBackup(skillName))).catch((err) => {log.warn(`read registry manifest failed for ${skillName}:`, err);return null;});@@ -257,7 +260,9 @@ export async function listAllInstalls(): Promise<}for (const skillName of await listBackupSkillNames()) {if (filesByName.has(skillName)) continue;- const restored = await withLock(skillName, () => readManifestWithBackup(skillName)).catch((err) => {+ const restored = await (options.readOnly+ ? readBackupManifest(skillName)+ : withLock(skillName, () => readManifestWithBackup(skillName))).catch((err) => {log.warn(`restore registry from backup failed for ${skillName}:`, err);return null;});diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.tsindex 00e435b50d..aa26232e0f 100644--- a/apps/desktop/src/main/skillhub/scanner.ts+++ b/apps/desktop/src/main/skillhub/scanner.ts@@ -1,7 +1,8 @@-import { isCindySkillEnabled, renameSkillWithActivation } from './activationPreferences';+import { isLexicallyAllowedSkillPath, isPathWithin, resolveAllowedExistingSkillPath, resolveExistingSkillPathForGrant } from './skillPathPolicy';+export { resolveExistingSkillPathForGrant } from './skillPathPolicy';+import { readDisabledSkillPathsForListing, renameSkillWithActivation } from './activationPreferences';import { skillInstallLockKey, tryAcquireSkillInstallLock } from './installLock';import { acquireSharedSkillMutationLease, type SkillMutationRelease } from './sharedMutationLease';-import { inspectLocalSkillTarget, isPluginManagedSkillPath } from './localSkillTarget';/*** SkillHub Scanner — 商店层 (registry / market) 视图组装。*@@ -18,15 +19,15 @@ import { inspectLocalSkillTarget, isPluginManagedSkillPath } from './localSkillT* Read-only for scan; write helpers gated by SKILL_PATH_WHITELIST.*/-import { createHash, randomUUID } from 'node:crypto';+import { randomUUID } from 'node:crypto';import fs from 'node:fs';-import os from 'node:os';import path from 'node:path';import matter from 'gray-matter';-import type { AgentCustomization, Maker, PiRuntimeCapabilityStatus } from '@cindy/maker-core';+import type { ListCustomizationsResult, Maker, PiRuntimeCapabilityStatus } from '@cindy/maker-core';import type { BuiltInSkillDescriptor } from '../maker-host/built-in-skills';import { registryService, type StoredInstall } from './registry';-import { reconcileScannedInstall } from './registryReconciliation';+import { app } from 'electron';+import { projectSkillList } from './customizationScanHost';import { isIgnoredSkillPackagePath } from './packageIgnore';import { createLogger } from '../logger';@@ -133,6 +134,8 @@ export interface SourceReport {}export interface ScanResult {+ /** Existing IPC flag, derived without resolving user aliases on Main. */+ learnSkillEnabled?: boolean;skills: Skill[];sources: SourceReport[];}@@ -153,84 +156,11 @@ export interface ProjectInput {* 本函数只负责:* 1. 把 AgentCustomization 转成 renderer 期望的 SkillhubSkill 形态 (补 id / projectHash)* 2. join registry: 装机记录 (StoredInstall) 是商店概念, 不在 maker 范围- * 3. orphan cleanup: registry 有但盘上没了的, 异步删+ * 3. 列表只读,不触发 orphan 删除或发现链接维护;写操作由显式安装/卸载负责** sources[] 字段保留兼容 renderer (但当前 renderer 只存不读), 用 maker 的 errors 还原 'error'* 状态; ok 状态简化为按 (kind/scope) 聚合 count。失败不抛, 单个 errors 收进 sources。*/-/**- * Codex/Pi scope → SkillScope 映射。- * Codex/Pi: 'user'|'system'|'admin' → 'global', 'repo' → 'project'。- * Claude: 已经是 'global'|'project',直通。- */-function normalizeScope(engine: string, rawScope: string): SkillScope {- if (engine === 'codex' || engine === 'pi') {- return rawScope === 'repo' ? 'project' : 'global';- }- return rawScope as SkillScope;-}--function realPathOrNormalized(value: string): string {- try {- return fs.realpathSync(value);- } catch {- return path.normalize(value);- }-}--function normalizeSkillEntityPath(c: AgentCustomization): AgentCustomization {- if (- c.kind === 'skill' &&- path.basename(c.absolutePath).toLowerCase() === 'skill.md'- ) {- return {- ...c,- absolutePath: path.dirname(c.absolutePath),- mdPath: c.mdPath ?? c.absolutePath,- };- }- return c;-}--function filterSkillPackageFileEntries(rootDir: string, entries: SkillFileEntry[]): SkillFileEntry[] {- return entries.filter((entry) => {- const childPath = path.join(rootDir, entry.name);- return !isIgnoredSkillPackagePath(skillPackageRelPath(rootDir, childPath, entry.name));- });-}--function readBuiltInCustomization(descriptor: BuiltInSkillDescriptor): AgentCustomization {- const skillFile = path.join(descriptor.absolutePath, 'SKILL.md');- const raw = fs.readFileSync(skillFile, 'utf8');- let frontmatter: Record<string, unknown> | undefined;- let description: string | undefined;- let parseError: string | undefined;- try {- const parsed = matter(raw);- frontmatter = parsed.data;- if (typeof parsed.data.description === 'string') {- description = parsed.data.description.trim().slice(0, 500) || undefined;- }- } catch (error) {- parseError = error instanceof Error ? error.message : String(error);- }- const files = fs.readdirSync(descriptor.absolutePath, { withFileTypes: true })- .sort((a, b) => a.name.localeCompare(b.name))- .map((entry) => ({ name: entry.name, kind: entry.isDirectory() ? 'dir' as const : 'file' as const }));- return {- engine: 'claude-code',- kind: 'skill',- scope: 'global',- name: descriptor.name,- description,- absolutePath: descriptor.absolutePath,- mdPath: skillFile,- files,- frontmatter,- parseError,- };-}-export async function scanAllSkills(params: { projects?: ProjectInput[] },maker: Maker,@@ -238,248 +168,23 @@ export async function scanAllSkills(builtInSkills: readonly BuiltInSkillDescriptor[] = [],): Promise<ScanResult> {const projects = params.projects ?? [];- const projectByWorkingDir = new Map<string, ProjectInput>();- const projectsByCanonicalWorkingDir = new Map<string, ProjectInput[]>();- const workingDirs: string[] = [];- for (const p of projects) {- if (p.projectRoot && path.isAbsolute(p.projectRoot)) {- workingDirs.push(p.projectRoot);- projectByWorkingDir.set(path.normalize(p.projectRoot), p);- const canonicalRoot = realPathOrNormalized(p.projectRoot);- const aliases = projectsByCanonicalWorkingDir.get(canonicalRoot) ?? [];- aliases.push(p);- projectsByCanonicalWorkingDir.set(canonicalRoot, aliases);- }- }- const projectForWorkingDir = (workingDir?: string): ProjectInput | undefined => {- if (!workingDir) return undefined;- const lexicalMatch = projectByWorkingDir.get(path.normalize(workingDir));- if (lexicalMatch) return lexicalMatch;- const canonicalMatches = projectsByCanonicalWorkingDir.get(realPathOrNormalized(workingDir));- return canonicalMatches?.length === 1 ? canonicalMatches[0] : undefined;- };-- let listed: { items: AgentCustomization[]; errors: Array<{ path?: string; message: string }> };+ let listed: ListCustomizationsResult;try {listed = await maker.listCustomizations({- workingDirs,+ workingDirs: projects.filter((p) => p.projectRoot && path.isAbsolute(p.projectRoot)).map((p) => p.projectRoot),forceReload: false,});} catch (err) {log.error('maker.listCustomizations failed', err);listed = { items: [], errors: [{ message: err instanceof Error ? err.message : String(err) }] };}- const discoveredEnginesByRealPath = new Map<- string,- Map<Skill['engine'], Skill['linkedEngines'][number]>- >();- for (const rawItem of listed.items) {- const item = normalizeSkillEntityPath(rawItem);- if (item.kind !== 'skill') continue;- const realPath = realPathOrNormalized(item.absolutePath);- const engines = discoveredEnginesByRealPath.get(realPath) ?? new Map();- if (!engines.has(item.engine)) {- engines.set(item.engine, {- engine: item.engine,- label: item.engine === 'claude-code' ? 'Claude' : item.engine === 'codex' ? 'Codex' : 'Pi',- ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),- });- }- discoveredEnginesByRealPath.set(realPath, engines);- }- const builtInRealPaths = new Set<string>();- for (const descriptor of builtInSkills) {- try {- const customization = readBuiltInCustomization(descriptor);- const realPath = realPathOrNormalized(customization.absolutePath);- builtInRealPaths.add(realPath);- listed.items.push(customization);- } catch (error) {- listed.errors.push({- path: descriptor.absolutePath,- message: `Could not read built-in Skill ${descriptor.name}: ${error instanceof Error ? error.message : String(error)}`,- });- }- }-- // ── 过滤 + 跨引擎去重 ──────────────────────────────────────────────────────- // ~/.agents/skills/ 是 agent-agnostic 的共享路径(canonical),实体文件在此。- // 当同一逻辑 skill 被多个来源发现时,优先保留公共路径作为显示路径。- const HIDDEN_SCOPES = new Set(['system', 'admin']);- const isBackupPath = (p: string) => /\.bak\.\d+$/.test(path.basename(p));- const isGenericPath = (p: string) => /\/\.agents\/skills\//.test(p.replace(/\\/g, '/'));- const seenItems = new Map<string, { winner: AgentCustomization; all: AgentCustomization[]; realPath: string }>();- for (const item of listed.items) {- const c = normalizeSkillEntityPath(item);- if (HIDDEN_SCOPES.has(c.scope)) continue;- if (isBackupPath(c.absolutePath)) continue;- const realKey = realPathOrNormalized(c.absolutePath);- const normalizedScope = normalizeScope(c.engine, c.scope);- const project = normalizedScope === 'project' ? projectForWorkingDir(c.workingDir) : undefined;- const dedupeKey = project ? `${realKey}\0project:${project.hash}` : realKey;- const existing = seenItems.get(dedupeKey);- if (existing) {- existing.all.push(c);- if (!isGenericPath(existing.winner.absolutePath) && isGenericPath(c.absolutePath)) {- existing.winner = c;- }- continue;- }- seenItems.set(dedupeKey, { winner: c, all: [c], realPath: realKey });- }- const deduped = Array.from(seenItems.values());-- // ── AgentCustomization → SkillhubSkill ──────────────────────────────────────- const candidates = deduped.map(({ winner: c, all, realPath }) => {- const engine = c.engine as Skill['engine'];- const project = projectForWorkingDir(c.workingDir);- const projectHash = project?.hash;- // skill 类型的 identity 始终是目录名(= market slug),不依赖 frontmatter name。- // Codex RPC 可能从 frontmatter 取 name 导致与目录名不一致,统一用 basename(realPath)。- const canonicalName = c.kind === 'skill' ? path.basename(realPath) : c.name;- // Codex RPC may return 'repo' scope for user-level skills when homedir is- // used as fallback cwd. If the workingDir doesn't map to a tracked project,- // treat the skill as global — it's effectively user-level.- const rawScope = normalizeScope(engine, c.scope);- const scope: SkillScope = (rawScope === 'project' && !projectHash) ? 'global' : rawScope;- const urlKey = scope === 'global'- ? `${c.kind}:global:${canonicalName}`- : `${c.kind}:project:${projectHash}:${canonicalName}`;- return { c, all, realPath, engine, project, projectHash, canonicalName, scope, urlKey };- });- const identityCounts = new Map<string, number>();- for (const candidate of candidates) {- const identity = `${candidate.engine}:${candidate.urlKey}`;- identityCounts.set(identity, (identityCounts.get(identity) ?? 0) + 1);- }-- const skills: Skill[] = candidates.map(({- c,- all,- realPath,- engine,- project,- projectHash,- canonicalName,- scope,- urlKey,- }) => {- const builtIn = builtInRealPaths.has(realPath);- const hasIdentityCollision = (identityCounts.get(`${engine}:${urlKey}`) ?? 0) > 1;- // Pi entries are new to this SkillHub projection. Give them a path-derived- // identity even when currently unique, so adding/removing a same-name source- // never changes the surviving Pi entry's React/storage identity.- const sourceKey = engine === 'pi' || hasIdentityCollision- ? createHash('sha256').update(realPath).digest('hex')- : undefined;- const id = `${engine}:${urlKey}${sourceKey ? `:source:${sourceKey}` : ''}`;-- const engineSet = new Map<Skill['engine'], Skill['linkedEngines'][number]>();- for (const item of all) {- const eng = item.engine;- if (!engineSet.has(eng)) {- engineSet.set(eng, {- engine: eng,- label: eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : 'Pi',- ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),- });- }- }- const linkedEngines = builtIn- ? Array.from(discoveredEnginesByRealPath.get(realPath)?.values() ?? [])- : Array.from(engineSet.values());-- const skill: Skill = {- id,- urlKey,- ...(sourceKey ? { sourceKey } : {}),- ...(hasIdentityCollision ? { requiresSourceKey: true } : {}),- engine,- linkedEngines,- kind: c.kind as SkillKind,- scope,- name: canonicalName,- description: c.description,- absolutePath: realPath,- discoveredPath: c.absolutePath,- mdPath: c.mdPath ?? realPath,- files: c.kind === 'skill'- ? filterSkillPackageFileEntries(realPath, (c.files ?? []) as SkillFileEntry[])- : [],- frontmatter: c.frontmatter,- parseError: c.parseError,- registryEntry: null, // 下面 join 阶段填- ...(c.kind === 'skill' ? (() => {- const discoveryPaths = [...new Set(all.map((item) => item.absolutePath))];- const target = inspectLocalSkillTarget(realPath, discoveryPaths, managedSkillRoots);- return { cindyEnabled: isCindySkillEnabled(realPath), discoveryPaths,- ...(builtIn ? { builtIn: true } : {}),- managedByPlugin: isPluginManagedSkillPath(realPath, managedSkillRoots),- canUninstall: !builtIn && target !== null, uninstallLinkOnly: target?.linkOnly ?? false };- })() : {}),- ...(project ? { projectRoot: project.projectRoot } : {}),- ...(projectHash ? { projectHash } : {}),- };- return skill;- });-- // ── join registry ──────────────────────────────────────────────────────────- let registryEntries: Awaited<ReturnType<typeof registryService.listAllInstalls>>;- try {- registryEntries = await registryService.listAllInstalls();- } catch (err) {- log.warn('registry list failed, fallback to empty:', err);- registryEntries = [];- }- const registryByPath = new Map<string, (typeof registryEntries)[number]>();- const registryLiveKeys = new Map<string, string>();- for (const r of registryEntries) {- const installPathKey = path.normalize(r.installPath);- registryByPath.set(installPathKey, r);- registryLiveKeys.set(installPathKey, installPathKey);- try {- const realInstallPathKey = path.normalize(fs.realpathSync(r.installPath));- registryByPath.set(realInstallPathKey, r);- registryLiveKeys.set(installPathKey, realInstallPathKey);- } catch {- // If the path no longer exists, keep the original key so orphan cleanup- // below can still test access(r.installPath) and remove stale records.- }- }- const liveRealPaths = new Set<string>();- for (const s of skills) {- if (s.kind !== 'skill') continue;- let resolved: string;- try {- resolved = fs.realpathSync(s.absolutePath);- } catch {- resolved = s.absolutePath;- }- const normPath = path.normalize(resolved);- // path 是物理唯一标识;允许 registry skillName 和 scanner directory name 不一致- // (历史数据或 frontmatter name 与目录名不同步时会出现)- const registered = registryByPath.get(normPath);- s.registryEntry = registered?.entry ?? null;- s.registrySkillName = registered?.skillName;- liveRealPaths.add(normPath);- }-- // Maintenance uses the same mutation protocol as install/uninstall and- // revalidates each registry/source snapshot after acquiring the lease.- void Promise.all(registryEntries.map((record) => {- const key = path.normalize(record.installPath);- return reconcileScannedInstall(record, !liveRealPaths.has(registryLiveKeys.get(key) ?? key));- }));-- // ── sources[] 兼容 (renderer 只存不读) ─────────────────────────────────────- const sources: SourceReport[] = listed.errors.map((e) => ({- kind: 'skill',- scope: 'global',- path: e.path ?? '',- status: { state: 'error', message: e.message },- }));-- return { skills, sources };+ let registryEntries: Awaited<ReturnType<typeof registryService.listAllInstalls>> = [];+ try { registryEntries = await registryService.listAllInstalls({ readOnly: true }); }+ catch (err) { log.warn('registry list failed, fallback to empty:', err); }+ // Listing must never start filesystem maintenance. Install/uninstall keep+ // their existing mutation leases and final on-disk validation in Main.+ return projectSkillList({ projects, listed, registryEntries, managedSkillRoots, builtInSkills,+ disabledPaths: readDisabledSkillPathsForListing(), userDataDir: app.getPath('userData'), appDataDir: app.getPath('appData') });}/**@@ -636,59 +341,6 @@ const EDIT_SIZE_CAP_WRITE = 1024 * 1024; // 1 MB write cap (defensive against pa// 统一白名单:所有引擎的 skill/command/agent 目录共用。// 新增引擎时只需在此 regex 加一个分支。-const SKILL_PATH_WHITELIST = /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills|pi\/skills)|codex-home\/skills)\//;--function isLexicallyAllowedSkillPath(absolutePath: string): boolean {- // path.resolve 解析 .. 和 . 段,防止遍历绕过白名单- const norm = path.resolve(absolutePath).replace(/\\/g, '/');- return SKILL_PATH_WHITELIST.test(norm);-}--function isPathWithin(root: string, candidate: string): boolean {- const relative = path.relative(root, candidate);- return relative === '' || (- relative !== '..'- && !relative.startsWith(`..${path.sep}`)- && !path.isAbsolute(relative)- );-}--/**- * Resolve the final existing target before Main performs IO. Project-owned- * `.pi/skills` paths get an extra physical boundary: neither the source root- * nor a child symlink may escape the project. Other roots keep supporting the- * existing global compatibility symlinks used by shared skill installs.- */-function resolveAllowedExistingSkillPath(absolutePath: string): string | null {- if (!isLexicallyAllowedSkillPath(absolutePath)) return null;- const lexicalPath = path.resolve(absolutePath);- let realTarget: string;- try {- realTarget = fs.realpathSync.native(lexicalPath);- } catch {- return null;- }-- const normalized = lexicalPath.replace(/\\/g, '/');- const marker = '/.pi/skills/';- const markerIndex = normalized.indexOf(marker);- if (markerIndex < 0) return realTarget;-- const lexicalSkillRoot = path.normalize(normalized.slice(0, markerIndex + marker.length - 1));- const lexicalProjectRoot = path.dirname(path.dirname(lexicalSkillRoot));- try {- const realProjectRoot = fs.realpathSync.native(lexicalProjectRoot);- const realSkillRoot = fs.realpathSync.native(lexicalSkillRoot);- if (- !isPathWithin(realProjectRoot, realSkillRoot)- || !isPathWithin(realSkillRoot, realTarget)- ) return null;- } catch {- return null;- }- return realTarget;-}-/*** Read-only built-ins can live outside the user-facing discovery whitelist.* Main may pass an attested physical root from the sender's latest scan; keep@@ -715,11 +367,6 @@ function resolveReadableExistingSkillPath(* grant. This deliberately reuses the same lexical whitelist and physical* symlink boundary as the eventual read/write operation.*/-export function resolveExistingSkillPathForGrant(absolutePath: string): string | null {- if (!absolutePath || !path.isAbsolute(absolutePath)) return null;- return resolveAllowedExistingSkillPath(absolutePath);-}-/** Return whether an existing target belongs to one of the sender's scanned roots. */export function isExistingSkillPathGranted(absolutePath: string,diff --git a/apps/desktop/src/main/skillhub/skillListProjection.ts b/apps/desktop/src/main/skillhub/skillListProjection.tsnew file mode 100644index 0000000000..8ed21e5d04--- /dev/null+++ b/apps/desktop/src/main/skillhub/skillListProjection.ts@@ -0,0 +1,318 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';+import matter from 'gray-matter';+import type { AgentCustomization, ListCustomizationsResult } from '@cindy/maker-core';+import type { BuiltInSkillDescriptor } from '../maker-host/built-in-skills';+import { canonicalBuiltInSkillActivationPath } from '../maker-host/built-in-skill-activation';+import type { StoredInstall } from './registry/types';+import type { ProjectInput, ScanResult, Skill, SkillFileEntry, SkillScope, SkillKind, SourceReport } from './scanner';+import { inspectLocalSkillTarget, isPluginManagedSkillPath } from './localSkillTarget';+import { isIgnoredSkillPackagePath } from './packageIgnore';++/** Read-only list projection. Runs only in the bounded discovery process. */+export interface SkillListProjectionInput {+ projects: ProjectInput[];+ listed: ListCustomizationsResult;+ registryEntries: Array<{ skillName: string; installPath: string; entry: StoredInstall }>;+ managedSkillRoots: readonly string[];+ builtInSkills: readonly BuiltInSkillDescriptor[];+ disabledPaths: readonly string[];+ userDataDir: string;+ appDataDir: string;+}++function activationKey(source: string, userDataDir: string, appDataDir: string): string {+ let resolved = realPathOrNormalized(source);+ if (path.basename(resolved).toLowerCase() === 'skill.md') resolved = path.dirname(resolved);+ resolved = canonicalBuiltInSkillActivationPath(resolved, userDataDir, appDataDir);+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;+}++function skillPackageRelPath(root: string, child: string, fallback: string): string {+ return path.relative(root, child).replace(/\\/g, '/') || fallback;+}++function normalizeScope(engine: string, rawScope: string): SkillScope {+ if (engine === 'codex' || engine === 'pi') {+ return rawScope === 'repo' ? 'project' : 'global';+ }+ return rawScope as SkillScope;+}++function realPathOrNormalized(value: string): string {+ try {+ return fs.realpathSync(value);+ } catch {+ return path.normalize(value);+ }+}++function normalizeSkillEntityPath(c: AgentCustomization): AgentCustomization {+ if (+ c.kind === 'skill' &&+ path.basename(c.absolutePath).toLowerCase() === 'skill.md'+ ) {+ return {+ ...c,+ absolutePath: path.dirname(c.absolutePath),+ mdPath: c.mdPath ?? c.absolutePath,+ };+ }+ return c;+}++function filterSkillPackageFileEntries(rootDir: string, entries: SkillFileEntry[]): SkillFileEntry[] {+ return entries.filter((entry) => {+ const childPath = path.join(rootDir, entry.name);+ return !isIgnoredSkillPackagePath(skillPackageRelPath(rootDir, childPath, entry.name));+ });+}++function readBuiltInCustomization(descriptor: BuiltInSkillDescriptor): AgentCustomization {+ const skillFile = path.join(descriptor.absolutePath, 'SKILL.md');+ const raw = fs.readFileSync(skillFile, 'utf8');+ let frontmatter: Record<string, unknown> | undefined;+ let description: string | undefined;+ let parseError: string | undefined;+ try {+ const parsed = matter(raw);+ frontmatter = parsed.data;+ if (typeof parsed.data.description === 'string') {+ description = parsed.data.description.trim().slice(0, 500) || undefined;+ }+ } catch (error) {+ parseError = error instanceof Error ? error.message : String(error);+ }+ const files = fs.readdirSync(descriptor.absolutePath, { withFileTypes: true })+ .sort((a, b) => a.name.localeCompare(b.name))+ .map((entry) => ({ name: entry.name, kind: entry.isDirectory() ? 'dir' as const : 'file' as const }));+ return {+ engine: 'claude-code',+ kind: 'skill',+ scope: 'global',+ name: descriptor.name,+ description,+ absolutePath: descriptor.absolutePath,+ mdPath: skillFile,+ files,+ frontmatter,+ parseError,+ };+}++export function buildSkillList(input: SkillListProjectionInput): ScanResult {+ const { projects, listed, managedSkillRoots, builtInSkills, registryEntries, disabledPaths, userDataDir, appDataDir } = input;+ const projectByWorkingDir = new Map<string, ProjectInput>();+ const projectsByCanonicalWorkingDir = new Map<string, ProjectInput[]>();+ const workingDirs: string[] = [];+ for (const p of projects) {+ if (p.projectRoot && path.isAbsolute(p.projectRoot)) {+ workingDirs.push(p.projectRoot);+ projectByWorkingDir.set(path.normalize(p.projectRoot), p);+ const canonicalRoot = realPathOrNormalized(p.projectRoot);+ const aliases = projectsByCanonicalWorkingDir.get(canonicalRoot) ?? [];+ aliases.push(p);+ projectsByCanonicalWorkingDir.set(canonicalRoot, aliases);+ }+ }+ const projectForWorkingDir = (workingDir?: string): ProjectInput | undefined => {+ if (!workingDir) return undefined;+ const lexicalMatch = projectByWorkingDir.get(path.normalize(workingDir));+ if (lexicalMatch) return lexicalMatch;+ const canonicalMatches = projectsByCanonicalWorkingDir.get(realPathOrNormalized(workingDir));+ return canonicalMatches?.length === 1 ? canonicalMatches[0] : undefined;+ };++ const discoveredEnginesByRealPath = new Map<+ string,+ Map<Skill['engine'], Skill['linkedEngines'][number]>+ >();+ for (const rawItem of listed.items) {+ const item = normalizeSkillEntityPath(rawItem);+ if (item.kind !== 'skill') continue;+ const realPath = realPathOrNormalized(item.absolutePath);+ const engines = discoveredEnginesByRealPath.get(realPath) ?? new Map();+ if (!engines.has(item.engine)) {+ engines.set(item.engine, {+ engine: item.engine,+ label: item.engine === 'claude-code' ? 'Claude' : item.engine === 'codex' ? 'Codex' : 'Pi',+ ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),+ });+ }+ discoveredEnginesByRealPath.set(realPath, engines);+ }+ const builtInRealPaths = new Set<string>();+ for (const descriptor of builtInSkills) {+ try {+ const customization = readBuiltInCustomization(descriptor);+ const realPath = realPathOrNormalized(customization.absolutePath);+ builtInRealPaths.add(realPath);+ listed.items.push(customization);+ } catch (error) {+ listed.errors.push({+ path: descriptor.absolutePath,+ message: `Could not read built-in Skill ${descriptor.name}: ${error instanceof Error ? error.message : String(error)}`,+ });+ }+ }++ // ── 过滤 + 跨引擎去重 ──────────────────────────────────────────────────────+ // ~/.agents/skills/ 是 agent-agnostic 的共享路径(canonical),实体文件在此。+ // 当同一逻辑 skill 被多个来源发现时,优先保留公共路径作为显示路径。+ const HIDDEN_SCOPES = new Set(['system', 'admin']);+ const isBackupPath = (p: string) => /\.bak\.\d+$/.test(path.basename(p));+ const isGenericPath = (p: string) => /\/\.agents\/skills\//.test(p.replace(/\\/g, '/'));+ const seenItems = new Map<string, { winner: AgentCustomization; all: AgentCustomization[]; realPath: string }>();+ for (const item of listed.items) {+ const c = normalizeSkillEntityPath(item);+ if (HIDDEN_SCOPES.has(c.scope)) continue;+ if (isBackupPath(c.absolutePath)) continue;+ const realKey = realPathOrNormalized(c.absolutePath);+ const normalizedScope = normalizeScope(c.engine, c.scope);+ const project = normalizedScope === 'project' ? projectForWorkingDir(c.workingDir) : undefined;+ const dedupeKey = project ? `${realKey}\0project:${project.hash}` : realKey;+ const existing = seenItems.get(dedupeKey);+ if (existing) {+ existing.all.push(c);+ if (!isGenericPath(existing.winner.absolutePath) && isGenericPath(c.absolutePath)) {+ existing.winner = c;+ }+ continue;+ }+ seenItems.set(dedupeKey, { winner: c, all: [c], realPath: realKey });+ }+ const deduped = Array.from(seenItems.values());++ // ── AgentCustomization → SkillhubSkill ──────────────────────────────────────+ const candidates = deduped.map(({ winner: c, all, realPath }) => {+ const engine = c.engine as Skill['engine'];+ const project = projectForWorkingDir(c.workingDir);+ const projectHash = project?.hash;+ // skill 类型的 identity 始终是目录名(= market slug),不依赖 frontmatter name。+ // Codex RPC 可能从 frontmatter 取 name 导致与目录名不一致,统一用 basename(realPath)。+ const canonicalName = c.kind === 'skill' ? path.basename(realPath) : c.name;+ // Codex RPC may return 'repo' scope for user-level skills when homedir is+ // used as fallback cwd. If the workingDir doesn't map to a tracked project,+ // treat the skill as global — it's effectively user-level.+ const rawScope = normalizeScope(engine, c.scope);+ const scope: SkillScope = (rawScope === 'project' && !projectHash) ? 'global' : rawScope;+ const urlKey = scope === 'global'+ ? `${c.kind}:global:${canonicalName}`+ : `${c.kind}:project:${projectHash}:${canonicalName}`;+ return { c, all, realPath, engine, project, projectHash, canonicalName, scope, urlKey };+ });+ const identityCounts = new Map<string, number>();+ for (const candidate of candidates) {+ const identity = `${candidate.engine}:${candidate.urlKey}`;+ identityCounts.set(identity, (identityCounts.get(identity) ?? 0) + 1);+ }++ const skills: Skill[] = candidates.map(({+ c,+ all,+ realPath,+ engine,+ project,+ projectHash,+ canonicalName,+ scope,+ urlKey,+ }) => {+ const builtIn = builtInRealPaths.has(realPath);+ const hasIdentityCollision = (identityCounts.get(`${engine}:${urlKey}`) ?? 0) > 1;+ // Pi entries are new to this SkillHub projection. Give them a path-derived+ // identity even when currently unique, so adding/removing a same-name source+ // never changes the surviving Pi entry's React/storage identity.+ const sourceKey = engine === 'pi' || hasIdentityCollision+ ? createHash('sha256').update(realPath).digest('hex')+ : undefined;+ const id = `${engine}:${urlKey}${sourceKey ? `:source:${sourceKey}` : ''}`;++ const engineSet = new Map<Skill['engine'], Skill['linkedEngines'][number]>();+ for (const item of all) {+ const eng = item.engine;+ if (!engineSet.has(eng)) {+ engineSet.set(eng, {+ engine: eng,+ label: eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : 'Pi',+ ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),+ });+ }+ }+ const linkedEngines = builtIn+ ? Array.from(discoveredEnginesByRealPath.get(realPath)?.values() ?? [])+ : Array.from(engineSet.values());++ const skill: Skill = {+ id,+ urlKey,+ ...(sourceKey ? { sourceKey } : {}),+ ...(hasIdentityCollision ? { requiresSourceKey: true } : {}),+ engine,+ linkedEngines,+ kind: c.kind as SkillKind,+ scope,+ name: canonicalName,+ description: c.description,+ absolutePath: realPath,+ discoveredPath: c.absolutePath,+ mdPath: c.mdPath ?? realPath,+ files: c.kind === 'skill'+ ? filterSkillPackageFileEntries(realPath, (c.files ?? []) as SkillFileEntry[])+ : [],+ frontmatter: c.frontmatter,+ parseError: c.parseError,+ registryEntry: null, // 下面 join 阶段填+ ...(c.kind === 'skill' ? (() => {+ const discoveryPaths = [...new Set(all.map((item) => item.absolutePath))];+ const target = inspectLocalSkillTarget(realPath, discoveryPaths, managedSkillRoots);+ return { cindyEnabled: !disabledPaths.includes(activationKey(realPath, userDataDir, appDataDir)), discoveryPaths,+ ...(builtIn ? { builtIn: true } : {}),+ managedByPlugin: isPluginManagedSkillPath(realPath, managedSkillRoots),+ canUninstall: !builtIn && target !== null, uninstallLinkOnly: target?.linkOnly ?? false };+ })() : {}),+ ...(project ? { projectRoot: project.projectRoot } : {}),+ ...(projectHash ? { projectHash } : {}),+ };+ return skill;+ });++ // ── join registry ──────────────────────────────────────────────────────────+ const registryByPath = new Map<string, (typeof registryEntries)[number]>();+ for (const r of registryEntries) {+ const installPathKey = path.normalize(r.installPath);+ registryByPath.set(installPathKey, r);+ try {+ const realInstallPathKey = path.normalize(fs.realpathSync(r.installPath));+ registryByPath.set(realInstallPathKey, r);+ } catch {+ // Missing paths retain their lexical registry key; listing never mutates them.+ }+ }+ for (const s of skills) {+ if (s.kind !== 'skill') continue;+ let resolved: string;+ try {+ resolved = fs.realpathSync(s.absolutePath);+ } catch {+ resolved = s.absolutePath;+ }+ const normPath = path.normalize(resolved);+ // path 是物理唯一标识;允许 registry skillName 和 scanner directory name 不一致+ // (历史数据或 frontmatter name 与目录名不同步时会出现)+ const registered = registryByPath.get(normPath);+ s.registryEntry = registered?.entry ?? null;+ s.registrySkillName = registered?.skillName;+ }++ // ── sources[] 兼容 (renderer 只存不读) ─────────────────────────────────────+ const sources: SourceReport[] = listed.errors.map((e) => ({+ kind: 'skill',+ scope: 'global',+ path: e.path ?? '',+ status: { state: 'error', message: e.message },+ }));++ return { skills, sources, learnSkillEnabled: skills.some((skill) => skill.builtIn && skill.name === 'learn' && skill.cindyEnabled !== false) };+}diff --git a/apps/desktop/src/main/skillhub/skillPathPolicy.ts b/apps/desktop/src/main/skillhub/skillPathPolicy.tsnew file mode 100644index 0000000000..7c487d02fc--- /dev/null+++ b/apps/desktop/src/main/skillhub/skillPathPolicy.ts@@ -0,0 +1,60 @@+import fs from 'node:fs';+import path from 'node:path';++const SKILL_PATH_WHITELIST = /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills|pi\/skills)|codex-home\/skills)\//;++export function isLexicallyAllowedSkillPath(absolutePath: string): boolean {+ // path.resolve 解析 .. 和 . 段,防止遍历绕过白名单+ const norm = path.resolve(absolutePath).replace(/\\/g, '/');+ return SKILL_PATH_WHITELIST.test(norm);+}++export function isPathWithin(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate);+ return relative === '' || (+ relative !== '..'+ && !relative.startsWith(`..${path.sep}`)+ && !path.isAbsolute(relative)+ );+}++/**+ * Resolve the final existing target before Main performs IO. Project-owned+ * `.pi/skills` paths get an extra physical boundary: neither the source root+ * nor a child symlink may escape the project. Other roots keep supporting the+ * existing global compatibility symlinks used by shared skill installs.+ */+export function resolveAllowedExistingSkillPath(absolutePath: string): string | null {+ if (!isLexicallyAllowedSkillPath(absolutePath)) return null;+ const lexicalPath = path.resolve(absolutePath);+ let realTarget: string;+ try {+ realTarget = fs.realpathSync.native(lexicalPath);+ } catch {+ return null;+ }++ const normalized = lexicalPath.replace(/\\/g, '/');+ const marker = '/.pi/skills/';+ const markerIndex = normalized.indexOf(marker);+ if (markerIndex < 0) return realTarget;++ const lexicalSkillRoot = path.normalize(normalized.slice(0, markerIndex + marker.length - 1));+ const lexicalProjectRoot = path.dirname(path.dirname(lexicalSkillRoot));+ try {+ const realProjectRoot = fs.realpathSync.native(lexicalProjectRoot);+ const realSkillRoot = fs.realpathSync.native(lexicalSkillRoot);+ if (+ !isPathWithin(realProjectRoot, realSkillRoot)+ || !isPathWithin(realSkillRoot, realTarget)+ ) return null;+ } catch {+ return null;+ }+ return realTarget;+}++export function resolveExistingSkillPathForGrant(absolutePath: string): string | null {+ if (!absolutePath || !path.isAbsolute(absolutePath)) return null;+ return resolveAllowedExistingSkillPath(absolutePath);+}diff --git a/apps/desktop/src/main/skillhub/skillScanGrants.ts b/apps/desktop/src/main/skillhub/skillScanGrants.tsnew file mode 100644index 0000000000..3f936c5e02--- /dev/null+++ b/apps/desktop/src/main/skillhub/skillScanGrants.ts@@ -0,0 +1,116 @@+import fs from 'node:fs';+import path from 'node:path';+import { normalizeWorkingDirForStorage } from '../../shared/workingDir';+import type { BuiltInSkillDescriptor } from '../maker-host/built-in-skills';+import type { Skill } from './scanner';+import { inspectLocalSkillTarget, type LocalSkillTarget } from './localSkillTarget';+import { resolveExistingSkillPathForGrant } from './skillPathPolicy';++export interface SkillScanGrantInput {+ skills: Skill[];+ managedSkillRoots: readonly string[];+ builtInSkills: readonly BuiltInSkillDescriptor[];+}++/** Private Main/worker snapshot; never sent to Renderer. Operations revalidate it. */+export interface SkillScanGrants {+ error?: string;+ entries: Array<{ root: string; projectRootKey?: string; builtIn?: boolean }>;+ records: Array<{ skill: Skill; physicalIdentity: string; target: LocalSkillTarget | null }>;+}++function projectRootKey(value: unknown): string | null {+ if (typeof value !== 'string' || value.includes('\0') || value.includes('\uFFFD')) return null;+ const normalized = normalizeWorkingDirForStorage(value);+ if (!normalized || !path.isAbsolute(normalized)) return null;+ const resolved = path.resolve(normalized);+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;+}+function physicalIdentity(source: string): string {+ const st = fs.statSync(source);+ return JSON.stringify([fs.realpathSync.native(source), st.dev, st.ino]);+}+export function prepareSkillScanGrants(+ input: SkillScanGrantInput,+ resolveGrant = resolveExistingSkillPathForGrant,+): SkillScanGrants {+ const { skills, managedSkillRoots, builtInSkills } = input;+ const normalizePathForCompare = (value: string): string => {+ const withoutWindowsNamespace = process.platform === 'win32'+ ? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')+ : value;+ const normalized = path.resolve(withoutWindowsNamespace);+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;+ };+ const realPathOrResolved = (value: string): string => {+ try { return normalizePathForCompare(fs.realpathSync.native(value)); }+ catch { return normalizePathForCompare(value); }+ };+ const configuredBuiltInRoot = (source: string): string | null => {+ const physicalSource = realPathOrResolved(source);+ const descriptor = builtInSkills.find((skill) => (+ realPathOrResolved(skill.absolutePath) === physicalSource+ ));+ return descriptor ? realPathOrResolved(descriptor.absolutePath) : null;+ };++ const entries: SkillScanGrants['entries'] = [];+ const seenEntries = new Set<string>();+ for (const skill of skills) {+ const skillProjectRootKey = skill.scope === 'project'+ ? projectRootKey(skill.projectRoot)+ : undefined;+ if (skill.scope === 'project' && !skillProjectRootKey) continue;+ // A built-in discovered through ~/.agents/skills still resolves to the+ // app-owned physical root. Keep Main's built-in attestation instead of+ // downgrading it to an ordinary discovery grant, otherwise the later+ // read handlers re-apply the lexical user-skill whitelist and reject the+ // exact path that the scan returned.+ if (skill.builtIn === true) {+ const root = configuredBuiltInRoot(skill.absolutePath);+ const entryKey = root ? `${root}\0built-in` : null;+ if (root && entryKey && !seenEntries.has(entryKey)) {+ seenEntries.add(entryKey);+ entries.push({ root, builtIn: true });+ }+ continue;+ }+ // discoveredPath preserves an allowed lexical alias when absolutePath was+ // canonicalized through a parent-directory symlink.+ for (const candidate of [skill.discoveredPath, skill.absolutePath]) {+ const root = resolveGrant(candidate);+ if (root) {+ const entryKey = `${root}\0${skillProjectRootKey ?? ''}`;+ if (!seenEntries.has(entryKey)) {+ seenEntries.add(entryKey);+ entries.push({+ root,+ ...(skillProjectRootKey ? { projectRootKey: skillProjectRootKey } : {}),+ });+ }+ break;+ }+ }+ }+ const records = skills.flatMap((skill) => {+ if (skill.kind !== 'skill') return [];+ try {+ return [{ skill, physicalIdentity: physicalIdentity(skill.absolutePath),+ target: inspectLocalSkillTarget(skill.absolutePath, skill.discoveryPaths ?? [skill.discoveredPath], managedSkillRoots) }];+ } catch { return []; }+ });+ const aliasesByIdentity = new Map<string, Set<string>>();+ for (const record of records) {+ const aliases = aliasesByIdentity.get(record.physicalIdentity) ?? new Set<string>();+ for (const alias of record.target?.aliases ?? []) aliases.add(alias);+ aliasesByIdentity.set(record.physicalIdentity, aliases);+ }+ for (const record of records) {+ // Removing the physical entity must clean every scanned scope's links.+ // Removing an external import keeps its scope-local operation/aliases.+ if (record.target && !record.target.linkOnly) {+ record.target.aliases = [...aliasesByIdentity.get(record.physicalIdentity)!];+ }+ }+ return { entries, records };+}diff --git a/packages/maker-core/package.json b/packages/maker-core/package.jsonindex 27a03779ae..4960a81d7b 100644--- a/packages/maker-core/package.json+++ b/packages/maker-core/package.json@@ -8,6 +8,7 @@"types": "./src/index.ts","exports": {".": "./src/index.ts",+ "./customization-scanner": "./src/agents/shared/customization-worker-api.ts","./contacts-sync-worker": "./src/contacts/sync/worker-api.ts","./pi-extension-ui": "./src/agents/pi/extension-ui-capabilities.ts","./pi-subagent-runs": "./src/agents/pi/pi-subagent-runs.ts"diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex b5b4f8591e..ea56629b4c 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -664,6 +664,11 @@ export interface AgentDeps {resolveSessionEnvironment?: (sessionId: string) => Promise<{ identity: string; assertCurrent?(): void } | undefined>;/** Cindy-only local Skill overrides. Freeze at native runtime startup; never apply to SSH. */getDisabledSkillPaths?: () => readonly string[];+ /** Optional host isolation for SkillHub discovery; native runtime discovery is unaffected. */+ scanLocalCustomizations?: (+ engine: 'claude-code' | 'codex' | 'pi',+ options: ListCustomizationsOptions,+ ) => Promise<ListCustomizationsResult>;/** Host-owned local Skills, loaded without writing user/project discovery directories. */getManagedSkills?: () => Promise<Array<AgentSkillCommand & {claudeCommandName: string;diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 91a5416fd0..f921bd264d 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -1212,7 +1212,9 @@ export class ClaudeCodeAgent extends BaseAgent {* 按 name 去重), 二者共享 ~/.claude/{...} 扫盘事实, 但消费者不同。*/async listCustomizations(opts: ListCustomizationsOptions): Promise<ListCustomizationsResult> {- const result = await scanClaudeCustomizations(opts);+ const result = await (this.deps.scanLocalCustomizations+ ? this.deps.scanLocalCustomizations('claude-code', opts)+ : scanClaudeCustomizations(opts));if (!opts.kinds || opts.kinds.includes('skill')) {result.items.push(...(await this.deps.getManagedSkills?.() ?? []).filter((skill) => skill.path).map((skill) => ({engine: 'claude-code' as const, kind: 'skill', scope: 'user', name: skill.name,diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 1c3145b46f..4fbf3df368 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2132,7 +2132,9 @@ export class CodexAgent extends BaseAgent {* 运行时技能列表(command palette)走 listAgentSkills → RPC,不受影响。*/async listCustomizations(opts: ListCustomizationsOptions): Promise<ListCustomizationsResult> {- return scanCodexCustomizations(opts);+ return this.deps.scanLocalCustomizations+ ? this.deps.scanLocalCustomizations('codex', opts)+ : scanCodexCustomizations(opts);}private async listSkillsForCwd(diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex c5d0930223..1d2b89e86c 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -8321,7 +8321,9 @@ export class PiAgent extends BaseAgent {/** SkillHub raw view; project items remain discovered until runtime truth says otherwise. */override async listCustomizations(opts: ListCustomizationsOptions): Promise<ListCustomizationsResult> {- const result = await scanPiCustomizations(opts);+ const result = await (this.deps.scanLocalCustomizations+ ? this.deps.scanLocalCustomizations('pi', opts)+ : scanPiCustomizations(opts));if (!opts.kinds || opts.kinds.includes('skill')) {result.items.push(...(await this.deps.getManagedSkills?.() ?? []).filter((skill) => skill.path).map((skill) => ({engine: 'pi' as const, kind: 'skill', scope: 'user', name: skill.name,diff --git a/packages/maker-core/src/agents/shared/customization-isolation.test.ts b/packages/maker-core/src/agents/shared/customization-isolation.test.tsnew file mode 100644index 0000000000..2be4e2b098--- /dev/null+++ b/packages/maker-core/src/agents/shared/customization-isolation.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it, vi } from 'vitest';+import { ClaudeCodeAgent } from '../claude-code/index.js';+import { CodexAgent } from '../codex/index.js';+import { PiAgent } from '../pi/index.js';+import type { ListCustomizationsResult } from '../../types/customizations.js';++vi.mock('../claude-code/customization-scanner.js', () => ({+ scanClaudeCustomizations: vi.fn(() => { throw new Error('Main must not scan'); }),+ scanClaudeRuntimeSkills: vi.fn(),+}));+vi.mock('../codex/customization-scanner.js', () => ({+ scanCodexCustomizations: vi.fn(() => { throw new Error('Main must not scan'); }),+}));+vi.mock('../pi/customization-scanner.js', () => ({+ scanPiCustomizations: vi.fn(() => { throw new Error('Main must not scan'); }),+}));++describe('host-isolated customization discovery', () => {+ it.each([+ ['claude-code', ClaudeCodeAgent, true],+ ['codex', CodexAgent, false],+ ['pi', PiAgent, true],+ ] as const)('%s uses host discovery and preserves managed Skills on scan failure', async (engine, Agent, includesManaged) => {+ const result: ListCustomizationsResult = { items: [], errors: [{ message: 'Scan timed out' }] };+ const scanLocalCustomizations = vi.fn(async () => result);+ const getManagedSkills = vi.fn(async () => [{+ name: 'managed', path: '/host/managed/SKILL.md', enabled: false, claudeCommandName: 'managed',+ }]);+ // Discovery uses only the injected dependencies; no runtime, auth or child CLI is needed.+ const agent = Object.create(Agent.prototype);+ Object.defineProperty(agent, 'deps', { value: { scanLocalCustomizations, getManagedSkills } });+ const options = { workingDirs: ['/project'], kinds: ['skill'] };+ const listed = await agent.listCustomizations(options);+ expect(scanLocalCustomizations).toHaveBeenCalledExactlyOnceWith(engine, options);+ expect(listed.errors).toEqual(result.errors);+ expect(listed.items).toHaveLength(includesManaged ? 1 : 0);+ if (includesManaged) expect(listed.items[0]).toMatchObject({ engine, name: 'managed', enabled: false });+ });+});diff --git a/packages/maker-core/src/agents/shared/customization-worker-api.ts b/packages/maker-core/src/agents/shared/customization-worker-api.tsnew file mode 100644index 0000000000..f586d78387--- /dev/null+++ b/packages/maker-core/src/agents/shared/customization-worker-api.ts@@ -0,0 +1,5 @@+// Narrow entry for hosts that isolate filesystem discovery. Keep the full+// agent/runtime graph out of the utility process.+export { scanClaudeCustomizations } from '../claude-code/customization-scanner.js';+export { scanCodexCustomizations } from '../codex/customization-scanner.js';+export { scanPiCustomizations } from '../pi/customization-scanner.js';