Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): harden built-in Skill activation

xd-bobo47329a92414d
diff --cc apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
index f21dd7c0e9,0000000000..3bc1f75185
mode 100644,000000..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
@@@ -1,710 -1,0 +1,793 @@@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ activeCindyBuiltInAgentSkills,
+ BUILT_IN_SKILLS_BUNDLE_VERSION,
+ builtInSkillDescriptors,
+ markCindyBuiltInAgentSkills,
+ prepareBuiltInSkills,
+ refreshBuiltInClaudeSkillLinks,
+ resolveBundledSystemSkillsRoot,
+} from '../built-in-skills';
+
+const roots: string[] = [];
+
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-built-in-skills-'));
+ roots.push(root);
+ const bundledRoot = path.join(root, 'resources', 'system-skills');
+ const source = path.join(bundledRoot, 'cindy-skill-creator');
+ const learnSource = path.join(bundledRoot, 'learn');
+ const userDataDir = path.join(root, 'user-data');
+ const appDataDir = path.join(root, 'app-data');
+ const homeDir = path.join(root, 'home');
+ fs.mkdirSync(path.join(source, 'scripts'), { recursive: true });
+ fs.mkdirSync(learnSource, { recursive: true });
+ fs.writeFileSync(
+ path.join(source, 'SKILL.md'),
+ '---\nname: cindy-skill-creator\ndescription: Create Skills\n---\n\n# Creator\n',
+ );
+ fs.writeFileSync(path.join(source, 'scripts', 'validate.py'), 'print("ok")\n');
+ fs.writeFileSync(
+ path.join(learnSource, 'SKILL.md'),
+ '---\nname: learn\ndescription: Start Cindy Learn\n---\n\n# Learn\n',
+ );
+ const withSharedMutation = async <T>(
+ _names: readonly string[],
+ operation: () => Promise<T>,
+ ): Promise<T> => operation();
+ return { bundledRoot, source, userDataDir, appDataDir, homeDir, withSharedMutation };
+}
+
+async function prepareAndProjectBuiltInSkills(
+ input: ReturnType<typeof fixture> & { bundleVersion?: number },
+) {
+ return prepareBuiltInSkills(input);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('built-in Skills', () => {
+ it('materializes immutable versioned bytes and exposes the active version', async () => {
+ const input = fixture();
+ const first = await prepareAndProjectBuiltInSkills(input);
+ const descriptor = builtInSkillDescriptors(input.userDataDir, input.appDataDir)[0]!;
+ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-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');
+ expect(first.changed).toBe(true);
+ expect(first.warnings).toEqual([]);
+ expect(manifest).toMatchObject({
+ schemaVersion: 3,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION,
+ });
+ expect(descriptor.absolutePath).toBe(
- path.join(root, '.versions', manifest.activeBundle, 'cindy-skill-creator'),
++ path.join(root, '.active', 'cindy-skill-creator'),
++ );
++ const firstImmutablePath = fs.realpathSync(descriptor.absolutePath);
++ expect(firstImmutablePath).toBe(
++ fs.realpathSync(path.join(root, '.versions', manifest.activeBundle, 'cindy-skill-creator')),
+ );
+ expect(fs.realpathSync(link)).toBe(fs.realpathSync(descriptor.absolutePath));
+ expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(
+ fs.realpathSync(descriptor.absolutePath),
+ );
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(
+ '# Creator',
+ );
+ const learnDescriptor = first.descriptors.find((item) => item.name === 'learn')!;
+ expect(fs.realpathSync(path.join(input.homeDir, '.agents', 'skills', 'learn'))).toBe(
+ fs.realpathSync(learnDescriptor.absolutePath),
+ );
+ expect(fs.readFileSync(path.join(learnDescriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(
+ '# Learn',
+ );
+
+ const second = await prepareAndProjectBuiltInSkills(input);
+ expect(second.changed).toBe(false);
+
+ fs.writeFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), '# Tampered\n');
+ const repaired = await prepareAndProjectBuiltInSkills(input);
+ const repairedDescriptor = repaired.descriptors.find(
+ (item) => item.name === 'cindy-skill-creator',
+ )!;
+ expect(repaired.changed).toBe(true);
- expect(repairedDescriptor.absolutePath).not.toBe(descriptor.absolutePath);
++ expect(repairedDescriptor.absolutePath).toBe(descriptor.absolutePath);
++ expect(fs.realpathSync(repairedDescriptor.absolutePath)).not.toBe(firstImmutablePath);
+ expect(fs.readFileSync(path.join(repairedDescriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(
+ '# Creator',
+ );
- expect(fs.existsSync(path.join(descriptor.absolutePath, 'SKILL.md'))).toBe(true);
++ expect(fs.existsSync(path.join(firstImmutablePath, 'SKILL.md'))).toBe(true);
+
+ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nUpdated\n');
+ const updated = await prepareAndProjectBuiltInSkills({
+ ...input,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ });
+ expect(updated.changed).toBe(true);
+ const updatedDescriptor = updated.descriptors.find(
+ (item) => item.name === 'cindy-skill-creator',
+ )!;
+ expect(fs.readFileSync(path.join(updatedDescriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(
+ 'Updated',
+ );
+ expect(fs.realpathSync(link)).toBe(fs.realpathSync(updatedDescriptor.absolutePath));
+ });
+
+ it('does not let an older or conflicting bundle overwrite newer shared bytes', async () => {
+ const input = fixture();
+ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nNewer bundle\n');
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 2 });
+ const descriptor = newer.descriptors[0]!;
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+
+ fs.writeFileSync(
+ path.join(input.source, 'SKILL.md'),
+ '---\nname: cindy-skill-creator\ndescription: Old bundle\n---\n\n# Old\n',
+ );
+ const older = await prepareBuiltInSkills({ ...input, bundleVersion: 1 });
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(older.warnings.join('\n')).toContain('only carries older bundle 1');
+
+ const conflicting = await prepareBuiltInSkills({ ...input, bundleVersion: 2 });
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(conflicting.warnings.join('\n')).toContain('bundle version 2 was reused');
+ });
+
+ it('fails closed when an existing bundle manifest is corrupt', async () => {
+ const input = fixture();
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const descriptor = newer.descriptors[0]!;
+ const manifestPath = path.join(input.appDataDir, 'Cindy', 'shared-system-skills', '.cindy-system-skills.json');
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+ fs.writeFileSync(manifestPath, '{ invalid json');
+ fs.writeFileSync(
+ path.join(input.source, 'SKILL.md'),
+ '---\nname: cindy-skill-creator\ndescription: Old bundle\n---\n\n# Old\n',
+ );
+
+ const older = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(older.changed).toBe(false);
+ expect(older.projectionSafe).toBe(false);
+ expect(older.warnings.join('\n')).toContain('manifest is unavailable');
+ });
+
+ 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 sharedTarget = fs.realpathSync(sharedLink);
+ const claudeTarget = fs.realpathSync(claudeLink);
+ const manifestPath = path.join(
+ input.appDataDir,
+ 'Cindy',
+ 'shared-system-skills',
+ '.cindy-system-skills.json',
+ );
+ fs.writeFileSync(manifestPath, JSON.stringify({
+ schemaVersion: 3,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION,
+ fingerprints: {},
+ activeBundle: 'damaged',
+ }));
+
+ const failed = await prepareAndProjectBuiltInSkills(input);
+
+ expect(failed.projectionSafe).toBe(false);
+ expect(failed.warnings.join('\n')).toContain('manifest is unavailable');
+ expect(fs.realpathSync(sharedLink)).toBe(sharedTarget);
+ expect(fs.realpathSync(claudeLink)).toBe(claudeTarget);
+ });
+
+ it('does not infer a first install when the manifest is missing beside existing Skills', async () => {
+ const input = fixture();
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const descriptor = newer.descriptors[0]!;
+ const manifestPath = path.join(input.appDataDir, 'Cindy', 'shared-system-skills', '.cindy-system-skills.json');
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+ fs.unlinkSync(manifestPath);
+
+ const retried = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(retried.changed).toBe(false);
+ expect(retried.warnings.join('\n')).toContain('manifest is unavailable');
+ });
+
+ it('restores the atomic manifest backup before applying version ordering', async () => {
+ const input = fixture();
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const descriptor = newer.descriptors[0]!;
+ const manifestPath = path.join(input.appDataDir, 'Cindy', 'shared-system-skills', '.cindy-system-skills.json');
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+ fs.renameSync(manifestPath, `${manifestPath}.bak`);
+ fs.writeFileSync(
+ path.join(input.source, 'SKILL.md'),
+ '---\nname: cindy-skill-creator\ndescription: Old bundle\n---\n\n# Old\n',
+ );
+
+ const older = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+
+ expect(fs.existsSync(manifestPath)).toBe(true);
+ expect(fs.existsSync(`${manifestPath}.bak`)).toBe(false);
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(older.warnings.join('\n')).toContain('only carries older bundle 4');
+ });
+
+ it('advances the bundle version only after every Skill is ready and retries partial upgrades', async () => {
+ const input = fixture();
+ await prepareBuiltInSkills(input);
+ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nCreator v2\n');
+ fs.writeFileSync(path.join(input.bundledRoot, 'learn', 'SKILL.md'), 'Learn v2\n');
+ fs.renameSync(
+ path.join(input.bundledRoot, 'learn', 'SKILL.md'),
+ path.join(input.bundledRoot, 'learn', 'SKILL.md.missing'),
+ );
+
+ const partial = await prepareBuiltInSkills({
+ ...input,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ });
+ const manifestPath = path.join(input.appDataDir, 'Cindy', 'shared-system-skills', '.cindy-system-skills.json');
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(
+ BUILT_IN_SKILLS_BUNDLE_VERSION,
+ );
+ expect(partial.warnings.join('\n')).toContain('missing SKILL.md');
+ expect(
+ fs.readFileSync(path.join(partial.descriptors[0]!.absolutePath, 'SKILL.md'), 'utf8'),
+ ).not.toContain('Creator v2');
+
+ fs.renameSync(
+ path.join(input.bundledRoot, 'learn', 'SKILL.md.missing'),
+ path.join(input.bundledRoot, 'learn', 'SKILL.md'),
+ );
+ const retried = await prepareBuiltInSkills({
+ ...input,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ });
+ expect(retried.warnings).toEqual([]);
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(
+ BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ );
+ expect(
+ fs.readFileSync(
+ path.join(
+ retried.descriptors.find((descriptor) => descriptor.name === 'learn')!.absolutePath,
+ 'SKILL.md',
+ ),
+ 'utf8',
+ ),
+ ).toBe('Learn v2\n');
+ });
+
+ it('keeps the active bundle readable when publishing a new version directory fails', async () => {
+ const input = fixture();
+ const initial = await prepareBuiltInSkills(input);
+ const creator = initial.descriptors.find((descriptor) => descriptor.name === 'cindy-skill-creator')!;
+ const learn = initial.descriptors.find((descriptor) => descriptor.name === 'learn')!;
+ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
+ const manifestPath = path.join(root, '.cindy-system-skills.json');
+ const initialManifest = fs.readFileSync(manifestPath, 'utf8');
+ const initialActiveBundle = JSON.parse(initialManifest).activeBundle as string;
+ const initialCreator = fs.readFileSync(path.join(creator.absolutePath, 'SKILL.md'), 'utf8');
+ const initialLearn = fs.readFileSync(path.join(learn.absolutePath, 'SKILL.md'), 'utf8');
+ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nCreator v2\n');
+ fs.writeFileSync(path.join(input.bundledRoot, 'learn', 'SKILL.md'), 'Learn v2\n');
+
+ const versionsRoot = path.join(root, '.versions');
+ const originalRename = fs.promises.rename.bind(fs.promises);
+ let activeBundleWasReadable = false;
+ vi.spyOn(fs.promises, 'rename').mockImplementation(async (source, destination) => {
+ if (
+ path.dirname(String(source)) === versionsRoot &&
+ path.basename(String(source)).endsWith('.pending') &&
+ path.dirname(String(destination)) === versionsRoot
+ ) {
+ activeBundleWasReadable = fs.existsSync(path.join(creator.absolutePath, 'SKILL.md'));
+ throw new Error('blocked version publish');
+ }
+ await originalRename(source, destination);
+ });
+
+ const failed = await prepareBuiltInSkills({
+ ...input,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ });
+
+ expect(failed.changed).toBe(false);
+ expect(failed.warnings.join('\n')).toContain('blocked version publish');
+ expect(activeBundleWasReadable).toBe(true);
+ expect(fs.readFileSync(manifestPath, 'utf8')).toBe(initialManifest);
+ expect(fs.readFileSync(path.join(creator.absolutePath, 'SKILL.md'), 'utf8')).toBe(initialCreator);
+ expect(fs.readFileSync(path.join(learn.absolutePath, 'SKILL.md'), 'utf8')).toBe(initialLearn);
+ expect(fs.readdirSync(versionsRoot)).toEqual([initialActiveBundle]);
+ });
+
+ it('keeps the previous version active when the manifest pointer switch fails', async () => {
+ const input = fixture();
+ const initial = await prepareBuiltInSkills(input);
+ const creator = initial.descriptors.find((descriptor) => descriptor.name === 'cindy-skill-creator')!;
+ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
+ const versionsRoot = path.join(root, '.versions');
+ const manifestPath = path.join(root, '.cindy-system-skills.json');
+ const initialManifest = fs.readFileSync(manifestPath, 'utf8');
+ const initialActiveBundle = JSON.parse(initialManifest).activeBundle as string;
+ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nCreator v2\n');
+
+ const originalRename = fs.renameSync.bind(fs);
+ vi.spyOn(fs, 'renameSync').mockImplementation((source, destination) => {
+ if (String(destination) === manifestPath && String(source).endsWith('.tmp')) {
+ throw new Error('blocked manifest switch');
+ }
+ originalRename(source, destination);
+ });
+
+ const failed = await prepareBuiltInSkills({
+ ...input,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ });
+
+ expect(failed.changed).toBe(false);
+ expect(failed.warnings.join('\n')).toContain('blocked manifest switch');
+ expect(fs.readFileSync(manifestPath, 'utf8')).toBe(initialManifest);
+ expect(fs.readFileSync(path.join(creator.absolutePath, 'SKILL.md'), 'utf8')).not.toContain(
+ 'Creator v2',
+ );
+ expect(failed.descriptors[0]!.absolutePath).toBe(creator.absolutePath);
+ expect(fs.readdirSync(versionsRoot)).toEqual([initialActiveBundle]);
+ });
+
- it('rolls every Agent projection back before keeping the previous manifest', async () => {
++ it('keeps every managed projection on one stable target across bundle upgrades', async () => {
+ const input = fixture();
+ const initial = await prepareBuiltInSkills(input);
+ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
- const manifestPath = path.join(root, '.cindy-system-skills.json');
- const initialManifest = fs.readFileSync(manifestPath, 'utf8');
+ const initialCreator = initial.descriptors.find(
+ (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 nativeCreatorLink = initialCreator.nativeClaudePath;
++ const nativeLearnLink = initialLearn.nativeClaudePath;
++ const initialCreatorBytes = fs.realpathSync(initialCreator.absolutePath);
++ const initialLearnBytes = fs.realpathSync(initialLearn.absolutePath);
++ const projectionTargets = new Map([
++ [creatorLink, fs.readlinkSync(creatorLink)],
++ [learnLink, fs.readlinkSync(learnLink)],
++ [nativeCreatorLink, fs.readlinkSync(nativeCreatorLink)],
++ [nativeLearnLink, fs.readlinkSync(nativeLearnLink)],
++ ]);
+ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nCreator v2\n');
+ fs.appendFileSync(path.join(input.bundledRoot, 'learn', 'SKILL.md'), '\nLearn v2\n');
+
- const originalSymlink = fs.promises.symlink.bind(fs.promises);
- vi.spyOn(fs.promises, 'symlink').mockImplementation(async (target, linkPath, type) => {
- if (
- String(target).includes(
- `${path.sep}.versions${path.sep}v${BUILT_IN_SKILLS_BUNDLE_VERSION + 1}-`,
- )
- && String(linkPath).includes(`learn.next-`)
- ) {
- throw new Error('blocked Learn projection');
++ const updated = await prepareBuiltInSkills({
++ ...input,
++ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
++ });
++
++ expect(updated.warnings).toEqual([]);
++ expect(updated.projectionSafe).toBe(true);
++ for (const [linkPath, target] of projectionTargets) {
++ expect(fs.readlinkSync(linkPath)).toBe(target);
++ }
++ expect(fs.readlinkSync(creatorLink)).toBe(path.join(root, '.active', 'cindy-skill-creator'));
++ expect(fs.realpathSync(creatorLink)).not.toBe(initialCreatorBytes);
++ expect(fs.realpathSync(learnLink)).not.toBe(initialLearnBytes);
++ expect(fs.realpathSync(nativeCreatorLink)).toBe(fs.realpathSync(creatorLink));
++ expect(fs.realpathSync(nativeLearnLink)).toBe(fs.realpathSync(learnLink));
++ });
++
++ it('finishes a committed active-pointer switch after an interrupted upgrade', async () => {
++ const input = fixture();
++ const initial = await prepareBuiltInSkills(input);
++ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
++ const activePath = path.join(root, '.active');
++ const oldActiveTarget = fs.readlinkSync(activePath);
++ const oldCreatorBytes = fs.realpathSync(initial.descriptors[0]!.absolutePath);
++ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nCreator v2\n');
++
++ const upgraded = await prepareBuiltInSkills({
++ ...input,
++ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
++ });
++ const committedCreatorBytes = fs.realpathSync(upgraded.descriptors[0]!.absolutePath);
++ expect(committedCreatorBytes).not.toBe(oldCreatorBytes);
++
++ // 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');
++ expect(fs.realpathSync(sharedLink)).toBe(oldCreatorBytes);
++
++ const recovered = await prepareBuiltInSkills({
++ ...input,
++ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
++ });
++
++ expect(recovered.changed).toBe(true);
++ expect(recovered.projectionSafe).toBe(true);
++ expect(recovered.warnings).toEqual([]);
++ expect(fs.realpathSync(sharedLink)).toBe(committedCreatorBytes);
++ });
++
++ it('restores the previous manifest and active pointer when publication fails', async () => {
++ const input = fixture();
++ const initial = await prepareBuiltInSkills(input);
++ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
++ const manifestPath = path.join(root, '.cindy-system-skills.json');
++ const activePath = path.join(root, '.active');
++ const initialManifest = fs.readFileSync(manifestPath, 'utf8');
++ const initialActiveTarget = fs.readlinkSync(activePath);
++ const initialCreatorBytes = fs.realpathSync(initial.descriptors[0]!.absolutePath);
++ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nCreator v2\n');
++
++ const originalRename = fs.promises.rename.bind(fs.promises);
++ vi.spyOn(fs.promises, 'rename').mockImplementation(async (source, destination) => {
++ if (String(destination) === activePath && String(source).includes('.active.next-')) {
++ throw new Error('blocked active pointer switch');
+ }
- await originalSymlink(target, linkPath, type);
++ await originalRename(source, destination);
+ });
+
+ const failed = await prepareBuiltInSkills({
+ ...input,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ });
+
- expect(failed.changed).toBe(false);
+ expect(failed.projectionSafe).toBe(true);
- expect(failed.warnings.join('\n')).toContain('blocked Learn projection');
- expect(failed.warnings.join('\n')).toContain('not every Agent projection accepted');
++ expect(failed.warnings.join('\n')).toContain('blocked active pointer switch');
+ expect(fs.readFileSync(manifestPath, 'utf8')).toBe(initialManifest);
- expect(fs.realpathSync(creatorLink)).toBe(fs.realpathSync(initialCreator.absolutePath));
- expect(fs.realpathSync(learnLink)).toBe(fs.realpathSync(initialLearn.absolutePath));
- expect(fs.realpathSync(initialCreator.nativeClaudePath)).toBe(
- fs.realpathSync(initialCreator.absolutePath),
- );
- expect(fs.realpathSync(initialLearn.nativeClaudePath)).toBe(
- fs.realpathSync(initialLearn.absolutePath),
- );
++ expect(fs.readlinkSync(activePath)).toBe(initialActiveTarget);
++ expect(fs.realpathSync(initial.descriptors[0]!.absolutePath)).toBe(initialCreatorBytes);
+ expect(fs.readdirSync(path.join(root, '.versions'))).toEqual([
+ JSON.parse(initialManifest).activeBundle,
+ ]);
+ });
+
+ it('repairs projections left on an unpublished bundle before another activation', async () => {
+ const input = fixture();
+ const initial = await prepareBuiltInSkills(input);
+ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
+ const orphanBundle = 'v10-aaaaaaaaaaaaaaaa-00000000-0000-0000-0000-000000000000';
+ const orphanRoot = path.join(root, '.versions', orphanBundle);
+ fs.cpSync(path.dirname(initial.descriptors[0]!.absolutePath), orphanRoot, { recursive: true });
+ const creatorLink = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');
+ fs.unlinkSync(creatorLink);
+ fs.symlinkSync(
+ path.join(orphanRoot, 'cindy-skill-creator'),
+ creatorLink,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+
+ const repaired = await prepareBuiltInSkills(input);
+
+ expect(repaired.projectionSafe).toBe(true);
+ expect(fs.realpathSync(creatorLink)).toBe(
+ fs.realpathSync(initial.descriptors[0]!.absolutePath),
+ );
+ });
+
++ it('migrates direct current-version links onto the stable active path', async () => {
++ const input = fixture();
++ const initial = await prepareBuiltInSkills(input);
++ 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);
++ fs.unlinkSync(sharedLink);
++ fs.symlinkSync(
++ immutableTarget,
++ sharedLink,
++ process.platform === 'win32' ? 'junction' : 'dir',
++ );
++
++ const migrated = await prepareBuiltInSkills(input);
++
++ expect(fs.readlinkSync(sharedLink)).toBe(path.join(root, '.active', descriptor.name));
++ expect(fs.realpathSync(sharedLink)).toBe(immutableTarget);
++ expect(migrated.changed).toBe(true);
++ expect(migrated.warnings).toEqual([]);
++ });
++
+ it('removes first-install projections when no bundle was ever activated', async () => {
+ const input = fixture();
+ 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 nativeLink = path.join(input.userDataDir, 'claude-home', 'skills', 'cindy-skill-creator');
+ fs.mkdirSync(path.join(orphanRoot, 'cindy-skill-creator'), { recursive: true });
+ fs.writeFileSync(
+ path.join(orphanRoot, 'cindy-skill-creator', 'SKILL.md'),
+ '# Unpublished\n',
+ );
+ fs.mkdirSync(path.dirname(sharedLink), { recursive: true });
+ fs.mkdirSync(path.dirname(nativeLink), { recursive: true });
+ fs.symlinkSync(
+ path.join(orphanRoot, 'cindy-skill-creator'),
+ sharedLink,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ fs.symlinkSync(sharedLink, nativeLink, process.platform === 'win32' ? 'junction' : 'dir');
+ fs.writeFileSync(
+ path.join(root, '.cindy-system-skills.json'),
+ `${JSON.stringify({ schemaVersion: 2, bundleVersion: 0, fingerprints: {} })}\n`,
+ );
+ fs.renameSync(
+ path.join(input.bundledRoot, 'learn', 'SKILL.md'),
+ path.join(input.bundledRoot, 'learn', 'SKILL.md.missing'),
+ );
+
+ const recovered = await prepareBuiltInSkills(input);
+
+ expect(recovered.projectionSafe).toBe(false);
+ expect(recovered.warnings.join('\n')).toContain('missing SKILL.md');
+ expect(fs.existsSync(sharedLink)).toBe(false);
+ expect(fs.existsSync(nativeLink)).toBe(false);
+ expect(JSON.parse(fs.readFileSync(
+ path.join(root, '.cindy-system-skills.json'),
+ 'utf8',
+ ))).toEqual({ schemaVersion: 2, bundleVersion: 0, fingerprints: {} });
+ });
+
+ it('creates a durable empty manifest before publishing the first version', async () => {
+ const input = fixture();
+ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
+ const manifestPath = path.join(root, '.cindy-system-skills.json');
+ const originalRename = fs.renameSync.bind(fs);
+ let manifestWrites = 0;
+ const rename = vi.spyOn(fs, 'renameSync').mockImplementation((source, destination) => {
+ if (String(destination) === manifestPath && String(source).endsWith('.tmp')) {
+ manifestWrites += 1;
+ if (manifestWrites === 2) throw new Error('blocked first activation');
+ }
+ originalRename(source, destination);
+ });
+
+ const failed = await prepareBuiltInSkills(input);
+
+ expect(failed.changed).toBe(false);
+ expect(failed.warnings.join('\n')).toContain('blocked first activation');
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))).toEqual({
+ schemaVersion: 2,
+ bundleVersion: 0,
+ fingerprints: {},
+ });
+
+ rename.mockRestore();
+ const retried = await prepareBuiltInSkills(input);
+ expect(retried.changed).toBe(true);
+ expect(retried.warnings).toEqual([]);
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))).toMatchObject({
+ schemaVersion: 3,
+ bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION,
+ });
+ });
+
+ it('keeps a user-owned same-name Skill while retaining the Cindy copy', async () => {
+ const input = fixture();
+ const userSkill = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');
+ fs.mkdirSync(userSkill, { recursive: true });
+ fs.writeFileSync(path.join(userSkill, 'SKILL.md'), '# User copy\n');
+
+ const result = await prepareAndProjectBuiltInSkills(input);
+ 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),
+ );
+ expect(result.warnings.join('\n')).toContain('already owned by the user');
+ });
+
+ 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 nextUserDataDir = path.join(path.dirname(input.userDataDir), 'next-user-data');
+
+ const next = await prepareAndProjectBuiltInSkills({ ...input, userDataDir: nextUserDataDir });
+ const nextDescriptor = next.descriptors[0]!;
+
+ expect(next.warnings).toEqual([]);
+ expect(next.changed).toBe(true);
+ expect(nextDescriptor.absolutePath).toBe(sharedDescriptor.absolutePath);
+ expect(fs.realpathSync(link)).toBe(fs.realpathSync(sharedDescriptor.absolutePath));
+ expect(fs.realpathSync(nextDescriptor.nativeClaudePath)).toBe(fs.realpathSync(link));
+ });
+
+ it('repairs a broken link left by an earlier Cindy profile', async () => {
+ 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');
+ fs.mkdirSync(path.dirname(link), { recursive: true });
+ fs.symlinkSync(oldTarget, link, process.platform === 'win32' ? 'junction' : 'dir');
+
+ const result = await prepareAndProjectBuiltInSkills(input);
+
+ expect(result.warnings).toEqual([]);
+ expect(fs.realpathSync(link)).toBe(fs.realpathSync(result.descriptors[0]!.absolutePath));
+ });
+
+ it('does not mutate shared Skill paths when the cross-process lease is unavailable', async () => {
+ const input = fixture();
+ const result = await prepareBuiltInSkills({
+ ...input,
+ withSharedMutation: async () => undefined,
+ });
+
+ expect(result.changed).toBe(false);
+ expect(result.warnings.join('\n')).toContain('another Skill mutation is in progress');
+ expect(fs.existsSync(result.descriptors[0]!.absolutePath)).toBe(false);
+ expect(fs.existsSync(path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator'))).toBe(false);
+ });
+
+ it('does not activate app-owned bytes until home and Claude projections are ready', async () => {
+ const input = fixture();
+ const result = await prepareBuiltInSkills(input);
+
+ expect(fs.existsSync(result.descriptors[0]!.absolutePath)).toBe(true);
+ expect(fs.realpathSync(path.join(
+ input.homeDir,
+ '.agents',
+ 'skills',
+ 'cindy-skill-creator',
+ ))).toBe(fs.realpathSync(result.descriptors[0]!.absolutePath));
+ expect(fs.realpathSync(result.descriptors[0]!.nativeClaudePath)).toBe(
+ fs.realpathSync(result.descriptors[0]!.absolutePath),
+ );
+ });
+
+ it('waits a bounded interval for another profile to finish materialization', async () => {
+ const input = fixture();
+ let waitMs: number | undefined;
+ const result = await prepareBuiltInSkills({
+ ...input,
+ withSharedMutation: async (_names, operation, options) => {
+ waitMs = options?.waitMs;
+ return operation();
+ },
+ });
+
+ expect(waitMs).toBe(5_000);
+ expect(result.warnings).toEqual([]);
+ expect(fs.existsSync(result.descriptors[0]!.absolutePath)).toBe(true);
+ });
+
+ it('keeps a user-owned same-name symlink', async () => {
+ const input = fixture();
+ const userSource = path.join(path.dirname(input.homeDir), 'user-skill');
+ const userSkill = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');
+ fs.mkdirSync(userSource, { recursive: true });
+ fs.mkdirSync(path.dirname(userSkill), { recursive: true });
+ fs.writeFileSync(path.join(userSource, 'SKILL.md'), '# User symlink copy\n');
+ fs.symlinkSync(userSource, userSkill, process.platform === 'win32' ? 'junction' : 'dir');
+
+ const result = await prepareAndProjectBuiltInSkills(input);
+
+ expect(fs.realpathSync(userSkill)).toBe(fs.realpathSync(userSource));
+ expect(result.warnings.join('\n')).toContain('already owned by the user');
+ });
+
+ it('keeps a user-owned Skill in the isolated Claude config directory', async () => {
+ const input = fixture();
+ const descriptor = builtInSkillDescriptors(input.userDataDir, input.appDataDir)[0]!;
+ fs.mkdirSync(descriptor.nativeClaudePath, { recursive: true });
+ fs.writeFileSync(path.join(descriptor.nativeClaudePath, 'SKILL.md'), '# Claude user copy\n');
+
+ const result = await prepareAndProjectBuiltInSkills(input);
+ expect(fs.readFileSync(path.join(descriptor.nativeClaudePath, 'SKILL.md'), 'utf8')).toBe(
+ '# Claude user copy\n',
+ );
+ expect(result.warnings.join('\n')).toContain('already owned by the user');
+ });
+
+ it('refreshes the isolated Claude runtime when the palette winner changes', async () => {
+ const input = fixture();
+ const first = await prepareAndProjectBuiltInSkills(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,
+ });
+
+ expect(updated.warnings).toEqual([]);
+ expect(fs.realpathSync(sharedSkill)).toBe(fs.realpathSync(descriptor.absolutePath));
+ expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(
+ fs.realpathSync(claudePaletteSkill),
+ );
+
+ fs.rmSync(claudePaletteSkill, { recursive: true, force: true });
+ const restored = await refreshBuiltInClaudeSkillLinks({
+ ...input,
+ descriptors: first.descriptors,
+ });
+
+ expect(restored.warnings).toEqual([]);
+ expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(fs.realpathSync(sharedSkill));
+ });
+
+ it('attests only commands backed by the materialized Cindy copy', async () => {
+ const input = fixture();
+ const { descriptors } = await prepareBuiltInSkills(input);
+ const bundledSkill = path.join(descriptors[0]!.absolutePath, 'SKILL.md');
+ const userCopy = path.join(input.homeDir, 'user-copy', 'SKILL.md');
+ fs.mkdirSync(path.dirname(userCopy), { recursive: true });
+ fs.writeFileSync(userCopy, '# User copy\n');
+
+ const [official, spoofed] = markCindyBuiltInAgentSkills([
+ {
+ kind: 'agent-skill', name: 'cindy-skill-creator', source: 'skill',
+ path: bundledSkill, scope: 'user', enabled: true,
+ },
+ {
+ kind: 'agent-skill', name: 'cindy-skill-creator', source: 'skill',
+ description: 'Create or update a Cindy Skill', path: userCopy,
+ scope: 'user', enabled: true, builtIn: true,
+ },
+ ], descriptors);
+
+ expect(official?.builtIn).toBe(true);
+ expect(spoofed?.builtIn).toBeUndefined();
+ });
+
+ it('removes disabled Cindy built-ins from the Agent roster without hiding user collisions', async () => {
+ const input = fixture();
+ const { descriptors } = await prepareBuiltInSkills(input);
+ const descriptor = descriptors[0]!;
+ const userCopy = path.join(input.homeDir, 'user-copy', 'SKILL.md');
+ fs.mkdirSync(path.dirname(userCopy), { recursive: true });
+ fs.writeFileSync(userCopy, '# User copy\n');
+
+ const skills = activeCindyBuiltInAgentSkills([
+ {
+ kind: 'agent-skill', name: descriptor.name, source: 'skill',
+ path: path.join(descriptor.absolutePath, 'SKILL.md'), scope: 'user', enabled: true,
+ },
+ {
+ kind: 'agent-skill', name: descriptor.name, source: 'skill',
+ path: userCopy, scope: 'user', enabled: true,
+ },
+ ], descriptors, (source) => source !== descriptor.absolutePath);
+
+ expect(skills).toHaveLength(1);
+ expect(skills[0]?.path).toBe(userCopy);
+ expect(skills[0]?.builtIn).toBeUndefined();
+ });
+
+ it('resolves source and packaged resource roots', () => {
+ expect(
+ resolveBundledSystemSkillsRoot({
+ isPackaged: false,
+ appPath: '/repo/apps/desktop',
+ resourcesPath: '/app/resources',
+ }),
+ ).toBe(path.join('/repo/apps/desktop', 'resources', 'system-skills'));
+ expect(
+ resolveBundledSystemSkillsRoot({
+ isPackaged: true,
+ appPath: '/repo/apps/desktop',
+ resourcesPath: '/app/resources',
+ }),
+ ).toBe(path.join('/app/resources', 'system-skills'));
+ });
+});
diff --cc apps/desktop/src/main/maker-host/auth-adapters.ts
index 4514e56419,202f95b92a..7e6b89b770
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@@ -604,42 -599,11 +604,42 @@@ export class DesktopClaudeAuthAdapter i
private async runEnsureSharedGlobalSkills(): Promise<void> {
try {
const ownerId = getActiveAppSession().dataOwnerId;
- const result = await withSharedGlobalSkillProjectionMutation(ownerId, () =>
- prepareSharedGlobalSkillLinks({
+ const result = await withSharedGlobalSkillProjectionMutation(ownerId, async () => {
- // Bundle publication projects every managed Agent link before it
- // advances the active manifest. The stable-owner boundary prevents a
- // passive profile from participating in that transaction.
++ // Bundle publication keeps every managed Agent link on one stable
++ // active pointer. The stable-owner boundary prevents a passive profile
++ // from participating in that transaction.
+ const preparedBuiltIns = await prepareBuiltInSkills({
+ bundledRoot: resolveBundledSystemSkillsRoot({
+ isPackaged: app.isPackaged,
+ appPath: app.getAppPath(),
+ resourcesPath: process.resourcesPath,
+ }),
+ 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 manifest. Reconcile once more after the generic
++ // 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,
+ ...sharedProjection.warnings,
+ ...claudePaletteProjection.warnings,
+ ],
+ };
+ });
for (const warning of result.warnings) {
assetPrepLog.warn('shared global skill warning', { warning });
}
diff --cc apps/desktop/src/main/maker-host/built-in-skills.ts
index 4861014e28,0000000000..de78fe859f
mode 100644,000000..100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@@ -1,1021 -1,0 +1,1217 @@@
+import { createHash, randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import { promises as fsp } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import type { AgentSkillCommand } from '@cindy/maker-core';
+import {
+ CINDY_LEARN_NAME,
+ CINDY_SKILL_CREATOR_NAME,
+} from '../../shared/cindyBuiltInSkills';
+import { withSkillMutation } from '../skillhub/sharedMutationLease';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';
+
+export const BUILT_IN_SKILL_CREATOR_NAME = CINDY_SKILL_CREATOR_NAME;
+export const BUILT_IN_LEARN_SKILL_NAME = CINDY_LEARN_NAME;
+
+const BUILT_IN_SKILL_NAMES = [BUILT_IN_SKILL_CREATOR_NAME, BUILT_IN_LEARN_SKILL_NAME] as const;
+const MANIFEST_FILE = '.cindy-system-skills.json';
+const VERSIONS_DIRECTORY = '.versions';
++const ACTIVE_BUNDLE_LINK = '.active';
+const BUILT_IN_SKILL_MUTATION_WAIT_MS = 5_000;
+/** Increment whenever shipped built-in Skill bytes change between releases. */
+export const BUILT_IN_SKILLS_BUNDLE_VERSION = 10;
+
+export interface BuiltInSkillDescriptor {
+ name: string;
+ absolutePath: string;
+ nativeClaudePath: string;
+}
+
+export interface PrepareBuiltInSkillsOptions {
+ bundledRoot: string;
+ userDataDir: string;
+ appDataDir?: string;
+ homeDir?: string;
+ bundleVersion?: number;
+ withSharedMutation?: typeof withSkillMutation;
+}
+
+export interface PrepareBuiltInSkillsResult {
+ descriptors: BuiltInSkillDescriptor[];
+ /** True only when every descriptor is backed by the active manifest's recorded bytes. */
+ projectionSafe: boolean;
+ changed: boolean;
+ warnings: string[];
+}
+
+export interface RefreshBuiltInClaudeSkillLinksOptions {
+ userDataDir: string;
+ appDataDir?: string;
+ homeDir?: string;
+ descriptors?: readonly BuiltInSkillDescriptor[];
+ withSharedMutation?: typeof withSkillMutation;
+}
+
+export interface RefreshBuiltInSharedSkillLinksOptions {
+ userDataDir: string;
+ appDataDir?: string;
+ homeDir?: string;
+ descriptors?: readonly BuiltInSkillDescriptor[];
+ withSharedMutation?: typeof withSkillMutation;
+}
+
+export interface RefreshBuiltInClaudeSkillLinksResult {
+ changed: boolean;
+ /** False only when a Cindy-managed projection could not be made usable. */
+ complete: boolean;
+ warnings: string[];
+}
+
+export type RefreshBuiltInSharedSkillLinksResult = RefreshBuiltInClaudeSkillLinksResult;
+
+interface MaterializationManifest {
+ schemaVersion: 2 | 3;
+ bundleVersion: number;
+ fingerprints: Record<string, string>;
+ activeBundle?: string;
+}
+
+interface PublishedMaterializationManifest extends MaterializationManifest {
+ schemaVersion: 3;
+ activeBundle: string;
+}
+
+export function resolveBundledSystemSkillsRoot(input: {
+ isPackaged: boolean;
+ appPath: string;
+ resourcesPath: string;
+}): string {
+ return input.isPackaged
+ ? path.join(input.resourcesPath, 'system-skills')
+ : path.join(input.appPath, 'resources', 'system-skills');
+}
+
+export function builtInSkillsRoot(userDataDir: string): string {
+ return path.join(userDataDir, 'system-skills');
+}
+
+/** Profile-independent storage shared by Global, China, dev, and isolated profiles. */
+export function sharedBuiltInSkillsRoot(appDataDir: string): string {
+ return path.join(appDataDir, 'Cindy', 'shared-system-skills');
+}
+
+export function builtInSkillDescriptors(
+ userDataDir: string,
+ appDataDir?: string,
+): BuiltInSkillDescriptor[] {
+ const root = appDataDir
+ ? sharedBuiltInSkillsRoot(appDataDir)
+ : builtInSkillsRoot(userDataDir);
+ const activeRoot = activeBuiltInSkillsRoot(root);
+ return builtInSkillDescriptorsAtRoot(activeRoot, userDataDir);
+}
+
+function builtInSkillDescriptorsAtRoot(
+ root: string,
+ userDataDir: string,
+): BuiltInSkillDescriptor[] {
+ return BUILT_IN_SKILL_NAMES.map((name) => ({
+ name,
+ absolutePath: path.join(root, name),
+ nativeClaudePath: path.join(userDataDir, 'claude-home', 'skills', name),
+ }));
+}
+
++function stableBuiltInSkillDescriptors(
++ root: string,
++ userDataDir: string,
++): BuiltInSkillDescriptor[] {
++ return builtInSkillDescriptorsAtRoot(path.join(root, ACTIVE_BUNDLE_LINK), userDataDir);
++}
++
+function validActiveBundle(value: unknown): value is string {
+ return typeof value === 'string'
+ && /^v[1-9][0-9]*-[a-f0-9]{16}-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
+}
+
+/** Keep enable/disable intent stable while immutable built-in bundle revisions change. */
+export function canonicalBuiltInSkillActivationPath(
+ source: string,
+ userDataDir: string,
+ appDataDir?: string,
+): string {
+ const name = path.basename(source);
+ if (!(BUILT_IN_SKILL_NAMES as readonly string[]).includes(name)) return source;
+ const bundleRoot = path.dirname(source);
++ const managedRoots = [
++ builtInSkillsRoot(userDataDir),
++ ...(appDataDir ? [sharedBuiltInSkillsRoot(appDataDir)] : []),
++ ];
++ if (
++ path.basename(bundleRoot) === ACTIVE_BUNDLE_LINK
++ && managedRoots.some((root) => realPathOrNormalized(path.dirname(bundleRoot)) === realPathOrNormalized(root))
++ ) {
++ return path.join(path.dirname(bundleRoot), name);
++ }
+ const versionsRoot = path.dirname(bundleRoot);
+ const stableRoot = path.dirname(versionsRoot);
+ if (
+ path.basename(versionsRoot) !== VERSIONS_DIRECTORY ||
+ !validActiveBundle(path.basename(bundleRoot)) ||
- ![
- builtInSkillsRoot(userDataDir),
- ...(appDataDir ? [sharedBuiltInSkillsRoot(appDataDir)] : []),
- ].some((root) => realPathOrNormalized(stableRoot) === realPathOrNormalized(root))
++ !managedRoots.some((root) => realPathOrNormalized(stableRoot) === realPathOrNormalized(root))
+ ) return source;
+ return path.join(stableRoot, name);
+}
+
+function parseManifest(raw: string): MaterializationManifest | null {
+ const parsed = JSON.parse(raw) as Partial<MaterializationManifest>;
+ const commonShapeIsValid =
+ Number.isSafeInteger(parsed.bundleVersion) &&
+ (parsed.bundleVersion ?? 0) >= 0 &&
+ parsed.fingerprints &&
+ typeof parsed.fingerprints === 'object' &&
+ !Array.isArray(parsed.fingerprints) &&
+ Object.values(parsed.fingerprints).every((value) => typeof value === 'string');
+ if (!commonShapeIsValid) return null;
+ if (parsed.schemaVersion === 2) {
+ return {
+ schemaVersion: 2,
+ bundleVersion: parsed.bundleVersion!,
+ fingerprints: parsed.fingerprints!,
+ };
+ }
+ if (parsed.schemaVersion === 3 && validActiveBundle(parsed.activeBundle)) {
+ return {
+ schemaVersion: 3,
+ bundleVersion: parsed.bundleVersion!,
+ fingerprints: parsed.fingerprints!,
+ activeBundle: parsed.activeBundle,
+ };
+ }
+ return null;
+}
+
+function activeBuiltInSkillsRoot(root: string): string {
++ const active = path.join(root, ACTIVE_BUNDLE_LINK);
++ if (fs.existsSync(active)) return active;
+ try {
+ const raw = readAtomicFileSync(path.join(root, MANIFEST_FILE));
- if (raw === null) return root;
++ if (raw === null) return active;
+ const manifest = parseManifest(raw);
- return manifest?.schemaVersion === 3
- ? path.join(root, VERSIONS_DIRECTORY, manifest.activeBundle!)
- : root;
++ // Schema 2 stored bytes directly below root. Keep that legacy view only
++ // until preparation migrates it to the stable active indirection.
++ return manifest?.schemaVersion === 2 && !isEmptyManifest(manifest) ? root : active;
+ } catch {
- // Preparation reports corrupt/unreadable manifests. Other readers retain
- // the legacy path and never guess an unpublished version directory.
- return root;
++ // Preparation reports corrupt/unreadable manifests. Other readers use the
++ // stable link and never guess an immutable version directory.
++ return active;
+ }
+}
+
+async function hashDirectory(root: string): Promise<string> {
+ const hash = createHash('sha256');
+ const visit = async (directory: string): Promise<void> => {
+ const entries = await fsp.readdir(directory, { withFileTypes: true });
+ entries.sort((a, b) => a.name.localeCompare(b.name));
+ for (const entry of entries) {
+ const absolute = path.join(directory, entry.name);
+ const relative = path.relative(root, absolute).split(path.sep).join('/');
+ hash.update(entry.isDirectory() ? `d\0${relative}\0` : `f\0${relative}\0`);
+ if (entry.isDirectory()) await visit(absolute);
+ else if (entry.isFile()) hash.update(await fsp.readFile(absolute));
+ else throw new Error(`unsupported bundled Skill entry: ${relative}`);
+ }
+ };
+ await visit(root);
+ return hash.digest('hex');
+}
+
+function emptyManifest(): MaterializationManifest {
+ return { schemaVersion: 2, bundleVersion: 0, fingerprints: {} };
+}
+
+function isEmptyManifest(manifest: MaterializationManifest): boolean {
+ return manifest.schemaVersion === 2
+ && manifest.bundleVersion === 0
+ && Object.keys(manifest.fingerprints).length === 0;
+}
+
+async function hasExistingMaterializedSkill(root: string): Promise<boolean> {
+ for (const name of BUILT_IN_SKILL_NAMES) {
+ try {
+ await fsp.lstat(path.join(root, name));
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
++ try {
++ await fsp.lstat(path.join(root, ACTIVE_BUNDLE_LINK));
++ return true;
++ } catch (error) {
++ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
++ }
+ try {
+ const versions = await fsp.readdir(path.join(root, VERSIONS_DIRECTORY));
+ if (versions.length > 0) return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ return false;
+}
+
+async function readManifest(root: string): Promise<MaterializationManifest> {
+ const manifestPath = path.join(root, MANIFEST_FILE);
+ let raw: string | null;
+ try {
+ raw = readAtomicFileSync(manifestPath);
+ } catch (error) {
+ throw new Error(
+ `could not read built-in Skill manifest without risking a downgrade: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+ if (raw === null) {
+ if (await hasExistingMaterializedSkill(root)) {
+ throw new Error('built-in Skill manifest is missing while materialized Skills still exist');
+ }
+ return emptyManifest();
+ }
+
+ const hasInstalledSkills = await hasExistingMaterializedSkill(root);
+
+ try {
+ const parsed = parseManifest(raw);
+ if (parsed) return parsed;
+ } catch (error) {
+ if (hasInstalledSkills) {
+ throw new Error(
+ `built-in Skill manifest is invalid while materialized Skills still exist: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+ return emptyManifest();
+ }
+ if (hasInstalledSkills) {
+ throw new Error(
+ 'built-in Skill manifest has an invalid shape while materialized Skills still exist',
+ );
+ }
+ return emptyManifest();
+}
+
+async function writeManifest(root: string, manifest: MaterializationManifest): Promise<void> {
+ const destination = path.join(root, MANIFEST_FILE);
+ atomicWriteFileSync(destination, `${JSON.stringify(manifest, null, 2)}\n`);
+}
+
+async function materializeSkill(
+ source: string,
+ destination: string,
+ expectedFingerprint: string,
+): Promise<boolean> {
+ const skillFile = path.join(source, 'SKILL.md');
+ if (!(await fsp.stat(skillFile).catch(() => null))?.isFile()) {
+ throw new Error(`bundled Skill is missing SKILL.md: ${source}`);
+ }
+
+ const root = path.dirname(destination);
+ const stage = path.join(root, `.${path.basename(destination)}.stage-${randomUUID()}`);
+ const backup = path.join(root, `.${path.basename(destination)}.backup-${randomUUID()}`);
+ await fsp.cp(source, stage, { recursive: true, force: true, errorOnExist: false });
+ const stagedFingerprint = await hashDirectory(stage).catch(() => null);
+ if (stagedFingerprint !== expectedFingerprint) {
+ await fsp.rm(stage, { recursive: true, force: true });
+ throw new Error(`staged Skill fingerprint mismatch: ${path.basename(destination)}`);
+ }
+ let movedExisting = false;
+ try {
+ if (fs.existsSync(destination)) {
+ await fsp.rename(destination, backup);
+ movedExisting = true;
+ }
+ await fsp.rename(stage, destination);
+ } catch (error) {
+ await fsp.rm(stage, { recursive: true, force: true }).catch(() => undefined);
+ if (movedExisting && !fs.existsSync(destination)) {
+ await fsp.rename(backup, destination).catch(() => undefined);
+ }
+ throw error;
+ }
+ if (movedExisting) await fsp.rm(backup, { recursive: true, force: true });
+ return true;
+}
+
+function materializedBundleName(
+ bundleVersion: number,
+ fingerprints: Readonly<Record<string, string>>,
+): string {
+ const digest = createHash('sha256');
+ for (const name of [...BUILT_IN_SKILL_NAMES].sort()) {
+ digest.update(name).update('\0').update(fingerprints[name] ?? '').update('\0');
+ }
+ return `v${bundleVersion}-${digest.digest('hex').slice(0, 16)}-${randomUUID()}`;
+}
+
+async function ensureSkillEntry(
+ descriptor: BuiltInSkillDescriptor,
+ linkPath: string,
+ replaceStaleCindyLink = false,
+ legacyUserDataDir?: string,
+ appDataDir?: string,
+ desiredTarget = descriptor.absolutePath,
+ additionalManagedTargets: readonly string[] = [],
+): Promise<{ changed: boolean; warning?: string; targetPath?: string }> {
+ await fsp.mkdir(path.dirname(linkPath), { recursive: true });
+
+ let currentTarget: string | undefined;
+ try {
+ const current = await fsp.realpath(linkPath);
+ currentTarget = current;
+ const expected = await fsp.realpath(desiredTarget);
- if (samePath(current, expected)) return { changed: false };
++ if (samePath(current, expected)) {
++ if (!replaceStaleCindyLink) return { changed: false };
++ const rawTarget = await fsp.readlink(linkPath).catch(() => null);
++ if (rawTarget === null) return { changed: false };
++ const lexicalTarget = path.isAbsolute(rawTarget)
++ ? rawTarget
++ : path.resolve(path.dirname(linkPath), rawTarget);
++ // A direct immutable-version link can resolve to the same bytes as the
++ // stable active link. Still migrate its lexical target so future bundle
++ // changes have one publication point.
++ if (samePath(lexicalTarget, desiredTarget)) return { changed: false };
++ }
+ } catch {
+ // Inspect the lexical entry below; a missing entry may be created.
+ }
+
+ try {
+ const stat = await fsp.lstat(linkPath);
+ if (
+ replaceStaleCindyLink &&
+ stat.isSymbolicLink() &&
+ await isCindyManagedSystemSkillTarget(
+ linkPath,
+ descriptor,
+ legacyUserDataDir,
+ appDataDir,
+ additionalManagedTargets,
+ )
+ ) {
+ const replacement = `${linkPath}.next-${randomUUID()}`;
+ const backup = `${linkPath}.previous-${randomUUID()}`;
+ await fsp.symlink(
+ desiredTarget,
+ replacement,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ let movedExisting = false;
+ try {
+ await fsp.rename(linkPath, backup);
+ movedExisting = true;
+ await fsp.rename(replacement, linkPath);
+ } catch (error) {
+ await fsp.rm(replacement, { force: true }).catch(() => undefined);
+ if (movedExisting && !fs.existsSync(linkPath)) {
+ await fsp.rename(backup, linkPath).catch(() => undefined);
+ }
+ throw error;
+ }
+ await fsp.rm(backup, { force: true });
+ return { changed: true, targetPath: desiredTarget };
+ }
+ return {
+ changed: false,
+ warning: `built-in Skill ${descriptor.name} was not linked because ${linkPath} is already owned by the user`,
+ ...(currentTarget ? { targetPath: currentTarget } : {}),
+ };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+
+ await fsp.symlink(
+ desiredTarget,
+ linkPath,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ return { changed: true, targetPath: desiredTarget };
+}
+
+async function isCindyManagedSystemSkillTarget(
+ linkPath: string,
+ descriptor: BuiltInSkillDescriptor,
+ legacyUserDataDir?: string,
+ appDataDir?: string,
+ additionalManagedTargets: readonly string[] = [],
+): Promise<boolean> {
+ try {
+ const rawTarget = await fsp.readlink(linkPath);
+ const target = path.isAbsolute(rawTarget)
+ ? rawTarget
+ : path.resolve(path.dirname(linkPath), rawTarget);
+ if (samePath(target, descriptor.absolutePath)) return true;
+ if (additionalManagedTargets.some((managedTarget) => samePath(target, managedTarget))) {
+ return true;
+ }
+ const managedRoots = [
+ ...(legacyUserDataDir ? [builtInSkillsRoot(legacyUserDataDir)] : []),
+ ...(appDataDir ? [sharedBuiltInSkillsRoot(appDataDir)] : []),
+ ];
+ for (const root of managedRoots) {
+ if (samePath(target, path.join(root, descriptor.name))) return true;
- const relative = path.relative(path.join(root, VERSIONS_DIRECTORY), target);
++ if (samePath(target, path.join(root, ACTIVE_BUNDLE_LINK, descriptor.name))) return true;
++ const relative = path.relative(
++ realPathOrNormalized(path.join(root, VERSIONS_DIRECTORY)),
++ realPathOrNormalized(target),
++ );
+ const segments = relative.split(path.sep);
+ if (
+ segments.length === 2 &&
+ validActiveBundle(segments[0]) &&
+ segments[1] === descriptor.name
+ ) return true;
+ }
+
+ const targetRoot = path.dirname(target);
+ if (
+ path.basename(target) !== descriptor.name ||
+ path.basename(targetRoot) !== 'system-skills'
+ ) {
+ return false;
+ }
+
+ // Migrate links created by the first implementation even after their old
+ // profile directory was deleted. The exact appData child + Cindy profile
+ // shape is deliberately narrower than an arbitrary `system-skills` link.
+ if (appDataDir) {
+ const profileDir = path.dirname(targetRoot);
+ const profileName = path.basename(profileDir);
+ if (
+ samePath(path.dirname(profileDir), appDataDir) &&
+ /^Cindy(?:Global|Dev)?(?:[-.][A-Za-z0-9._-]+)?$/.test(profileName)
+ ) return true;
+ }
+
+ return false;
+ } catch {
+ return false;
+ }
+}
+
+function normalizeForCompare(value: string): string {
+ const withoutWindowsNamespace = process.platform === 'win32'
+ ? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')
+ : value;
+ const resolved = path.resolve(withoutWindowsNamespace);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
+function samePath(left: string, right: string): boolean {
+ return normalizeForCompare(left) === normalizeForCompare(right);
+}
+
++function activeBundleTarget(root: string, bundle: string): string {
++ return path.join(root, VERSIONS_DIRECTORY, bundle);
++}
++
++async function readActiveBundle(root: string): Promise<string | null> {
++ const activePath = path.join(root, ACTIVE_BUNDLE_LINK);
++ let stat: fs.Stats;
++ try {
++ stat = await fsp.lstat(activePath);
++ } catch (error) {
++ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
++ throw error;
++ }
++ if (!stat.isSymbolicLink()) {
++ throw new Error(`built-in Skill active pointer is not a link: ${activePath}`);
++ }
++ const rawTarget = await fsp.readlink(activePath);
++ const target = path.isAbsolute(rawTarget)
++ ? rawTarget
++ : path.resolve(root, rawTarget);
++ const relative = path.relative(
++ realPathOrNormalized(path.join(root, VERSIONS_DIRECTORY)),
++ realPathOrNormalized(target),
++ );
++ const segments = relative.split(path.sep);
++ if (segments.length !== 1 || !validActiveBundle(segments[0])) {
++ throw new Error(`built-in Skill active pointer has an invalid target: ${target}`);
++ }
++ return segments[0];
++}
++
++async function switchActiveBundle(root: string, bundle: string): Promise<boolean> {
++ const target = activeBundleTarget(root, bundle);
++ if (!(await fsp.stat(target).catch(() => null))?.isDirectory()) {
++ throw new Error(`built-in Skill bundle is unavailable: ${target}`);
++ }
++ if (await readActiveBundle(root) === bundle) return false;
++
++ const activePath = path.join(root, ACTIVE_BUNDLE_LINK);
++ const replacement = `${activePath}.next-${randomUUID()}`;
++ const backup = `${activePath}.previous-${randomUUID()}`;
++ await fsp.symlink(target, replacement, process.platform === 'win32' ? 'junction' : 'dir');
++ try {
++ // POSIX replaces a symlink atomically. Windows may reject replacing an
++ // existing directory junction, in which case the fallback still changes
++ // every Agent through this one pointer rather than one projection at a time.
++ await fsp.rename(replacement, activePath);
++ } catch (firstError) {
++ const activeEntryExists = await fsp.lstat(activePath).then(() => true).catch(() => false);
++ if (!activeEntryExists) {
++ await fsp.rm(replacement, { force: true }).catch(() => undefined);
++ throw firstError;
++ }
++ let movedExisting = false;
++ try {
++ await fsp.rename(activePath, backup);
++ movedExisting = true;
++ await fsp.rename(replacement, activePath);
++ } catch (error) {
++ await fsp.rm(replacement, { force: true }).catch(() => undefined);
++ const activeEntryExistsAfterFailure = await fsp.lstat(activePath)
++ .then(() => true)
++ .catch(() => false);
++ if (movedExisting && !activeEntryExistsAfterFailure) {
++ await fsp.rename(backup, activePath).catch(() => undefined);
++ }
++ throw error;
++ }
++ await fsp.rm(backup, { force: true }).catch(() => undefined);
++ }
++ return true;
++}
++
++async function removeActiveBundlePointer(root: string): Promise<boolean> {
++ const activePath = path.join(root, ACTIVE_BUNDLE_LINK);
++ const activeBundle = await readActiveBundle(root);
++ if (activeBundle === null) return false;
++ await fsp.unlink(activePath);
++ return true;
++}
++
+async function ensureSharedEntry(
+ descriptor: BuiltInSkillDescriptor,
+ homeDir: string,
+ legacyUserDataDir: string,
+ appDataDir?: string,
+): Promise<{ changed: boolean; warning?: string; targetPath?: string }> {
+ return ensureSkillEntry(
+ descriptor,
+ path.join(homeDir, '.agents', 'skills', descriptor.name),
+ true,
+ legacyUserDataDir,
+ appDataDir,
+ );
+}
+
+async function refreshBuiltInSharedSkillLinksUnlocked(
+ options: Omit<RefreshBuiltInSharedSkillLinksOptions, 'withSharedMutation'>,
+): 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;
+
+ for (const descriptor of descriptors) {
+ try {
+ const linked = await ensureSharedEntry(
+ descriptor,
+ homeDir,
+ options.userDataDir,
+ options.appDataDir,
+ );
+ changed = linked.changed || changed;
+ if (linked.warning) warnings.push(linked.warning);
+ } catch (error) {
+ complete = false;
+ warnings.push(
+ `could not expose built-in Skill ${descriptor.name}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+
+ return { changed, complete, warnings };
+}
+
+/** Refresh the home-level shared projection. Call only inside the stable owner boundary. */
+export async function refreshBuiltInSharedSkillLinks(
+ options: RefreshBuiltInSharedSkillLinksOptions,
+): Promise<RefreshBuiltInSharedSkillLinksResult> {
+ const descriptors = options.descriptors
+ ?? builtInSkillDescriptors(options.userDataDir, options.appDataDir);
+ const mutate = options.withSharedMutation ?? withSkillMutation;
+ const refreshed = await mutate(
+ descriptors.map((descriptor) => descriptor.name),
+ () => refreshBuiltInSharedSkillLinksUnlocked({ ...options, descriptors }),
+ { waitMs: BUILT_IN_SKILL_MUTATION_WAIT_MS },
+ );
+ return refreshed ?? {
+ changed: false,
+ complete: false,
+ warnings: ['could not expose built-in Skills because another Skill mutation is in progress'],
+ };
+}
+
+function realPathOrNormalized(value: string): string {
+ try { return normalizeForCompare(fs.realpathSync.native(value)); }
+ 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;
+}
+
+/** Main-owned attestation used by the renderer; names and descriptions are not trusted. */
+export function markCindyBuiltInAgentSkills(
+ skills: readonly AgentSkillCommand[],
+ descriptors: readonly BuiltInSkillDescriptor[],
+): AgentSkillCommand[] {
+ const trustedSkillFiles = new Map(descriptors.map((descriptor) => [
+ descriptor.name,
+ realPathOrNormalized(path.join(descriptor.absolutePath, 'SKILL.md')),
+ ]));
+ return skills.map((skill) => {
+ const trustedPath = trustedSkillFiles.get(skill.name);
+ const builtIn = Boolean(skill.path && trustedPath && realPathOrNormalized(skill.path) === trustedPath);
+ if (builtIn) return { ...skill, builtIn: true };
+ if (skill.builtIn === undefined) return skill;
+ const rest = { ...skill };
+ delete rest.builtIn;
+ return rest;
+ });
+}
+
+/** Mark trusted Cindy entries, then apply the live activation override to those entries only. */
+export function activeCindyBuiltInAgentSkills(
+ skills: readonly AgentSkillCommand[],
+ descriptors: readonly BuiltInSkillDescriptor[],
+ isEnabled: (source: string) => boolean,
+): AgentSkillCommand[] {
+ 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);
+ return descriptor ? isEnabled(descriptor.absolutePath) : false;
+ });
+}
+
+async function refreshBuiltInClaudeSkillLinksUnlocked(
- options: Omit<RefreshBuiltInClaudeSkillLinksOptions, 'withSharedMutation'>,
++ options: Omit<RefreshBuiltInClaudeSkillLinksOptions, 'withSharedMutation'> & {
++ allowUnresolvedManagedSharedTarget?: boolean;
++ },
+): 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 claudeRuntimeTarget = await hasSkillFile(claudePalettePath)
- ? claudePalettePath
- : sharedPath;
- if (!(await hasSkillFile(claudeRuntimeTarget))) {
++ 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],
+ );
+ changed = linked.changed || changed;
+ if (linked.warning) 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)}`,
+ );
+ }
+ }
+
+ return { changed, complete, warnings };
+}
+
+/** Keep Cindy's isolated Claude runtime pointed at the latest shared/palette winner. */
+export async function refreshBuiltInClaudeSkillLinks(
+ options: RefreshBuiltInClaudeSkillLinksOptions,
+): Promise<RefreshBuiltInClaudeSkillLinksResult> {
+ const descriptors = options.descriptors
+ ?? builtInSkillDescriptors(options.userDataDir, options.appDataDir);
+ const mutate = options.withSharedMutation ?? withSkillMutation;
+ const refreshed = await mutate(
+ descriptors.map((descriptor) => descriptor.name),
+ () => refreshBuiltInClaudeSkillLinksUnlocked({ ...options, descriptors }),
+ { waitMs: BUILT_IN_SKILL_MUTATION_WAIT_MS },
+ );
+ return refreshed ?? {
+ changed: false,
+ complete: false,
+ warnings: ['could not refresh built-in Claude Skills because another Skill mutation is in progress'],
+ };
+}
+
+interface BuiltInProjectionSnapshot {
+ path: string;
+ kind: 'missing' | 'symlink' | 'other';
+ target?: string;
+}
+
+function builtInProjectionPaths(
+ descriptors: readonly BuiltInSkillDescriptor[],
+ homeDir: string,
+): string[] {
+ return [...new Set(descriptors.flatMap((descriptor) => [
+ descriptor.nativeClaudePath,
+ path.join(homeDir, '.agents', 'skills', descriptor.name),
+ ]))];
+}
+
+async function captureBuiltInProjectionState(
+ descriptors: readonly BuiltInSkillDescriptor[],
+ homeDir: string,
+): Promise<BuiltInProjectionSnapshot[]> {
+ const snapshots: BuiltInProjectionSnapshot[] = [];
+ for (const entryPath of builtInProjectionPaths(descriptors, homeDir)) {
+ try {
+ const stat = await fsp.lstat(entryPath);
+ if (stat.isSymbolicLink()) {
+ snapshots.push({ path: entryPath, kind: 'symlink', target: await fsp.readlink(entryPath) });
+ } else {
+ snapshots.push({ path: entryPath, kind: 'other' });
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ snapshots.push({ path: entryPath, kind: 'missing' });
+ }
+ }
+ return snapshots;
+}
+
+async function restoreBuiltInProjectionState(
+ snapshots: readonly BuiltInProjectionSnapshot[],
+): Promise<{ complete: boolean; warnings: string[] }> {
+ const warnings: string[] = [];
+ let complete = true;
+ for (const snapshot of snapshots) {
+ try {
+ const current = await fsp.lstat(snapshot.path).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (snapshot.kind === 'other') {
+ if (!current || current.isSymbolicLink()) {
+ throw new Error('a user-owned projection entry changed during activation');
+ }
+ continue;
+ }
+ if (current && !current.isSymbolicLink()) {
+ throw new Error('a user-owned projection entry appeared during activation');
+ }
+ if (current) await fsp.unlink(snapshot.path);
+ if (snapshot.kind === 'symlink') {
+ await fsp.mkdir(path.dirname(snapshot.path), { recursive: true });
+ await fsp.symlink(
+ snapshot.target!,
+ snapshot.path,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ }
+ } catch (error) {
+ complete = false;
+ warnings.push(
+ `could not restore built-in Skill projection ${snapshot.path}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+ return { complete, warnings };
+}
+
+async function removeInactiveBuiltInProjections(
+ root: string,
+ descriptors: readonly BuiltInSkillDescriptor[],
+ homeDir: string,
+ allowedDescriptors: readonly BuiltInSkillDescriptor[],
+): Promise<{ complete: boolean; warnings: string[] }> {
+ const versionsRoot = realPathOrNormalized(path.join(root, VERSIONS_DIRECTORY));
++ const activeRoot = normalizeForCompare(path.join(root, ACTIVE_BUNDLE_LINK));
+ const allowedRoots = allowedDescriptors.map((descriptor) => (
+ realPathOrNormalized(descriptor.absolutePath)
+ ));
+ const sharedPaths = new Set(descriptors.map((descriptor) => normalizeForCompare(
+ path.join(homeDir, '.agents', 'skills', descriptor.name),
+ )));
+ const warnings: string[] = [];
+ let complete = true;
+ // Native Claude links can resolve through the shared links, so inspect and
+ // remove them first while the full stale chain is still readable.
+ for (const entryPath of builtInProjectionPaths(descriptors, homeDir)) {
+ try {
+ const stat = await fsp.lstat(entryPath);
+ if (!stat.isSymbolicLink()) continue;
+ const rawTarget = await fsp.readlink(entryPath);
+ const lexicalTarget = normalizeForCompare(path.isAbsolute(rawTarget)
+ ? rawTarget
+ : path.resolve(path.dirname(entryPath), rawTarget));
+ let resolvedTarget = true;
+ const target = await fsp.realpath(entryPath)
+ .then(normalizeForCompare)
+ .catch(() => {
+ resolvedTarget = false;
+ return lexicalTarget;
+ });
+ const relative = path.relative(versionsRoot, target);
++ const activeRelative = path.relative(activeRoot, lexicalTarget);
++ const lexicallyPointsIntoActive = activeRelative !== ''
++ && activeRelative !== '..'
++ && !activeRelative.startsWith(`..${path.sep}`)
++ && !path.isAbsolute(activeRelative);
+ const pointsIntoAllowedBundle = allowedRoots.some((allowedRoot) => {
+ const allowedRelative = path.relative(allowedRoot, target);
+ return allowedRelative === '' || (
+ allowedRelative !== '..'
+ && !allowedRelative.startsWith(`..${path.sep}`)
+ && !path.isAbsolute(allowedRelative)
+ );
+ });
+ if (
+ (!resolvedTarget && sharedPaths.has(lexicalTarget))
++ || (allowedRoots.length === 0 && lexicallyPointsIntoActive)
+ || (
+ relative !== ''
+ && relative !== '..'
+ && !relative.startsWith(`..${path.sep}`)
+ && !path.isAbsolute(relative)
+ && !pointsIntoAllowedBundle
+ )
+ ) {
+ await fsp.unlink(entryPath);
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ complete = false;
+ warnings.push(
+ `could not remove inactive built-in Skill projection ${entryPath}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+ return { complete, warnings };
+}
+
+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,
+ });
+ const claude = await refreshBuiltInClaudeSkillLinksUnlocked({
+ userDataDir: options.userDataDir,
+ appDataDir: options.appDataDir,
+ homeDir,
+ descriptors,
++ allowUnresolvedManagedSharedTarget,
+ });
+ return {
+ changed: shared.changed || claude.changed,
+ complete: shared.complete && claude.complete,
+ warnings: [...shared.warnings, ...claude.warnings],
+ };
+}
+
+/**
- * Materialize Cindy-owned Skill bytes and make every managed Agent projection
- * usable before atomically advancing the active manifest. The immutable old
- * bundle remains available for rollback throughout the transaction.
++ * Materialize Cindy-owned Skill bytes, keep every managed Agent projection on
++ * the stable active path, then publish the whole bundle through one pointer.
++ * The immutable old bundle remains available throughout the transaction.
+ */
+export async function prepareBuiltInSkills(
+ options: PrepareBuiltInSkillsOptions,
+): Promise<PrepareBuiltInSkillsResult> {
+ const root = options.appDataDir
+ ? sharedBuiltInSkillsRoot(options.appDataDir)
+ : builtInSkillsRoot(options.userDataDir);
+ const warnings: string[] = [];
+ let changed = false;
+ let projectionSafe = false;
+ const bundleVersion = options.bundleVersion ?? BUILT_IN_SKILLS_BUNDLE_VERSION;
+ if (!Number.isSafeInteger(bundleVersion) || bundleVersion < 1) {
+ throw new Error(`invalid built-in Skill bundle version: ${bundleVersion}`);
+ }
+ const mutate = options.withSharedMutation ?? withSkillMutation;
+ const locked = await mutate(BUILT_IN_SKILL_NAMES, async () => {
+ await fsp.mkdir(root, { recursive: true });
+ const homeDir = options.homeDir ?? os.homedir();
- const descriptors = builtInSkillDescriptors(options.userDataDir, options.appDataDir);
++ const stableDescriptors = stableBuiltInSkillDescriptors(root, options.userDataDir);
++ let descriptors = builtInSkillDescriptors(options.userDataDir, options.appDataDir);
+ let manifest: MaterializationManifest;
+ try {
+ manifest = await readManifest(root);
+ if (isEmptyManifest(manifest)) {
+ // Establish a durable pre-publication pointer on first install. If the
+ // process exits after publishing version bytes but before activating
+ // them, the next launch can safely ignore that orphan and retry.
+ await writeManifest(root, manifest);
+ }
+ } catch (error) {
+ warnings.push(
+ `kept existing built-in Skills because their manifest is unavailable: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ return true;
+ }
+ if (isEmptyManifest(manifest)) {
++ try {
++ changed = await removeActiveBundlePointer(root) || changed;
++ } catch (error) {
++ warnings.push(
++ `kept the empty built-in Skill manifest because its active pointer could not be cleared: ${error instanceof Error ? error.message : String(error)}`,
++ );
++ return true;
++ }
++ descriptors = stableDescriptors;
+ const recovered = await removeInactiveBuiltInProjections(root, descriptors, homeDir, []);
+ warnings.push(...recovered.warnings);
+ if (!recovered.complete) {
+ warnings.push('kept the empty built-in Skill manifest because unpublished Agent projections could not be removed');
+ return true;
+ }
+ }
++ let committedBundleVerified = manifest.schemaVersion === 2;
++ if (manifest.schemaVersion === 3) {
++ const committedBundle = manifest.activeBundle!;
++ const committedDescriptors = builtInSkillDescriptorsAtRoot(
++ activeBundleTarget(root, committedBundle),
++ options.userDataDir,
++ );
++ committedBundleVerified = true;
++ for (const descriptor of committedDescriptors) {
++ const installed = await hashDirectory(descriptor.absolutePath).catch(() => null);
++ if (installed !== manifest.fingerprints[descriptor.name]) {
++ committedBundleVerified = false;
++ break;
++ }
++ }
++ if (committedBundleVerified) {
++ try {
++ changed = await switchActiveBundle(root, committedBundle) || changed;
++ } catch (error) {
++ warnings.push(
++ `could not recover the committed built-in Skill bundle: ${error instanceof Error ? error.message : String(error)}`,
++ );
++ return true;
++ }
++ } else {
++ warnings.push('the committed built-in Skill bundle does not match its recorded fingerprints');
++ }
++ descriptors = stableDescriptors;
++ }
+ const installedFingerprints = new Map<string, string | null>();
+ for (const descriptor of descriptors) {
+ installedFingerprints.set(
+ descriptor.name,
+ await hashDirectory(descriptor.absolutePath).catch(() => null),
+ );
+ }
- projectionSafe = !isEmptyManifest(manifest) && descriptors.every((descriptor) => (
++ projectionSafe = !isEmptyManifest(manifest) && committedBundleVerified && descriptors.every((descriptor) => (
+ typeof manifest.fingerprints[descriptor.name] === 'string'
+ && installedFingerprints.get(descriptor.name) === manifest.fingerprints[descriptor.name]
+ ));
+
+ if (!projectionSafe && !isEmptyManifest(manifest)) {
+ const recovered = await removeInactiveBuiltInProjections(
+ root,
+ descriptors,
+ homeDir,
- descriptors,
++ [],
+ );
+ warnings.push(...recovered.warnings);
+ if (!recovered.complete) {
+ warnings.push('kept the active built-in Skill manifest because inactive Agent projections could not be removed');
+ return true;
+ }
+ }
+
+ // The manifest is the authority after a crash. Repair its projections
+ // before attempting another activation so an interrupted prior run cannot
+ // leak a newer unpublished bundle into an Agent runtime.
+ if (projectionSafe) {
+ const activeProjection = await projectBuiltInSkillLinksUnlocked(options, descriptors);
+ changed = activeProjection.changed || changed;
+ warnings.push(...activeProjection.warnings);
+ if (!activeProjection.complete) {
+ projectionSafe = false;
+ warnings.push('kept the active built-in Skill bundle because its Agent projections could not be verified');
+ return true;
+ }
+ }
+ const newerBundleIsInstalled = manifest.bundleVersion > bundleVersion;
+ if (newerBundleIsInstalled) {
+ warnings.push(
+ `kept built-in Skill bundle ${manifest.bundleVersion}; this build only carries older bundle ${bundleVersion}`,
+ );
+ return true;
+ }
+
+ const plans: Array<{
+ descriptor: BuiltInSkillDescriptor;
+ source: string;
+ fingerprint: string;
+ installedFingerprint: string | null;
+ }> = [];
+ for (const descriptor of descriptors) {
+ const source = path.join(options.bundledRoot, descriptor.name);
+ try {
+ if (!(await fsp.stat(path.join(source, 'SKILL.md')).catch(() => null))?.isFile()) {
+ throw new Error(`bundled Skill is missing SKILL.md: ${source}`);
+ }
+ const fingerprint = await hashDirectory(source);
+ const installedFingerprint = installedFingerprints.get(descriptor.name) ?? null;
+ const recordedFingerprint = manifest.fingerprints[descriptor.name];
+ const sameVersionConflict =
+ manifest.bundleVersion === bundleVersion &&
+ recordedFingerprint !== undefined &&
+ recordedFingerprint !== fingerprint;
+ if (sameVersionConflict) {
+ warnings.push(
+ `kept built-in Skill ${descriptor.name} because bundle version ${bundleVersion} was reused for different bytes`,
+ );
+ continue;
+ }
+ plans.push({ descriptor, source, fingerprint, installedFingerprint });
+ } catch (error) {
+ warnings.push(
+ `could not materialize built-in Skill ${descriptor.name}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+
+ if (plans.length !== descriptors.length) return true;
+
+ const fingerprints = Object.fromEntries(
+ plans.map(({ descriptor, fingerprint }) => [descriptor.name, fingerprint]),
+ );
+ const materializationNeeded =
+ manifest.schemaVersion !== 3 ||
+ manifest.bundleVersion !== bundleVersion ||
+ plans.some(
+ ({ descriptor, fingerprint, installedFingerprint }) =>
+ manifest.fingerprints[descriptor.name] !== fingerprint ||
+ installedFingerprint !== fingerprint,
+ );
+ if (!materializationNeeded) return true;
+
+ const activeBundle = materializedBundleName(bundleVersion, fingerprints);
+ const versionsRoot = path.join(root, VERSIONS_DIRECTORY);
+ const pending = path.join(versionsRoot, `.${activeBundle}.pending`);
+ const published = path.join(versionsRoot, activeBundle);
+ const nextManifest: PublishedMaterializationManifest = {
+ schemaVersion: 3,
+ bundleVersion,
+ fingerprints,
+ activeBundle,
+ };
+ let publishedDirectory = false;
++ let manifestAdvanced = false;
+ let projectionSnapshots: BuiltInProjectionSnapshot[] = [];
+ try {
+ await fsp.mkdir(versionsRoot, { recursive: true });
+ await fsp.mkdir(pending, { recursive: true });
+ for (const { descriptor, source, fingerprint } of plans) {
+ await materializeSkill(source, path.join(pending, descriptor.name), fingerprint);
+ }
- // Publish immutable bytes first. The one manifest-file replacement below
- // remains the only authoritative visibility switch. Project the complete
- // candidate first, then commit the pointer only if every Agent can use it.
++ // Every managed projection permanently targets .active/<skill>. Preparing
++ // those links cannot split the live bundle because .active still resolves
++ // to the previous version. The final pointer replacement publishes every
++ // Skill to every managed Agent together.
+ await fsp.rename(pending, published);
+ publishedDirectory = true;
- const candidateDescriptors = builtInSkillDescriptorsAtRoot(published, options.userDataDir);
- projectionSnapshots = await captureBuiltInProjectionState(candidateDescriptors, homeDir);
++ projectionSnapshots = await captureBuiltInProjectionState(stableDescriptors, homeDir);
+ const candidateProjection = await projectBuiltInSkillLinksUnlocked(
+ options,
- candidateDescriptors,
++ stableDescriptors,
++ true,
+ );
+ warnings.push(...candidateProjection.warnings);
+ if (!candidateProjection.complete) {
+ throw new Error('not every Agent projection accepted the prepared bundle');
+ }
+ await writeManifest(root, nextManifest);
++ manifestAdvanced = true;
++ await switchActiveBundle(root, activeBundle);
+ changed = true;
+ projectionSafe = true;
+ } catch (error) {
+ await fsp.rm(pending, { recursive: true, force: true }).catch(() => undefined);
- const restored = projectionSnapshots.length > 0
++ let manifestRestored = true;
++ if (manifestAdvanced) {
++ try {
++ await writeManifest(root, manifest);
++ if (manifest.schemaVersion === 3) {
++ await switchActiveBundle(root, manifest.activeBundle!);
++ } else {
++ await removeActiveBundlePointer(root);
++ }
++ } catch (restoreError) {
++ manifestRestored = false;
++ warnings.push(
++ `could not restore the previous built-in Skill manifest: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
++ );
++ }
++ }
++ const restored = manifestRestored && projectionSnapshots.length > 0
+ ? await restoreBuiltInProjectionState(projectionSnapshots)
- : { complete: true, warnings: [] };
++ : { complete: manifestRestored, warnings: [] };
+ warnings.push(...restored.warnings);
+ if (!restored.complete) projectionSafe = false;
+ if (publishedDirectory && restored.complete) {
+ await fsp.rm(published, { recursive: true, force: true }).catch(() => undefined);
+ }
+ warnings.push(
+ `could not activate built-in Skill bundle: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ return true;
+ }, { waitMs: BUILT_IN_SKILL_MUTATION_WAIT_MS });
+ if (locked === undefined) {
+ warnings.push('could not prepare built-in Skills because another Skill mutation is in progress');
+ }
+
+ return {
+ descriptors: builtInSkillDescriptors(options.userDataDir, options.appDataDir),
+ projectionSafe,
+ changed,
+ warnings,
+ };
+}
diff --cc apps/desktop/src/main/maker-host/index.ts
index 26da0a5214,3e9676630f..70d49ff19d
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@@ -1,5 -1,5 +1,5 @@@
import { registerCodexTextOnlyPolicy } from './codex-text-only-policy.js';
--import { readDisabledSkillPaths } from '../skillhub/activationPreferences';
++import { isCindyLearnSkillEnabled, readDisabledSkillPaths } from '../skillhub/activationPreferences';
import { cindyMakeManager } from '../cindy-make/manager.js';
import { makeSourceRoot } from '../cindy-make/sourcePaths.js';
import { clearCodexAccountUsageSnapshot } from '../usageBroadcaster.js';
@@@ -25,6 -25,6 +25,7 @@@ import { app, BrowserWindow } from 'ele
import { createHash, randomUUID } from 'node:crypto';
import { promises as fs } from 'node:fs';
import fsSync from 'node:fs';
++import os from 'node:os';
import path from 'node:path';
import {
@@@ -937,31 -933,6 +938,43 @@@ export function getMaker(): Maker
pluginRegistry,
resolveIOSSimulatorAccess,
invokeRemote: remoteInvoke,
+ attestCindyLearnSkillForSession: async (
+ sessionId: string,
+ sessionInstanceId: string | undefined,
+ ) => {
+ const session = _maker?.getSession(sessionId);
+ if (
+ !sessionInstanceId
+ || !session
+ || session.instanceId !== sessionInstanceId
+ || session.remoteHostId
++ || !isCindyLearnSkillEnabled()
+ ) {
+ return false;
+ }
- const result = await _maker!.listAgentSkills(session.agentKind, {
- workingDir: session.workDir,
- sessionId,
- });
++ const result = session.agentKind === 'claude-code'
++ ? await _maker!.listAgentRuntimeSkills(session.agentKind, {
++ workingDir: session.workDir,
++ sessionId,
++ runtimeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || (
++ process.env.XDT_USER_DATA_DIR && !app.isPackaged
++ ? path.join(app.getPath('userData'), 'claude-home')
++ : path.join(os.homedir(), '.claude')
++ ),
++ })
++ : await _maker!.listAgentSkills(session.agentKind, {
++ workingDir: session.workDir,
++ sessionId,
++ });
++ if (result.errors?.length) return false;
+ const skills = markCindyBuiltInAgentSkills(
+ result.skills,
+ builtInSkillDescriptors(app.getPath('userData'), app.getPath('appData')),
+ );
+ const learnCandidates = skills.filter((skill) => skill.name.toLowerCase() === 'learn');
+ return learnCandidates.length > 0
+ && learnCandidates.every((skill) => skill.builtIn === true);
+ },
// 只读活跃 Session 的运行时真相。权限切换是 runtime-first、DB-second,
// 因此插件过户自动放行不得回退 sessions.permission_mode;会话不再 active
// 时同样 fail closed。闭包在 MCP tool-call 时执行,此时 _maker 已装配完成。
diff --cc apps/desktop/src/renderer/components/chat/SystemCard.tsx
index f99bedff78,abd90a830a..da5dd8ca8c
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@@ -44,7 -44,7 +44,8 @@@ import
} from './activityRowChrome';
import { MarkdownRenderer } from './MarkdownRenderer';
import { CindyMakeDoctorCard } from './CindyMakeDoctorCard';
+import { builtInSkillDescriptionKey } from '@/features/skillhub/lib/builtInSkillPresentation';
+ import { CindyMakeCompleteCard } from '@/components/cindy-make/CindyMakeCompleteCard';
interface SystemCardProps {
cardType:
diff --cc packages/maker-core/src/agents/base-agent.ts
index 00ed58a119,00ed58a119..b3fa13d375
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@@ -73,6 -73,6 +73,7 @@@ import type
AgentBuiltinCommand,
ListAgentSkillsOptions,
ListAgentSkillsResult,
++ ListRuntimeSkillsOptions,
} from '../types/palette.js';
import type {
ListCustomizationsOptions,
@@@ -2517,6 -2517,6 +2518,11 @@@ export abstract class BaseAgent
void opts;
return { skills: [] };
}
++
++ /** Runtime-accurate Skill discovery for host-side authorization checks. */
++ async listRuntimeSkills(opts: ListRuntimeSkillsOptions): Promise<ListAgentSkillsResult> {
++ return this.listAgentSkills(opts);
++ }
/**
* ChatInput `@` palette entries for this agent kind.
diff --cc packages/maker-core/src/agents/claude-code/customization-scanner.test.ts
index 5fe30dc0a9,0000000000..cae4d71df7
mode 100644,000000..100644
--- a/packages/maker-core/src/agents/claude-code/customization-scanner.test.ts
+++ b/packages/maker-core/src/agents/claude-code/customization-scanner.test.ts
@@@ -1,49 -1,0 +1,70 @@@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { scanClaudeRuntimeSkills } from './customization-scanner.js';
+
+const roots: string[] = [];
+
+function writeSkill(root: string, name: string): string {
+ const skillDir = path.join(root, 'skills', name);
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(skillDir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: ${name}\n---\n`,
+ );
+ return skillDir;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('scanClaudeRuntimeSkills', () => {
+ it('uses the child runtime config directory for global Skills', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-runtime-skills-'));
+ roots.push(root);
+ const home = path.join(root, 'home');
+ const isolatedConfig = path.join(root, 'user-data', 'claude-home');
+ const workingDir = path.join(root, 'project');
+ fs.mkdirSync(path.join(workingDir, '.git'), { recursive: true });
+ writeSkill(path.join(home, '.claude'), 'default-home');
+ const isolatedSkill = writeSkill(isolatedConfig, 'isolated-home');
+ const projectSkill = writeSkill(path.join(workingDir, '.claude'), 'project-skill');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+
+ const result = await scanClaudeRuntimeSkills(workingDir, isolatedConfig);
+
+ expect(result.items.map((item) => item.name)).toEqual([
+ 'isolated-home',
+ 'project-skill',
+ ]);
+ expect(result.items.map((item) => item.absolutePath)).toEqual([
+ isolatedSkill,
+ fs.realpathSync(projectSkill),
+ ]);
+ });
++
++ it('includes ancestor project Skills through the nearest Git boundary', async () => {
++ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-runtime-ancestors-'));
++ roots.push(root);
++ const isolatedConfig = path.join(root, 'claude-home');
++ const repository = path.join(root, 'repository');
++ const workingDir = path.join(repository, 'packages', 'app');
++ fs.mkdirSync(path.join(repository, '.git'), { recursive: true });
++ fs.mkdirSync(workingDir, { recursive: true });
++ const globalLearn = writeSkill(isolatedConfig, 'learn');
++ const repositoryLearn = writeSkill(path.join(repository, '.claude'), 'learn');
++ const outsideLearn = writeSkill(path.join(root, '.claude'), 'outside');
++
++ const result = await scanClaudeRuntimeSkills(workingDir, isolatedConfig);
++
++ expect(result.items.filter((item) => item.name === 'learn').map((item) => item.absolutePath)).toEqual([
++ globalLearn,
++ fs.realpathSync(repositoryLearn),
++ ]);
++ expect(result.items.map((item) => item.absolutePath)).not.toContain(fs.realpathSync(outsideLearn));
++ });
+});
diff --cc packages/maker-core/src/agents/claude-code/index.ts
index 76356226b4,43602b7c93..a303908802
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@@ -167,6 -167,6 +167,7 @@@ import type
AgentBuiltinCommand,
ListAgentSkillsOptions,
ListAgentSkillsResult,
++ ListRuntimeSkillsOptions,
} from '../../types/palette.js';
import { CLAUDE_CODE_AGENT_COMMANDS } from './commands.js';
import type {
@@@ -1015,6 -1015,6 +1016,35 @@@ export class ClaudeCodeAgent extends Ba
};
}
++ override async listRuntimeSkills(opts: ListRuntimeSkillsOptions): Promise<ListAgentSkillsResult> {
++ if (opts.remoteHostId) return this.listAgentSkills(opts);
++ if (!opts.workingDir) return { skills: [] };
++ let result: Awaited<ReturnType<typeof scanClaudeRuntimeSkills>>;
++ try {
++ result = await scanClaudeRuntimeSkills(opts.workingDir, opts.runtimeConfigDir);
++ } catch (error) {
++ return {
++ skills: [],
++ errors: [{
++ path: opts.workingDir,
++ message: error instanceof Error ? error.message : String(error),
++ }],
++ };
++ }
++ return {
++ skills: result.items.map((item) => ({
++ kind: 'agent-skill' as const,
++ name: item.name,
++ description: item.description,
++ source: 'skill' as const,
++ path: item.mdPath,
++ scope: item.scope === 'project' ? 'project' as const : 'global' as const,
++ enabled: true,
++ })),
++ ...(result.errors.length > 0 ? { errors: result.errors } : {}),
++ };
++ }
++
async scanAtResources(opts: ScanAtResourcesOptions): Promise<ScanAtResourcesResult> {
return scanClaudeAtResources(opts.workingDir, opts.cap, opts.query);
}
diff --cc packages/maker-core/src/maker.test.ts
index ac18e9ef61,ac18e9ef61..d2b6dd2921
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@@ -138,6 -138,6 +138,35 @@@ function createAgent
}
describe('Maker Pi managed-package skill boundary', () => {
++ it('uses the runtime Skill view for host authorization checks', async () => {
++ const agent = createAgent(async () => {
++ throw new Error('not used');
++ }, 'claude-code');
++ agent.listRuntimeSkills = vi.fn(async () => ({ skills: [{
++ kind: 'agent-skill' as const,
++ name: 'learn',
++ source: 'skill' as const,
++ path: '/repo/.claude/skills/learn/SKILL.md',
++ }] }));
++ const maker = new Maker({
++ agents: { 'claude-code': agent },
++ storage: createStorage(),
++ logger: createLogger(),
++ });
++
++ const result = await maker.listAgentRuntimeSkills('claude-code', {
++ workingDir: '/repo/src',
++ runtimeConfigDir: '/runtime/claude-home',
++ });
++
++ expect(result.skills.map((skill) => skill.name)).toEqual(['learn']);
++ expect(agent.listRuntimeSkills).toHaveBeenCalledWith({
++ workingDir: '/repo/src',
++ runtimeConfigDir: '/runtime/claude-home',
++ });
++ await maker.shutdown();
++ });
++
it.each(['claude-code', 'codex', 'pi'] as const)('keeps %s live palettes on their startup Skill snapshot', async (agentKind) => {
const source = '/fixture/disabled-skill';
let disabled: string[] = [source];
diff --cc packages/maker-core/src/maker.ts
index 0ce4016694,0ce4016694..9c2f25013e
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@@ -29,6 -29,6 +29,7 @@@ import type
AgentBuiltinCommand,
ListAgentSkillsOptions,
ListAgentSkillsResult,
++ ListRuntimeSkillsOptions,
} from './types/palette.js';
import type {
ListCustomizationsOptions,
@@@ -1396,6 -1396,6 +1397,22 @@@ export class Maker
return filter(await mergePiRuntimeSkillStatuses(result, session.getRuntimeCapabilities()));
}
++ /** Host-only runtime view used when a capability must match the live engine winner. */
++ async listAgentRuntimeSkills(
++ agentKind: AgentKind,
++ opts: ListRuntimeSkillsOptions & { sessionId?: string },
++ ): Promise<ListAgentSkillsResult> {
++ const { sessionId, ...agentOpts } = opts;
++ const agent = this.requireAgent(agentKind);
++ const session = sessionId ? this.getSession(sessionId) : undefined;
++ const result = await agent.listRuntimeSkills(agentOpts);
++ return agent.filterActiveSkillCommands(
++ result,
++ agentOpts.remoteHostId ?? session?.remoteHostId ?? undefined,
++ session?.agentKind === agentKind ? session.getDisabledSkillPaths() : undefined,
++ );
++ }
++
/** ChatInput `@` palette entries, routed by agent kind. */
async scanAtResources(
agentKind: AgentKind,
diff --cc packages/maker-core/src/types/palette.ts
index 86e508d0a0,7dcea84f9a..aec83502a7
--- a/packages/maker-core/src/types/palette.ts
+++ b/packages/maker-core/src/types/palette.ts
@@@ -90,6 -88,6 +90,12 @@@ export interface ListAgentSkillsOption
includeManagedPiPackages?: boolean;
}
++/** Host-only runtime discovery inputs used for security decisions about the live task. */
++export interface ListRuntimeSkillsOptions extends ListAgentSkillsOptions {
++ /** Exact config directory passed to the local runtime process, when it differs from its default. */
++ runtimeConfigDir?: string;
++}
++
export interface ListAgentSkillsResult {
skills: AgentSkillCommand[];
errors?: Array<{ path?: string; message: string }>;