Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(skillhub): serialize background maintenance with uninstall transactions
xd-boboe529734fd35f
diff --git a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.tsindex e3309266fd..c3541786f9 100644--- a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts+++ b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts@@ -1,7 +1,13 @@import os from 'node:os';import path from 'node:path';-import { promises as fs } from 'node:fs';-import { afterEach, describe, expect, it, vi } from 'vitest';+import nodeFs, { promises as fs } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';++const lockRoot = nodeFs.mkdtempSync(path.join(os.tmpdir(), 'cindy-projection-locks-'));+vi.mock('electron', () => ({ app: { getPath: () => lockRoot } }));+vi.mock('../logger', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() }) }));+import { acquireSharedSkillMutationLease } from '../skillhub/sharedMutationLease';import {prepareSharedGlobalSkillLinks,@@ -38,10 +44,96 @@ async function sameRealPath(a: string, b: string): Promise<boolean> {}afterEach(async () => {+ vi.restoreAllMocks();const dirs = tmpDirs;tmpDirs = [];await Promise.all(dirs.map((dir) => fs.rm(dir, { recursive: true, force: true })));});+afterAll(() => nodeFs.rmSync(lockRoot, { recursive: true, force: true }));++describe('shared Skill projection mutations', () => {+ it.each(['global', 'project'] as const)('blocks %s projection for a pending uninstall, then permits its installing caller', async (scope) => {+ const root = await makeTmpDir();+ const name = randomUUID();+ const paths = sharedGlobalSkillsPaths(root);+ const source = await writeSkill(paths.sharedSkillsDir, name);+ const project = async () => scope === 'global'+ ? prepareSharedGlobalSkillLinks({ homeDir: root, isCrossAgentSyncEnabled: () => false })+ : prepareSharedProjectSkillLinks({ workingDir: root });+ const token = randomUUID();+ const initial = (await acquireSharedSkillMutationLease([name]))!;+ initial.retainUntilComplete(token);+ await initial();+ expect((await project()).changed).toBe(false);+ await expect(fs.lstat(path.join(paths.claudeSkillsDir, name))).rejects.toMatchObject({ code: 'ENOENT' });+ const owner = (await acquireSharedSkillMutationLease([name], token))!;+ try {+ owner.complete(token);+ expect((await project()).changed).toBe(false); // An independent window still cannot write.+ expect((await owner.run(project)).changed).toBe(true);+ expect(await sameRealPath(source, path.join(paths.claudeSkillsDir, name))).toBe(true);+ } finally { await owner(); }+ });++ it('locks the physical basename when projecting a differently named external alias', async () => {+ const root = await makeTmpDir();+ const paths = sharedGlobalSkillsPaths(root);+ const name = randomUUID();+ const alias = randomUUID();+ const source = await writeSkill(path.join(root, 'external'), name);+ await fs.mkdir(paths.sharedSkillsDir, { recursive: true });+ await fs.symlink(source, path.join(paths.sharedSkillsDir, alias), process.platform === 'win32' ? 'junction' : 'dir');+ const lease = (await acquireSharedSkillMutationLease([name]))!;+ try {+ const result = await prepareSharedGlobalSkillLinks({ homeDir: root, isCrossAgentSyncEnabled: () => false });+ expect(result.changed).toBe(false);+ await expect(fs.lstat(path.join(paths.claudeSkillsDir, alias))).rejects.toMatchObject({ code: 'ENOENT' });+ } finally { await lease(); }+ });++ it('revalidates the source after the final awaited mkdir before linking', async () => {+ const root = await makeTmpDir();+ const paths = sharedGlobalSkillsPaths(root);+ const name = randomUUID();+ const source = await writeSkill(paths.sharedSkillsDir, name);+ const mkdir = fs.mkdir;+ vi.spyOn(fs, 'mkdir').mockImplementation(async (...args: Parameters<typeof mkdir>) => {+ const result = await mkdir(...args);+ if (String(args[0]) === paths.claudeSkillsDir) {+ await fs.rename(source, `${source}-old`);+ await mkdir(source);+ }+ return result;+ });+ await expect(prepareSharedProjectSkillLinks({ workingDir: root })).rejects.toThrow('Skill source changed');+ await expect(fs.lstat(path.join(paths.claudeSkillsDir, name))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('preserves a broken link replaced while the cleanup reads its previous target', async () => {+ const root = await makeTmpDir();+ const paths = sharedGlobalSkillsPaths(root);+ const name = randomUUID();+ const link = path.join(paths.claudeSkillsDir, name);+ const nextTarget = path.join(paths.sharedSkillsDir, `${name}-new`);+ await fs.mkdir(paths.claudeSkillsDir, { recursive: true });+ await fs.symlink(path.join(paths.sharedSkillsDir, name), link, process.platform === 'win32' ? 'junction' : 'dir');+ const readlink = fs.readlink;+ let replaced = false;+ vi.spyOn(fs, 'readlink').mockImplementation(async (...args: Parameters<typeof readlink>) => {+ const result = await readlink(...args);+ if (!replaced && String(args[0]) === link) {+ replaced = true;+ await fs.unlink(link);+ await fs.symlink(nextTarget, link, process.platform === 'win32' ? 'junction' : 'dir');+ }+ return result;+ });+ await prepareSharedProjectSkillLinks({ workingDir: root });+ expect(replaced).toBe(true);+ expect((await fs.lstat(link)).isSymbolicLink()).toBe(true);+ expect(await readlink(link)).toContain(`${name}-new`);+ });+});describe('prepareSharedGlobalSkillLinks', () => {it('does not pull other-agent skills into the shared index by default (opt-in gate, #2930)', async () => {diff --git a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts b/apps/desktop/src/main/learn-host/__tests__/controller.test.tsindex d5f28ac330..a410a487c9 100644--- a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/learn-host/__tests__/controller.test.ts@@ -14,7 +14,9 @@ import type { ScanStagingResult } from '../staging';import { computeProposalFingerprint } from '../stagingValidation.pure';import { tryAcquireSkillInstallLock } from '../../skillhub/installLock';vi.mock('../../skillhub/sharedMutationLease', () => ({- acquireSharedSkillMutationLease: vi.fn(async () => async () => {}),+ acquireSharedSkillMutationLease: vi.fn(async () => Object.assign(async () => {}, {+ run: <T>(operation: () => Promise<T>) => operation(),+ })),}));vi.mock('../../logger', () => ({diff --git a/apps/desktop/src/main/learn-host/controller.ts b/apps/desktop/src/main/learn-host/controller.tsindex cb205d8dcf..e82c72a7b9 100644--- a/apps/desktop/src/main/learn-host/controller.ts+++ b/apps/desktop/src/main/learn-host/controller.ts@@ -975,13 +975,14 @@ export class LearnController {runId: run.runId,};this.assertNotDisposedForReview(runId);- const result = await this.deps.applyProposal({- proposalDir: frozenDir,+ const proposalDir = frozenDir;+ const result = await releaseShared.run(() => this.deps.applyProposal({+ proposalDir,// 用重校验后的 verdict 名(string 且为冻结副本的真实值;run.skillName 经// update 重赋值后类型收窄丢失,语义上两者已一致)skillName: verdict.skillName,provenance,- });+ }));applied = true;this.detachWatcher(runId);await this.deps.staging.cleanup(runId);diff --git a/apps/desktop/src/main/maker-host/shared-global-skills.ts b/apps/desktop/src/main/maker-host/shared-global-skills.tsindex aa028420fb..93caf01e62 100644--- a/apps/desktop/src/main/maker-host/shared-global-skills.ts+++ b/apps/desktop/src/main/maker-host/shared-global-skills.ts@@ -1,6 +1,6 @@import os from 'node:os';import path from 'node:path';-import { promises as fsp } from 'node:fs';+import fs, { promises as fsp } from 'node:fs';type LinkStatus = 'linked' | 'kept' | 'conflict' | 'skipped' | 'error';@@ -12,6 +12,7 @@ interface SkillEntry {path: string;realPath: string;isSymlink: boolean;+ identity: string;}interface LinkAction {@@ -56,6 +57,28 @@ interface PrepareProjectOptions {workingDir: string;}+// Keep read-only path helpers importable outside Electron. Actual mutations+// resolve the Main-owned lease only when they execute.+async function withLinkMutation<T>(names: string[], operation: () => Promise<T>): Promise<T | undefined> {+ const { withSkillMutation } = await import('../skillhub/sharedMutationLease');+ return withSkillMutation(names, operation);+}++function sourceIdentity(file: string): string | null {+ try {+ const stat = fs.statSync(file);+ return JSON.stringify([normalizeForCompare(fs.realpathSync.native(file)), stat.dev, stat.ino, stat.birthtimeMs]);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw error;+ }+}++function linkIdentity(file: string): string {+ const stat = fs.lstatSync(file);+ return JSON.stringify([stat.dev, stat.ino, stat.birthtimeMs, fs.readlinkSync(file)]);+}+function normalizeForCompare(value: string): string {const resolved = path.resolve(value);return process.platform === 'win32' ? resolved.toLowerCase() : resolved;@@ -151,8 +174,13 @@ async function listSkillEntries(const skillPath = path.join(rootPath, ent.name);if (!(await hasSkillFile(skillPath))) continue;- const realPath = await realPathOrNull(skillPath);- if (!realPath) continue;+ let realPath: string;+ let identity: string | null;+ try {+ realPath = normalizeForCompare(fs.realpathSync.native(skillPath));+ identity = sourceIdentity(skillPath);+ } catch { continue; }+ if (!identity) continue;skills.push({name: ent.name,@@ -160,6 +188,7 @@ async function listSkillEntries(path: skillPath,realPath,isSymlink: ent.isSymbolicLink(),+ identity,});}return skills;@@ -203,6 +232,8 @@ async function cleanupBrokenManagedLinks(if (!ent.isSymbolicLink()) continue;const linkPath = path.join(rootPath, ent.name);+ let identity: string;+ try { identity = linkIdentity(linkPath); } catch { continue; }if (await realPathOrNull(linkPath)) continue;let targetPath: string;@@ -222,12 +253,16 @@ async function cleanupBrokenManagedLinks();if (!pointsIntoCurrentRoots && !matchesMovedProjectLink) continue;- assertMutationAllowed?.();try {- await fsp.unlink(linkPath);- changed = true;+ const removed = await withLinkMutation([ent.name, path.basename(targetPath)], async () => {+ if (linkIdentity(linkPath) !== identity || sourceIdentity(linkPath) !== null) return false;+ assertMutationAllowed?.();+ fs.unlinkSync(linkPath);+ return true;+ });+ changed = removed === true || changed;} catch {- // Broken symlink cleanup is best-effort; later link creation will report conflicts if needed.+ // Replaced entries and inaccessible paths are not proof of a broken link.}}return changed;@@ -302,12 +337,13 @@ async function linkEntriesIntoRoot(}const targetPath = path.join(targetRoot, entry.name);- const result = await ensureDirectoryLink(- entry,- targetPath,- useRelativeTarget,- assertMutationAllowed,- );+ const result = await withLinkMutation([entry.name, path.basename(entry.realPath)], async () => {+ if (sourceIdentity(entry.path) !== entry.identity) return { status: 'skipped' as const, changed: false };+ return ensureDirectoryLink(entry, targetPath, useRelativeTarget, () => {+ assertMutationAllowed?.();+ if (sourceIdentity(entry.path) !== entry.identity) throw new Error('Skill source changed during link projection');+ });+ }) ?? { status: 'skipped' as const, changed: false };changed = changed || result.changed;const action: LinkAction = {name: entry.name,diff --git a/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts b/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.tsindex 6a14cac92f..fecd9ee81e 100644--- a/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts@@ -1,13 +1,15 @@import path from 'node:path';import os from 'node:os';import fs from 'node:fs';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { randomUUID } from 'node:crypto';import { net } from 'electron';import { getCurrentUserId } from '../../authManager';import type { StoredInstall } from '../registry/types';import { registryService } from '../registry';import { parseAutoSyncConfig, SkillhubAutoSyncService } from '../autoSyncService';import type { install as installFn } from '../installService';+import { acquireSharedSkillMutationLease } from '../sharedMutationLease';type InstallResult = Awaited<ReturnType<typeof installFn>>;type SuccessfulInstallResult = Extract<InstallResult, { success: true }>;@@ -24,13 +26,13 @@ const loggerMocks = vi.hoisted(() => ({warn: vi.fn(),}));const originalAutoSyncConfigUrl = process.env.XDT_SKILLHUB_AUTO_SYNC_CONFIG_URL;-const TEST_ROOT = path.join('/tmp', 'xdt-auto-sync-test');+const TEST_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-auto-sync-test-'));const TEST_HOME = path.join(TEST_ROOT, 'home');const TEST_USER_DATA = path.join(TEST_ROOT, 'userData');vi.mock('electron', () => ({app: {- getPath: vi.fn(() => path.join('/tmp', 'xdt-auto-sync-test', 'userData')),+ getPath: vi.fn(() => TEST_USER_DATA),},net: {fetch: vi.fn(),@@ -151,6 +153,33 @@ function makeService(options: {}describe('SkillhubAutoSyncService', () => {+ afterAll(() => fs.rmSync(TEST_ROOT, { recursive: true, force: true }));++ it('defers automatic cancellation cleanup behind a pending uninstall and retries after release', async () => {+ vi.mocked(registryService.removeInstall).mockResolvedValue(undefined);+ const installPath = path.join(TEST_HOME, '.agents', 'skills', 'alpha');+ fs.mkdirSync(installPath, { recursive: true });+ fs.writeFileSync(path.join(installPath, 'SKILL.md'), 'fixture');+ const token = randomUUID();+ const lease = (await acquireSharedSkillMutationLease(['alpha']))!;+ lease.retainUntilComplete(token);+ await lease();+ const store = path.join(TEST_USER_DATA, 'skillhub', 'auto-sync-pending-cleanups.json');+ fs.mkdirSync(path.dirname(store), { recursive: true });+ fs.writeFileSync(store, JSON.stringify({ schemaVersion: 1, cleanups: [{ slug: 'alpha', absolutePath: installPath }] }));+ const setup = makeService({ useDefaultCleanupInstall: true, configSkills: [] });+ await setup.service.runOnceAfterLogin();+ expect(fs.existsSync(installPath)).toBe(true);+ expect(fs.existsSync(store)).toBe(true);+ expect(registryService.removeInstall).not.toHaveBeenCalled();+ const resumed = (await acquireSharedSkillMutationLease(['alpha'], token))!;+ resumed.complete(token);+ await resumed();+ await setup.service.runOnceAfterLogin();+ expect(fs.existsSync(installPath)).toBe(false);+ expect(fs.existsSync(store)).toBe(false);+ });+beforeEach(() => {vi.clearAllMocks();fs.rmSync(TEST_ROOT, { recursive: true, force: true });diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.tsindex 487f81d964..2531a8d530 100644--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts@@ -197,6 +197,36 @@ describe('skillhub/installService', () => {expect(isCindySkillEnabled(source)).toBe(true);});+ it('serializes an in-flight scanner repair before uninstall snapshots and removes its completed link', async () => {+ const { source, target } = await localFixture('scanner-race');+ const { registryService } = await import('../registry');+ const { reconcileScannedInstall } = await import('../registryReconciliation');+ const { uninstall } = await import('../installService');+ const { shell } = await import('electron');+ const entry = { version: '1.0.0', catalogScope: 'market' } as import('../registry').StoredInstall;+ let entered!: () => void;+ const checking = new Promise<void>((resolve) => { entered = resolve; });+ let resume!: () => void;+ const waiting = new Promise<void>((resolve) => { resume = resolve; });+ vi.mocked(registryService.getInstall).mockImplementationOnce(async () => {+ entered();+ await waiting;+ return entry;+ });+ const repair = reconcileScannedInstall({ skillName: 'scanner-race', installPath: source, entry }, false);+ await checking;+ try {+ expect((await uninstall(source, target)).success).toBe(false);+ expect(shell.trashItem).not.toHaveBeenCalled();+ } finally { resume(); await repair; }+ const link = path.join(TEST_ROOT, '.claude', 'skills', 'scanner-race');+ expect(fs.existsSync(link)).toBe(true);+ expect(await uninstall(source, target)).toEqual({ success: true });+ expect(fs.existsSync(source)).toBe(false);+ expect(() => fs.lstatSync(link)).toThrow();+ expect(shell.trashItem).toHaveBeenCalledTimes(1);+ });+it('preserves files, registry and disabled state when system trash fails', async () => {const { source, target } = await localFixture('trash-failure');const { shell } = await import('electron');diff --git a/apps/desktop/src/main/skillhub/__tests__/registryReconciliation.test.ts b/apps/desktop/src/main/skillhub/__tests__/registryReconciliation.test.tsnew file mode 100644index 0000000000..6690f27f19--- /dev/null+++ b/apps/desktop/src/main/skillhub/__tests__/registryReconciliation.test.ts@@ -0,0 +1,107 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { randomUUID } from 'node:crypto';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';++const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-scan-maintenance-'));+vi.mock('electron', () => ({ app: { getPath: () => root } }));+vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+vi.mock('../registry', () => ({ registryService: { getInstall: vi.fn(), removeInstall: vi.fn() } }));+import { registryService, type StoredInstall } from '../registry';+import { reconcileScannedInstall } from '../registryReconciliation';+import { acquireSharedSkillMutationLease } from '../sharedMutationLease';++afterEach(() => vi.restoreAllMocks());+afterAll(() => fs.rmSync(root, { recursive: true, force: true }));++function fixture(existing = true) {+ const skillName = randomUUID();+ const installPath = path.join(root, '.agents', 'skills', skillName);+ if (existing) fs.mkdirSync(installPath, { recursive: true });+ const entry = { version: '1.0.0', catalogScope: 'market' } as StoredInstall;+ vi.mocked(registryService.getInstall).mockResolvedValue(entry);+ vi.mocked(registryService.removeInstall).mockClear();+ return { record: { skillName, installPath, entry }, link: path.join(root, '.claude', 'skills', skillName) };+}++describe('background registry maintenance', () => {+ it('holds the mutation lease across async registry checks and the final Claude link write', async () => {+ const { record, link } = fixture();+ let checked!: () => void;+ const checking = new Promise<void>((resolve) => { checked = resolve; });+ let resume!: () => void;+ const waiting = new Promise<void>((resolve) => { resume = resolve; });+ vi.mocked(registryService.getInstall).mockImplementationOnce(async () => {+ checked();+ await waiting;+ return record.entry;+ });+ const repair = reconcileScannedInstall(record, false);+ await checking;+ try { expect(await acquireSharedSkillMutationLease([record.skillName])).toBeNull(); }+ finally { resume(); await repair; }+ expect(fs.realpathSync(link)).toBe(fs.realpathSync(record.installPath));+ const next = await acquireSharedSkillMutationLease([record.skillName]);+ expect(next).not.toBeNull();+ await next!();+ });++ it('cannot create a late link while an uninstall receipt is pending, including after restart', async () => {+ const { record, link } = fixture();+ const token = randomUUID();+ const lease = (await acquireSharedSkillMutationLease([record.skillName]))!;+ lease.retainUntilComplete(token);+ await lease();+ vi.resetModules();+ const restarted = await import('../registryReconciliation');+ await restarted.reconcileScannedInstall(record, false);+ expect(fs.existsSync(link)).toBe(false);+ const resumed = (await acquireSharedSkillMutationLease([record.skillName], token))!;+ fs.renameSync(record.installPath, `${record.installPath}-trashed`);+ vi.mocked(registryService.getInstall).mockResolvedValue(null);+ resumed.complete(token);+ await resumed();+ await restarted.reconcileScannedInstall(record, false);+ expect(() => fs.lstatSync(link)).toThrow();+ });++ it.each(['registry', 'source'] as const)('rejects a stale %s snapshot before creating a link', async (change) => {+ const { record, link } = fixture();+ vi.mocked(registryService.getInstall).mockImplementationOnce(async () => {+ if (change === 'registry') return { ...record.entry, version: '2.0.0' };+ fs.renameSync(record.installPath, `${record.installPath}-old`);+ fs.mkdirSync(record.installPath);+ return record.entry;+ });+ await reconcileScannedInstall(record, false);+ expect(fs.existsSync(link)).toBe(false);+ });++ it('preserves an unrelated existing Claude link', async () => {+ const { record, link } = fixture();+ const external = path.join(root, randomUUID());+ fs.mkdirSync(external);+ fs.mkdirSync(path.dirname(link), { recursive: true });+ fs.symlinkSync(external, link, process.platform === 'win32' ? 'junction' : 'dir');+ await reconcileScannedInstall(record, false);+ expect(fs.realpathSync(link)).toBe(fs.realpathSync(external));+ });++ it('does not remove an orphan record if its source is restored during the registry read', async () => {+ const { record } = fixture(false);+ vi.mocked(registryService.getInstall).mockImplementationOnce(async () => {+ fs.mkdirSync(record.installPath, { recursive: true });+ return record.entry;+ });+ await reconcileScannedInstall(record, true);+ expect(registryService.removeInstall).not.toHaveBeenCalled();+ });++ it('treats access failure as an unknown source, never an orphan', async () => {+ const { record } = fixture();+ vi.spyOn(fs, 'statSync').mockImplementationOnce(() => { throw Object.assign(new Error('denied'), { code: 'EACCES' }); });+ await reconcileScannedInstall(record, true);+ expect(registryService.removeInstall).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanner.test.tsindex 83ee2f8413..1941683fed 100644--- a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts@@ -6,6 +6,7 @@ import os from 'node:os';vi.mock('../registry', () => ({registryService: {listAllInstalls: vi.fn(async () => []),+ getInstall: vi.fn(async () => null),removeInstall: vi.fn(async () => undefined),},}));diff --git a/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts b/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.tsindex 55992874bd..641ab42e6f 100644--- a/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts@@ -10,10 +10,49 @@ vi.mock('electron', () => ({ app: { getPath: (name: string) => {return root;} } }));vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() }) }));-import { acquireSharedSkillMutationLease } from '../sharedMutationLease';+import { acquireSharedSkillMutationLease, withSkillMutation } from '../sharedMutationLease';afterAll(() => fs.rmSync(root, { recursive: true, force: true }));describe('shared Skill mutation lease', () => {+ it('borrows only the current call chain and keeps an unawaited child locked until it finishes', async () => {+ const lease = (await acquireSharedSkillMutationLease(['parent']))!;+ let finishChild!: () => void;+ const waiting = new Promise<void>((resolve) => { finishChild = resolve; });+ let child!: Promise<unknown>;+ await lease.run(async () => {+ expect(await withSkillMutation(['PARENT', 'extra'], async () => 'nested')).toBe('nested');+ child = withSkillMutation(['parent'], () => waiting);+ });+ expect(await withSkillMutation(['parent'], async () => 'independent')).toBeUndefined();+ let released = false;+ const releasing = lease().then(() => { released = true; });+ try {+ expect(await acquireSharedSkillMutationLease(['parent'])).toBeNull();+ expect(released).toBe(false);+ } finally {+ finishChild();+ await child;+ await releasing;+ }+ expect(await withSkillMutation(['parent'], async () => 'next')).toBe('next');+ });++ it('does not borrow an expired async context after its lease has been released', async () => {+ const lease = (await acquireSharedSkillMutationLease(['expired']))!;+ let resume!: () => void;+ const waiting = new Promise<void>((resolve) => { resume = resolve; });+ let delayed!: Promise<unknown>;+ await lease.run(async () => {+ delayed = waiting.then(() => withSkillMutation(['expired'], async () => 'stale'));+ });+ await lease();+ const successor = (await acquireSharedSkillMutationLease(['expired']))!;+ try {+ resume();+ expect(await delayed).toBeUndefined();+ } finally { await successor(); }+ });+it('contains a damaged durable barrier to its own resource name', async () => {const token = randomUUID();const key = createHash('sha256').update('damaged-receipt').digest('hex');diff --git a/apps/desktop/src/main/skillhub/autoSyncService.ts b/apps/desktop/src/main/skillhub/autoSyncService.tsindex 9384deb9fd..c89760d6f5 100644--- a/apps/desktop/src/main/skillhub/autoSyncService.ts+++ b/apps/desktop/src/main/skillhub/autoSyncService.ts@@ -16,6 +16,7 @@ import * as installService from './installService';import { SkillhubMarketService } from './marketService';import { listIgnoredAutoSyncSkills, recordAutoSyncCandidateSkills } from './autoSyncPreferences';import { registryService } from './registry';+import { withSkillMutation } from './sharedMutationLease';import type { StoredInstall } from './registry/types';import { skillhubCatalogKey, type SkillhubCatalogScope } from '../../shared/skillhubCatalog';@@ -785,7 +786,19 @@ function normalizeForCompare(value: string): string {return process.platform === 'win32' ? normalized.toLowerCase() : normalized;}-async function cleanupAutoSyncedGlobalInstall({+async function cleanupAutoSyncedGlobalInstall(params: CancelledInstallCleanup): Promise<void> {+ const names = [params.slug, path.basename(params.absolutePath)];+ if (params.previousInstall) names.push(params.previousInstall.skillName, path.basename(params.previousInstall.installPath));+ const completed = await withSkillMutation(names, async () => {+ await cleanupAutoSyncedGlobalInstallUnderLease(params);+ return true;+ });+ // The existing cancellation journal retries this cleanup; a busy lease must+ // not be reported as success and silently discard that pending work.+ if (!completed) throw new Error('another client is changing this skill');+}++async function cleanupAutoSyncedGlobalInstallUnderLease({slug,absolutePath,previousInstall,diff --git a/apps/desktop/src/main/skillhub/importLocalSkill.ts b/apps/desktop/src/main/skillhub/importLocalSkill.tsindex c9b2caf855..fc0eba6ab1 100644--- a/apps/desktop/src/main/skillhub/importLocalSkill.ts+++ b/apps/desktop/src/main/skillhub/importLocalSkill.ts@@ -558,14 +558,14 @@ export async function importLocalSkill(params: ImportLocalParams): Promise<Impor}}- const projectWorkingDir = await reconcileProjectLinks(finalDir);+ const projectWorkingDir = await releaseShared.run(() => reconcileProjectLinks(finalDir));try {const ownerId = getCurrentDataOwnerId();const linkResult = await withSharedGlobalSkillProjectionMutation(ownerId, () =>- prepareSharedGlobalSkillLinks({+ releaseShared!.run(() => prepareSharedGlobalSkillLinks({assertOwnerStable: () =>assertGhostSkillProjectionBoundaryStableForOwner(ownerId),- }),+ })),);for (const warning of linkResult.warnings) {log.warn('[importLocal] shared global skill link warning:', warning);diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.tsindex a641a79ecb..cf3eae241f 100644--- a/apps/desktop/src/main/skillhub/installService.ts+++ b/apps/desktop/src/main/skillhub/installService.ts@@ -904,14 +904,14 @@ export async function install(log.warn('[skillInstall] claude symlink failed (non-fatal):', claudeLink, err);}}- const projectWorkingDir = await reconcileProjectSkillLinksForPaths(logicalFinalDir, finalDir);+ const projectWorkingDir = await releaseShared.run(() => reconcileProjectSkillLinksForPaths(logicalFinalDir, finalDir));try {const ownerId = getCurrentDataOwnerId();const linkResult = await withSharedGlobalSkillProjectionMutation(ownerId, () =>- prepareSharedGlobalSkillLinks({+ releaseShared!.run(() => prepareSharedGlobalSkillLinks({assertOwnerStable: () =>assertGhostSkillProjectionBoundaryStableForOwner(ownerId),- }),+ })),);for (const warning of linkResult.warnings) {log.warn('[skillInstall] shared global skill link warning:', warning);@@ -1091,8 +1091,17 @@ async function uninstallLocked(const allowed = () => ownerId === getCurrentDataOwnerId() && canMutate();const recordIgnore = !!(registryMatch && await shouldRecordAutoSyncIgnore(skillName, registryMatch.entry, cloudUserId ?? undefined));const wasIgnored = recordIgnore && (await listIgnoredAutoSyncSkills(cloudUserId ?? undefined)).has(skillName);+ const knownEntries = [...(target?.aliases ?? []), absolutePath, resolved,+ ...(registryMatch ? [registryMatch.installPath] : [])];+ // A repair can finish after the UI scan but before this lease. Include the+ // sibling discovery entries for each known scope in the locked snapshot.+ const compatibilityEntries = knownEntries.flatMap((entry) => {+ if (!/\/\.(?:agents|claude|codex)\/skills\/[^/]+$/.test(entry.replace(/\\/g, '/'))) return [];+ const base = path.dirname(path.dirname(path.dirname(entry)));+ return ['.agents', '.claude', '.codex'].map((root) => path.join(base, root, 'skills', path.basename(entry)));+ });const candidates = target?.linkOnly ? [...new Set([...target.aliases, target.operationPath])] : [...new Set([- ...(target?.aliases ?? []), absolutePath, ...(registryMatch ? [registryMatch.installPath] : []),+ ...knownEntries, ...compatibilityEntries,path.join(os.homedir(), '.claude', 'skills', skillName),path.join(os.homedir(), '.codex', 'skills', skillName),path.join(os.homedir(), '.agents', 'skills', skillName),diff --git a/apps/desktop/src/main/skillhub/registryReconciliation.ts b/apps/desktop/src/main/skillhub/registryReconciliation.tsnew file mode 100644index 0000000000..e2822467ca--- /dev/null+++ b/apps/desktop/src/main/skillhub/registryReconciliation.ts@@ -0,0 +1,44 @@+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import { createLogger } from '../logger';+import { registryService, type StoredInstall } from './registry';+import { withSkillMutation } from './sharedMutationLease';+import { fileIdentity } from './uninstallJournal';++const log = createLogger('skillhub:registry-reconciliation');++/** Background scan maintenance is a writer too; stale scan snapshots grant no writes. */+export async function reconcileScannedInstall(+ record: { skillName: string; installPath: string; entry: StoredInstall },+ orphan: boolean,+): Promise<void> {+ try {+ const sourceIdentity = fileIdentity(record.installPath, true);+ const source = sourceIdentity ? fs.realpathSync.native(record.installPath) : record.installPath;+ await withSkillMutation([record.skillName, path.basename(record.installPath), path.basename(source)], async () => {+ const current = await registryService.getInstall(record.skillName, record.installPath);+ if (JSON.stringify(current) !== JSON.stringify(record.entry)+ || fileIdentity(record.installPath, true) !== sourceIdentity) return;+ if (sourceIdentity === null) {+ if (orphan) await registryService.removeInstall(record.skillName, record.installPath, {+ expected: record.entry, canMutate: () => true,+ shouldRemove: () => fileIdentity(record.installPath, true) === null,+ });+ return;+ }+ const index = record.installPath.replace(/\\/g, '/').lastIndexOf('/.agents/skills/');+ if (index < 0) return;+ const base = record.installPath.slice(0, index);+ const link = path.join(base || os.homedir(), '.claude', 'skills', record.skillName);+ // Existing entries belong to their current owner, including external links.+ if (fileIdentity(link) !== null) return;+ // Keep final validation and link creation synchronous inside the lease.+ fs.mkdirSync(path.dirname(link), { recursive: true });+ if (fileIdentity(record.installPath, true) !== sourceIdentity) return;+ fs.symlinkSync(record.installPath, link, process.platform === 'win32' ? 'junction' : 'dir');+ });+ } catch (error) {+ log.warn('Skill registry maintenance deferred:', error);+ }+}diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.tsindex 66de700e66..253fba1066 100644--- a/apps/desktop/src/main/skillhub/scanner.ts+++ b/apps/desktop/src/main/skillhub/scanner.ts@@ -25,6 +25,7 @@ import path from 'node:path';import matter from 'gray-matter';import type { AgentCustomization, Maker, PiRuntimeCapabilityStatus } from '@cindy/maker-core';import { registryService, type StoredInstall } from './registry';+import { reconcileScannedInstall } from './registryReconciliation';import { isIgnoredSkillPackagePath } from './packageIgnore';import { createLogger } from '../logger';@@ -392,60 +393,12 @@ export async function scanAllSkills(liveRealPaths.add(normPath);}- // ── orphan cleanup (fire-and-forget) ───────────────────────────────────────- // 只删除磁盘上目录已不存在的条目;未被当前 scan 覆盖但目录仍在的不算孤儿- // (可能只是该项目不在本次 workingDirs 里)。- const orphans = registryEntries.filter((r) => {- const installPathKey = path.normalize(r.installPath);- return !liveRealPaths.has(registryLiveKeys.get(installPathKey) ?? installPathKey);- });- if (orphans.length > 0) {- void Promise.all(- orphans.map(async (o) => {- try {- await fs.promises.access(o.installPath);- } catch {- await registryService.removeInstall(o.skillName, o.installPath).catch((err) =>- log.warn(`orphan cleanup failed for ${o.skillName}@${o.installPath}:`, err),- );- }- }),- );- }-- // ── Claude symlink repair (fire-and-forget) ────────────────────────────────- // 存量安装可能缺少 .claude/skills/ symlink(Codex 原生扫 .agents/ 但 Claude 只扫 .claude/)。- // 每次 scan 时检测并补建,确保 Claude Code 能稳定发现。- void Promise.all(- registryEntries- .filter((r) => /[/\\]\.agents[/\\]skills[/\\]/.test(r.installPath))- .map(async (r) => {- try {- await fs.promises.access(r.installPath);- } catch { return; }- const agentsIdx = r.installPath.replace(/\\/g, '/').lastIndexOf('/.agents/skills/');- if (agentsIdx < 0) return;- const base = r.installPath.slice(0, agentsIdx);- const claudeLink = path.join(base || os.homedir(), '.claude', 'skills', r.skillName);- try {- const stat = await fs.promises.lstat(claudeLink);- if (stat.isSymbolicLink()) {- const target = path.resolve(path.dirname(claudeLink), await fs.promises.readlink(claudeLink));- if (path.normalize(target) === path.normalize(r.installPath)) return;- await fs.promises.unlink(claudeLink);- } else {- return;- }- } catch (err) {- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return;- }- await fs.promises.mkdir(path.dirname(claudeLink), { recursive: true });- await fs.promises.symlink(- r.installPath, claudeLink,- process.platform === 'win32' ? 'junction' : 'dir',- ).catch((e) => log.warn(`claude symlink repair failed for ${r.skillName}:`, e));- }),- );+ // Maintenance uses the same mutation protocol as install/uninstall and+ // revalidates each registry/source snapshot after acquiring the lease.+ void Promise.all(registryEntries.map((record) => {+ const key = path.normalize(record.installPath);+ return reconcileScannedInstall(record, !liveRealPaths.has(registryLiveKeys.get(key) ?? key));+ }));// ── sources[] 兼容 (renderer 只存不读) ─────────────────────────────────────const sources: SourceReport[] = listed.errors.map((e) => ({diff --git a/apps/desktop/src/main/skillhub/sharedMutationLease.ts b/apps/desktop/src/main/skillhub/sharedMutationLease.tsindex ecc2d40ded..aac5bead8e 100644--- a/apps/desktop/src/main/skillhub/sharedMutationLease.ts+++ b/apps/desktop/src/main/skillhub/sharedMutationLease.ts@@ -1,4 +1,5 @@import { createHash } from 'node:crypto';+import { AsyncLocalStorage } from 'node:async_hooks';import fs from 'node:fs';import path from 'node:path';import { app } from 'electron';@@ -9,6 +10,7 @@ import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFilconst log = createLogger('skillhub:shared-mutation');export type SkillMutationRelease = (() => Promise<void>) & {+ run<T>(operation: () => Promise<T>): Promise<T>;/** Keep conflicting writers out after releasing the process lease. */retainUntilComplete(token: string): void;complete(token: string): void;@@ -23,6 +25,28 @@ export function isSkillMutationToken(value: unknown): value is string {}interface PendingMutation { token: string; keys: string[] }+interface MutationContext {+ names: string[];+ active(): boolean;+ run<T>(operation: () => Promise<T>): Promise<T>;+}+const mutationContext = new AsyncLocalStorage<MutationContext[]>();++/** Nested projections reuse only leases in their own async call chain. */+export async function withSkillMutation<T>(names: readonly string[], operation: () => Promise<T>): Promise<T | undefined> {+ const requested = skillMutationNames(names);+ const held = (mutationContext.getStore() ?? []).filter((lease) => lease.active()+ && requested.some((name) => lease.names.includes(name)));+ const missing = requested.filter((name) => !held.some((lease) => lease.names.includes(name)));+ // Borrowing pins the underlying lease until the child finishes, even if its+ // caller starts releasing the lease without awaiting that child.+ const run = held.reduceRight<() => Promise<T>>((next, lease) => () => lease.run(next), operation);+ if (!missing.length) return run();+ const lease = await acquireSharedSkillMutationLease(missing);+ if (!lease) return undefined;+ try { return await lease.run(run); }+ finally { await lease(); }+}function readPending(root: string, keys: string[]): PendingMutation[] {// Read only the held resource names: a damaged receipt must not block unrelated Skills.@@ -81,10 +105,38 @@ export async function acquireSharedSkillMutationLease(if (readPending(root, keys).some((record) => record.keys.some((key) => keys.includes(key))&& !(record.token === pendingToken && matchesKeys(record)))) return;let active = true;+ let closing = false;+ let borrowers = 0;+ let drained: (() => void) | undefined;+ const context: MutationContext = {+ names: skillMutationNames(names),+ active: () => active && !closing,+ async run<T>(operation: () => Promise<T>): Promise<T> {+ if (!context.active()) throw new Error('Skill mutation lease is no longer held');+ borrowers++;+ try {+ const inherited = mutationContext.getStore() ?? [];+ return await mutationContext.run(inherited.includes(context) ? inherited : [...inherited, context], operation);+ } finally {+ if (--borrowers === 0) drained?.();+ }+ },+ };const assertActive = (token: string) => {- if (!active || !isSkillMutationToken(token)) throw new Error('Skill mutation lease is no longer held');+ if (!context.active() || !isSkillMutationToken(token)) throw new Error('Skill mutation lease is no longer held');};- const leased = Object.assign(async () => { active = false; release(); await finished; }, {+ let releasePromise: Promise<void> | undefined;+ const leased = Object.assign(() => {+ if (!releasePromise) releasePromise = (async () => {+ closing = true;+ if (borrowers > 0) await new Promise<void>((resolve) => { drained = resolve; });+ active = false;+ release();+ await finished;+ })();+ return releasePromise;+ }, {+ run: context.run,retainUntilComplete(token: string) {assertActive(token);const existing = readPending(root, keys).filter((record) => record.token === token);diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 71be659bc4..e229f1c08f 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -72,6 +72,12 @@`pending/<名称哈希>/<token>.json` 持久屏障继续阻止冲突写入,直到清理完成。进程退出只回收短期 lease,不删除屏障;屏障只存操作 token 和名称哈希,不存用户路径或账号。锁只协调采用此协议的 Cindy 实例,不约束外部 CLI。+ 后台扫描补链、孤儿注册清理及原生发现根的补链/断链清理也必须参与同一 lease,+ 并在锁内重验注册快照及源/入口文件身份,不能根据锁外扫描结果直接写入。安装、+ 导入、学习流程中的嵌套补链只复用当前异步调用链仍有效的 lease,释放要等借用者结束;+ 独立窗口及释放后的迟到回调必须重新获取,拿不到锁的维护留待下次扫描。+ 卸载持锁后的快照包含每个已知 scope 的同名兼容入口,覆盖 UI 扫描后刚完成的补链。+ 自动同步的取消/失效清理同样获取 lease;锁被占用时交回既有重试流程,不当作清理成功。卸载在改动前将身份及副作用快照写入当前 profile 的 `skillhub/uninstall-cleanups`,先写回执、再建立屏障、再移到回收站;恢复不重放回收站操作,只按旧入口与目标身份逐项清理。注册记录在注册表锁内比较旧快照,来源恢复或替换时保留其链接、注册与偏好。