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: coordinate skill mutations across clients and scan worktree details

xd-bobo2c409831fd10
diff --git a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts b/apps/desktop/src/main/learn-host/__tests__/controller.test.ts
index 37e11e9d08..d5f28ac330 100644
--- a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/learn-host/__tests__/controller.test.ts
@@ -13,6 +13,9 @@ import {
import type { ScanStagingResult } from '../staging';
import { computeProposalFingerprint } from '../stagingValidation.pure';
import { tryAcquireSkillInstallLock } from '../../skillhub/installLock';
+vi.mock('../../skillhub/sharedMutationLease', () => ({
+ acquireSharedSkillMutationLease: vi.fn(async () => async () => {}),
+}));
vi.mock('../../logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
@@ -1111,6 +1114,12 @@ describe('LearnController 状态机', () => {
releaseMarket();
}
+ const { acquireSharedSkillMutationLease } = await import('../../skillhub/sharedMutationLease');
+ vi.mocked(acquireSharedSkillMutationLease).mockResolvedValueOnce(null);
+ await expect(h.controller.apply('r1')).rejects.toMatchObject({ code: 'LEARN_BUSY' });
+ expect(h.applyCalls).toHaveLength(0);
+ expect(h.store.get('r1')!.status).toBe('awaiting-review');
+
// 不同名的市场安装不阻塞;同名锁释放后重试成功
const releaseUnrelated = tryAcquireSkillInstallLock('unrelated-skill', 'market-install')!;
try {
diff --git a/apps/desktop/src/main/learn-host/controller.ts b/apps/desktop/src/main/learn-host/controller.ts
index c1de599f6f..cb205d8dcf 100644
--- a/apps/desktop/src/main/learn-host/controller.ts
+++ b/apps/desktop/src/main/learn-host/controller.ts
@@ -34,6 +34,7 @@ import {
} from '../../shared/learnTypes';
import type { FileChange } from '../skillhub/snapshot';
import { getSkillInstallLockOwner, tryAcquireSkillInstallLock } from '../skillhub/installLock';
+import { acquireSharedSkillMutationLease, type SkillMutationRelease } from '../skillhub/sharedMutationLease';
import { prependHandoffToUserMessage } from '../maker-ipc/agentHandoff';
import type { EvidenceSearchFn } from './evidence';
import { collectEvidence } from './evidence';
@@ -896,6 +897,7 @@ export class LearnController {
const pausedWatcher = await this.pauseRevisionWatcherForApply(runId);
let frozenDir: string | null = null;
let releaseSkillLock: (() => void) | null = null;
+ let releaseShared: SkillMutationRelease | null = null;
let applied = false;
try {
this.assertNotDisposedForReview(runId);
@@ -942,6 +944,8 @@ export class LearnController {
run = await this.update(run, { skillName: verdict.skillName });
}
releaseSkillLock = this.acquireSkillApplyLock(verdict.skillName);
+ releaseShared = await acquireSharedSkillMutationLease([verdict.skillName]);
+ if (!releaseShared) throw new LearnError('LEARN_BUSY', 'another client is changing this skill');
// 必须先经 getProposalDiff 审查(reviewed 指纹已登记)且与当前提案一致。
// 只查"已定义且不等"会留一个窗:重扫刚把 reviewed 清空、面板还没刷新完,
// 这时点 apply 装的是没人看过的新内容(收严 Codex 的初版)。
@@ -984,6 +988,7 @@ export class LearnController {
await this.update(run, { status: 'applied' });
return result;
} finally {
+ await releaseShared?.();
releaseSkillLock?.();
// 失败路径(校验拒绝 / applyProposal 抛错回滚到冻结位)把提案放回 staging。
if (!applied) {
diff --git a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
index 1d73aabdcb..c5169e1da7 100644
--- a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
@@ -65,7 +65,7 @@ describe('Skill activation preferences', () => {
expect(reloaded.isCindySkillEnabled(source)).toBe(true);
});
- it.each(['success', 'enabled-source', 'backup-cleanup-failure', 'content-failure', 'preference-failure', 'owner-changed'])('migrates disabled state with a local rename (%s)', async (scenario) => {
+ it.each(['success', 'enabled-source', 'backup-cleanup-failure', 'content-failure', 'preference-failure', 'owner-changed', 'shared-busy'])('migrates disabled state with a local rename (%s)', async (scenario) => {
const { renameLocalSkill } = await import('../scanner');
const { setCindySkillEnabled, readDisabledSkillPaths, skillActivationKey } = await import('../activationPreferences');
const source = path.join(root, scenario, '.agents', 'skills', 'old-name');
@@ -76,6 +76,8 @@ describe('Skill activation preferences', () => {
await setCindySkillEnabled(scenario === 'enabled-source' ? destination : source, false);
const before = [...readDisabledSkillPaths()];
const oldKey = skillActivationKey(source);
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ const externalLease = scenario === 'shared-busy' ? await acquireSharedSkillMutationLease(['old-name']) : null;
const realRename = fs.renameSync;
const realUnlink = fs.unlinkSync;
const unlinkSpy = vi.spyOn(fs, 'unlinkSync').mockImplementation((file) => {
@@ -127,13 +129,13 @@ describe('Skill activation preferences', () => {
expect((await pack(destination)).sha256).toBe(packed.sha256);
}
} else {
- expect(injected).toBe(scenario !== 'owner-changed');
+ expect(injected).toBe(scenario !== 'owner-changed' && scenario !== 'shared-busy');
expect(result.success).toBe(false);
expect(fs.existsSync(destination)).toBe(false);
expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe(content);
expect(readDisabledSkillPaths()).toEqual(before);
}
- } finally { spy.mockRestore(); unlinkSpy.mockRestore(); }
+ } finally { spy.mockRestore(); unlinkSpy.mockRestore(); await externalLease?.(); }
});
});
diff --git a/apps/desktop/src/main/skillhub/__tests__/allowedProjectRoots.test.ts b/apps/desktop/src/main/skillhub/__tests__/allowedProjectRoots.test.ts
index 72dbec3a0c..ada93ad178 100644
--- a/apps/desktop/src/main/skillhub/__tests__/allowedProjectRoots.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/allowedProjectRoots.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest';
import { deriveAllowedSkillhubProjectRoots } from '../allowedProjectRoots';
describe('deriveAllowedSkillhubProjectRoots', () => {
- it('matches renderer grouping by folding managed and conventional worktrees to the base repo', () => {
+ it('allows both the grouped repo and real cwd of managed and conventional worktrees', () => {
const repo = path.resolve('/repo');
const normalizedRepo = repo.replaceAll(path.sep, '/');
@@ -13,6 +13,6 @@ describe('deriveAllowedSkillhubProjectRoots', () => {
path.join(repo, '.worktrees', 'user-task'),
repo,
null,
- ])).toEqual([normalizedRepo]);
+ ])).toEqual([normalizedRepo, `${normalizedRepo}/.cindy-worktrees/managed-task`, `${normalizedRepo}/.worktrees/user-task`]);
});
});
diff --git a/apps/desktop/src/main/skillhub/__tests__/importLocalSkill.test.ts b/apps/desktop/src/main/skillhub/__tests__/importLocalSkill.test.ts
index 834f573143..bfc04c9894 100644
--- a/apps/desktop/src/main/skillhub/__tests__/importLocalSkill.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/importLocalSkill.test.ts
@@ -70,6 +70,18 @@ async function writeZip(files: Record<string, string | Buffer>): Promise<string>
}
describe('importLocalSkill zip / installPath guards', () => {
+ it('does not import over a directory leased by another client', async () => {
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ const { importLocalSkill } = await import('../importLocalSkill');
+ const zipPath = await writeZip({ 'SKILL.md': '---\nname: leased-import\ndescription: fixture\n---\n' });
+ const target = path.join(TEST_ROOT, '.agents', 'skills', 'leased-import');
+ const release = await acquireSharedSkillMutationLease(['leased-import']);
+ try {
+ expect(await importLocalSkill({ filePath: zipPath, installPath: target })).toMatchObject({ success: false, errorCode: 'BUSY' });
+ expect(fs.existsSync(target)).toBe(false);
+ } finally { await release!(); }
+ });
+
it('inspect rejects an oversized SKILL.md before full-budget inflate', async () => {
const { inspectLocalSkill } = await import('../importLocalSkill');
const huge = `---
diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
index 9fb1d86a62..f6868c4145 100644
--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
@@ -2104,6 +2104,25 @@ describe('skillhub/installService', () => {
// ── 共享安装锁(与 learn apply 互斥) ───────────────────────────────────────
+ it('refuses installation and uninstall while another client holds the filesystem lease', async () => {
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ const { install, uninstall } = await import('../installService');
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const { shell } = await import('electron');
+ const finalDir = path.join(TEST_ROOT, '.agents', 'skills', 'external-client');
+ fs.mkdirSync(finalDir, { recursive: true });
+ fs.writeFileSync(path.join(finalDir, 'SKILL.md'), 'original');
+ const target = inspectLocalSkillTarget(finalDir, [finalDir])!;
+ const release = await acquireSharedSkillMutationLease(['external-client']);
+ expect(release).not.toBeNull();
+ try {
+ expect((await uninstall(finalDir, target)).success).toBe(false);
+ expect((await install({ name: 'external-client', installPath: finalDir, version: '1.0.0' }, () => {})).success).toBe(false);
+ expect(shell.trashItem).not.toHaveBeenCalled();
+ expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf8')).toBe('original');
+ } finally { await release!(); }
+ });
+
it('rejects install while a learn apply holds the shared lock; other names unaffected', async () => {
const { net } = await import('electron');
const { getCurrentUserId } = await import('../../authManager');
@@ -2283,6 +2302,9 @@ describe('skillhub/installService', () => {
} else {
let finishTrash: (() => void) | undefined;
vi.mocked(shell.trashItem).mockImplementationOnce(async (entry) => {
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ expect(await acquireSharedSkillMutationLease([aliasName])).toBeNull();
+ expect(await acquireSharedSkillMutationLease([sourceName])).toBeNull();
await new Promise<void>((resolve) => { finishTrash = resolve; });
await fs.promises.rename(entry, path.join(TEST_ROOT, 'trashed-alias'));
});
diff --git a/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts b/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts
new file mode 100644
index 0000000000..48c017251f
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/sharedMutationLease.test.ts
@@ -0,0 +1,42 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterAll, describe, expect, it, vi } from 'vitest';
+
+const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-skill-lease-'));
+vi.mock('electron', () => ({ app: { getPath: (name: string) => {
+ if (name !== 'appData') throw new Error('lease must not depend on profile-specific userData');
+ return root;
+} } }));
+vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() }) }));
+import { acquireSharedSkillMutationLease } from '../sharedMutationLease';
+afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
+
+describe('shared Skill mutation lease', () => {
+ 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();
+ try {
+ // This layer has no in-process holder map: exclusion is the filesystem protocol.
+ expect(await acquireSharedSkillMutationLease(['ALIAS'])).toBeNull();
+ const other = await acquireSharedSkillMutationLease(['unrelated']);
+ expect(other).not.toBeNull();
+ await other!();
+ } finally { await first!(); }
+ const next = await acquireSharedSkillMutationLease(['alias', 'ALIAS']);
+ expect(next).not.toBeNull();
+ await first!(); // Late release must not remove the successor's file.
+ try { expect(await acquireSharedSkillMutationLease(['alias'])).toBeNull(); }
+ finally { await next!(); }
+ });
+
+ it('releases earlier names if a later name is busy', async () => {
+ const held = await acquireSharedSkillMutationLease(['z-busy']);
+ try {
+ expect(await acquireSharedSkillMutationLease(['a-free', 'z-busy'])).toBeNull();
+ const free = await acquireSharedSkillMutationLease(['a-free']);
+ expect(free).not.toBeNull();
+ await free!();
+ } finally { await held!(); }
+ });
+});
diff --git a/apps/desktop/src/main/skillhub/allowedProjectRoots.ts b/apps/desktop/src/main/skillhub/allowedProjectRoots.ts
index 3eef421916..c49d1a30f9 100644
--- a/apps/desktop/src/main/skillhub/allowedProjectRoots.ts
+++ b/apps/desktop/src/main/skillhub/allowedProjectRoots.ts
@@ -1,7 +1,7 @@
import { and, eq, inArray, isNotNull, isNull } from 'drizzle-orm';
import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';
-import { normalizeWorkingDirForGrouping } from '../../shared/workingDir.js';
+import { normalizeWorkingDirForGrouping, normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import { getDbClient } from '../localDb/client/current';
import { sessions } from '../localDb/schema';
@@ -10,7 +10,7 @@ export function deriveAllowedSkillhubProjectRoots(
): string[] {
return [...new Set(
workingDirs
- .map((workingDir) => normalizeWorkingDirForGrouping(workingDir))
+ .flatMap((workingDir) => [normalizeWorkingDirForGrouping(workingDir), normalizeWorkingDirForStorage(workingDir)])
.filter((workingDir): workingDir is string => workingDir !== null),
)];
}
diff --git a/apps/desktop/src/main/skillhub/importLocalSkill.ts b/apps/desktop/src/main/skillhub/importLocalSkill.ts
index 8a10d2f0dd..c9b2caf855 100644
--- a/apps/desktop/src/main/skillhub/importLocalSkill.ts
+++ b/apps/desktop/src/main/skillhub/importLocalSkill.ts
@@ -34,6 +34,7 @@ import {
type SkillImportMetadata,
} from './importLocalSkill.pure.js';
import { getSkillInstallLockOwner, tryAcquireSkillInstallLock } from './installLock';
+import { acquireSharedSkillMutationLease, type SkillMutationRelease } from './sharedMutationLease';
import { ensureSymlinkToShared } from './installService';
import { registryService } from './registry';
@@ -456,6 +457,7 @@ export async function importLocalSkill(params: ImportLocalParams): Promise<Impor
const stagingDir = path.join(path.dirname(finalDir), `.xdt-importing-${name}-${rand()}`);
let replaceDir: string | null = null;
let finalDirCreated = false;
+ let releaseShared: SkillMutationRelease | null = null;
const rollback = async () => {
if (finalDirCreated) {
@@ -475,6 +477,8 @@ export async function importLocalSkill(params: ImportLocalParams): Promise<Impor
};
try {
+ releaseShared = await acquireSharedSkillMutationLease([name]);
+ if (!releaseShared) return { success: false, errorCode: 'BUSY', message: busyMessage(name) };
try {
await materialize(stagingDir);
} catch (err) {
@@ -579,6 +583,7 @@ export async function importLocalSkill(params: ImportLocalParams): Promise<Impor
...(projectWorkingDir ? { projectWorkingDir } : {}),
};
} finally {
+ await releaseShared?.();
releaseLock();
}
}
diff --git a/apps/desktop/src/main/skillhub/installLock.ts b/apps/desktop/src/main/skillhub/installLock.ts
index 2f9fb9bb65..1f9f215037 100644
--- a/apps/desktop/src/main/skillhub/installLock.ts
+++ b/apps/desktop/src/main/skillhub/installLock.ts
@@ -14,7 +14,8 @@
* 语义一致(市场侧返回"正在安装中"错误,learn 侧抛 LEARN_BUSY)。
* - 键为小写归一后的 skillName:自定义 installPath 同样按 name 互斥,
* 大小写敏感卷上的不同大小写名称也保守串行,不凭 OS 猜测卷的大小写语义。
- * - 进程内即可:市场安装与 learn 落盘都跑在 desktop main 进程。
+ * - 文件变更还需 sharedMutationLease 的跨进程锁;本模块只提供本进程的
+ * fail-fast 状态与持有方提示,不能单独保护正式版/dev/isolated 间的切换。
*/
/** 锁持有方标识 —— 对端获取失败时据此生成可理解的错误文案。 */
diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.ts
index 1451a55ca7..c6d778b47f 100644
--- a/apps/desktop/src/main/skillhub/installService.ts
+++ b/apps/desktop/src/main/skillhub/installService.ts
@@ -41,6 +41,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 {
prepareSharedGlobalSkillLinks,
prepareSharedProjectSkillLinks,
@@ -517,7 +518,14 @@ export async function install(
return false;
};
+ let releaseShared: SkillMutationRelease | null = null;
try {
+ releaseShared = await acquireSharedSkillMutationLease([p.name]);
+ if (!releaseShared) {
+ const message = skillLockBusyMessage(p.name);
+ onProgress({ phase: 'failed', name: p.name, errorCode: 'INTERNAL', message });
+ return { success: false, errorCode: 'INTERNAL', message };
+ }
// 链接拓扑必须在持锁后读取,避免 install / learn final-switch 之间的 TOCTOU。
const finalDir = await resolvePhysicalInstallDir(logicalFinalDir, p.name);
const stagingDir = path.join(path.dirname(finalDir), `.xdt-installing-${p.name}-${rand()}`);
@@ -915,6 +923,7 @@ export async function install(
...(projectWorkingDir ? { projectWorkingDir } : {}),
};
} finally {
+ await releaseShared?.();
inflight.delete(p.name);
releaseLock();
}
@@ -950,9 +959,10 @@ 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))];
// 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 new Set([skillName, path.basename(target?.operationPath ?? absolutePath)].map(skillInstallLockKey))) {
+ for (const lockName of lockNames) {
const release = tryAcquireSkillInstallLock(lockName, 'market-uninstall');
if (!release) {
for (const unlock of releaseLocks) unlock();
@@ -960,7 +970,10 @@ export async function uninstall(
}
releaseLocks.push(release);
}
+ let releaseShared: SkillMutationRelease | null = null;
try {
+ releaseShared = await acquireSharedSkillMutationLease(lockNames);
+ if (!releaseShared) return { success: false, errorCode: 'INTERNAL', message: skillLockBusyMessage(skillName) };
// Keep the exact registry identity for metadata cleanup after trash succeeds.
const registryMatch = target?.linkOnly
? (await registryService.listAllInstalls()).find((record) =>
@@ -985,6 +998,7 @@ export async function uninstall(
canMutate,
);
} finally {
+ await releaseShared?.();
for (const unlock of releaseLocks) unlock();
}
}
@@ -1175,11 +1189,14 @@ export async function retryUninstallCleanup(token: string, canMutate: () => bool
if (!cleanup) return true;
const release = tryAcquireSkillInstallLock(cleanup.skillName, 'market-uninstall');
if (!release) return false;
+ let releaseShared: 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 { release(); }
+ } finally { await releaseShared?.(); release(); }
}
async function shouldRecordAutoSyncIgnore(skillName: string, registryEntry: StoredInstall, userId?: string): Promise<boolean> {
diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.ts
index a64e382fb9..66de700e66 100644
--- a/apps/desktop/src/main/skillhub/scanner.ts
+++ b/apps/desktop/src/main/skillhub/scanner.ts
@@ -1,5 +1,6 @@
import { isCindySkillEnabled, renameSkillWithActivation } from './activationPreferences';
import { skillInstallLockKey, tryAcquireSkillInstallLock } from './installLock';
+import { acquireSharedSkillMutationLease, type SkillMutationRelease } from './sharedMutationLease';
import { inspectLocalSkillTarget, isPluginManagedSkillPath } from './localSkillTarget';
/**
* SkillHub Scanner — 商店层 (registry / market) 视图组装。
@@ -889,7 +890,10 @@ export async function renameLocalSkill(params: {
const backupPath = `${newSkillMd}.xdt-rename-${randomUUID()}`;
let renamed = false;
let backedUp = false;
+ let releaseShared: SkillMutationRelease | null = null;
try {
+ releaseShared = await acquireSharedSkillMutationLease([oldName, newName]);
+ if (!releaseShared) return { success: false, error: 'Skill is busy; retry after the current operation' };
await renameSkillWithActivation(absolutePath, newAbsolutePath, () => {
if (!canMutate()) throw new Error('Skill mutation context changed');
// Recheck after waiting for the preferences lock; never replace a new entity.
@@ -932,6 +936,7 @@ export async function renameLocalSkill(params: {
}
return { success: false, error: `Skill rename failed: ${String(err)}` };
} finally {
+ await releaseShared?.();
releases.forEach((unlock) => unlock());
}
}
diff --git a/apps/desktop/src/main/skillhub/sharedMutationLease.ts b/apps/desktop/src/main/skillhub/sharedMutationLease.ts
new file mode 100644
index 0000000000..b086c98c77
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/sharedMutationLease.ts
@@ -0,0 +1,51 @@
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import { app } from 'electron';
+import { withCrossProcessLock } from '../device-link/crossProcessLock';
+import { createLogger } from '../logger';
+import { skillInstallLockKey } from './installLock';
+
+const log = createLogger('skillhub:shared-mutation');
+export type SkillMutationRelease = () => Promise<void>;
+
+/**
+ * All Desktop profiles share native Skill directories. Keep the lease root
+ * outside profile-specific userData. Names conservatively serialize the same
+ * final basename across every install location, like the in-process lock.
+ * Import aliases and rename operations acquire all affected names in order.
+ */
+export async function acquireSharedSkillMutationLease(
+ names: readonly string[],
+): Promise<SkillMutationRelease | null> {
+ let root: string;
+ try {
+ root = path.join(app.getPath('appData'), 'Cindy', 'shared-skill-mutation-locks');
+ fs.mkdirSync(root, { recursive: true });
+ } catch {
+ log.warn('Skill mutation lock directory is unavailable');
+ return null;
+ }
+ const keys = [...new Set(names.map(skillInstallLockKey))].sort();
+ let enter!: (release: SkillMutationRelease | null) => void;
+ const entered = new Promise<SkillMutationRelease | null>((resolve) => { enter = resolve; });
+ let release!: () => void;
+ const released = new Promise<void>((resolve) => { release = resolve; });
+ let finished: Promise<void>;
+ const acquire = async (index: number): Promise<void> => {
+ if (index === keys.length) {
+ enter(async () => { release(); await finished; });
+ await released;
+ return;
+ }
+ const key = createHash('sha256').update(keys[index]!).digest('hex');
+ await withCrossProcessLock(path.join(root, `${key}.lock`),
+ { label: 'skill-mutation', waitMs: 0 }, async (status) => {
+ if (status.held) await acquire(index + 1);
+ });
+ };
+ finished = acquire(0).catch(() => {
+ log.warn('Skill mutation lock could not be acquired or released');
+ }).finally(() => { enter(null); });
+ return entered;
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
index 6a58e384cd..68977bf366 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
@@ -20,6 +20,7 @@
import { useEffect, useMemo, useRef } from 'react';
import { Outlet } from 'react-router-dom';
import { skillhubCatalogKey } from '../../../shared/skillhubCatalog';
+import { normalizeWorkingDirForStorage } from '../../../shared/workingDir';
import { useCCSessions } from '@/hooks/useCCSessions';
import { groupSessions } from '@/features/cc-agent/lib/projectGrouping';
@@ -135,13 +136,16 @@ export function useSkillhubStoreSync(): void {
const skillhubProjects = useMemo<SkillhubProject[] | null>(() => {
if (sessionsLoading) return null;
const { projects } = groupSessions(sessions, { includePinnedInProjects: true, includeDraftsInProjects: true });
- return projects
- .filter((p) => p.scope === 'local')
- .map((p) => ({
- projectRoot: p.workingDir,
- hash: projectHash(p.workingDir),
- displayName: p.displayName,
- }));
+ const catalogue = new Map<string, SkillhubProject>();
+ for (const project of projects.filter((p) => p.scope === 'local')) {
+ const roots = [project.workingDir, ...project.sessions.map((s) => normalizeWorkingDirForStorage(s.workingDir))];
+ for (const root of roots) {
+ if (!root || catalogue.has(root)) continue;
+ catalogue.set(root, { projectRoot: root, hash: projectHash(root),
+ displayName: root === project.workingDir ? project.displayName : `${project.displayName} · ${root.split('/').at(-1)}` });
+ }
+ }
+ return [...catalogue.values()];
}, [sessions, sessionsLoading]);
useEffect(() => {
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx
index 3e4ed99858..079b11c36f 100644
--- a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx
@@ -29,6 +29,9 @@ it('keeps pinned and newly created local project directories in the scan catalog
mocks.sessions = [
session('pinned', '/repo/pinned', { pinnedAt: '2026-09-08T01:00:00Z' }),
session('created', '/repo/created', { userSendAt: null }),
+ session('worktree', '/repo/base/.cindy-worktrees/task'),
+ session('legacy-worktree', '/repo/base/.xdt-worktrees/legacy'),
+ session('user-worktree', '/repo/base/.worktrees/custom'),
session('ssh', '/remote', { remoteHostId: 'ssh-host', pinnedAt: '2026-09-08T01:00:00Z' }),
];
const { rerender } = renderHook(useSkillhubStoreSync);
@@ -36,10 +39,14 @@ it('keeps pinned and newly created local project directories in the scan catalog
mocks.loading = false;
rerender();
const projects = mocks.syncProjects.mock.lastCall![0];
- expect(projects).toHaveLength(2);
+ expect(projects).toHaveLength(6);
expect(projects).toEqual(expect.arrayContaining([
expect.objectContaining({ projectRoot: '/repo/pinned', hash: projectHash('/repo/pinned') }),
expect.objectContaining({ projectRoot: '/repo/created', hash: projectHash('/repo/created') }),
+ expect.objectContaining({ projectRoot: '/repo/base', hash: projectHash('/repo/base') }),
+ expect.objectContaining({ projectRoot: '/repo/base/.cindy-worktrees/task', hash: projectHash('/repo/base/.cindy-worktrees/task') }),
+ expect.objectContaining({ projectRoot: '/repo/base/.xdt-worktrees/legacy', hash: projectHash('/repo/base/.xdt-worktrees/legacy') }),
+ expect.objectContaining({ projectRoot: '/repo/base/.worktrees/custom', hash: projectHash('/repo/base/.worktrees/custom') }),
]));
mocks.sessions = mocks.sessions.map((item) => ({ ...item, pinnedAt: null }));
rerender();
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 6fabb8971a..5738d15c37 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -58,6 +58,7 @@
| 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 共用;释放与崩溃回收复用既有跨进程锁协议 |
| 用户明确导出的文件 | 用户选择或任务明确指定的目标路径 |
- 禁止把 `process.cwd()`、仓库根或源码目录作为 userData、凭证目录或临时目录的默认回退。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7d78b00abc..a10d6c6bf6 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -52,6 +52,8 @@
同源多副本按范围和最近项目匹配;旧路径无法唯一消歧时不任意选择副本。SkillHub
项目目录包含置顶任务和已创建但尚未发消息的项目任务,不沿用侧栏的展示排除规则;
仍只扫描本地目录,并由 Main 的项目目录白名单复核。
+ worktree 同时保留分组后的基仓与任务实际 cwd:分组路径只作目录归并,不能代替
+ 原生技能发现路径。Renderer 项目目录和 Main 白名单使用同样的两组路径,排除远程任务。
扫描结果可选携带按物理路径关联的 `registrySkillName`,市场详情按此原始注册 slug
与 catalog scope 匹配;保留实际目录名用于本地展示。未注册或旧扫描缺少该字段时,
只按精确名称匹配,不用大小写折叠推断两个目录属于同一市场技能。
@@ -59,8 +61,13 @@
实体卸载;检查覆盖入口、发现根及引擎配置目录各级,拒绝其中的符号链接,保留发现
布局以上的已跟踪项目别名兼容。外部入口移除及清理重试保留源文件和按物理身份共享的
停用偏好。安装、学习、导入、重命名及卸载共用小写归一的名称锁,一次操作的多个锁名
- 按相同规则去重;大小写敏感卷上的同名大小写变体也保守互斥。卸载遇到目录大小写
- 变体时按实际文件身份匹配清单,并使用清单原始名称清理记录及自动同步偏好。
+ 按相同规则去重;大小写敏感卷上的同名大小写变体也保守互斥。
+ 名称锁之外,安装、学习、导入、重命名、卸载及清理重试还持有跨进程 lease:复用现有文件锁协议,
+ 在 Electron `appData/Cindy/shared-skill-mutation-locks` 下按归一名称的哈希共享锁文件,
+ 不随正式版/dev/isolated profile 的 userData 改变。名字相同但目录不同也保守串行;
+ 导入别名、重命名等多名称操作按同一顺序获取,拿不到锁不变更文件,等待系统回收站
+ 及后续清理完成后才释放。锁只协调采用此协议的 Cindy 实例,不约束外部 CLI。
+ 卸载遇到目录大小写变体时按实际文件身份匹配清单,并使用清单原始名称清理记录及自动同步偏好。
原子编辑的 `*.xdt-tmp` 和重命名的 `SKILL.md.xdt-rename-<UUID>` 是内部保留文件,
共用 `packageIgnore` 从浏览、哈希、发布快照与 ZIP 中排除;即使备份清理被文件锁阻止,
也不得上传旧内容,不因清理失败回滚已经提交的重命名与偏好。