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): make built-in skill publication transactional

xd-boboc4e278b1c3f0
diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
index f3e57137ad..5423006ab6 100644
--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
@@ -244,9 +244,11 @@ describe('passive shared-userData instance auth isolation', () => {
const ownerBoundary = body.indexOf('withSharedGlobalSkillProjectionMutation(ownerId');
expect(ownerBoundary).toBeGreaterThan(-1);
expect(body.indexOf('prepareBuiltInSkills({')).toBeGreaterThan(ownerBoundary);
- expect(body.indexOf('refreshBuiltInSharedSkillLinks({')).toBeGreaterThan(ownerBoundary);
expect(body.indexOf('prepareSharedGlobalSkillLinks({')).toBeGreaterThan(ownerBoundary);
- expect(body.indexOf('refreshBuiltInClaudeSkillLinks({')).toBeGreaterThan(ownerBoundary);
+ expect(body).not.toContain('refreshBuiltInSharedSkillLinks({');
+ expect(body.indexOf('refreshBuiltInClaudeSkillLinks({')).toBeGreaterThan(
+ body.indexOf('prepareSharedGlobalSkillLinks({'),
+ );
});
it('relogin marker:passive 不消费整机一份的 marker,也不删 primary 的 token', () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
index 64df7527e5..da645f3a40 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
@@ -9,7 +9,6 @@ import {
markCindyBuiltInAgentSkills,
prepareBuiltInSkills,
refreshBuiltInClaudeSkillLinks,
- refreshBuiltInSharedSkillLinks,
resolveBundledSystemSkillsRoot,
} from '../built-in-skills';
@@ -45,30 +44,7 @@ function fixture() {
async function prepareAndProjectBuiltInSkills(
input: ReturnType<typeof fixture> & { bundleVersion?: number },
) {
- const prepared = await prepareBuiltInSkills(input);
- const shared = prepared.projectionSafe
- ? await refreshBuiltInSharedSkillLinks({
- userDataDir: input.userDataDir,
- appDataDir: input.appDataDir,
- homeDir: input.homeDir,
- descriptors: prepared.descriptors,
- withSharedMutation: input.withSharedMutation,
- })
- : { changed: false, warnings: [] };
- const claude = prepared.projectionSafe
- ? await refreshBuiltInClaudeSkillLinks({
- userDataDir: input.userDataDir,
- appDataDir: input.appDataDir,
- homeDir: input.homeDir,
- descriptors: prepared.descriptors,
- withSharedMutation: input.withSharedMutation,
- })
- : { changed: false, warnings: [] };
- return {
- ...prepared,
- changed: prepared.changed || shared.changed || claude.changed,
- warnings: [...prepared.warnings, ...shared.warnings, ...claude.warnings],
- };
+ return prepareBuiltInSkills(input);
}
afterEach(() => {
@@ -344,6 +320,116 @@ describe('built-in Skills', () => {
expect(fs.readdirSync(versionsRoot)).toEqual([initialActiveBundle]);
});
+ it('rolls every Agent projection back before keeping the previous manifest', 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');
+ 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}v9-`)
+ && String(linkPath).includes(`learn.next-`)
+ ) {
+ throw new Error('blocked Learn projection');
+ }
+ await originalSymlink(target, linkPath, type);
+ });
+
+ const failed = await prepareBuiltInSkills({ ...input, bundleVersion: 9 });
+
+ 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(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.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 = 'v9-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('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');
@@ -437,18 +523,20 @@ describe('built-in Skills', () => {
expect(fs.existsSync(path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator'))).toBe(false);
});
- it('materializes app-owned bytes without mutating home-level discovery roots', async () => {
+ 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.existsSync(path.join(
+ expect(fs.realpathSync(path.join(
input.homeDir,
'.agents',
'skills',
'cindy-skill-creator',
- ))).toBe(false);
- expect(fs.existsSync(result.descriptors[0]!.nativeClaudePath)).toBe(false);
+ ))).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 () => {
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index 92247e178c..4514e56419 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -42,7 +42,6 @@ import { prepareSharedGlobalSkillLinks } from './shared-global-skills.js';
import {
prepareBuiltInSkills,
refreshBuiltInClaudeSkillLinks,
- refreshBuiltInSharedSkillLinks,
resolveBundledSystemSkillsRoot,
} from './built-in-skills.js';
import {
@@ -606,9 +605,9 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
try {
const ownerId = getActiveAppSession().dataOwnerId;
const result = await withSharedGlobalSkillProjectionMutation(ownerId, async () => {
- // Bundle activation and every projection of that bundle share one
- // stable-owner critical section. Passive instances are rejected before
- // they can switch the process-independent active manifest.
+ // 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.
const preparedBuiltIns = await prepareBuiltInSkills({
bundledRoot: resolveBundledSystemSkillsRoot({
isPackaged: app.isPackaged,
@@ -618,17 +617,15 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
userDataDir: app.getPath('userData'),
appDataDir: app.getPath('appData'),
});
- const builtInSharedProjection = preparedBuiltIns.projectionSafe
- ? await refreshBuiltInSharedSkillLinks({
- userDataDir: app.getPath('userData'),
- appDataDir: app.getPath('appData'),
- descriptors: preparedBuiltIns.descriptors,
- })
- : { warnings: ['skipped built-in Skill projection because the active bundle could not be verified'] };
const sharedProjection = await prepareSharedGlobalSkillLinks({
assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
});
- const isolatedClaudeProjection = preparedBuiltIns.projectionSafe
+ // Publication already established a usable Claude projection before
+ // switching the manifest. 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'),
@@ -638,9 +635,8 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
return {
warnings: [
...preparedBuiltIns.warnings,
- ...builtInSharedProjection.warnings,
...sharedProjection.warnings,
- ...isolatedClaudeProjection.warnings,
+ ...claudePaletteProjection.warnings,
],
};
});
diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.ts
index d308d25cea..cd970dca9c 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -31,6 +31,7 @@ export interface PrepareBuiltInSkillsOptions {
bundledRoot: string;
userDataDir: string;
appDataDir?: string;
+ homeDir?: string;
bundleVersion?: number;
withSharedMutation?: typeof withSkillMutation;
}
@@ -61,6 +62,8 @@ export interface RefreshBuiltInSharedSkillLinksOptions {
export interface RefreshBuiltInClaudeSkillLinksResult {
changed: boolean;
+ /** False only when a Cindy-managed projection could not be made usable. */
+ complete: boolean;
warnings: string[];
}
@@ -362,13 +365,27 @@ async function ensureSkillEntry(
additionalManagedTargets,
)
) {
- await fsp.unlink(linkPath);
+ const replacement = `${linkPath}.next-${randomUUID()}`;
+ const backup = `${linkPath}.previous-${randomUUID()}`;
await fsp.symlink(
desiredTarget,
- linkPath,
+ replacement,
process.platform === 'win32' ? 'junction' : 'dir',
);
- return { changed: true };
+ 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,
@@ -479,6 +496,7 @@ async function refreshBuiltInSharedSkillLinksUnlocked(
const homeDir = options.homeDir ?? os.homedir();
const warnings: string[] = [];
let changed = false;
+ let complete = true;
for (const descriptor of descriptors) {
try {
@@ -491,13 +509,14 @@ async function refreshBuiltInSharedSkillLinksUnlocked(
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, warnings };
+ return { changed, complete, warnings };
}
/** Refresh the home-level shared projection. Call only inside the stable owner boundary. */
@@ -514,6 +533,7 @@ export async function refreshBuiltInSharedSkillLinks(
);
return refreshed ?? {
changed: false,
+ complete: false,
warnings: ['could not expose built-in Skills because another Skill mutation is in progress'],
};
}
@@ -546,7 +566,8 @@ export function markCindyBuiltInAgentSkills(
const builtIn = Boolean(skill.path && trustedPath && realPathOrNormalized(skill.path) === trustedPath);
if (builtIn) return { ...skill, builtIn: true };
if (skill.builtIn === undefined) return skill;
- const { builtIn: _untrusted, ...rest } = skill;
+ const rest = { ...skill };
+ delete rest.builtIn;
return rest;
});
}
@@ -573,6 +594,7 @@ async function refreshBuiltInClaudeSkillLinksUnlocked(
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);
@@ -581,6 +603,7 @@ async function refreshBuiltInClaudeSkillLinksUnlocked(
? claudePalettePath
: sharedPath;
if (!(await hasSkillFile(claudeRuntimeTarget))) {
+ complete = false;
warnings.push(
`could not expose built-in Skill ${descriptor.name} to Claude because its palette winner is unavailable`,
);
@@ -599,13 +622,14 @@ async function refreshBuiltInClaudeSkillLinksUnlocked(
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, warnings };
+ return { changed, complete, warnings };
}
/** Keep Cindy's isolated Claude runtime pointed at the latest shared/palette winner. */
@@ -622,13 +646,179 @@ export async function refreshBuiltInClaudeSkillLinks(
);
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 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 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))
+ || (
+ 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[],
+): 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,
+ });
+ return {
+ changed: shared.changed || claude.changed,
+ complete: shared.complete && claude.complete,
+ warnings: [...shared.warnings, ...claude.warnings],
+ };
+}
+
/**
- * Materialize Cindy-owned Skill bytes under a profile-independent appData path.
- * Home-level discovery links are refreshed separately inside the stable owner boundary.
+ * 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.
*/
export async function prepareBuiltInSkills(
options: PrepareBuiltInSkillsOptions,
@@ -646,6 +836,7 @@ export async function prepareBuiltInSkills(
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);
let manifest: MaterializationManifest;
try {
@@ -662,6 +853,14 @@ export async function prepareBuiltInSkills(
);
return true;
}
+ if (isEmptyManifest(manifest)) {
+ 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;
+ }
+ }
const installedFingerprints = new Map<string, string | null>();
for (const descriptor of descriptors) {
installedFingerprints.set(
@@ -673,6 +872,34 @@ export async function prepareBuiltInSkills(
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(
@@ -740,6 +967,7 @@ export async function prepareBuiltInSkills(
activeBundle,
};
let publishedDirectory = false;
+ let projectionSnapshots: BuiltInProjectionSnapshot[] = [];
try {
await fsp.mkdir(versionsRoot, { recursive: true });
await fsp.mkdir(pending, { recursive: true });
@@ -747,20 +975,35 @@ export async function prepareBuiltInSkills(
await materializeSkill(source, path.join(pending, descriptor.name), fingerprint);
}
// Publish immutable bytes first. The one manifest-file replacement below
- // is the only visibility switch; old descriptors and symlinks keep pointing
- // at their intact version directory for concurrent readers.
+ // remains the only authoritative visibility switch. Project the complete
+ // candidate first, then commit the pointer only if every Agent can use it.
await fsp.rename(pending, published);
publishedDirectory = true;
+ const candidateDescriptors = builtInSkillDescriptorsAtRoot(published, options.userDataDir);
+ projectionSnapshots = await captureBuiltInProjectionState(candidateDescriptors, homeDir);
+ const candidateProjection = await projectBuiltInSkillLinksUnlocked(
+ options,
+ candidateDescriptors,
+ );
+ warnings.push(...candidateProjection.warnings);
+ if (!candidateProjection.complete) {
+ throw new Error('not every Agent projection accepted the prepared bundle');
+ }
await writeManifest(root, nextManifest);
changed = true;
projectionSafe = true;
} catch (error) {
await fsp.rm(pending, { recursive: true, force: true }).catch(() => undefined);
- if (publishedDirectory) {
+ const restored = projectionSnapshots.length > 0
+ ? await restoreBuiltInProjectionState(projectionSnapshots)
+ : { complete: true, 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 materialize built-in Skill bundle: ${error instanceof Error ? error.message : String(error)}`,
+ `could not activate built-in Skill bundle: ${error instanceof Error ? error.message : String(error)}`,
);
}
return true;
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 8be51e3bd7..5b88c6ec56 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -470,6 +470,55 @@ describe('registerSkillhubIpc usage handlers', () => {
expect(writeSkillFile).not.toHaveBeenCalled();
});
+ it('preserves the built-in attestation when discovery used a shared alias', async () => {
+ const builtInRoot = path.join(fixtureRoot, 'shared-system-skills', 'learn');
+ const builtInFile = path.join(builtInRoot, 'SKILL.md');
+ const sharedAlias = path.join(fixtureRoot, 'home', '.agents', 'skills', 'learn');
+ fs.mkdirSync(builtInRoot, { recursive: true });
+ fs.mkdirSync(path.dirname(sharedAlias), { recursive: true });
+ fs.writeFileSync(builtInFile, '# Learn\n');
+ fs.symlinkSync(builtInRoot, sharedAlias, process.platform === 'win32' ? 'junction' : 'dir');
+ const physicalBuiltInRoot = fs.realpathSync.native(builtInRoot);
+ const attestedRoot = process.platform === 'win32'
+ ? physicalBuiltInRoot.toLowerCase()
+ : physicalBuiltInRoot;
+ const sender = { id: 181, on: vi.fn(), once: vi.fn() };
+ resolveExistingSkillPathForGrant.mockReturnValue(physicalBuiltInRoot);
+ isExistingSkillPathGranted.mockReturnValue(true);
+ scanAllSkills.mockResolvedValueOnce({
+ skills: [{
+ id: 'builtin:learn',
+ kind: 'skill',
+ name: 'learn',
+ absolutePath: builtInRoot,
+ discoveredPath: sharedAlias,
+ discoveryPaths: [sharedAlias],
+ scope: 'global',
+ builtIn: true,
+ }],
+ sources: [],
+ });
+ readSkillRawFile.mockResolvedValue({ success: true, content: '# Learn\n' });
+ const { registerSkillhubIpc } = await import('../registerIpc');
+ registerSkillhubIpc({
+ getMaker: () => ({ listAgentSkills }) as never,
+ getManagedSkillRoots,
+ getBuiltInSkills: () => [{
+ name: 'learn',
+ absolutePath: builtInRoot,
+ nativeClaudePath: '/tmp/claude-home/skills/learn',
+ }],
+ getAllowedProjectRoots,
+ marketService: marketService as never,
+ publishService: { publish, cancel } as never,
+ });
+
+ await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
+ await handlers.get('skillhub:read-raw')?.({ sender }, { filePath: builtInFile });
+
+ expect(readSkillRawFile).toHaveBeenCalledWith({ filePath: builtInFile, attestedRoot });
+ });
+
it('keeps a scanned built-in version immutable after the active bundle advances', async () => {
const versionsRoot = path.join(fixtureRoot, 'shared-system-skills', '.versions');
const previousRoot = path.join(versionsRoot, 'v7-previous', 'learn');
@@ -911,10 +960,13 @@ describe('registerSkillhubIpc usage handlers', () => {
});
scanAllSkills.mockResolvedValueOnce({
skills: [{
+ id: 'builtin:cindy-skill-creator',
+ name: 'cindy-skill-creator',
absolutePath: builtInRoot,
discoveredPath: builtInRoot,
scope: 'user',
kind: 'skill',
+ builtIn: true,
}],
sources: [],
});
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 0f659eb59d..970eeca100 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -236,9 +236,22 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
? projectRootKey(skill.projectRoot)
: undefined;
if (skill.scope === 'project' && !skillProjectRootKey) continue;
+ // A built-in discovered through ~/.agents/skills still resolves to the
+ // app-owned physical root. Keep Main's built-in attestation instead of
+ // downgrading it to an ordinary discovery grant, otherwise the later
+ // read handlers re-apply the lexical user-skill whitelist and reject the
+ // exact path that the scan returned.
+ if (skill.builtIn === true) {
+ const root = configuredBuiltInRoot(skill.absolutePath);
+ const entryKey = root ? `${root}\0built-in` : null;
+ if (root && entryKey && !seenEntries.has(entryKey)) {
+ seenEntries.add(entryKey);
+ entries.push({ root, builtIn: true });
+ }
+ continue;
+ }
// discoveredPath preserves an allowed lexical alias when absolutePath was
// canonicalized through a parent-directory symlink.
- let remembered = false;
for (const candidate of [skill.discoveredPath, skill.absolutePath]) {
const root = resolveExistingSkillPathForGrant(candidate);
if (root) {
@@ -250,21 +263,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
...(skillProjectRootKey ? { projectRootKey: skillProjectRootKey } : {}),
});
}
- remembered = true;
break;
}
}
- // Scanner may inject the official copy when a same-name user Skill owns
- // every normal discovery alias. Authorize only the exact physical root
- // supplied by Main so its detail/files view remains readable.
- if (!remembered) {
- const root = configuredBuiltInRoot(skill.absolutePath);
- const entryKey = root ? `${root}\0built-in` : null;
- if (root && entryKey && !seenEntries.has(entryKey)) {
- seenEntries.add(entryKey);
- entries.push({ root, builtIn: true });
- }
- }
}
scannedSkillRootsBySender.set(event.sender.id, { ownerId, entries });
const records = skills.flatMap((skill) => {