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(worktree): stop polluting global git safe.directory (#3207)

Tsai Yuan1aa9c68a825d
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
index 9274045750..8e6aa89e44 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
@@ -14,6 +14,7 @@ import type { WorktreeMeta } from '../worktree/types';
import { withWorktreeRestoreMutation } from '../worktree/restoreLock';
const gitExecMock = vi.fn();
+const crossProcessLockMock = vi.fn();
const isWorktreeDirtyMock = vi.fn();
const autoStashMock = vi.fn();
const restoreAutoStashMock = vi.fn();
@@ -22,6 +23,7 @@ const ignoredFilesMock = vi.fn();
const changedIncludeFilesMock = vi.fn();
const storeSetMock = vi.fn();
const storeMap = new Map<string, WorktreeMeta>();
+const pendingSafeDirectoryCleanups: string[] = [];
const liveSessionRows: Array<{
id: string;
status: string | null;
@@ -33,6 +35,15 @@ let liveSessionLookupError: Error | null = null;
vi.mock('../worktree/gitExec', () => ({
gitExec: (...args: unknown[]) => gitExecMock(...args),
GitExecError: class GitExecError extends Error {},
+ globalSafeDirectoryLockPath: () => '/tmp/cindy-git-safe-directory.lock',
+ safeDirectorySpellings: (p: string) => {
+ const normalized = process.platform === 'win32' ? p.replace(/\\/g, '/') : p;
+ return normalized === p ? [p] : [normalized, p];
+ },
+}));
+
+vi.mock('../device-link/crossProcessLock', () => ({
+ withCrossProcessLock: (...args: unknown[]) => crossProcessLockMock(...args),
}));
vi.mock('../worktree/dirty', () => ({
@@ -57,6 +68,18 @@ vi.mock('../worktree/worktreeStore', () => ({
),
set: (...args: unknown[]) => storeSetMock(...args),
del: vi.fn((sessionId: string) => storeMap.delete(sessionId)),
+ getPendingSafeDirectoryCleanups: () => [...pendingSafeDirectoryCleanups],
+ addPendingSafeDirectoryCleanups: (paths: readonly string[]) => {
+ for (const p of paths) {
+ if (p && !pendingSafeDirectoryCleanups.includes(p)) pendingSafeDirectoryCleanups.push(p);
+ }
+ },
+ removePendingSafeDirectoryCleanups: (paths: readonly string[]) => {
+ const toRemove = new Set(paths);
+ for (let i = pendingSafeDirectoryCleanups.length - 1; i >= 0; i -= 1) {
+ if (toRemove.has(pendingSafeDirectoryCleanups[i])) pendingSafeDirectoryCleanups.splice(i, 1);
+ }
+ },
}));
vi.mock('../localDb/client/current', () => ({
@@ -94,6 +117,7 @@ describe('removeWorktreeForSession', () => {
beforeEach(async () => {
vi.clearAllMocks();
storeMap.clear();
+ pendingSafeDirectoryCleanups.length = 0;
liveSessionRows.length = 0;
liveSessionRows.push({
id: '__unrelated_active_session__',
@@ -111,6 +135,10 @@ describe('removeWorktreeForSession', () => {
}
return { stdout: '', stderr: '' };
});
+ crossProcessLockMock.mockReset().mockImplementation(
+ (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>
+ task({ held: true }),
+ );
isWorktreeDirtyMock.mockReset().mockResolvedValue(false);
autoStashMock.mockReset().mockResolvedValue(true);
restoreAutoStashMock.mockReset().mockResolvedValue(true);
@@ -1021,6 +1049,120 @@ describe('removeWorktreeForSession', () => {
}
});
+ it('discard pre-created: cleans the generated quarantine path from global safe.directory', async () => {
+ const tmpRoot = fsSync.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-safedir-'));
+ try {
+ const base = path.join(tmpRoot, 'repo');
+ const worktreePath = path.join(base, '.xdt-worktrees', 's1');
+ fsSync.mkdirSync(worktreePath, { recursive: true });
+ const meta: WorktreeMeta = { ...makeMeta('s1'), baseRepo: base, path: worktreePath };
+ storeMap.set('s1', meta);
+
+ await expect(manager.discardPrecreatedWorktree('s1', worktreePath)).resolves.toEqual({
+ status: 'discarded',
+ branchDeleted: false,
+ });
+
+ // 本轮 preserveDirty 现场生成的 .xdt-removing-* 路径
+ const moveCalls = gitExecMock.mock.calls.filter(
+ ([args]) => Array.isArray(args) && args[0] === 'worktree' && args[1] === 'move',
+ );
+ expect(moveCalls).toHaveLength(1);
+ const quarantinePath = moveCalls[0][0][3] as string;
+
+ // 原路径与本轮生成路径都要从全局 safe.directory 精确清理(#2627)
+ expect(gitExecMock).toHaveBeenCalledWith([
+ 'config',
+ '--global',
+ '--unset-all',
+ '--fixed-value',
+ 'safe.directory',
+ worktreePath,
+ ]);
+ expect(gitExecMock).toHaveBeenCalledWith([
+ 'config',
+ '--global',
+ '--unset-all',
+ '--fixed-value',
+ 'safe.directory',
+ quarantinePath,
+ ]);
+ } finally {
+ fsSync.rmSync(tmpRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('defers safe.directory cleanup to the store when the global lock is not acquired', async () => {
+ crossProcessLockMock.mockImplementation(
+ (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>
+ task({ held: false, reason: 'busy' }),
+ );
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+
+ await manager.removeWorktreeForSession('s1');
+
+ // 目录已删、store.del 已执行; 拿不到锁时不得做无锁 --unset-all, 而是落盘待下次启动补清
+ expect(
+ gitExecMock.mock.calls.some(
+ ([args]) => Array.isArray(args) && args.includes('--unset-all'),
+ ),
+ ).toBe(false);
+ expect(pendingSafeDirectoryCleanups).toContain(meta.path);
+ });
+
+ it('reconcilePendingSafeDirectoryCleanups drains pending entries under the lock', async () => {
+ const gonePath = path.join(BASE_REPO, '.xdt-worktrees', 'gone');
+ pendingSafeDirectoryCleanups.push(gonePath);
+ crossProcessLockMock.mockImplementation(
+ (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>
+ task({ held: true }),
+ );
+
+ await manager.reconcilePendingSafeDirectoryCleanups();
+
+ expect(gitExecMock).toHaveBeenCalledWith([
+ 'config',
+ '--global',
+ '--unset-all',
+ '--fixed-value',
+ 'safe.directory',
+ gonePath,
+ ]);
+ expect(pendingSafeDirectoryCleanups).toEqual([]);
+ });
+
+ it('reconcile skips and drops pending paths re-created by a live worktree', async () => {
+ // 旧删除留下的待办 + 同名新 worktree 已在 store 里占用该路径
+ const reusedPath = path.join(BASE_REPO, '.xdt-worktrees', 'reused');
+ const orphanPath = path.join(BASE_REPO, '.xdt-worktrees', 'orphan');
+ pendingSafeDirectoryCleanups.push(reusedPath, orphanPath);
+ storeMap.set('s-new', { ...makeMeta('reused'), path: reusedPath });
+ crossProcessLockMock.mockImplementation(
+ (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>
+ task({ held: true }),
+ );
+
+ await manager.reconcilePendingSafeDirectoryCleanups();
+
+ // 复用路径: 不 --unset-all(条目归新 worktree), 只从待办移除
+ expect(
+ gitExecMock.mock.calls.some(
+ ([args]) => Array.isArray(args) && args.includes(reusedPath),
+ ),
+ ).toBe(false);
+ // 孤儿路径: 正常清理并出队
+ expect(gitExecMock).toHaveBeenCalledWith([
+ 'config',
+ '--global',
+ '--unset-all',
+ '--fixed-value',
+ 'safe.directory',
+ orphanPath,
+ ]);
+ expect(pendingSafeDirectoryCleanups).toEqual([]);
+ });
+
it('does not move a worktree when quarantine state cannot be persisted', async () => {
const tmpRoot = fsSync.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-quarantine-persist-'));
try {
@@ -1082,7 +1224,9 @@ describe('removeWorktreeForSession', () => {
['update-ref', '-d', `refs/heads/${meta.branch}`, 'abc123'],
BASE_REPO,
);
- expect(gitOperations).toEqual([
+ // config 是 safe.directory 清理的副作用, 其次数随平台拼写数(POSIX 1 次 / Windows
+ // 正反斜杠 2 次)变化, 不参与这里的顺序断言。
+ expect(gitOperations.filter((op) => op !== 'config')).toEqual([
'symbolic-ref',
'worktree',
'rev-parse',
diff --git a/apps/desktop/src/main/__tests__/worktreeStore.test.ts b/apps/desktop/src/main/__tests__/worktreeStore.test.ts
index 189a2f2539..e146040568 100644
--- a/apps/desktop/src/main/__tests__/worktreeStore.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeStore.test.ts
@@ -2,17 +2,29 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { WorktreeMeta } from '../worktree/types';
-const backingStore = { worktrees: {} as Record<string, WorktreeMeta> };
+// 按 store 文件名隔离的后备数据: worktrees.json 与 worktree-safe-directory-cleanup.json
+// 是两个物理文件, 单测同样按 name 隔离, 验证队列写入不会碰 worktrees 键。
+const storesByName = new Map<string, Record<string, unknown>>();
const setWorktreePathInDbMock = vi.fn();
vi.mock('electron-store', () => ({
default: class MockStore {
- get(key: 'worktrees', fallback: Record<string, WorktreeMeta>) {
- return backingStore[key] ?? fallback;
+ constructor(opts: { name?: string } = {}) {
+ this.name = opts.name ?? 'default';
+ if (!storesByName.has(this.name)) storesByName.set(this.name, {});
}
- set(key: 'worktrees', value: Record<string, WorktreeMeta>) {
- backingStore[key] = value;
+ name: string;
+
+ get(key: string, fallback: unknown) {
+ const backing = storesByName.get(this.name) ?? {};
+ return backing[key] ?? fallback;
+ }
+
+ set(key: string, value: unknown) {
+ const backing = storesByName.get(this.name) ?? {};
+ backing[key] = value;
+ storesByName.set(this.name, backing);
}
},
}));
@@ -21,9 +33,18 @@ vi.mock('../localDb/ipc/sessions', () => ({
setWorktreePathInDb: (...args: unknown[]) => setWorktreePathInDbMock(...args),
}));
+// 队列读改写走跨进程锁; 单测里直通持锁, 聚焦合并/去重语义, 不落真实锁文件。
+vi.mock('../device-link/crossProcessLock', () => ({
+ withCrossProcessLock: (
+ _lockPath: string,
+ _opts: unknown,
+ task: (status: unknown) => Promise<unknown>,
+ ) => task({ held: true }),
+}));
+
describe('worktreeStore', () => {
beforeEach(async () => {
- backingStore.worktrees = {};
+ storesByName.clear();
setWorktreePathInDbMock.mockReset();
vi.resetModules();
});
@@ -47,4 +68,42 @@ describe('worktreeStore', () => {
expect(store.get(meta.sessionId)).toEqual(meta);
expect(setWorktreePathInDbMock).toHaveBeenCalledWith(meta.sessionId, meta.path);
});
+
+ it('adds and removes pending safe.directory cleanup paths (deduped)', async () => {
+ const store = await import('../worktree/worktreeStore');
+
+ expect(store.getPendingSafeDirectoryCleanups()).toEqual([]);
+
+ await store.addPendingSafeDirectoryCleanups(['/a', '/a', '/b']);
+ expect(store.getPendingSafeDirectoryCleanups()).toEqual(['/a', '/b']);
+
+ await store.removePendingSafeDirectoryCleanups(['/a']);
+ expect(store.getPendingSafeDirectoryCleanups()).toEqual(['/b']);
+
+ await store.removePendingSafeDirectoryCleanups(['/b']);
+ expect(store.getPendingSafeDirectoryCleanups()).toEqual([]);
+ });
+
+ it('queue writes live in a separate store file from worktrees', async () => {
+ const store = await import('../worktree/worktreeStore');
+ const meta: WorktreeMeta = {
+ sessionId: 'session-1',
+ name: 'auto-test',
+ path: '/repo/.xdt-worktrees/auto-test',
+ baseRepo: '/repo',
+ branch: 'xdt/auto-test',
+ sourceBranch: 'main',
+ createdAt: '2026-05-26T00:00:00.000Z',
+ ephemeral: false,
+ };
+
+ await store.set(meta.sessionId, meta);
+ await store.addPendingSafeDirectoryCleanups(['/deferred']);
+
+ // 两类写入落在不同 store 文件: worktrees.json 只含 worktrees 键,
+ // 队列文件只含 pending 键 —— 互相整体重写也不会抹掉对方的数据。
+ expect(Object.keys(storesByName.get('worktrees') ?? {})).toEqual(['worktrees']);
+ expect(storesByName.get('worktrees')?.worktrees).toEqual({ [meta.sessionId]: meta });
+ expect(storesByName.get('worktree-safe-directory-cleanup')).toEqual({ pending: ['/deferred'] });
+ });
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 915383b443..18e3c6b3ee 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -436,6 +436,7 @@ import {
registerWorktreeIpc,
WorktreePool,
reconcileWorktreesForDeletedSessions,
+ reconcilePendingSafeDirectoryCleanups,
} from './worktree';
// shadow savepoint 链的启动期对账(孤儿 refs/cindy/savepoints/* 清理)
import { reconcileSavepointRefsForDeletedSessions } from './git-snapshot/savepointCleanup';
@@ -5205,6 +5206,10 @@ const registerIpcHandlers = () => {
void reconcileWorktreesForDeletedSessions().catch((err) => {
console.error('[bootstrap-electron] worktree reconcile failed (non-fatal):', err);
});
+ // 删除 worktree 时因拿不到全局 safe.directory 锁而落盘的残留路径, 启动期补清。
+ void reconcilePendingSafeDirectoryCleanups().catch((err) => {
+ console.error('[bootstrap-electron] safe.directory cleanup reconcile failed (non-fatal):', err);
+ });
// 同窗口的 shadow savepoint 对账:owning session 已删除的孤儿保存点链
// (refs/cindy/savepoints/<sid>)启动期补删。fire-and-forget,不阻塞启动。
void reconcileSavepointRefsForDeletedSessions().catch((err) => {
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index 210364b078..1ce65cafe4 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -26,7 +26,8 @@ import {
} from './nameGenerator';
import { readAttachedWorktreeBranch } from './attachedBranch';
import { classifyError, type ClassifyInput } from './errorClassifier';
-import { gitExec, GitExecError } from './gitExec';
+import { gitExec, GitExecError, globalSafeDirectoryLockPath, safeDirectorySpellings } from './gitExec';
+import { withCrossProcessLock } from '../device-link/crossProcessLock';
import { applyWorktreeIncludeFile, listChangedWorktreeIncludeFiles } from './includePatternsEngine';
import { hasKeepSentinel, isManagedWorktreePath } from './safety';
import {
@@ -104,6 +105,212 @@ function activeWorktreePath(meta: WorktreeMeta): string {
return meta.quarantinePath ?? meta.path;
}
+/**
+ * 在持有全局 safe.directory 跨进程锁的前提下, 按精确值移除一组路径的 safe.directory
+ * 条目(#2627)。每个目标按 safeDirectorySpellings 展开成「规范化 + 原生」两种拼写逐一
+ * --unset-all(Windows 上 add 写 C:/...、历史条目可能写 C:\..., 只删一种会残留另一种)。
+ * 返回实际成功清理或本就不存在(exit 5)的目标; 其余失败仅告警、不算已清理, 由调用方
+ * 决定是否落盘推迟到下次启动再试。
+ */
+async function unsetSafeDirectoryEntriesLocked(
+ targets: Iterable<string>,
+): Promise<string[]> {
+ const cleaned: string[] = [];
+ for (const target of targets) {
+ let failed = false;
+ for (const spelling of safeDirectorySpellings(target)) {
+ try {
+ await gitExec([
+ 'config',
+ '--global',
+ '--unset-all',
+ '--fixed-value',
+ 'safe.directory',
+ spelling,
+ ]);
+ } catch (err) {
+ // exit 5 = 该值本就不存在(常见:正常创建从未写 safe.directory), 无需告警
+ if (err instanceof GitExecError && err.exitCode === 5) continue;
+ failed = true;
+ log.warn(
+ `[worktree] remove safe.directory entry for ${spelling} failed:`,
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ }
+ if (!failed) cleaned.push(target);
+ }
+ return cleaned;
+}
+
+/**
+ * 计算一组候选路径需要精确清理的全部 safe.directory 拼写:
+ * - 逻辑拼写: meta 里记录的 path.join 产物;
+ * - 物理拼写: baseRepo 是 symlink/junction 时, git 在 dubious-ownership 报错里
+ * 给的是 realpath 后的物理路径, ensureGlobalSafeDirectory 写的正是这个值,
+ * 只按逻辑拼写会漏删 —— 用 fs.realpath(baseRepo) + 相对后缀补出物理拼写。
+ * 每种拼写再经 safeDirectorySpellings 展开正/反斜杠两种形式。
+ */
+async function resolveSafeDirectorySpellings(
+ candidates: Iterable<string>,
+ baseRepo: string,
+): Promise<string[]> {
+ const spellings = new Set<string>();
+ let physicalBase: string | null = null;
+ try {
+ physicalBase = await fs.realpath(baseRepo);
+ } catch {
+ physicalBase = null; // baseRepo 解析不到时只清逻辑拼写
+ }
+ for (const candidate of candidates) {
+ for (const s of safeDirectorySpellings(candidate)) spellings.add(s);
+ if (physicalBase) {
+ const rel = path.relative(baseRepo, candidate);
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
+ for (const s of safeDirectorySpellings(path.join(physicalBase, rel))) spellings.add(s);
+ }
+ }
+ }
+ return [...spellings];
+}
+
+/**
+ * 删除/归档成功后, 清理该 worktree 路径残留在全局 git config 里的 safe.directory
+ * 条目(#2627)。只按精确值移除, 不触碰用户其它仓库的手动配置; 失败仅日志, 不影响
+ * 删除主流程。传入本次删除涉及的所有候选路径:原始 path + 已持久化的 quarantinePath
+ * + 本轮实际 removalPath —— 其中 removalPath 可能是 preserveDirty 现场生成的
+ * `.xdt-removing-*` 目录, 它在 ignored-file 扫描 / 所有权复核时触发过 gitExec 的
+ * 按需 safe.directory, 必须一并清理, 否则会永久残留。
+ *
+ * 写前日志: 先把全部拼写(逻辑 + 物理)落盘到 pendingSafeDirectoryCleanups, 再执行
+ * 精确 --unset-all, 成功后只移除已清理的那部分。调用方保证在 store.del(sessionId)
+ * **之前**调用本函数 —— 这样即便进程在本函数与 store.del 之间崩溃, 队列里仍有这份
+ * 路径, 启动对账还能补清; 反过来(先删元数据再落盘)一旦崩溃就永久丢路径。
+ *
+ * 与 gitExec 的 ensureGlobalSafeDirectory(--add)共用同一把跨进程锁: 两种写操作必须
+ * 串行, 否则并发写全局 config 会因 .gitconfig.lock 冲突失败。拿不到锁时不无锁
+ * --unset-all, 候选路径已在前一步入队, 留给启动对账补清。
+ */
+async function removeWorktreeSafeDirectory(
+ baseRepo: string,
+ ...paths: (string | null | undefined)[]
+): Promise<void> {
+ const candidates = new Set(
+ paths.filter((p): p is string => typeof p === 'string' && p.length > 0),
+ );
+ if (candidates.size === 0) return;
+
+ const spellings = await resolveSafeDirectorySpellings(candidates, baseRepo);
+
+ // 写前日志: 在 store.del 之前先持久化清理意图。
+ try {
+ await store.addPendingSafeDirectoryCleanups(spellings);
+ } catch (err) {
+ // 落盘失败只是丢失「崩溃后补清」的机会, 不能反向中断删除主流程; 继续尝试即时清理。
+ log.warn(
+ '[worktree] persist safe.directory cleanup intent failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+
+ const cleaned = await withCrossProcessLock(
+ globalSafeDirectoryLockPath(),
+ { label: 'git-safe-directory', waitMs: 1_000 },
+ async (status) => {
+ if (!status.held) return [];
+ return unsetSafeDirectoryEntriesLocked(spellings);
+ },
+ );
+
+ if (cleaned.length > 0) {
+ try {
+ await store.removePendingSafeDirectoryCleanups(cleaned);
+ } catch (err) {
+ log.warn(
+ '[worktree] remove cleaned safe.directory paths from store failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ }
+}
+
+/**
+ * 计算当前仍被活跃 worktree 占用的全部 safe.directory 拼写。对账清理前用于区分
+ * 「孤儿条目」与「路径已被同名新 worktree 复用」: 删除把路径留在待办队列后, 同名
+ * 预创建 worktree 可能重建并依赖(或重新 add)同一 safe.directory 值, 此时旧待办
+ * 绝不能再 --unset-all(会删掉新条目, 让 Agent 在异所有权环境再次报 dubious
+ * ownership)。git config 条目本身没有代际信息, store 的活跃 meta 是唯一权威。
+ */
+async function computeInUseSafeDirectorySpellings(): Promise<Set<string>> {
+ const inUse = new Set<string>();
+ for (const meta of store.getAll()) {
+ const candidates = [meta.path, meta.quarantinePath].filter(
+ (p): p is string => typeof p === 'string' && p.length > 0,
+ );
+ if (candidates.length === 0) continue;
+ for (const spelling of await resolveSafeDirectorySpellings(candidates, meta.baseRepo)) {
+ inUse.add(spelling);
+ }
+ }
+ return inUse;
+}
+
+/**
+ * 启动期对账: 补清 removeWorktreeSafeDirectory 因拿不到锁(或 --unset-all 失败)而
+ * 落盘的 safe.directory 残留路径。成功(exit 0)或本就不存在(exit 5)的路径从 store
+ * 移除; 仍失败的留待下次启动。fire-and-forget, 不阻塞启动。
+ *
+ * 清理前先剔除仍被活跃 worktree 占用的路径(同名复用场景): 这些待办已作废——条目
+ * 归新一代 worktree 所有, 由它自己的删除流程负责, 这里只出队不清理。占用判定必须
+ * 在**持锁临界区内**重估: 快照算在锁外时, 两个 Cindy 实例重叠的场景下, 新 worktree
+ * 可以在快照之后、拿到锁之前认领待办路径, 锁内照删就复现误删新条目的问题。
+ */
+export async function reconcilePendingSafeDirectoryCleanups(): Promise<void> {
+ const pending = store.getPendingSafeDirectoryCleanups();
+ if (pending.length === 0) return;
+
+ const { cleaned, reclaimed } = await withCrossProcessLock(
+ globalSafeDirectoryLockPath(),
+ { label: 'git-safe-directory', waitMs: 1_000 },
+ async (status) => {
+ if (!status.held) return { cleaned: [] as string[], reclaimed: [] as string[] };
+ // 持锁后重估占用: 确保不被快照与持锁之间认领路径的新 worktree 抢先。
+ const inUse = await computeInUseSafeDirectorySpellings();
+ const targets = pending.filter((p) => !inUse.has(p));
+ const reclaimedNow = pending.filter((p) => inUse.has(p));
+ const cleanedNow = await unsetSafeDirectoryEntriesLocked(targets);
+ return { cleaned: cleanedNow, reclaimed: reclaimedNow };
+ },
+ );
+
+ // 复用路径的旧待办作废: 只出队, 不动 git config(条目归新 worktree)。
+ if (reclaimed.length > 0) {
+ log.info(
+ '[worktree] drop stale safe.directory cleanups for re-created paths:',
+ reclaimed.join(', '),
+ );
+ try {
+ await store.removePendingSafeDirectoryCleanups(reclaimed);
+ } catch (err) {
+ log.warn(
+ '[worktree] remove reclaimed safe.directory paths from store failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ }
+
+ if (cleaned.length > 0) {
+ try {
+ await store.removePendingSafeDirectoryCleanups(cleaned);
+ } catch (err) {
+ log.warn(
+ '[worktree] remove cleaned safe.directory paths from store failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ }
+}
+
async function timed<T>(label: string, fn: () => Promise<T>): Promise<T> {
const startedAt = Date.now();
try {
@@ -659,8 +866,9 @@ export async function copyClaudeSiviDirs(
* 6. configureHooksPath
* 7. copyClaudeSiviDirs(跳过 .claude/worktrees 这类历史工作区状态)
* 8. applyWorktreeIncludeFile
- * 9. git config --global --add safe.directory <path>
- * 10. worktreeStore.set(sessionId, meta) → 同步写 sessions.worktree_path
+ * 9. worktreeStore.set(sessionId, meta) → 同步写 sessions.worktree_path
+ * (不再无条件写全局 safe.directory:dubious-ownership 时由 gitExec 幂等按需处理;
+ * 删除/归档时由 removeWorktreeForSession 清理该 path 的条目, 见 #2627)
*/
export async function createWorktree(req: CreateWorktreeReq): Promise<CreateWorktreeResp> {
const create = () => withCreateWorktreeQueue(req.baseRepo, () => createWorktreeInner(req));
@@ -856,20 +1064,7 @@ async function createWorktreeInner(req: CreateWorktreeReq): Promise<CreateWorktr
);
}
- // 9. safe.directory
- try {
- await timed('add safe.directory', () =>
- gitExec(['config', '--global', '--add', 'safe.directory', worktreePath]),
- );
- } catch (err) {
- // 非致命 — 仅日志
- log.warn(
- `[worktree] add safe.directory failed:`,
- err instanceof Error ? err.message : String(err),
- );
- }
-
- // 10. store + DB
+ // 9. store + DB
const meta: WorktreeMeta = {
sessionId: req.sessionId,
name,
@@ -1293,6 +1488,8 @@ async function removeWorktreeForSessionInner(
}
if (removedByGit) {
+ // 写前日志: 先落盘清理意图(物理 + 逻辑拼写), 再删最后一份元数据。
+ await removeWorktreeSafeDirectory(meta.baseRepo, meta.path, meta.quarantinePath, removalPath);
store.del(sessionId);
} else if (snapshotted) {
// Both removal paths failed: put WIP back before restoring the live registration. If apply
diff --git a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
index 593af88c87..21bc3a982d 100644
--- a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
@@ -14,12 +14,24 @@ type ExecCb = (err: Error | null, stdout: string, stderr: string) => void;
const mocks = vi.hoisted(() => ({
execFile: vi.fn(),
killProcessTree: vi.fn(),
+ withCrossProcessLock: vi.fn(),
}));
vi.mock('node:child_process', () => ({ execFile: mocks.execFile }));
vi.mock('../../scheduler-host/proc-util', () => ({ killProcessTree: mocks.killProcessTree }));
+vi.mock('../../device-link/crossProcessLock', () => ({
+ withCrossProcessLock: mocks.withCrossProcessLock,
+}));
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
-import { gitExec, GitExecError } from '../gitExec';
+import {
+ gitExec,
+ GitExecError,
+ normalizeSafeDirectorySpelling,
+ safeDirectorySpellings,
+} from '../gitExec';
const realPlatform = process.platform;
@@ -146,6 +158,13 @@ beforeEach(() => {
vi.useFakeTimers();
mocks.execFile.mockReset();
mocks.killProcessTree.mockReset();
+ mocks.withCrossProcessLock.mockReset();
+ // 默认按「持锁成功」直通, 让 dubious-ownership 的 read+add 序列可逐步驱动;
+ // 需要验证锁被使用时单独断言 mock 调用即可。
+ mocks.withCrossProcessLock.mockImplementation(
+ (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>
+ task({ held: true }),
+ );
});
afterEach(() => {
@@ -541,3 +560,137 @@ describe('gitExec timeoutMs', () => {
expect(vi.getTimerCount()).toBe(0);
});
});
+
+describe('gitExec dubious-ownership safe.directory', () => {
+ /**
+ * 只按调用顺序捕获每次 git execFile 的 args 与回调(不 spawn 真进程),
+ * 供 dubious-ownership 的「幂等 add + 重试一次」路径逐步驱动。
+ */
+ function installSequenceMock() {
+ const calls: string[][] = [];
+ const cbs: ExecCb[] = [];
+ mocks.execFile.mockImplementation(
+ (file: string, args: string[], _opts: unknown, cb?: ExecCb) => {
+ if (file !== 'git') throw new Error(`unexpected execFile: ${file}`);
+ calls.push(args as string[]);
+ cbs.push(cb as ExecCb);
+ return new EventEmitter();
+ },
+ );
+ return { calls, cbs };
+ }
+
+ async function flushDeep() {
+ for (let i = 0; i < 20; i += 1) await Promise.resolve();
+ }
+
+ it('首次 dubious ownership → 幂等加入 safe.directory 后重试一次', async () => {
+ const { calls, cbs } = installSequenceMock();
+
+ const p = gitExec(['status'], '/repo');
+ expect(calls).toEqual([['status']]);
+ cbs[0](new Error('boom'), '', "fatal: detected dubious ownership in repository at '/repo'");
+ await flushDeep();
+
+ // read+add 必须包在跨进程锁里, 保证并发实例下仍是原子的
+ expect(mocks.withCrossProcessLock).toHaveBeenCalledTimes(1);
+
+ // 读取现有 safe.directory → 未配置(exit 1)按空处理
+ expect(calls[1]).toEqual(['config', '--global', '--get-all', 'safe.directory']);
+ cbs[1](Object.assign(new Error('exit 1'), { code: 1 }), '', '');
+ await flushDeep();
+
+ // 尚不存在 → 幂等 add 一次
+ expect(calls[2]).toEqual(['config', '--global', '--add', 'safe.directory', '/repo']);
+ cbs[2](null, '', '');
+ await flushDeep();
+
+ // 重试原命令
+ expect(calls[3]).toEqual(['status']);
+ cbs[3](null, 'ok', '');
+ await expect(p).resolves.toEqual({ stdout: 'ok', stderr: '' });
+ });
+
+ it('路径已在 safe.directory 中 → 不重复 --add, 直接重试原命令', async () => {
+ const { calls, cbs } = installSequenceMock();
+
+ const p = gitExec(['status'], '/repo');
+ cbs[0](new Error('boom'), '', "fatal: detected dubious ownership in repository at '/repo'");
+ await flushDeep();
+
+ expect(calls[1]).toEqual(['config', '--global', '--get-all', 'safe.directory']);
+ cbs[1](null, '/repo\n', '');
+ await flushDeep();
+
+ // 已存在 → 跳过 --add, 直接重试
+ expect(calls[2]).toEqual(['status']);
+ cbs[2](null, 'ok', '');
+ await expect(p).resolves.toEqual({ stdout: 'ok', stderr: '' });
+ expect(calls.some((a) => a.includes('--add'))).toBe(false);
+ });
+
+ it('--get-all 读取失败(非「键不存在」) → 不 --add, 原错误上抛', async () => {
+ const { calls, cbs } = installSequenceMock();
+
+ const p = gitExec(['status'], '/repo');
+ cbs[0](new Error('boom'), '', "fatal: detected dubious ownership in repository at '/repo'");
+ await flushDeep();
+
+ expect(calls[1]).toEqual(['config', '--global', '--get-all', 'safe.directory']);
+ // 读取错误(exit 3 = 配置文件损坏/锁冲突)不得被当成「未配置」,后续 --add 不得发生
+ const readErr = Object.assign(new Error('bad config'), { code: 3 });
+ cbs[1](readErr, '', 'error: could not lock config file');
+ await flushDeep();
+
+ expect(calls.some((a) => a.includes('--add'))).toBe(false);
+ // 原 dubious-ownership 错误上抛(不再重试)
+ await expect(p).rejects.toMatchObject({
+ stderr: expect.stringContaining('dubious ownership'),
+ });
+ });
+
+ it('未持锁(held:false) → 不做无锁 read+add, 原错误上抛', async () => {
+ const { calls, cbs } = installSequenceMock();
+ mocks.withCrossProcessLock.mockImplementation((_lp, _opts, task) =>
+ task({ held: false, reason: 'busy' }),
+ );
+
+ const p = gitExec(['status'], '/repo');
+ cbs[0](new Error('boom'), '', "fatal: detected dubious ownership in repository at '/repo'");
+ await flushDeep();
+
+ // 锁未拿到 → 不得执行任何 config 读写, 原 dubious-ownership 错误上抛
+ expect(calls).toEqual([['status']]);
+ await expect(p).rejects.toMatchObject({
+ stderr: expect.stringContaining('dubious ownership'),
+ });
+ });
+});
+
+describe('safe.directory path spelling', () => {
+ it('normalizes Windows backslashes to forward slashes', () => {
+ setPlatform('win32');
+ expect(normalizeSafeDirectorySpelling('C:\\repo\\.xdt-worktrees\\s1')).toBe(
+ 'C:/repo/.xdt-worktrees/s1',
+ );
+ expect(normalizeSafeDirectorySpelling('C:/repo/.xdt-worktrees/s1')).toBe(
+ 'C:/repo/.xdt-worktrees/s1',
+ );
+ });
+
+ it('returns the native spelling only on POSIX', () => {
+ setPlatform('linux');
+ expect(normalizeSafeDirectorySpelling('/repo/.xdt-worktrees/s1')).toBe(
+ '/repo/.xdt-worktrees/s1',
+ );
+ expect(safeDirectorySpellings('/repo/.xdt-worktrees/s1')).toEqual([
+ '/repo/.xdt-worktrees/s1',
+ ]);
+ });
+
+ it('covers both spellings on Windows for exact --fixed-value cleanup', () => {
+ setPlatform('win32');
+ expect(safeDirectorySpellings('C:\\repo\\s1')).toEqual(['C:/repo/s1', 'C:\\repo\\s1']);
+ expect(safeDirectorySpellings('C:/repo/s1')).toEqual(['C:/repo/s1']);
+ });
+});
diff --git a/apps/desktop/src/main/worktree/gitExec.ts b/apps/desktop/src/main/worktree/gitExec.ts
index 709829bcfb..167660bfb0 100644
--- a/apps/desktop/src/main/worktree/gitExec.ts
+++ b/apps/desktop/src/main/worktree/gitExec.ts
@@ -4,7 +4,8 @@
* 职责:
* - 用 child_process.execFile 调用 git, 保留 stderr/stdout/exitCode
* - 自动处理 dubious-ownership: 若 stderr 含 "dubious ownership", 提取路径,
- * `git config --global --add safe.directory <path>`, 重试**一次**原命令
+ * 幂等地 `git config --global --add safe.directory <path>`(已存在则不重复添加),
+ * 重试**一次**原命令
* - 抛出 GitExecError 让上层 errorClassifier 解析为 WorktreeError
*
* 不在这里做 errorClassifier — 那是上层 createWorktree/removeWorktree 的职责,
@@ -12,8 +13,14 @@
*/
import { execFile, type ExecFileOptions } from 'node:child_process';
+import os from 'node:os';
+import path from 'node:path';
import { killProcessTree } from '../scheduler-host/proc-util';
+import { withCrossProcessLock } from '../device-link/crossProcessLock';
+import { createLogger } from '../logger';
+
+const log = createLogger('gitExec');
export interface GitExecResult {
stdout: string;
@@ -446,6 +453,86 @@ function extractDubiousPath(stderr: string): string | null {
return null;
}
+/**
+ * safe.directory 全局配置「读改写」的跨进程锁文件路径。
+ *
+ * 读(get-all)与写(add)是两条独立的 git config 命令,本身不互斥:两个 Cindy 实例
+ * 并发触发同一仓库的 dubious-ownership 时可能都读到「不存在」再各加一条,堆积出
+ * 重复条目(#2627)。用跨进程锁把这两步圈成原子区。锁文件用 os.tmpdir() 落地;
+ * Linux 的 /tmp 多用户共享,用 uid(Windows 无 uid 时退回 0)区分用户,避免不同用户
+ * 串扰同一把锁。
+ */
+export function globalSafeDirectoryLockPath(): string {
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
+ return path.join(os.tmpdir(), `cindy-git-safe-directory-${uid}.lock`);
+}
+
+/**
+ * 把一条路径规范成 git 呈现/比较 safe.directory 时用的拼写。
+ *
+ * Windows 上 git 在错误信息里以 `C:/...`(正斜杠)输出路径, 而 `path.join` 产出的是
+ * 原生 `C:\...`。`git config --fixed-value` 是字符串精确相等, 若 add 写正斜杠、清理
+ * 用反斜杠, 会永远匹配不到并残留条目。所以 add 与清理都必须经过同一个规范化函数。
+ */
+export function normalizeSafeDirectorySpelling(p: string): string {
+ return process.platform === 'win32' ? p.replace(/\\/g, '/') : p;
+}
+
+/**
+ * 给定一个逻辑路径, 返回需要精确清理的 safe.directory 拼写集合。覆盖两类来源:
+ * - 规范化拼写(C:/...): gitExec 从 dubious-ownership 报错提取并 add 的拼写;
+ * - 原生拼写(C:\...): 历史版本无条件 add、或 gitExec 用 cwd 兜底时写下的拼写。
+ * 两边都删, 才能把历史遗留的反斜杠条目一并清掉。
+ */
+export function safeDirectorySpellings(p: string): string[] {
+ const normalized = normalizeSafeDirectorySpelling(p);
+ return normalized === p ? [p] : [normalized, p];
+}
+
+/**
+ * 读取当前全局 safe.directory 的值列表。仅当「键不存在」(git config --get-all 对
+ * 缺失键返回退出码 1)时按空列表处理;其余读取错误(配置锁冲突/权限/配置损坏/spawn
+ * 失败)必须向上抛,否则会把「读不到」误判成「未配置」而重复 --add,反而制造出
+ * 本条修复要避免的重复条目。
+ */
+async function readGlobalSafeDirectories(): Promise<string[]> {
+ try {
+ const { stdout } = await execFileOnce(['config', '--global', '--get-all', 'safe.directory']);
+ return stdout
+ .split('\n')
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0);
+ } catch (err) {
+ if (err instanceof GitExecError && err.exitCode === 1) return [];
+ throw err;
+ }
+}
+
+/**
+ * 幂等地把 targetPath 加入全局 safe.directory: 已存在则不再 --add, 避免同一路径
+ * 因多个 git 操作反复触发 dubious-ownership 而用 --add 堆积出重复记录(#2627)。
+ *
+ * 读+写放在 withCrossProcessLock 里保证跨进程原子。**未持锁绝不无锁读改写**:其它
+ * 实例长期持锁 / 锁基础设施不可用时 fail-closed 抛错,让 gitExec 把原始
+ * dubious-ownership 错误还给调用方,而不是退化成并发写入重复条目。用底层
+ * execFileOnce 而非 gitExec, 防止递归进入 dubious-ownership 分支。
+ */
+async function ensureGlobalSafeDirectory(targetPath: string): Promise<void> {
+ await withCrossProcessLock(
+ globalSafeDirectoryLockPath(),
+ { label: 'git-safe-directory', waitMs: 1_000 },
+ async (status) => {
+ if (!status.held) {
+ throw new Error('could not acquire the global safe.directory lock');
+ }
+ // 统一成 git 的拼写再读写: 让幂等检查与后续清理命中同一个值。
+ const normalized = normalizeSafeDirectorySpelling(targetPath);
+ if ((await readGlobalSafeDirectories()).some((p) => p === normalized)) return;
+ await execFileOnce(['config', '--global', '--add', 'safe.directory', normalized]);
+ },
+ );
+}
+
/**
* 主 API: 执行 git 命令, 自动处理 dubious-ownership。
*
@@ -471,13 +558,17 @@ export async function gitExec(
const dubiousPath = extractDubiousPath(err.stderr) ?? cwd;
if (dubiousPath) {
try {
- await execFileOnce(
- ['config', '--global', '--add', 'safe.directory', dubiousPath],
- );
+ await ensureGlobalSafeDirectory(dubiousPath);
// 配完 safe.directory 后重试原命令
return await execFileOnce(args, cwd, opts);
- } catch {
- // 重试或配置失败都直接抛原始错误(让 classifier 报 dubious-ownership)
+ } catch (cause) {
+ // 对外错误契约不变: 调用方/classifier 仍拿到原始 dubious-ownership 错误。
+ // 但 ensureGlobalSafeDirectory 的真实失败(--get-all 权限/锁冲突/配置损坏,
+ // 或拿不到跨进程锁)不能被静默吞掉 —— 先落日志保住诊断信息, 再抛原始错误。
+ log.warn(
+ `gitExec auto safe.directory add failed for ${dubiousPath}:`,
+ cause instanceof Error ? cause.message : String(cause),
+ );
throw err;
}
}
diff --git a/apps/desktop/src/main/worktree/index.ts b/apps/desktop/src/main/worktree/index.ts
index 2c4b8656ec..8986bcbdca 100644
--- a/apps/desktop/src/main/worktree/index.ts
+++ b/apps/desktop/src/main/worktree/index.ts
@@ -32,6 +32,7 @@ export {
recycleWorktreeForRemovedSession,
reconcileWorktreesForDeletedSessions,
} from './sessionRemovalRecycle';
+export { reconcilePendingSafeDirectoryCleanups } from './WorktreeManager';
export {
getWorktreeRestoreStatus,
restoreMissingManagedWorktreeForSession,
diff --git a/apps/desktop/src/main/worktree/worktreeStore.ts b/apps/desktop/src/main/worktree/worktreeStore.ts
index bbdb052b23..dccc568106 100644
--- a/apps/desktop/src/main/worktree/worktreeStore.ts
+++ b/apps/desktop/src/main/worktree/worktreeStore.ts
@@ -13,14 +13,23 @@
* - set(sid, meta): 写 store + 同步写 sessions.worktree_path = meta.path(反范式快照)
* - delete(sid): 清 store 条目, **不**清 sessions.worktree_path(保留历史值, 徽标按 store 判)
*
+ * pendingSafeDirectoryCleanups 队列**刻意放在独立 store 文件**(worktree-safe-directory-cleanup.json):
+ * electron-store 每次 set 都整体重写整个文件, 若队列与 worktrees 同文件, 一个进程写
+ * worktrees(set/del)、另一个写队列时, 两个读改写周期从同一份文件快照出发, 后写的会把
+ * 先写的新增整个抹掉(丢待办路径 → 启动补清永远看不到)。分文件后两类写互不重叠。
+ *
* v8 是 ESM-only(项目 main 用 CJS 输出), 所以锁 v7 — CJS 兼容, API 完全一致。
*/
+import os from 'node:os';
+import path from 'node:path';
+
import Store from 'electron-store';
import type { WorktreeMeta } from './types';
import { setWorktreePathInDb } from '../localDb/ipc/sessions';
import { createLogger } from '../logger';
+import { withCrossProcessLock } from '../device-link/crossProcessLock';
const log = createLogger('worktreeStore');
@@ -28,7 +37,13 @@ interface WorktreesStoreShape {
worktrees: Record<string, WorktreeMeta>;
}
+interface SafeDirectoryCleanupStoreShape {
+ /** 删除 worktree 时因拿不到全局 safe.directory 锁而推迟到下次启动补清的路径。 */
+ pending: string[];
+}
+
let storeInstance: Store<WorktreesStoreShape> | null = null;
+let cleanupStoreInstance: Store<SafeDirectoryCleanupStoreShape> | null = null;
/**
* 懒加载单例。在 main 进程 app.whenReady 之后第一次调用时构造;
@@ -49,6 +64,20 @@ function getStore(): Store<WorktreesStoreShape> {
return storeInstance;
}
+/** 队列专用 store 单例(独立文件, 见文件头注释)。 */
+function getCleanupStore(): Store<SafeDirectoryCleanupStoreShape> {
+ if (cleanupStoreInstance) return cleanupStoreInstance;
+ cleanupStoreInstance = new Store<SafeDirectoryCleanupStoreShape>({
+ name: 'worktree-safe-directory-cleanup',
+ defaults: { pending: [] },
+ schema: {
+ pending: { type: 'array', items: { type: 'string' } },
+ },
+ clearInvalidConfig: true,
+ });
+ return cleanupStoreInstance;
+}
+
/** 测试钩子: 注入自定义 store(单测里用 mock)。 */
export function _setStoreForTests(s: Store<WorktreesStoreShape> | null): void {
storeInstance = s;
@@ -83,6 +112,77 @@ export function getAllPaths(): string[] {
));
}
+function readPendingSafeDirectoryCleanups(): string[] {
+ const raw = getCleanupStore().get('pending', []);
+ if (!Array.isArray(raw)) return [];
+ return raw.filter((p): p is string => typeof p === 'string' && p.length > 0);
+}
+
+/**
+ * pendingSafeDirectoryCleanups 队列「读改写」的专用跨进程锁。
+ *
+ * 与 gitExec 的 safe.directory 锁分开: 这里只保护 electron-store 上「读列表 → 合并
+ * → 写回」这微秒级的一步;若与 --add/--unset-all 共用同一把锁, 删除侧拿不到锁时连
+ * 落盘兜底都做不了, 反而复现「两个进程各读同一份列表、后写覆盖先写」的丢路径窗口。
+ */
+function pendingSafeDirectoryCleanupLockPath(): string {
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
+ return path.join(os.tmpdir(), `cindy-git-safe-directory-cleanup-${uid}.lock`);
+}
+
+/**
+ * 读取当前推迟清理的 safe.directory 路径(供启动期 reconcile 补清)。
+ */
+export function getPendingSafeDirectoryCleanups(): string[] {
+ return readPendingSafeDirectoryCleanups();
+}
+
+/**
+ * 追加推迟清理的路径(去重)。读改写全程持队列锁, 避免并发实例丢更新。
+ */
+export async function addPendingSafeDirectoryCleanups(paths: readonly string[]): Promise<void> {
+ const unique = [...new Set(paths)].filter((p) => p && p.length > 0);
+ if (unique.length === 0) return;
+ await withCrossProcessLock(
+ pendingSafeDirectoryCleanupLockPath(),
+ { label: 'git-safe-directory-cleanup', waitMs: 1_000 },
+ async (status) => {
+ if (!status.held) {
+ throw new Error('could not acquire the safe.directory cleanup queue lock');
+ }
+ const existing = new Set(readPendingSafeDirectoryCleanups());
+ let changed = false;
+ for (const p of unique) {
+ if (!existing.has(p)) {
+ existing.add(p);
+ changed = true;
+ }
+ }
+ if (changed) getCleanupStore().set('pending', [...existing]);
+ },
+ );
+}
+
+/**
+ * 移除已成功清理的路径。读改写全程持队列锁, 与 add 串行化避免覆盖。
+ */
+export async function removePendingSafeDirectoryCleanups(paths: readonly string[]): Promise<void> {
+ const toRemove = new Set(paths);
+ if (toRemove.size === 0) return;
+ await withCrossProcessLock(
+ pendingSafeDirectoryCleanupLockPath(),
+ { label: 'git-safe-directory-cleanup', waitMs: 1_000 },
+ async (status) => {
+ if (!status.held) {
+ throw new Error('could not acquire the safe.directory cleanup queue lock');
+ }
+ const current = readPendingSafeDirectoryCleanups();
+ const next = current.filter((p) => !toRemove.has(p));
+ if (next.length !== current.length) getCleanupStore().set('pending', next);
+ },
+ );
+}
+
/**
* 写入 / 覆盖一条 meta, 同时同步 DB sessions.worktree_path。
* DB 写失败仅日志告警, 不抛(store 是 source of truth)。