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(skillhub): persist uninstall cleanup through failures and restarts

xd-bobo9bd4b9092575
diff --git a/apps/desktop/help-knowledge/skills.md b/apps/desktop/help-knowledge/skills.md
index 4927ea56c5..0759352e8b 100644
--- a/apps/desktop/help-knowledge/skills.md
+++ b/apps/desktop/help-knowledge/skills.md
@@ -36,7 +36,7 @@ Skills are reusable agent capabilities you package as a folder and load into you
- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.
- External source imports remove only their discovery links and keep the external source files. Package-owned or built-in skills must be removed through their owning package; their uninstall action is unavailable here. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared skill links.
- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.
-- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If only metadata/link cleanup fails, the notice offers **Retry cleanup** until the current window is closed or reloaded. Retry before then; closing or reloading ends the retry receipt without restoring the removed files.
+- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If cleanup is interrupted, the notice offers **Retry cleanup**. The unfinished operation survives closing, reloading, and restarting Cindy; reopen Skills in the same Cindy profile and account to continue. Cindy pauses conflicting installations until cleanup completes. Retrying never moves files to the trash a second time and preserves externally restored or replaced content.
**Publishing your own skill:**
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index 4ed54e0093..377bd0a882 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -144,7 +144,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
id: "skills",
title: "Skills (reusable agent capabilities)",
summary: "Browse, install, disable, uninstall, publish, and update agent skills; installed skills appear as \"/\" slash commands and are shared across Claude Code and Codex.",
- content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work with both agents:**\n\n- Skills are **engine-shared** — the same installed skill is available to both Claude Code and Codex, so you install it once.\n\n**Where skills live on disk:**\n\n- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command. Pi package skills remain usable from `/`, but do not show this local detail shortcut; manage them through their package.\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Disabling or uninstalling a local skill (Desktop):**\n\n- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from new-task command previews. Active tasks retain the skill preference snapshot applied when their Agent started, including their command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.\n- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.\n- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.\n- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.\n- External source imports remove only their discovery links and keep the external source files. Package-owned or built-in skills must be removed through their owning package; their uninstall action is unavailable here. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared skill links.\n- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.\n- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If only metadata/link cleanup fails, the notice offers **Retry cleanup** until the current window is closed or reloaded. Retry before then; closing or reloading ends the retry receipt without restoring the removed files.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, you set the skill's **visibility**: PUBLIC (anyone in the org) or DEPARTMENT_SCOPED (only the departments you choose).\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.\n\nIn a new-task draft, the slash hover panel offers detail links for global skills. Project skill detail links are available after creating a task, when SkillHub can include that project in its scan.",
+ content: "Skills are reusable agent capabilities you package as a folder and load into your sessions. They're managed on the same page as Plugins — **Skills** and **Plugins** are two tabs of one management surface (the Skills tab is the in-app browser for finding, installing, publishing, and updating skills).\n\n**Skills work with both agents:**\n\n- Skills are **engine-shared** — the same installed skill is available to both Claude Code and Codex, so you install it once.\n\n**Where skills live on disk:**\n\n- Global (available to every session): the shared root `~/.agents/skills/<name>/`, which is cross-linked to `~/.claude/skills/` and `~/.codex/skills/` so every engine sees the same skills. On Windows that's under `C:\\Users\\<you>\\`.\n- Project-scoped (only inside one working directory): `<working-dir>/.agents/skills/<name>/` or `<working-dir>/.claude/skills/<name>/`.\n- Each skill is its own folder with a required `SKILL.md` at the root (the prompt / spec the agent reads). Sibling files and subfolders in that folder are also visible to the agent.\n\n**Importing a local skill:**\n\n- On the Skills page, use **Import skill** (top-right) to pick a `.zip` package or a standalone `SKILL.md` file.\n- A zip must contain a `SKILL.md` (at the package root, or inside a single top-level folder). The YAML frontmatter must include non-empty `name` and `description` fields; `name` must match `^[a-z0-9-]{1,200}$`.\n- You then choose where to install: global, a known project, or another directory. Cindy extracts metadata from the file automatically and lists the skill with that name and description.\n- Imported skills can be uninstalled from the detail page, and you can publish them to SkillHub later if you want.\n\n**Using an installed skill:**\n\n- Hover over a local skill in the `/` suggestions and choose **View skill details** in its information panel to open that exact skill. This does not insert or send the command. Pi package skills remain usable from `/`, but do not show this local detail shortcut; manage them through their package.\n\n- Type `/` in the composer to open the slash-command palette; your installed skills show up there alongside built-in and agent commands. Pick one to run it.\n\n**Disabling or uninstalling a local skill (Desktop):**\n\n- Open a skill's detail page to use the switch in the top action bar. For a market skill installed in multiple locations, select the local copy from the location dropdown beside the switch. Turning it off keeps the files and removes the skill from new-task command previews. Active tasks retain the skill preference snapshot applied when their Agent started, including their command palette. New or restarted Claude Code, Codex, and Pi agents apply that choice; an already-running agent keeps its existing context.\n- Renaming a local skill while publishing keeps its enabled or disabled setting. If renaming fails, Cindy restores the original folder and content.\n- The switch is local to this device and Cindy profile. It does not edit external CLI settings, sync to other devices, or override a native engine's own disabled state. Enable it again to let the engine discover it normally.\n- In the skill's details, use **… → Uninstall skill**. Confirm the location and shared-file impact. Standalone skills, including locally written skills without a market installation record, move to the system trash. Recovery is through the operating system's trash.\n- External source imports remove only their discovery links and keep the external source files. Package-owned or built-in skills must be removed through their owning package; their uninstall action is unavailable here. Skills provided by Cindy plugins are managed on the owning plugin's page, including when discovered through shared skill links.\n- Offline removal of an automatically synced skill is remembered on this device, including after restart or sign-in. Automatic sync skips it until you explicitly install it again.\n- Uninstalling a shared copy affects external CLIs that use it. It does not unpublish a skill or delete other users' copies. If file removal fails, Cindy keeps the installation. If cleanup is interrupted, the notice offers **Retry cleanup**. The unfinished operation survives closing, reloading, and restarting Cindy; reopen Skills in the same Cindy profile and account to continue. Cindy pauses conflicting installations until cleanup completes. Retrying never moves files to the trash a second time and preserves externally restored or replaced content.\n\n**Publishing your own skill:**\n\n- Find the publish action on the Skills page and point it at the skill's local folder. It zips the folder and uploads it — reading your directory in place, without copying or moving anything.\n- On first publish, you set the skill's **visibility**: PUBLIC (anyone in the org) or DEPARTMENT_SCOPED (only the departments you choose).\n- The local registry records what you published, so the app knows it's \"yours\" for future updates.\n\n**Updating an already-published skill:**\n\n- On your own skill's detail page you'll see a **发布新版本** (Publish New Version) button.\n- Edit the local folder however you want and publish — the version is **auto-incremented server-side**, you don't pick a number.\n- **Old versions stay live alongside the new one.** Users who already installed an older version keep it until they choose to update.\n- The display name and description are sent on every republish, so editing those metadata fields just means doing a republish.\n\n**Managing an already-published skill:**\n\n- Change who can see or use your skill from the management menu — public, shared with selected teams / departments, or private to you.\n- **Unpublish** makes it private again and returns ownership to your personal scope; it does not remove copies other users already installed.\n- **Authorship is fixed.** Only the original author's account can publish new versions of a given skill (enforced server-side as `NOT_AUTHOR`).\n\n**Browsing and installing others' skills:**\n\n- The marketplace lets you install skills into your global skills directory. You can request a specific version on install; the local registry tracks which version you have.\n\n**Notes:**\n\n- A skill folder without a `SKILL.md` at its root won't be picked up (lowercase `skill.md` is also accepted).\n- Project-scoped skills only show up in sessions whose working directory matches — useful for skills tied to a particular repo's conventions.\n- Editing files inside an installed skill folder takes effect on the next session start; you don't need to reinstall.\n- Uninstalling only removes your local copy. For your own published skills, use unpublish or manage visibility to change market availability.\n\nIn a new-task draft, the slash hover panel offers detail links for global skills. Project skill detail links are available after creating a task, when SkillHub can include that project in its scan.",
},
{
id: "updates-and-about",
diff --git a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
index c5169e1da7..09d16a9d64 100644
--- a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
@@ -9,6 +9,24 @@ vi.mock('../../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.
afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
describe('Skill activation preferences', () => {
+ it('clears only captured disabled intent, preserving later toggles and unrelated paths', async () => {
+ const prefs = await import('../activationPreferences');
+ const source = path.join(root, 'intent-source');
+ const other = path.join(root, 'intent-other');
+ await prefs.setCindySkillEnabled(source, false);
+ const snapshot = prefs.snapshotSkillActivation(source)!;
+ await prefs.setCindySkillEnabled(source, true);
+ await prefs.setCindySkillEnabled(source, false);
+ await prefs.setCindySkillEnabled(other, false);
+ await prefs.clearSkillActivationSnapshot(snapshot, () => true);
+ expect(prefs.isCindySkillEnabled(source)).toBe(false);
+ const current = prefs.snapshotSkillActivation(source)!;
+ await prefs.clearSkillActivationSnapshot(current, () => true);
+ expect(prefs.isCindySkillEnabled(source)).toBe(true);
+ expect(prefs.isCindySkillEnabled(other)).toBe(false);
+ await prefs.setCindySkillEnabled(other, true);
+ });
+
it('defaults to native behavior, persists only disabled paths, and preserves concurrent changes', async () => {
const { isCindySkillEnabled, setCindySkillEnabled, readDisabledSkillPaths, skillActivationKey } = await import('../activationPreferences');
const a = path.join(root, 'project-a', 'skill');
diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
index f6868c4145..487f81d964 100644
--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
@@ -341,20 +341,210 @@ describe('skillhub/installService', () => {
expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('restored');
});
- it('releases a discarded cleanup receipt without retrying filesystem or registry operations', async () => {
- const { source, target } = await localFixture('cleanup-discarded');
+ it('recovers a receipt after restart while retaining every alias barrier', async () => {
+ const { source, target } = await localFixture('cleanup-restarted');
const { registryService } = await import('../registry');
vi.mocked(registryService.getInstall).mockResolvedValue({
origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
});
vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('disk unavailable'));
- const { uninstall, retryUninstallCleanup, discardUninstallCleanup } = await import('../installService');
+ const { uninstall } = await import('../installService');
const { shell } = await import('electron');
const result = await uninstall(source, target);
if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
- discardUninstallCleanup(result.cleanupToken);
+ vi.resetModules();
+ const { retryUninstallCleanup, listPendingUninstallCleanups } = await import('../installService');
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ expect(listPendingUninstallCleanups()).toEqual([{ token: result.cleanupToken, name: 'cleanup-restarted' }]);
+ expect(await acquireSharedSkillMutationLease(['cleanup-restarted'])).toBeNull();
expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(listPendingUninstallCleanups()).toEqual([]);
+ const next = await acquireSharedSkillMutationLease(['cleanup-restarted']);
+ expect(next).not.toBeNull();
+ await next!();
+ expect(shell.trashItem).toHaveBeenCalledOnce();
+ });
+
+ it.each(['retry-then-install', 'external-replacement'] as const)('finishes old imported aliases without losing the source (%s)', async (scenario) => {
+ const source = path.join(TEST_ROOT, 'external', 'old-source');
+ const alias = path.join(TEST_ROOT, '.agents', 'skills', 'reinstalled-alias');
+ const compatibilityAlias = path.join(TEST_ROOT, '.claude', 'skills', 'different-alias');
+ fs.mkdirSync(source, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'old external skill');
+ for (const entry of [alias, compatibilityAlias]) makeDirectoryLink(entry, source);
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
+ const target = inspectLocalSkillTarget(source, [alias, compatibilityAlias])!;
+ expect(target.linkOnly).toBe(true);
+ const originalUnlink = fs.unlinkSync;
+ const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
+ if (entry === compatibilityAlias) throw Object.assign(new Error('fixture link is busy'), { code: 'EPERM' });
+ return originalUnlink(entry);
+ });
+ const { uninstall, install } = await import('../installService');
+ const { shell } = await import('electron');
+ let result: Awaited<ReturnType<typeof uninstall>>;
+ try { result = await uninstall(source, target); }
+ finally { unlink.mockRestore(); }
+ if (!result.success || !result.cleanupToken) throw new Error('expected unfinished cleanup');
+ vi.resetModules();
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ for (const name of ['old-source', 'reinstalled-alias', 'different-alias']) {
+ expect(await acquireSharedSkillMutationLease([name])).toBeNull();
+ }
+ const unrelated = await acquireSharedSkillMutationLease(['unrelated-skill']);
+ expect(unrelated).not.toBeNull();
+ await unrelated!();
+ const zip = await makeZip({ 'SKILL.md': 'new installed skill' });
+ await setupInstallDownload('reinstalled-alias', zip);
+ const params = { name: 'reinstalled-alias', installPath: alias, version: '1.0.0' };
+ expect((await install(params, () => {})).success).toBe(false);
+ if (scenario === 'external-replacement') {
+ // External CLIs do not participate in Cindy's shared mutation protocol.
+ fs.mkdirSync(alias);
+ fs.writeFileSync(path.join(alias, 'SKILL.md'), 'new installed skill');
+ }
+ const { retryUninstallCleanup } = await import('../installService');
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(fs.lstatSync(compatibilityAlias, { throwIfNoEntry: false })).toBeUndefined();
+ if (scenario === 'retry-then-install') expect((await install(params, () => {})).success).toBe(true);
+ expect(fs.readFileSync(path.join(alias, 'SKILL.md'), 'utf8')).toBe('new installed skill');
+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('old external skill');
+ expect(shell.trashItem).toHaveBeenCalledOnce();
+ });
+
+ it('preserves restored source links and newer disabled intent during delayed cleanup', async () => {
+ const { source } = await localFixture('restored-source');
+ const alias = path.join(TEST_ROOT, '.claude', 'skills', 'restored-alias');
+ makeDirectoryLink(alias, source);
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const target = inspectLocalSkillTarget(source, [source, alias])!;
+ const prefs = await import('../activationPreferences');
+ await prefs.setCindySkillEnabled(source, false);
+ const originalUnlink = fs.unlinkSync;
+ const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
+ if (entry === alias) throw Object.assign(new Error('busy'), { code: 'EPERM' });
+ return originalUnlink(entry);
+ });
+ const { uninstall, retryUninstallCleanup } = await import('../installService');
+ let result: Awaited<ReturnType<typeof uninstall>>;
+ try { result = await uninstall(source, target); }
+ finally { unlink.mockRestore(); }
+ if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
+ fs.mkdirSync(source);
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'restored source');
+ await prefs.setCindySkillEnabled(source, true);
+ await prefs.setCindySkillEnabled(source, false);
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(fs.readFileSync(path.join(alias, 'SKILL.md'), 'utf8')).toBe('restored source');
+ expect(prefs.isCindySkillEnabled(source)).toBe(false);
+ });
+
+ it.each(['before-trash', 'after-trash', 'barrier-release'] as const)('recovers interrupted persistence without replaying trash (%s)', async (failure) => {
+ const { source, target } = await localFixture('persistence-failure');
+ const { shell } = await import('electron');
+ const journal = await import('../uninstallJournal');
+ const realWrite = journal.writeUninstallCleanup;
+ const write = vi.spyOn(journal, 'writeUninstallCleanup').mockImplementation((record) => {
+ if (failure === 'before-trash' || (failure === 'after-trash' && record.phase !== 'prepared')) throw new Error('disk full');
+ realWrite(record);
+ });
+ const originalUnlink = fs.unlinkSync;
+ const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
+ if (failure === 'barrier-release' && String(entry).includes('shared-skill-mutation-locks') && String(entry).endsWith('.json')) {
+ throw Object.assign(new Error('busy'), { code: 'EPERM' });
+ }
+ return originalUnlink(entry);
+ });
+ const { uninstall } = await import('../installService');
+ let result: Awaited<ReturnType<typeof uninstall>>;
+ try { result = await uninstall(source, target); }
+ finally { write.mockRestore(); unlink.mockRestore(); }
+ if (failure === 'before-trash') {
+ expect(result.success).toBe(false);
+ expect(shell.trashItem).not.toHaveBeenCalled();
+ expect(fs.existsSync(source)).toBe(true);
+ return;
+ }
+ if (!result.success || !result.cleanupToken) throw new Error('expected durable receipt');
+ vi.resetModules();
+ const { retryUninstallCleanup } = await import('../installService');
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ expect(await acquireSharedSkillMutationLease(['persistence-failure'])).toBeNull();
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(shell.trashItem).toHaveBeenCalledOnce();
+ expect(fs.existsSync(source)).toBe(false);
+ });
+
+ it('retries only finalization after completed journal deletion fails', async () => {
+ const { source, target } = await localFixture('completed-receipt');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue({
+ origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ });
+ const originalUnlink = fs.unlinkSync;
+ const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
+ if (String(entry).includes('uninstall-cleanups') && String(entry).endsWith('.json')) {
+ throw Object.assign(new Error('busy journal'), { code: 'EPERM' });
+ }
+ return originalUnlink(entry);
+ });
+ const { uninstall, retryUninstallCleanup } = await import('../installService');
+ let result: Awaited<ReturnType<typeof uninstall>>;
+ try { result = await uninstall(source, target); }
+ finally { unlink.mockRestore(); }
+ if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
+ const { readUninstallCleanup } = await import('../uninstallJournal');
+ expect(readUninstallCleanup(result.cleanupToken)?.phase).toBe('completed');
expect(registryService.removeInstall).toHaveBeenCalledOnce();
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ const next = await acquireSharedSkillMutationLease(['completed-receipt']);
+ expect(next).not.toBeNull();
+ await next!();
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(registryService.removeInstall).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the receipt and barrier when a retry cannot inspect the source', async () => {
+ const { source, target } = await localFixture('unreadable-source');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue({
+ origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ });
+ vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('busy registry'));
+ const { uninstall, retryUninstallCleanup, listPendingUninstallCleanups } = await import('../installService');
+ const result = await uninstall(source, target);
+ if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
+ const originalStat = fs.lstatSync;
+ const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((...args) => {
+ if (String(args[0]) === target.sourcePath) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ return originalStat(...args);
+ });
+ try { expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(false); }
+ finally { stat.mockRestore(); }
+ expect(listPendingUninstallCleanups()).toHaveLength(1);
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ expect(await acquireSharedSkillMutationLease(['unreadable-source'])).toBeNull();
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ });
+
+ it('retains cleanup across owner changes and refuses to run it as another owner', async () => {
+ const { source, target } = await localFixture('owner-cleanup');
+ const { shell } = await import('electron');
+ const { getCurrentDataOwnerId } = await import('../../authManager');
+ vi.mocked(shell.trashItem).mockImplementationOnce(async (entry) => {
+ await fs.promises.rename(entry, source + '-trash');
+ vi.mocked(getCurrentDataOwnerId).mockReturnValue('other-owner');
+ });
+ const { uninstall, retryUninstallCleanup, listPendingUninstallCleanups } = await import('../installService');
+ const result = await uninstall(source, target);
+ if (!result.success || !result.cleanupToken) throw new Error('expected durable receipt');
+ expect(listPendingUninstallCleanups()).toEqual([]);
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(false);
+ vi.mocked(getCurrentDataOwnerId).mockReturnValue('user-1');
+ expect(listPendingUninstallCleanups()).toHaveLength(1);
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
expect(shell.trashItem).toHaveBeenCalledOnce();
});
@@ -469,6 +659,7 @@ describe('skillhub/installService', () => {
expect(registryService.removeInstall).toHaveBeenCalledWith(
'imported-offline',
expect.stringMatching(/[/\\]imported-offline$/),
+ expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }),
);
} finally {
vi.mocked(getAppCapabilities).mockImplementation(() => ({
@@ -1183,7 +1374,7 @@ describe('skillhub/installService', () => {
expect(fs.existsSync(projectAlias)).toBe(false);
expect(fs.existsSync(globalAlias)).toBe(true);
expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('fixture');
- expect(registryService.removeInstall).toHaveBeenCalledExactlyOnceWith('foo', projectAlias);
+ expect(registryService.removeInstall).toHaveBeenCalledExactlyOnceWith('foo', projectAlias, expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }));
} finally { home.mockRestore(); }
});
@@ -1205,7 +1396,7 @@ describe('skillhub/installService', () => {
const { uninstall } = await import('../installService');
const result = await uninstall(target.sourcePath, target);
expect(result).toEqual({ success: true, projectWorkingDir: projectRoot });
- expect(sharedSkills.prepareSharedProjectSkillLinks).toHaveBeenCalledWith({ workingDir: projectRoot });
+ expect(sharedSkills.prepareSharedProjectSkillLinks).not.toHaveBeenCalled();
expect(fs.existsSync(alias)).toBe(false);
expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('external content');
});
@@ -1236,9 +1427,7 @@ describe('skillhub/installService', () => {
const result = await uninstall(finalDir);
expect(result).toEqual({ success: true, projectWorkingDir: projectRoot });
- expect(sharedSkills.prepareSharedProjectSkillLinks).toHaveBeenCalledWith({
- workingDir: projectRoot,
- });
+ expect(sharedSkills.prepareSharedProjectSkillLinks).not.toHaveBeenCalled();
});
it('trashes a market install in local mode while cloud is unavailable', async () => {
@@ -1298,7 +1487,7 @@ describe('skillhub/installService', () => {
const result = await uninstall(physicalDir);
expect(result).toEqual({ success: true });
expect(fs.existsSync(physicalDir)).toBe(false);
- expect(registryService.removeInstall).toHaveBeenCalledWith('foo', logicalDir);
+ expect(registryService.removeInstall).toHaveBeenCalledWith('foo', logicalDir, expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }));
});
it('uninstalls a linked install when the scanner passes its physical path', async () => {
@@ -1334,7 +1523,7 @@ describe('skillhub/installService', () => {
expect(result.success).toBe(true);
expect(fs.existsSync(physicalDir)).toBe(false);
- expect(registryService.removeInstall).toHaveBeenCalledWith(skillName, logicalDir);
+ expect(registryService.removeInstall).toHaveBeenCalledWith(skillName, logicalDir, expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }));
});
it('clears a previous auto-sync ignore marker after a successful manual install', async () => {
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index f6c63a8bd4..392791bfa9 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -22,7 +22,7 @@ const installServiceMocks = vi.hoisted(() => ({
cancelInstall: vi.fn(),
uninstall: vi.fn(),
retryUninstallCleanup: vi.fn(),
- discardUninstallCleanup: vi.fn(),
+ listPendingUninstallCleanups: vi.fn(),
}));
vi.mock('electron', () => ({
@@ -128,6 +128,7 @@ const marketService = {
describe('registerSkillhubIpc usage handlers', () => {
beforeEach(async () => {
+ installServiceMocks.listPendingUninstallCleanups.mockReturnValue([]);
handlers.clear();
vi.clearAllMocks();
getManagedSkillRoots.mockReturnValue([]);
@@ -766,7 +767,7 @@ describe('registerSkillhubIpc usage handlers', () => {
expect(setCindySkillEnabled).toHaveBeenCalledTimes(1);
});
- it.each(['destroyed', 'reload'] as const)('revokes cleanup grants and receipts on window %s', async (lifecycle) => {
+ it.each(['destroyed', 'reload'] as const)('revokes window cleanup grants and reissues them after a fresh scan (%s)', async (lifecycle) => {
const { event, absolutePath } = await scanLocalFixture();
installServiceMocks.uninstall.mockResolvedValueOnce({ success: true, cleanupToken: 'receipt' });
await handlers.get('skillhub:uninstall')!(event, { absolutePath });
@@ -775,19 +776,38 @@ describe('registerSkillhubIpc usage handlers', () => {
} else {
event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1]({}, '', false, true);
}
- expect(installServiceMocks.discardUninstallCleanup).toHaveBeenCalledWith('receipt');
await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).rejects.toThrow('PRECONDITION_FAILED');
expect(installServiceMocks.retryUninstallCleanup).not.toHaveBeenCalled();
+ installServiceMocks.listPendingUninstallCleanups.mockReturnValue([{ token: 'receipt', name: 'example' }]);
+ installServiceMocks.retryUninstallCleanup.mockResolvedValueOnce(true);
+ expect(await handlers.get('skillhub:scan')!(event, {})).toMatchObject({
+ success: true, pendingCleanups: [{ token: 'receipt', name: 'example' }],
+ });
+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({ complete: true });
+ });
+
+ it('issues independent recovery grants to two scanned windows and rejects account changes', async () => {
+ const { event } = await scanLocalFixture();
+ const second = { sender: { id: event.sender.id + 1, once: vi.fn(), on: vi.fn() } };
+ installServiceMocks.listPendingUninstallCleanups.mockReturnValue([{ token: 'receipt', name: 'example' }]);
+ installServiceMocks.retryUninstallCleanup.mockImplementation(async (_token, canMutate) => canMutate());
+ await handlers.get('skillhub:scan')!(event, {});
+ await handlers.get('skillhub:scan')!(second, {});
+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({ complete: true });
+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(second, 'receipt')).toEqual({ complete: true });
+ await handlers.get('skillhub:scan')!(event, {});
+ getCurrentDataOwnerId.mockReturnValue('other-owner');
+ await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).rejects.toThrow('PRECONDITION_FAILED');
});
- it('discards a late cleanup receipt when its window reloads during uninstall', async () => {
+ it('withholds a late cleanup receipt when its window reloads during uninstall', async () => {
const { event, absolutePath } = await scanLocalFixture();
installServiceMocks.uninstall.mockImplementationOnce(async () => {
event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation')![1]({}, '', false, true);
return { success: true, cleanupToken: 'late-receipt' };
});
expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({ success: true });
- expect(installServiceMocks.discardUninstallCleanup).toHaveBeenCalledWith('late-receipt');
+ await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'late-receipt')).rejects.toThrow('PRECONDITION_FAILED');
});
it('rejects direct uninstall of a plugin snapshot even when the scanned UI claims it is removable', async () => {
diff --git a/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts b/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts
index 48c017251f..55992874bd 100644
--- a/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts
@@ -1,6 +1,7 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { createHash, randomUUID } from 'node:crypto';
import { afterAll, describe, expect, it, vi } from 'vitest';
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-skill-lease-'));
@@ -13,6 +14,43 @@ import { acquireSharedSkillMutationLease } from '../sharedMutationLease';
afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
describe('shared Skill mutation lease', () => {
+ it('contains a damaged durable barrier to its own resource name', async () => {
+ const token = randomUUID();
+ const key = createHash('sha256').update('damaged-receipt').digest('hex');
+ const file = path.join(root, 'Cindy', 'shared-skill-mutation-locks', 'pending', key, `${token}.json`);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, '{');
+ try {
+ expect(await acquireSharedSkillMutationLease(['damaged-receipt'])).toBeNull();
+ const other = await acquireSharedSkillMutationLease(['healthy-receipt']);
+ expect(other).not.toBeNull();
+ await other!();
+ } finally { fs.unlinkSync(file); }
+ });
+
+ it('retains a durable barrier after release and allows only its full receipt to resume', async () => {
+ const token = randomUUID();
+ const names = ['durable-source', 'durable-alias'];
+ const lease = await acquireSharedSkillMutationLease(names);
+ lease!.retainUntilComplete(token);
+ await lease!();
+ vi.resetModules();
+ const restarted = (await import('../sharedMutationLease')).acquireSharedSkillMutationLease;
+ expect(await restarted(['durable-alias'])).toBeNull();
+ expect(await restarted(names, randomUUID())).toBeNull();
+ expect(await restarted(['durable-alias'], token)).toBeNull();
+ const resumed = await restarted(names, token);
+ expect(resumed).not.toBeNull();
+ try {
+ resumed!.complete(token);
+ // Releasing the barrier never releases an executing process's lease early.
+ expect(await restarted(['durable-source'])).toBeNull();
+ } finally { await resumed!(); }
+ const next = await restarted(['durable-alias']);
+ expect(next).not.toBeNull();
+ await next!();
+ });
+
it('excludes independent callers through the shared lock file, preserving case-folded alias locks', async () => {
const first = await acquireSharedSkillMutationLease(['source', 'Alias']);
expect(first).not.toBeNull();
diff --git a/apps/desktop/src/main/skillhub/activationPreferences.ts b/apps/desktop/src/main/skillhub/activationPreferences.ts
index 70814e6aff..05724bb1f7 100644
--- a/apps/desktop/src/main/skillhub/activationPreferences.ts
+++ b/apps/desktop/src/main/skillhub/activationPreferences.ts
@@ -1,5 +1,6 @@
import fs from 'node:fs';
import path from 'node:path';
+import { randomUUID } from 'node:crypto';
import { app } from 'electron';
import { createLogger } from '../logger';
import { createOverrideSettingsFile } from '../maker-host/override-settings-file';
@@ -8,6 +9,7 @@ import { createOverrideSettingsFile } from '../maker-host/override-settings-file
interface SkillActivationPreferences {
disabledPaths: string[];
discoveryPaths?: Record<string, string[]>;
+ revisions?: Record<string, string>;
}
export function skillActivationKey(source: string): string {
@@ -29,6 +31,8 @@ const store = createOverrideSettingsFile<SkillActivationPreferences>({
.filter(([source, aliases]) => path.isAbsolute(source) && Array.isArray(aliases))
.map(([source, aliases]) => [source, aliases.filter((alias): alias is string =>
typeof alias === 'string' && path.isAbsolute(alias))])),
+ revisions: Object.fromEntries(Object.entries((raw as SkillActivationPreferences | null)?.revisions ?? {})
+ .filter(([source, revision]) => path.isAbsolute(source) && typeof revision === 'string')),
};
},
log: createLogger('skillhub:activation'),
@@ -52,15 +56,43 @@ export function isCindySkillEnabled(source: string): boolean {
return !readDisabledSkillPaths().includes(skillActivationKey(source));
}
+export interface SkillActivationSnapshot { key: string; revision?: string; aliases: string[] }
+
+export function snapshotSkillActivation(source: string): SkillActivationSnapshot | null {
+ store.invalidateIfChanged();
+ const value = store.read();
+ const key = skillActivationKey(source);
+ return value.disabledPaths.includes(key)
+ ? { key, revision: value.revisions?.[key], aliases: value.discoveryPaths?.[key] ?? [] } : null;
+}
+
+/** Compare the captured intent inside the settings lock; later toggles always win. */
+export async function clearSkillActivationSnapshot(snapshot: SkillActivationSnapshot, canMutate: () => boolean): Promise<void> {
+ await store.updateAtomic(({ value }) => {
+ if (!canMutate()) throw new Error('Skill mutation context changed');
+ const { key } = snapshot;
+ if (value.revisions?.[key] !== snapshot.revision
+ || JSON.stringify(value.discoveryPaths?.[key] ?? []) !== JSON.stringify(snapshot.aliases)) return value;
+ const discoveryPaths = { ...value.discoveryPaths };
+ const revisions = { ...value.revisions };
+ delete discoveryPaths[key];
+ delete revisions[key];
+ return { disabledPaths: value.disabledPaths.filter((item) => item !== key), discoveryPaths, revisions };
+ });
+}
+
export async function setCindySkillEnabled(source: string, enabled: boolean, canMutate: () => boolean = () => true, discoveryPaths: readonly string[] = []): Promise<void> {
const key = skillActivationKey(source);
await store.updateAtomic(({ value }) => {
if (!canMutate()) throw new Error('Skill mutation context changed');
const aliases = { ...value.discoveryPaths };
+ const revisions = { ...value.revisions };
+ delete revisions[key];
+ if (!enabled) revisions[key] = randomUUID();
delete aliases[key];
if (!enabled) aliases[key] = [...new Set([...(value.discoveryPaths?.[key] ?? []), ...discoveryPaths])]
.filter((alias) => path.isAbsolute(alias) && skillActivationKey(alias) === key);
- return { discoveryPaths: aliases, disabledPaths: enabled
+ return { revisions, discoveryPaths: aliases, disabledPaths: enabled
? value.disabledPaths.filter((item) => item !== key)
: [...new Set([...value.disabledPaths, key])].sort(),
};
@@ -80,9 +112,13 @@ export async function renameSkillWithActivation(
const disabledPaths = value.disabledPaths.filter((key) => key !== oldKey && key !== newKey);
if (value.disabledPaths.includes(oldKey)) disabledPaths.push(newKey);
const discoveryPaths = { ...value.discoveryPaths };
+ const revisions = { ...value.revisions };
+ delete revisions[oldKey];
+ delete revisions[newKey];
+ if (value.disabledPaths.includes(oldKey)) revisions[newKey] = randomUUID();
delete discoveryPaths[oldKey];
delete discoveryPaths[newKey];
if (value.disabledPaths.includes(oldKey)) discoveryPaths[newKey] = [destination];
- return { disabledPaths: [...new Set(disabledPaths)].sort(), discoveryPaths };
+ return { disabledPaths: [...new Set(disabledPaths)].sort(), discoveryPaths, revisions };
});
}
diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.ts
index c6d778b47f..a641a79ecb 100644
--- a/apps/desktop/src/main/skillhub/installService.ts
+++ b/apps/desktop/src/main/skillhub/installService.ts
@@ -28,7 +28,8 @@ import os from 'node:os';
import path from 'node:path';
import { app, net, shell } from 'electron';
import { isLocalSkillTargetCurrent, type LocalSkillTarget } from './localSkillTarget';
-import { isCindySkillEnabled, setCindySkillEnabled } from './activationPreferences';
+import { isCindySkillEnabled, setCindySkillEnabled, snapshotSkillActivation, clearSkillActivationSnapshot } from './activationPreferences';
+import { fileIdentity, writeUninstallCleanup, readUninstallCleanup, listUninstallCleanups, deleteUninstallCleanup, type UninstallCleanup } from './uninstallJournal';
import JSZip from 'jszip';
import { skillhubApiFetch } from './hubApi';
import { getCurrentDataOwnerId, getCurrentUserId } from '../authManager';
@@ -41,7 +42,7 @@ import { registryService } from './registry';
import type { StoredInstall } from './registry/types';
import { computeFolderHash } from './folderHash';
import { getSkillInstallLockOwner, skillInstallLockKey, tryAcquireSkillInstallLock } from './installLock';
-import { acquireSharedSkillMutationLease, type SkillMutationRelease } from './sharedMutationLease';
+import { acquireSharedSkillMutationLease, skillMutationNames, type SkillMutationRelease } from './sharedMutationLease';
import {
prepareSharedGlobalSkillLinks,
prepareSharedProjectSkillLinks,
@@ -180,13 +181,19 @@ async function pathExists(p: string): Promise<boolean> {
* Skill 目录变化后维护项目级双 Agent 兼容链接,并返回需要失效缓存的 cwd。
* 链接维护本身保持 best-effort;即使失败也返回 cwd,让调用层刷新实际磁盘状态。
*/
-async function reconcileProjectSkillLinksForPaths(...skillPaths: string[]): Promise<string | undefined> {
+function projectWorkingDirForSkillPaths(...skillPaths: string[]): string | undefined {
const projectWorkingDir = skillPaths
.map((skillPath) => projectWorkingDirFromSkillPath(skillPath))
.find((workingDir): workingDir is string => Boolean(workingDir));
if (!projectWorkingDir || path.resolve(projectWorkingDir) === path.resolve(os.homedir())) {
return undefined;
}
+ return projectWorkingDir;
+}
+
+async function reconcileProjectSkillLinksForPaths(...skillPaths: string[]): Promise<string | undefined> {
+ const projectWorkingDir = projectWorkingDirForSkillPaths(...skillPaths);
+ if (!projectWorkingDir) return undefined;
try {
const linkResult = await prepareSharedProjectSkillLinks({ workingDir: projectWorkingDir });
@@ -959,7 +966,8 @@ export async function uninstall(
// 共享安装锁:同名 install / learn apply 的 final-switch 进行中时拒绝删除,
// 避免 rm 掉对方刚切入的目录、registry 写入交错。
const releaseLocks: Array<() => void> = [];
- const lockNames = [...new Set([skillName, path.basename(target?.operationPath ?? absolutePath)].map(skillInstallLockKey))];
+ const lockNames = skillMutationNames([skillName, path.basename(absolutePath),
+ path.basename(target?.operationPath ?? absolutePath), ...(target?.aliases ?? []).map((alias) => path.basename(alias))]);
// An imported discovery link can have a different name from its source. Install
// replaces that entry under its discovery name, so hold both locks through trash.
for (const lockName of lockNames) {
@@ -994,6 +1002,8 @@ export async function uninstall(
registryMatch?.skillName ?? skillName,
cloudUserId,
registryMatch,
+ releaseShared,
+ lockNames,
target,
canMutate,
);
@@ -1064,139 +1074,164 @@ async function findRegistryInstallForPath(
return null;
}
-/** uninstall 的持锁主体(锁获取/释放在 uninstall 外壳完成)。 */
+/** The durable receipt owns cleanup; window grants only authorize execution. */
async function uninstallLocked(
absolutePath: string,
resolved: string,
skillName: string,
cloudUserId: string | null,
registryMatch: RegistryInstallMatch | null,
+ lease: SkillMutationRelease,
+ lockNames: string[],
target?: LocalSkillTarget,
canMutate: () => boolean = () => true,
): Promise<UninstallResult> {
- const registryEntry = registryMatch?.entry;
-
- if (!canMutate()) return { success: false, errorCode: 'CANCELLED', message: 'Skill mutation context changed' };
- const recordIgnore = !!(registryEntry && await shouldRecordAutoSyncIgnore(skillName, registryEntry, cloudUserId ?? undefined));
+ const ownerId = getCurrentDataOwnerId();
+ if (!ownerId || !canMutate()) return { success: false, errorCode: 'CANCELLED', message: 'Skill mutation context changed' };
+ const allowed = () => ownerId === getCurrentDataOwnerId() && canMutate();
+ const recordIgnore = !!(registryMatch && await shouldRecordAutoSyncIgnore(skillName, registryMatch.entry, cloudUserId ?? undefined));
const wasIgnored = recordIgnore && (await listIgnoredAutoSyncSkills(cloudUserId ?? undefined)).has(skillName);
- // Persist the user's opt-out before touching files, so auto-sync cannot recreate the Skill.
- if (recordIgnore && !wasIgnored) {
- try { await ignoreAutoSyncSkill(skillName, cloudUserId ?? undefined); }
- catch { return { success: false, errorCode: 'WRITE_FAILED', message: 'Could not save uninstall preference' }; }
- }
const candidates = target?.linkOnly ? [...new Set([...target.aliases, target.operationPath])] : [...new Set([
- ...(target?.aliases ?? []), absolutePath,
+ ...(target?.aliases ?? []), absolutePath, ...(registryMatch ? [registryMatch.installPath] : []),
path.join(os.homedir(), '.claude', 'skills', skillName),
path.join(os.homedir(), '.codex', 'skills', skillName),
path.join(os.homedir(), '.agents', 'skills', skillName),
])];
- // Capture exact links while their target still exists. Never sweep unrelated broken links.
- const links = candidates.flatMap((candidate) => {
- try {
- return fs.lstatSync(candidate).isSymbolicLink() && fs.realpathSync.native(candidate) === resolved
- ? [{ path: candidate, value: fs.readlinkSync(candidate), ino: fs.lstatSync(candidate).ino }] : [];
- } catch { return []; }
- });
+ const operationPath = target?.operationPath ?? resolved;
+ let cleanup: UninstallCleanup;
try {
- const exists = fs.existsSync(resolved);
- if (!canMutate() || (target && !isLocalSkillTargetCurrent(target))) throw new Error('Skill source changed; refresh and retry');
- if (exists) await shell.trashItem(target?.operationPath ?? resolved);
- } catch (err) {
- if (recordIgnore && !wasIgnored) {
- await clearIgnoredAutoSyncSkill(skillName, cloudUserId ?? undefined).catch((error) => log.warn('[skillInstall] restore auto-sync preference failed:', error));
+ const sourceIdentity = fileIdentity(resolved, true);
+ const operationIdentity = fileIdentity(operationPath);
+ if (!allowed() || !sourceIdentity || !operationIdentity || (target && !isLocalSkillTargetCurrent(target))
+ || candidates.some((candidate) => !lockNames.includes(skillInstallLockKey(path.basename(candidate))))) {
+ throw new Error('Skill source changed; refresh and retry');
}
- return { success: false, errorCode: 'WRITE_FAILED', message: err instanceof Error ? err.message : String(err) };
+ const links = candidates.flatMap((candidate) => {
+ try {
+ return fs.lstatSync(candidate).isSymbolicLink() && fs.realpathSync.native(candidate) === resolved
+ ? [{ path: candidate, value: fs.readlinkSync(candidate), identity: fileIdentity(candidate)! }] : [];
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ });
+ cleanup = {
+ version: 1, token: crypto.randomUUID(), ownerId, phase: 'prepared', lockNames,
+ skillName, resolved, sourceIdentity, operationPath, operationIdentity,
+ registryMatch, links, linkOnly: target?.linkOnly ?? false,
+ activation: target?.linkOnly ? null : snapshotSkillActivation(resolved),
+ undoIgnore: recordIgnore && !wasIgnored, cloudUserId,
+ };
+ // Journal first, then the shared barrier, then side effects. A crash in any
+ // gap leaves either no effects or enough information to finish without trashing twice.
+ writeUninstallCleanup(cleanup);
+ lease.retainUntilComplete(cleanup.token);
+ } catch (error) {
+ return { success: false, errorCode: 'WRITE_FAILED', message: error instanceof Error ? error.message : String(error) };
}
- const cleanup: UninstallCleanup = {
- skillName, resolved, operationPath: target?.operationPath ?? resolved, absolutePath,
- registryMatch, links, linkOnly: target?.linkOnly ?? false,
- };
- const complete = await finishUninstallCleanup(cleanup, canMutate);
- const cleanupToken = complete ? undefined : crypto.randomUUID();
- if (cleanupToken) pendingUninstallCleanup.set(cleanupToken, cleanup);
- const projectWorkingDir = await reconcileProjectSkillLinksForPaths(
- target?.operationPath ?? absolutePath, resolved, absolutePath,
- );
- return { success: true, ...(cleanupToken ? { cleanupToken } : {}),
+ let trashError: unknown;
+ try {
+ if (cleanup.undoIgnore) await ignoreAutoSyncSkill(skillName, cloudUserId ?? undefined);
+ if (!allowed() || (target && !isLocalSkillTargetCurrent(target))) throw new Error('Skill source changed; refresh and retry');
+ await shell.trashItem(operationPath);
+ cleanup.phase = 'removed';
+ writeUninstallCleanup(cleanup);
+ } catch (error) { trashError = error; }
+
+ // Even a rejected trash call can have removed its entry. Recovery inspects
+ // the original identity; it never repeats the destructive operation.
+ const complete = await finishUninstallCleanup(cleanup, lease, allowed);
+ if (trashError && cleanup.phase === 'completed' && fileIdentity(operationPath) === cleanup.operationIdentity) {
+ return { success: false, errorCode: 'WRITE_FAILED', message: trashError instanceof Error ? trashError.message : String(trashError) };
+ }
+ // Cache invalidation needs the cwd, not a broad link reconciliation: that
+ // would project a remaining import back into an entry we just removed.
+ const projectWorkingDir = projectWorkingDirForSkillPaths(operationPath, resolved, absolutePath);
+ return { success: true, ...(!complete ? { cleanupToken: cleanup.token } : {}),
...(projectWorkingDir ? { projectWorkingDir } : {}) };
}
-interface UninstallCleanup {
- skillName: string;
- resolved: string;
- operationPath: string;
- linkOnly: boolean;
- absolutePath: string;
- registryMatch: RegistryInstallMatch | null;
- links: Array<{ path: string; value: string; ino: number }>;
+/** Only the current profile/data owner can receive a new window grant. */
+export function listPendingUninstallCleanups(): Array<{ token: string; name: string }> {
+ const ownerId = getCurrentDataOwnerId();
+ return listUninstallCleanups().filter((record) => record.ownerId === ownerId)
+ .map((record) => ({ token: record.token, name: record.skillName }));
}
-// Only Main-issued receipts can retry metadata/link cleanup; no second trash operation.
-const pendingUninstallCleanup = new Map<string, UninstallCleanup>();
-
-/** End a window-scoped retry receipt without performing any filesystem mutation. */
-export function discardUninstallCleanup(token: string): void {
- pendingUninstallCleanup.delete(token);
-}
-
-async function finishUninstallCleanup(cleanup: UninstallCleanup, canMutate: () => boolean): Promise<boolean> {
- const { skillName, resolved, operationPath, registryMatch, links } = cleanup;
+async function finishUninstallCleanup(
+ cleanup: UninstallCleanup,
+ lease: SkillMutationRelease,
+ canMutate: () => boolean,
+): Promise<boolean> {
if (!canMutate()) return false;
- // Restore/reinstall wins over a delayed cleanup. Never alter a new installation.
- if (fs.existsSync(operationPath)) return true;
- let complete = true;
try {
- if (registryMatch) {
- const current = await registryService.getInstall(skillName, registryMatch.installPath);
- if (!canMutate()) return false;
- if (JSON.stringify(current) === JSON.stringify(registryMatch.entry)) {
- await registryService.removeInstall(skillName, registryMatch.installPath);
- }
- }
- } catch (err) {
- complete = false;
- log.warn('[skillInstall] uninstall registry cleanup failed:', err);
- }
- for (const link of links) {
- if (!canMutate()) return false;
- try {
- const stat = fs.lstatSync(link.path);
- if (stat.isSymbolicLink() && stat.ino === link.ino && fs.readlinkSync(link.path) === link.value) {
- // Keep validation and unlink adjacent; no awaited boundary can replace the link.
- fs.unlinkSync(link.path);
- }
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
- complete = false;
- log.warn('[skillInstall] uninstall link cleanup failed:', err);
+ if (cleanup.phase !== 'completed') {
+ if (cleanup.phase === 'prepared' && fileIdentity(cleanup.operationPath) === cleanup.operationIdentity) {
+ // The trash operation never committed (or the original was restored).
+ if (cleanup.undoIgnore) await clearIgnoredAutoSyncSkill(cleanup.skillName, cleanup.cloudUserId ?? undefined);
+ } else {
+ for (const link of cleanup.links) {
+ if (!canMutate()) return false;
+ if (fileIdentity(link.path) !== link.identity || fs.readlinkSync(link.path) !== link.value) continue;
+ const currentTarget = fileIdentity(link.path, true);
+ // Remove only links still serving the old source (external imports),
+ // or broken links whose source is still absent. A replaced source wins.
+ if ((cleanup.linkOnly && currentTarget === cleanup.sourceIdentity
+ && fileIdentity(cleanup.operationPath) !== cleanup.operationIdentity)
+ || (currentTarget === null && fileIdentity(cleanup.resolved, true) === null)) fs.unlinkSync(link.path);
+ }
+ const { registryMatch } = cleanup;
+ if (registryMatch && fileIdentity(registryMatch.installPath) === null) {
+ await registryService.removeInstall(registryMatch.skillName, registryMatch.installPath, {
+ expected: registryMatch.entry, canMutate,
+ shouldRemove: () => fileIdentity(registryMatch.installPath) === null,
+ });
+ }
+ if (cleanup.activation && fileIdentity(cleanup.resolved, true) === null) {
+ await clearSkillActivationSnapshot(cleanup.activation,
+ () => canMutate() && fileIdentity(cleanup.resolved, true) === null);
+ }
}
+ if (!canMutate()) return false;
+ // Completion is durable before the barrier opens. Failure to delete a
+ // completed receipt can only retry finalization, never old cleanup effects.
+ writeUninstallCleanup({ ...cleanup, phase: 'completed' });
+ cleanup.phase = 'completed';
}
+ lease.complete(cleanup.token);
+ deleteUninstallCleanup(cleanup.token);
+ return true;
+ } catch (error) {
+ log.warn('[skillInstall] uninstall cleanup remains pending:', error);
+ return false;
}
- // Unlinking an import does not remove the physical Skill or the user's shared
- // preference. Other scopes (and later reimports) must keep that explicit state.
- if (!cleanup.linkOnly && !isCindySkillEnabled(resolved)) {
- await setCindySkillEnabled(resolved, true, canMutate).catch((err) => {
- complete = false;
- log.warn('[skillInstall] activation cleanup failed:', err);
- });
- }
- return complete;
}
export async function retryUninstallCleanup(token: string, canMutate: () => boolean): Promise<boolean> {
- const cleanup = pendingUninstallCleanup.get(token);
+ const cleanup = readUninstallCleanup(token);
if (!cleanup) return true;
- const release = tryAcquireSkillInstallLock(cleanup.skillName, 'market-uninstall');
- if (!release) return false;
- let releaseShared: SkillMutationRelease | null = null;
+ const allowed = () => cleanup.ownerId === getCurrentDataOwnerId() && canMutate();
+ if (!allowed()) return false;
+ const releases: Array<() => void> = [];
+ let lease: SkillMutationRelease | null = null;
try {
- releaseShared = await acquireSharedSkillMutationLease([cleanup.skillName, path.basename(cleanup.operationPath), path.basename(cleanup.resolved)]);
- if (!releaseShared) return false;
- const complete = await finishUninstallCleanup(cleanup, canMutate);
- if (complete) pendingUninstallCleanup.delete(token);
- return complete;
- } finally { await releaseShared?.(); release(); }
+ for (const name of cleanup.lockNames) {
+ const release = tryAcquireSkillInstallLock(name, 'market-uninstall');
+ if (!release) return false;
+ releases.push(release);
+ }
+ lease = await acquireSharedSkillMutationLease(cleanup.lockNames, token);
+ if (!lease) return false;
+ // A second process may have completed the same receipt while this caller
+ // waited for a lease. Always re-read under the acquired lock.
+ const current = readUninstallCleanup(token);
+ if (!current) return true;
+ return await finishUninstallCleanup(current, lease, allowed);
+ } finally {
+ await lease?.();
+ for (const release of releases) release();
+ }
}
async function shouldRecordAutoSyncIgnore(skillName: string, registryEntry: StoredInstall, userId?: string): Promise<boolean> {
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index fb34815be0..7b5299e8d3 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -117,6 +117,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const marketService = options.marketService ?? new SkillhubMarketService();
const localImportGrants = new Map<string, LocalImportGrant>();
const uninstallConfirmations = new Set<number>();
+ const cleanupGrantKey = (senderId: number, token: string) => `${senderId}:${token}`;
const cleanupGrants = new Map<string, { ownerId: string | null; senderId: number }>();
const scannedSkillRootsBySender = new Map<number, ScannedSkillGrant>();
const localSkillsBySender = new Map<number, Array<{
@@ -175,7 +176,6 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
for (const [token, grant] of cleanupGrants) {
if (grant.senderId !== event.sender.id) continue;
cleanupGrants.delete(token);
- installService.discardUninstallCleanup(token);
}
scannedSkillRootsBySender.delete(event.sender.id);
localSkillsBySender.delete(event.sender.id);
@@ -408,6 +408,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
&& getCurrentDataOwnerId() === scanOwnerId
) {
rememberScannedSkillRoots(event, scanOwnerId, result.skills);
+ const pendingCleanups = installService.listPendingUninstallCleanups();
+ for (const { token } of pendingCleanups) {
+ cleanupGrants.set(cleanupGrantKey(event.sender.id, token), { ownerId: scanOwnerId, senderId: event.sender.id });
+ }
+ return { success: true, ...result, pendingCleanups };
}
return { success: true, ...result };
} catch (err) {
@@ -1052,15 +1057,18 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const result = await installService.uninstall(absolutePath, target,
() => approvalCurrent()
&& !isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots()));
- if (!result.success) throwIpcError('INTERNAL', 'Could not move Skill to the trash; retry');
+ if (!result.success) {
+ // A failed trash/preparation can still leave durable rollback work.
+ broadcastLocalChange();
+ throwIpcError('INTERNAL', 'Could not move Skill to the trash; retry');
+ }
await refreshCodexProjectSkillCache(result.projectWorkingDir);
broadcastLocalChange();
if (result.cleanupToken) {
- if ((cleanupGenerationBySender.get(event.sender) ?? 0) !== cleanupGeneration) {
- installService.discardUninstallCleanup(result.cleanupToken);
+ if (!approvalCurrent()) {
return { success: true };
}
- cleanupGrants.set(result.cleanupToken, { ownerId, senderId: event.sender.id });
+ cleanupGrants.set(cleanupGrantKey(event.sender.id, result.cleanupToken), { ownerId, senderId: event.sender.id });
}
return { success: true, ...(result.cleanupToken ? { cleanupToken: result.cleanupToken } : {}) };
},
@@ -1068,13 +1076,14 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
ipcMain.handle('skillhub:retry-uninstall-cleanup', async (event, token: string) => {
assertTrustedAppRendererEvent(event);
- const grant = cleanupGrants.get(token);
+ const key = cleanupGrantKey(event.sender.id, token);
+ const grant = cleanupGrants.get(key);
const canMutate = () => !!grant && grant.ownerId === getCurrentDataOwnerId()
- && cleanupGrants.get(token) === grant
+ && cleanupGrants.get(key) === grant
&& grant.senderId === event.sender.id && !isAppSessionBoundaryPending();
if (!canMutate()) throwIpcError('PRECONDITION_FAILED', 'Cleanup is no longer available');
const complete = await installService.retryUninstallCleanup(token, canMutate);
- if (complete) cleanupGrants.delete(token);
+ if (complete) cleanupGrants.delete(key);
broadcastLocalChange();
return { complete };
});
diff --git a/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts b/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts
index e46bf21529..a213db8e76 100644
--- a/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts
+++ b/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts
@@ -264,6 +264,30 @@ describe('updateInstall', () => {
});
describe('removeInstall', () => {
+ it('checks the old snapshot and mutation context after queued registry writes', async () => {
+ const old = makeEntry();
+ await addInstall('my-skill', globalPath, old);
+ const replacement = makeEntry({ version: 'new', folderHash: 'new-hash' });
+ const update = addInstall('my-skill', globalPath, replacement);
+ const remove = removeInstall('my-skill', globalPath, {
+ expected: old, canMutate: () => true, shouldRemove: () => true,
+ });
+ await Promise.all([update, remove]);
+ expect((await getInstall('my-skill', globalPath))?.version).toBe('new');
+ const current = (await getInstall('my-skill', globalPath))!;
+ await expect(removeInstall('my-skill', globalPath, {
+ expected: current, canMutate: () => false, shouldRemove: () => true,
+ })).rejects.toThrow('context changed');
+ await removeInstall('my-skill', globalPath, {
+ expected: current, canMutate: () => true, shouldRemove: () => false,
+ });
+ expect(await getInstall('my-skill', globalPath)).toEqual(current);
+ await removeInstall('my-skill', globalPath, {
+ expected: current, canMutate: () => true, shouldRemove: () => true,
+ });
+ expect(await getInstall('my-skill', globalPath)).toBeNull();
+ });
+
it('删掉一条 entry,其他留存', async () => {
const projectPath = path.join('/projects/foo', '.claude', 'skills', 'my-skill');
await addInstall('my-skill', globalPath, makeEntry());
diff --git a/apps/desktop/src/main/skillhub/registry/registryService.ts b/apps/desktop/src/main/skillhub/registry/registryService.ts
index 7e3bcf93ba..249d64f639 100644
--- a/apps/desktop/src/main/skillhub/registry/registryService.ts
+++ b/apps/desktop/src/main/skillhub/registry/registryService.ts
@@ -182,11 +182,19 @@ export async function updateInstall(
* 如果是该 skill 最后一条 install → 整个文件 unlink
* 不存在的 (name, path) → no-op,不抛错
*/
-export async function removeInstall(skillName: string, installPath: string): Promise<void> {
+export async function removeInstall(
+ skillName: string,
+ installPath: string,
+ condition?: { expected: StoredInstall; canMutate: () => boolean; shouldRemove: () => boolean },
+): Promise<void> {
const normalizedPath = path.normalize(installPath);
await withLock(skillName, async () => {
const existing = await readManifestWithBackup(skillName);
+ if (condition) {
+ if (!condition.canMutate()) throw new Error('Skill mutation context changed');
+ if (JSON.stringify(existing?.installs[normalizedPath]) !== JSON.stringify(condition.expected) || !condition.shouldRemove()) return;
+ }
if (!existing || !existing.installs[normalizedPath]) {
return; // no-op
}
diff --git a/apps/desktop/src/main/skillhub/sharedMutationLease.ts b/apps/desktop/src/main/skillhub/sharedMutationLease.ts
index b086c98c77..ecc2d40ded 100644
--- a/apps/desktop/src/main/skillhub/sharedMutationLease.ts
+++ b/apps/desktop/src/main/skillhub/sharedMutationLease.ts
@@ -5,9 +5,49 @@ import { app } from 'electron';
import { withCrossProcessLock } from '../device-link/crossProcessLock';
import { createLogger } from '../logger';
import { skillInstallLockKey } from './installLock';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';
const log = createLogger('skillhub:shared-mutation');
-export type SkillMutationRelease = () => Promise<void>;
+export type SkillMutationRelease = (() => Promise<void>) & {
+ /** Keep conflicting writers out after releasing the process lease. */
+ retainUntilComplete(token: string): void;
+ complete(token: string): void;
+};
+
+export function skillMutationNames(names: readonly string[]): string[] {
+ return [...new Set(names.map(skillInstallLockKey))].sort();
+}
+
+export function isSkillMutationToken(value: unknown): value is string {
+ return typeof value === 'string' && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value);
+}
+
+interface PendingMutation { token: string; keys: string[] }
+
+function readPending(root: string, keys: string[]): PendingMutation[] {
+ // Read only the held resource names: a damaged receipt must not block unrelated Skills.
+ return keys.flatMap((key) => {
+ const dir = path.join(root, 'pending', key);
+ let files: string[];
+ try { files = fs.readdirSync(dir); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ return [...new Set(files.filter((file) => /\.json(?:\.bak)?$/.test(file))
+ .map((file) => file.replace(/\.bak$/, '')))].flatMap((file) => {
+ const raw = readAtomicFileSync(path.join(dir, file));
+ if (raw === null) return [];
+ const value = JSON.parse(raw) as PendingMutation;
+ if (!isSkillMutationToken(value.token) || file !== `${value.token}.json`
+ || !Array.isArray(value.keys) || !value.keys.includes(key)
+ || value.keys.some((item) => typeof item !== 'string' || !/^[a-f0-9]{64}$/.test(item))) {
+ throw new Error('Invalid pending Skill mutation');
+ }
+ return [value];
+ });
+ });
+}
/**
* All Desktop profiles share native Skill directories. Keep the lease root
@@ -17,6 +57,7 @@ export type SkillMutationRelease = () => Promise<void>;
*/
export async function acquireSharedSkillMutationLease(
names: readonly string[],
+ pendingToken?: string,
): Promise<SkillMutationRelease | null> {
let root: string;
try {
@@ -26,7 +67,8 @@ export async function acquireSharedSkillMutationLease(
log.warn('Skill mutation lock directory is unavailable');
return null;
}
- const keys = [...new Set(names.map(skillInstallLockKey))].sort();
+ const keys = skillMutationNames(names).map((name) => createHash('sha256').update(name).digest('hex'));
+ if (keys.length === 0 || (pendingToken !== undefined && !isSkillMutationToken(pendingToken))) return null;
let enter!: (release: SkillMutationRelease | null) => void;
const entered = new Promise<SkillMutationRelease | null>((resolve) => { enter = resolve; });
let release!: () => void;
@@ -34,11 +76,41 @@ export async function acquireSharedSkillMutationLease(
let finished: Promise<void>;
const acquire = async (index: number): Promise<void> => {
if (index === keys.length) {
- enter(async () => { release(); await finished; });
+ const matchesKeys = (record: PendingMutation) =>
+ record.keys.length === keys.length && record.keys.every((key) => keys.includes(key));
+ if (readPending(root, keys).some((record) => record.keys.some((key) => keys.includes(key))
+ && !(record.token === pendingToken && matchesKeys(record)))) return;
+ let active = true;
+ const assertActive = (token: string) => {
+ if (!active || !isSkillMutationToken(token)) throw new Error('Skill mutation lease is no longer held');
+ };
+ const leased = Object.assign(async () => { active = false; release(); await finished; }, {
+ retainUntilComplete(token: string) {
+ assertActive(token);
+ const existing = readPending(root, keys).filter((record) => record.token === token);
+ if (existing.some((record) => !matchesKeys(record))) throw new Error('Skill mutation resources changed');
+ for (const key of keys) {
+ atomicWriteFileSync(path.join(root, 'pending', key, `${token}.json`), JSON.stringify({ token, keys }));
+ }
+ },
+ complete(token: string) {
+ assertActive(token);
+ const existing = readPending(root, keys).find((record) => record.token === token);
+ if (!existing) return;
+ if (!matchesKeys(existing)) throw new Error('Skill mutation resources changed');
+ for (const key of keys) {
+ for (const suffix of ['.json.bak', '.json']) {
+ try { fs.unlinkSync(path.join(root, 'pending', key, `${token}${suffix}`)); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ }
+ }
+ },
+ });
+ enter(leased);
await released;
return;
}
- const key = createHash('sha256').update(keys[index]!).digest('hex');
+ const key = keys[index]!;
await withCrossProcessLock(path.join(root, `${key}.lock`),
{ label: 'skill-mutation', waitMs: 0 }, async (status) => {
if (status.held) await acquire(index + 1);
diff --git a/apps/desktop/src/main/skillhub/uninstallJournal.ts b/apps/desktop/src/main/skillhub/uninstallJournal.ts
new file mode 100644
index 0000000000..bfea89021e
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/uninstallJournal.ts
@@ -0,0 +1,85 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { app } from 'electron';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';
+import type { StoredInstall } from './registry/types';
+import type { SkillActivationSnapshot } from './activationPreferences';
+import { isSkillMutationToken } from './sharedMutationLease';
+
+/** A durable operation receipt, never a Renderer-provided path or authorization. */
+export interface UninstallCleanup {
+ version: 1;
+ token: string;
+ ownerId: string;
+ phase: 'prepared' | 'removed' | 'completed';
+ lockNames: string[];
+ skillName: string;
+ resolved: string;
+ sourceIdentity: string;
+ operationPath: string;
+ operationIdentity: string;
+ linkOnly: boolean;
+ registryMatch: { skillName: string; installPath: string; entry: StoredInstall } | null;
+ links: Array<{ path: string; value: string; identity: string }>;
+ activation: SkillActivationSnapshot | null;
+ undoIgnore: boolean;
+ cloudUserId: string | null;
+}
+
+export function fileIdentity(file: string, follow = false): string | null {
+ try {
+ const stat = follow ? fs.statSync(file) : fs.lstatSync(file);
+ return JSON.stringify([stat.dev, stat.ino, stat.birthtimeMs, stat.isSymbolicLink()]);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+function journalDir(): string {
+ return path.join(app.getPath('userData'), 'skillhub', 'uninstall-cleanups');
+}
+
+function journalPath(token: string): string {
+ if (!isSkillMutationToken(token)) throw new Error('Invalid uninstall receipt');
+ return path.join(journalDir(), `${token}.json`);
+}
+
+export function writeUninstallCleanup(cleanup: UninstallCleanup): void {
+ atomicWriteFileSync(journalPath(cleanup.token), JSON.stringify(cleanup));
+}
+
+export function readUninstallCleanup(token: string): UninstallCleanup | null {
+ const raw = readAtomicFileSync(journalPath(token));
+ if (raw === null) return null;
+ const value = JSON.parse(raw) as UninstallCleanup;
+ if (value.version !== 1 || value.token !== token || typeof value.ownerId !== 'string'
+ || !['prepared', 'removed', 'completed'].includes(value.phase)
+ || !Array.isArray(value.lockNames) || !value.lockNames.length || value.lockNames.some((name) => typeof name !== 'string')
+ || ![value.resolved, value.operationPath, ...value.links.map((link) => link.path),
+ ...(value.registryMatch ? [value.registryMatch.installPath] : [])].every((file) => typeof file === 'string' && path.isAbsolute(file))
+ || typeof value.sourceIdentity !== 'string' || typeof value.operationIdentity !== 'string') {
+ throw new Error('Invalid uninstall journal');
+ }
+ return value;
+}
+
+export function listUninstallCleanups(): UninstallCleanup[] {
+ let files: string[];
+ try { files = fs.readdirSync(journalDir()); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ return [...new Set(files.filter((file) => /\.json(?:\.bak)?$/.test(file))
+ .map((file) => file.replace(/\.json(?:\.bak)?$/, '')))]
+ .flatMap((token) => { const record = readUninstallCleanup(token); return record ? [record] : []; });
+}
+
+export function deleteUninstallCleanup(token: string): void {
+ // Delete the backup first: a failed final unlink must not resurrect an older phase.
+ for (const file of [`${journalPath(token)}.bak`, journalPath(token)]) {
+ try { fs.unlinkSync(file); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ }
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 5c9a6411ad..d277d9214a 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2957,6 +2957,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
error?: string;
skills?: import('../main/skillhub/scanner').Skill[];
sources?: import('../main/skillhub/scanner').SourceReport[];
+ pendingCleanups?: Array<{ token: string; name: string }>;
}> => ipcRenderer.invoke('skillhub:scan', params),
readSkill: (params: {
diff --git a/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
index 33ba4ae213..ca22618e5b 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
@@ -8,6 +8,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigge
import { extractIpcError } from '@/utils/ipcError';
import { toast } from '@/lib/toast';
import { refresh } from '../hooks/useSkillhub';
+import { showUninstallCleanup } from '../lib/uninstallCleanupNotifications';
/** Local management for Skill details, independent of cloud ownership. */
export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
@@ -53,26 +54,7 @@ export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
return;
}
if (result.cleanupToken) {
- const token = result.cleanupToken;
- let retrying = false;
- const showCleanup = () => {
- const id = toast.warning(t('skillhub.management.cleanupIncomplete'), {
- duration: 0,
- action: { label: t('skillhub.management.retryCleanup'), onClick: () => {
- if (retrying) return;
- retrying = true;
- void window.electronAPI.skillhub.retryUninstallCleanup(token).then(({ complete }) => {
- if (complete) {
- toast.dismiss(id);
- toast.success(t('skillhub.management.cleanupComplete'));
- void refresh();
- }
- }).catch((error: unknown) => reportError(error, 'uninstallFailed'))
- .finally(() => { retrying = false; });
- } },
- });
- };
- showCleanup();
+ showUninstallCleanup(result.cleanupToken, skill.name, refresh);
} else {
toast.success(t('skillhub.detail.uninstalledToast', { name: skill.name }));
}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx b/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx
index 03713161a1..151e9b7960 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/LocalSkillControls.test.tsx
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
confirm: vi.fn(), setEnabled: vi.fn(), uninstall: vi.fn(), retry: vi.fn(), refresh: vi.fn(),
success: vi.fn(), error: vi.fn(), warning: vi.fn(), dismiss: vi.fn(),
}));
+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: mocks.confirm }) }));
vi.mock('../../hooks/useSkillhub', () => ({ refresh: mocks.refresh }));
@@ -13,6 +14,7 @@ vi.mock('@/lib/toast', () => ({ toast: {
success: mocks.success, error: mocks.error, warning: mocks.warning, dismiss: mocks.dismiss,
} }));
import { LocalSkillControls } from '../LocalSkillControls';
+import { resetUninstallCleanupNotices } from '../../lib/uninstallCleanupNotifications';
const skill = { id: 'global-example', name: 'example', kind: 'skill', absolutePath: '/fixture/.agents/skills/example',
scope: 'global', cindyEnabled: true, canUninstall: true } as SkillhubSkill;
@@ -24,6 +26,7 @@ async function chooseUninstall() {
}
beforeEach(() => {
+ resetUninstallCleanupNotices();
vi.clearAllMocks();
mocks.confirm.mockResolvedValue(true);
mocks.refresh.mockResolvedValue(undefined);
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
index b10dd50c2c..133094c7e1 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
@@ -1,6 +1,12 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { toast, type ToastOptions } from '@/lib/toast';
+
+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
+vi.mock('@/lib/toast', () => ({ toast: {
+ warning: vi.fn(() => 'cleanup-notice'), dismiss: vi.fn(), success: vi.fn(), error: vi.fn(),
+} }));
vi.mock('../useSkillSync', () => ({
registerSyncStoreSetters: vi.fn(),
@@ -32,6 +38,27 @@ describe('SkillHub data-owner bootstrap', () => {
expect(scan).toHaveBeenLastCalledWith({ projects: [] });
});
+ it('restores cleanup notices from scanning and invalidates old actions across owner changes', async () => {
+ reset();
+ const retry = vi.fn(async () => ({ complete: true }));
+ window.electronAPI.skillhub.retryUninstallCleanup = retry;
+ scan.mockResolvedValue({ success: true, skills: [], sources: [], pendingCleanups: [{ token: 'receipt', name: 'example' }] });
+ await refresh();
+ await refresh();
+ expect(toast.warning).toHaveBeenCalledOnce();
+ const firstAction = (vi.mocked(toast.warning).mock.calls[0]![1] as ToastOptions).action!;
+ setSkillhubDataOwner('another-owner');
+ firstAction.onClick();
+ expect(retry).not.toHaveBeenCalled();
+ await refresh();
+ const newAction = (vi.mocked(toast.warning).mock.calls.at(-1)![1] as ToastOptions).action!;
+ newAction.onClick();
+ await vi.waitFor(() => expect(retry).toHaveBeenCalledOnce());
+ expect(retry).toHaveBeenCalledWith('receipt');
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith('skillhub.management.cleanupComplete'));
+ reset();
+ });
+
it('makes a stale refresh wait for and return the newest scan result', async () => {
reset();
let resolveFirst!: (value: { success: true; skills: SkillhubSkill[]; sources: [] }) => void;
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
index ea1a22dcdc..abdce633d1 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
@@ -18,6 +18,7 @@
import { useEffect, useMemo, useState } from 'react';
import { skillhubCatalogKey } from '../../../../shared/skillhubCatalog';
+import { syncUninstallCleanupNotices, resetUninstallCleanupNotices } from '../lib/uninstallCleanupNotifications';
import { invalidateSkillSyncRequests, registerSyncStoreSetters } from './useSkillSync';
interface SkillhubProject {
@@ -89,6 +90,7 @@ export function refresh(): Promise<SkillhubSkill[]> {
return latestScan?.id === scanRequestId ? latestScan.promise : state.skills;
}
if (result.success) {
+ syncUninstallCleanupNotices(result.pendingCleanups ?? [], refresh);
const skills = result.skills ?? [];
setState({
skills,
@@ -196,6 +198,7 @@ export function setSyncError(err: string | null): void {
* owner's late result cannot repopulate the new owner's store.
*/
export function reset(): void {
+ resetUninstallCleanupNotices();
scanRequestId += 1;
latestScan = null;
invalidateSkillSyncRequests();
@@ -238,6 +241,7 @@ function ensureAuthListener(): void {
if (import.meta.hot) {
import.meta.hot.dispose(() => {
+ resetUninstallCleanupNotices();
authListenerUnsubscribe?.();
localStateListenerUnsubscribe?.();
authListenerUnsubscribe = null;
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/uninstallCleanupNotifications.ts b/apps/desktop/src/renderer/features/skillhub/lib/uninstallCleanupNotifications.ts
new file mode 100644
index 0000000000..c0ccdee54c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/uninstallCleanupNotifications.ts
@@ -0,0 +1,49 @@
+import { i18n } from '@/i18n';
+import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
+
+const notices = new Map<string, { id: string; retrying: boolean }>();
+
+export function showUninstallCleanup(token: string, name: string, refresh: () => Promise<unknown>): void {
+ if (notices.has(token)) return;
+ const notice = { id: '', retrying: false };
+ notices.set(token, notice);
+ notice.id = toast.warning(i18n.t('skillhub.management.cleanupIncomplete', { name }), {
+ duration: 0,
+ onClose: () => { if (notices.get(token) === notice) notices.delete(token); },
+ action: { label: i18n.t('skillhub.management.retryCleanup'), onClick: () => {
+ if (notices.get(token) !== notice || notice.retrying) return;
+ notice.retrying = true;
+ void window.electronAPI.skillhub.retryUninstallCleanup(token).then(({ complete }) => {
+ if (notices.get(token) !== notice) return;
+ if (complete) {
+ notices.delete(token);
+ toast.dismiss(notice.id);
+ toast.success(i18n.t('skillhub.management.cleanupComplete'));
+ void refresh();
+ }
+ }).catch((error: unknown) => {
+ if (notices.get(token) !== notice) return;
+ const code = extractIpcError(error)?.code;
+ toast.error(i18n.t(code === 'PRECONDITION_FAILED' || code === 'PERMISSION_DENIED'
+ ? 'skillhub.management.refreshRequired' : 'skillhub.management.uninstallFailed'));
+ }).finally(() => { notice.retrying = false; });
+ } },
+ });
+}
+
+export function syncUninstallCleanupNotices(pending: Array<{ token: string; name: string }>, refresh: () => Promise<unknown>): void {
+ const tokens = new Set(pending.map(({ token }) => token));
+ for (const [token, notice] of notices) {
+ if (tokens.has(token)) continue;
+ notices.delete(token);
+ toast.dismiss(notice.id);
+ }
+ for (const { token, name } of pending) showUninstallCleanup(token, name, refresh);
+}
+
+export function resetUninstallCleanupNotices(): void {
+ const old = [...notices.values()];
+ notices.clear();
+ for (const { id } of old) toast.dismiss(id);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 7f2008f7f5..280204f236 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11244,7 +11244,7 @@
"sharedImpact": "Other Agents sharing this skill will also be affected. Published versions and installations elsewhere are unaffected.",
"managedElsewhere": "This Skill belongs to another package or shared directory. Remove it at its source.",
"managedByPlugin": "This skill is provided by a plugin. Manage it on that plugin’s page.",
- "cleanupIncomplete": "The skill was removed, but some records or links remain. Retry before closing or reloading this window.",
+ "cleanupIncomplete": "Uninstall cleanup for “{{name}}” is unfinished. Retry now or reopen Skills later to continue. Reinstallation is paused until cleanup completes.",
"retryCleanup": "Retry cleanup",
"cleanupComplete": "Cleanup completed"
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 2105d9bcf3..1a9bccdef7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -11228,7 +11228,7 @@
"sharedImpact": "このスキルを共有する他の Agent にも影響します。公開済みバージョンや別の場所のインストールには影響しません。",
"managedElsewhere": "このスキルは別のパッケージまたは共有ディレクトリで管理されています。提供元で削除してください",
"managedByPlugin": "このスキルはプラグインが提供しています。提供元のプラグインページで管理してください。",
- "cleanupIncomplete": "スキルは削除されましたが、一部の記録やリンクが残っています。ウィンドウを閉じるか再読み込みする前に再試行してください。",
+ "cleanupIncomplete": "「{{name}}」のアンインストール後のクリーンアップが未完了です。再試行するか、後でスキルを開き直して続行してください。完了するまで再インストールはできません。",
"retryCleanup": "整理を再試行",
"cleanupComplete": "整理が完了しました"
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1f0697fa1b..c317f81125 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -11228,7 +11228,7 @@
"sharedImpact": "이 스킬을 공유하는 다른 Agent도 영향을 받습니다. 게시된 버전과 다른 위치에 설치된 스킬에는 영향을 주지 않습니다.",
"managedElsewhere": "이 스킬은 다른 패키지 또는 공유 디렉터리에서 관리됩니다. 원본 위치에서 제거하세요",
"managedByPlugin": "이 스킬은 플러그인이 제공합니다. 해당 플러그인 페이지에서 관리하세요.",
- "cleanupIncomplete": "스킬은 제거되었지만 일부 기록이나 링크가 남아 있습니다. 창을 닫거나 새로고침하기 전에 다시 시도하세요.",
+ "cleanupIncomplete": "“{{name}}”의 제거 정리가 완료되지 않았습니다. 다시 시도하거나 나중에 스킬을 다시 열어 계속하세요. 정리가 완료될 때까지 재설치할 수 없습니다.",
"retryCleanup": "정리 다시 시도",
"cleanupComplete": "정리 완료"
}
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index d3fbfa42b3..25732743fd 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -11228,7 +11228,7 @@
"sharedImpact": "共用此技能的其他 Agent 也会受影响。云端发布和其他安装位置不受影响。",
"managedElsewhere": "此技能由其他包或共享目录管理,需在其来源处移除",
"managedByPlugin": "此技能由插件提供,请到所属插件页面管理。",
- "cleanupIncomplete": "技能已移除,但部分记录或链接未清理完成。请在关闭或刷新窗口前重试。",
+ "cleanupIncomplete": "“{{name}}”的卸载清理尚未完成。请重试;重开技能中心后也可继续。清理完成前无法重新安装。",
"retryCleanup": "重试清理",
"cleanupComplete": "清理完成"
}
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index ff98bd439a..ca3f4f6bfa 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -11228,7 +11228,7 @@
"sharedImpact": "共用此技能的其他 Agent 也會受影響。雲端發布和其他安裝位置不受影響。",
"managedElsewhere": "此技能由其他套件或共用目錄管理,需在其來源處移除",
"managedByPlugin": "此技能由插件提供,請到所屬插件頁面管理。",
- "cleanupIncomplete": "技能已移除,但部分記錄或連結未清理完成。請在關閉或重新整理視窗前重試。",
+ "cleanupIncomplete": "「{{name}}」的解除安裝清理尚未完成。請重試;重新開啟技能中心後也可繼續。清理完成前無法重新安裝。",
"retryCleanup": "重試清理",
"cleanupComplete": "清理完成"
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 04bf4f0311..762ec5bcf0 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3170,6 +3170,7 @@ interface ElectronAPI {
error?: string;
skills?: SkillhubSkill[];
sources?: SkillhubSourceReport[];
+ pendingCleanups?: Array<{ token: string; name: string }>;
}>;
readSkill: (params: { mdPath: string }) => Promise<{
success: boolean;
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 5738d15c37..faf2b986cd 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -58,7 +58,8 @@
| Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 |
| 可丢弃的临时数据 | `app.getPath('temp')` 或 `os.tmpdir()` 下的任务专属目录 |
| 测试生成物 | `os.tmpdir()` 下通过 `mkdtemp` 创建的独立目录,并在测试结束时清理 |
-| 跨 profile 的共享 Skill 文件互斥 | `app.getPath('appData')/Cindy/shared-skill-mutation-locks`,仅存文件锁协议元数据,保证正式版/dev/isolated 共用;释放与崩溃回收复用既有跨进程锁协议 |
+| Skill 卸载清理回执 | `app.getPath('userData')/skillhub/uninstall-cleanups/<token>.json`,记录操作 owner、旧文件/注册/偏好身份与完成阶段;跨窗口和重启保留,当前 owner 重试完成后删除,不作为授权凭据 |
+| 跨 profile 的共享 Skill 文件互斥 | `app.getPath('appData')/Cindy/shared-skill-mutation-locks`,仅存文件锁及未完成操作的 token/名称哈希,保证正式版/dev/isolated 共用;短期锁复用既有崩溃回收,持久屏障必须等对应清理完成后删除,读取损坏只阻止相关名称 |
| 用户明确导出的文件 | 用户选择或任务明确指定的目标路径 |
- 禁止把 `process.cwd()`、仓库根或源码目录作为 userData、凭证目录或临时目录的默认回退。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index a10d6c6bf6..71be659bc4 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -41,7 +41,9 @@
的本地 IPC 可选携带 `skillId`,Main 同时匹配路径、当前发送窗口的扫描记录和项目授权,
缺省字段保留旧调用行为,不向 device-link 新开放管理能力。启停偏好仍按物理身份共享;
`activation-preferences.json` 的可选 `discoveryPaths` 按物理路径保存已扫描的绝对发现
- 路径数组;缺省兼容旧偏好。启动时复核指向,启用时删除该身份的入口记录,重命名时
+ 路径数组,可选 `revisions` 记录每次停用意图的代次;缺省兼容旧偏好。卸载清理只在
+ 设置锁内匹配原代次及入口快照后清除旧偏好,不覆盖后续启停。启动时复核指向,启用时
+ 删除该身份的入口记录,重命名时
同事务迁移到新入口。活动任务在启动时另存规范化物理身份快照,菜单过滤不重新解析
停用别名;同时冻结词法入口到物理身份的映射,在写原生配置前剔除改指向的入口,
使原生停用目标与菜单快照一致。插件托管技能只能在所属插件管理,详情禁用开关,Main 拒绝独立启停。
@@ -65,8 +67,18 @@
名称锁之外,安装、学习、导入、重命名、卸载及清理重试还持有跨进程 lease:复用现有文件锁协议,
在 Electron `appData/Cindy/shared-skill-mutation-locks` 下按归一名称的哈希共享锁文件,
不随正式版/dev/isolated profile 的 userData 改变。名字相同但目录不同也保守串行;
- 导入别名、重命名等多名称操作按同一顺序获取,拿不到锁不变更文件,等待系统回收站
- 及后续清理完成后才释放。锁只协调采用此协议的 Cindy 实例,不约束外部 CLI。
+ 导入别名、重命名等多名称操作按同一顺序获取,拿不到锁不变更文件。卸载覆盖物理源名
+ 及清理快照中每个发现别名;执行中的短期 lease 持有到本次清理尝试结束,未完成时以
+ `pending/<名称哈希>/<token>.json` 持久屏障继续阻止冲突写入,直到清理完成。进程退出
+ 只回收短期 lease,不删除屏障;屏障只存操作 token 和名称哈希,不存用户路径或账号。
+ 锁只协调采用此协议的 Cindy 实例,不约束外部 CLI。
+ 卸载在改动前将身份及副作用快照写入当前 profile 的 `skillhub/uninstall-cleanups`,
+ 先写回执、再建立屏障、再移到回收站;恢复不重放回收站操作,只按旧入口与目标身份逐项
+ 清理。注册记录在注册表锁内比较旧快照,来源恢复或替换时保留其链接、注册与偏好。
+ 清理完成状态必须先落盘,随后才移除屏障及回执;最终删除失败只重试收尾,不重放清理。
+ 窗口导航/关闭只撤销授权,不删除回执。`skillhub:scan` 可选返回当前 profile/data owner
+ 的 `pendingCleanups: [{ token, name }]`,并向当前窗口重新发放重试授权;不同窗口互不
+ 覆盖授权。此字段不开放远程管理能力。
卸载遇到目录大小写变体时按实际文件身份匹配清单,并使用清单原始名称清理记录及自动同步偏好。
原子编辑的 `*.xdt-tmp` 和重命名的 `SKILL.md.xdt-rename-<UUID>` 是内部保留文件,
共用 `packageIgnore` 从浏览、哈希、发布快照与 ZIP 中排除;即使备份清理被文件锁阻止,