Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(skills): 将预装和插件技能迁入 Cindy 私有目录 (#5318)
Dash337aaac66b34
diff --git a/apps/desktop/help-knowledge/skills.md b/apps/desktop/help-knowledge/skills.mdindex 429e72aad1..0cecca5260 100644--- a/apps/desktop/help-knowledge/skills.md+++ b/apps/desktop/help-knowledge/skills.md@@ -11,8 +11,9 @@ Skills are reusable agent capabilities you package as a folder and load into you**Where skills live on disk:**-- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\Users\<you>\`.+- User-created or imported global skills (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\Users\<you>\`.- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.+- Cindy’s preinstalled skills and plugin-provided skills are kept in Cindy-managed directories and loaded into local Claude Code, Codex, and Pi tasks. Cindy does not add them to the user’s shared skill directories, so external CLIs do not discover them automatically. User-created and imported skills keep the locations above.- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.**Importing a local skill:**@@ -46,7 +47,7 @@ Skills are reusable agent capabilities you package as a folder and load into you- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.-- External source imports remove only their discovery links and keep the external source files. Package-owned Skills must be removed through their owning package. Cindy's built-in Skills cannot be uninstalled, but they can be disabled. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared Skill links.+- External source imports remove only their discovery links and keep the external source files. Package-owned Skills must be removed through their owning package. Cindy's built-in Skills cannot be uninstalled, but they can be disabled. Skills provided by Cindy plugins are managed on the owning plugin's page and loaded through Cindy's private skill entries.- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If cleanup is interrupted, the notice offers **Retry cleanup**. The unfinished operation survives closing, reloading, and restarting Cindy; reopen Skills in the same Cindy profile and account to continue. Cindy pauses conflicting installations until cleanup completes. Retrying never moves files to the trash a second time and preserves externally restored or replaced content.diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.tsindex b5ad259695..d8d5aac236 100644--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts@@ -246,9 +246,8 @@ describe('passive shared-userData instance auth isolation', () => {expect(body.indexOf('prepareBuiltInSkills({')).toBeGreaterThan(ownerBoundary);expect(body.indexOf('prepareSharedGlobalSkillLinks({')).toBeGreaterThan(ownerBoundary);expect(body).not.toContain('refreshBuiltInSharedSkillLinks({');- expect(body.indexOf('refreshBuiltInClaudeSkillLinks({')).toBeGreaterThan(- body.indexOf('prepareSharedGlobalSkillLinks({'),- );+ expect(body.indexOf('migrateBuiltInGlobalSkillLinks({')).toBeGreaterThan(ownerBoundary);+ expect(body.indexOf('migrateBuiltInGlobalSkillLinks({')).toBeLessThan(body.indexOf('prepareSharedGlobalSkillLinks({'));});it('relogin marker:passive 不消费整机一份的 marker,也不删 primary 的 token', () => {diff --git a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.tsindex f9f1edc946..7f4ba30ff5 100644--- a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts+++ b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts@@ -188,7 +188,9 @@ describe('desktop auth session-expiry detection', () => {const end = ghostSource.indexOf('\n}\n', start);const body = ghostSource.slice(start, end);- expect(body).toContain('await removeGhostSkillLinksForRoots(listGhostOwnerProjectionRoots())');+ expect(body).toContain('const roots = listGhostOwnerProjectionRoots();');+ expect(body).toContain('await removeGhostSkillLinksForRoots(roots, undefined,');+ expect(body).toContain("roots.map((root) => path.join(ghostSkillPluginRoot(root), 'skills'))");expect(body).toContain('throw new Error(`ghost owner skill cleanup incomplete');expect(body).not.toContain('AuthBoundaryQuarantine');diff --git a/apps/desktop/src/main/__tests__/codexGlobalSkills.test.ts b/apps/desktop/src/main/__tests__/codexGlobalSkills.test.tsindex eb712189f9..9236d22e42 100644--- a/apps/desktop/src/main/__tests__/codexGlobalSkills.test.ts+++ b/apps/desktop/src/main/__tests__/codexGlobalSkills.test.ts@@ -1,12 +1,13 @@import os from 'node:os';import path from 'node:path';import { promises as fs } from 'node:fs';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {CODEX_LEGACY_CODEX_SKILLS_LINK_NAME,CODEX_SHARED_AGENTS_SKILLS_LINK_NAME,codexGlobalSkillsPaths,+ codexManagedSkillLinkName,prepareCodexGlobalSkillsLinks,} from '../maker-host/codex-global-skills';@@ -36,12 +37,136 @@ async function sameRealPath(a: string, b: string): Promise<boolean> {}afterEach(async () => {+ vi.restoreAllMocks();const dirs = tmpDirs;tmpDirs = [];await Promise.all(dirs.map((dir) => fs.rm(dir, { recursive: true, force: true })));});describe('prepareCodexGlobalSkillsLinks', () => {+ it('loads only verified individual sources, retires old aggregates and preserves foreign occupants', async () => {+ const root = await makeTmpDir();+ const homeDir = path.join(root, 'home');+ const codexHome = path.join(root, 'codex');+ const ownerA = path.join(+ root,+ 'owner-a',+ 'ghost-install-state',+ 'skill-snapshots',+ 'example',+ 'rev',+ );+ const ownerB = path.join(+ root,+ 'owner-b',+ 'ghost-install-state',+ 'skill-snapshots',+ 'example',+ 'rev',+ );+ await writeSkill(path.join(ownerA, 'skills'), 'learn');+ await writeSkill(path.join(ownerB, 'skills'), 'learn');+ const projection = path.join(root, 'owner-a', 'ghost-install-state', 'agent-skills', 'skills');+ await writeSkill(projection, 'unapproved--extra');+ await fs.mkdir(path.join(codexHome, 'skills'), { recursive: true });+ const linkType = process.platform === 'win32' ? 'junction' : 'dir';+ await fs.symlink(projection, path.join(codexHome, 'skills', 'cindy-1'), linkType);+ const foreign = path.join(root, 'foreign');+ await fs.mkdir(foreign);+ await fs.symlink(foreign, path.join(codexHome, 'skills', 'cindy-foreign'), linkType);+ await fs.mkdir(path.join(codexHome, 'skills', 'cindy-user-directory'));+ const command = 'cindy-plugin-example:learn';+ const link = path.join(codexHome, 'skills', codexManagedSkillLinkName(command));+ const options = (owner: string) => ({+ homeDir,+ managedRoots: [root],+ managedSkills: [+ {+ path: path.join(owner, 'skills', 'learn', 'SKILL.md'),+ claudeCommandName: command,+ },+ ],+ });+ await prepareCodexGlobalSkillsLinks(codexHome, options(ownerA));+ expect(await sameRealPath(link, path.join(ownerA, 'skills', 'learn'))).toBe(true);+ await expect(fs.lstat(path.join(codexHome, 'skills', 'cindy-1'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect(await fs.readdir(projection)).toEqual(['unapproved--extra']);+ await prepareCodexGlobalSkillsLinks(codexHome, options(ownerB));+ expect(await sameRealPath(link, path.join(ownerB, 'skills', 'learn'))).toBe(true);+ await prepareCodexGlobalSkillsLinks(codexHome, {+ homeDir,+ managedRoots: [root],+ managedSkills: [],+ });+ await expect(fs.lstat(link)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await sameRealPath(path.join(codexHome, 'skills', 'cindy-foreign'), foreign)).toBe(true);+ expect(+ (await fs.stat(path.join(codexHome, 'skills', 'cindy-user-directory'))).isDirectory(),+ ).toBe(true);+ await fs.symlink(foreign, link, linkType);+ await expect(prepareCodexGlobalSkillsLinks(codexHome, options(ownerA))).rejects.toThrow(+ 'foreign skill link is preserved',+ );+ expect(await sameRealPath(link, foreign)).toBe(true);+ await expect(fs.stat(path.join(homeDir, '.agents'))).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(fs.stat(path.join(homeDir, '.claude'))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it.each(['directory-conflict', 'create-error', 'replace-error', 'missing', 'cycle'] as const)(+ 'rejects an incomplete managed projection (%s) instead of reporting a successful refresh',+ async (failure) => {+ const root = await makeTmpDir();+ const codexHome = path.join(root, 'codex');+ const snapshots = path.join(root, 'ghost-install-state', 'skill-snapshots');+ const command = 'cindy-plugin-example:learn';+ const link = path.join(codexHome, 'skills', codexManagedSkillLinkName(command));+ await fs.mkdir(path.dirname(link), { recursive: true });+ await writeSkill(snapshots, 'old');+ await writeSkill(snapshots, 'current');+ let source = path.join(snapshots, 'current');+ if (failure === 'directory-conflict') {+ await fs.mkdir(link);+ await fs.writeFile(path.join(link, 'keep.txt'), 'user-owned');+ } else if (failure === 'replace-error') {+ await fs.symlink(+ path.join(snapshots, 'old'),+ link,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const rm = fs.rm;+ vi.spyOn(fs, 'rm').mockImplementation(async (target, options) => {+ if (target === link) throw Object.assign(new Error('locked entry'), { code: 'EPERM' });+ return rm(target, options);+ });+ } else if (failure === 'create-error') {+ vi.spyOn(fs, 'symlink').mockRejectedValue(+ Object.assign(new Error('link denied'), { code: 'EACCES' }),+ );+ } else if (failure === 'missing') {+ source = path.join(snapshots, 'missing');+ } else {+ source = path.join(codexHome, 'skills', 'cycle');+ await writeSkill(path.dirname(source), 'cycle');+ }+ await expect(+ prepareCodexGlobalSkillsLinks(codexHome, {+ homeDir: path.join(root, 'home'),+ managedRoots: [root],+ managedSkills: [{ path: path.join(source, 'SKILL.md'), claudeCommandName: command }],+ }),+ ).rejects.toThrow('Cannot prepare Codex managed Skill');+ if (failure === 'directory-conflict')+ expect(await fs.readFile(path.join(link, 'keep.txt'), 'utf8')).toBe('user-owned');+ if (failure === 'replace-error')+ expect(await sameRealPath(link, path.join(snapshots, 'old'))).toBe(true);+ expect(await fs.readFile(path.join(snapshots, 'current', 'SKILL.md'), 'utf8')).toContain(+ 'body',+ );+ },+ );+it('links legacy Codex and shared agent skills directly under the custom CODEX_HOME skills root', async () => {const root = await makeTmpDir();const homeDir = path.join(root, 'home');@@ -110,8 +235,12 @@ describe('prepareCodexGlobalSkillsLinks', () => {const result = await prepareCodexGlobalSkillsLinks(codexHome, { homeDir });expect(result.sources.find((source) => source.name === 'codex')?.status).toBe('conflict');- await expect(fs.readFile(path.join(conflictingDir, 'keep.txt'), 'utf8')).resolves.toBe('do not remove');- expect(result.warnings.some((warning) => warning.includes('cannot link Codex codex skills'))).toBe(true);+ await expect(fs.readFile(path.join(conflictingDir, 'keep.txt'), 'utf8')).resolves.toBe(+ 'do not remove',+ );+ expect(+ result.warnings.some((warning) => warning.includes('cannot link Codex codex skills')),+ ).toBe(true);});it('removes the old aggregate scan link without deleting non-managed files', async () => {@@ -125,14 +254,20 @@ describe('prepareCodexGlobalSkillsLinks', () => {const oldScanEntry = path.join(codexHome, 'skills', 'xdt-global');await fs.mkdir(path.join(codexHome, 'skills'), { recursive: true });await fs.mkdir(oldAggregateDir, { recursive: true });- await fs.symlink(oldAggregateDir, oldScanEntry, process.platform === 'win32' ? 'junction' : 'dir');+ await fs.symlink(+ oldAggregateDir,+ oldScanEntry,+ process.platform === 'win32' ? 'junction' : 'dir',+ );await fs.writeFile(path.join(oldAggregateDir, 'keep.txt'), 'do not remove', 'utf8');await prepareCodexGlobalSkillsLinks(codexHome, { homeDir });const paths = codexGlobalSkillsPaths(codexHome, homeDir);await expect(fs.lstat(oldScanEntry)).rejects.toMatchObject({ code: 'ENOENT' });- await expect(fs.readFile(path.join(oldAggregateDir, 'keep.txt'), 'utf8')).resolves.toBe('do not remove');+ await expect(fs.readFile(path.join(oldAggregateDir, 'keep.txt'), 'utf8')).resolves.toBe(+ 'do not remove',+ );expect(await sameRealPath(paths.legacyCodexSkillsLink, legacySkills)).toBe(true);});});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex e501e781b2..6051c7ba15 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -2144,7 +2144,7 @@ describe('FORGE_GUIDE', () => {'捆绑 Agent Skills(skill 能力)','skill.items','SKILL.md',- '~/.agents/skills',+ '不写入用户的全局技能目录','逐字一致','不受插件沙箱约束',// 工作区会话(workspace):目录亲选/确认卡授权,判重复用。diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.tsindex b1d64c8b1a..41190728d5 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts@@ -11,6 +11,7 @@ import { GhostManager } from '../GhostManager';import {checkSkillMdConsistency,ghostSkillLinkName,+ ghostSkillPluginRoot,removeGhostSkillLinksForRoots,reconcileGhostSkillLinks as reconcileGhostSkillLinksRaw,} from '../skillSlot';@@ -45,7 +46,8 @@ afterEach(async () => {await fs.promises.rm(workDir, { recursive: true, force: true });});-const sharedDir = () => path.join(homeDir, '.agents', 'skills');+const sharedDir = () => path.join(ghostSkillPluginRoot(approvalStateRoot), 'skills');+const legacySharedDir = () => path.join(homeDir, '.agents', 'skills');const claudeDir = () => path.join(homeDir, '.claude', 'skills');/**@@ -134,7 +136,7 @@ describe('skillSlot · checkSkillMdConsistency', () => {});describe('skillSlot · reconcileGhostSkillLinks', () => {- it('启用插件 → 建链进共享根并扇出 .claude;二次对账幂等', async () => {+ it('启用插件 → 私有目录可见;二次对账幂等', async () => {await writeSkillDir('my-ghost', 'skills/foo', 'foo');const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];@@ -145,15 +147,47 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {const sharedLink = path.join(sharedDir(), linkName);const target = path.join(brainRoot, 'my-ghost', 'skills', 'foo');expect(sameRealPath(sharedLink, target)).toBe(true);- // .claude 兼容扇出(经 prepareSharedGlobalSkillLinks)- expect(sameRealPath(path.join(claudeDir(), linkName), target)).toBe(true);+ expect(fs.existsSync(legacySharedDir())).toBe(false);+ expect(fs.existsSync(claudeDir())).toBe(false);const second = await reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });expect(second.changed).toBe(false);expect(second.actions.filter((a) => a.op !== 'kept')).toEqual([]);});- it('停用/卸载 → 撤链,.claude 悬空兼容链接一并回收', async () => {+ it('migrates legacy fanout without touching user skills, and separates equal plugin skill names', async () => {+ const target = await writeSkillDir('my-ghost', 'skills/foo', 'foo');+ await writeSkillDir('other-ghost', 'skills/foo', 'foo');+ await fs.promises.mkdir(legacySharedDir(), { recursive: true });+ await fs.promises.mkdir(claudeDir(), { recursive: true });+ const legacy = path.join(legacySharedDir(), 'my-ghost--foo');+ const fanout = path.join(claudeDir(), 'my-ghost--foo');+ await fs.promises.symlink(target, legacy, 'dir');+ await fs.promises.symlink(legacy, fanout, 'dir');+ const user = path.join(legacySharedDir(), 'user-skill');+ await fs.promises.mkdir(user);+ await fs.promises.writeFile(path.join(user, 'SKILL.md'), '# User skill');+ const ghosts = ['my-ghost', 'other-ghost'].map((id) => ghost(id, [{ dir: 'skills/foo', name: 'foo' }]));+ await reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });+ expect(fs.readdirSync(legacySharedDir())).toEqual(['user-skill']);+ expect(fs.readdirSync(claudeDir())).toEqual([]);+ expect(fs.readFileSync(path.join(user, 'SKILL.md'), 'utf8')).toBe('# User skill');+ expect(fs.readdirSync(sharedDir())).toEqual(['my-ghost--foo', 'other-ghost--foo']);+ });++ it('removes a dangling legacy secondary link while preserving unrelated dangling links', async () => {+ await fs.promises.mkdir(legacySharedDir(), { recursive: true });+ await fs.promises.mkdir(claudeDir(), { recursive: true });+ const legacy = path.join(legacySharedDir(), 'my-ghost--foo');+ await fs.promises.symlink(path.join(brainRoot, 'my-ghost', 'missing'), legacy, 'dir');+ await fs.promises.symlink(legacy, path.join(claudeDir(), 'my-ghost--foo'), 'dir');+ await fs.promises.symlink(path.join(workDir, 'user-missing'), path.join(claudeDir(), 'user-skill'), 'dir');+ await removeGhostSkillLinksForRoots([brainRoot, approvalStateRoot], homeDir);+ expect(fs.readdirSync(legacySharedDir())).toEqual([]);+ expect(fs.readdirSync(claudeDir())).toEqual(['user-skill']);+ });++ it('停用/卸载 → 撤销私有投影', async () => {await writeSkillDir('my-ghost', 'skills/foo', 'foo');const enabled = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, approvalStateRoot, homeDir });@@ -164,7 +198,6 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {const result = await reconcileGhostSkillLinks({ ghosts: disabled, brainRoot, approvalStateRoot, homeDir });expect(result.changed).toBe(true);expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);- expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);// 卸载(清单里没有它)语义相同:再建再收敛一次验证await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, approvalStateRoot, homeDir });@@ -294,7 +327,6 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {expect(result.changed).toBe(true);expect(result.warnings.some((warning) => warning.includes('字节不可信'))).toBe(true);expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);- expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);});it('外来链接(目标不在任何受管根内)→ 活链断链都不碰', async () => {@@ -476,9 +508,9 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {const foreignTarget = path.join(workDir, 'projects', 'other-ghost', 'skills', 'foo');await fs.promises.mkdir(managedTarget, { recursive: true });await fs.promises.mkdir(foreignTarget, { recursive: true });- await fs.promises.mkdir(sharedDir(), { recursive: true });- const managedLink = path.join(sharedDir(), 'other-ghost--foo');- const foreignLink = path.join(sharedDir(), 'foreign--foo');+ await fs.promises.mkdir(legacySharedDir(), { recursive: true });+ const managedLink = path.join(legacySharedDir(), 'other-ghost--foo');+ const foreignLink = path.join(legacySharedDir(), 'foreign--foo');await fs.promises.symlink(managedTarget, managedLink, process.platform === 'win32' ? 'junction' : 'dir');await fs.promises.symlink(foreignTarget, foreignLink, process.platform === 'win32' ? 'junction' : 'dir');@@ -493,8 +525,8 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {const managedRoot = path.join(ownerRoot, 'cindy-brain');const managedTarget = path.join(managedRoot, 'other-ghost', 'skills', 'foo');await fs.promises.mkdir(managedTarget, { recursive: true });- await fs.promises.mkdir(sharedDir(), { recursive: true });- const managedLink = path.join(sharedDir(), 'other-ghost--foo');+ await fs.promises.mkdir(legacySharedDir(), { recursive: true });+ const managedLink = path.join(legacySharedDir(), 'other-ghost--foo');await fs.promises.symlink(managedTarget,managedLink,@@ -527,8 +559,8 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');const managedTarget = path.join(ownerRoot, 'other-ghost', 'skills', 'foo');await fs.promises.mkdir(managedTarget, { recursive: true });- await fs.promises.mkdir(sharedDir(), { recursive: true });- const managedLink = path.join(sharedDir(), 'other-ghost--foo');+ await fs.promises.mkdir(legacySharedDir(), { recursive: true });+ const managedLink = path.join(legacySharedDir(), 'other-ghost--foo');await fs.promises.symlink(managedTarget,managedLink,@@ -555,8 +587,8 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');const managedTarget = path.join(ownerRoot, 'other-ghost', 'skills', 'foo');await fs.promises.mkdir(managedTarget, { recursive: true });- await fs.promises.mkdir(sharedDir(), { recursive: true });- const managedLink = path.join(sharedDir(), 'other-ghost--foo');+ await fs.promises.mkdir(legacySharedDir(), { recursive: true });+ const managedLink = path.join(legacySharedDir(), 'other-ghost--foo');await fs.promises.symlink(managedTarget,managedLink,@@ -578,8 +610,8 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {const foreignTarget = path.join(workDir, 'projects', 'foreign', 'skills', 'foo');await fs.promises.mkdir(ownerRoot, { recursive: true });await fs.promises.mkdir(foreignTarget, { recursive: true });- await fs.promises.mkdir(sharedDir(), { recursive: true });- const foreignLink = path.join(sharedDir(), 'foreign--foo');+ await fs.promises.mkdir(legacySharedDir(), { recursive: true });+ const foreignLink = path.join(legacySharedDir(), 'foreign--foo');await fs.promises.symlink(foreignTarget,foreignLink,@@ -704,7 +736,6 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'expect(approvedSkillRoot).toBeTruthy();const target = path.join(approvedSkillRoot!, 'skills', 'demo');expect(sameRealPath(path.join(sharedDir(), linkName), target)).toBe(true);- expect(sameRealPath(path.join(claudeDir(), linkName), target)).toBe(true);// 链接指向的 SKILL.md 就是包里那份expect(await fs.promises.readFile(path.join(sharedDir(), linkName, 'SKILL.md'), 'utf8'),@@ -733,7 +764,6 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'});expect(tampered.warnings.some((warning) => warning.includes('字节不可信'))).toBe(true);expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);- expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);// 4) 卸载 → 对账 → 双端链接消失const removed = await manager.uninstall('e2e-ghost');@@ -745,6 +775,5 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'homeDir,});expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);- expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);});});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 06f56e447f..8ba008ab20 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -4379,8 +4379,8 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);稳定原则进入 Manual。Manual 与 \`list_tools\` 用完整调用互相指路,不复制同一段规则。以下只解释存量包的兼容形态,用于维护与迁移,**不要照抄到新插件**。存量插件装入且-启用后,主机仍会把每个技能目录链接进共享技能根-\`~/.agents/skills/<插件id>--<技能name>\`(Windows 用 junction),停用/卸载即撤链。+启用后,主机把每个技能目录投影到 Cindy 的账号隔离目录,分别接入 Claude Code、+Codex、Pi,不写入用户的全局技能目录;停用/卸载即撤销这些入口。目录形态(每条 item 一个目录,内必须有 SKILL.md):@@ -4401,25 +4401,9 @@ SKILL.md 硬规则(打包与装入双侧强制,任一不满足直接拒):- \`name\`:小写字母/数字加单连字符分段(禁首尾/连续连字符),≤64 字符;- SKILL.md 单文件 ≤64KB;items 最多 4 条。-正文开头建议写一段**环境守卫**(非强制,但强烈建议):技能挂进的是**共享**技能根,-用户在 Cindy 之外直接跑 Claude Code / Codex 时同样会看到你的技能,而那里没有插件-通道。Agent 读完正文自然会发现调不动 \`ghost_call\`,但很容易转头用 shell 自己实现-一个"看起来像"的替代品——这段守卫拦的就是这个。放在 H1 标题之后的第一段-(Agent 从头读正文):--\`\`\`markdown-> **本技能属于 Cindy 插件 \`<插件 id>\`:动手前先看工具列表,没有名字含 \`ghost_call\`-> 的工具就说明不在 Cindy 中,本技能不可用。** 此时不要执行任何步骤,也不要用 shell-> 或别的工具自己实现一遍——能力在插件的运行时里,替代品做不出等价产出。直接告诉-> 用户「这个技能需要在 Cindy 客户端里使用」,然后停下。-\`\`\`--- 判据只写"名字含 \`ghost_call\`",**不要写某个引擎的工具名全称**:Claude Code 与- Codex 的 MCP 工具名前缀不同,写死一边会让另一边误判成"不在 Cindy";-- 写在正文里,**不要塞进 frontmatter \`description\`**:description 每个会话都常驻- 上下文,正文只在技能被激活后才读,守卫写正文不花常驻预算;-- 一个插件多条 item 时每份 SKILL.md 各写各的(技能之间互相看不见);-- 技能正文是英文时照译一份,别中英混排。+这些入口仅供 Cindy 管理的 Agent 会话使用,不会自动暴露给外部 CLI,无需为旧的+全局目录发现方式添加环境守卫。技能如依赖插件工具,仍应说明实际依赖;调用时工具+不可用就报告缺失,不得据此假定已获得其它能力或权限。信任与作用域(如实告知用户,也请作者自重):diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 7c4593abad..9c1700dc5a 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -896,7 +896,7 @@ export class GhostInstallReceiptStore {* 回收同一插件下非当前 revision 的技能快照与崩溃残留的 `.tmp` 目录。** 只在新 receipt 已经原子提交之后跑:此刻旧 revision 已不是批准事实,留着- * 就是每次更新泄漏一份完整拷贝。共享技能根里指向旧 revision 的链接会因此+ * 就是每次更新泄漏一份完整拷贝。插件技能根里指向旧 revision 的链接会因此* 短暂断链,直到下一轮对账重指——对越出沙箱的 skill 能力来说,短暂"技能不可* 用"是正确的收敛方向,留着旧批准版本继续生效不是。*diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex d01534a5b8..684de21378 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -211,7 +211,7 @@ import { reclaimLoopbackPort } from './portReclaim.js';import { GhostConnectionManager } from './ghostConnections.js';import { getResolvedMainLocale, t } from '../i18n.js';import { getDeepLinkMainWindow } from '../deepLink.js';-import { reconcileGhostSkillLinks, removeGhostSkillLinksForRoots } from './skillSlot.js';+import { reconcileGhostSkillLinks, removeGhostSkillLinksForRoots, ghostSkillPluginRoot } from './skillSlot.js';import { assertGhostSkillProjectionStableOwner } from '../authBoundaryQuarantine.js';import { type GhostOwnerScope } from './ghostOwnerScope.js';import {@@ -1102,12 +1102,14 @@ function listGhostOwnerProjectionRoots(): string[] {];}-/** Stop every sandbox and revoke global skill projections before changing the active data owner. */+/** Stop every sandbox and revoke private and legacy skill projections before changing the active data owner. */export async function suspendAllGhosts(): Promise<void> {runtimeSingleton?.destroyAll();resetNodeRuntimeBrokerForAccountBoundary();brainRootCache = null;- const skillCleanup = await removeGhostSkillLinksForRoots(listGhostOwnerProjectionRoots());+ const roots = listGhostOwnerProjectionRoots();+ const skillCleanup = await removeGhostSkillLinksForRoots(roots, undefined,+ roots.map((root) => path.join(ghostSkillPluginRoot(root), 'skills')));for (const warning of skillCleanup.warnings) {log.warn('ghost owner skill cleanup warning', { warning });}diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.tsindex 00f6593212..04f0498448 100644--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@ -1,39 +1,13 @@/**- * skillSlot.ts —— skill 槽的两半:SKILL.md 一致性检查 + 共享技能根链接对账。- *- * 设计要点:- * - **确认框看到的 = Agent 读到的**:manifest 里 skill.items 的 name/description- * 必须与包内 SKILL.md frontmatter 逐字一致。`checkSkillMdConsistency` 是唯一- * 裁判,打包(forge.packGhostDir)与装入(GhostManager.parse)两侧共用,- * 杜绝两端契约漂移。- * - **单一幂等 reconciler**:`reconcileGhostSkillLinks` 以"期望态 vs 实际态"- * 对账,不做增量命令式挂链——install/update/启停/卸载全走同一条广播管线- * 触发对账,崩溃残留(悬空链接)下一轮自动自愈。- * - **链接指向 Host 批准快照,不指向可变安装目录**:共享技能根- * `~/.agents/skills/<id>--<name>` 是指向**批准状态根**里- * `skill-snapshots/<id>/<revision>/<dir>` 的 junction(win32)/dir symlink。- * skill 槽是唯一越出沙箱的能力,确认框看到的 SKILL.md 必须就是 Agent 之后- * 读到的那份,所以装入/更新确认时把技能目录逐字节拷成快照(只收普通文件),- * 链接指快照而不是随后可被改写的 `brainRoot/<id>/<dir>`。代价是目标路径按- * revision 变化:每次更新都换一个新目标,靠对账重指(旧 revision 快照在- * receipt 提交后回收)。卸载即断链,由对账回收。- * - **两个受管根**:因此本文件同时管理安装根(brainRoot)与批准状态根- * (approvalStateRoot);两者都必须由调用方给出,漏给会让活链接被判成外来- * 链接而永不撤链 —— 停用/卸载后技能仍对主 Agent 生效,故 approvalStateRoot- * 是必填项。- * - **绝不误伤**:只删"确认为 symlink/junction 且目标落在上述两个受管根之一"- * 的条目。真实目录(SkillHub 实体技能、用户手放的技能)与外来链接一律不碰,- * 占位冲突只 warn 不覆盖(同 shared-global-skills 的冲突哲学)。- * - **`.claude` 扇出与回收都不归这里管**:对账后调 prepareSharedGlobalSkillLinks,- * 它负责把 `.agents` 新条目 link 进 `.claude`;我们撤链后留下的 `.claude`- * 悬空兼容链接目标指向 `.agents` 受管根,同样由它的 cleanupBrokenManagedLinks- * 回收——职责分界干净:目标在本文件受管根内的链接归本文件,目标在 `.agents`- * 受管根内的归它。- * - 多账号:两个受管根都是 owner-scoped,`~/.agents/skills` 是全局的。本函数只- * 管理 realpath 落在**当前 owner 的受管根**内的活链接;他 owner 的活链接不碰- * (与 SkillHub 实体技能同一跨账号可见性现状)。悬空链接按结构判据回收- * (断链对所有消费方都是死重,跨 owner 清理防积尘),判据见- * `targetLooksGhostManaged`。+ * Validate bundled Skill metadata and reconcile owner-private projections of+ * approved snapshots. All harnesses consume agent-skills/skills; Claude builds+ * filtered per-session plugins from these sources. No new user-global links are made.+ * Legacy user-global links are removed only when their targets establish Cindy+ * ownership. Real directories and foreign links are preserved.+ * Source bytes must remain receipt-bound approved snapshots, never mutable plugin+ * install directories. Reconciliation validates the snapshot digest and metadata+ * before exposing it. Both brainRoot and approvalStateRoot are required so old+ * projections can be revoked on update, uninstall and owner changes.*/import { promises as fsp } from 'node:fs';@@ -49,12 +23,14 @@ import {type InstalledGhost,} from '../../shared/ghost.js';import { parseAndValidateFrontmatter } from '../skillhub/frontmatterValidation.js';-import {- prepareSharedGlobalSkillLinks,- sharedGlobalSkillsPaths,-} from '../maker-host/shared-global-skills.js';+import { sharedGlobalSkillsPaths } from '../maker-host/shared-global-skills.js';-/** 共享技能根里 ghost 技能的链接名。name 侧禁 `--`(GHOST_SKILL_NAME_RE),+/** Owner-scoped plugin root; never installed into the user's shared skill directories. */+export function ghostSkillPluginRoot(approvalStateRoot: string): string {+ return path.join(approvalStateRoot, 'agent-skills');+}++/** 私有技能根里 ghost 技能的链接名。name 侧禁 `--`(GHOST_SKILL_NAME_RE),* 按"最后一个 `--`"拆分唯一,不同插件不可能撞名。 */export function ghostSkillLinkName(ghostId: string, skillName: string): string {return `${ghostId}--${skillName}`;@@ -113,6 +89,7 @@ export interface ReconcileGhostSkillLinksResult {export async function removeGhostSkillLinksForRoots(managedRoots: readonly string[],homeDir?: string,+ additionalSkillDirs: readonly string[] = [],): Promise<{ changed: boolean; warnings: string[]; blockers: string[] }> {const warnings: string[] = [];const blockers: string[] = [];@@ -140,7 +117,7 @@ export async function removeGhostSkillLinksForRoots(}if (lexicalRoots.length === 0) return { changed, warnings, blockers };- for (const dir of [paths.sharedSkillsDir, paths.claudeSkillsDir, paths.codexSkillsDir]) {+ for (const dir of [paths.claudeSkillsDir, paths.codexSkillsDir, paths.sharedSkillsDir, ...additionalSkillDirs]) {let entries: Dirent[];try {entries = await fsp.readdir(dir, { withFileTypes: true });@@ -186,6 +163,16 @@ export async function removeGhostSkillLinksForRoots(warnings.push(`Unable to resolve owner skill link ${linkPath}: ${(err as Error).message}`);}}+ let sourceTargetProof: string | undefined;+ if (!managed && isSameOrInside(lexicalTarget, normalizeForCompare(paths.sharedSkillsDir))) {+ // The second link can be dangling while its source still identifies a+ // legacy Cindy target. Inspect it before removing the source link.+ try {+ sourceTargetProof = await fsp.readlink(lexicalTarget);+ const sourceTarget = path.resolve(path.dirname(lexicalTarget), sourceTargetProof);+ managed = lexicalRoots.some((root) => isSameOrInside(normalizeForCompare(sourceTarget), root));+ } catch { /* An unprovable/user-owned dangling link is left untouched. */ }+ }if (!managed) continue;try {const stat = await fsp.lstat(linkPath);@@ -202,7 +189,8 @@ export async function removeGhostSkillLinksForRoots(const finalLexicalTarget = normalizeForCompare(path.resolve(path.dirname(linkPath), finalRawTarget),);- if (finalLexicalTarget !== lexicalTarget) {+ if (finalLexicalTarget !== lexicalTarget+ || (sourceTargetProof !== undefined && await fsp.readlink(lexicalTarget) !== sourceTargetProof)) {const message = `Skipped owner skill link whose target changed before removal: ${linkPath}`;warnings.push(message);blockers.push(message);@@ -232,11 +220,11 @@ interface ReconcileOptions {*/approvalStateRoot: string;/**- * 在把批准快照投影成共享链接前重算其完整内容摘要。必填:只检查 SKILL.md+ * 在把批准快照投影成私有链接前重算其完整内容摘要。必填:只检查 SKILL.md* frontmatter 拦不住正文/辅助文件被改写,而已有链接目标不变时也不能直接 kept。*/validateApprovedSkillSnapshot: (ghost: InstalledGhost) => Promise<boolean>;- /** Present only for the Ghost-managed global fanout path. */+ /** Shared owner boundary check, also required while migrating old global links. */assertOwnerStable?: () => void;/** 覆盖 home 目录(仅测试)。 */homeDir?: string;@@ -305,7 +293,7 @@ function targetLooksGhostManaged(}/**- * 共享技能根对账:期望态(启用、已批准且带 skill 槽的插件)vs 实际态(根下目标+ * 插件技能根对账:期望态(启用、已批准且带 skill 槽的插件)vs 实际态(根下目标* 落在受管根内的链接)。幂等、best-effort、不 throw;warnings 交调用方记日志。*/export async function reconcileGhostSkillLinks(@@ -315,7 +303,8 @@ export async function reconcileGhostSkillLinks(const warnings: string[] = [];let changed = false;- const { sharedSkillsDir } = sharedGlobalSkillsPaths(opts.homeDir);+ const pluginRoot = ghostSkillPluginRoot(opts.approvalStateRoot);+ const sharedSkillsDir = path.join(pluginRoot, 'skills');// realpath 兼容 brainRoot 或其祖先是 symlink 的场景(relocated home dir)——// 活链接 realpath 后必须与归一化的物理根比较才可靠。resolve 失败退化到词法。const lexicalManagedRootCompares = [@@ -335,9 +324,10 @@ export async function reconcileGhostSkillLinks(const approvalStateDirName = path.basename(path.resolve(opts.approvalStateRoot));try {+ opts.assertOwnerStable?.();await fsp.mkdir(sharedSkillsDir, { recursive: true });} catch (err) {- warnings.push(`无法创建共享技能根 ${sharedSkillsDir}:${(err as Error).message}`);+ warnings.push(`无法创建私有技能根 ${sharedSkillsDir}:${(err as Error).message}`);return { changed, actions, warnings };}@@ -390,7 +380,7 @@ export async function reconcileGhostSkillLinks(const entries = await fsp.readdir(sharedSkillsDir, { withFileTypes: true });linkNames = entries.filter((ent) => ent.isSymbolicLink()).map((ent) => ent.name);} catch (err) {- warnings.push(`无法读取共享技能根 ${sharedSkillsDir}:${(err as Error).message}`);+ warnings.push(`无法读取插件技能根 ${sharedSkillsDir}:${(err as Error).message}`);return { changed, actions, warnings };}@@ -495,7 +485,7 @@ export async function reconcileGhostSkillLinks(await fsp.lstat(linkPath);// 走到这里 = 位置被占且不是删除步清掉的托管链接(真实目录/外来链接)。actions.push({ linkName, op: 'skipped', reason: 'occupied-by-unmanaged-entry' });- warnings.push(`共享技能根 ${linkName} 被非托管条目占用,不覆盖`);+ warnings.push(`私有技能根 ${linkName} 被非托管条目占用,不覆盖`);continue;} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {@@ -512,20 +502,9 @@ export async function reconcileGhostSkillLinks(}}- // —— 扇出:`.agents` 条目 → `.claude` 兼容链接;撤链留下的 `.claude` 悬空- // 兼容链接(目标在受管根内)也由它回收。每次对账都跑(兼容链接可能独立- // 缺失——canonical 正常但 .claude 侧被删或上次扇出失败);幂等、失败不阻断。- try {- const fanout = await prepareSharedGlobalSkillLinks(- {- ...(opts.homeDir !== undefined ? { homeDir: opts.homeDir } : {}),- ...(opts.assertOwnerStable ? { assertOwnerStable: opts.assertOwnerStable } : {}),- },- );- warnings.push(...fanout.warnings);- } catch (err) {- warnings.push(`共享技能链接扇出失败:${(err as Error).message}`);- }-+ opts.assertOwnerStable?.();+ const migrated = await removeGhostSkillLinksForRoots([opts.brainRoot, opts.approvalStateRoot], opts.homeDir);+ changed ||= migrated.changed;+ warnings.push(...migrated.warnings);return { changed, actions, warnings };}diff --git a/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.tsindex a5953f66ca..1f6e3ad71b 100644--- a/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts+++ b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import {consumeLearnInvocationGrant,+ canGrantUnqualifiedClaudeLearnInvocation,createLearnInvocationGrantConsumer,parseDirectLearnInvocation,} from '../invocationGrant.js';@@ -16,6 +17,7 @@ let activeDb: { sqlite: Database.Database; client: DbClient } | null = null;function createInvocationDb(): Database.Database {const sqlite = new Database(':memory:');sqlite.exec(`+ CREATE TABLE bot_session_links (session_id TEXT PRIMARY KEY);CREATE TABLE sessions (id TEXT PRIMARY KEY,cleared_at INTEGER@@ -49,6 +51,13 @@ afterEach(() => {});describe('Learn invocation grant', () => {+ it('does not attest a Bot-owned /learn alias using the global skill catalog', async () => {+ const sqlite = createInvocationDb();+ sqlite.prepare('INSERT INTO bot_session_links(session_id) VALUES (?)').run('bot-session');+ await expect(canGrantUnqualifiedClaudeLearnInvocation('bot-session')).resolves.toBe(false);+ await expect(canGrantUnqualifiedClaudeLearnInvocation('ordinary-session')).resolves.toBe(true);+ });+const grant = (sessionInstanceId = 'instance-1') => ({version: 1 as const,sessionInstanceId,@@ -84,6 +93,8 @@ describe('Learn invocation grant', () => {it.each([['/learn', { input: '', sourceKind: 'session' }],['/Learn', { input: '', sourceKind: 'session' }],+ ['/cindy:learn', { input: '', sourceKind: 'session' }],+ ['/cindy:learn release flow', { input: 'release flow', sourceKind: 'freetext' }],['/learn release flow', { input: 'release flow', sourceKind: 'freetext' }],['/LEARN Preserve Release Case', { input: 'Preserve Release Case', sourceKind: 'freetext' }],[@@ -110,6 +121,8 @@ describe('Learn invocation grant', () => {it.each(['/learner',+ '/other:learn',+ '/cindy:learner','/learning release flow','/skill:learner release flow','please inspect /Learn docs',diff --git a/apps/desktop/src/main/learn-host/invocationGrant.ts b/apps/desktop/src/main/learn-host/invocationGrant.tsindex d4322d9142..19f79cdb6a 100644--- a/apps/desktop/src/main/learn-host/invocationGrant.ts+++ b/apps/desktop/src/main/learn-host/invocationGrant.ts@@ -6,7 +6,7 @@ import {isDbClientNotReadyError,tryGetDbClient,} from '../localDb/client/current.js';-import { messages, sessions } from '../localDb/schema.js';+import { botSessionLinks, messages, sessions } from '../localDb/schema.js';export type LearnInvocationGrantResult =| { ok: true }@@ -41,6 +41,16 @@ type ConsumeUserInvocation = (const messageRowid = sql<number>`"messages"."rowid"`;+/** Bot-owned plugins are absent from the global skill catalog, so their /learn+ * aliases cannot be attested there. Bot calls must use /cindy:learn explicitly. */+export async function canGrantUnqualifiedClaudeLearnInvocation(sessionId: string): Promise<boolean> {+ const db = tryGetDbClient();+ if (!db) return false;+ const [botLink] = await db.drizzle.select({ sessionId: botSessionLinks.sessionId })+ .from(botSessionLinks).where(eq(botSessionLinks.sessionId, sessionId)).limit(1);+ return !botLink;+}+function normalizeInput(value: string): string {return value.trim().replace(/\s+/g, ' ');}@@ -51,7 +61,7 @@ export function parseDirectLearnInvocation(// Slash-skill dispatch resolves names case-insensitively. Keep the grant// parser on the same rule so an invocation accepted as the Learn Skill is// also accepted when that Skill calls the privileged host tool.- const command = /^\/(?:skill:)?learn(?:\s+([\s\S]*))?$/i.exec(text.trim());+ const command = /^\/(?:(?:skill|cindy):)?learn(?:\s+([\s\S]*))?$/i.exec(text.trim());if (!command) return null;const arg = (command[1] ?? '').trim();diff --git a/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts b/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.tsindex 146d0c1324..01a107fb6c 100644--- a/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts@@ -24,18 +24,18 @@ beforeEach(() => {});describe('asset preparation boundaries', () => {- it('rechecks plugin capability revocation even while successful Skill preparation is cached', async () => {+ it('rechecks plugin capability revocation and Skill projections at each launch', async () => {const skills = vi.fn(async () => true);// Avoid constructor credential reconciliation; exercise the real preparation entry points.const adapter = Object.assign(Object.create(DesktopCodexAuthAdapter.prototype), {pendingAssetsPrep: new PreparationCache(0),- skillAssetsPrep: new PreparationCache(30_000), runEnsureGlobalCodexSkills: skills,+ runEnsureGlobalCodexSkills: skills,}) as DesktopCodexAuthAdapter;Object.defineProperty(adapter, 'codexHome', { value: 'unused-test-home' });await adapter.ensureGlobalCodexAssets();state.bridge.mockResolvedValueOnce({ warnings: [], routingFailures: ['revoked'] });await expect(adapter.ensureGlobalCodexAssets()).rejects.toThrow('Cannot start Codex safely');- expect(skills).toHaveBeenCalledTimes(1);+ expect(skills).toHaveBeenCalledTimes(2);expect(state.bridge).toHaveBeenCalledTimes(2);state.bridge.mockRejectedValueOnce(new Error('unreadable'));await expect(adapter.ensureGlobalCodexAssets()).rejects.toThrow('unreadable');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 7bbffce095..8ad48666a0 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@@ -10,6 +10,8 @@ vi.mock('../../skillhub/registry', () => ({}));import {+ builtInSkillPluginRoot,+ migrateBuiltInGlobalSkillLinks,activeCindyBuiltInAgentSkills,BUILT_IN_SKILLS_BUNDLE_VERSION,builtInSkillDescriptors,@@ -30,6 +32,7 @@ function fixture() {const userDataDir = path.join(root, 'user-data');const appDataDir = path.join(root, 'app-data');const homeDir = path.join(root, 'home');+ fs.mkdirSync(homeDir, { recursive: true });fs.mkdirSync(path.join(source, 'scripts'), { recursive: true });fs.mkdirSync(learnSource, { recursive: true });fs.writeFileSync(@@ -82,6 +85,16 @@ afterEach(() => {});describe('built-in Skills', () => {+ it('publishes a fresh bundle without replacing an entry created in the same preparation', async () => {+ const replaceDirectoryEntryAtomically = vi.fn(async () => {+ throw new Error('fresh preparation must not need an existing-entry replacement');+ });+ const result = await prepareBuiltInSkills({ ...fixture(), replaceDirectoryEntryAtomically });+ expect(result.warnings).toEqual([]);+ expect(result.projectionSafe).toBe(true);+ expect(replaceDirectoryEntryAtomically).not.toHaveBeenCalled();+ });+it('materializes immutable versioned bytes and exposes the active version', async () => {const input = fixture();const first = await prepareAndProjectBuiltInSkills(input);@@ -90,7 +103,7 @@ describe('built-in Skills', () => {const manifest = JSON.parse(fs.readFileSync(path.join(root, '.cindy-system-skills.json'), 'utf8'),);- const link = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const link = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');expect(first.changed).toBe(true);expect(first.warnings).toEqual([]);expect(manifest).toMatchObject({@@ -112,7 +125,7 @@ describe('built-in Skills', () => {'# Creator',);const learnDescriptor = first.descriptors.find((item) => item.name === 'learn')!;- expect(fs.realpathSync(path.join(input.homeDir, '.agents', 'skills', 'learn'))).toBe(+ expect(fs.realpathSync(path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'learn'))).toBe(fs.realpathSync(learnDescriptor.absolutePath),);expect(fs.readFileSync(path.join(learnDescriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(@@ -193,8 +206,8 @@ describe('built-in Skills', () => {it('preserves existing projections when a manifest has a corrupt shape', async () => {const input = fixture();await prepareAndProjectBuiltInSkills(input);- const sharedLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');- const claudeLink = path.join(input.userDataDir, 'claude-home', 'skills', 'cindy-skill-creator');+ const sharedLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');+ const claudeLink = sharedLink;const sharedTarget = fs.realpathSync(sharedLink);const claudeTarget = fs.realpathSync(claudeLink);const manifestPath = path.join(@@ -384,8 +397,8 @@ describe('built-in Skills', () => {(descriptor) => descriptor.name === 'cindy-skill-creator',)!;const initialLearn = initial.descriptors.find((descriptor) => descriptor.name === 'learn')!;- const creatorLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');- const learnLink = path.join(input.homeDir, '.agents', 'skills', 'learn');+ const creatorLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');+ const learnLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'learn');const nativeCreatorLink = initialCreator.nativeClaudePath;const nativeLearnLink = initialLearn.nativeClaudePath;const initialCreatorBytes = fs.realpathSync(initialCreator.absolutePath);@@ -435,7 +448,7 @@ describe('built-in Skills', () => {// Simulate termination after the manifest commit but before .active moved.fs.unlinkSync(activePath);fs.symlinkSync(oldActiveTarget, activePath, process.platform === 'win32' ? 'junction' : 'dir');- const sharedLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const sharedLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');expect(fs.realpathSync(sharedLink)).toBe(oldCreatorBytes);const recovered = await prepareBuiltInSkills({@@ -464,7 +477,7 @@ describe('built-in Skills', () => {fs.writeFileSync(path.join(redirectedCreator, 'SKILL.md'), '# Redirected\n');fs.unlinkSync(activePath);fs.symlinkSync(redirectedRoot, activePath, process.platform === 'win32' ? 'junction' : 'dir');- const sharedLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const sharedLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');expect(fs.realpathSync(sharedLink)).toBe(fs.realpathSync(redirectedCreator));const recovered = await prepareBuiltInSkills(input);@@ -597,7 +610,7 @@ describe('built-in Skills', () => {expect(fs.lstatSync(orphanRoot).isSymbolicLink()).toBe(false);expect(fs.lstatSync(orphanRoot).isDirectory()).toBe(true);expect(fs.realpathSync(orphanRoot)).not.toBe(bundleRoot);- const creatorLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const creatorLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');fs.unlinkSync(creatorLink);fs.symlinkSync(path.join(orphanRoot, 'cindy-skill-creator'),@@ -623,7 +636,7 @@ describe('built-in Skills', () => {const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');const descriptor = initial.descriptors[0]!;const immutableTarget = fs.realpathSync(descriptor.absolutePath);- const sharedLink = path.join(input.homeDir, '.agents', 'skills', descriptor.name);+ const sharedLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', descriptor.name);fs.unlinkSync(sharedLink);fs.symlinkSync(immutableTarget,@@ -644,7 +657,7 @@ describe('built-in Skills', () => {const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');const orphanBundle = 'v8-bbbbbbbbbbbbbbbb-00000000-0000-0000-0000-000000000000';const orphanRoot = path.join(root, '.versions', orphanBundle);- const sharedLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const sharedLink = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');const nativeLink = path.join(input.userDataDir, 'claude-home', 'skills', 'cindy-skill-creator');fs.mkdirSync(path.join(orphanRoot, 'cindy-skill-creator'), { recursive: true });fs.writeFileSync(@@ -669,6 +682,7 @@ describe('built-in Skills', () => {);const recovered = await prepareBuiltInSkills(input);+ await migrateBuiltInGlobalSkillLinks(input);expect(recovered.projectionSafe).toBe(false);expect(recovered.warnings.join('\n')).toContain('missing SKILL.md');@@ -724,16 +738,16 @@ describe('built-in Skills', () => {expect(fs.readFileSync(path.join(userSkill, 'SKILL.md'), 'utf8')).toBe('# User copy\n');expect(fs.existsSync(path.join(result.descriptors[0]!.absolutePath, 'SKILL.md'))).toBe(true);expect(fs.realpathSync(result.descriptors[0]!.nativeClaudePath)).toBe(- fs.realpathSync(userSkill),+ fs.realpathSync(result.descriptors[0]!.absolutePath),);- expect(result.warnings.join('\n')).toContain('already owned by the user');+ expect(result.warnings).toEqual([]);});it('keeps every profile on one stable shared copy', async () => {const input = fixture();const first = await prepareAndProjectBuiltInSkills(input);const sharedDescriptor = first.descriptors[0]!;- const link = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const link = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');const nextUserDataDir = path.join(path.dirname(input.userDataDir), 'next-user-data');const next = await prepareAndProjectBuiltInSkills({ ...input, userDataDir: nextUserDataDir });@@ -750,7 +764,7 @@ describe('built-in Skills', () => {const input = fixture();const oldProfile = path.join(input.appDataDir, 'CindyDev-dev2-old-checkout');const oldTarget = path.join(oldProfile, 'system-skills', 'cindy-skill-creator');- const link = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const link = path.join(builtInSkillPluginRoot(input.userDataDir), 'skills', 'cindy-skill-creator');fs.mkdirSync(path.dirname(link), { recursive: true });fs.symlinkSync(oldTarget, link, process.platform === 'win32' ? 'junction' : 'dir');@@ -780,8 +794,7 @@ describe('built-in Skills', () => {expect(fs.existsSync(result.descriptors[0]!.absolutePath)).toBe(true);expect(fs.realpathSync(path.join(- input.homeDir,- '.agents',+ builtInSkillPluginRoot(input.userDataDir),'skills','cindy-skill-creator',))).toBe(fs.realpathSync(result.descriptors[0]!.absolutePath));@@ -818,7 +831,7 @@ describe('built-in Skills', () => {const result = await prepareAndProjectBuiltInSkills(input);expect(fs.realpathSync(userSkill)).toBe(fs.realpathSync(userSource));- expect(result.warnings.join('\n')).toContain('already owned by the user');+ expect(result.warnings).toEqual([]);});it('keeps a user-owned Skill in the isolated Claude config directory', async () => {@@ -831,39 +844,57 @@ describe('built-in Skills', () => {expect(fs.readFileSync(path.join(nativeClaudePath, 'SKILL.md'), 'utf8')).toBe('# Claude user copy\n',);- expect(result.warnings.join('\n')).toContain('already owned by the user');+ expect(result.warnings).toEqual([]);});- it('refreshes the isolated Claude runtime when the palette winner changes', async () => {+ it('keeps the private Claude plugin independent of user palette winners', async () => {const input = fixture();- const first = await prepareAndProjectBuiltInSkills(input);+ const first = await prepareBuiltInSkills(input);const descriptor = first.descriptors.find((item) => item.name === 'learn')!;- const sharedSkill = path.join(input.homeDir, '.agents', 'skills', 'learn');- expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(fs.realpathSync(sharedSkill));-- const claudePaletteSkill = path.join(input.homeDir, '.claude', 'skills', 'learn');- fs.mkdirSync(claudePaletteSkill, { recursive: true });- fs.writeFileSync(path.join(claudePaletteSkill, 'SKILL.md'), '# User Claude Learn\n');-- const updated = await refreshBuiltInClaudeSkillLinks({- ...input,- descriptors: first.descriptors,- });-+ const userSkill = path.join(input.homeDir, '.claude', 'skills', 'learn');+ fs.mkdirSync(userSkill, { recursive: true });+ fs.writeFileSync(path.join(userSkill, 'SKILL.md'), '# User Learn');+ const updated = await refreshBuiltInClaudeSkillLinks({ ...input, descriptors: first.descriptors });expect(updated.warnings).toEqual([]);- expect(fs.realpathSync(sharedSkill)).toBe(fs.realpathSync(descriptor.absolutePath));- expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(- fs.realpathSync(claudePaletteSkill),- );+ expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(fs.realpathSync(descriptor.absolutePath));+ expect(fs.readFileSync(path.join(userSkill, 'SKILL.md'), 'utf8')).toBe('# User Learn');+ expect(fs.existsSync(path.join(input.homeDir, '.agents'))).toBe(false);+ });- fs.rmSync(claudePaletteSkill, { recursive: true, force: true });- const restored = await refreshBuiltInClaudeSkillLinks({- ...input,- descriptors: first.descriptors,- });+ it('migrates both old global links and does not recreate them on restart', async () => {+ const input = fixture();+ const first = await prepareBuiltInSkills(input);+ for (const descriptor of first.descriptors) {+ const shared = path.join(input.homeDir, '.agents', 'skills', descriptor.name);+ const claude = path.join(input.homeDir, '.claude', 'skills', descriptor.name);+ fs.mkdirSync(path.dirname(shared), { recursive: true });+ fs.mkdirSync(path.dirname(claude), { recursive: true });+ fs.symlinkSync(descriptor.absolutePath, shared, process.platform === 'win32' ? 'junction' : 'dir');+ fs.symlinkSync(shared, claude, process.platform === 'win32' ? 'junction' : 'dir');+ }+ expect(await migrateBuiltInGlobalSkillLinks(input)).toEqual([]);+ await prepareBuiltInSkills(input);+ expect(fs.readdirSync(path.join(input.homeDir, '.agents', 'skills'))).toEqual([]);+ expect(fs.readdirSync(path.join(input.homeDir, '.claude', 'skills'))).toEqual([]);+ for (const descriptor of first.descriptors) expect(fs.existsSync(descriptor.nativeClaudePath)).toBe(true);+ });- expect(restored.warnings).toEqual([]);- expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(fs.realpathSync(sharedSkill));+ it('preserves user directories and foreign links during the legacy migration', async () => {+ const input = fixture();+ await prepareBuiltInSkills(input);+ const userSkill = path.join(input.homeDir, '.agents', 'skills', 'learn');+ const userAlias = path.join(input.homeDir, '.claude', 'skills', 'learn');+ fs.mkdirSync(userSkill, { recursive: true });+ fs.mkdirSync(path.dirname(userAlias), { recursive: true });+ fs.writeFileSync(path.join(userSkill, 'SKILL.md'), '# User Learn');+ fs.symlinkSync(userSkill, userAlias, process.platform === 'win32' ? 'junction' : 'dir');+ const foreign = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');+ const foreignTarget = path.join(input.homeDir, 'user-missing');+ fs.symlinkSync(foreignTarget, foreign, process.platform === 'win32' ? 'junction' : 'dir');+ expect(await migrateBuiltInGlobalSkillLinks(input)).toEqual([]);+ expect(fs.readFileSync(path.join(userSkill, 'SKILL.md'), 'utf8')).toBe('# User Learn');+ expect(fs.realpathSync(userAlias)).toBe(fs.realpathSync(userSkill));+ expect(fs.readlinkSync(foreign)).toContain('user-missing');});it('attests only commands backed by the materialized Cindy copy', async () => {@@ -914,6 +945,19 @@ describe('built-in Skills', () => {expect(skills[0]?.builtIn).toBeUndefined();});+ it('attests and deactivates namespaced Cindy commands without trusting the namespace alone', async () => {+ const input = fixture();+ const { descriptors } = await prepareBuiltInSkills(input);+ const descriptor = descriptors[0]!;+ const command = {+ kind: 'agent-skill' as const, name: `cindy:${descriptor.name}`, source: 'skill' as const,+ runtimeCommandName: `cindy:${descriptor.name}`, path: path.join(descriptor.absolutePath, 'SKILL.md'), enabled: true,+ };+ expect(markCindyBuiltInAgentSkills([command], descriptors)[0]?.builtIn).toBe(true);+ expect(markCindyBuiltInAgentSkills([{ ...command, path: '/user/SKILL.md' }], descriptors)[0]?.builtIn).toBeUndefined();+ expect(activeCindyBuiltInAgentSkills([command], descriptors, () => false)).toEqual([]);+ });+it('resolves source and packaged resource roots', () => {expect(resolveBundledSystemSkillsRoot({diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.tsindex b3dfb2abe5..6057f9565f 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts@@ -40,6 +40,11 @@ vi.mock('electron', () => ({safeStorage: { isEncryptionAvailable: () => h.encryptionAvailable },}));+// Skill discovery is covered by managed-skills.test.ts, not this runtime/auth fixture.+vi.mock('../managed-skills.js', () => ({+ listCindyManagedSkills: async () => [],+ cindyManagedSkillRoots: async () => [],+}));vi.mock('@cindy/maker-core', () => ({}));vi.mock('../../appCapabilities.js', () => ({diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.tsindex 38739a63d2..7b49ec31f2 100644--- a/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts@@ -4,6 +4,7 @@ import path from 'node:path';import { EventEmitter } from 'node:events';import { PassThrough } from 'node:stream';import { shell } from 'electron';+import { prepareCodexGlobalSkillsLinks } from '../codex-global-skills.js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const state = vi.hoisted(() => ({@@ -66,6 +67,7 @@ import {loginCodexAccount,logoutCodexAccount,parseCodexAccountIdentity,+ prepareCodexAccountHome,setCodexAccountRetirement,} from '../codex-account-auth';@@ -95,6 +97,36 @@ afterEach(() => {});describe('native Codex account credentials', () => {+ it('mounts private built-in and plugin skills in every independent account home', async () => {+ const real = await vi.importActual<typeof import('../codex-global-skills.js')>('../codex-global-skills.js');+ vi.mocked(prepareCodexGlobalSkillsLinks).mockImplementationOnce((home, options) =>+ real.prepareCodexGlobalSkillsLinks(home, { ...options, homeDir: path.join(state.root, 'user-home') }),+ ).mockImplementationOnce((home, options) =>+ real.prepareCodexGlobalSkillsLinks(home, { ...options, homeDir: path.join(state.root, 'user-home') }),+ );+ const roots = [path.join(state.root, 'shared-system-skills', 'version'), path.join(state.root, 'owner-a', 'ghost-install-state', 'skill-snapshots', 'example', 'rev')];+ for (const [index, root] of roots.entries()) {+ const skill = path.join(root, 'skills', index === 0 ? 'learn' : 'example--demo');+ fs.mkdirSync(skill, { recursive: true });+ fs.writeFileSync(path.join(skill, 'SKILL.md'), `skill-${index}`);+ }+ const homes: string[] = [];+ const managedSkills = roots.map((root, index) => ({+ kind: 'agent-skill' as const, source: 'skill' as const, name: index === 0 ? 'learn' : 'demo',+ path: path.join(root, 'skills', index === 0 ? 'learn' : 'example--demo', 'SKILL.md'),+ claudeCommandName: index === 0 ? 'cindy:learn' : 'cindy-plugin-example:demo',+ }));+ for (const provider of ['account-a', 'account-b']) {+ expect((await loginCodexAccount(provider, () => true)).ok).toBe(true);+ const home = await prepareCodexAccountHome(provider, [state.root], managedSkills);+ homes.push(home);+ expect(fs.readFileSync(path.join(home, 'skills', real.codexManagedSkillLinkName('cindy:learn'), 'SKILL.md'), 'utf8')).toBe('skill-0');+ expect(fs.readFileSync(path.join(home, 'skills', real.codexManagedSkillLinkName('cindy-plugin-example:demo'), 'SKILL.md'), 'utf8')).toBe('skill-1');+ }+ expect(homes[0]).not.toBe(homes[1]);+ expect(fs.existsSync(path.join(state.root, 'user-home'))).toBe(false);+ });+it('leaves opening the authorization page to Codex even when both streams print its URL', async () => {const progress = vi.fn();expect((await loginCodexAccount('account-a', () => true, progress)).ok).toBe(true);diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.tsindex 7b00b55abc..9ba96989b2 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts@@ -27,6 +27,12 @@ vi.mock('electron', () => ({safeStorage: { isEncryptionAvailable: () => false },}));+// Skill discovery is covered separately; keep cold plugin transforms out of auth timing.+vi.mock('../managed-skills.js', () => ({+ listCindyManagedSkills: async () => [],+ cindyManagedSkillRoots: async () => [],+}));+vi.mock('@cindy/maker-core', () => ({}));vi.mock('../../authBoundaryQuarantine.js', async (importOriginal) => {diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.tsindex 2bcfccfdb0..4d7e3d17fa 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts@@ -36,6 +36,11 @@ vi.mock('electron', () => ({safeStorage: { isEncryptionAvailable: () => false },}));+// Skill discovery is covered by managed-skills.test.ts, not this runtime/auth fixture.+vi.mock('../managed-skills.js', () => ({+ listCindyManagedSkills: async () => [],+ cindyManagedSkillRoots: async () => [],+}));vi.mock('@cindy/maker-core', () => ({}));vi.mock('../../agent-binaries/index.js', () => ({@@ -247,6 +252,8 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {h.dataOwnerId = 'owner-a';const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();+ // This fixture owns credentials only; asset preparation has separate boundary tests.+ vi.spyOn(adapter, 'ensureGlobalCodexAssets').mockResolvedValue();await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({authenticated: true,@@ -956,6 +963,7 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();let finishLogout!: () => void;+ vi.spyOn(adapter, 'ensureGlobalCodexAssets').mockResolvedValue();const logoutOperation = new Promise<void>((resolve) => {finishLogout = resolve;});diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.tsindex 1a24bd90ab..04cb45a5bb 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts@@ -20,6 +20,12 @@ vi.mock('electron', () => ({safeStorage: { isEncryptionAvailable: () => false },}));+// Skill discovery is covered separately; keep cold plugin transforms out of login timing.+vi.mock('../managed-skills.js', () => ({+ listCindyManagedSkills: async () => [],+ cindyManagedSkillRoots: async () => [],+}));+vi.mock('@cindy/maker-core', () => ({}));describe('DesktopCodexAuthAdapter login single-flight', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/managed-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/managed-skills.test.tsnew file mode 100644index 0000000000..bba89d5309--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/managed-skills.test.ts@@ -0,0 +1,173 @@+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({+ root: '',+ owner: 'a',+ pending: false,+ enabled: true,+ verified: true,+}));+vi.mock('electron', () => ({ app: { getPath: () => state.root } }));+vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => state.owner,+ getActiveAppSession: () => ({ dataOwnerId: state.owner }),+ isAppSessionBoundaryPending: () => state.pending,+}));+vi.mock('../../authBoundaryQuarantine.js', () => ({+ withSharedGlobalSkillProjectionMutation: async (_owner: string, work: () => Promise<unknown>) =>+ work(),+}));+vi.mock('../built-in-skills.js', () => ({+ sharedBuiltInSkillsRoot: (root: string) => path.join(root, 'shared-system-skills'),+ builtInSkillDescriptors: () => [+ { name: 'learn', absolutePath: path.join(state.root, 'shared-system-skills', 'skills', 'learn') },+ ],+}));+vi.mock('../../cindy-brain/index.js', () => ({+ getGhostManager: () => ({ verifyApprovedSkillSnapshot: async () => state.verified }),+ listAvailableGhostsForAuthorization: () => [+ {+ enabled: state.enabled,+ approvedSkillRoot: path.join(+ state.root,+ state.owner,+ 'ghost-install-state',+ 'skill-snapshots',+ 'rev',+ ),+ manifest: {+ id: 'my-plugin',+ skill: {+ items: [{ name: 'demo', dir: 'skills/demo', description: 'Approved description' }],+ },+ },+ },+ ],+}));+import { listCindyManagedSkills, prepareCindyCodexSkills } from '../managed-skills.js';+import { codexManagedSkillLinkName } from '../codex-global-skills.js';++async function writeSkill(root: string, slot: string, name: string) {+ const dir = path.join(root, 'skills', slot);+ await fs.mkdir(dir, { recursive: true });+ await fs.writeFile(+ path.join(dir, 'SKILL.md'),+ `---\nname: "${name}"\ndescription: Fixture\n---\nBody`,+ );+}++beforeEach(async () => {+ state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-managed-skill-catalog-'));+ state.owner = 'a';+ state.pending = false;+ state.enabled = true;+ state.verified = true;+ await writeSkill(path.join(state.root, 'shared-system-skills'), 'learn', 'learn');+ await writeSkill(+ path.join(state.root, 'a', 'ghost-install-state', 'skill-snapshots', 'rev'),+ 'demo',+ ' demo ',+ );+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(state.root, 'user-home'));+});+afterEach(async () => {+ vi.restoreAllMocks();+ await fs.rm(state.root, { recursive: true, force: true });+});++describe('Cindy managed skill catalog', () => {+ it('uses verified sources and manifest names despite real-directory and foreign-link projection conflicts', async () => {+ await writeSkill(path.join(state.root, 'managed-agent-skills', 'cindy'), 'learn', 'impostor');+ const ghostRoot = path.join(state.root, 'a', 'ghost-install-state', 'agent-skills');+ await writeSkill(ghostRoot, 'my-plugin--demo', 'unapproved');+ await fs.symlink(+ path.join(ghostRoot, 'skills', 'my-plugin--demo'),+ path.join(ghostRoot, 'skills', 'foreign--demo'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const skills = await listCindyManagedSkills();+ expect(skills.map((skill) => skill.claudeCommandName)).toEqual([+ 'cindy:learn',+ 'cindy-plugin-my-plugin:demo',+ ]);+ expect(skills.map((skill) => skill.path)).toEqual(+ await Promise.all([+ fs.realpath(path.join(state.root, 'shared-system-skills', 'skills', 'learn', 'SKILL.md')),+ fs.realpath(+ path.join(+ state.root,+ 'a',+ 'ghost-install-state',+ 'skill-snapshots',+ 'rev',+ 'skills',+ 'demo',+ 'SKILL.md',+ ),+ ),+ ]),+ );+ expect(skills[1]?.description).toBe('Approved description');+ state.owner = 'b';+ expect((await listCindyManagedSkills()).map((skill) => skill.claudeCommandName)).toEqual([+ 'cindy:learn',+ ]);+ });++ it.each(['disabled', 'unverified'])(+ 'does not discover a %s plugin from an occupied slot',+ async (mode) => {+ await writeSkill(+ path.join(state.root, 'a', 'ghost-install-state', 'agent-skills'),+ 'my-plugin--demo',+ 'demo',+ );+ if (mode === 'disabled') state.enabled = false;+ else state.verified = false;+ expect((await listCindyManagedSkills()).map((skill) => skill.claudeCommandName)).toEqual([+ 'cindy:learn',+ ]);+ },+ );++ it('refuses discovery during an account boundary', async () => {+ state.pending = true;+ await expect(listCindyManagedSkills()).rejects.toThrow('Skill owner is changing');+ });++ it('revokes disabled plugin projections from default and independent Codex homes without deleting sources', async () => {+ const homes = ['default', 'account-a', 'account-b'].map((name) => path.join(state.root, name));+ const linkName = codexManagedSkillLinkName('cindy-plugin-my-plugin:demo');+ const source = path.join(+ state.root,+ 'a',+ 'ghost-install-state',+ 'skill-snapshots',+ 'rev',+ 'skills',+ 'demo',+ 'SKILL.md',+ );+ for (const home of homes) {+ await prepareCindyCodexSkills(home);+ expect(await fs.realpath(path.join(home, 'skills', linkName, 'SKILL.md'))).toBe(+ await fs.realpath(source),+ );+ await fs.mkdir(path.join(home, 'skills', 'cindy-user-owned'));+ }+ state.enabled = false;+ for (const home of homes) {+ await prepareCindyCodexSkills(home);+ await expect(fs.lstat(path.join(home, 'skills', linkName))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect((await fs.stat(path.join(home, 'skills', 'cindy-user-owned'))).isDirectory()).toBe(+ true,+ );+ }+ expect(await fs.readFile(source, 'utf8')).toContain('Fixture');+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.tsindex 8d8cac6ef2..0b7027e0f6 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts@@ -16,6 +16,11 @@ const state = vi.hoisted(() => ({capToolchainThreads: true,}));+// Skill discovery is covered by managed-skills.test.ts, not this runtime/auth fixture.+vi.mock('../managed-skills.js', () => ({+ listCindyManagedSkills: async () => [],+ cindyManagedSkillRoots: async () => [],+}));// Account discovery persistence is outside this runtime/route fixture.vi.mock('../model-discovery/xai.js', () => ({discardXaiModelsDiskCache: vi.fn(async () => {}),diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsindex 851f10c5a3..3d6d23e40e 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@ -9,6 +9,11 @@ import path from 'node:path';import { BUNDLED_CATALOG, PROVIDER_MODEL_CATALOG, providerModelRecord, buildUserProvider, providerPresetOAuth, parseModelsListResponse, mergeDiscoveredRuntimeModels, type Catalog } from '@cindy/model-providers';+// Skill discovery is covered by managed-skills.test.ts, not this runtime/auth fixture.+vi.mock('../managed-skills.js', () => ({+ listCindyManagedSkills: async () => [],+ cindyManagedSkillRoots: async () => [],+}));// Account discovery persistence is outside this runtime/route fixture.vi.mock('../model-discovery/xai.js', () => ({discardXaiModelsDiskCache: vi.fn(async () => {}),diff --git a/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts b/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.tsindex 334dcee9b5..556bb9a840 100644--- a/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts@@ -12,6 +12,11 @@ const state = vi.hoisted(() => ({userDataPath: '',}));+// Skill discovery is covered by managed-skills.test.ts, not this runtime/auth fixture.+vi.mock('../managed-skills.js', () => ({+ listCindyManagedSkills: async () => [],+ cindyManagedSkillRoots: async () => [],+}));// Account discovery persistence is outside this runtime/route fixture.vi.mock('../model-discovery/xai.js', () => ({discardXaiModelsDiskCache: vi.fn(async () => {}),diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex 0a1640d06a..ad91e9beac 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -1,3 +1,4 @@+import { cindyManagedSkillRoots, listCindyManagedSkills } from './managed-skills.js';import { retainInvalidatedProviderPresentation, retainProviderPresentationAfterAuthChange } from './provider-presentation-store.js';import { subscriptionAccountKind, subscriptionAccountState } from './subscription-account-auth.js';/**@@ -42,7 +43,7 @@ import { prepareSharedGlobalSkillLinks } from './shared-global-skills.js';import { PreparationCache } from './preparation-cache.js';import {prepareBuiltInSkills,- refreshBuiltInClaudeSkillLinks,+ migrateBuiltInGlobalSkillLinks,resolveBundledSystemSkillsRoot,} from './built-in-skills.js';import {@@ -630,26 +631,17 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {userDataDir: app.getPath('userData'),appDataDir: app.getPath('appData'),});+ const migrationWarnings = preparedBuiltIns.projectionSafe+ ? await migrateBuiltInGlobalSkillLinks({ userDataDir: app.getPath('userData'), appDataDir: app.getPath('appData') })+ : [];const sharedProjection = await prepareSharedGlobalSkillLinks({assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),});- // Publication already established a usable Claude projection before- // switching the active pointer. Reconcile once more after the generic- // palette sync so a newly surfaced user-owned ~/.claude winner keeps- // precedence; atomic link replacement preserves the usable projection- // if this optional refinement fails.- const claudePaletteProjection = preparedBuiltIns.projectionSafe- ? await refreshBuiltInClaudeSkillLinks({- userDataDir: app.getPath('userData'),- appDataDir: app.getPath('appData'),- descriptors: preparedBuiltIns.descriptors,- })- : { warnings: [] };return {warnings: [...preparedBuiltIns.warnings,+ ...migrationWarnings,...sharedProjection.warnings,- ...claudePaletteProjection.warnings,],};});@@ -930,10 +922,10 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {/*** Plugin capability enforcement is always rechecked after concurrent callers- * settle. Only successful Skill/rules preparation has a 30-second TTL.+ * settle. Skill projections also refresh at each launch so a removed or+ * disabled approved source cannot survive in a cached Codex discovery root.*/private readonly pendingAssetsPrep = new PreparationCache(0);- private readonly skillAssetsPrep = new PreparationCache(30_000);/*** 进行中的 reconcileWithSystemCodex 调用 —— 多个调用点 (构造 / getState / getAuthEnv /@@ -1371,18 +1363,15 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {async ensureGlobalCodexAssets(): Promise<void> {const scope = preparationScope();await this.pendingAssetsPrep.ensure(scope.key, async () => {- await this.skillAssetsPrep.ensure(scope.key, async () => {- const success = await this.runEnsureGlobalCodexSkills(scope.ownerId);- return success && scope.current();- });+ await this.runEnsureGlobalCodexSkills(scope.ownerId);await this.runEnsureGlobalCodexPlugins();return true;});}private async runEnsureGlobalCodexSkills(ownerId: string | null): Promise<boolean> {- // Load-bearing order: Codex skill linking scans ~/.agents/skills, so shared- // links must populate that directory before prepareCodexGlobalSkillsLinks runs.+ // Prepare the private built-in roots before Codex snapshots discovery.+ await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();const sharedOutcome = await withSharedGlobalSkillProjectionMutation(ownerId, () =>prepareSharedGlobalSkillLinks({assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),@@ -1393,7 +1382,9 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {);const [skillsOutcome, rulesOutcome] = await Promise.all([- prepareCodexGlobalSkillsLinks(this.codexHome).then(+ withSharedGlobalSkillProjectionMutation(ownerId, async () =>+ prepareCodexGlobalSkillsLinks(this.codexHome, { managedRoots: await cindyManagedSkillRoots(), managedSkills: await listCindyManagedSkills() }),+ ).then((r) => ({ ok: true as const, label: 'skills' as const, warnings: r.warnings }),(err: Error) => ({ ok: false as const, label: 'skills' as const, err }),),@@ -1404,6 +1395,8 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {]);const outcomes = [sharedOutcome, skillsOutcome, rulesOutcome];+ // A failed verified catalog must not fall back to yesterday's projections.+ if (!skillsOutcome.ok) throw skillsOutcome.err;for (const outcome of outcomes) {if (!outcome.ok) {assetPrepLog.warn('prepare Codex global asset failed', {@@ -2503,7 +2496,11 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {async getAuthEnv(options?: AuthAdapterOptions): Promise<Record<string, string>> {if (isCodexAccountProvider(options?.providerId)) {- return { CODEX_HOME: await prepareCodexAccountHome(options!.providerId!) };+ const ownerId = getActiveAppSession().dataOwnerId;+ await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();+ return { CODEX_HOME: await withSharedGlobalSkillProjectionMutation(ownerId, async () =>+ prepareCodexAccountHome(options!.providerId!, await cindyManagedSkillRoots(), await listCindyManagedSkills()),+ ) };}this.ensureInvalidationMarkerLoaded();await this.ensureGlobalCodexAssets();diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.tsindex 9f25579445..85067d4106 100644--- a/apps/desktop/src/main/maker-host/built-in-skills.ts+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts@@ -26,6 +26,7 @@ export const BUILT_IN_SKILLS_BUNDLE_VERSION = 12;export interface BuiltInSkillDescriptor {name: string;absolutePath: string;+ /** Profile-owned discovery projection (legacy field name); never a user-global path. */nativeClaudePath: string;}@@ -98,6 +99,10 @@ export function resolveBundledSystemSkillsRoot(input: {: path.join(input.appPath, 'resources', 'system-skills');}+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');}@@ -149,7 +154,7 @@ function builtInSkillDescriptorsAtRoot(return BUILT_IN_SKILL_NAMES.map((name) => ({name,absolutePath: path.join(root, name),- nativeClaudePath: path.join(userDataDir, 'claude-home', 'skills', name),+ nativeClaudePath: path.join(builtInSkillPluginRoot(userDataDir), 'skills', name),}));}@@ -652,14 +657,13 @@ async function removeActiveBundlePointer(root: string): Promise<boolean> {async function ensureSharedEntry(descriptor: BuiltInSkillDescriptor,- homeDir: string,legacyUserDataDir: string,appDataDir?: string,replaceDirectoryEntryAtomically?: AtomicReplaceDirectoryEntry,): Promise<{ changed: boolean; warning?: string; targetPath?: string }> {return ensureSkillEntry(descriptor,- path.join(homeDir, '.agents', 'skills', descriptor.name),+ descriptor.nativeClaudePath,true,legacyUserDataDir,appDataDir,@@ -674,7 +678,6 @@ async function refreshBuiltInSharedSkillLinksUnlocked(): Promise<RefreshBuiltInSharedSkillLinksResult> {const descriptors = options.descriptors?? builtInSkillDescriptors(options.userDataDir, options.appDataDir);- const homeDir = options.homeDir ?? os.homedir();const warnings: string[] = [];let changed = false;let complete = true;@@ -683,7 +686,6 @@ async function refreshBuiltInSharedSkillLinksUnlocked(try {const linked = await ensureSharedEntry(descriptor,- homeDir,options.userDataDir,options.appDataDir,options.replaceDirectoryEntryAtomically,@@ -701,7 +703,7 @@ async function refreshBuiltInSharedSkillLinksUnlocked(return { changed, complete, warnings };}-/** Refresh the home-level shared projection. Call only inside the stable owner boundary. */+/** Refresh private skill projections. Call only inside the stable owner boundary. */export async function refreshBuiltInSharedSkillLinks(options: RefreshBuiltInSharedSkillLinksOptions,): Promise<RefreshBuiltInSharedSkillLinksResult> {@@ -725,13 +727,10 @@ function realPathOrNormalized(value: string): string {catch { return normalizeForCompare(value); }}-async function hasSkillFile(skillDir: string): Promise<boolean> {- for (const fileName of ['SKILL.md', 'skill.md']) {- if ((await fsp.stat(path.join(skillDir, fileName)).catch(() => null))?.isFile()) {- return true;- }- }- return false;+function builtInCommandName(skill: AgentSkillCommand): string {+ return skill.name.startsWith('cindy:') && skill.runtimeCommandName === skill.name+ ? skill.name.slice('cindy:'.length)+ : skill.name;}/** Main-owned attestation used by the renderer; names and descriptions are not trusted. */@@ -744,7 +743,7 @@ export function markCindyBuiltInAgentSkills(realPathOrNormalized(path.join(descriptor.absolutePath, 'SKILL.md')),]));return skills.map((skill) => {- const trustedPath = trustedSkillFiles.get(skill.name);+ const trustedPath = trustedSkillFiles.get(builtInCommandName(skill));const builtIn = Boolean(skill.path && trustedPath && realPathOrNormalized(skill.path) === trustedPath);if (builtIn) return { ...skill, builtIn: true };if (skill.builtIn === undefined) return skill;@@ -763,68 +762,36 @@ export function activeCindyBuiltInAgentSkills(const descriptorsByName = new Map(descriptors.map((descriptor) => [descriptor.name, descriptor]));return markCindyBuiltInAgentSkills(skills, descriptors).filter((skill) => {if (skill.builtIn !== true) return true;- const descriptor = descriptorsByName.get(skill.name);+ const descriptor = descriptorsByName.get(builtInCommandName(skill));return descriptor ? isEnabled(descriptor.absolutePath) : false;});}async function refreshBuiltInClaudeSkillLinksUnlocked(- options: Omit<RefreshBuiltInClaudeSkillLinksOptions, 'withSharedMutation'> & {- allowUnresolvedManagedSharedTarget?: boolean;- },+ options: Omit<RefreshBuiltInClaudeSkillLinksOptions, 'withSharedMutation'>,): Promise<RefreshBuiltInClaudeSkillLinksResult> {const descriptors = options.descriptors?? builtInSkillDescriptors(options.userDataDir, options.appDataDir);- const homeDir = options.homeDir ?? os.homedir();const warnings: string[] = [];let changed = false;let complete = true;for (const descriptor of descriptors) {- const sharedPath = path.join(homeDir, '.agents', 'skills', descriptor.name);- const claudePalettePath = path.join(homeDir, '.claude', 'skills', descriptor.name);- const hasClaudePaletteSkill = await hasSkillFile(claudePalettePath);- const claudeRuntimeTarget = hasClaudePaletteSkill ? claudePalettePath : sharedPath;- const unresolvedSharedTargetIsManaged = !hasClaudePaletteSkill- && options.allowUnresolvedManagedSharedTarget === true- && await isCindyManagedSystemSkillTarget(- sharedPath,- descriptor,- options.userDataDir,- options.appDataDir,- );- if (!(await hasSkillFile(claudeRuntimeTarget)) && !unresolvedSharedTargetIsManaged) {- complete = false;- warnings.push(- `could not expose built-in Skill ${descriptor.name} to Claude because its palette winner is unavailable`,- );- continue;- }try {- const linked = await ensureSkillEntry(- descriptor,- descriptor.nativeClaudePath,- true,- options.userDataDir,- options.appDataDir,- claudeRuntimeTarget,- [sharedPath, claudePalettePath],- options.replaceDirectoryEntryAtomically,- );+ const linked = await ensureSkillEntry(descriptor, descriptor.nativeClaudePath, true,+ options.userDataDir, options.appDataDir, undefined, [], options.replaceDirectoryEntryAtomically);changed = linked.changed || changed;- if (linked.warning) warnings.push(linked.warning);+ if (linked.warning) { complete = false; warnings.push(linked.warning); }} catch (error) {complete = false;- warnings.push(- `could not expose built-in Skill ${descriptor.name} to Claude: ${error instanceof Error ? error.message : String(error)}`,- );+ warnings.push(`could not expose built-in Skill ${descriptor.name}: ${String(error)}`);}}return { changed, complete, warnings };}-/** Keep Cindy's isolated Claude runtime pointed at the latest shared/palette winner. */+/** Refresh private projections used by Cindy's local Claude plugin and other harnesses. */export async function refreshBuiltInClaudeSkillLinks(options: RefreshBuiltInClaudeSkillLinksOptions,): Promise<RefreshBuiltInClaudeSkillLinksResult> {@@ -843,6 +810,32 @@ export async function refreshBuiltInClaudeSkillLinks(};}+/** Remove only old Cindy-owned links, inspecting fanout before its source. */+export async function migrateBuiltInGlobalSkillLinks(options: {+ userDataDir: string; appDataDir?: string; homeDir?: string;+}): Promise<string[]> {+ const warnings: string[] = [];+ const home = options.homeDir ?? os.homedir();+ // Descriptors here identify legacy targets, not official identity.+ const root = options.appDataDir ? sharedBuiltInSkillsRoot(options.appDataDir) : builtInSkillsRoot(options.userDataDir);+ for (const descriptor of stableBuiltInSkillDescriptors(root, options.userDataDir)) {+ const shared = path.join(home, '.agents', 'skills', descriptor.name);+ const sharedManaged = await isCindyManagedSystemSkillTarget(shared, descriptor, options.userDataDir, options.appDataDir);+ for (const entry of [path.join(home, '.claude', 'skills', descriptor.name),+ path.join(options.userDataDir, 'claude-home', 'skills', descriptor.name), shared]) {+ try {+ const before = await fsp.readlink(entry);+ if (!await isCindyManagedSystemSkillTarget(entry, descriptor, options.userDataDir, options.appDataDir,+ sharedManaged ? [shared] : [])) continue;+ if (await fsp.readlink(entry) === before) await fsp.unlink(entry);+ } catch (error) {+ if (!['ENOENT', 'EINVAL'].includes((error as NodeJS.ErrnoException).code ?? '')) warnings.push(String(error));+ }+ }+ }+ return warnings;+}+interface BuiltInProjectionSnapshot {path: string;kind: 'missing' | 'symlink' | 'other';@@ -855,7 +848,6 @@ function builtInProjectionPaths(): string[] {return [...new Set(descriptors.flatMap((descriptor) => [descriptor.nativeClaudePath,- path.join(homeDir, '.agents', 'skills', descriptor.name),]))];}@@ -993,29 +985,15 @@ async function removeInactiveBuiltInProjections(async function projectBuiltInSkillLinksUnlocked(options: PrepareBuiltInSkillsOptions,descriptors: readonly BuiltInSkillDescriptor[],- allowUnresolvedManagedSharedTarget = false,): Promise<{ changed: boolean; complete: boolean; warnings: string[] }> {- const homeDir = options.homeDir ?? os.homedir();- const shared = await refreshBuiltInSharedSkillLinksUnlocked({- userDataDir: options.userDataDir,- appDataDir: options.appDataDir,- homeDir,- descriptors,- replaceDirectoryEntryAtomically: options.replaceDirectoryEntryAtomically,- });- const claude = await refreshBuiltInClaudeSkillLinksUnlocked({+ // All harnesses now share one private projection. Preparing the old shared+ // and Claude branches twice would replace our own still-dangling entry.+ return refreshBuiltInClaudeSkillLinksUnlocked({userDataDir: options.userDataDir,appDataDir: options.appDataDir,- homeDir,descriptors,- allowUnresolvedManagedSharedTarget,replaceDirectoryEntryAtomically: options.replaceDirectoryEntryAtomically,});- return {- changed: shared.changed || claude.changed,- complete: shared.complete && claude.complete,- warnings: [...shared.warnings, ...claude.warnings],- };}/**@@ -1233,7 +1211,6 @@ export async function prepareBuiltInSkills(const candidateProjection = await projectBuiltInSkillLinksUnlocked(options,stableDescriptors,- true,);warnings.push(...candidateProjection.warnings);if (!candidateProjection.complete) {diff --git a/apps/desktop/src/main/maker-host/codex-account-auth.ts b/apps/desktop/src/main/maker-host/codex-account-auth.tsindex c252e58157..98432cca05 100644--- a/apps/desktop/src/main/maker-host/codex-account-auth.ts+++ b/apps/desktop/src/main/maker-host/codex-account-auth.ts@@ -4,7 +4,7 @@ import { spawn, type ChildProcess } from 'node:child_process';import fs from 'node:fs';import fsp from 'node:fs/promises';import path from 'node:path';-import type { AuthState } from '@cindy/maker-core';+import type { AgentDeps, AuthState } from '@cindy/maker-core';import { getActiveAppSession } from '../appSessionState.js';import { getCachedBinaryStatus, isVettedAgentBinaryPath } from '../agent-binaries/index.js';import { getActiveCatalog } from './active-catalog.js';@@ -120,10 +120,10 @@ export function codexAccountState(providerId: string): AuthState {}}-export async function prepareCodexAccountHome(providerId: string): Promise<string> {+export async function prepareCodexAccountHome(providerId: string, managedRoots: readonly string[], managedSkills: Awaited<ReturnType<NonNullable<AgentDeps['getManagedSkills']>>>): Promise<string> {if (!codexAccountState(providerId).authenticated) throw new Error('Codex account requires login');const home = codexAccountHome(providerId);- await Promise.all([prepareCodexGlobalSkillsLinks(home), prepareCodexGlobalRulesCopy(home)]);+ await Promise.all([prepareCodexGlobalSkillsLinks(home, { managedRoots, managedSkills }), prepareCodexGlobalRulesCopy(home)]);const plugins = await prepareCodexGlobalPluginsBridge(home, {capabilityRouting: DESKTOP_CAPABILITY_ROUTING_POLICY,});diff --git a/apps/desktop/src/main/maker-host/codex-global-skills.ts b/apps/desktop/src/main/maker-host/codex-global-skills.tsindex 2d1c8d943d..0fbd87bd2e 100644--- a/apps/desktop/src/main/maker-host/codex-global-skills.ts+++ b/apps/desktop/src/main/maker-host/codex-global-skills.ts@@ -6,6 +6,7 @@ import {ensureDirectoryLink,isDirectory,isSameOrInside,+ normalizeForCompare,realPathOrNull,removeManagedLink,type ManagedLinkStatus,@@ -14,7 +15,7 @@ import {export const CODEX_LEGACY_CODEX_SKILLS_LINK_NAME = 'xdt-codex';export const CODEX_SHARED_AGENTS_SKILLS_LINK_NAME = 'xdt-agents';-type SourceName = 'codex' | 'agents';+type SourceName = 'codex' | 'agents' | `cindy-${string}`;type LinkStatus = ManagedLinkStatus;export interface CodexGlobalSkillSourceResult {@@ -35,6 +36,28 @@ export interface CodexGlobalSkillsPrepareResult {interface PrepareOptions {homeDir?: string;+ /** Owned storage roots, used only to recognize obsolete projections. */+ managedRoots?: readonly string[];+ managedSkills?: readonly { path?: string; claudeCommandName: string }[];+}++export function codexManagedSkillLinkName(command: string): `cindy-${string}` {+ return `cindy-${encodeURIComponent(command)}`;+}++function isManagedSkillTarget(target: string, roots: readonly string[]): boolean {+ const normalized = normalizeForCompare(target);+ if (!roots.some((root) => isSameOrInside(normalized, normalizeForCompare(root)))) return false;+ const segments = normalized.split(path.sep);+ return (+ segments.includes('shared-system-skills') ||+ segments.some(+ (segment, index) =>+ (segment === 'ghost-install-state' &&+ ['skill-snapshots', 'agent-skills'].includes(segments[index + 1] ?? '')) ||+ (segment === 'managed-agent-skills' && segments[index + 1] === 'cindy'),+ )+ );}async function cleanupLegacyAggregate(codexHome: string): Promise<void> {@@ -96,10 +119,50 @@ export async function prepareCodexGlobalSkillsLinks(const sourceDefs: Array<{ name: SourceName; source: string; link: string }> = [{ name: 'codex', source: paths.legacyCodexSkillsDir, link: paths.legacyCodexSkillsLink },{ name: 'agents', source: paths.sharedAgentsSkillsDir, link: paths.sharedAgentsSkillsLink },+ ...(opts.managedSkills ?? []).flatMap((skill) =>+ skill.path+ ? [+ {+ name: codexManagedSkillLinkName(skill.claudeCommandName),+ source: path.dirname(skill.path),+ link: path.join(paths.skillsDir, codexManagedSkillLinkName(skill.claudeCommandName)),+ },+ ]+ : [],+ ),];+ // Never expose a whole projection directory: preserved conflicts in it are+ // not approved skills. Retire old aggregates and obsolete individual links.+ const desiredLinks = new Set(sourceDefs.map((source) => source.link));+ const ownedRoots = [...(opts.managedRoots ?? [])];+ for (const root of opts.managedRoots ?? []) {+ const realRoot = await realPathOrNull(root);+ if (realRoot) ownedRoots.push(realRoot);+ }+ const foreignLinks = new Set<string>();+ for (const entry of await fsp.readdir(paths.skillsDir)) {+ if (!entry.startsWith('cindy-')) continue;+ const link = path.join(paths.skillsDir, entry);+ if (!(await fsp.lstat(link)).isSymbolicLink()) continue;+ const rawTarget = await fsp.readlink(link);+ const target = path.resolve(paths.skillsDir, rawTarget);+ if (!isManagedSkillTarget(target, ownedRoots)) {+ foreignLinks.add(link);+ continue;+ }+ if (!desiredLinks.has(link) && (await fsp.readlink(link)) === rawTarget) {+ changed = (await removeManagedLink(link)) || changed;+ }+ }+const sources: CodexGlobalSkillSourceResult[] = [];for (const sourceDef of sourceDefs) {+ if (foreignLinks.has(sourceDef.link)) {+ sources.push({ ...sourceDef, status: 'conflict', reason: 'foreign skill link is preserved' });+ warnings.push(`cannot link Codex ${sourceDef.name} skills: foreign skill link is preserved`);+ continue;+ }if (!(await isDirectory(sourceDef.source))) {changed = (await removeManagedLink(sourceDef.link)) || changed;sources.push({ ...sourceDef, status: 'missing', reason: 'source directory does not exist' });@@ -122,6 +185,17 @@ export async function prepareCodexGlobalSkillsLinks(}}+ // All callers share the same success contract: a verified managed Skill must+ // have its current entry. User compatibility roots retain warning semantics.+ const failedManagedSource = sources.find(+ (source) => source.name.startsWith('cindy-') && !['linked', 'kept'].includes(source.status),+ );+ if (failedManagedSource) {+ throw new Error(+ `Cannot prepare Codex managed Skill ${failedManagedSource.name}: ${failedManagedSource.reason ?? failedManagedSource.status}`,+ );+ }+return {codexHome: paths.codexHome,skillsDir: paths.skillsDir,diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 7337a0d258..4c5529b5e8 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -1,3 +1,4 @@+import { listCindyManagedSkills, prepareCindyCodexSkills } from './managed-skills.js';import { createCompanionImportProvider } from '../bot-import/importProvider.js';import { createCompanionConnectionsProvider } from '../bot-import/connectionProvider.js';import { resolveCompanionRuntimeEnvironment } from '../bot-import/runtime.js';@@ -1172,6 +1173,7 @@ export function getMaker(): Maker {const claudeAgent = new ClaudeCodeAgent({resolveSessionEnvironment: resolveCompanionRuntimeEnvironment,getDisabledSkillPaths: readDisabledSkillPaths,+ getManagedSkills: listCindyManagedSkills,auth: desktopClaudeAuthAdapter,runtimeConfig: buildDesktopClaudeRuntimeConfig(getClaudeEndpoint),binaryPath: claudePath,@@ -1500,6 +1502,8 @@ export function getMaker(): Maker {const codexAgent = new CodexAgent({resolveSessionEnvironment: resolveCompanionRuntimeEnvironment,getDisabledSkillPaths: readDisabledSkillPaths,+ getManagedSkills: listCindyManagedSkills,+ prepareCodexSkills: prepareCindyCodexSkills,auth: desktopCodexAuthAdapter,runtimeConfig: desktopCodexRuntimeConfig,binaryPath: codexPath,diff --git a/apps/desktop/src/main/maker-host/managed-skills.ts b/apps/desktop/src/main/maker-host/managed-skills.tsnew file mode 100644index 0000000000..b4540fd0af--- /dev/null+++ b/apps/desktop/src/main/maker-host/managed-skills.ts@@ -0,0 +1,81 @@+import fs from 'node:fs';+import path from 'node:path';+import { app } from 'electron';+import matter from 'gray-matter';+import {+ activeOwnerScopeKey,+ getActiveAppSession,+ isAppSessionBoundaryPending,+} from '../appSessionState.js';+import type { AgentDeps } from '@cindy/maker-core';+import { builtInSkillDescriptors, sharedBuiltInSkillsRoot } from './built-in-skills.js';+import { getGhostManager, listAvailableGhostsForAuthorization } from '../cindy-brain/index.js';+import { withSharedGlobalSkillProjectionMutation } from '../authBoundaryQuarantine.js';+import { prepareCodexGlobalSkillsLinks } from './codex-global-skills.js';++/** Reconcile the selected app-server home, including independently routed accounts. */+export async function prepareCindyCodexSkills(codexHome: string): Promise<void> {+ const ownerId = getActiveAppSession().dataOwnerId;+ await withSharedGlobalSkillProjectionMutation(ownerId, async () => {+ await prepareCodexGlobalSkillsLinks(codexHome, {+ managedRoots: await cindyManagedSkillRoots(),+ managedSkills: await listCindyManagedSkills(),+ });+ });+}++/** Ownership roots for retiring private Codex links, never directories to scan. */+export async function cindyManagedSkillRoots(): Promise<string[]> {+ return [app.getPath('userData'), sharedBuiltInSkillsRoot(app.getPath('appData'))];+}++export const listCindyManagedSkills: NonNullable<AgentDeps['getManagedSkills']> = async () => {+ const owner = activeOwnerScopeKey();+ if (isAppSessionBoundaryPending()) throw new Error('Skill owner is changing');+ const builtIns = builtInSkillDescriptors(app.getPath('userData'), app.getPath('appData'));+ const skills: Awaited<ReturnType<NonNullable<AgentDeps['getManagedSkills']>>> = [];+ const addSkill = (directory: string, name: string, namespace: string, description?: string) => {+ try {+ // Bind the verified source itself, not a mutable discovery projection.+ const file = fs.realpathSync.native(path.join(directory, 'SKILL.md'));+ const { data } = matter(fs.readFileSync(file, 'utf8'));+ skills.push({+ kind: 'agent-skill',+ name,+ description:+ description ??+ (typeof data.description === 'string' ? data.description.trim() : undefined),+ source: 'skill',+ scope: 'user',+ path: file,+ enabled: true,+ claudeCommandName: `${namespace}:${name}`,+ });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ };+ for (const skill of builtIns) addSkill(skill.absolutePath, skill.name, 'cindy');+ // Reuse receipt verification. Occupants preserved in the projection directory+ // (real directories, foreign links, stale slots) are not an approval catalog.+ const manager = getGhostManager();+ for (const ghost of listAvailableGhostsForAuthorization()) {+ if (+ !ghost.enabled ||+ !ghost.approvedSkillRoot ||+ !(await manager.verifyApprovedSkillSnapshot(ghost))+ )+ continue;+ for (const item of ghost.manifest.skill?.items ?? []) {+ addSkill(+ path.join(ghost.approvedSkillRoot, item.dir),+ item.name,+ `cindy-plugin-${ghost.manifest.id}`,+ item.description,+ );+ }+ }+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ throw new Error('Skill owner changed during discovery');+ return skills;+};diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 7fc1a21abd..0bfb36fdbb 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -1,3 +1,4 @@+import { listCindyManagedSkills } from './managed-skills.js';import { resolveCompanionRuntimeEnvironment } from '../bot-import/runtime.js';import { readCachedGenericOAuthAccessToken } from './generic-oauth.js';import { providerPresetModelRecord, providerModelAdapterId } from '@cindy/model-providers';@@ -1876,6 +1877,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {return new PiAgent({resolveSessionEnvironment: resolveCompanionRuntimeEnvironment,getDisabledSkillPaths: readDisabledSkillPaths,+ getManagedSkills: listCindyManagedSkills,resolveModelContextLimit: (providerId, modelId) => {const catalog = getActiveCatalog();const source = resolveModelContextProviderId(catalog, 'pi', providerId, modelId);diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.tsindex aca3058e65..796f8e4dbb 100644--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts@@ -144,7 +144,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [id: "skills",title: "Skills (reusable agent capabilities)",summary: "Create, search, browse, install, disable, uninstall, publish, and update agent Skills; Skills appear as \"/\" slash commands and are shared across Claude Code, Codex, and Pi.",- content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work across local agents:**\n\n- Skills are **engine-shared** — the same installed Skill is available to Claude Code, Codex, and Pi, so you install it once.\n\n**Where skills live on disk:**\n\n- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command. Pi package skills remain usable from `/`, but do not show this local detail shortcut; manage them through their package.\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Creating or learning a Skill from the composer:**\n\n- Cindy includes `/cindy-skill-creator`. Invoke it with a description of the Skill you want, such as `/cindy-skill-creator Create a Skill that checks release notes`. Invoking it without a description asks what you want to create.\n- The current Agent creates or updates the Skill directly with its normal file tools. It does not use the `/learn` staging flow.\n- Ask for a Skill in the composer, for example “Find a release-notes Skill” or `/cindy-skill-creator Search our organization's code-review Skills`. The Agent can search SkillHub's public marketplace or your organization's catalog. Without a specified scope, organization identities search both; personal identities search the public marketplace. Results identify their source, including when two Skills share a name. Search alone does not install anything.\n- You can also ask `/cindy-skill-creator` to upload your own Skill to SkillHub or publish a new version directly in the conversation. Give the local Skill folder (or the Skill just created) and, for a first upload, who should be able to access it. Ordinary local creation/editing does not automatically publish it.\n- Uploads use Cindy's signed-in account, which determines ownership; choosing sharing targets does not change that ownership. The Agent can list your published Skills, upload the folder, and check scan/review status. Upload success does not mean public approval. Updating requires confirmed original authorship and management access, and preserves visibility and ownership; a missing authorship flag is not treated as permission. This works in a local desktop task, including when controlled from a phone; SSH files must first be made available on the Cindy host.\n- Each Agent upload or version update follows the task's permission mode: Ask requests approval for that publication, Auto reviews it against your request, and Full Access bypasses operation approval. A previous helper-tool approval does not authorize later publications. Search, listing, and status queries remain automatic.\n- Unless you request another location, new Skills go to `~/.agents/skills/<name>/`. Ask for a project-specific Skill to create it under `<working-dir>/.agents/skills/<name>/`.\n- Cindy also includes `/learn`. Bare `/learn` distills the current task; `/learn <description>` learns from a described workflow; `/learn hub:<scope>:<slug> [instructions]` learns from a SkillHub Skill. Cindy gathers evidence, runs the distillation in a separate task, and shows a diff for review before saving the proposed Skill.\n- The built-in `cindy-skill-creator` and `learn` entries appear in the local Skill list with an Official badge. You can disable or enable either entry there; because they ship with Cindy, they cannot be uninstalled. The setting applies to new or restarted Agent sessions. Disabling `learn` also disables the **Learn this skill** action in SkillHub after the local Skill list has refreshed.\n\n**Disabling or uninstalling a local skill (Desktop):**\n\n- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from new-task command previews. Active tasks retain the skill preference snapshot applied when their Agent started, including their command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.\n- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.\n- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.\n- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.\n- External source imports remove only their discovery links and keep the external source files. Package-owned Skills must be removed through their owning package. Cindy's built-in Skills cannot be uninstalled, but they can be disabled. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared Skill links.\n- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.\n- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If cleanup is interrupted, the notice offers **Retry cleanup**. The unfinished operation survives closing, reloading, and restarting Cindy; reopen Skills in the same Cindy profile and account to continue. Cindy pauses conflicting installations until cleanup completes. Retrying never moves files to the trash a second time and preserves externally restored or replaced content.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, choose visibility: personal identities support public or private; organization identities support public or organization sharing. Public publication is subject to review.\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.\n\nIn a new-task draft, the slash hover panel offers detail links for global skills. Project skill detail links are available after creating a task, when SkillHub can include that project in its scan.",+ content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work across local agents:**\n\n- Skills are **engine-shared** — the same installed Skill is available to Claude Code, Codex, and Pi, so you install it once.\n\n**Where skills live on disk:**\n\n- User-created or imported global skills (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Cindy’s preinstalled skills and plugin-provided skills are kept in Cindy-managed directories and loaded into local Claude Code, Codex, and Pi tasks. Cindy does not add them to the user’s shared skill directories, so external CLIs do not discover them automatically. User-created and imported skills keep the locations above.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command. Pi package skills remain usable from `/`, but do not show this local detail shortcut; manage them through their package.\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Creating or learning a Skill from the composer:**\n\n- Cindy includes `/cindy-skill-creator`. Invoke it with a description of the Skill you want, such as `/cindy-skill-creator Create a Skill that checks release notes`. Invoking it without a description asks what you want to create.\n- The current Agent creates or updates the Skill directly with its normal file tools. It does not use the `/learn` staging flow.\n- Ask for a Skill in the composer, for example “Find a release-notes Skill” or `/cindy-skill-creator Search our organization's code-review Skills`. The Agent can search SkillHub's public marketplace or your organization's catalog. Without a specified scope, organization identities search both; personal identities search the public marketplace. Results identify their source, including when two Skills share a name. Search alone does not install anything.\n- You can also ask `/cindy-skill-creator` to upload your own Skill to SkillHub or publish a new version directly in the conversation. Give the local Skill folder (or the Skill just created) and, for a first upload, who should be able to access it. Ordinary local creation/editing does not automatically publish it.\n- Uploads use Cindy's signed-in account, which determines ownership; choosing sharing targets does not change that ownership. The Agent can list your published Skills, upload the folder, and check scan/review status. Upload success does not mean public approval. Updating requires confirmed original authorship and management access, and preserves visibility and ownership; a missing authorship flag is not treated as permission. This works in a local desktop task, including when controlled from a phone; SSH files must first be made available on the Cindy host.\n- Each Agent upload or version update follows the task's permission mode: Ask requests approval for that publication, Auto reviews it against your request, and Full Access bypasses operation approval. A previous helper-tool approval does not authorize later publications. Search, listing, and status queries remain automatic.\n- Unless you request another location, new Skills go to `~/.agents/skills/<name>/`. Ask for a project-specific Skill to create it under `<working-dir>/.agents/skills/<name>/`.\n- Cindy also includes `/learn`. Bare `/learn` distills the current task; `/learn <description>` learns from a described workflow; `/learn hub:<scope>:<slug> [instructions]` learns from a SkillHub Skill. Cindy gathers evidence, runs the distillation in a separate task, and shows a diff for review before saving the proposed Skill.\n- The built-in `cindy-skill-creator` and `learn` entries appear in the local Skill list with an Official badge. You can disable or enable either entry there; because they ship with Cindy, they cannot be uninstalled. The setting applies to new or restarted Agent sessions. Disabling `learn` also disables the **Learn this skill** action in SkillHub after the local Skill list has refreshed.\n\n**Disabling or uninstalling a local skill (Desktop):**\n\n- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from new-task command previews. Active tasks retain the skill preference snapshot applied when their Agent started, including their command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.\n- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.\n- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.\n- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.\n- External source imports remove only their discovery links and keep the external source files. Package-owned Skills must be removed through their owning package. Cindy's built-in Skills cannot be uninstalled, but they can be disabled. Skills provided by Cindy plugins are managed on the owning plugin's page and loaded through Cindy's private skill entries.\n- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.\n- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If cleanup is interrupted, the notice offers **Retry cleanup**. The unfinished operation survives closing, reloading, and restarting Cindy; reopen Skills in the same Cindy profile and account to continue. Cindy pauses conflicting installations until cleanup completes. Retrying never moves files to the trash a second time and preserves externally restored or replaced content.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, choose visibility: personal identities support public or private; organization identities support public or organization sharing. Public publication is subject to review.\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.\n\nIn a new-task draft, the slash hover panel offers detail links for global skills. Project skill detail links are available after creating a task, when SkillHub can include that project in its scan.",},{id: "updates-and-about",@@ -158,7 +158,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [title: "Using voice input (dictation)",summary: "Push-to-talk dictation that inserts ASR text into the focused composer; configure shortcut, mic, language, refinement, and dictionary in Settings > Voice Input.",tab: "voice-input",- content: "Voice input lets you dictate instead of typing. Hold a shortcut, talk, release — the recognized text is inserted into whichever composer has focus.\n\n**Activation:**\n\n- Default shortcut: **Alt+Space** on macOS, **Ctrl+Shift+Space** on Windows. The shortcut is customizable on macOS and Windows. On Linux, global voice shortcuts are not supported yet (the setting is hidden).\n- The shortcut is **global** — it works even when Cindy isn't the focused app, so you can dictate into the composer from anywhere.\n- It's **push-and-hold**: press to start listening, release to stop and submit.\n\n**Settings:**\n\n- **Microphone** — pick a specific device or leave on \"auto\" (system default).\n- **Language** — auto / 中文 (zh-CN) / 繁體中文 (zh-TW) / English / 日本語 / 한국어. Those are the supported recognition locales — there's no free-form locale field.\n- **Refinement** — optional LLM post-process that cleans up the raw ASR text (fixes punctuation, removes ums, joins fragments). You can write a custom refinement prompt to bias it toward your preferences.\n- **Mute system audio while recording** — toggle; reduces feedback / echo from your speakers picking up onto the mic. On by default.\n- **Fast activation** — toggle; keeps the mic warm so press-to-talk has lower latency at the cost of slightly more background mic usage. Off by default.\n- **Interaction sound** — a short sound cue when dictation starts / stops. On by default.\n\n**Dictionary (improves recognition of your terms):**\n\n- **Manual entries** — type terms you want recognized (people's names, product names, jargon).\n- **Learned entries** — when you edit the text shortly after dictation lands in the composer, the external-edit inspector picks up your corrections and feeds them back as automatic dictionary entries. Both manual and learned entries feed the refinement pass.\n\n**Permissions (macOS):**\n\n- **Microphone** — required; the page prompts the OS dialog if you haven't granted it.\n- **Input Monitoring** and **Accessibility** — may be required depending on how the global shortcut is captured. The page shows each permission's status (granted / denied / unknown) so you know what to grant in System Settings.\n\n**Notes:**\n\n- Push-and-hold is the primary activation mode; **Fast activation** changes the warm-up behavior, not the trigger itself.\n- If the global shortcut fails to register (e.g. it's already taken by another app like an IME), you'll see a warning in the page; pick a different shortcut.\n- If the connection drops mid-dictation, the text recognized up to that point is kept — it lands in the composer (or stays in the overlay with a copy button) alongside the error, instead of being discarded. That salvaged text is raw ASR output: refinement needs the connection that just failed, so it is skipped.",+ content: "Voice input lets you dictate instead of typing. Hold a shortcut, talk, release — the recognized text is inserted into whichever composer has focus.\n\n**Activation:**\n\n- Default shortcut: **Alt+Space** on macOS, **Ctrl+Shift+Space** on Windows. The shortcut is customizable on macOS and Windows. On Linux, global voice shortcuts are not supported yet (the setting is hidden).\n- The shortcut is **global** — it works even when Cindy isn't the focused app, so you can dictate into the composer from anywhere.\n- It's **push-and-hold**: press to start listening, release to stop and submit.\n- Pressing the microphone immediately shows the recording controls and starts the timer. The start cue acknowledges the action and plays independently while capture starts in the background. Once audio becomes available, it is retained even while the recognition service is connecting; up to about 60 seconds is buffered locally and sent in order when it connects. You can stop before connection completes without discarding that buffered audio.\n\n**Settings:**\n\n- **Microphone** — pick a specific device or leave on \"auto\" (system default).\n- **Language** — auto / 中文 (zh-CN) / 繁體中文 (zh-TW) / English / 日本語 / 한국어. Those are the supported recognition locales — there's no free-form locale field.\n- **Refinement** — optional LLM post-process that cleans up the raw ASR text (fixes punctuation, removes ums, joins fragments). You can write a custom refinement prompt to bias it toward your preferences.\n- **Mute system audio while recording** — toggle; reduces feedback / echo from your speakers picking up onto the mic. On by default.\n- When enabled, the start cue finishes before system audio is muted. Capture continues throughout. Audio captured before the mute finishes is retained too, so the beginning of your speech is not cut off; a brief amount of sound already playing through the speakers may also be captured.\n- **Fast activation** — toggle; keeps the mic warm so press-to-talk has lower latency at the cost of slightly more background mic usage. Off by default.\n- **Interaction sound** — a short sound cue when dictation starts / stops. On by default.\n\n**Dictionary (improves recognition of your terms):**\n\n- **Manual entries** — type terms you want recognized (people's names, product names, jargon).\n- **Learned entries** — when you edit the text shortly after dictation lands in the composer, the external-edit inspector picks up your corrections and feeds them back as automatic dictionary entries. Both manual and learned entries feed the refinement pass.\n\n**Permissions (macOS):**\n\n- **Microphone** — required; the page prompts the OS dialog if you haven't granted it.\n- **Input Monitoring** and **Accessibility** — may be required depending on how the global shortcut is captured. The page shows each permission's status (granted / denied / unknown) so you know what to grant in System Settings.\n\n**Notes:**\n\n- If Cindy reports \"Too many voice requests\", wait a moment before starting another recording. Cindy voice providers share this account limit, so automatic provider switching stops for that attempt. The limit does not mark the providers as faulty or impose a provider cooldown.\n- Push-and-hold is the primary activation mode; **Fast activation** changes the warm-up behavior, not the trigger itself.\n- If the global shortcut fails to register (e.g. it's already taken by another app like an IME), you'll see a warning in the page; pick a different shortcut.\n- If the connection drops mid-dictation, the text recognized up to that point is kept — it lands in the composer (or stays in the overlay with a copy button) alongside the error, instead of being discarded. That salvaged text is raw ASR output: refinement needs the connection that just failed, so it is skipped.",},{id: "worktrees",diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 0356fe8450..bb168a52da 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -441,6 +441,7 @@ import {import { isCindySkillEnabled } from '../skillhub/activationPreferences.js';import {parseDirectLearnInvocation,+ canGrantUnqualifiedClaudeLearnInvocation,type CindyLearnInvocationGrant,} from '../learn-host/invocationGrant.js';import { ensurePiManagerInstalled } from '../maker-host/pi-manager-client.js';@@ -13768,6 +13769,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)|| (session.getStatus && session.getStatus() !== 'active')) return null;+ if (session.agentKind === 'claude-code'+ && !/^\/cindy:learn(?:\s|$)/i.test(dispatchedText.trim())+ && !await canGrantUnqualifiedClaudeLearnInvocation(session.id)) return null;+const descriptors = builtInSkillDescriptors(app.getPath('userData'),app.getPath('appData'),@@ -13790,7 +13795,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)result.skills,descriptors,isCindySkillEnabled,- ).filter((skill) => skill.name.toLowerCase() === 'learn');+ ).filter((skill) => (skill.name.toLowerCase() === 'learn' || skill.runtimeCommandName === 'cindy:learn')+ && (!/^\/cindy:learn(?:\s|$)/i.test(dispatchedText.trim())+ || (skill.builtIn === true && skill.runtimeCommandName === 'cindy:learn')));if (learnCandidates.length !== 1|| learnCandidates.some((skill) => skill.builtIn !== true || !skill.path)diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex ce77d84b91..607244f80f 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -3280,8 +3280,7 @@ export function CCAgentSessionView({return {handled: false,accepted: false,- message:- agentKind === 'pi' ? rewriteAgentSkillInvocationForDispatch(message, hit) : message,+ message: rewriteAgentSkillInvocationForDispatch(message, hit),};}// Desktop commands stay `^/` only. A whitespace-prefixed `/help` is not a dispatch.diff --git a/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts b/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.tsindex 9c164cacd6..70ee0e9cec 100644--- a/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts@@ -634,3 +634,11 @@ describe('Pi project skill availability', () => {expect(reloaded).toBe(false);});});+++describe('Claude managed skill dispatch', () => {+ it('rewrites the short Cindy command to its native plugin command, preserving arguments', () => {+ const command = skill({ name: 'learn', runtimeCommandName: 'cindy:learn', builtIn: true });+ expect(rewriteAgentSkillInvocationForDispatch('/learn keep this workflow', command)).toBe('/cindy:learn keep this workflow');+ });+});diff --git a/apps/desktop/src/renderer/lib/slashCommands.ts b/apps/desktop/src/renderer/lib/slashCommands.tsindex 01222510c8..cef71df9b9 100644--- a/apps/desktop/src/renderer/lib/slashCommands.ts+++ b/apps/desktop/src/renderer/lib/slashCommands.ts@@ -117,14 +117,15 @@ export async function rewritePiSkillMessageForSend(params: {workingDir?: string | null;sessionId?: string;}): Promise<string> {- if (params.agentKind !== 'pi') return params.message;+ if (params.agentKind !== 'pi' && params.agentKind !== 'claude-code') return params.message;const leading = leadingSlashInvocation(params.message);if (!leading) return params.message;const commands = await loadAllCommands(params.agentKind, params.workingDir, {...(params.sessionId ? { sessionId: params.sessionId } : {}),});const hit = commands.find((command) => command.name.toLowerCase() === leading.name.toLowerCase());- return rewritePiSkillAliasFromCommand(params.message, hit);+ return params.agentKind === 'pi' ? rewritePiSkillAliasFromCommand(params.message, hit)+ : rewriteAgentSkillInvocationForDispatch(params.message, hit);}/**diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 12cd899aec..2688b1c0a9 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -127,8 +127,8 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;* 一个网址标签页。网址范围装入时在 preview.hosts 白名单里定死(同 network* 域名白名单语法),运行期主机逐次校验,范围外一律拒——防钓鱼是结构性的。* 'skill' = 捆绑 Agent Skills(2026-07-25):插件随包携带 SKILL.md 技能目录,- * 装入且启用后由主机链接进共享技能根 ~/.agents/skills/<id>--<name>(win32 用- * junction),Claude Code 与 Codex 都能发现。信任面与其它槽完全不同量级:技能+ * 装入且启用后由主机投影到 Cindy 的账号隔离目录,通过各 Harness 的私有入口+ * 提供给 Claude Code、Codex、Pi,不写入用户共用技能目录。信任面与其它槽完全不同量级:技能* 指令由主 Agent 以**用户全部权限**执行、对所有项目与会话生效、不受插件沙箱* 约束,也不随"某工作目录停用本插件"而隐藏——仅全局停用/卸载才撤链。因此* manifest 全声明式(items 的 name/description 必须与 SKILL.md frontmatter 逐字@@ -1047,7 +1047,7 @@ export const GHOST_SKILL_NAME_MAX_CHARS = 64;/*** skill 槽:技能 name 形状——小写字母/数字,连字符仅作单段分隔(禁首尾与连续* 连字符)。比 learn-host 的 SKILL_NAME_RE 更严:意识 id 允许含 `--`- * (GHOST_ID_RE),共享技能根的链接名是 `<id>--<name>`,只有 name 侧禁 `--`,+ * (GHOST_ID_RE),插件私有技能根的链接名是 `<id>--<name>`,只有 name 侧禁 `--`,* 按"最后一个 `--`"拆分才唯一,不同插件才不可能撞出同一个链接名。*/export const GHOST_SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;@@ -1493,7 +1493,7 @@ export interface GhostManifest {preview?: GhostPreviewNeeds;/*** 随包捆绑的 Agent Skills 清单。- * 启用时主机链接进共享技能根,Claude Code 与 Codex 双端可见;字段不参与+ * 启用时由 Cindy 私有入口加载到本地 Claude Code、Codex 与 Pi,不写用户共享目录;字段不参与* 本地化(必须与 SKILL.md 逐字一致,见 GhostSkillItem)。*/skill?: GhostSkillNeeds;@@ -4638,7 +4638,7 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo// 技能是本能力的全部知情面)。name/description 与 SKILL.md 的逐字一致性在// 打包(packGhostDir)与装入(GhostManager.parse)两侧另行强制,这里只管// 声明本身的形状。name/dir 大小写折叠去重:win32 文件系统折叠大小写,- // 共享技能根的链接名不允许折叠后相撞。+ // 插件私有技能根的链接名不允许折叠后相撞。let skill: GhostSkillNeeds | undefined;if (raw.skill !== undefined) {if (!isPlainObject(raw.skill)) {diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 4a7dbe05a4..427700c16b 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -179,3 +179,35 @@ Claude.ai 登录,也不得收集、存储或中转订阅凭证。Cindy 因此[`desktop-development.md`](desktop-development.md) 或[`mobile-development.md`](mobile-development.md) 选择,并为路径回退、清理和秘密不外泄补定向测试。+++## Cindy 托管的预装技能++内置技能字节仍在 Cindy 的 `shared-system-skills` 中随应用版本管理,当前实例在+`<userData>/managed-agent-skills/cindy` 中建立私有入口。三套 Harness 分别通过本地+Claude plugin、Cindy 的 `CODEX_HOME/skills`、Pi 显式 `--skill` 加载;不再安装到+`~/.agents/skills` 或 `~/.claude/skills`。存量插件技能使用账号隔离的+`<ghost-install-state>/agent-skills`,继续只指向已批准快照。++运行期清单来自已验证的内置描述符与插件批准快照,不扫描私有投影目录中的占位内容。+三套 Harness 均加载核验后的物理来源;Codex 在默认及独立账号的 `CODEX_HOME` 中+逐个挂载这些技能,每次本地任务启动(包括复用 app-server)都刷新实际 home 的入口,+并通过原生 `skills/list forceReload` 清除旧发现缓存;刷新失败则不提交新线程。+投影函数统一要求每个托管来源为已建立或保持正确链接;缺失、冲突、扫描环及 I/O 错误+直接抛出,默认账号、独立账号和复用进程均不能把 warning 当作成功。用户技能兼容根+仍保留原有 warning 行为,用户实体目录及外来链接不被覆盖。+不将整个私有目录交给扫描器。Bot 的路径授权与+Claude/Pi 最终加载使用同一物理来源,目录别名重指不能替换已授权的技能。+Codex Bot 在刷新原生技能清单后,按启动时冻结的物理路径授权生成线程级开关;+刷新中新出现或未成功核验的技能默认禁用,无法定位路径的发现错误阻止线程启动。++Pi 将筛选后的物理来源链接到现有会话配置目录内,通过单个 `--skill` 目录参数交给+原生加载器;技能数量不会增加启动参数长度,`--no-skills` 的 Bot 白名单仍生效。+入口随会话配置目录一起回收;技能发现、路径解析和建链失败均走同一既有启动失败清理,撤销 MCP 会话路由与+权限临时文件,不新增全局目录或独立清理机制。++Claude 的插件技能不受 `skillOverrides` 控制,因此每个本地 Query 只将已启用且+符合 Bot 白名单的技能链接到临时插件入口;关闭 Query 时回收入口,源文件不变。++升级清理只删除可确认由 Cindy 创建的旧软链接,不删除目标内容、不覆盖用户同名+技能、不修改 Git ignore。旧版本 Cindy 实例仍可能重建旧链接,这是迁移的已知边界。diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 2488daa646..063262a761 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -218,6 +218,11 @@AI 审阅,Ask 弹确认卡,远程/缺会话/查询失败 fail closed),禁止在 Host 已放行后再因目录边界悄悄硬断。`ghost_forge_pack` 只负责校验与打包;只有用户明确要求后调用独立的 `ghost_forge_install` 才安装或更新,不因 scaffold/pack 成功而隐式安装。+- 存量插件技能投影在当前账号的 `<状态根>/agent-skills`,不写 `~/.agents/skills`+ 或 `~/.claude/skills`。Claude 使用每插件独立的本地 plugin(命令带命名空间),+ Codex 通过 Cindy 的 `CODEX_HOME/skills`,Pi 通过显式 `--skill` 加载;均保留技能+ 停用与 Bot 白名单。旧全局链接仅在能证明属于 Cindy 时迁移删除;用户文件与外来+ 链接保留。账号切换撤销私有投影与遗留全局投影。- `skill` 是唯一**越出沙箱**的能力:技能指令由主 Agent 以用户全部权限执行、全局生效、不随 workdir 级停用隐藏。其安全边界是**声明一致性**(manifest 里的name/description 必须与 SKILL.md frontmatter 逐字一致,`skillSlot.ts` 的@@ -229,7 +234,7 @@内存投影**(inspect 时已被 `packageSha256` 钉住的那份字节),不从已发布的可变安装目录首读:publish 与首次 hash 之间被换的字节应当在快照对账时被拒,而不是被首读钉成固化基线;安装事务校验的 SKILL.md 必须就是 Agent 之后- 读到的那份,所以共享技能根的链接指快照而不是可被改写的 `cindy-brain/<id>/<dir>`。+ 读到的那份,所以 Cindy 私有技能投影的链接指快照而不是可被改写的 `cindy-brain/<id>/<dir>`。快照缺失需要从安装目录重建时,**顺序本身就是安全性质**:先把字节复制进状态根的临时目录,再对**临时目录里那份即将成为快照的字节**做全部权威校验(尺寸上限 →指纹逐字节比对 → frontmatter 一致性),通过才 rename 就位。**不得改成"先校验安装@@ -240,7 +245,7 @@喂入、不整份读进内存(技能目录里除 SKILL.md 之外的文件没有尺寸上限,整份读会被一个塞进来的超大辅助文件撑爆)。只靠 `checkSkillMdConsistency` 拦不住"frontmatter 不动、改写正文或塞辅助文件",那会把一份未经合法安装/更新事务校验的指令在一次启用里固化成- 宿主快照并全局挂链。对不上一律 fail closed,要求重新安装合法包,不许就地自愈成新固化状态;+ 宿主快照并挂载到 Cindy 会话。对不上一律 fail closed,要求重新安装合法包,不许就地自愈成新固化状态;`skillContentSha256` 因此是**运行期判据**,与只作审计用的 `packageSha256` 不同,且必填——留"字段缺失就跳过校验"的可选口子等于给漂移开一条绕过路径)+ **链接对账**(`reconcileGhostSkillLinks` 只增删"目标落在@@ -578,8 +583,8 @@写批准事实时暴露:对不上就删掉重建,重建仍要过安装目录的字节校验,安装字节也漂移时一律拒绝并要求重新安装合法包。- **仍未关闭(消费侧瞬时窗口)**:启动/装卸/启停广播触发技能对账时,Host 会在建立- 或保留共享链接前重新核对整棵批准快照;但这次核对之后、主 Agent 顺着共享技能链接- 读取之前,快照仍可被同权限进程改写。Agent 的读取路径不在宿主控制内,宿主不做逐次+ 或保留私有投影前重新核对整棵批准快照,加载清单也核验批准来源;但核对之后、主 Agent+ 读取技能之前,快照仍可被同权限进程改写。Agent 的读取路径不在宿主控制内,宿主不做逐次校验。receipt 同理——它有严格结构与字段校验(改坏即判 `invalid`、fail closed),但没有签名或 MAC,能写状态根的进程可以伪造一份结构合法的批准。- 彻底关闭需要给状态根加签名/MAC 或 OS 级写保护,**尚未做**;改动批准链路时不得声称diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 829cb60f84..f3e9419d11 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -72,6 +72,7 @@ import type {ScanAtResourcesOptions,ScanAtResourcesResult,AgentBuiltinCommand,+ AgentSkillCommand,ListAgentSkillsOptions,ListAgentSkillsResult,ListRuntimeSkillsOptions,@@ -691,6 +692,12 @@ 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[];+ /** Host-owned local Skills, loaded without writing user/project discovery directories. */+ getManagedSkills?: () => Promise<Array<AgentSkillCommand & {+ claudeCommandName: string;+ }>>;+ /** Refresh host-owned Skill links in the actual local Codex home before each thread, including reused servers. */+ prepareCodexSkills?: (codexHome: string) => Promise<void>;/** Optional low-I/O, provider-neutral turn change recorder supplied by the host. */turnChangeCapture?: TurnChangeCaptureHooks;auth: AuthAdapter;diff --git a/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.tsindex 35791980e7..5b5f94f273 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts@@ -29,6 +29,7 @@ vi.mock('@anthropic-ai/claude-agent-sdk', () => ({import { ClaudeCodeAgent } from '../index.js';const tempDirs: string[] = [];+const liveHandles: Awaited<ReturnType<ClaudeCodeAgent['startSession']>>[] = [];const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;function createNoopLogger(): Logger {@@ -98,6 +99,10 @@ async function startBotSession(input: {reviewMode?: boolean;remote?: boolean;ordinary?: boolean;+ managed?: boolean;+ disabled?: boolean;+ allowManaged?: boolean;+ catalogState?: 'failed' | 'disabled' | 'missing' | 'user-collision';}) {const configDir = await makeTempDir();process.env.CLAUDE_CONFIG_DIR = configDir;@@ -105,6 +110,13 @@ async function startBotSession(input: {sdkMock.query.mockReturnValue(createFakeQuery());const deps = createDeps();+ if (input.managed) {+ await fs.mkdir(`${configDir}/managed/learn`, { recursive: true });+ await fs.writeFile(`${configDir}/managed/learn/SKILL.md`, '---\nname: learn\ndescription: Fixture\n---\nBody');+ deps.getManagedSkills = async () => [{kind: 'agent-skill', name: 'learn', path: `${configDir}/managed/learn/SKILL.md`,+ source: 'skill', enabled: true, claudeCommandName: 'cindy:learn'}];+ if (input.disabled) deps.getDisabledSkillPaths = () => [`${configDir}/managed/learn`];+ }let remoteOptions: unknown;if (input.remote) {deps.remoteCcQueryFactory = async ({ startParams, botSession }) => {@@ -114,7 +126,7 @@ async function startBotSession(input: {};}const agent = new ClaudeCodeAgent(deps);- await agent.startSession({+ const handle = await agent.startSession({sessionId: 'session-bot-skills',model: 'claude-opus-4-6',workingDir,@@ -128,9 +140,15 @@ async function startBotSession(input: {botId: 'bot-1',profileVersion: 1,skillPolicy: {- mode: 'inherit',- configured: [],- catalog: [],+ mode: input.allowManaged !== undefined ? 'allowlist' : 'inherit',+ configured: input.allowManaged ? [input.catalogState === 'user-collision' ? 'learn' : 'cindy:learn'] : [],+ catalog: !input.managed || input.catalogState === 'missing' ? [] : [+ { name: 'cindy:learn', runtimeCommandName: 'cindy:learn', path: `${configDir}/managed/learn`,+ enabled: input.catalogState !== 'disabled',+ runtimeStatus: input.catalogState === 'failed' ? 'failed' as const : 'loaded' as const },+ ...(input.catalogState === 'user-collision'+ ? [{ name: 'learn', path: `${configDir}/user/learn/SKILL.md`, enabled: true }] : []),+ ],...(input.ownSkillPluginRoots? {ownSkills: [{ name: 'weekly-report', path: `${OWN_SKILL_ROOT}/skills/weekly-report` }],@@ -143,13 +161,14 @@ async function startBotSession(input: {},});+ liveHandles.push(handle);const options = (input.remote ? remoteOptions : sdkMock.query.mock.calls.at(-1)?.[0]?.options) as| {plugins?: Array<{ type: string; path: string }>;settingSources?: string[];disallowedTools?: string[];strictMcpConfig?: boolean;- settings?: { autoMemoryEnabled?: boolean; autoDreamEnabled?: boolean };+ settings?: { autoMemoryEnabled?: boolean; autoDreamEnabled?: boolean; skillOverrides?: Record<string, string> };systemPrompt?: { append?: string };}| undefined;@@ -158,6 +177,17 @@ async function startBotSession(input: {}afterEach(async () => {+ await Promise.all(liveHandles.splice(0).map((handle) => handle.close()));+ // The session owns its plugin staging directories. Wait for asynchronous+ // disposal instead of racing a second rm against it (EPERM on Windows).+ for (const [call] of sdkMock.query.mock.calls) {+ for (const plugin of call.options.plugins ?? []) {+ if (plugin.path === OWN_SKILL_ROOT) continue;+ await vi.waitFor(async () => {+ await expect(fs.stat(path.dirname(plugin.path))).rejects.toMatchObject({ code: 'ENOENT' });+ });+ }+ }sdkMock.forkSession.mockReset();sdkMock.query.mockReset();if (originalClaudeConfigDir === undefined) {@@ -223,3 +253,83 @@ describe('Claude Code mounts the Bot\'s own learned Skills', () => {expect(prompt).not.toContain('Smart Contacts');});});+++describe('Cindy managed skills use Claude session plugins', () => {+ it('mounts managed skills for ordinary sessions without setting a global config directory', async () => {+ const options = await startBotSession({ ordinary: true, managed: true });+ expect(options.plugins).toHaveLength(1);+ expect(await fs.readdir(path.join(options.plugins![0]!.path, 'skills'))).toEqual(['learn']);+ expect(options.settingSources).toEqual(['user', 'project', 'local']);+ });+ it('reclaims the session plugin when the handle closes, preserving its source skill', async () => {+ const options = await startBotSession({ ordinary: true, managed: true });+ const root = options.plugins![0]!.path;+ const source = await fs.realpath(path.join(root, 'skills', 'learn'));+ await liveHandles.at(-1)!.close();+ await vi.waitFor(async () => { await expect(fs.stat(path.dirname(root))).rejects.toMatchObject({ code: 'ENOENT' }); });+ expect(await fs.readFile(path.join(source, 'SKILL.md'), 'utf8')).toContain('Fixture');+ });++ it('disables only the namespaced command, preserving a user learn skill', async () => {+ const options = await startBotSession({ ordinary: true, managed: true, disabled: true });+ expect(options.plugins).toBeUndefined();+ expect(options.settings?.skillOverrides?.learn).toBeUndefined();+ });+ it.each([false, true])('respects the Bot managed skill allowlist: %s', async (allowManaged) => {+ const options = await startBotSession({ managed: true, allowManaged });+ if (allowManaged) {+ expect(options.plugins).toHaveLength(1);+ expect(await fs.readdir(path.join(options.plugins![0]!.path, 'skills'))).toEqual(['learn']);+ } else expect(options.plugins).toBeUndefined();+ });+ it.each(['failed', 'disabled', 'missing', 'user-collision'] as const)('does not mount an unproven managed Bot skill: %s', async (catalogState) => {+ const options = await startBotSession({ managed: true, allowManaged: true, catalogState });+ expect(options.plugins).toBeUndefined();+ });+ it('keeps managed commands ahead of Bot plugin aliases', async () => {+ const options = await startBotSession({ managed: true, allowManaged: true, ownSkillPluginRoots: [OWN_SKILL_ROOT] });+ expect(options.plugins).toHaveLength(2);+ expect(await fs.readdir(path.join(options.plugins![0]!.path, 'skills'))).toEqual(['learn']);+ expect(options.plugins![1]!.path).toBe(OWN_SKILL_ROOT);+ });+ it('does not grant ambient managed skills to a Bot with a legacy inherit policy', async () => {+ const options = await startBotSession({ managed: true });+ expect(options.plugins).toBeUndefined();+ });+ it.each([{reviewMode: true}, {remote: true}])('does not send local managed plugins to restricted runtimes %o', async (flags) => {+ const options = await startBotSession({ ...flags, managed: true });+ expect(options.plugins).toBeUndefined();+ });+});+++describe('managed skill command collisions', () => {+ it('keeps user /learn and exposes Cindy under its full native name', async () => {+ const configDir = await makeTempDir();+ process.env.CLAUDE_CONFIG_DIR = configDir;+ const userSkill = path.join(configDir, 'skills', 'learn');+ await fs.mkdir(userSkill, { recursive: true });+ await fs.writeFile(path.join(userSkill, 'SKILL.md'), '---\nname: learn\ndescription: User Learn\n---\nUser body');+ const deps = createDeps();+ deps.getManagedSkills = async () => [{ kind: 'agent-skill', name: 'learn', source: 'skill',+ path: '/cindy/learn/SKILL.md', enabled: true, claudeCommandName: 'cindy:learn' }];+ const agent = new ClaudeCodeAgent(deps);+ const result = await agent.listRuntimeSkills({ workingDir: await makeTempDir(), runtimeConfigDir: configDir });+ expect(result.skills.map((skill) => skill.name)).toEqual(['cindy:learn', 'learn']);+ expect(result.skills[0]?.runtimeCommandName).toBe('cindy:learn');+ expect(result.skills[1]?.path).toBe(path.join(userSkill, 'SKILL.md'));+ });++ it('keeps the short display name when unambiguous and namespaces collisions between plugins', async () => {+ const configDir = await makeTempDir();+ process.env.CLAUDE_CONFIG_DIR = configDir;+ const deps = createDeps();+ deps.getManagedSkills = async () => ['cindy', 'cindy-plugin-a', 'cindy-plugin-b'].map((plugin, index) => ({+ kind: 'agent-skill', name: index ? 'demo' : 'learn', source: 'skill', enabled: true,+ path: `/${plugin}/SKILL.md`, claudeCommandName: `${plugin}:${index ? 'demo' : 'learn'}`,+ }));+ const result = await new ClaudeCodeAgent(deps).listRuntimeSkills({ workingDir: await makeTempDir(), runtimeConfigDir: configDir });+ expect(result.skills.map((skill) => skill.name)).toEqual(['learn', 'cindy-plugin-a:demo', 'cindy-plugin-b:demo']);+ });+});diff --git a/packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.tsindex b99da4ec07..ee91fd08a0 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.ts@@ -156,7 +156,7 @@ afterEach(async () => {});describe('Claude extraDirs mid-session rebuild', () => {- it('setExtraDirs 后下一次 send 走 resume+fork,不用 fresh:true', async () => {+ it.each(['none', 'remove', 'disable', 'enable'] as const)('setExtraDirs rebuild preserves conversation and launch skill preferences: %s', async (change) => {const configDir = await makeTempDir();const workingDir = await makeTempDir();process.env.CLAUDE_CONFIG_DIR = configDir;@@ -168,8 +168,21 @@ describe('Claude extraDirs mid-session rebuild', () => {await fs.writeFile(path.join(projectDir, `${sdkSessionId}.jsonl`), '{"type":"summary"}\n', 'utf8');const firstQuery = createFakeQuery();+ const closeFirstQuery = firstQuery.close;sdkMock.query.mockReturnValue(firstQuery);- const agent = new ClaudeCodeAgent(createDeps());+ const deps = createDeps();+ const managedDir = path.join(configDir, 'managed', 'example--demo');+ let disabledPaths = change === 'enable' ? [managedDir] : [];+ deps.getDisabledSkillPaths = () => disabledPaths;+ if (change !== 'none') {+ await fs.mkdir(managedDir, { recursive: true });+ await fs.writeFile(path.join(managedDir, 'SKILL.md'), '---\nname: demo\ndescription: Fixture\n---\nBody');+ deps.getManagedSkills = vi.fn(async () => await fs.stat(managedDir).then(() => [{+ kind: 'agent-skill' as const, name: 'demo', source: 'skill' as const,+ path: path.join(managedDir, 'SKILL.md'), claudeCommandName: 'cindy-plugin-example:demo',+ }]).catch(() => []));+ }+ const agent = new ClaudeCodeAgent(deps);const handle = await agent.startSession({sessionId: 'session-library-extradirs',model: 'claude-opus-4-6',@@ -177,6 +190,16 @@ describe('Claude extraDirs mid-session rebuild', () => {resumeSessionId: sdkSessionId,});+ if (change === 'remove' || change === 'disable') {+ expect(sdkMock.query.mock.calls[0]?.[0].options.plugins).toHaveLength(1);+ } else {+ expect(sdkMock.query.mock.calls[0]?.[0].options.plugins).toBeUndefined();+ }+ if (change === 'remove') {+ await fs.rm(managedDir, { recursive: true });+ }+ if (change === 'disable') disabledPaths = [managedDir];+ if (change === 'enable') disabledPaths = [];const libraryRoot = '/Users/example/libraries/xd-mivo';await handle.setExtraDirs?.([libraryRoot], libraryRoot);@@ -193,7 +216,15 @@ describe('Claude extraDirs mid-session rebuild', () => {expect(rebuildArgs.options.additionalDirectories).toEqual([libraryRoot]);expect(rebuildArgs.options.resumeSessionAt).toBeUndefined();expect(rebuildArgs.options).not.toHaveProperty('fresh');- expect(firstQuery.close).toHaveBeenCalled();+ expect(closeFirstQuery).toHaveBeenCalled();+ if (change !== 'none') {+ expect(deps.getManagedSkills).toHaveBeenCalledTimes(2);+ }+ if (change === 'disable') {+ expect(rebuildArgs.options.plugins).toHaveLength(1);+ } else {+ expect(rebuildArgs.options.plugins).toBeUndefined();+ }const wire = sdkMock.query.mock.calls[1][0].prompt as AsyncIterable<{ message: { content: unknown } }>;const next = await wire[Symbol.asyncIterator]().next();expect(JSON.stringify(next.value.message.content)).toContain('libraryRoot');diff --git a/packages/maker-core/src/agents/claude-code/__tests__/managed-skill-plugins.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/managed-skill-plugins.test.tsnew file mode 100644index 0000000000..89e7cc3ceb--- /dev/null+++ b/packages/maker-core/src/agents/claude-code/__tests__/managed-skill-plugins.test.ts@@ -0,0 +1,92 @@+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { prepareManagedSkillPlugins } from "../managed-skill-plugins.js";++const cleanup: Array<() => Promise<void>> = [];+afterEach(async () => {+ await Promise.all(cleanup.splice(0).map((remove) => remove()));+});++describe("private Claude skill projections", () => {+ it("mounts only selected skills, preserves plugin namespaces and removes only temporary links", async () => {+ const root = await fs.mkdtemp(+ path.join(os.tmpdir(), "cindy-managed-plugin-test-"),+ );+ cleanup.push(() => fs.rm(root, { recursive: true, force: true }));+ const source = path.join(root, "approved", "learn");+ await fs.mkdir(source, { recursive: true });+ await fs.writeFile(+ path.join(source, "SKILL.md"),+ "---\nname: learn\ndescription: Fixture\n---\nBody",+ );+ const projection = await prepareManagedSkillPlugins(+ ["cindy", "cindy-plugin-example"].map((plugin) => ({+ kind: "agent-skill",+ name: "learn",+ source: "skill",+ path: path.join(source, "SKILL.md"),+ claudeCommandName: `${plugin}:learn`,+ })),+ );+ cleanup.push(projection.dispose);+ expect(projection.roots).toHaveLength(2);+ for (const plugin of projection.roots) {+ expect(+ JSON.parse(+ await fs.readFile(+ path.join(plugin, ".claude-plugin", "plugin.json"),+ "utf8",+ ),+ ).name,+ ).toBe(path.basename(plugin));+ expect(await fs.readdir(path.join(plugin, "skills"))).toEqual(["learn"]);+ expect(await fs.realpath(path.join(plugin, "skills", "learn"))).toBe(+ await fs.realpath(source),+ );+ }+ await projection.dispose();+ await expect(fs.stat(projection.roots[0]!)).rejects.toMatchObject({+ code: "ENOENT",+ });+ expect(await fs.readFile(path.join(source, "SKILL.md"), "utf8")).toContain(+ "Body",+ );+ });++ it("skips a source removed after discovery while keeping other selected skills", async () => {+ const root = await fs.mkdtemp(+ path.join(os.tmpdir(), "cindy-managed-plugin-race-"),+ );+ cleanup.push(() => fs.rm(root, { recursive: true, force: true }));+ const kept = path.join(root, "kept");+ const removed = path.join(root, "removed");+ await fs.mkdir(kept);+ await fs.mkdir(removed);+ const discovered = [kept, removed].map((source) => ({+ kind: "agent-skill" as const,+ name: path.basename(source),+ source: "skill" as const,+ path: path.join(source, "SKILL.md"),+ claudeCommandName: `cindy:${path.basename(source)}`,+ }));+ await fs.rm(removed, { recursive: true });+ const warnings: string[] = [];+ const projection = await prepareManagedSkillPlugins(discovered, (name) =>+ warnings.push(name),+ );+ cleanup.push(projection.dispose);+ expect(warnings).toEqual(["cindy:removed"]);+ expect(projection.roots).toHaveLength(1);+ expect(await fs.readdir(path.join(projection.roots[0]!, "skills"))).toEqual(+ ["kept"],+ );+ });++ it("does not mount a plugin when no skills are enabled", async () => {+ const projection = await prepareManagedSkillPlugins([]);+ expect(projection.roots).toEqual([]);+ await projection.dispose();+ });+});diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 2e55fd043a..38b91e9033 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -193,6 +193,8 @@ import type {import type { McpProviderContext } from '../../interfaces/mcp-provider.js';import { claudeDisabledSkillOverrides, snapshotDisabledSkillLaunch, currentDisabledSkillLaunchPaths } from '../shared/skill-activation.js';import { scanClaudeCustomizations, scanClaudeRuntimeSkills } from './customization-scanner.js';+import { prepareManagedSkillPlugins } from './managed-skill-plugins.js';+import { resolveAllowedManagedSkills, snapshotManagedSkillGrants } from '../shared/managed-skill-policy.js';import {REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS,isReviewSensitiveCredentialSelector,@@ -1084,6 +1086,20 @@ export class ClaudeCodeAgent extends BaseAgent {* Skill 扫描 —— 走 scanClaudeSlashCommands (扫 ~/.claude/{commands,skills}),* 包装成新的 AgentSkillCommand 形状(kind='agent-skill')。*/+ private async managedSkillCommands(nativeNames: readonly string[] = []) {+ const managed = await this.deps.getManagedSkills?.() ?? [];+ const counts = new Map<string, number>();+ for (const name of [...nativeNames, ...managed.map((skill) => skill.name)]) {+ counts.set(name, (counts.get(name) ?? 0) + 1);+ }+ return managed.map(({ claudeCommandName, ...skill }) => ({+ ...skill,+ // Preserve user commands and distinguish plugins with the same skill name.+ name: (counts.get(skill.name) ?? 0) > 1 ? claudeCommandName : skill.name,+ runtimeCommandName: claudeCommandName,+ }));+ }+override async listAgentSkills(opts: ListAgentSkillsOptions): Promise<ListAgentSkillsResult> {if (opts.remoteHostId) {const fileOps = this.deps.getRemoteAgentFileOps?.(opts.remoteHostId);@@ -1092,7 +1108,7 @@ export class ClaudeCodeAgent extends BaseAgent {}const raw = await scanClaudeSlashCommands(opts.workingDir);return {- skills: raw.map((c) => ({+ skills: [...await this.managedSkillCommands(raw.map((item) => item.name)), ...raw.map((c) => ({kind: 'agent-skill' as const,name: c.name,description: c.description,@@ -1100,7 +1116,7 @@ export class ClaudeCodeAgent extends BaseAgent {path: c.path,scope: c.scope,enabled: c.enabled,- })),+ }))],};}@@ -1120,7 +1136,7 @@ export class ClaudeCodeAgent extends BaseAgent {};}return {- skills: result.items.map((item) => ({+ skills: [...await this.managedSkillCommands(result.items.map((item) => item.name)), ...result.items.map((item) => ({kind: 'agent-skill' as const,name: item.name,description: item.description,@@ -1128,7 +1144,7 @@ export class ClaudeCodeAgent extends BaseAgent {path: item.mdPath,scope: item.scope === 'project' ? 'project' as const : 'global' as const,enabled: true,- })),+ }))],...(result.errors.length > 0 ? { errors: result.errors } : {}),};}@@ -1143,7 +1159,15 @@ export class ClaudeCodeAgent extends BaseAgent {* 按 name 去重), 二者共享 ~/.claude/{...} 扫盘事实, 但消费者不同。*/async listCustomizations(opts: ListCustomizationsOptions): Promise<ListCustomizationsResult> {- return scanClaudeCustomizations(opts);+ const result = await 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,+ description: skill.description, absolutePath: path.dirname(skill.path!), mdPath: skill.path,+ enabled: skill.enabled,+ })));+ }+ return result;}/**@@ -2583,8 +2607,11 @@ export class ClaudeCodeAgent extends BaseAgent {// (eg. summarized reasoning UI 本地有 remote 没)。getter 让 memOverride /// mutableFastMode 读最新值 (setMemory / setFastMode 运行时改) 而不是 buildQuery// 时快照。装配逻辑(含 apiKeyHelper 恒置空的鉴权防线)在 flag-settings.ts。- const disabledSkillPaths = opts.remoteHostId || opts.botRuntimeProfile || reviewMode+ const managedSkillGrants = snapshotManagedSkillGrants(opts.botRuntimeProfile?.skillPolicy);+ const launchDisabledSkillPaths = opts.remoteHostId || reviewMode? [] : [...(this.deps.getDisabledSkillPaths?.() ?? [])];+ const managedDisabledSkillLaunch = snapshotDisabledSkillLaunch(launchDisabledSkillPaths);+ const disabledSkillPaths = opts.botRuntimeProfile ? [] : launchDisabledSkillPaths;const disabledSkillLaunch = snapshotDisabledSkillLaunch(disabledSkillPaths);const disabledSkillSnapshot = disabledSkillLaunch.identities;const disabledSkillOverrides = disabledSkillPaths.length > 0@@ -3962,11 +3989,26 @@ export class ClaudeCodeAgent extends BaseAgent {const sdkStartPermissionMode = extra?.permissionMode ?? effectiveSdkPermissionMode();sdkInPlanMode = sdkStartPermissionMode === 'plan';// Review 会话不带任何 Bot 身份/能力(与 botSkillPolicy 同口径)。+ companionEnvironment?.assertCurrent?.();+ // Re-read at each Query boundary: plugin uninstall/disable may remove the+ // previous projection while the conversation itself remains open.+ const managedSkills = !reviewMode && this.deps.getManagedSkills+ ? await this.deps.getManagedSkills() : [];+ const managedDisabledPaths = currentDisabledSkillLaunchPaths(managedDisabledSkillLaunch);+ const allowedManagedSkills = resolveAllowedManagedSkills(managedSkills, managedSkillGrants, managedDisabledPaths);+ const managedPlugins = allowedManagedSkills.length+ ? await prepareManagedSkillPlugins(allowedManagedSkills, (name) => {+ log.warn('managed skill disappeared before Query startup; skipping', { skill: name });+ }) : undefined;+ const releaseManagedPlugins = () => {+ void managedPlugins?.dispose().catch((error) => log.warn('managed skill plugin cleanup failed', { error: String(error) }));+ };+ const querySignal = abortController.signal;+ if (managedPlugins) querySignal.addEventListener('abort', releaseManagedPlugins, { once: true });const botOwnSkillPluginRoots = reviewMode? []- : [...new Set(opts.botRuntimeProfile?.skillPolicy.ownSkillPluginRoots ?? [])];- companionEnvironment?.assertCurrent?.();- const query = sdkQuery({+ : [...new Set([...(managedPlugins?.roots ?? []), ...(opts.botRuntimeProfile?.skillPolicy.ownSkillPluginRoots ?? [])])];+ const createLocalQuery = () => sdkQuery({prompt: inputQueue as unknown as Parameters<typeof sdkQuery>[0]['prompt'],options: {abortController,@@ -3974,10 +4016,8 @@ export class ClaudeCodeAgent extends BaseAgent {// 附加目录在 Query 创建时冻结;运行时 setter 立即收紧 Cindy 审核,后续 Query// 重建再取最新 closure。空数组省略字段,让 SDK 走默认。...(additionalDirectories.length > 0 ? { additionalDirectories } : {}),- // Bot 自己沉淀的技能。cc 的 skillOverrides 只能开关它**自己发现到的**- // Skill(~/.claude/skills 与项目 .claude/skills),而这些技能躺在 Cindy- // 自有的 per-bot 目录里 —— 唯一不污染那两个共享目录(会串到别的伙伴和- // 普通任务)的挂载方式就是把 per-bot 根当本地 plugin 挂进来。+ // Bot 自有技能和已按启用状态/白名单过滤的 Cindy 托管技能,+ // 只通过本次 Query 的本地插件加载,不写用户共用技能目录。// 与 additionalDirectories 同理:路径是本机的,远端 cc-mgr 分支不透传。...(botOwnSkillPluginRoots.length > 0? { plugins: botOwnSkillPluginRoots.map((root) => ({ type: 'local' as const, path: root })) }@@ -4103,6 +4143,26 @@ export class ClaudeCodeAgent extends BaseAgent {: {}),},});+ let query: Query;+ try {+ companionEnvironment?.assertCurrent?.();+ if (managedPlugins && querySignal.aborted) throw new Error('Claude session closed before skill plugins were loaded');+ query = createLocalQuery();+ } catch (error) {+ querySignal.removeEventListener('abort', releaseManagedPlugins);+ if (managedPlugins) await managedPlugins.dispose();+ throw error;+ }+ if (managedPlugins) {+ const closeQuery = query.close.bind(query);+ query.close = () => {+ try { return closeQuery(); }+ finally {+ querySignal.removeEventListener('abort', releaseManagedPlugins);+ releaseManagedPlugins();+ }+ };+ }if (sdkStartPermissionMode === 'auto') nativeAutoQueries.add(query);if (modelUsageCumulativeStartsAtZero) modelUsageStartsAtZeroQueries.add(query);if (nativeCliAuth && typeof query.applyFlagSettings === 'function') {diff --git a/packages/maker-core/src/agents/claude-code/managed-skill-plugins.ts b/packages/maker-core/src/agents/claude-code/managed-skill-plugins.tsnew file mode 100644index 0000000000..4ea92c2429--- /dev/null+++ b/packages/maker-core/src/agents/claude-code/managed-skill-plugins.ts@@ -0,0 +1,73 @@+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { AgentDeps } from "../base-agent.js";++type ManagedSkills = Awaited<+ ReturnType<NonNullable<AgentDeps["getManagedSkills"]>>+>;++/** Claude ignores skillOverrides for plugins. Mount only this session's allowed skills. */+export async function prepareManagedSkillPlugins(+ skills: ManagedSkills,+ onUnavailable?: (name: string) => void,+): Promise<{+ roots: string[];+ dispose: () => Promise<void>;+}> {+ if (!skills.length) return { roots: [], dispose: async () => {} };+ const staging = await fs.mkdtemp(+ path.join(os.tmpdir(), "cindy-claude-skills-"),+ );+ const dispose = () => fs.rm(staging, { recursive: true, force: true });+ const roots = new Map<string, string>();+ try {+ for (const skill of skills) {+ if (!skill.path)+ throw new Error(`Managed skill has no path: ${skill.name}`);+ const [pluginName, skillName, extra] = skill.claudeCommandName.split(":");+ if (+ extra !== undefined ||+ !pluginName ||+ !skillName ||+ !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(pluginName) ||+ !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(skillName)+ ) {+ throw new Error(+ `Invalid managed Claude command: ${skill.claudeCommandName}`,+ );+ }+ // An uninstall can finish after discovery but before projection. Only a+ // missing source is skippable; other I/O failures still fail closed.+ let source: string;+ try {+ source = await fs.realpath(path.dirname(skill.path));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ onUnavailable?.(skill.claudeCommandName);+ continue;+ }+ let root = roots.get(pluginName);+ if (!root) {+ root = path.join(staging, pluginName);+ await fs.mkdir(path.join(root, ".claude-plugin"), { recursive: true });+ await fs.mkdir(path.join(root, "skills"));+ await fs.writeFile(+ path.join(root, ".claude-plugin", "plugin.json"),+ JSON.stringify({ name: pluginName, version: "1.0.0" }),+ );+ roots.set(pluginName, root);+ }+ // Freeze the approved source rather than following a mutable discovery link.+ await fs.symlink(+ source,+ path.join(root, "skills", skillName),+ process.platform === "win32" ? "junction" : "dir",+ );+ }+ return { roots: [...roots.values()], dispose };+ } catch (error) {+ await dispose();+ throw error;+ }+}diff --git a/packages/maker-core/src/agents/codex/capability-routing.test.ts b/packages/maker-core/src/agents/codex/capability-routing.test.tsindex 6259e9e256..b3c1bf299d 100644--- a/packages/maker-core/src/agents/codex/capability-routing.test.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.test.ts@@ -1,3 +1,7 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { snapshotManagedSkillGrants } from '../shared/managed-skill-policy.js';import { describe, expect, it } from 'vitest';import type { CapabilityRoutingPolicy } from '../../types/capability-routing.js';@@ -12,6 +16,36 @@ import {} from './capability-routing.js';describe('Bot Skill config', () => {+ it('keeps physical grants frozen when a catalog alias is repointed before reload', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-bot-skill-grants-'));+ try {+ const old = path.join(root, 'approved');+ const replacement = path.join(root, 'replacement');+ const alias = path.join(root, 'discovery');+ for (const dir of [old, replacement]) {+ fs.mkdirSync(dir);+ fs.writeFileSync(path.join(dir, 'SKILL.md'), '# fixture');+ }+ fs.symlinkSync(old, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const policy = { mode: 'allowlist' as const, configured: ['learn'],+ catalog: [{ name: 'learn', path: path.join(alias, 'SKILL.md') }] };+ const grants = snapshotManagedSkillGrants(policy)!;+ fs.unlinkSync(alias);+ fs.symlinkSync(replacement, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const paths = [old, replacement].map(dir => path.join(dir, 'SKILL.md'));+ expect(buildCodexBotSkillConfigOverrides(policy, { grants,+ skills: paths.map(source => ({ path: source, enabled: true })),+ })['skills.config']).toEqual(expect.arrayContaining([+ { path: paths[0], enabled: true }, { path: paths[1], enabled: false },+ { path: policy.catalog[0]!.path, enabled: false },+ ]));+ // A scoped native discovery error wins over a previously granted path.+ expect(buildCodexBotSkillConfigOverrides(policy, { grants,+ skills: [{ path: paths[0]!, enabled: false }],+ })['skills.config']).toEqual(expect.arrayContaining([{ path: paths[0], enabled: false }]));+ } finally { fs.rmSync(root, { recursive: true, force: true }); }+ });+it('maps a Bot allowlist to native per-thread Codex Skill state', () => {expect(buildCodexBotSkillConfigOverrides({mode: 'allowlist',diff --git a/packages/maker-core/src/agents/codex/capability-routing.ts b/packages/maker-core/src/agents/codex/capability-routing.tsindex a3411a4ab9..9adf0b4918 100644--- a/packages/maker-core/src/agents/codex/capability-routing.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.ts@@ -3,6 +3,7 @@ import type {CapabilityRoutingPolicy,} from '../../types/capability-routing.js';import type { BotRuntimeMcpPolicy, BotRuntimeSkillPolicy } from '../base-agent.js';+import { canonicalSkillPath } from '../shared/skill-activation.js';import { isBotMcpServerAllowed } from '../shared/bot-runtime-policy.js';const CODEX_HARNESS_ID = 'codex';@@ -15,6 +16,7 @@ interface CodexSkillState {/** Build Codex's native per-thread Skill config for a Bot allowlist. */export function buildCodexBotSkillConfigOverrides(policy: BotRuntimeSkillPolicy | undefined,+ refreshed?: { skills: readonly { path: string; enabled?: boolean }[]; grants: ReadonlySet<string> },): Record<string, unknown> {if (!policy) return {};const byPath = new Map<string, { path: string; enabled: boolean }>();@@ -28,9 +30,18 @@ export function buildCodexBotSkillConfigOverrides(byPath.set(skillPath, {path: skillPath,enabled: item.enabled !== false && item.runtimeStatus !== 'failed' &&+ (!refreshed || refreshed.grants.has(canonicalSkillPath(skillPath))) &&(allowed.has(item.name.trim()) || (!!runtimeName && allowed.has(runtimeName))),});}+ // The refreshed native catalog can contain skills absent from the Bot's+ // earlier catalog. Grant by frozen physical identity, never by a new name.+ for (const item of refreshed?.skills ?? []) {+ byPath.set(item.path, {+ path: item.path,+ enabled: item.enabled !== false && refreshed!.grants.has(canonicalSkillPath(item.path)),+ });+ }// Cindy-owned Bot Skills are outside the ambient allowlist. Codex has no// plugin-root mount equivalent, so project them as explicit per-thread Skill// paths and let them win any accidental same-path ambient entry.diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 4f425336b8..44911942e9 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -368,6 +368,129 @@ function createDeps(};}+describe('Codex managed Skill startup', () => {+ it('does not submit a Bot thread when refreshed discovery has an unscoped error', async () => {+ const agent = new CodexAgent(createDeps({}, { prepareCodexSkills: async () => {} }));+ const host = installFakeHost(agent, method => method === Method.SkillsList+ ? { data: [{ cwd: '/repo', skills: [], errors: [{ message: 'catalog unavailable' }] }] } : undefined,+ { codexHome: '/tmp/mock-codex-home' });+ try {+ await expect(agent.startSession({ sessionId: 'bot-error', workingDir: '/repo', model: 'gpt-5.4',+ botRuntimeProfile: { botId: 'bot-1', profileVersion: 1,+ skillPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ mcpPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ toolsetPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ },+ })).rejects.toThrow('catalog unavailable');+ expect(host.request.mock.calls.some(([method]) => method === Method.ThreadStart || method === Method.ThreadResume)).toBe(false);+ } finally { await agent.dispose(); }+ });++ it.each(['start', 'resume'] as const)('keeps late discovered skills outside frozen Bot grants on %s', async (operation) => {+ let projected = false;+ const known = '/skills/approved/SKILL.md';+ const late = '/skills/late/SKILL.md';+ const failed = '/skills/failed/SKILL.md';+ const own = '/bots/bot-1/skills/own/SKILL.md';+ const agent = new CodexAgent(createDeps({}, {+ prepareCodexSkills: async () => { projected = true; },+ }));+ const host = installFakeHost(agent, (method) => {+ if (method !== Method.SkillsList) return undefined;+ expect(projected).toBe(true);+ return { data: [{ cwd: '/repo', errors: [], skills: [known, late, failed].map(source => ({+ name: 'same-name', description: 'fixture', path: source, scope: 'user', enabled: true,+ })) }] };+ }, { codexHome: '/tmp/mock-codex-home', userAgent: 'mock-codex/0.145.0' });+ try {+ for (const restricted of [false, true]) {+ const handle = await agent.startSession({+ sessionId: `bot-${restricted}`, model: 'gpt-5.4', workingDir: '/repo',+ ...(operation === 'resume' ? { resumeSessionId: '11111111-1111-4111-8111-111111111111' } : {}),+ botRuntimeProfile: { botId: 'bot-1', profileVersion: 1,+ skillPolicy: { mode: 'allowlist', configured: ['same-name', 'failed'],+ catalog: restricted ? [] : [+ { name: 'same-name', path: known },+ { name: 'failed', path: failed, runtimeStatus: 'failed' },+ ], ownSkills: [{ name: 'own', path: own }] },+ mcpPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ toolsetPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ },+ });+ const method = operation === 'resume' ? Method.ThreadResume : Method.ThreadStart;+ const params = host.request.mock.calls.filter(([m]) => m === method).at(-1)?.[1] as { config: Record<string, unknown> };+ expect(params.config['skills.config']).toEqual(expect.arrayContaining([+ { path: known, enabled: !restricted }, { path: late, enabled: false },+ { path: failed, enabled: false }, { path: own, enabled: true },+ ]));+ await handle.close();+ }+ } finally { await agent.dispose(); }+ });++ it.each(['start', 'resume'] as const)('refreshes projections and reloads the catalog before %s on a reused server', async (operation) => {+ let enabled = true;+ let projected = false;+ const prepareCodexSkills = vi.fn(async (home: string) => {+ expect(home).toBe('/tmp/mock-codex-home');+ projected = enabled;+ });+ const discovered: boolean[] = [];+ MockCodexTransport.beforeSkillsListResponse = () => { discovered.push(projected); };+ const agent = new CodexAgent(createDeps({}, { prepareCodexSkills }));+ try {+ const first = await agent.startSession({ sessionId: 'enabled', model: 'gpt-5.4', workingDir: '/repo' });+ enabled = false;+ const second = await agent.startSession({ sessionId: 'disabled', model: 'gpt-5.4', workingDir: '/repo',+ ...(operation === 'resume' ? { resumeSessionId: '11111111-1111-4111-8111-111111111111' } : {}) });+ expect(prepareCodexSkills).toHaveBeenCalledTimes(2);+ expect(discovered).toEqual([true, false]);+ expect(createdTransports).toHaveLength(1);+ const requests = createdTransports[0]!.lines.map(line => JSON.parse(line))+ .filter(item => [Method.SkillsList, Method.ThreadStart, Method.ThreadResume].includes(item.method));+ expect(requests.map(item => item.method)).toEqual([+ Method.SkillsList, Method.ThreadStart, Method.SkillsList,+ operation === 'resume' ? Method.ThreadResume : Method.ThreadStart,+ ]);+ expect(requests.filter(item => item.method === Method.SkillsList)+ .every(item => item.params.forceReload === true)).toBe(true);+ await first.close();+ await second.close();+ } finally { await agent.dispose(); }+ });++ it('does not project local managed Skills into a remote server', async () => {+ const prepareCodexSkills = vi.fn(async () => {});+ const agent = new CodexAgent(createDeps({}, { prepareCodexSkills, getRemoteCodexTransport: () => {+ const transport = new MockCodexTransport();+ createdTransports.push(transport);+ return transport;+ } }));+ try {+ const handle = await agent.startSession({ sessionId: 'remote', model: 'gpt-5.4',+ workingDir: '/remote', remoteHostId: 'remote-skills' });+ expect(prepareCodexSkills).not.toHaveBeenCalled();+ await handle.close();+ } finally { await agent.dispose(); }+ });++ it.each(['projection', 'reload'])('does not submit a thread after %s failure', async (failure) => {+ const prepareCodexSkills = vi.fn(async () => {+ if (failure === 'projection') throw new Error('projection unavailable');+ });+ if (failure === 'reload') MockCodexTransport.onCreate = transport => {+ transport.setMockResponse(Method.SkillsList, { error: { code: -32000, message: 'reload unavailable' } });+ };+ const agent = new CodexAgent(createDeps({}, { prepareCodexSkills }));+ try {+ await expect(agent.startSession({ sessionId: 'failure', model: 'gpt-5.4', workingDir: '/repo' }))+ .rejects.toThrow(/unavailable/);+ expect(createdTransports.flatMap(transport => transport.lines).map(line => JSON.parse(line))+ .some(item => item.method === Method.ThreadStart)).toBe(false);+ } finally { await agent.dispose(); }+ });+});+describe('Codex archive synchronization', () => {it('uses the retained writer and records the native archive path without closing sibling tasks', async () => {const storage = { historyHome: '/history', sqliteHome: '/state' };diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 924ffadbe4..bd4bd7f131 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -48,6 +48,7 @@ import {type TurnPermissionPolicy,} from '../base-agent.js';import { skillEntryPath, snapshotDisabledSkillLaunch, currentDisabledSkillLaunchPaths } from '../shared/skill-activation.js';+import { snapshotManagedSkillGrants } from '../shared/managed-skill-policy.js';import type { AgentCredentialMode } from '../../interfaces/auth-adapter.js';import type {Capabilities,@@ -3615,6 +3616,9 @@ assertRouteCurrent();const sid = opts.sessionId ?? '';const log = this.deps.logger.child(sid ? `s:${sid}/codex` : 'codex');const reviewMode = opts.reviewMode === true;+ const botSkillGrants = !opts.remoteHostId && !reviewMode+ ? snapshotManagedSkillGrants(opts.botRuntimeProfile?.skillPolicy) : undefined;+ let refreshedBotSkillConfig: Record<string, unknown> | undefined;if (reviewMode && opts.remoteHostId) {throw new Error('Cindy Review currently supports local Codex sessions only');}@@ -5206,6 +5210,24 @@ assertRouteCurrent();// 永不返回, UI 无限卡初始化 — 与 request() 的 startup deadline 同款。initResp = await host.ensureStartedWithTimeout(CRITICAL_THREAD_RPC_TIMEOUT_MS, 'startSession initialize');assertCurrentHost('initialize');+ if (!opts.remoteHostId && this.deps.prepareCodexSkills) {+ if (!initResp.codexHome) throw new Error('Codex did not report its local Skill home');+ await this.deps.prepareCodexSkills(initResp.codexHome);+ assertCurrentHost('Skill projection refresh');+ // app-server outlives threads; refreshing files alone leaves its cached+ // catalog available to the next thread after a plugin is disabled.+ const refreshed = await this.listSkillsForHost(host, opts.workingDir, true, CRITICAL_THREAD_RPC_TIMEOUT_MS);+ if (botSkillGrants !== undefined) {+ const unscopedError = refreshed.errors.find(error => !error.path);+ if (unscopedError) throw new Error(unscopedError.message);+ refreshedBotSkillConfig = buildCodexBotSkillConfigOverrides(opts.botRuntimeProfile?.skillPolicy, {+ grants: botSkillGrants,+ skills: [...refreshed.skills, ...refreshed.errors.flatMap(error =>+ error.path ? [{ path: error.path, enabled: false }] : [])],+ });+ }+ assertCurrentHost('Skill catalog reload');+ }} catch (error) {releaseHostBindingLeaseIfNeeded();// Exhaustion/cancellation of native startup is terminal for this request;@@ -5500,7 +5522,7 @@ assertRouteCurrent();}capabilityRoutingConfig = mergeCodexSkillConfigOverrides(capabilityRoutingConfig,- buildCodexBotSkillConfigOverrides(+ refreshedBotSkillConfig ?? buildCodexBotSkillConfigOverrides(reviewMode ? undefined : opts.botRuntimeProfile?.skillPolicy,),);diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.tsindex 7a6214ada9..72b9ea6770 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts@@ -3,12 +3,15 @@* events and only latches deterministic failures for the next-send rollover.*/-import { mkdtempSync, mkdirSync, renameSync, symlinkSync, unlinkSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import fsSync, { promises as fs, existsSync, mkdtempSync, mkdirSync, realpathSync, renameSync, symlinkSync, unlinkSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { assertPiSpawnArgvFitsPlatform } from '../project-resource-cli.js';+import { preparePinnedPiSkillInvocation } from '../runtime-capabilities.js';const knobs = vi.hoisted(() => ({+ spawnArgs: [] as string[],compactCalls: [] as Array<Record<string, unknown>>,compactHold: null as null | Promise<void>,rpcCalls: [] as Array<Record<string, unknown>>,@@ -31,8 +34,10 @@ const knobs = vi.hoisted(() => ({vi.mock("../transport.js", () => ({createPiStdioTransport: (opts: {+ args?: string[];onProcessSpawned?: (pid: number) => void | (() => void);}) => {+ knobs.spawnArgs = opts.args ?? [];opts.onProcessSpawned?.(1234);return {writeLine: async () => {},@@ -178,6 +183,7 @@ describe("PiAgent native auto-compaction ownership", () => {let cwd = "";beforeEach(() => {+ knobs.spawnArgs = [];knobs.compactCalls = [];knobs.compactHold = null;knobs.rpcCalls = [];@@ -200,6 +206,7 @@ describe("PiAgent native auto-compaction ownership", () => {});afterEach(() => {+ vi.restoreAllMocks();rmSync(agentHome, { recursive: true, force: true });rmSync(cwd, { recursive: true, force: true });});@@ -345,6 +352,114 @@ describe("PiAgent native auto-compaction ownership", () => {knobs.onEvent?.({ type: "agent_settled" });}+ it.each(['ordinary', 'disabled', 'bot-allow', 'bot-deny', 'bot-failed', 'bot-disabled', 'bot-missing', 'bot-user-collision', 'bot-global-disabled'] as const)('loads managed skills through explicit paths: %s', async (mode) => {+ const skill = path.join(agentHome, 'managed', 'learn', 'SKILL.md');+ mkdirSync(path.dirname(skill), {recursive:true}); writeFileSync(skill, '---\nname: learn\ndescription: fixture\n---\nLearn');+ const deps = buildDeps();+ deps.getManagedSkills = async () => [{kind:'agent-skill', name:'learn', source:'skill', path:skill,+ claudeCommandName:'cindy:learn'}];+ if(mode === 'disabled' || mode === 'bot-global-disabled') deps.getDisabledSkillPaths = () => [path.dirname(skill)];+ const bot = mode.startsWith('bot');+ const handle = await new PiAgent(deps).startSession({ sessionId:'managed-skills', workingDir:cwd, model:'m',+ ...(bot ? {botRuntimeProfile:{botId:'fixture',profileVersion:1,+ skillPolicy:{mode:'allowlist' as const, configured:mode === 'bot-deny' ? [] : ['skill:learn'],+ catalog: mode === 'bot-missing' ? [] : [+ { name: 'learn', runtimeCommandName: 'skill:learn', path: skill,+ enabled: mode !== 'bot-disabled', runtimeStatus: mode === 'bot-failed' ? 'failed' as const : 'loaded' as const },+ ...(mode === 'bot-user-collision' ? [{ name: 'learn', runtimeCommandName: 'skill:learn',+ path: path.join(agentHome, 'user-learn', 'SKILL.md'), enabled: true }] : []),+ ]},+ mcpPolicy:{mode:'inherit' as const,configured:[],catalog:[]},+ toolsetPolicy:{mode:'inherit' as const,configured:[],catalog:[]}}} : {})});+ try {+ const projection = knobs.spawnArgs.find((arg) => path.basename(arg) === 'cindy-managed-skills');+ expect(!!projection).toBe(mode === 'ordinary' || mode === 'bot-allow');+ expect(knobs.spawnArgs).not.toContain(realpathSync(skill));+ if (projection) {+ const entries = readdirSync(projection);+ expect(entries).toHaveLength(1);+ const projectedFile = path.join(projection, entries[0]!, 'SKILL.md');+ expect(realpathSync(projectedFile)).toBe(realpathSync(skill));+ expect(preparePinnedPiSkillInvocation('/learn', { name: 'learn', path: skill }, {+ capturedAt: '2026-10-01T00:00:00.000Z', generation: 1, status: 'loaded', source: 'pi:get_commands',+ commands: [{ name: 'skill:learn', source: 'skill', sourceInfo: { path: projectedFile, baseDir: path.dirname(projectedFile) } }],+ })).toBe('/skill:learn');+ }+ if(bot) expect(knobs.spawnArgs).toContain('--no-skills');+ if(mode === 'bot-allow') expect(knobs.spawnArgs.filter((arg) => arg === '--skill')).toHaveLength(1);+ } finally {await handle.close();}+ });++ it('keeps hundreds of long managed skill paths out of Windows argv and cleans only session links', async () => {+ const skills = Array.from({ length: 350 }, (_, index) => {+ const file = path.join(agentHome, 'approved', 'revision-'.repeat(12), String(index), 'SKILL.md');+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, `---\nname: fixture-${index}\ndescription: fixture\n---\nBody`);+ return { kind: 'agent-skill' as const, name: `fixture-${index}`, source: 'skill' as const,+ path: file, claudeCommandName: `cindy-plugin-example:fixture-${index}` };+ });+ expect(() => assertPiSpawnArgvFitsPlatform(skills.flatMap((skill) => ['--skill', skill.path]), 'win32')).toThrow();+ const deps = buildDeps();+ deps.getManagedSkills = async () => skills;+ const handle = await new PiAgent(deps).startSession({ sessionId: 'many-skills', workingDir: cwd, model: 'm' });+ const projection = knobs.spawnArgs.find((arg) => path.basename(arg) === 'cindy-managed-skills')!;+ try {+ expect(() => assertPiSpawnArgvFitsPlatform(knobs.spawnArgs, 'win32')).not.toThrow();+ expect(knobs.spawnArgs.filter((arg) => arg === '--skill')).toHaveLength(1);+ expect(knobs.spawnArgs.some((arg) => skills.some((skill) => arg === skill.path))).toBe(false);+ const entries = readdirSync(projection).sort();+ expect(entries).toHaveLength(skills.length);+ expect(entries.map((entry) => realpathSync(path.join(projection, entry, 'SKILL.md'))))+ .toEqual(skills.map((skill) => realpathSync(skill.path)));+ } finally { await handle.close(); }+ await vi.waitFor(() => expect(existsSync(projection)).toBe(false));+ expect(skills.every((skill) => existsSync(skill.path))).toBe(true);+ });++ it.each(['discovery', 'realpath', 'mkdir', 'symlink'] as const)('cleans startup resources when managed Skill %s fails', async (operation) => {+ const skill = path.join(agentHome, 'managed', 'learn', 'SKILL.md');+ mkdirSync(path.dirname(skill), { recursive: true });+ writeFileSync(skill, '---\nname: learn\ndescription: fixture\n---\nLearn');+ const deps = buildDeps();+ const disposeSessionCtx = vi.fn();+ deps.preparePiExtraSpawnConfig = async () => ({ disposeSessionCtx });+ deps.getManagedSkills = async () => [{ kind: 'agent-skill', name: 'learn', source: 'skill',+ path: skill, claudeCommandName: 'cindy:learn' }];+ const failure = Object.assign(new Error('managed projection I/O failed'), { code: 'EACCES' });+ const originalMkdir = fs.mkdir;+ const originalSymlink = fs.symlink;+ let failedPath = '';+ if (operation === 'discovery') {+ deps.getManagedSkills = async () => { failedPath = skill; throw failure; };+ } else if (operation === 'realpath') {+ const originalRealpath = fsSync.realpathSync;+ vi.spyOn(fsSync, 'realpathSync').mockImplementation(((target: string, options: unknown) => {+ if (String(target) === skill) { failedPath = skill; throw failure; }+ return originalRealpath(target, options as never);+ }) as typeof fsSync.realpathSync);+ } else if (operation === 'mkdir') {+ vi.spyOn(fs, 'mkdir').mockImplementation((async (target: string, options: unknown) => {+ if (String(target).endsWith('cindy-managed-skills')) { failedPath = String(target); throw failure; }+ return originalMkdir(target, options as never);+ }) as typeof fs.mkdir);+ } else {+ vi.spyOn(fs, 'symlink').mockImplementation(async (target, link, type) => {+ if (String(link).includes('cindy-managed-skills')) { failedPath = String(link); throw failure; }+ return originalSymlink(target, link, type);+ });+ }+ await expect(new PiAgent(deps).startSession({ sessionId: 'failed-skill', workingDir: cwd, model: 'm' }))+ .rejects.toBe(failure);+ expect(failedPath).not.toBe('');+ expect(disposeSessionCtx).toHaveBeenCalledTimes(1);+ expect(knobs.spawnArgs).toEqual([]);+ await vi.waitFor(() => {+ expect(readdirSync(path.join(agentHome, 'run-tmp'))).toEqual([]);+ expect(readdirSync(path.join(agentHome, 'runtime')).filter(name => /^(perm|subagent)-/.test(name))).toEqual([]);+ });+ expect(existsSync(skill)).toBe(true);+ });+it("enables Pi native auto-compaction during startup", async () => {const handle = await start();expect(knobs.rpcCalls).toContainEqual({diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 1fe7d0094f..9570f2a51f 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -1,6 +1,6 @@import { getPiExtensionUiCapability } from './extension-ui-capabilities.js';import { parsePiManagementArgs, parsePiManagementText } from './managed-command.js';-import { snapshotDisabledSkillLaunch, currentDisabledSkillLaunchPaths, extendDisabledSkillLaunchPaths, type DisabledSkillLaunchSnapshot } from '../shared/skill-activation.js';+import { canonicalSkillPath, snapshotDisabledSkillLaunch, currentDisabledSkillLaunchPaths, extendDisabledSkillLaunchPaths, type DisabledSkillLaunchSnapshot } from '../shared/skill-activation.js';/*** PiAgent —— pi coding agent(earendil-works/pi)接入。*@@ -210,6 +210,7 @@ import {unavailablePiProjectResourceAssembly,} from './project-resource-assembly.js';import { applyPiBotSkillPolicy } from './bot-skill-policy.js';+import { resolveAllowedManagedSkills, snapshotManagedSkillGrants } from '../shared/managed-skill-policy.js';import {assertPiSpawnArgvFitsPlatform,collectPiProjectResourceCliPaths,@@ -3751,44 +3752,83 @@ export class PiAgent extends BaseAgent {}: collectedProjectResources;- const args = [- '--mode',- 'rpc',- // --no-approve remains the hard project-settings gate. Explicit --skill /- // --prompt-template / --extension pass original in-repo paths without- // trusting `.pi/settings.json` or auto-installing project packages.- '--no-approve',- ...(nativePackagePaths.length === 0 ? ['--no-extensions'] : []),- '--session-dir',- sessionDir,- '--provider',- initialProvider,- '--model',- initialWireModel,- ...(reviewMode ? ['--tools', 'read,grep,find,ls'] : []),- // Bot sessions must not absorb project/global AGENTS.md or CLAUDE.md from- // the cwd chain — their context is the Bot profile, not the workspace.- ...(opts.botRuntimeProfile ? ['--no-context-files'] : []),- ...(botSkillSelection.disableImplicitSkills ? ['--no-skills'] : []),- ...(appendSystemPrompt.length > 0 ? ['--append-system-prompt', appendSystemPrompt] : []),- '--extension',- bridgeExtensionPath,- ...(localSubagentSupported ? ['--extension', subagentExtensionPath] : []),- ...(!reviewMode && planModeExtAvailable ? ['--extension', planModeExtPath] : []),- ...(loadProjectResourcesInPlace- ? piProjectResourceCliArgs(projectResourceCli)- : botSkillSelection.explicitSkillPaths.flatMap((skillPath) => ['--skill', skillPath])),- ];+ // Own the entire managed-skill setup in the existing startup rollback:+ // discovery and path checks can fail before any projection is created.+ let managedSkillPaths: string[];+ let managedSkillRoot: string | undefined;+ let args: string[];try {+ const managedSkillGrants = snapshotManagedSkillGrants(opts.botRuntimeProfile?.skillPolicy);+ const managedSkills = opts.remoteHostId || reviewMode ? [] : await this.deps.getManagedSkills?.() ?? [];+ const managedDisabledPaths = snapshotDisabledSkillLaunch(opts.remoteHostId || reviewMode ? [] : this.deps.getDisabledSkillPaths?.() ?? []);+ const managedSourceIdentities = new Set(managedSkills.flatMap((skill) =>+ skill.path ? [canonicalSkillPath(skill.path)] : []));+ const managedSourcePaths = new Set(managedSkills.flatMap((skill) => skill.path ? [path.resolve(skill.path)] : []));+ managedSkillPaths = resolveAllowedManagedSkills(managedSkills, managedSkillGrants,+ currentDisabledSkillLaunchPaths(managedDisabledPaths)).map((skill) => skill.path);+ // The catalog path may alias a managed source. Apply the managed grant and+ // activation checks once, including paths already selected by the Bot.+ const additionalSkillPaths = [...new Map([+ ...(loadProjectResourcesInPlace ? [] : botSkillSelection.explicitSkillPaths.filter((skillPath) =>+ !managedSourcePaths.has(path.resolve(skillPath)) && !managedSourceIdentities.has(canonicalSkillPath(skillPath)))),+ ].map((skillPath) => [canonicalSkillPath(skillPath), skillPath])).values()];++ // One explicit directory also works with --no-skills. Keep its lifetime in+ // the existing per-session configHome and link only already-authorized+ // physical sources; argv size must not grow with installed plugin count.+ const managedLaunchSkills = managedSkillPaths.filter((skillPath) => !projectResourceCli.skills+ .some((existing) => canonicalSkillPath(existing) === canonicalSkillPath(skillPath)));+ managedSkillRoot = managedLaunchSkills.length ? path.join(configHome, 'cindy-managed-skills') : undefined;++ args = [+ '--mode',+ 'rpc',+ // --no-approve remains the hard project-settings gate. Explicit --skill /+ // --prompt-template / --extension pass original in-repo paths without+ // trusting `.pi/settings.json` or auto-installing project packages.+ '--no-approve',+ ...(nativePackagePaths.length === 0 ? ['--no-extensions'] : []),+ '--session-dir',+ sessionDir,+ '--provider',+ initialProvider,+ '--model',+ initialWireModel,+ ...(reviewMode ? ['--tools', 'read,grep,find,ls'] : []),+ // Bot sessions must not absorb project/global AGENTS.md or CLAUDE.md from+ // the cwd chain — their context is the Bot profile, not the workspace.+ ...(opts.botRuntimeProfile ? ['--no-context-files'] : []),+ ...(botSkillSelection.disableImplicitSkills ? ['--no-skills'] : []),+ ...additionalSkillPaths.filter((skillPath) => !projectResourceCli.skills+ .some((existing) => canonicalSkillPath(existing) === canonicalSkillPath(skillPath)))+ .flatMap((skillPath) => ['--skill', skillPath]),+ ...(managedSkillRoot ? ['--skill', managedSkillRoot] : []),+ ...(appendSystemPrompt.length > 0 ? ['--append-system-prompt', appendSystemPrompt] : []),+ '--extension',+ bridgeExtensionPath,+ ...(localSubagentSupported ? ['--extension', subagentExtensionPath] : []),+ ...(!reviewMode && planModeExtAvailable ? ['--extension', planModeExtPath] : []),+ ...(loadProjectResourcesInPlace+ ? piProjectResourceCliArgs(projectResourceCli)+ : []),+ ];+ if (managedSkillRoot) {+ await fs.mkdir(managedSkillRoot);+ for (const [index, skillPath] of managedLaunchSkills.entries()) {+ // Preserve discovery order for same-name skills without long filenames.+ await fs.symlink(path.dirname(skillPath), path.join(managedSkillRoot, String(index).padStart(12, '0')),+ process.platform === 'win32' ? 'junction' : 'dir');+ }+ }assertPiSpawnArgvFitsPlatform(args);} catch (error) {try {disposeSessionCtx?.();} catch {- /* best-effort: cleanup failure must not mask argv budget failure */+ /* best-effort: cleanup failure must not mask Skill setup / argv failure */}disposeSessionCtx = undefined;- cleanupConfigHome();+ await cleanupConfigHome();cleanupRuntimeFiles();throw error;}@@ -5686,6 +5726,8 @@ export class PiAgent extends BaseAgent {[...managedPackageRoots,...projectResourceCli.skills,+ ...managedSkillPaths,+ ...(managedSkillRoot ? [managedSkillRoot] : []),...projectResourceCli.promptTemplates,...projectResourceCli.extensions,],@@ -7951,7 +7993,15 @@ export class PiAgent extends BaseAgent {/** SkillHub raw view; project items remain discovered until runtime truth says otherwise. */override async listCustomizations(opts: ListCustomizationsOptions): Promise<ListCustomizationsResult> {- return scanPiCustomizations(opts);+ const result = await 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,+ description: skill.description, absolutePath: path.dirname(skill.path!), mdPath: skill.path,+ enabled: skill.enabled,+ })));+ }+ return result;}/**@@ -7974,6 +8024,8 @@ export class PiAgent extends BaseAgent {]);const out: ListAgentSkillsResult = {skills: [+ ...(await this.deps.getManagedSkills?.() ?? []).map(({ claudeCommandName: _command, ...skill }) =>+ ({ ...skill, runtimeCommandName: `skill:${skill.name}` })),...items.filter((it) => it.kind === 'skill' && it.enabled !== false).map((it) => ({diff --git a/packages/maker-core/src/agents/shared/managed-skill-policy.test.ts b/packages/maker-core/src/agents/shared/managed-skill-policy.test.tsnew file mode 100644index 0000000000..573a837bc7--- /dev/null+++ b/packages/maker-core/src/agents/shared/managed-skill-policy.test.ts@@ -0,0 +1,83 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { canonicalSkillPath } from "./skill-activation.js";+import {+ resolveAllowedManagedSkills,+ snapshotManagedSkillGrants,+} from "./managed-skill-policy.js";+import { prepareManagedSkillPlugins } from "../claude-code/managed-skill-plugins.js";++describe("managed skill Bot grants", () => {+ it("checks and mounts the same source if an alias moves between approval and loading", async () => {+ const root = fs.mkdtempSync(+ path.join(os.tmpdir(), "cindy-managed-grants-"),+ );+ try {+ const approved = path.join(root, "approved");+ const replaced = path.join(root, "replaced");+ const alias = path.join(root, "discovery");+ for (const dir of [approved, replaced]) {+ fs.mkdirSync(dir);+ fs.writeFileSync(path.join(dir, "SKILL.md"), "# Fixture");+ }+ fs.symlinkSync(+ approved,+ alias,+ process.platform === "win32" ? "junction" : "dir",+ );+ const grants = snapshotManagedSkillGrants({+ mode: "allowlist",+ configured: ["cindy:learn"],+ catalog: [+ {+ name: "learn",+ runtimeCommandName: "cindy:learn",+ path: path.join(alias, "SKILL.md"),+ enabled: true,+ },+ ],+ });+ expect(grants?.has(canonicalSkillPath(approved))).toBe(true);+ const discovered = [+ {+ kind: "agent-skill" as const,+ name: "learn",+ source: "skill" as const,+ claudeCommandName: "cindy:learn",+ path: path.join(alias, "SKILL.md"),+ },+ ];+ const selected = resolveAllowedManagedSkills(discovered, grants, []);+ // Pi receives these exact physical paths as --skill arguments.+ expect(selected[0]?.path).toBe(+ fs.realpathSync(path.join(approved, "SKILL.md")),+ );+ fs.unlinkSync(alias);+ fs.symlinkSync(+ replaced,+ alias,+ process.platform === "win32" ? "junction" : "dir",+ );+ expect(grants?.has(canonicalSkillPath(alias))).toBe(false);+ expect(grants?.has(canonicalSkillPath(approved))).toBe(true);+ expect(resolveAllowedManagedSkills(discovered, grants, [])).toEqual([]);+ const mounted = await prepareManagedSkillPlugins(selected);+ try {+ expect(+ fs.realpathSync.native(path.join(mounted.roots[0]!, "skills", "learn")),+ ).toBe(fs.realpathSync.native(approved));+ } finally {+ await mounted.dispose();+ }+ expect(resolveAllowedManagedSkills(selected, grants, [approved])).toEqual(+ [],+ );+ fs.rmSync(approved, { recursive: true });+ expect(resolveAllowedManagedSkills(selected, grants, [])).toEqual([]);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+ });+});diff --git a/packages/maker-core/src/agents/shared/managed-skill-policy.ts b/packages/maker-core/src/agents/shared/managed-skill-policy.tsnew file mode 100644index 0000000000..5865ef9ba4--- /dev/null+++ b/packages/maker-core/src/agents/shared/managed-skill-policy.ts@@ -0,0 +1,59 @@+import fs from "node:fs";+import type {+ AgentDeps,+ BotRuntimeSkillPolicy,+ BotRuntimeSkillEntry,+} from "../base-agent.js";+import { canonicalSkillPath, isSkillDisabled } from "./skill-activation.js";++/** Check and mount the same physical file, even if a discovery alias moves later. */+export function resolveAllowedManagedSkills(+ skills: Awaited<ReturnType<NonNullable<AgentDeps["getManagedSkills"]>>>,+ grants: ReadonlySet<string> | undefined,+ disabledPaths: readonly string[],+) {+ return skills.flatMap((skill) => {+ if (!skill.path) return [];+ let source: string;+ try {+ source = fs.realpathSync(skill.path);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw error;+ }+ if (+ (grants !== undefined && !grants.has(canonicalSkillPath(source))) ||+ isSkillDisabled(source, disabledPaths)+ )+ return [];+ return [{ ...skill, path: source }];+ });+}++/** Freeze only resolved, usable Bot grants; names alone never grant a managed source. */+export function snapshotManagedSkillGrants(+ policy: BotRuntimeSkillPolicy | undefined,+): ReadonlySet<string> | undefined {+ if (!policy) return undefined;+ // The host maps legacy inherit to no external grants. Bot-owned Skills have+ // their own mounting path and are deliberately outside this policy.+ if (policy.mode !== "allowlist") return new Set();+ const catalog = new Map<string, BotRuntimeSkillEntry>();+ for (const item of policy.catalog) {+ catalog.set(item.name.trim(), item);+ if (item.runtimeCommandName?.trim())+ catalog.set(item.runtimeCommandName.trim(), item);+ }+ const allowed = new Set<string>();+ for (const name of policy.configured) {+ const item = catalog.get(name.trim());+ if (+ item?.path &&+ item.enabled !== false &&+ item.runtimeStatus !== "failed"+ ) {+ allowed.add(canonicalSkillPath(item.path));+ }+ }+ return allowed;+}diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.tsindex e47becccaf..832d48a4db 100644--- a/packages/plugin-protocol/src/manifest.ts+++ b/packages/plugin-protocol/src/manifest.ts@@ -68,8 +68,8 @@ function isWindowsReservedName(name: string): boolean {* 一个网址标签页。网址范围装入时在 preview.hosts 白名单里定死(同 network* 域名白名单语法),运行期主机逐次校验,范围外一律拒——防钓鱼是结构性的。* 'skill' = 捆绑 Agent Skills(2026-07-25):插件随包携带 SKILL.md 技能目录,- * 装入且启用后由主机链接进共享技能根 ~/.agents/skills/<id>--<name>(win32 用- * junction),Claude Code 与 Codex 都能发现。信任面与其它槽完全不同量级:技能+ * 装入且启用后由主机投影到 Cindy 的账号隔离目录,通过各 Harness 的私有入口+ * 提供给 Claude Code、Codex、Pi,不写入用户共用技能目录。信任面与其它槽完全不同量级:技能* 指令由主 Agent 以**用户全部权限**执行、对所有项目与会话生效、不受插件沙箱* 约束,也不随"某工作目录停用本插件"而隐藏——仅全局停用/卸载才撤链。因此* manifest 全声明式(items 的 name/description 必须与 SKILL.md frontmatter 逐字@@ -786,7 +786,7 @@ export const GHOST_SKILL_NAME_MAX_CHARS = 64;/*** skill 槽:技能 name 形状——小写字母/数字,连字符仅作单段分隔(禁首尾与连续* 连字符)。比 SkillHub 的技能名规则更严:意识 id 允许含 `--`(GHOST_ID_RE),- * 共享技能根的链接名是 `<id>--<name>`,只有 name 侧禁 `--`,+ * 插件私有技能根的链接名是 `<id>--<name>`,只有 name 侧禁 `--`,* 按"最后一个 `--`"拆分才唯一,不同插件才不可能撞出同一个链接名。*/export const GHOST_SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;@@ -973,7 +973,7 @@ export interface GhostManifest {preview?: GhostPreviewNeeds;/*** skill 能力详单;v2 与 'skill' slot 成对。随包捆绑的 Agent Skills 清单。- * 启用时主机链接进共享技能根,Claude Code 与 Codex 双端可见;字段不参与+ * 启用时由 Cindy 私有入口加载到本地 Claude Code、Codex 与 Pi,不写用户共享目录;字段不参与* 本地化(必须与 SKILL.md 逐字一致,见 GhostSkillItem)。*/skill?: GhostSkillNeeds;@@ -3325,7 +3325,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {// skill 槽详单:与 slots 含 'skill' **严格成对**(有槽必有详单——捆绑了什么// 技能是本能力的全部知情面)。name/description 与 SKILL.md 的逐字一致性在// 打包与装入两侧另行强制,这里只管声明本身的形状。name/dir 大小写折叠去重:- // win32 文件系统折叠大小写,共享技能根的链接名不允许折叠后相撞。+ // win32 文件系统折叠大小写,插件私有技能根的链接名不允许折叠后相撞。let skill: GhostSkillNeeds | undefined;if (raw.skill !== undefined) {if (!isPlainObject(raw.skill)) {