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。

feat(worktree): 新建 Worktree 使用 Cindy 分支命名空间 (#1682)

Dashe75a59a98404
diff --git a/apps/desktop/help-knowledge/worktrees.md b/apps/desktop/help-knowledge/worktrees.md
index e7780123d3..daa102d97c 100644
--- a/apps/desktop/help-knowledge/worktrees.md
+++ b/apps/desktop/help-knowledge/worktrees.md
@@ -3,6 +3,7 @@ id: worktrees
title: Working in an isolated git worktree
summary: Opt a session into an isolated git worktree so its changes stay on their own branch and folder.
---
+
A session can run inside its own **git worktree** — a separate working copy of the same repository on its own branch — so the agent's edits don't mix with your main checkout.
**Opting in:**
@@ -13,7 +14,7 @@ A session can run inside its own **git worktree** — a separate working copy of
**Where it goes:**
- Folder: `<repo>/.cindy-worktrees/<auto-generated-name>/` — kept inside the same repo so git tooling can find it. Worktrees created by older versions under `.xdt-worktrees/` remain supported.
-- Branch: `xdt/<auto-generated-name>` — auto-created off the source branch you pick, which defaults to the repo's current branch (HEAD).
+- Branch: `cindy/<auto-generated-name>` — auto-created off the source branch you pick, which defaults to the repo's current branch (HEAD). Branches created by older versions under `xdt/` remain supported and do not need to be renamed.
**Lifecycle:**
@@ -35,5 +36,5 @@ A session can run inside its own **git worktree** — a separate working copy of
**Notes:**
- The agent's **Read / Write / Bash** tools automatically operate inside the worktree path — you don't need to switch directories manually.
-- Because the branch survives the worktree, "did the agent's changes go anywhere?" is always answerable with `git branch --list 'xdt/*'`.
+- Because the branch survives the worktree, "did the agent's changes go anywhere?" is always answerable with `git branch --list 'cindy/*' 'xdt/*'`.
- Worktrees are a per-session opt-in — they're not on by default and they don't change non-worktree sessions in any way.
diff --git a/apps/desktop/src/main/__tests__/worktreeBranchNamespace.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeBranchNamespace.git-integration.test.ts
new file mode 100644
index 0000000000..762e1e9570
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/worktreeBranchNamespace.git-integration.test.ts
@@ -0,0 +1,84 @@
+import { execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ blocksManagedWorktreeBranchNamespace,
+ getManagedWorktreeReservedName,
+} from '../../shared/managedWorktreeBranches';
+import { readAttachedWorktreeBranch } from '../worktree/attachedBranch';
+
+const tempDirs: string[] = [];
+
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync('git', args, {
+ cwd,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_CONFIG_GLOBAL: os.devNull,
+ },
+ }).trim();
+}
+
+function makeRepo(): string {
+ const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-branch-namespace-'));
+ tempDirs.push(repo);
+ git(repo, 'init', '--initial-branch=main');
+ git(repo, 'config', 'user.name', 'Cindy Test');
+ git(repo, 'config', 'user.email', '[email protected]');
+ fs.writeFileSync(path.join(repo, 'README.md'), 'test\n');
+ git(repo, 'add', 'README.md');
+ git(repo, 'commit', '-m', 'init');
+ return repo;
+}
+
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+describe('managed Worktree branch namespace', () => {
+ it('turns a real descendant ref collision into a reserved name', () => {
+ const repo = makeRepo();
+ git(repo, 'branch', 'cindy/foo/bar');
+
+ expect(() => git(repo, 'branch', 'cindy/foo')).toThrow();
+ const branches = git(repo, 'branch', '--format=%(refname:short)').split(/\r?\n/);
+ expect(branches.map(getManagedWorktreeReservedName).filter(Boolean)).toContain('foo');
+ expect(() => git(repo, 'branch', 'cindy/foo-2')).not.toThrow();
+ });
+
+ it('detects a real namespace-root ref that blocks every cindy/* branch', () => {
+ const repo = makeRepo();
+ git(repo, 'branch', 'cindy');
+
+ expect(() => git(repo, 'branch', 'cindy/foo')).toThrow();
+ expect(blocksManagedWorktreeBranchNamespace('cindy')).toBe(true);
+ });
+
+ it('keeps local origin/* branches distinct from origin tracking refs', () => {
+ const repo = makeRepo();
+ git(repo, 'branch', 'origin/cindy');
+ git(repo, 'update-ref', 'refs/remotes/origin/cindy', 'HEAD');
+
+ const refs = git(repo, 'branch', '--all', '--format=%(refname)').split(/\r?\n/);
+ expect(refs).toContain('refs/heads/origin/cindy');
+ expect(refs).toContain('refs/remotes/origin/cindy');
+ });
+
+ it('reads the canonical branch name when a tag has the same short name', async () => {
+ const repo = makeRepo();
+ git(repo, 'branch', 'cindy/foo');
+ git(repo, 'tag', 'cindy/foo');
+ git(repo, 'checkout', 'cindy/foo');
+
+ expect(git(repo, 'symbolic-ref', '--quiet', '--short', 'HEAD')).toBe('heads/cindy/foo');
+ await expect(readAttachedWorktreeBranch(repo)).resolves.toBe('cindy/foo');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
index 8f2f513374..d4a7e4fba5 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
@@ -50,9 +50,10 @@ vi.mock('../worktree/includePatternsEngine', () => ({
vi.mock('../worktree/worktreeStore', () => ({
get: (sessionId: string) => storeMap.get(sessionId) ?? null,
getAll: () => [...storeMap.values()],
- getAllPaths: () => [...storeMap.values()].flatMap((m) => (
- m.quarantinePath ? [m.path, m.quarantinePath] : [m.path]
- )),
+ getAllPaths: () =>
+ [...storeMap.values()].flatMap((m) =>
+ m.quarantinePath ? [m.path, m.quarantinePath] : [m.path],
+ ),
set: (...args: unknown[]) => storeSetMock(...args),
del: vi.fn((sessionId: string) => storeMap.delete(sessionId)),
}));
@@ -93,7 +94,15 @@ describe('removeWorktreeForSession', () => {
storeMap.clear();
liveSessionRows.length = 0;
liveSessionLookupError = null;
- gitExecMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' });
+ gitExecMock.mockReset().mockImplementation(async (args: string[], cwd?: string) => {
+ if (args[0] === 'symbolic-ref') {
+ const meta = [...storeMap.values()].find(
+ (candidate) => candidate.path === cwd || candidate.quarantinePath === cwd,
+ );
+ return { stdout: `refs/heads/${meta?.branch ?? 'xdt/unknown'}\n`, stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
isWorktreeDirtyMock.mockReset().mockResolvedValue(false);
autoStashMock.mockReset().mockResolvedValue(true);
restoreAutoStashMock.mockReset().mockResolvedValue(true);
@@ -115,6 +124,101 @@ describe('removeWorktreeForSession', () => {
expect(gitExecMock).not.toHaveBeenCalled();
});
+ it('suggestName reserves current and legacy names from local and origin branches', async () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);
+ try {
+ gitExecMock.mockImplementation(async (args: string[]) => ({
+ stdout:
+ args[0] === 'branch'
+ ? 'refs/heads/cindy/pensive-lederberg\nrefs/remotes/origin/xdt/pensive-lederberg-2\n'
+ : '',
+ stderr: '',
+ }));
+
+ await expect(manager.suggestName(BASE_REPO)).resolves.toBe('pensive-lederberg-3');
+ expect(gitExecMock).toHaveBeenCalledWith(
+ ['branch', '--all', '--format=%(refname)'],
+ BASE_REPO,
+ );
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ it('suggestName reserves the first name segment of a current-prefix descendant ref', async () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);
+ try {
+ gitExecMock.mockImplementation(async (args: string[]) => ({
+ stdout: args[0] === 'branch' ? 'refs/heads/cindy/pensive-lederberg/child\n' : '',
+ stderr: '',
+ }));
+
+ await expect(manager.suggestName(BASE_REPO)).resolves.toBe('pensive-lederberg-2');
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ it('suggestName ignores remote descendant refs because they do not block local heads', async () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);
+ try {
+ gitExecMock.mockImplementation(async (args: string[]) => ({
+ stdout: args[0] === 'branch' ? 'refs/remotes/origin/cindy/pensive-lederberg/child\n' : '',
+ stderr: '',
+ }));
+
+ await expect(manager.suggestName(BASE_REPO)).resolves.toBe('pensive-lederberg');
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ it('suggestName distinguishes local origin/* branches from origin tracking refs', async () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);
+ try {
+ gitExecMock.mockImplementation(async (args: string[]) => ({
+ stdout:
+ args[0] === 'branch'
+ ? [
+ 'refs/heads/origin/cindy',
+ 'refs/remotes/origin/cindy',
+ 'refs/heads/origin/cindy/pensive-lederberg',
+ ].join('\n')
+ : '',
+ stderr: '',
+ }));
+
+ await expect(manager.suggestName(BASE_REPO)).resolves.toBe('pensive-lederberg');
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ it('suggestName reserves exact origin tracking worktree branches', async () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);
+ try {
+ gitExecMock.mockImplementation(async (args: string[]) => ({
+ stdout: args[0] === 'branch' ? 'refs/remotes/origin/cindy/pensive-lederberg\n' : '',
+ stderr: '',
+ }));
+
+ await expect(manager.suggestName(BASE_REPO)).resolves.toBe('pensive-lederberg-2');
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ it('suggestName reports a current-prefix namespace root before Git ref creation fails', async () => {
+ gitExecMock.mockImplementation(async (args: string[]) => ({
+ stdout: args[0] === 'branch' ? 'refs/heads/cindy\n' : '',
+ stderr: '',
+ }));
+
+ await expect(manager.suggestName(BASE_REPO)).rejects.toThrow(
+ '分支 "cindy" 占用了 "cindy/*" 命名空间',
+ );
+ });
+
it('preserves worktree still referenced by another live session', async () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
@@ -126,6 +230,72 @@ describe('removeWorktreeForSession', () => {
expect(storeMap.has('s1')).toBe(true);
});
+ it('preserves a clean worktree whose attached branch differs from Store metadata', async () => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/feature/manual-switch\n', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await manager.removeWorktreeForSession('s1');
+
+ expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
+ expect(autoStashMock).not.toHaveBeenCalled();
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
+ expect(storeMap.has('s1')).toBe(true);
+ });
+
+ it('preserves a dirty worktree before snapshotting when its branch changed', async () => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ isWorktreeDirtyMock.mockResolvedValue(true);
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/feature/manual-switch\n', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await manager.removeWorktreeForSession('s1');
+
+ expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
+ expect(autoStashMock).not.toHaveBeenCalled();
+ expect(storeMap.has('s1')).toBe(true);
+ });
+
+ it('preserves detached or unreadable HEAD state', async () => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') throw new Error('detached HEAD');
+ return { stdout: '', stderr: '' };
+ });
+
+ await manager.removeWorktreeForSession('s1');
+
+ expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
+ expect(autoStashMock).not.toHaveBeenCalled();
+ expect(storeMap.has('s1')).toBe(true);
+ });
+
+ it('preserves a worktree whose registered branch is outside its managed candidates', async () => {
+ const meta = { ...makeMeta('s1'), branch: 'feature/manual-switch' };
+ storeMap.set('s1', meta);
+
+ await manager.removeWorktreeForSession('s1');
+
+ expect(gitExecMock).not.toHaveBeenCalled();
+ expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
+ expect(autoStashMock).not.toHaveBeenCalled();
+ expect(storeMap.has('s1')).toBe(true);
+ });
+
it('owning session row does not block its own recycle (archived owner)', async () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
@@ -160,7 +330,10 @@ describe('removeWorktreeForSession', () => {
await manager.removeWorktreeForSession('s1');
- expect(gitExecMock).not.toHaveBeenCalled();
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
expect(storeMap.has('s1')).toBe(true);
});
@@ -175,7 +348,10 @@ describe('removeWorktreeForSession', () => {
expect(changedIncludeFilesMock).toHaveBeenCalledWith(BASE_REPO, meta.path);
expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
expect(autoStashMock).not.toHaveBeenCalled();
- expect(gitExecMock).not.toHaveBeenCalled();
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
expect(storeMap.has('s1')).toBe(true);
});
@@ -207,7 +383,10 @@ describe('removeWorktreeForSession', () => {
expect(canRemove).toHaveBeenCalledTimes(2);
expect(autoStashMock).toHaveBeenCalledWith(meta.path, 's1');
expect(restoreAutoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- expect(gitExecMock).not.toHaveBeenCalled();
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
expect(storeMap.has('s1')).toBe(true);
expect(storeSetMock).toHaveBeenCalledWith('s1', meta);
});
@@ -264,7 +443,15 @@ describe('removeWorktreeForSession', () => {
storeMap.set('s1', meta);
isWorktreeDirtyMock.mockResolvedValue(true);
autoStashMock.mockResolvedValue(true);
- gitExecMock.mockRejectedValueOnce(new Error('worktree locked'));
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: `refs/heads/${meta.branch}\n`, stderr: '' };
+ }
+ if (args[0] === 'worktree' && args[1] === 'remove') {
+ throw new Error('worktree locked');
+ }
+ return { stdout: '', stderr: '' };
+ });
await manager.removeWorktreeForSession('s1');
@@ -361,6 +548,9 @@ describe('removeWorktreeForSession', () => {
let removeAttempts = 0;
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: `refs/heads/${meta.branch}\n`, stderr: '' };
+ }
if (args[0] === 'worktree' && args[1] === 'remove') {
removeAttempts += 1;
if (removeAttempts < 3) throw new Error('locked');
@@ -403,7 +593,11 @@ describe('removeWorktreeForSession', () => {
releaseStash();
await Promise.all([first, second]);
- expect(gitExecMock).toHaveBeenCalledTimes(1);
+ expect(
+ gitExecMock.mock.calls.filter(
+ ([args]) => Array.isArray(args) && args[0] === 'worktree' && args[1] === 'remove',
+ ),
+ ).toHaveLength(1);
expect(gitExecMock).toHaveBeenCalledWith(
['worktree', 'remove', '--force', meta.path],
BASE_REPO,
@@ -430,12 +624,14 @@ describe('removeWorktreeForSession', () => {
it('discard pre-created: recovery waits for an in-flight create before deciding the record is absent', async () => {
let releaseGitVersion!: () => void;
gitExecMock.mockImplementationOnce(
- () => new Promise<{ stdout: string; stderr: string }>((resolve) => {
- releaseGitVersion = () => resolve({
- stdout: 'git version 2.50.0\n',
- stderr: '',
- });
- }),
+ () =>
+ new Promise<{ stdout: string; stderr: string }>((resolve) => {
+ releaseGitVersion = () =>
+ resolve({
+ stdout: 'git version 2.50.0\n',
+ stderr: '',
+ });
+ }),
);
const recoveryKey = 'recovery-key-123456';
const create = manager.createWorktree({
@@ -472,15 +668,11 @@ describe('removeWorktreeForSession', () => {
const canRemove = vi.fn(async () => false);
await expect(
- manager.discardPrecreatedWorktreeByRecoveryKey(
- 's1',
- meta.recoveryKey,
- { canRemove },
- ),
+ manager.discardPrecreatedWorktreeByRecoveryKey('s1', meta.recoveryKey, { canRemove }),
).resolves.toEqual({ status: 'preserved' });
expect(canRemove).toHaveBeenCalledTimes(1);
- expect(gitExecMock).not.toHaveBeenCalled();
+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
expect(storeMap.get('s1')).toBe(meta);
});
@@ -492,10 +684,7 @@ describe('removeWorktreeForSession', () => {
storeMap.set('s1', meta);
await expect(
- manager.discardPrecreatedWorktreeByRecoveryKey(
- 's1',
- 'different-key-123456',
- ),
+ manager.discardPrecreatedWorktreeByRecoveryKey('s1', 'different-key-123456'),
).resolves.toEqual({ status: 'path-mismatch' });
expect(gitExecMock).not.toHaveBeenCalled();
@@ -506,17 +695,13 @@ describe('removeWorktreeForSession', () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
isWorktreeDirtyMock.mockResolvedValue(true);
- gitExecMock.mockResolvedValueOnce({ stdout: '0\n', stderr: '' });
await expect(manager.discardPrecreatedWorktree('s1', meta.path)).resolves.toEqual({
status: 'preserved',
});
expect(autoStashMock).not.toHaveBeenCalled();
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
expect(storeMap.get('s1')).toBe(meta);
});
@@ -524,17 +709,13 @@ describe('removeWorktreeForSession', () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
const canRemove = vi.fn(async () => false);
- gitExecMock.mockResolvedValueOnce({ stdout: '0\n', stderr: '' });
await expect(
manager.discardPrecreatedWorktree('s1', meta.path, { canRemove }),
).resolves.toEqual({ status: 'preserved' });
expect(canRemove).toHaveBeenCalledTimes(1);
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
expect(storeMap.get('s1')).toBe(meta);
});
@@ -543,6 +724,9 @@ describe('removeWorktreeForSession', () => {
storeMap.set('s1', meta);
isWorktreeDirtyMock.mockResolvedValue(false);
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: `refs/heads/${meta.branch}\n`, stderr: '' };
+ }
if (args[0] === 'worktree' && args[1] === 'remove') {
throw new Error('worktree contains modified or untracked files');
}
@@ -553,18 +737,12 @@ describe('removeWorktreeForSession', () => {
status: 'preserved',
});
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
expect(gitExecMock).not.toHaveBeenCalledWith(
['worktree', 'remove', '--force', meta.path],
BASE_REPO,
);
- expect(gitExecMock).not.toHaveBeenCalledWith(
- expect.arrayContaining(['rev-list']),
- BASE_REPO,
- );
+ expect(gitExecMock).not.toHaveBeenCalledWith(expect.arrayContaining(['rev-list']), BASE_REPO);
expect(storeMap.get('s1')).toBe(meta);
});
@@ -579,10 +757,7 @@ describe('removeWorktreeForSession', () => {
});
expect(ignoredFilesMock).toHaveBeenCalledWith(BASE_REPO, meta.path);
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
expect(storeMap.get('s1')).toBe(meta);
});
@@ -597,10 +772,7 @@ describe('removeWorktreeForSession', () => {
});
expect(ignoredFilesMock).toHaveBeenCalledWith(BASE_REPO, meta.path);
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
});
it('quarantines the worktree before the final ignored-file scan', async () => {
@@ -615,13 +787,11 @@ describe('removeWorktreeForSession', () => {
path: worktreePath,
};
storeMap.set('s1', meta);
- ignoredFilesMock
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce(['.env']);
+ ignoredFilesMock.mockResolvedValueOnce([]).mockResolvedValueOnce(['.env']);
- await expect(
- manager.discardPrecreatedWorktree('s1', meta.path),
- ).resolves.toEqual({ status: 'preserved' });
+ await expect(manager.discardPrecreatedWorktree('s1', meta.path)).resolves.toEqual({
+ status: 'preserved',
+ });
const moves = gitExecMock.mock.calls.filter(
([args]) => Array.isArray(args) && args[0] === 'worktree' && args[1] === 'move',
@@ -632,15 +802,9 @@ describe('removeWorktreeForSession', () => {
expect(moves[1][0]).toEqual(['worktree', 'move', quarantinePath, meta.path]);
expect(ignoredFilesMock).toHaveBeenNthCalledWith(1, base, meta.path);
expect(ignoredFilesMock).toHaveBeenNthCalledWith(2, base, quarantinePath);
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', quarantinePath],
- base,
- );
+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', quarantinePath], base);
expect(storeMap.get('s1')).toEqual(meta);
- expect(storeSetMock).toHaveBeenCalledWith(
- 's1',
- expect.objectContaining({ quarantinePath }),
- );
+ expect(storeSetMock).toHaveBeenCalledWith('s1', expect.objectContaining({ quarantinePath }));
} finally {
fsSync.rmSync(tmpRoot, { recursive: true, force: true });
}
@@ -661,15 +825,13 @@ describe('removeWorktreeForSession', () => {
};
storeMap.set('s1', meta);
- await expect(
- manager.discardPrecreatedWorktree('s1', worktreePath),
- ).resolves.toEqual({ status: 'discarded', branchDeleted: false });
+ await expect(manager.discardPrecreatedWorktree('s1', worktreePath)).resolves.toEqual({
+ status: 'discarded',
+ branchDeleted: false,
+ });
expect(ignoredFilesMock).toHaveBeenCalledWith(base, quarantinePath);
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', quarantinePath],
- base,
- );
+ expect(gitExecMock).toHaveBeenCalledWith(['worktree', 'remove', quarantinePath], base);
expect(gitExecMock).not.toHaveBeenCalledWith(
['worktree', 'move', worktreePath, quarantinePath],
base,
@@ -694,9 +856,9 @@ describe('removeWorktreeForSession', () => {
storeMap.set('s1', meta);
storeSetMock.mockRejectedValueOnce(new Error('disk full'));
- await expect(
- manager.discardPrecreatedWorktree('s1', worktreePath),
- ).resolves.toEqual({ status: 'preserved' });
+ await expect(manager.discardPrecreatedWorktree('s1', worktreePath)).resolves.toEqual({
+ status: 'preserved',
+ });
expect(gitExecMock).not.toHaveBeenCalledWith(
['worktree', 'move', worktreePath, expect.any(String)],
@@ -715,11 +877,14 @@ describe('removeWorktreeForSession', () => {
gitExecMock.mockImplementation(async (args: string[]) => {
gitOperations.push(args[0] ?? '');
return {
- stdout: args[0] === 'rev-parse'
- ? 'abc123\n'
- : args[0] === 'rev-list'
- ? '0\n'
- : '',
+ stdout:
+ args[0] === 'symbolic-ref'
+ ? `refs/heads/${meta.branch}\n`
+ : args[0] === 'rev-parse'
+ ? 'abc123\n'
+ : args[0] === 'rev-list'
+ ? '0\n'
+ : '',
stderr: '',
};
});
@@ -733,15 +898,18 @@ describe('removeWorktreeForSession', () => {
['rev-list', '--count', `${meta.sourceBranch}..${meta.branch}`],
BASE_REPO,
);
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
expect(gitExecMock).toHaveBeenCalledWith(
['update-ref', '-d', `refs/heads/${meta.branch}`, 'abc123'],
BASE_REPO,
);
- expect(gitOperations).toEqual(['worktree', 'rev-parse', 'rev-list', 'update-ref']);
+ expect(gitOperations).toEqual([
+ 'symbolic-ref',
+ 'worktree',
+ 'rev-parse',
+ 'rev-list',
+ 'update-ref',
+ ]);
expect(storeMap.has('s1')).toBe(false);
});
@@ -749,11 +917,14 @@ describe('removeWorktreeForSession', () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
gitExecMock.mockImplementation(async (args: string[]) => ({
- stdout: args[0] === 'rev-parse'
- ? 'abc123\n'
- : args[0] === 'rev-list'
- ? '1\n'
- : '',
+ stdout:
+ args[0] === 'symbolic-ref'
+ ? `refs/heads/${meta.branch}\n`
+ : args[0] === 'rev-parse'
+ ? 'abc123\n'
+ : args[0] === 'rev-list'
+ ? '1\n'
+ : '',
stderr: '',
}));
@@ -762,10 +933,7 @@ describe('removeWorktreeForSession', () => {
branchDeleted: false,
});
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
expect(gitExecMock).not.toHaveBeenCalledWith(
expect.arrayContaining(['update-ref', '-d']),
BASE_REPO,
@@ -777,6 +945,9 @@ describe('removeWorktreeForSession', () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: `refs/heads/${meta.branch}\n`, stderr: '' };
+ }
if (args[0] === 'rev-parse') return { stdout: 'abc123\n', stderr: '' };
if (args[0] === 'rev-list') return { stdout: '0\n', stderr: '' };
if (args[0] === 'update-ref') throw new Error('cannot lock ref: expected abc123');
@@ -794,7 +965,7 @@ describe('removeWorktreeForSession', () => {
);
});
- it('discard pre-created: never deletes a branch that does not match the generated name', async () => {
+ it('discard pre-created: preserves a worktree registered to a non-managed branch', async () => {
const meta = {
...makeMeta('s1'),
branch: 'main',
@@ -802,21 +973,14 @@ describe('removeWorktreeForSession', () => {
storeMap.set('s1', meta);
await expect(manager.discardPrecreatedWorktree('s1', meta.path)).resolves.toEqual({
- status: 'discarded',
- branchDeleted: false,
+ status: 'preserved',
});
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', meta.path],
- BASE_REPO,
- );
+ expect(gitExecMock).not.toHaveBeenCalled();
expect(gitExecMock).not.toHaveBeenCalledWith(
expect.arrayContaining(['update-ref', '-d']),
BASE_REPO,
);
- expect(gitExecMock).not.toHaveBeenCalledWith(
- expect.arrayContaining(['rev-list']),
- BASE_REPO,
- );
+ expect(gitExecMock).not.toHaveBeenCalledWith(expect.arrayContaining(['rev-list']), BASE_REPO);
});
});
diff --git a/apps/desktop/src/main/__tests__/worktreeNameGenerator.test.ts b/apps/desktop/src/main/__tests__/worktreeNameGenerator.test.ts
index e8321c720b..3bba283411 100644
--- a/apps/desktop/src/main/__tests__/worktreeNameGenerator.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeNameGenerator.test.ts
@@ -5,10 +5,15 @@
import { describe, it, expect } from 'vitest';
import {
+ blocksManagedWorktreeBranchNamespace,
generateRawName,
avoidCollision,
generateUniqueName,
getBranchName,
+ getManagedWorktreeBranchCandidates,
+ getManagedWorktreeNameFromBranch,
+ getManagedWorktreeReservedName,
+ isManagedWorktreeBranchForName,
validateWorktreeName,
} from '../worktree/nameGenerator';
@@ -44,9 +49,33 @@ describe('nameGenerator', () => {
expect(avoidCollision('Jolly-Turing', ['JOLLY-TURING'])).toBe('Jolly-Turing-2');
});
- it('getBranchName prefixes xdt/', () => {
- expect(getBranchName('jolly-turing')).toBe('xdt/jolly-turing');
- expect(getBranchName('foo-bar-3')).toBe('xdt/foo-bar-3');
+ it('getBranchName prefixes new branches with cindy/', () => {
+ expect(getBranchName('jolly-turing')).toBe('cindy/jolly-turing');
+ expect(getBranchName('foo-bar-3')).toBe('cindy/foo-bar-3');
+ });
+
+ it('keeps recognizing legacy xdt/ branches without writing new ones', () => {
+ expect(getManagedWorktreeBranchCandidates('jolly-turing')).toEqual([
+ 'cindy/jolly-turing',
+ 'xdt/jolly-turing',
+ ]);
+ expect(getManagedWorktreeNameFromBranch('cindy/jolly-turing')).toBe('jolly-turing');
+ expect(getManagedWorktreeNameFromBranch('xdt/jolly-turing')).toBe('jolly-turing');
+ expect(getManagedWorktreeNameFromBranch('cindy/jolly-turing/child')).toBeNull();
+ expect(getManagedWorktreeNameFromBranch('xdt/jolly-turing/child')).toBeNull();
+ expect(getManagedWorktreeNameFromBranch('feature/jolly-turing')).toBeNull();
+ expect(isManagedWorktreeBranchForName('cindy/jolly-turing', 'jolly-turing')).toBe(true);
+ expect(isManagedWorktreeBranchForName('xdt/jolly-turing', 'jolly-turing')).toBe(true);
+ expect(isManagedWorktreeBranchForName('main', 'jolly-turing')).toBe(false);
+ });
+
+ it('reserves ref ancestors and descendants that would block cindy/<name>', () => {
+ expect(blocksManagedWorktreeBranchNamespace('cindy')).toBe(true);
+ expect(blocksManagedWorktreeBranchNamespace('xdt')).toBe(false);
+ expect(getManagedWorktreeReservedName('cindy/foo')).toBe('foo');
+ expect(getManagedWorktreeReservedName('cindy/foo/bar')).toBe('foo');
+ expect(getManagedWorktreeReservedName('xdt/foo')).toBe('foo');
+ expect(getManagedWorktreeReservedName('xdt/foo/bar')).toBeNull();
});
it('generateUniqueName always returns a name not in taken (after retries + suffix)', () => {
diff --git a/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts b/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
index 84d31793d9..a5a11ccf83 100644
--- a/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
@@ -8,6 +8,8 @@ import type { WorktreeMeta } from '../worktree/types';
const gitExecMock = vi.fn();
const isWorktreeDirtyMock = vi.fn();
+const resolveAvailableWorktreeNameMock = vi.fn();
+const createWorktreeMock = vi.fn();
const storeMap = new Map<string, WorktreeMeta>();
const liveSessionRows: Array<{
id: string;
@@ -35,7 +37,9 @@ vi.mock('../worktree/worktreeStore', () => ({
vi.mock('../worktree/WorktreeManager', () => ({
copyClaudeSiviDirs: vi.fn(),
- createWorktree: vi.fn(),
+ createWorktree: (...args: unknown[]) => createWorktreeMock(...args),
+ resolveAvailableWorktreeName: (...args: unknown[]) =>
+ resolveAvailableWorktreeNameMock(...args),
}));
vi.mock('../localDb/client/current', () => ({
@@ -89,6 +93,10 @@ describe('WorktreePool safety', () => {
liveSessionQueryCount = 0;
gitExecMock.mockReset();
isWorktreeDirtyMock.mockReset().mockResolvedValue(false);
+ resolveAvailableWorktreeNameMock
+ .mockReset()
+ .mockImplementation(async (_baseRepo: string, requestedName: string) => requestedName);
+ createWorktreeMock.mockReset();
rmSpy = vi.spyOn(fs, 'rm');
pool = await import('../worktree/WorktreePool');
@@ -218,8 +226,7 @@ describe('WorktreePool safety', () => {
const fetchCall = gitExecMock.mock.calls.find((c) => (c[0] as string[])[0] === 'fetch');
expect(fetchCall).toBeTruthy();
const opts = fetchCall?.[2] as
- | { timeoutMs?: number; extraEnv?: Record<string, string> }
- | undefined;
+ { timeoutMs?: number; extraEnv?: Record<string, string> } | undefined;
expect(opts?.timeoutMs).toBeGreaterThan(0);
expect(opts?.extraEnv?.GIT_TERMINAL_PROMPT).toBe('0');
});
@@ -248,6 +255,92 @@ describe('WorktreePool safety', () => {
expect(gitExecMock.mock.calls.some((c) => (c[0] as string[])[0] === 'fetch')).toBe(false);
});
+ it('reuses a legacy pooled worktree on a new cindy/* branch', async () => {
+ const meta = makeMeta(baseRepo, 'session-1', '2026-05-26T00:00:00.000Z');
+ fsSync.mkdirSync(meta.path, { recursive: true });
+ storeMap.set(meta.sessionId, meta);
+ await expect(pool.releaseWorktree(meta.sessionId)).resolves.toBe('pooled');
+ gitExecMock.mockClear();
+
+ const res = await pool.acquireWorktree({
+ sessionId: 'session-2',
+ name: 'reuse-1',
+ baseRepo,
+ sourceBranch: 'main',
+ ephemeral: true,
+ });
+
+ expect(res).toMatchObject({
+ ok: true,
+ meta: { name: 'reuse-1', branch: 'cindy/reuse-1' },
+ });
+ expect(gitExecMock).toHaveBeenCalledWith(
+ ['checkout', '--no-track', '-b', 'cindy/reuse-1', 'main'],
+ meta.path,
+ );
+ expect(
+ gitExecMock.mock.calls.some((call) => (call[0] as string[]).includes('-B')),
+ ).toBe(false);
+ });
+
+ it('uses the Manager-reserved name when reusing a pooled worktree', async () => {
+ const meta = makeMeta(baseRepo, 'session-1', '2026-05-26T00:00:00.000Z');
+ fsSync.mkdirSync(meta.path, { recursive: true });
+ storeMap.set(meta.sessionId, meta);
+ await expect(pool.releaseWorktree(meta.sessionId)).resolves.toBe('pooled');
+ gitExecMock.mockClear();
+ resolveAvailableWorktreeNameMock.mockResolvedValue('reuse-1-2');
+
+ const res = await pool.acquireWorktree({
+ sessionId: 'session-2',
+ name: 'reuse-1',
+ baseRepo,
+ sourceBranch: 'main',
+ ephemeral: true,
+ });
+
+ expect(res).toMatchObject({
+ ok: true,
+ meta: { name: 'reuse-1-2', branch: 'cindy/reuse-1-2' },
+ });
+ expect(gitExecMock).toHaveBeenCalledWith(
+ ['checkout', '--no-track', '-b', 'cindy/reuse-1-2', 'main'],
+ meta.path,
+ );
+ });
+
+ it('falls back without reset or clean when branch creation loses a collision race', async () => {
+ const meta = makeMeta(baseRepo, 'session-1', '2026-05-26T00:00:00.000Z');
+ fsSync.mkdirSync(meta.path, { recursive: true });
+ storeMap.set(meta.sessionId, meta);
+ await expect(pool.releaseWorktree(meta.sessionId)).resolves.toBe('pooled');
+ gitExecMock.mockClear();
+ const fallback = {
+ ok: false as const,
+ error: { kind: 'unknown' as const, message: 'fresh create failed' },
+ };
+ createWorktreeMock.mockResolvedValue(fallback);
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'checkout') throw new Error('branch already exists');
+ return { stdout: '', stderr: '' };
+ });
+
+ const req = {
+ sessionId: 'session-2',
+ name: 'reuse-1',
+ baseRepo,
+ sourceBranch: 'main',
+ ephemeral: true,
+ };
+ await expect(pool.acquireWorktree(req)).resolves.toBe(fallback);
+
+ const commands = gitExecMock.mock.calls.map((call) => call[0] as string[]);
+ expect(commands.some((args) => args[0] === 'reset')).toBe(false);
+ expect(commands.some((args) => args[0] === 'clean')).toBe(false);
+ expect(commands.some((args) => args.includes('-B'))).toBe(false);
+ expect(createWorktreeMock).toHaveBeenCalledWith(req);
+ });
+
it('preserves dirty worktrees instead of auto-stashing them into the pool', async () => {
const meta = makeMeta(baseRepo, 'session-1', '2026-05-26T00:00:00.000Z');
fsSync.mkdirSync(meta.path, { recursive: true });
diff --git a/apps/desktop/src/main/__tests__/worktreeRestore.test.ts b/apps/desktop/src/main/__tests__/worktreeRestore.test.ts
index aec6bd07b6..76b451c2df 100644
--- a/apps/desktop/src/main/__tests__/worktreeRestore.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRestore.test.ts
@@ -63,10 +63,14 @@ vi.mock('../localDb/client/current', () => ({
where: () => {
if ('id' in selection) return dbOwnerRows;
if (dbBindingRows.length > 0) return [dbBindingRows.shift()!];
- return dbWorktreePath === undefined ? [] : [{
- workingDir: dbWorkingDir,
- worktreePath: dbWorktreePath,
- }];
+ return dbWorktreePath === undefined
+ ? []
+ : [
+ {
+ workingDir: dbWorkingDir,
+ worktreePath: dbWorktreePath,
+ },
+ ];
},
}),
}),
@@ -119,19 +123,22 @@ describe('worktree restore', () => {
dbWorktreePath = null;
fsSync.mkdirSync(wtPath, { recursive: true });
const meta = { sessionId: 'owner', path: wtPath };
- storeGetMock.mockImplementation((sessionId: string) => sessionId === 'owner' ? meta : null);
+ storeGetMock.mockImplementation((sessionId: string) => (sessionId === 'owner' ? meta : null));
storeGetAllMock.mockReturnValue([meta]);
dbOwnerRows = [{ id: 'owner', worktreePath: null, status: 'active' }];
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/xdt/wt1\n', stderr: '' };
+ }
if (args[0] === 'rev-parse' && args.includes('refs/xdt/snapshots/owner')) {
return { stdout: `${SHA}\n`, stderr: '' };
}
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('borrower', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('borrower', wtPath)).resolves.toBe(
+ true,
+ );
const calls = gitExecMock.mock.calls.map(argsOf);
expect(calls).toContainEqual(['stash', 'apply', SHA]);
@@ -153,6 +160,94 @@ describe('worktree restore', () => {
});
});
+ it('present directory without Store metadata re-registers its actual HEAD branch', async () => {
+ fsSync.mkdirSync(wtPath, { recursive: true });
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/cindy/wt1\n', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.restoreWorktreeForSession('s1')).resolves.toEqual({
+ ok: true,
+ snapshotApplied: true,
+ });
+ expect(storeSetMock).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({ branch: 'cindy/wt1', sourceBranch: 'cindy/wt1' }),
+ );
+ });
+
+ it.each(['feature/foo', 'cindy/other'])(
+ 'present directory without Store metadata does not register non-candidate branch %s',
+ async (branch) => {
+ fsSync.mkdirSync(wtPath, { recursive: true });
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: `refs/heads/${branch}\n`, stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.restoreWorktreeForSession('s1')).resolves.toEqual({
+ ok: true,
+ snapshotApplied: true,
+ });
+ expect(storeSetMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it('preserves a pending snapshot when the existing directory is on a custom branch', async () => {
+ fsSync.mkdirSync(wtPath, { recursive: true });
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/feature/manual-switch\n', stderr: '' };
+ }
+ if (args[0] === 'rev-parse' && args.includes('refs/xdt/snapshots/s1')) {
+ return { stdout: `${SHA}\n`, stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.restoreWorktreeForSession('s1')).resolves.toEqual({
+ ok: true,
+ snapshotApplied: false,
+ });
+ expect(gitExecMock.mock.calls.map(argsOf)).not.toContainEqual(['stash', 'apply', SHA]);
+ expect(storeSetMock).not.toHaveBeenCalled();
+ });
+
+ it('present directory prefers actual HEAD when Store metadata is stale', async () => {
+ fsSync.mkdirSync(wtPath, { recursive: true });
+ storeGetMock
+ .mockReturnValueOnce({
+ sessionId: 's1',
+ name: 'wt1',
+ path: wtPath,
+ baseRepo,
+ branch: 'xdt/wt1',
+ sourceBranch: 'main',
+ createdAt: '2026-08-04T00:00:00.000Z',
+ })
+ .mockReturnValueOnce(null);
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/cindy/wt1\n', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.restoreWorktreeForSession('s1')).resolves.toEqual({
+ ok: true,
+ snapshotApplied: true,
+ });
+ expect(storeSetMock).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({ branch: 'cindy/wt1', sourceBranch: 'cindy/wt1' }),
+ );
+ });
+
it('legacy .xdt-worktrees directory still on disk → present', async () => {
const legacyPath = path.join(baseRepo, '.xdt-worktrees', 'wt1');
fsSync.mkdirSync(legacyPath, { recursive: true });
@@ -168,6 +263,9 @@ describe('worktree restore', () => {
it('present directory with pending snapshot stays restorable and retries apply', async () => {
fsSync.mkdirSync(wtPath, { recursive: true });
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/xdt/wt1\n', stderr: '' };
+ }
if (args[0] === 'rev-parse' && args.includes('refs/xdt/snapshots/s1')) {
return { stdout: `${SHA}\n`, stderr: '' };
}
@@ -194,10 +292,10 @@ describe('worktree restore', () => {
it('present directory ignores a consumed snapshot ref left behind after apply', async () => {
fsSync.mkdirSync(wtPath, { recursive: true });
gitExecMock.mockImplementation(async (args: string[]) => {
- if (args[0] === 'rev-parse' && (
- args.includes('refs/xdt/snapshots/s1')
- || args.includes('refs/xdt/snapshots-consumed/s1')
- )) {
+ if (
+ args[0] === 'rev-parse' &&
+ (args.includes('refs/xdt/snapshots/s1') || args.includes('refs/xdt/snapshots-consumed/s1'))
+ ) {
return { stdout: `${SHA}\n`, stderr: '' };
}
return { stdout: '', stderr: '' };
@@ -219,10 +317,10 @@ describe('worktree restore', () => {
it('local and origin tracking branches missing → gone', async () => {
gitExecMock.mockImplementation(async (args: string[]) => {
- if (args[0] === 'rev-parse' && (
- args.includes('refs/heads/xdt/wt1')
- || args.includes('refs/remotes/origin/xdt/wt1')
- )) {
+ if (
+ args[0] === 'rev-parse' &&
+ (args.includes('refs/heads/xdt/wt1') || args.includes('refs/remotes/origin/xdt/wt1'))
+ ) {
throw new Error('unknown revision');
}
return { stdout: '', stderr: '' };
@@ -251,6 +349,54 @@ describe('worktree restore', () => {
});
});
+ it('new cindy branch missing locally + origin tracking branch present → restorable', async () => {
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'rev-parse' && args.includes('refs/heads/cindy/wt1')) {
+ throw new Error('unknown revision');
+ }
+ if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/cindy/wt1')) {
+ return { stdout: 'deadbeef\n', stderr: '' };
+ }
+ if (
+ args[0] === 'rev-parse' &&
+ (args.includes('refs/heads/xdt/wt1') || args.includes('refs/remotes/origin/xdt/wt1'))
+ ) {
+ throw new Error('unknown revision');
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.getWorktreeRestoreStatus('s1')).resolves.toEqual({
+ state: 'restorable',
+ worktreePath: wtPath,
+ hasSnapshot: false,
+ });
+ });
+
+ it('new and legacy branches both exist → fail closed without restoring either', async () => {
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (
+ args[0] === 'rev-parse' &&
+ (args.includes('refs/heads/cindy/wt1') || args.includes('refs/heads/xdt/wt1'))
+ ) {
+ return { stdout: 'deadbeef\n', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.getWorktreeRestoreStatus('s1')).resolves.toEqual({
+ state: 'gone',
+ worktreePath: wtPath,
+ });
+ await expect(mod.restoreWorktreeForSession('s1')).resolves.toEqual({
+ ok: false,
+ reason: 'gone',
+ });
+ const calls = gitExecMock.mock.calls.map(argsOf);
+ expect(calls.some((args) => args[0] === 'branch')).toBe(false);
+ expect(calls.some((args) => args[0] === '-c' && args[3] === 'add')).toBe(false);
+ });
+
it('branch present + snapshot present → restorable with hasSnapshot', async () => {
gitExecMock.mockImplementation(async (args: string[]) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/xdt/wt1')) {
@@ -268,6 +414,81 @@ describe('worktree restore', () => {
});
});
+ it('Store branch wins even when the pooled path basename differs from meta.name', async () => {
+ const pooledMeta = {
+ sessionId: 's1',
+ name: 'scheduled-task',
+ path: wtPath,
+ baseRepo,
+ branch: 'xdt/scheduled-task',
+ sourceBranch: 'main',
+ createdAt: '2026-08-04T00:00:00.000Z',
+ };
+ storeGetMock.mockReturnValue(pooledMeta);
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'rev-parse' && args.includes('refs/heads/xdt/scheduled-task')) {
+ return { stdout: 'deadbeef\n', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.restoreWorktreeForSession('s1')).resolves.toEqual({
+ ok: true,
+ snapshotApplied: true,
+ });
+ expect(gitExecMock.mock.calls.map(argsOf)).toContainEqual([
+ '-c',
+ 'core.longpaths=true',
+ 'worktree',
+ 'add',
+ wtPath,
+ 'xdt/scheduled-task',
+ ]);
+ expect(storeSetMock).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({ name: 'scheduled-task', branch: 'xdt/scheduled-task' }),
+ );
+ });
+
+ it('ignores a custom Store branch and restores only the matching managed candidate', async () => {
+ storeGetMock.mockReturnValue({
+ sessionId: 's1',
+ name: 'wt1',
+ path: wtPath,
+ baseRepo,
+ branch: 'feature/manual-switch',
+ sourceBranch: 'main',
+ createdAt: '2026-08-04T00:00:00.000Z',
+ });
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'rev-parse' && args.includes('refs/heads/xdt/wt1')) {
+ return { stdout: 'deadbeef\n', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(mod.restoreWorktreeForSession('s1')).resolves.toEqual({
+ ok: true,
+ snapshotApplied: true,
+ });
+
+ const calls = gitExecMock.mock.calls.map(argsOf);
+ expect(calls).not.toContainEqual([
+ 'rev-parse',
+ '--verify',
+ '--quiet',
+ 'refs/heads/feature/manual-switch',
+ ]);
+ expect(calls).toContainEqual([
+ '-c',
+ 'core.longpaths=true',
+ 'worktree',
+ 'add',
+ wtPath,
+ 'xdt/wt1',
+ ]);
+ });
+
it('restore: worktree add + snapshot apply + store re-register', async () => {
gitExecMock.mockImplementation(async (args: string[]) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/xdt/wt1')) {
@@ -298,12 +519,15 @@ describe('worktree restore', () => {
overwriteExisting: false,
});
expect(calls.some((a) => a[0] === 'stash' && a[1] === 'apply' && a[2] === SHA)).toBe(true);
- const snapshotApplyOrder = gitExecMock.mock.invocationCallOrder[
- calls.findIndex((a) => a[0] === 'stash' && a[1] === 'apply' && a[2] === SHA)
- ];
+ const snapshotApplyOrder =
+ gitExecMock.mock.invocationCallOrder[
+ calls.findIndex((a) => a[0] === 'stash' && a[1] === 'apply' && a[2] === SHA)
+ ];
expect(snapshotApplyOrder).toBeLessThan(copyClaudeSiviDirsMock.mock.invocationCallOrder[0]!);
expect(snapshotApplyOrder).toBeLessThan(applyIncludeMock.mock.invocationCallOrder[0]!);
- expect(calls.some((a) => a[0] === 'update-ref' && a[1] === '-d' && a[2] === 'refs/xdt/snapshots/s1')).toBe(true);
+ expect(
+ calls.some((a) => a[0] === 'update-ref' && a[1] === '-d' && a[2] === 'refs/xdt/snapshots/s1'),
+ ).toBe(true);
expect(storeSetMock).toHaveBeenCalledWith(
's1',
expect.objectContaining({ sessionId: 's1', path: wtPath, branch: 'xdt/wt1' }),
@@ -334,20 +558,14 @@ describe('worktree restore', () => {
const calls = gitExecMock.mock.calls.map(argsOf);
const createBranchIndex = calls.findIndex((args) => args[0] === 'branch');
const addWorktreeIndex = calls.findIndex((args) => args[0] === '-c' && args[3] === 'add');
- expect(calls[createBranchIndex]).toEqual([
- 'branch',
- 'xdt/wt1',
- 'refs/remotes/origin/xdt/wt1',
- ]);
+ expect(calls[createBranchIndex]).toEqual(['branch', 'xdt/wt1', 'refs/remotes/origin/xdt/wt1']);
expect(createBranchIndex).toBeLessThan(addWorktreeIndex);
});
it('send-time restore only accepts the DB-authoritative managed path', async () => {
const stalePath = path.join(baseRepo, '.cindy-worktrees', 'stale');
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', stalePath),
- ).resolves.toBe(false);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', stalePath)).resolves.toBe(false);
expect(gitExecMock).not.toHaveBeenCalled();
});
@@ -355,9 +573,7 @@ describe('worktree restore', () => {
it('send-time restore rejects a historical worktree after DB working_dir moved', async () => {
dbWorkingDir = baseRepo;
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(false);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(false);
expect(gitExecMock).not.toHaveBeenCalled();
});
@@ -366,9 +582,7 @@ describe('worktree restore', () => {
dbWorktreePath = null;
fsSync.mkdirSync(wtPath, { recursive: true });
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
expect(gitExecMock).not.toHaveBeenCalled();
expect(storeSetMock).not.toHaveBeenCalled();
@@ -376,22 +590,28 @@ describe('worktree restore', () => {
it('send-time check applies the owning session snapshot before allowing a non-owner', async () => {
fsSync.mkdirSync(wtPath, { recursive: true });
- const equivalentOwnerPath = path.join(path.dirname(wtPath), 'nested', '..', path.basename(wtPath));
+ const equivalentOwnerPath = path.join(
+ path.dirname(wtPath),
+ 'nested',
+ '..',
+ path.basename(wtPath),
+ );
dbBindingRows = [
{ workingDir: wtPath, worktreePath: null },
{ workingDir: wtPath, worktreePath: equivalentOwnerPath },
];
dbOwnerRows = [{ id: 'owner', worktreePath: equivalentOwnerPath, status: 'active' }];
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/xdt/wt1\n', stderr: '' };
+ }
if (args[0] === 'rev-parse' && args.includes('refs/xdt/snapshots/owner')) {
return { stdout: `${SHA}\n`, stderr: '' };
}
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
const calls = gitExecMock.mock.calls.map(argsOf);
expect(calls).toContainEqual(['stash', 'apply', SHA]);
@@ -405,9 +625,7 @@ describe('worktree restore', () => {
it('send-time check does not rebuild a missing managed worktree for a non-owner', async () => {
dbWorktreePath = null;
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(false);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(false);
expect(gitExecMock).not.toHaveBeenCalled();
expect(storeSetMock).not.toHaveBeenCalled();
@@ -417,7 +635,9 @@ describe('worktree restore', () => {
fsSync.mkdirSync(wtPath, { recursive: true });
dbWorktreePath = null;
const deletedMeta = { sessionId: 'deleted-owner', path: wtPath };
- storeGetMock.mockImplementation((sessionId: string) => sessionId === 'deleted-owner' ? deletedMeta : null);
+ storeGetMock.mockImplementation((sessionId: string) =>
+ sessionId === 'deleted-owner' ? deletedMeta : null,
+ );
storeGetAllMock.mockReturnValue([deletedMeta]);
dbOwnerRows = [{ id: 'deleted-owner', worktreePath: wtPath, status: 'deleted' }];
gitExecMock.mockImplementation(async (args: string[]) => {
@@ -427,9 +647,7 @@ describe('worktree restore', () => {
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
expect(gitExecMock).not.toHaveBeenCalled();
expect(storeSetMock).not.toHaveBeenCalled();
@@ -439,15 +657,16 @@ describe('worktree restore', () => {
fsSync.mkdirSync(wtPath, { recursive: true });
storeGetMock.mockReturnValue({ sessionId: 's1', path: wtPath });
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/xdt/wt1\n', stderr: '' };
+ }
if (args[0] === 'rev-parse' && args.includes('refs/xdt/snapshots/s1')) {
return { stdout: `${SHA}\n`, stderr: '' };
}
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
const calls = gitExecMock.mock.calls.map(argsOf);
expect(calls).toContainEqual(['stash', 'apply', SHA]);
@@ -460,14 +679,17 @@ describe('worktree restore', () => {
let releaseMutation!: () => void;
const mutation = withWorktreeRestoreMutation(
's1',
- () => new Promise<void>((resolve) => {
- releaseMutation = resolve;
- }),
+ () =>
+ new Promise<void>((resolve) => {
+ releaseMutation = resolve;
+ }),
);
const readiness = mod.restoreMissingManagedWorktreeForSession('s1', wtPath);
let settled = false;
- void readiness.finally(() => { settled = true; });
+ void readiness.finally(() => {
+ settled = true;
+ });
await Promise.resolve();
expect(settled).toBe(false);
expect(gitExecMock).not.toHaveBeenCalled();
@@ -481,23 +703,22 @@ describe('worktree restore', () => {
storeGetMock.mockReturnValue({ sessionId: 's1', path: wtPath });
let fallbackStashPresent = false;
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/xdt/wt1\n', stderr: '' };
+ }
if (args[0] === 'stash' && args[1] === 'list') {
return { stdout: fallbackStashPresent ? `${AUTO_STASH}\n` : '', stderr: '' };
}
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
await withWorktreeRestoreMutation('s1', async () => {
fallbackStashPresent = true;
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
expect(gitExecMock.mock.calls.map(argsOf)).toContainEqual(['stash', 'apply', SHA]);
});
@@ -505,13 +726,9 @@ describe('worktree restore', () => {
fsSync.mkdirSync(wtPath, { recursive: true });
storeGetMock.mockReturnValue({ sessionId: 's1', path: wtPath });
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
const callsAfterFirstSend = gitExecMock.mock.calls.length;
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
expect(gitExecMock.mock.calls).toHaveLength(callsAfterFirstSend);
});
@@ -533,9 +750,7 @@ describe('worktree restore', () => {
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(true);
expect(storeSetMock).toHaveBeenCalledWith(
's1',
@@ -556,9 +771,7 @@ describe('worktree restore', () => {
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', childPath),
- ).resolves.toBe(true);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', childPath)).resolves.toBe(true);
expect(gitExecMock.mock.calls.map(argsOf)).toContainEqual([
'-c',
@@ -584,9 +797,7 @@ describe('worktree restore', () => {
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', childPath),
- ).resolves.toBe(false);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', childPath)).resolves.toBe(false);
});
it('concurrent restore requests share one worktree mutation', async () => {
@@ -614,8 +825,12 @@ describe('worktree restore', () => {
it('concurrent send-time restores wait for snapshot apply before allowing either send', async () => {
let releaseApply!: () => void;
let signalApplyStarted!: () => void;
- const applyStarted = new Promise<void>((resolve) => { signalApplyStarted = resolve; });
- const applyRelease = new Promise<void>((resolve) => { releaseApply = resolve; });
+ const applyStarted = new Promise<void>((resolve) => {
+ signalApplyStarted = resolve;
+ });
+ const applyRelease = new Promise<void>((resolve) => {
+ releaseApply = resolve;
+ });
gitExecMock.mockImplementation(async (args: string[]) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/xdt/wt1')) {
return { stdout: 'deadbeef\n', stderr: '' };
@@ -638,7 +853,9 @@ describe('worktree restore', () => {
await applyStarted;
const second = mod.restoreMissingManagedWorktreeForSession('s1', wtPath);
let secondSettled = false;
- void second.finally(() => { secondSettled = true; });
+ void second.finally(() => {
+ secondSettled = true;
+ });
await Promise.resolve();
expect(secondSettled).toBe(false);
@@ -651,6 +868,9 @@ describe('worktree restore', () => {
it('send-time restore remains blocked and retries a pending snapshot after apply conflict', async () => {
gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'symbolic-ref') {
+ return { stdout: 'refs/heads/xdt/wt1\n', stderr: '' };
+ }
if (args[0] === 'rev-parse' && args.includes('refs/heads/xdt/wt1')) {
return { stdout: 'deadbeef\n', stderr: '' };
}
@@ -664,12 +884,8 @@ describe('worktree restore', () => {
return { stdout: '', stderr: '' };
});
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(false);
- await expect(
- mod.restoreMissingManagedWorktreeForSession('s1', wtPath),
- ).resolves.toBe(false);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(false);
+ await expect(mod.restoreMissingManagedWorktreeForSession('s1', wtPath)).resolves.toBe(false);
const calls = gitExecMock.mock.calls.map(argsOf);
expect(calls.filter((args) => args[0] === '-c' && args[3] === 'add')).toHaveLength(1);
diff --git a/apps/desktop/src/main/maker-ipc/handoffWorktree.ts b/apps/desktop/src/main/maker-ipc/handoffWorktree.ts
index d493d430e4..5b5a9a722f 100644
--- a/apps/desktop/src/main/maker-ipc/handoffWorktree.ts
+++ b/apps/desktop/src/main/maker-ipc/handoffWorktree.ts
@@ -1,13 +1,19 @@
import path from 'node:path';
-import type { CreateWorktreeReq, CreateWorktreeResp, DetectCwdResp, ListBranchesResp, WorktreeMeta } from '../worktree/types.js';
+import type {
+ CreateWorktreeReq,
+ CreateWorktreeResp,
+ DetectCwdResp,
+ ListBranchesResp,
+ WorktreeMeta,
+} from '../worktree/types.js';
/**
* send_to_session create 分支的 worktree 准备逻辑(use_worktree=true 时)。
*
* 职责:从 dispatcher session 的 workingDir 解析出 base repo,然后为「即将创建的
* 新 session」预建一个正规的 session worktree(与 UI 新会话勾选 worktree 产出的
- * 完全同类:.cindy-worktrees/<name> + xdt/<name> 分支、worktreeStore 绑定、关闭时
+ * 完全同类:.cindy-worktrees/<name> + cindy/<name> 分支、worktreeStore 绑定、关闭时
* auto-stash 清理)。调用方拿到 worktree 路径后以其为 workingDir 创建 session。
*
* base repo 解析的三种情况(按序):
@@ -41,8 +47,7 @@ export interface HandoffWorktreeDeps {
}
export type PrepareHandoffWorktreeResult =
- | { ok: true; sessionId: string; meta: WorktreeMeta }
- | { ok: false; message: string };
+ { ok: true; sessionId: string; meta: WorktreeMeta } | { ok: false; message: string };
/** a 是否等于 b 或位于 b 目录之下(大小写按 Windows 习惯不敏感比较,POSIX 敏感)。 */
function isSamePathOrUnder(a: string, b: string): boolean {
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index 3c946042e8..817894d0f3 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -164,6 +164,6 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
id: "worktrees",
title: "Working in an isolated git worktree",
summary: "Opt a session into an isolated git worktree so its changes stay on their own branch and folder.",
- content: "A session can run inside its own **git worktree** — a separate working copy of the same repository on its own branch — so the agent's edits don't mix with your main checkout.\n\n**Opting in:**\n\n- In the new-chat view, click the working-directory chip → the **gear** icon to open the Advanced popover → tick the **worktree** checkbox.\n- The worktree is created **on first message send**, not on session create. An overlay shows the status (creating / ready / failed).\n\n**Where it goes:**\n\n- Folder: `<repo>/.cindy-worktrees/<auto-generated-name>/` — kept inside the same repo so git tooling can find it. Worktrees created by older versions under `.xdt-worktrees/` remain supported.\n- Branch: `xdt/<auto-generated-name>` — auto-created off the source branch you pick, which defaults to the repo's current branch (HEAD).\n\n**Lifecycle:**\n\n- Created on first agent turn that needs files.\n- Survives across app restarts as long as the session is around. Transient closes (`/clear`, reconnecting, quitting the app) do **not** remove it.\n- The folder is removed only when you explicitly **delete or archive** the session; the **branch is preserved** (no force-delete), so you can keep the work or merge / cherry-pick from it later.\n- Uncommitted changes inside the worktree are **auto-stashed** before the folder is removed, so nothing is silently lost. Removal is also skipped if you leave a `.worktree-keep` file in it or another live session is still using it.\n\n**When the option is disabled:**\n\n- Git is not installed on your machine.\n- The chosen working directory isn't a git repository.\n- The chosen directory is already inside an existing worktree (no nesting).\n\n**Error cases (shown on the overlay):**\n\n- `permission-denied` (can't write into the repo dir), `git-crypt-locked` (repo uses git-crypt and isn't unlocked), `dubious-ownership` (git's safe.directory check tripped), `lfs-error`, `not-a-git-repo`, `git-not-installed`.\n\n**Notes:**\n\n- The agent's **Read / Write / Bash** tools automatically operate inside the worktree path — you don't need to switch directories manually.\n- Because the branch survives the worktree, \"did the agent's changes go anywhere?\" is always answerable with `git branch --list 'xdt/*'`.\n- Worktrees are a per-session opt-in — they're not on by default and they don't change non-worktree sessions in any way.",
+ content: "A session can run inside its own **git worktree** — a separate working copy of the same repository on its own branch — so the agent's edits don't mix with your main checkout.\n\n**Opting in:**\n\n- In the new-chat view, click the working-directory chip → the **gear** icon to open the Advanced popover → tick the **worktree** checkbox.\n- The worktree is created **on first message send**, not on session create. An overlay shows the status (creating / ready / failed).\n\n**Where it goes:**\n\n- Folder: `<repo>/.cindy-worktrees/<auto-generated-name>/` — kept inside the same repo so git tooling can find it. Worktrees created by older versions under `.xdt-worktrees/` remain supported.\n- Branch: `cindy/<auto-generated-name>` — auto-created off the source branch you pick, which defaults to the repo's current branch (HEAD). Branches created by older versions under `xdt/` remain supported and do not need to be renamed.\n\n**Lifecycle:**\n\n- Created on first agent turn that needs files.\n- Survives across app restarts as long as the session is around. Transient closes (`/clear`, reconnecting, quitting the app) do **not** remove it.\n- The folder is removed only when you explicitly **delete or archive** the session; the **branch is preserved** (no force-delete), so you can keep the work or merge / cherry-pick from it later.\n- Uncommitted changes inside the worktree are **auto-stashed** before the folder is removed, so nothing is silently lost. Removal is also skipped if you leave a `.worktree-keep` file in it or another live session is still using it.\n\n**When the option is disabled:**\n\n- Git is not installed on your machine.\n- The chosen working directory isn't a git repository.\n- The chosen directory is already inside an existing worktree (no nesting).\n\n**Error cases (shown on the overlay):**\n\n- `permission-denied` (can't write into the repo dir), `git-crypt-locked` (repo uses git-crypt and isn't unlocked), `dubious-ownership` (git's safe.directory check tripped), `lfs-error`, `not-a-git-repo`, `git-not-installed`.\n\n**Notes:**\n\n- The agent's **Read / Write / Bash** tools automatically operate inside the worktree path — you don't need to switch directories manually.\n- Because the branch survives the worktree, \"did the agent's changes go anywhere?\" is always answerable with `git branch --list 'cindy/*' 'xdt/*'`.\n- Worktrees are a per-session opt-in — they're not on by default and they don't change non-worktree sessions in any way.",
},
];
diff --git a/apps/desktop/src/main/scheduler-host/workdir-resolver.ts b/apps/desktop/src/main/scheduler-host/workdir-resolver.ts
index de20a74631..1a6c6924bb 100644
--- a/apps/desktop/src/main/scheduler-host/workdir-resolver.ts
+++ b/apps/desktop/src/main/scheduler-host/workdir-resolver.ts
@@ -18,7 +18,7 @@ export interface WorkdirResolveResult {
ok: boolean;
path?: string;
/**
- * Worktree 上新建的分支名(如 `xdt/sched-abc12345`)。
+ * Worktree 上新建的分支名(如 `cindy/sched-abc12345`)。
* 仅 useWorktree=true 时填;非 worktree 模式下保持 undefined。
* Runner 应优先使用此字段,避免再用 `git rev-parse --abbrev-ref HEAD` 兜底。
*/
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index f6c5585228..478af05518 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -15,20 +15,19 @@ import path from 'node:path';
import fs from 'node:fs/promises';
import {
+ blocksManagedWorktreeBranchNamespace,
generateUniqueName,
avoidCollision,
getBranchName,
+ getManagedWorktreeNameFromBranch,
+ getManagedWorktreeReservedName,
+ isManagedWorktreeBranchForName,
validateWorktreeName,
} from './nameGenerator';
-import {
- classifyError,
- type ClassifyInput,
-} from './errorClassifier';
+import { readAttachedWorktreeBranch } from './attachedBranch';
+import { classifyError, type ClassifyInput } from './errorClassifier';
import { gitExec, GitExecError } from './gitExec';
-import {
- applyWorktreeIncludeFile,
- listChangedWorktreeIncludeFiles,
-} from './includePatternsEngine';
+import { applyWorktreeIncludeFile, listChangedWorktreeIncludeFiles } from './includePatternsEngine';
import { hasKeepSentinel, isManagedWorktreePath } from './safety';
import {
isWorktreeDirty,
@@ -133,7 +132,10 @@ async function withCreateWorktreeQueue<T>(baseRepo: string, fn: () => Promise<T>
const current = new Promise<void>((resolve) => {
releaseCurrent = resolve;
});
- const queued = previous.then(() => current, () => current);
+ const queued = previous.then(
+ () => current,
+ () => current,
+ );
createWorktreeQueues.set(key, queued);
await previous.catch(() => {});
@@ -161,7 +163,10 @@ async function withPrecreatedWorktreeOperationQueue<T>(
const current = new Promise<void>((resolve) => {
releaseCurrent = resolve;
});
- const queued = previous.then(() => current, () => current);
+ const queued = previous.then(
+ () => current,
+ () => current,
+ );
precreatedWorktreeOperationQueues.set(sessionId, queued);
await previous.catch(() => {});
@@ -254,10 +259,7 @@ export async function detectCwd(cwd: string): Promise<DetectCwdResp> {
* 用 `git branch --format=%(refname:short)` 拿干净的分支列表。
*/
export async function listBranches(baseRepo: string): Promise<ListBranchesResp> {
- const { stdout } = await gitExec(
- ['branch', '--format=%(refname:short)'],
- baseRepo,
- );
+ const { stdout } = await gitExec(['branch', '--format=%(refname:short)'], baseRepo);
const branches = stdout
.split(/\r?\n/)
.map((s) => s.trim())
@@ -286,7 +288,7 @@ export async function revParseCommit(repoDir: string, ref: string): Promise<stri
}
/**
- * 列出已被本仓库占用的名字: store 里 sessionId → name + git 分支 xdt/* 去前缀。
+ * 列出已被本仓库占用的名字: store 里 sessionId → name + 当前/历史托管分支去前缀。
* 用于 nameGenerator 冲突避让 + create 阶段二次校验。
*/
async function getTakenNames(baseRepo: string): Promise<string[]> {
@@ -297,15 +299,41 @@ async function getTakenNames(baseRepo: string): Promise<string[]> {
taken.add(meta.name);
}
}
- // git branches: 仅 xdt/* 前缀
+ // 本地与 origin tracking 分支都纳入占用判定:否则本地无 xdt/foo、
+ // 远端尚有 origin/xdt/foo 时又新建 cindy/foo,回收后会出现双候选歧义。
+ // 必须保留完整 ref namespace;短名 `origin/cindy` 既可能是本地
+ // refs/heads/origin/cindy,也可能是 refs/remotes/origin/cindy,不能靠字符串去前缀猜。
+ let branchesOutput: string;
try {
- const { stdout } = await gitExec(['branch', '--format=%(refname:short)'], baseRepo);
- for (const line of stdout.split(/\r?\n/)) {
- const t = line.trim();
- if (t.startsWith('xdt/')) taken.add(t.slice('xdt/'.length));
- }
+ ({ stdout: branchesOutput } = await gitExec(
+ ['branch', '--all', '--format=%(refname)'],
+ baseRepo,
+ ));
} catch {
// ignore — 拿不到 git 分支时仅用 store
+ return [...taken];
+ }
+ const localRefPrefix = 'refs/heads/';
+ const originRefPrefix = 'refs/remotes/origin/';
+ for (const line of branchesOutput.split(/\r?\n/)) {
+ const ref = line.trim();
+ const isLocal = ref.startsWith(localRefPrefix);
+ const isOriginTracking = ref.startsWith(originRefPrefix);
+ if (!isLocal && !isOriginTracking) continue;
+
+ const branch = ref.slice((isLocal ? localRefPrefix : originRefPrefix).length);
+ const displayBranch = isLocal ? branch : `origin/${branch}`;
+ if (isLocal && blocksManagedWorktreeBranchNamespace(branch)) {
+ throw new Error(
+ `无法创建 Cindy Worktree:分支 "${displayBranch}" 占用了 "cindy/*" 命名空间。请先重命名或删除该分支。`,
+ );
+ }
+ // 本地 current-prefix 后代 ref 会在 refs/heads 下真实阻塞父级,需预留首段;
+ // origin tracking refs 与本地 heads 分属不同 namespace,仅精确托管分支参与占用。
+ const reservedName = isLocal
+ ? getManagedWorktreeReservedName(branch)
+ : getManagedWorktreeNameFromBranch(branch);
+ if (reservedName) taken.add(reservedName);
}
return [...taken];
}
@@ -318,6 +346,14 @@ export async function suggestName(baseRepo: string): Promise<string> {
return generateUniqueName(taken);
}
+/** Pool 与完整创建流程共用的显式名称避让入口。 */
+export async function resolveAvailableWorktreeName(
+ baseRepo: string,
+ requestedName: string,
+): Promise<string> {
+ return avoidCollision(requestedName, await getTakenNames(baseRepo));
+}
+
export function getForSession(sessionId: string): WorktreeMeta | null {
return store.get(sessionId);
}
@@ -462,9 +498,7 @@ async function configureHooksPath(worktreePath: string, baseRepo: string): Promi
// 让 worktree 的 hooks 仍指向源 repo 的 .git/hooks(共享 husky / pre-commit 等)
// git config 的路径以正斜杠书写最稳妥(Windows 下反斜杠会被转义), 这里统一标准化
const hooksPath = path.join(baseRepo, '.git', 'hooks').replace(/\\/g, '/');
- await gitExec(
- ['-C', worktreePath, 'config', 'core.hooksPath', hooksPath],
- );
+ await gitExec(['-C', worktreePath, 'config', 'core.hooksPath', hooksPath]);
}
const CLAUDE_COPY_EXCLUDED_TOP_LEVEL_DIRS = new Set(['worktrees']);
@@ -565,7 +599,7 @@ async function listProtectedClaudeSiviPaths(
/**
* git worktree add 参数(导出仅供单测断言)。--no-track 是分支边界约束:sourceBranch
* 现在常是远端跟踪引用(refs/remotes/<remote>/<默认分支>),不加它 git 会按
- * branch.autoSetupMerge 默认给新 xdt/* 分支挂上对远端默认分支的 upstream 配置
+ * branch.autoSetupMerge 默认给新托管分支挂上对远端默认分支的 upstream 配置
* (branch.<name>.remote/merge)——此后裸 git push/pull 可能误推/误并默认分支,
* 破坏自动 worktree 的独立分支边界;起点是本地分支时 --no-track 为无害 no-op。
*/
@@ -620,7 +654,7 @@ export async function copyClaudeSiviDirs(
* 2. listBranches 校验 sourceBranch 存在
* 3. 计算 path = baseRepo/.cindy-worktrees/<name>; 已存在 → 重新 avoidCollision 拿一个
* 4. mkdirp parent
- * 5. git worktree add -b xdt/<name> <path> <sourceBranch>
+ * 5. git worktree add -b cindy/<name> <path> <sourceBranch>
* 失败时若 stderr 含 core.longpaths → 自动 git config --global core.longpaths true 重试一次
* 6. configureHooksPath
* 7. copyClaudeSiviDirs(跳过 .claude/worktrees 这类历史工作区状态)
@@ -628,21 +662,14 @@ export async function copyClaudeSiviDirs(
* 9. git config --global --add safe.directory <path>
* 10. worktreeStore.set(sessionId, meta) → 同步写 sessions.worktree_path
*/
-export async function createWorktree(
- req: CreateWorktreeReq,
-): Promise<CreateWorktreeResp> {
- const create = () => withCreateWorktreeQueue(
- req.baseRepo,
- () => createWorktreeInner(req),
- );
+export async function createWorktree(req: CreateWorktreeReq): Promise<CreateWorktreeResp> {
+ const create = () => withCreateWorktreeQueue(req.baseRepo, () => createWorktreeInner(req));
return req.recoveryKey === undefined
? create()
: withPrecreatedWorktreeOperationQueue(req.sessionId, create);
}
-async function createWorktreeInner(
- req: CreateWorktreeReq,
-): Promise<CreateWorktreeResp> {
+async function createWorktreeInner(req: CreateWorktreeReq): Promise<CreateWorktreeResp> {
const snap: CreatedSnapshot = {};
const totalStartedAt = Date.now();
try {
@@ -661,17 +688,13 @@ async function createWorktreeInner(
},
};
}
- const recoveryKey = typeof req.recoveryKey === 'string'
- ? req.recoveryKey.trim()
- : null;
+ const recoveryKey = typeof req.recoveryKey === 'string' ? req.recoveryKey.trim() : null;
if (
- req.recoveryKey !== undefined
- && (
- !recoveryKey
- || recoveryKey.length < MIN_RECOVERY_KEY_LENGTH
- || recoveryKey.length > MAX_RECOVERY_KEY_LENGTH
- || !RECOVERY_KEY_PATTERN.test(recoveryKey)
- )
+ req.recoveryKey !== undefined &&
+ (!recoveryKey ||
+ recoveryKey.length < MIN_RECOVERY_KEY_LENGTH ||
+ recoveryKey.length > MAX_RECOVERY_KEY_LENGTH ||
+ !RECOVERY_KEY_PATTERN.test(recoveryKey))
) {
return {
ok: false,
@@ -685,7 +708,10 @@ async function createWorktreeInner(
// 1. detect
const cwdInfo = await timed('detect cwd', () => detectCwd(req.baseRepo));
if (!cwdInfo.gitInstalled) {
- return { ok: false, error: classifyError({ cause: { code: 'ENOENT', syscall: 'spawn git' } }) };
+ return {
+ ok: false,
+ error: classifyError({ cause: { code: 'ENOENT', syscall: 'spawn git' } }),
+ };
}
if (!cwdInfo.isGitRepo) {
return { ok: false, error: classifyError({ stderr: 'not a git repository' }) };
@@ -722,11 +748,8 @@ async function createWorktreeInner(
// 3. 路径冲突避让
const taken = await timed('collect taken names', () => getTakenNames(baseRepo));
- let name = req.name;
- // 显式 collision: 用户给的 name 与已用冲突 → avoidCollision 加后缀
- if (taken.includes(name)) {
- name = avoidCollision(name, taken);
- }
+ // 显式 collision(含大小写与 ref 层级冲突)统一走 avoidCollision。
+ let name = avoidCollision(req.name, taken);
let worktreePath = path.join(baseRepo, MANAGED_WORKTREE_DIR_NAME, name);
// 文件系统 collision(store 没记录但目录已存在): 多走一次 avoid
let attempts = 0;
@@ -750,10 +773,7 @@ async function createWorktreeInner(
try {
await timed('git worktree add', () => gitExec(addArgs, baseRepo));
} catch (err) {
- if (
- err instanceof GitExecError &&
- /filename too long|core\.longpaths/i.test(err.stderr)
- ) {
+ if (err instanceof GitExecError && /filename too long|core\.longpaths/i.test(err.stderr)) {
// 启用 core.longpaths 后重试一次
try {
await gitExec(['config', '--global', 'core.longpaths', 'true']);
@@ -805,7 +825,9 @@ async function createWorktreeInner(
// 8. include patterns
try {
- const results = await timed('apply include file', () => applyWorktreeIncludeFile(baseRepo, worktreePath));
+ const results = await timed('apply include file', () =>
+ applyWorktreeIncludeFile(baseRepo, worktreePath),
+ );
const failed = results.filter((r) => r.status === 'failed');
if (failed.length > 0) {
log.warn(
@@ -822,7 +844,9 @@ async function createWorktreeInner(
// 9. safe.directory
try {
- await timed('add safe.directory', () => gitExec(['config', '--global', '--add', 'safe.directory', worktreePath]));
+ await timed('add safe.directory', () =>
+ gitExec(['config', '--global', '--add', 'safe.directory', worktreePath]),
+ );
} catch (err) {
// 非致命 — 仅日志
log.warn(
@@ -933,13 +957,8 @@ async function removeWorktreeForSessionInner(
): Promise<void> {
let meta = store.get(sessionId);
if (!meta) return;
- if (
- meta.quarantinePath
- && !isExpectedQuarantinePath(meta, meta.quarantinePath)
- ) {
- log.warn(
- `[worktree] preserved worktree at ${meta.path}: invalid persisted quarantine path`,
- );
+ if (meta.quarantinePath && !isExpectedQuarantinePath(meta, meta.quarantinePath)) {
+ log.warn(`[worktree] preserved worktree at ${meta.path}: invalid persisted quarantine path`);
return;
}
const hadPersistedQuarantine = Boolean(meta.quarantinePath);
@@ -962,9 +981,7 @@ async function removeWorktreeForSessionInner(
meta = repaired;
}
}
- const removalOptions = hadPersistedQuarantine
- ? { ...options, preserveDirty: true }
- : options;
+ const removalOptions = hadPersistedQuarantine ? { ...options, preserveDirty: true } : options;
const worktreePath = activeWorktreePath(meta);
// 哨兵守卫: 用户放了 .worktree-keep ⇒ 无条件保留(必须在 dirty/stash 之前——
@@ -988,6 +1005,31 @@ async function removeWorktreeForSessionInner(
return;
}
+ // Store 只持久化创建时的托管分支;若用户/Agent 后来切到其它分支或 detached
+ // HEAD,当前恢复协议无法在目录删除后可靠重建那个基底。必须在任何 snapshot、
+ // quarantine 或 remove 前 fail closed,保留完整 worktree。
+ if (!isManagedWorktreeBranchForName(meta.branch, meta.name)) {
+ log.warn(
+ `[worktree] preserved worktree at ${worktreePath}: registered branch ${meta.branch} ` +
+ `is not a managed branch for ${meta.name}`,
+ );
+ return;
+ }
+ const attachedBranch = await readAttachedWorktreeBranch(worktreePath);
+ if (!attachedBranch) {
+ log.warn(
+ `[worktree] preserved worktree at ${worktreePath}: cannot confirm an attached HEAD branch`,
+ );
+ return;
+ }
+ if (attachedBranch !== meta.branch) {
+ log.warn(
+ `[worktree] preserved worktree at ${worktreePath}: HEAD branch ${attachedBranch} ` +
+ `does not match registered branch ${meta.branch}`,
+ );
+ return;
+ }
+
let changedIncludeFiles: Awaited<ReturnType<typeof listChangedWorktreeIncludeFiles>>;
try {
changedIncludeFiles = await listChangedWorktreeIncludeFiles(meta.baseRepo, worktreePath);
@@ -1046,8 +1088,8 @@ async function removeWorktreeForSessionInner(
await store.set(sessionId, meta);
} else {
log.warn(
- `[worktree] recycle cancelled for ${meta.path}, but snapshot reapply failed; `
- + 'worktree stays unregistered so SEND remains blocked until restore succeeds',
+ `[worktree] recycle cancelled for ${meta.path}, but snapshot reapply failed; ` +
+ 'worktree stays unregistered so SEND remains blocked until restore succeeds',
);
}
}
@@ -1060,10 +1102,7 @@ async function removeWorktreeForSessionInner(
if (!quarantinePath) return true;
const currentQuarantinePath = quarantinePath;
try {
- await gitExec(
- ['worktree', 'move', currentQuarantinePath, meta.path],
- meta.baseRepo,
- );
+ await gitExec(['worktree', 'move', currentQuarantinePath, meta.path], meta.baseRepo);
quarantinePath = null;
try {
await store.set(sessionId, clearQuarantinePath(meta));
@@ -1093,7 +1132,7 @@ async function removeWorktreeForSessionInner(
}
};
- if (removalOptions.preserveDirty && !quarantinePath && await pathExists(meta.path)) {
+ if (removalOptions.preserveDirty && !quarantinePath && (await pathExists(meta.path))) {
const candidate = `${meta.path}.xdt-removing-${randomUUID()}`;
try {
// Persist the intended quarantine path before the rename. This closes both
@@ -1170,7 +1209,9 @@ async function removeWorktreeForSessionInner(
return;
}
// fallback: fs.rm —— 必须三条校验通过
- if (isManagedWorktreePath(removalPath, meta.baseRepo, [...store.getAllPaths(), removalPath])) {
+ if (
+ isManagedWorktreePath(removalPath, meta.baseRepo, [...store.getAllPaths(), removalPath])
+ ) {
try {
await fs.rm(removalPath, { recursive: true, force: true });
// 让 git worktree 状态自洽
@@ -1203,8 +1244,8 @@ async function removeWorktreeForSessionInner(
await store.set(sessionId, meta);
} else {
log.warn(
- `[worktree] remove failed for ${meta.path}, and snapshot reapply also failed; `
- + 'worktree stays unregistered until restore succeeds',
+ `[worktree] remove failed for ${meta.path}, and snapshot reapply also failed; ` +
+ 'worktree stays unregistered until restore succeeds',
);
}
}
@@ -1219,9 +1260,7 @@ async function removeWorktreeForSessionInner(
}
await withWorktreeRestoreMutation(sessionId, async () => {
if (!(await autoStashDirtyWorktree(worktreePath, sessionId))) {
- log.warn(
- `[worktree] worktree at ${worktreePath} has uncommitted changes, preserving`,
- );
+ log.warn(`[worktree] worktree at ${worktreePath} has uncommitted changes, preserving`);
return;
}
await finishRemoval(true);
@@ -1264,7 +1303,8 @@ export async function discardPrecreatedWorktreeByRecoveryKey(
* - expectedPath 必须与 store 中该 sessionId 的受管路径精确匹配,控制端不能指定任意目录;
* - ephemeral / dirty / keep sentinel / include-file 变化 / live-ref 冲突一律保留;
* - canRemove 由宿主反复核对「session 未落库且无 live handle」,挡住晚到的 create;
- * - 正常创建后尚无独有 commit 的 xdt/* 分支才随目录删除;存在独有 commit 时保留分支。
+ * - 正常创建后尚无独有 commit 的 cindy/* 或历史 xdt/* 分支才随目录删除;
+ * 存在独有 commit 时保留分支。
*/
export async function discardPrecreatedWorktree(
sessionId: string,
@@ -1274,10 +1314,9 @@ export async function discardPrecreatedWorktree(
const meta = store.get(sessionId);
if (!meta) return { status: 'absent' };
const expected = path.resolve(expectedPath);
- const matchesRegisteredPath = (
- path.resolve(meta.path) === expected
- || (meta.quarantinePath !== undefined && path.resolve(meta.quarantinePath) === expected)
- );
+ const matchesRegisteredPath =
+ path.resolve(meta.path) === expected ||
+ (meta.quarantinePath !== undefined && path.resolve(meta.quarantinePath) === expected);
if (!matchesRegisteredPath) {
return { status: 'path-mismatch' };
}
@@ -1291,7 +1330,7 @@ export async function discardPrecreatedWorktree(
// 目录成功移除后再读分支,封住用户在 dirty check 与 worktree remove 之间刚完成
// commit 的窗口。store 元数据损坏时也绝不删除非本记录自动推导出的分支。
- const isGeneratedBranch = meta.branch === getBranchName(meta.name);
+ const isGeneratedBranch = isManagedWorktreeBranchForName(meta.branch, meta.name);
let branchTipToDelete: string | null = null;
if (isGeneratedBranch) {
try {
diff --git a/apps/desktop/src/main/worktree/WorktreePool.ts b/apps/desktop/src/main/worktree/WorktreePool.ts
index dde204296d..6349a9933d 100644
--- a/apps/desktop/src/main/worktree/WorktreePool.ts
+++ b/apps/desktop/src/main/worktree/WorktreePool.ts
@@ -71,14 +71,24 @@ export async function acquireWorktree(
if (entry) {
pool.delete(key);
- const newBranch = getBranchName(req.name);
try {
- await resetWorktree(entry.meta.path, entry.meta.baseRepo, req.sourceBranch, newBranch, opts);
+ const resolvedName = await WorktreeManager.resolveAvailableWorktreeName(
+ entry.meta.baseRepo,
+ req.name,
+ );
+ const newBranch = getBranchName(resolvedName);
+ await resetWorktree(
+ entry.meta.path,
+ entry.meta.baseRepo,
+ req.sourceBranch,
+ newBranch,
+ opts,
+ );
const meta: WorktreeMeta = {
...entry.meta,
sessionId: req.sessionId,
- name: req.name,
+ name: resolvedName,
branch: newBranch,
sourceBranch: req.sourceBranch,
createdAt: new Date().toISOString(),
@@ -97,10 +107,12 @@ export async function acquireWorktree(
if (await isWorktreeDirty(entry.meta.path)) {
log.warn(`[WorktreePool] dirty worktree preserved at ${entry.meta.path}`);
} else {
- const drained = await drainEntry(entry.meta).then(() => true).catch(async () => {
- await gitExec(['worktree', 'prune'], entry.meta.baseRepo).catch(() => {});
- return false;
- });
+ const drained = await drainEntry(entry.meta)
+ .then(() => true)
+ .catch(async () => {
+ await gitExec(['worktree', 'prune'], entry.meta.baseRepo).catch(() => {});
+ return false;
+ });
if (drained) store.del(entry.meta.sessionId);
}
}
@@ -153,8 +165,9 @@ async function resetWorktree(
}
}
- // 2. 切换分支并重置文件(-B 强制覆盖已有同名分支)
- await gitExec(['checkout', '-B', newBranch, sourceBranch], worktreePath);
+ // 2. 非覆盖式创建并切换分支。查重后的 TOCTOU 竞态会让 -b 安全失败,
+ // 绝不能用 -B 重置一个不属于池条目的已有分支。
+ await gitExec(['checkout', '--no-track', '-b', newBranch, sourceBranch], worktreePath);
// 3. 确保 index 与 HEAD 一致(上次 agent 可能 git add 了文件但未 commit)
await gitExec(['reset', '--hard', sourceBranch], worktreePath);
@@ -226,7 +239,9 @@ export async function releaseWorktree(sessionId: string): Promise<'pooled' | 'pr
if (hasLiveSessionReference(existing.meta, liveSessionPathKeys)) {
logPreservedLiveSessionWorktree(existing.meta);
} else {
- const drained = await drainEntry(existing.meta).then(() => true).catch(() => false);
+ const drained = await drainEntry(existing.meta)
+ .then(() => true)
+ .catch(() => false);
if (drained) {
store.del(existing.meta.sessionId);
}
@@ -255,16 +270,17 @@ export async function releaseWorktree(sessionId: string): Promise<'pooled' | 'pr
async function evictIfOverLimit(liveSessionPathKeys?: LiveSessionPathKeys): Promise<void> {
if (store.getAll().length <= MAX_WORKTREES) return;
- const liveRefs = liveSessionPathKeys === undefined
- ? await loadLiveSessionPathKeys()
- : liveSessionPathKeys;
+ const liveRefs =
+ liveSessionPathKeys === undefined ? await loadLiveSessionPathKeys() : liveSessionPathKeys;
// 每轮重新读 store 取最旧的 clean 候选,避免 stale snapshot 问题
while (store.getAll().length > MAX_WORKTREES) {
const candidate = await findOldestCleanCandidate(liveRefs);
if (!candidate) break; // 剩余全是 dirty / 池中在用,允许超限
- const drained = await drainEntry(candidate).then(() => true).catch(() => false);
+ const drained = await drainEntry(candidate)
+ .then(() => true)
+ .catch(() => false);
if (drained) store.del(candidate.sessionId);
else break;
}
@@ -323,7 +339,7 @@ async function drainEntry(meta: WorktreeMeta): Promise<void> {
throw err;
}
- // 兜底:只允许删除 xdt 已登记的托管 worktree 目录
+ // 兜底:只允许删除 Cindy 已登记的托管 worktree 目录
try {
await fs.rm(meta.path, { recursive: true, force: true });
await gitExec(['worktree', 'prune'], meta.baseRepo).catch(() => {});
@@ -390,14 +406,18 @@ export async function recoverPool(): Promise<void> {
// 2. 哨兵: 用户声明保留,不入池不清理
if (hasKeepSentinel(meta.path)) {
- log.info(`[WorktreePool] preserved sentinel worktree at ${meta.path} (session ${meta.sessionId})`);
+ log.info(
+ `[WorktreePool] preserved sentinel worktree at ${meta.path} (session ${meta.sessionId})`,
+ );
continue;
}
// 3. 检查 dirty
const dirty = await isWorktreeDirty(meta.path);
if (dirty) {
- log.warn(`[WorktreePool] preserved dirty worktree at ${meta.path} (session ${meta.sessionId})`);
+ log.warn(
+ `[WorktreePool] preserved dirty worktree at ${meta.path} (session ${meta.sessionId})`,
+ );
continue;
}
@@ -415,7 +435,9 @@ export async function recoverPool(): Promise<void> {
if (hasLiveSessionReference(meta, liveSessionPathKeys)) {
logPreservedLiveSessionWorktree(meta);
} else {
- const drained = await drainEntry(meta).then(() => true).catch(() => false);
+ const drained = await drainEntry(meta)
+ .then(() => true)
+ .catch(() => false);
if (drained) store.del(meta.sessionId);
}
}
diff --git a/apps/desktop/src/main/worktree/__tests__/copyClaudeSiviDirs.test.ts b/apps/desktop/src/main/worktree/__tests__/copyClaudeSiviDirs.test.ts
index fd8713ab74..ef5849c463 100644
--- a/apps/desktop/src/main/worktree/__tests__/copyClaudeSiviDirs.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/copyClaudeSiviDirs.test.ts
@@ -65,8 +65,12 @@ afterEach(async () => {
});
describe('buildWorktreeAddArgs', () => {
- it('带 --no-track:远端引用为起点时不给 xdt/* 分支挂 branch.<name>.remote/merge 跟踪配置', () => {
- const args = buildWorktreeAddArgs('xdt/auto-x1', '/repo/.cindy-worktrees/auto-x1', 'refs/remotes/origin/main');
+ it('带 --no-track:远端引用为起点时不给 cindy/* 分支挂 branch.<name>.remote/merge 跟踪配置', () => {
+ const args = buildWorktreeAddArgs(
+ 'cindy/auto-x1',
+ '/repo/.cindy-worktrees/auto-x1',
+ 'refs/remotes/origin/main',
+ );
// --no-track 抑制 branch.autoSetupMerge 的默认行为:新分支不产生 upstream
// 跟踪配置,裸 git push/pull 不会误指向远端默认分支
expect(args).toContain('--no-track');
@@ -74,7 +78,11 @@ describe('buildWorktreeAddArgs', () => {
const bIdx = args.indexOf('-b');
expect(noTrackIdx).toBeGreaterThan(-1);
expect(noTrackIdx).toBeLessThan(bIdx); // 在 -b 之前,作用于分支创建
- expect(args.slice(-3)).toEqual(['xdt/auto-x1', '/repo/.cindy-worktrees/auto-x1', 'refs/remotes/origin/main']);
+ expect(args.slice(-3)).toEqual([
+ 'cindy/auto-x1',
+ '/repo/.cindy-worktrees/auto-x1',
+ 'refs/remotes/origin/main',
+ ]);
});
});
diff --git a/apps/desktop/src/main/worktree/attachedBranch.ts b/apps/desktop/src/main/worktree/attachedBranch.ts
new file mode 100644
index 0000000000..bc0d2075e0
--- /dev/null
+++ b/apps/desktop/src/main/worktree/attachedBranch.ts
@@ -0,0 +1,20 @@
+import { gitExec } from './gitExec';
+
+const LOCAL_BRANCH_REF_PREFIX = 'refs/heads/';
+
+/**
+ * Read the attached local branch without Git's context-dependent short-name
+ * disambiguation. A same-named tag can make `--short` return `heads/<name>`,
+ * so callers must normalize the full symbolic ref themselves.
+ */
+export async function readAttachedWorktreeBranch(worktreePath: string): Promise<string | null> {
+ try {
+ const { stdout } = await gitExec(['symbolic-ref', '--quiet', 'HEAD'], worktreePath);
+ const ref = stdout.trim();
+ if (!ref.startsWith(LOCAL_BRANCH_REF_PREFIX)) return null;
+ const branch = ref.slice(LOCAL_BRANCH_REF_PREFIX.length);
+ return branch || null;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/desktop/src/main/worktree/nameGenerator.ts b/apps/desktop/src/main/worktree/nameGenerator.ts
index 8cdaafca80..5588d7f77d 100644
--- a/apps/desktop/src/main/worktree/nameGenerator.ts
+++ b/apps/desktop/src/main/worktree/nameGenerator.ts
@@ -6,25 +6,111 @@
*/
const ADJECTIVES: readonly string[] = [
- 'pensive', 'eager', 'jolly', 'silly', 'epic', 'brave', 'calm', 'clever',
- 'curious', 'dazzling', 'earnest', 'elegant', 'fierce', 'gentle', 'happy',
- 'humble', 'inspiring', 'keen', 'lively', 'loyal', 'merry', 'noble',
- 'optimistic', 'peaceful', 'proud', 'quirky', 'radiant', 'serene', 'sharp',
- 'silent', 'sincere', 'steady', 'stoic', 'sturdy', 'sweet', 'swift', 'tender',
- 'thoughtful', 'tranquil', 'trusty', 'upbeat', 'vibrant', 'vigilant', 'warm',
- 'wise', 'witty', 'zealous', 'amazing', 'bold', 'cheerful',
+ 'pensive',
+ 'eager',
+ 'jolly',
+ 'silly',
+ 'epic',
+ 'brave',
+ 'calm',
+ 'clever',
+ 'curious',
+ 'dazzling',
+ 'earnest',
+ 'elegant',
+ 'fierce',
+ 'gentle',
+ 'happy',
+ 'humble',
+ 'inspiring',
+ 'keen',
+ 'lively',
+ 'loyal',
+ 'merry',
+ 'noble',
+ 'optimistic',
+ 'peaceful',
+ 'proud',
+ 'quirky',
+ 'radiant',
+ 'serene',
+ 'sharp',
+ 'silent',
+ 'sincere',
+ 'steady',
+ 'stoic',
+ 'sturdy',
+ 'sweet',
+ 'swift',
+ 'tender',
+ 'thoughtful',
+ 'tranquil',
+ 'trusty',
+ 'upbeat',
+ 'vibrant',
+ 'vigilant',
+ 'warm',
+ 'wise',
+ 'witty',
+ 'zealous',
+ 'amazing',
+ 'bold',
+ 'cheerful',
];
// 取自计算机/科学史上的名人, 避免争议性人物。
const SURNAMES: readonly string[] = [
- 'lederberg', 'turing', 'lovelace', 'hopper', 'knuth', 'dijkstra', 'ritchie',
- 'thompson', 'kernighan', 'torvalds', 'stallman', 'wozniak', 'curie', 'darwin',
- 'einstein', 'feynman', 'galileo', 'hawking', 'newton', 'pasteur', 'tesla',
- 'archimedes', 'babbage', 'bohr', 'borg', 'cohen', 'colden', 'edison',
- 'engelbart', 'euclid', 'fermi', 'goldberg', 'goodall', 'hamilton', 'hertz',
- 'hodgkin', 'jang', 'jepsen', 'kalam', 'kapitsa', 'kepler', 'lamarr',
- 'leakey', 'liskov', 'mclean', 'mendel', 'mendeleev', 'mirzakhani', 'morse',
- 'noether', 'panini',
+ 'lederberg',
+ 'turing',
+ 'lovelace',
+ 'hopper',
+ 'knuth',
+ 'dijkstra',
+ 'ritchie',
+ 'thompson',
+ 'kernighan',
+ 'torvalds',
+ 'stallman',
+ 'wozniak',
+ 'curie',
+ 'darwin',
+ 'einstein',
+ 'feynman',
+ 'galileo',
+ 'hawking',
+ 'newton',
+ 'pasteur',
+ 'tesla',
+ 'archimedes',
+ 'babbage',
+ 'bohr',
+ 'borg',
+ 'cohen',
+ 'colden',
+ 'edison',
+ 'engelbart',
+ 'euclid',
+ 'fermi',
+ 'goldberg',
+ 'goodall',
+ 'hamilton',
+ 'hertz',
+ 'hodgkin',
+ 'jang',
+ 'jepsen',
+ 'kalam',
+ 'kapitsa',
+ 'kepler',
+ 'lamarr',
+ 'leakey',
+ 'liskov',
+ 'mclean',
+ 'mendel',
+ 'mendeleev',
+ 'mirzakhani',
+ 'morse',
+ 'noether',
+ 'panini',
];
function pick<T>(arr: readonly T[]): T {
@@ -79,10 +165,7 @@ export function generateRawName(): string {
*
* 注意: 大小写敏感比对在 Windows 下不安全(路径不分大小写), 因此比对时 toLowerCase。
*/
-export function avoidCollision(
- name: string,
- taken: readonly string[],
-): string {
+export function avoidCollision(name: string, taken: readonly string[]): string {
const takenSet = new Set(taken.map((t) => t.toLowerCase()));
if (!takenSet.has(name.toLowerCase())) return name;
let n = 2;
@@ -102,10 +185,7 @@ export function avoidCollision(
* 调用方传入"已用名字列表"(store + git branch 的 union), avoidCollision 用 -2/-3 后缀
* 兜住所有冲突, 所以实际只需要 1 次随机就够; maxAttempts > 1 仅在希望尽量避免数字后缀时有用。
*/
-export function generateUniqueName(
- taken: readonly string[],
- maxAttempts = 5,
-): string {
+export function generateUniqueName(taken: readonly string[], maxAttempts = 5): string {
for (let i = 0; i < maxAttempts; i += 1) {
const raw = generateRawName();
const takenSet = new Set(taken.map((t) => t.toLowerCase()));
@@ -115,9 +195,11 @@ export function generateUniqueName(
return avoidCollision(generateRawName(), taken);
}
-/**
- * 把 name → 分支名: `xdt/<name>`。纯函数, 没有副作用。
- */
-export function getBranchName(name: string): string {
- return `xdt/${name}`;
-}
+export {
+ blocksManagedWorktreeBranchNamespace,
+ getBranchName,
+ getManagedWorktreeBranchCandidates,
+ getManagedWorktreeNameFromBranch,
+ getManagedWorktreeReservedName,
+ isManagedWorktreeBranchForName,
+} from '../../shared/managedWorktreeBranches';
diff --git a/apps/desktop/src/main/worktree/restore.ts b/apps/desktop/src/main/worktree/restore.ts
index b128a44206..49bf79db54 100644
--- a/apps/desktop/src/main/worktree/restore.ts
+++ b/apps/desktop/src/main/worktree/restore.ts
@@ -1,6 +1,7 @@
/**
* worktree 恢复(P1,对齐 Codex Desktop 的 snapshot-restore 思路):
- * 会话的 worktree 被回收后(删除/归档/历史误删),从保留的分支 `xdt/<name>` 重建
+ * 会话的 worktree 被回收后(删除/归档/历史误删),从保留的 `cindy/<name>`
+ * 或历史 `xdt/<name>` 分支重建
* worktree,并把回收时留下的内容快照(refs/xdt/snapshots/<sessionId>,见 dirty.ts)
* apply 回去,一键恢复到回收前的状态。
*
@@ -20,6 +21,7 @@ import {
getRestorableSnapshotSha,
markSnapshotConsumed,
} from './dirty';
+import { readAttachedWorktreeBranch } from './attachedBranch';
import { gitExec, GitExecError } from './gitExec';
import { applyWorktreeIncludeFile } from './includePatternsEngine';
import { pathKey } from './liveSessionRefs';
@@ -33,6 +35,10 @@ import * as store from './worktreeStore';
import { getDbClient } from '../localDb/client/current';
import { sessions } from '../localDb/schema';
import { createLogger } from '../logger';
+import {
+ getManagedWorktreeBranchCandidates,
+ isManagedWorktreeBranchForName,
+} from '../../shared/managedWorktreeBranches';
import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';
import type { WorktreeMeta } from './types';
@@ -65,7 +71,12 @@ export interface WorktreeRestoreResult {
interface ParsedManagedPath {
baseRepo: string;
name: string;
- branch: string;
+}
+
+interface WorktreeRestorePlan {
+ status: WorktreeRestoreStatus;
+ parsed?: ParsedManagedPath;
+ branch?: string;
}
interface SessionWorktreeBinding {
@@ -81,7 +92,7 @@ function parseManagedWorktreePath(worktreePath: string): ParsedManagedPath | nul
if (!isManagedWorktreeDirectoryName(path.basename(parent))) return null;
const name = path.basename(resolved);
if (!name) return null;
- return { baseRepo: path.dirname(parent), name, branch: `xdt/${name}` };
+ return { baseRepo: path.dirname(parent), name };
} catch {
return null;
}
@@ -119,7 +130,9 @@ async function pathIsDirectory(p: string): Promise<boolean> {
}
}
-async function readSessionWorktreeBinding(sessionId: string): Promise<SessionWorktreeBinding | null> {
+async function readSessionWorktreeBinding(
+ sessionId: string,
+): Promise<SessionWorktreeBinding | null> {
const db = getDbClient().drizzle;
const rows = await db
.select({
@@ -145,25 +158,21 @@ async function readWorktreeOwnerSessionId(worktreePath: string): Promise<string
})
.from(sessions)
.where(ne(sessions.status, 'deleted'));
- if (registeredOwner && rows.some((row) => (
- row.id === registeredOwner.sessionId && row.status !== 'deleted'
- ))) {
+ if (
+ registeredOwner &&
+ rows.some((row) => row.id === registeredOwner.sessionId && row.status !== 'deleted')
+ ) {
return registeredOwner.sessionId;
}
- const matchingRows = rows.filter((row) => (
- row.status !== 'deleted' && pathKey(row.worktreePath) === worktreeKey
- ));
- return matchingRows.find((row) => row.status === 'active')?.id
- ?? matchingRows[0]?.id
- ?? null;
+ const matchingRows = rows.filter(
+ (row) => row.status !== 'deleted' && pathKey(row.worktreePath) === worktreeKey,
+ );
+ return matchingRows.find((row) => row.status === 'active')?.id ?? matchingRows[0]?.id ?? null;
}
async function refExists(baseRepo: string, ref: string): Promise<boolean> {
try {
- const { stdout } = await gitExec(
- ['rev-parse', '--verify', '--quiet', ref],
- baseRepo,
- );
+ const { stdout } = await gitExec(['rev-parse', '--verify', '--quiet', ref], baseRepo);
return stdout.trim().length > 0;
} catch {
return false;
@@ -179,12 +188,46 @@ function originBranchRef(branch: string): string {
}
async function hasRestorableBranch(baseRepo: string, branch: string): Promise<boolean> {
- return await refExists(baseRepo, localBranchRef(branch))
- || await refExists(baseRepo, originBranchRef(branch));
+ return (
+ (await refExists(baseRepo, localBranchRef(branch))) ||
+ (await refExists(baseRepo, originBranchRef(branch)))
+ );
}
+type RestorableBranchResolution =
+ | { state: 'found'; branch: string }
+ | { state: 'missing' }
+ | { state: 'ambiguous'; branches: string[] };
+
/**
- * PR cleanup may have removed the local xdt/* branch while leaving origin/xdt/*.
+ * 目录已经回收时只允许恢复到确定的分支:Store 里的精确分支优先;否则新旧
+ * 托管前缀只能唯一命中。两个候选同时存在时 fail closed,避免把快照套到错误基底。
+ */
+async function resolveRestorableBranch(
+ baseRepo: string,
+ name: string,
+ storedBranch?: string,
+): Promise<RestorableBranchResolution> {
+ if (
+ storedBranch &&
+ isManagedWorktreeBranchForName(storedBranch, name) &&
+ (await hasRestorableBranch(baseRepo, storedBranch))
+ ) {
+ return { state: 'found', branch: storedBranch };
+ }
+
+ const candidates = getManagedWorktreeBranchCandidates(name);
+ const matches: string[] = [];
+ for (const branch of candidates) {
+ if (await hasRestorableBranch(baseRepo, branch)) matches.push(branch);
+ }
+ if (matches.length === 1) return { state: 'found', branch: matches[0] };
+ if (matches.length === 0) return { state: 'missing' };
+ return { state: 'ambiguous', branches: matches };
+}
+
+/**
+ * PR cleanup may have removed the local managed branch while leaving its origin tracking ref.
* Recreate only that exact local branch from the already-fetched tracking ref; restore never
* performs network I/O, changes the primary checkout, or guesses a different commit.
*/
@@ -208,14 +251,7 @@ async function addRestoredWorktree(
worktreePath: string,
branch: string,
): Promise<void> {
- const addArgs = [
- '-c',
- 'core.longpaths=true',
- 'worktree',
- 'add',
- worktreePath,
- branch,
- ];
+ const addArgs = ['-c', 'core.longpaths=true', 'worktree', 'add', worktreePath, branch];
try {
await gitExec(addArgs, baseRepo);
} catch (err) {
@@ -269,16 +305,17 @@ function restoredWorktreeMeta(
sessionId: string,
parsed: ParsedManagedPath,
worktreePath: string,
+ branch: string,
): WorktreeMeta {
return {
sessionId,
name: parsed.name,
path: worktreePath,
baseRepo: parsed.baseRepo,
- branch: parsed.branch,
+ branch,
// 原始 sourceBranch 在回收时随 store 条目丢失,恢复后以自身分支占位
// (仅影响 UI 显示,不参与任何 git 操作)。
- sourceBranch: parsed.branch,
+ sourceBranch: branch,
createdAt: new Date().toISOString(),
};
}
@@ -287,6 +324,7 @@ async function finishRestoredWorktree(
sessionId: string,
parsed: ParsedManagedPath,
worktreePath: string,
+ branch: string,
): Promise<void> {
await copyClaudeSiviDirs(parsed.baseRepo, worktreePath, {
overwriteExisting: false,
@@ -304,52 +342,114 @@ async function finishRestoredWorktree(
err instanceof Error ? err.message : String(err),
);
});
- await store.set(sessionId, restoredWorktreeMeta(sessionId, parsed, worktreePath));
+ await store.set(sessionId, restoredWorktreeMeta(sessionId, parsed, worktreePath, branch));
}
-/** 查询会话 worktree 的可恢复状态(restore 横幅数据源)。任何异常都归入 no-worktree/gone 保守分支。 */
-export async function getWorktreeRestoreStatus(sessionId: string): Promise<WorktreeRestoreStatus> {
+async function getWorktreeRestorePlan(sessionId: string): Promise<WorktreeRestorePlan> {
let worktreePath: string | null = null;
+ let registeredMeta: WorktreeMeta | null = null;
try {
- worktreePath = store.get(sessionId)?.path
- ?? (await readSessionWorktreeBinding(sessionId))?.worktreePath
- ?? null;
+ registeredMeta = store.get(sessionId);
+ worktreePath =
+ registeredMeta?.path ?? (await readSessionWorktreeBinding(sessionId))?.worktreePath ?? null;
} catch (err) {
- log.warn(`[restore] session lookup failed for ${sessionId}:`, err instanceof Error ? err.message : String(err));
- return { state: 'no-worktree' };
+ log.warn(
+ `[restore] session lookup failed for ${sessionId}:`,
+ err instanceof Error ? err.message : String(err),
+ );
+ return { status: { state: 'no-worktree' } };
}
- if (!worktreePath) return { state: 'no-worktree' };
+ if (!worktreePath) return { status: { state: 'no-worktree' } };
const parsed = parseManagedWorktreePath(worktreePath);
- if (!parsed) return { state: 'no-worktree' };
+ if (!parsed) return { status: { state: 'no-worktree' } };
+
+ const registeredForPath =
+ registeredMeta && pathKey(registeredMeta.path) === pathKey(worktreePath)
+ ? registeredMeta
+ : null;
+ const restoreName = registeredForPath?.name || parsed.name;
+ const restoreParsed = restoreName === parsed.name ? parsed : { ...parsed, name: restoreName };
if (await pathExists(worktreePath)) {
- const pending = await findPendingSnapshot(parsed.baseRepo, sessionId, parsed.name);
- return { state: 'present', worktreePath, hasSnapshot: pending !== null };
+ const pending = await findPendingSnapshot(
+ restoreParsed.baseRepo,
+ sessionId,
+ restoreParsed.name,
+ );
+ const attachedBranch = await readAttachedWorktreeBranch(worktreePath);
+ const branch =
+ attachedBranch && isManagedWorktreeBranchForName(attachedBranch, restoreParsed.name)
+ ? attachedBranch
+ : undefined;
+ if (attachedBranch && !branch) {
+ log.warn(
+ `[restore] preserved existing worktree registration gap at ${worktreePath}: ` +
+ `HEAD branch ${attachedBranch} is not managed for ${restoreParsed.name}`,
+ );
+ }
+ return {
+ status: { state: 'present', worktreePath, hasSnapshot: pending !== null },
+ parsed: restoreParsed,
+ ...(branch ? { branch } : {}),
+ };
+ }
+ if (!(await pathExists(restoreParsed.baseRepo))) {
+ return { status: { state: 'gone', worktreePath }, parsed: restoreParsed };
+ }
+ const branchResolution = await resolveRestorableBranch(
+ restoreParsed.baseRepo,
+ restoreParsed.name,
+ registeredForPath?.branch,
+ );
+ if (branchResolution.state === 'ambiguous') {
+ log.warn(
+ `[restore] ambiguous managed branches for ${worktreePath}; refusing to guess:`,
+ branchResolution.branches,
+ );
+ return { status: { state: 'gone', worktreePath }, parsed: restoreParsed };
}
- if (!(await pathExists(parsed.baseRepo))) return { state: 'gone', worktreePath };
- if (!(await hasRestorableBranch(parsed.baseRepo, parsed.branch))) {
- return { state: 'gone', worktreePath };
+ if (branchResolution.state === 'missing') {
+ return { status: { state: 'gone', worktreePath }, parsed: restoreParsed };
}
- const hasSnapshot = (await findPendingSnapshot(parsed.baseRepo, sessionId, parsed.name)) !== null;
- return { state: 'restorable', worktreePath, hasSnapshot };
+ const hasSnapshot =
+ (await findPendingSnapshot(restoreParsed.baseRepo, sessionId, restoreParsed.name)) !== null;
+ return {
+ status: { state: 'restorable', worktreePath, hasSnapshot },
+ parsed: restoreParsed,
+ branch: branchResolution.branch,
+ };
+}
+
+/** 查询会话 worktree 的可恢复状态(restore 横幅数据源)。任何异常都归入 no-worktree/gone 保守分支。 */
+export async function getWorktreeRestoreStatus(sessionId: string): Promise<WorktreeRestoreStatus> {
+ return (await getWorktreeRestorePlan(sessionId)).status;
}
/**
- * 一键恢复:`git worktree add <path> xdt/<name>` 重建 + apply 内容快照 + 重新登记 store。
+ * 一键恢复:用 Store 保存的精确分支,或唯一命中的 cindy/* / xdt/* 分支重建,
+ * 然后 apply 内容快照并重新登记 store。
* 快照 apply 失败时保留目录与快照,但移除 store 登记,避免后续回收把新编辑
* 覆盖到同一个 snapshot ref;重试成功后才恢复本地配置并重新登记。
*/
async function restoreWorktreeForSessionOnce(sessionId: string): Promise<WorktreeRestoreResult> {
- const status = await getWorktreeRestoreStatus(sessionId);
+ const plan = await getWorktreeRestorePlan(sessionId);
+ const { status } = plan;
if (status.state === 'present') {
- const parsed = parseManagedWorktreePath(status.worktreePath);
+ const parsed = plan.parsed ?? parseManagedWorktreePath(status.worktreePath);
if (!parsed) return { ok: true, snapshotApplied: true };
if (!status.hasSnapshot) {
- if (!store.get(sessionId)) {
- await finishRestoredWorktree(sessionId, parsed, status.worktreePath);
+ if (!store.get(sessionId) && plan.branch) {
+ await finishRestoredWorktree(sessionId, parsed, status.worktreePath, plan.branch);
}
return { ok: true, snapshotApplied: true };
}
+ if (!plan.branch) {
+ log.warn(
+ `[restore] preserved pending snapshot for ${status.worktreePath}: ` +
+ 'cannot confirm the expected managed HEAD branch',
+ );
+ return { ok: true, snapshotApplied: false };
+ }
const snapshotApplied = await applyPendingSnapshot(
parsed.baseRepo,
status.worktreePath,
@@ -360,22 +460,23 @@ async function restoreWorktreeForSessionOnce(sessionId: string): Promise<Worktre
store.del(sessionId);
return { ok: true, snapshotApplied: false };
}
- if (!store.get(sessionId)) {
- await finishRestoredWorktree(sessionId, parsed, status.worktreePath);
+ if (!store.get(sessionId) && plan.branch) {
+ await finishRestoredWorktree(sessionId, parsed, status.worktreePath, plan.branch);
}
return { ok: true, snapshotApplied };
}
if (status.state !== 'restorable') {
return { ok: false, reason: status.state === 'gone' ? 'gone' : 'no-worktree' };
}
- const parsed = parseManagedWorktreePath(status.worktreePath)!;
+ const parsed = plan.parsed!;
+ const branch = plan.branch!;
let snapshotApplied: boolean;
try {
// 目录被手动删过时 git 元数据可能残留,先 prune 对账再 add。
await gitExec(['worktree', 'prune'], parsed.baseRepo).catch(() => undefined);
- await ensureLocalBranchForRestore(parsed.baseRepo, parsed.branch);
- await addRestoredWorktree(parsed.baseRepo, status.worktreePath, parsed.branch);
+ await ensureLocalBranchForRestore(parsed.baseRepo, branch);
+ await addRestoredWorktree(parsed.baseRepo, status.worktreePath, branch);
// 快照必须先于本地配置恢复:未跟踪文件可能同时命中 .claude/.sivi 或
// .xdtworktreeinclude,提前拷贝会让 git stash apply 因目标已存在而失败。
snapshotApplied = await applyPendingSnapshot(
@@ -388,14 +489,16 @@ async function restoreWorktreeForSessionOnce(sessionId: string): Promise<Worktre
store.del(sessionId);
return { ok: true, snapshotApplied: false };
}
- await finishRestoredWorktree(sessionId, parsed, status.worktreePath);
+ await finishRestoredWorktree(sessionId, parsed, status.worktreePath, branch);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.warn(`[restore] worktree add failed for ${status.worktreePath}:`, msg);
return { ok: false, reason: 'git-error', detail: msg };
}
- log.info(`[restore] worktree restored at ${status.worktreePath} (session ${sessionId}, snapshotApplied=${snapshotApplied})`);
+ log.info(
+ `[restore] worktree restored at ${status.worktreePath} (session ${sessionId}, snapshotApplied=${snapshotApplied})`,
+ );
return { ok: true, snapshotApplied };
}
@@ -403,9 +506,8 @@ async function restoreWorktreeForSessionOnce(sessionId: string): Promise<Worktre
export function restoreWorktreeForSession(sessionId: string): Promise<WorktreeRestoreResult> {
const existing = restoreInFlight.get(sessionId);
if (existing) return existing;
- const tracked = withWorktreeRestoreMutation(
- sessionId,
- () => restoreWorktreeForSessionOnce(sessionId),
+ const tracked = withWorktreeRestoreMutation(sessionId, () =>
+ restoreWorktreeForSessionOnce(sessionId),
).finally(() => {
if (restoreInFlight.get(sessionId) === tracked) {
restoreInFlight.delete(sessionId);
@@ -445,8 +547,9 @@ async function ensureOwnedWorktreeReady(
// send in that window must join the same restore instead of treating the directory as ready.
const restoring = restoreInFlight.get(ownerSessionId);
if (restoring) {
- const restoreVersion = restoreInFlightVersions.get(ownerSessionId)
- ?? getWorktreeRestoreMutationVersion(ownerSessionId);
+ const restoreVersion =
+ restoreInFlightVersions.get(ownerSessionId) ??
+ getWorktreeRestoreMutationVersion(ownerSessionId);
const result = await restoring;
if (!result.ok || result.snapshotApplied === false) return false;
const ready = await markSendReadyIfMutationStable(
@@ -470,17 +573,18 @@ async function ensureOwnedWorktreeReady(
// as it snapshots, so later sends use this zero-Git fast path until a later restore mutation
// invalidates the versioned readiness entry.
if (
- await pathIsDirectory(worktreePath)
- && store.get(ownerSessionId)
- && sendReadyWorktrees.get(readinessKey) === currentMutationVersion
- && getWorktreeRestoreMutationVersion(ownerSessionId) === currentMutationVersion
+ (await pathIsDirectory(worktreePath)) &&
+ store.get(ownerSessionId) &&
+ sendReadyWorktrees.get(readinessKey) === currentMutationVersion &&
+ getWorktreeRestoreMutationVersion(ownerSessionId) === currentMutationVersion
) {
return true;
}
const restore = restoreWorktreeForSession(ownerSessionId);
- const restoreVersion = restoreInFlightVersions.get(ownerSessionId)
- ?? getWorktreeRestoreMutationVersion(ownerSessionId);
+ const restoreVersion =
+ restoreInFlightVersions.get(ownerSessionId) ??
+ getWorktreeRestoreMutationVersion(ownerSessionId);
const result = await restore;
if (!result.ok || result.snapshotApplied === false) return false;
const ready = await markSendReadyIfMutationStable(
@@ -533,5 +637,5 @@ export async function restoreMissingManagedWorktreeForSession(
if (!ownerSessionId) return await pathIsDirectory(expectedWorkingDir);
const ready = await ensureOwnedWorktreeReady(ownerSessionId, worktreePath);
- return ready && await pathIsDirectory(expectedWorkingDir);
+ return ready && (await pathIsDirectory(expectedWorkingDir));
}
diff --git a/apps/desktop/src/main/worktree/types.ts b/apps/desktop/src/main/worktree/types.ts
index ec79961cdd..892b30e896 100644
--- a/apps/desktop/src/main/worktree/types.ts
+++ b/apps/desktop/src/main/worktree/types.ts
@@ -17,7 +17,7 @@ export interface WorktreeMeta {
path: string;
/** 创建 worktree 时所在的 git repo 根目录(cwd)。 */
baseRepo: string;
- /** 新建的本地分支名,固定为 `xdt/<name>`。删除 worktree 时**不**带 -D, 分支保留。 */
+ /** 托管分支名;新建为 `cindy/<name>`,历史记录也可能为 `xdt/<name>`。回收目录时分支保留。 */
branch: string;
/** 用户在 worktree 创建表单选择的源分支(git worktree add -b <branch> <path> <sourceBranch>)。 */
sourceBranch: string;
@@ -70,8 +70,7 @@ export interface CreateWorktreeReq {
}
export type CreateWorktreeResp =
- | { ok: true; meta: WorktreeMeta }
- | { ok: false; error: WorktreeError };
+ { ok: true; meta: WorktreeMeta } | { ok: false; error: WorktreeError };
export interface DetectCwdReq {
cwd: string;
diff --git a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
index 28da6b5aae..6176bc59ee 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
@@ -58,6 +58,18 @@ describe('NewMakerDraftRoute worktree send flow', () => {
expect(source).not.toContain("sourceBranch: wt.sourceBranch.trim() || 'main'");
});
+ it('uses the shared Cindy branch helper and adopts the authoritative created branch', () => {
+ const previewBranch = source.indexOf('let branchName = getBranchName(name);');
+ const worktreeCreate = source.indexOf('window.electronAPI.worktreeCreate', previewBranch);
+ const authoritativeBranch = source.indexOf('branchName = resp.meta.branch;', worktreeCreate);
+ const creatingStateRefresh = source.indexOf("status: 'creating'", authoritativeBranch);
+
+ expect(source).not.toContain('`xdt/${name}`');
+ expect(previewBranch).toBeGreaterThan(-1);
+ expect(authoritativeBranch).toBeGreaterThan(worktreeCreate);
+ expect(creatingStateRefresh).toBeGreaterThan(authoritativeBranch);
+ });
+
it('treats remote session creation as committed before the shared non-blocking handoff', () => {
const remoteSessionId = source.search(/const remoteSessionId\s*=\s*presetSessionId/);
const commitPoint = source.indexOf('remoteSessionId 到手就是**提交点**', remoteSessionId);
diff --git a/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx b/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx
index f2af694097..8378b93097 100644
--- a/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx
@@ -3,7 +3,7 @@
* ---------------------------------------------------------------------------
* 自足组件(仿 UpgradeBanner):按 sessionId 自查 worktree:restore-status,两种
* 状态渲染(其余自渲染 null,父级无需条件编排):
- * - restorable(目录没了但 xdt/<name> 分支还在)→「工作区已被回收 → 恢复工作区」;
+ * - restorable(目录没了但 cindy/<name> 或历史 xdt/<name> 分支还在)→恢复入口;
* - present + hasSnapshot(目录还在,但残留待 apply 的快照——典型是回收时
* stash 成功但目录删除失败,或上次恢复只重建了目录、快照 apply 失败)
* →「有未应用的更改快照 → 恢复更改」,文案不再谎称"目录不存在"。
@@ -154,9 +154,11 @@ export function WorktreeRestoreBanner({
}
void refreshWorktrees();
} else {
- toast.error(t('chat.worktreeRestoreBanner.failed', {
- message: t(restoreFailureKey(result.reason as RestoreFailureReason | undefined)),
- }));
+ toast.error(
+ t('chat.worktreeRestoreBanner.failed', {
+ message: t(restoreFailureKey(result.reason as RestoreFailureReason | undefined)),
+ }),
+ );
setPhase('restorable');
}
} catch {
diff --git a/apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx b/apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx
index 4f462217a2..2988d639f9 100644
--- a/apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx
@@ -22,7 +22,7 @@ import { cn } from '@/lib/utils';
import { Spinner } from '@/components/ui/spinner';
interface WorktreeCreatingOverlayProps {
- /** 当前正在创建的目标分支名 (含 xdt/ 前缀)。 */
+ /** 当前正在创建的目标托管分支名。 */
branchName: string;
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index f4fb52b79a..c2ea704c9f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -66,6 +66,7 @@ import { resolveDeviceLinkSubmission } from './deviceLinkCreateArgs';
import { commitRemoteSessionHandoff } from './remoteSessionHandoff';
import { AgentSelect } from '@/components/new-chat/AgentSelect';
import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../../shared/agentKindConversion';
+import { getBranchName } from '../../../shared/managedWorktreeBranches';
import { TopRightChipStack, TopRightChipStackProvider } from '@/components/chat/TopRightChipStack';
import { useProportionalWidth } from '@/hooks/useProportionalWidth';
import { useCCSessions } from '@/hooks/useCCSessions';
@@ -2629,7 +2630,7 @@ export function NewMakerDraftRoute() {
}
if (!name) name = `auto-${Date.now().toString(36).slice(-6)}`;
- const branchName = `xdt/${name}`;
+ let branchName = getBranchName(name);
const newSession = await createSession({
id: sessionId,
agentKind: persistedAgentKind,
@@ -2727,6 +2728,13 @@ export function NewMakerDraftRoute() {
return;
}
+ // Main 会在创建时再做一次分支/路径冲突避让,因此回包里的
+ // meta.branch 才是权威名字。立即替换预估值,避免 UI 继续显示未实际创建的分支。
+ branchName = resp.meta.branch;
+ worktreeCreationStore.set(newSession.id, {
+ status: 'creating',
+ name: branchName,
+ });
const newDir = resp.meta.path;
const latestSession = await sessionService.get(newSession.id).catch((err) => {
log.warn('[draft worktree send] get latest session failed', err);
diff --git a/apps/desktop/src/renderer/lib/worktree.types.ts b/apps/desktop/src/renderer/lib/worktree.types.ts
index ab5e376ed4..3e7dc1b65b 100644
--- a/apps/desktop/src/renderer/lib/worktree.types.ts
+++ b/apps/desktop/src/renderer/lib/worktree.types.ts
@@ -14,7 +14,7 @@ export interface WorktreeMeta {
path: string;
/** baseRepo 根目录绝对路径(创建时所在 session 的 workingDir)。 */
baseRepo: string;
- /** main 侧固定前缀的分支名 `xdt/<name>`。 */
+ /** main 侧托管分支名;新建为 `cindy/<name>`,历史记录可能为 `xdt/<name>`。 */
branch: string;
/** 用户在创建时选择的源分支(如 `main`)。 */
sourceBranch: string;
@@ -55,8 +55,7 @@ export interface CreateWorktreeReq {
}
export type CreateWorktreeResp =
- | { ok: true; meta: WorktreeMeta }
- | { ok: false; error: WorktreeError };
+ { ok: true; meta: WorktreeMeta } | { ok: false; error: WorktreeError };
export interface DetectCwdResp {
isGitRepo: boolean;
diff --git a/apps/desktop/src/shared/managedWorktreeBranches.ts b/apps/desktop/src/shared/managedWorktreeBranches.ts
new file mode 100644
index 0000000000..d43f83feba
--- /dev/null
+++ b/apps/desktop/src/shared/managedWorktreeBranches.ts
@@ -0,0 +1,69 @@
+/**
+ * Cindy 托管 worktree 的分支命名事实源。
+ *
+ * 新建分支统一写入 `cindy/<name>`;升级前创建的 `xdt/<name>` 永久保留读取兼容,
+ * 现有分支不要求改名。这里仅管理 worktree 分支,不涉及 `refs/xdt/*` 快照引用。
+ */
+export const MANAGED_WORKTREE_BRANCH_PREFIX = 'cindy';
+export const LEGACY_MANAGED_WORKTREE_BRANCH_PREFIX = 'xdt';
+
+export const MANAGED_WORKTREE_BRANCH_PREFIXES = [
+ MANAGED_WORKTREE_BRANCH_PREFIX,
+ LEGACY_MANAGED_WORKTREE_BRANCH_PREFIX,
+] as const;
+
+/** 当前写入前缀本身若已是分支,Git 无法再创建其下任何 `cindy/*` ref。 */
+export function blocksManagedWorktreeBranchNamespace(branch: string): boolean {
+ return branch === MANAGED_WORKTREE_BRANCH_PREFIX;
+}
+
+/**
+ * 返回某条现有分支占用的新 Worktree 名。
+ *
+ * 当前前缀下的后代 ref(如 `cindy/foo/bar`)会阻止创建 `cindy/foo`,因此
+ * 预留首个路径段;旧前缀只把精确的 `xdt/<name>` 视为恢复候选,嵌套 ref
+ * 不会与新写入的 `cindy/<name>` 形成层级冲突。
+ */
+export function getManagedWorktreeReservedName(branch: string): string | null {
+ const currentMarker = `${MANAGED_WORKTREE_BRANCH_PREFIX}/`;
+ if (branch.startsWith(currentMarker)) {
+ return branch.slice(currentMarker.length).split('/')[0] || null;
+ }
+
+ const legacyMarker = `${LEGACY_MANAGED_WORKTREE_BRANCH_PREFIX}/`;
+ if (branch.startsWith(legacyMarker)) {
+ const name = branch.slice(legacyMarker.length);
+ return name && !name.includes('/') ? name : null;
+ }
+ return null;
+}
+
+/** 新建 Cindy 托管 worktree 使用的分支名。 */
+export function getBranchName(name: string): string {
+ return `${MANAGED_WORKTREE_BRANCH_PREFIX}/${name}`;
+}
+
+/** 按优先级列出当前与历史托管分支候选。 */
+export function getManagedWorktreeBranchCandidates(name: string): string[] {
+ return MANAGED_WORKTREE_BRANCH_PREFIXES.map((prefix) => `${prefix}/${name}`);
+}
+
+/** 从当前或历史托管分支中解析 worktree 名;其它分支返回 null。 */
+export function getManagedWorktreeNameFromBranch(branch: string): string | null {
+ for (const prefix of MANAGED_WORKTREE_BRANCH_PREFIXES) {
+ const marker = `${prefix}/`;
+ if (branch.startsWith(marker) && branch.length > marker.length) {
+ const name = branch.slice(marker.length);
+ // Worktree name 永远是单个合法路径段。`cindy/foo/bar` 仅是会阻塞
+ // `cindy/foo` 的 ref 后代,`xdt/foo/bar` 则只是普通 legacy 命名空间分支;
+ // 两者都不是托管 Worktree 的精确分支。
+ return name.includes('/') ? null : name;
+ }
+ }
+ return null;
+}
+
+/** 判断分支是否是指定名字对应的当前或历史自动生成分支。 */
+export function isManagedWorktreeBranchForName(branch: string, name: string): boolean {
+ return getManagedWorktreeBranchCandidates(name).includes(branch);
+}
diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.md
index c81b35e1f8..f1601b4d06 100644
--- a/docs/dev-rules/development-workflow.md
+++ b/docs/dev-rules/development-workflow.md
@@ -25,7 +25,7 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径
`apps/desktop/logs/`,读日志时拼 baseRepo 的绝对路径。
- **结束前必须 commit**:会话被删除或归档时脏 worktree 会先存内容快照再删目录。**PR
merged/closed 不等于 Cindy 会话已结束**:只要 owning session 仍 active,任何外部 Git
- cleanup 都必须跳过该 `.cindy-worktrees` / `.xdt-worktrees` 目录与本地 `xdt/*` 分支,交给
+ cleanup 都必须跳过该 `.cindy-worktrees` / `.xdt-worktrees` 目录与本地 `cindy/*` / `xdt/*` 分支,交给
用户显式归档/删除会话时回收;禁止手动 `git worktree remove` 造成 active session 的 cwd
悬空。手动干活时可放 `.worktree-keep` 哨兵文件豁免自动回收。
- **stale prebundle 白屏**:给带依赖的内部包新增 export 后,运行中实例可能因 stale Vite
diff --git a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
index 5e8fa74b3c..a6aae8082a 100644
--- a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
+++ b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
@@ -1,9 +1,13 @@
-import { BRAND_NAME } from '@cindy/maker-shared/branding';
-import { z } from 'zod';
+import { BRAND_NAME } from "@cindy/maker-shared/branding";
+import { z } from "zod";
-import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
-import type { ControlResult, ControlWorkerAgent, LiziMcpSessionContext } from '../types.js';
-import { errorPayload, okPayload } from './_payload.js';
+import type { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";
+import type {
+ ControlResult,
+ ControlWorkerAgent,
+ LiziMcpSessionContext,
+} from "../types.js";
+import { errorPayload, okPayload } from "./_payload.js";
/**
* Host 注入的 session handoff 回调。把一条控制层消息投递到一个 session:
@@ -28,21 +32,21 @@ export type SendToSessionCallback = (params: {
{
targetSessionId: string;
agentKind: ControlWorkerAgent;
- wakeKind: 'resumed' | 'already-active' | 'created' | 'queued';
+ wakeKind: "resumed" | "already-active" | "created" | "queued";
targetTitle: string | null;
targetLastUserSendAt: string | null;
/** create + useWorktree 成功时为新 session 的 worktree 绝对路径;其余情况 host 可省略。 */
worktreePath?: string | null;
},
- | 'NOT_FOUND'
- | 'ARCHIVED'
- | 'DELETED'
- | 'BUSY'
- | 'AGENT_NOT_READY'
- | 'INVALID_ARGS'
- | 'LEAD_NOT_SUPPORTED'
- | 'WORKTREE_UNAVAILABLE'
- | 'HOST_NOT_READY'
+ | "NOT_FOUND"
+ | "ARCHIVED"
+ | "DELETED"
+ | "BUSY"
+ | "AGENT_NOT_READY"
+ | "INVALID_ARGS"
+ | "LEAD_NOT_SUPPORTED"
+ | "WORKTREE_UNAVAILABLE"
+ | "HOST_NOT_READY"
>
>;
@@ -58,31 +62,31 @@ export interface SendToSessionDeps {
// lizi_xdtHelperMcpServer.ts 的 D_LIST_TOOLS(handoff 类目介绍)。
const DESCRIPTION = [
'⚠️【不要用于"开协同 / 多 worker"】用户要"开协同 / 多 agent / 派个 worker 帮我做 X / 拉个 agent review"等诉求时, 用 cindy_orca 的 start_team + create_worker(create_worker 支持 agent / model / effort / initial_task, 一步建 worker 并派活), 不要用本工具。本工具 create 模式产出的是独立 session: 不进协同分组(不在 Lead 右侧的 worker 栏)、且只能克隆当前 session 的 agent / model, 无法指定 worker 用 codex 或某个模型 —— 拿它"开协同"会让需求被静默吞掉。本工具仅供 skill 把外部业务对象(issue / jira / pr)绑定到专属 session。',
- '',
- '把一条控制层 handoff 消息投递到一个 session。两种模式:',
- '- 传 target_session_id → jump:投递到该既有 session(已关闭会自动 resume),wake_kind 返 resumed / already-active;目标正在跑 turn 时消息进入其输入队列、当前 turn 结束后自动派发,wake_kind 返 queued(无需重试)。',
- '- 不传 target_session_id → create:为业务对象新建一个专属 session(继承当前 session 的 workingDir / model / effort / fastMode),投递首条消息,wake_kind 返 created,并在返回里回传新建的 target_session_id 供调用方建立绑定。可加 working_dir 把新 session 落到另一个项目目录(见下),可加 use_worktree=true 让新 session 在自己的独立 git worktree 里工作(见下)。',
- '',
- '【working_dir(仅 create 模式)】缺省新 session 继承当前 session 的 workingDir;传 working_dir(绝对路径,目录须已存在)可把新 session 直接落到另一个项目目录——「从项目 A 的对话把任务 handoff 到项目 B 的全新对话」一次调用完成,无需先在 B 里找一个旧对话中转。与 use_worktree 组合时,worktree 的 base git 仓库从 working_dir 解析。路径不是绝对路径 / 不存在 / 不是目录 → 返 INVALID_ARGS(message 带原因)。jump 模式忽略此参数。',
- '',
- '【use_worktree(仅 create 模式)】use_worktree=true 时,host 会先从**新 session 的 workingDir**(即 working_dir 覆盖后的目录;未覆盖时为当前 workingDir,此时 session 自己在 worktree 里跑也能正确反推主仓库)解析出 base git 仓库,为新 session 预建一个正规 session worktree(<baseRepo>/.cindy-worktrees/<自动名> + xdt/<自动名> 分支,UI 有徽标,session 关闭时自动 stash 未提交改动后回收),新 session 的 workingDir 即该 worktree 路径,返回里带 worktree_path。适用:新 session 要改代码 / checkout 分支,不能污染当前工作树时(如 PR 修复跟进)。workingDir 不是 git 仓库 / git 未装 / worktree 创建失败 → 返 WORKTREE_UNAVAILABLE(不静默降级);调用方可视情况去掉该参数重试(新 session 将直接共享当前 workingDir)。jump 模式忽略此参数。',
- '当前 dispatcher session 不会被本工具关闭或改写,消息投递成功后立即返回。',
- '',
- '【典型场景】skill 把某个外部业务对象(issue / jira / pr / 任意自定义 key)绑定到一个 session:首次处理时不传 id 让工具新建并拿回 id 写绑定;二次处理同一对象时传 id 把新消息路由回那个 session,保留完整上下文。',
- '',
+ "",
+ "把一条控制层 handoff 消息投递到一个 session。两种模式:",
+ "- 传 target_session_id → jump:投递到该既有 session(已关闭会自动 resume),wake_kind 返 resumed / already-active;目标正在跑 turn 时消息进入其输入队列、当前 turn 结束后自动派发,wake_kind 返 queued(无需重试)。",
+ "- 不传 target_session_id → create:为业务对象新建一个专属 session(继承当前 session 的 workingDir / model / effort / fastMode),投递首条消息,wake_kind 返 created,并在返回里回传新建的 target_session_id 供调用方建立绑定。可加 working_dir 把新 session 落到另一个项目目录(见下),可加 use_worktree=true 让新 session 在自己的独立 git worktree 里工作(见下)。",
+ "",
+ "【working_dir(仅 create 模式)】缺省新 session 继承当前 session 的 workingDir;传 working_dir(绝对路径,目录须已存在)可把新 session 直接落到另一个项目目录——「从项目 A 的对话把任务 handoff 到项目 B 的全新对话」一次调用完成,无需先在 B 里找一个旧对话中转。与 use_worktree 组合时,worktree 的 base git 仓库从 working_dir 解析。路径不是绝对路径 / 不存在 / 不是目录 → 返 INVALID_ARGS(message 带原因)。jump 模式忽略此参数。",
+ "",
+ "【use_worktree(仅 create 模式)】use_worktree=true 时,host 会先从**新 session 的 workingDir**(即 working_dir 覆盖后的目录;未覆盖时为当前 workingDir,此时 session 自己在 worktree 里跑也能正确反推主仓库)解析出 base git 仓库,为新 session 预建一个正规 session worktree(<baseRepo>/.cindy-worktrees/<自动名> + cindy/<自动名> 分支,UI 有徽标,session 关闭时自动 stash 未提交改动后回收),新 session 的 workingDir 即该 worktree 路径,返回里带 worktree_path。历史 xdt/<自动名> 分支仍可恢复与回收。适用:新 session 要改代码 / checkout 分支,不能污染当前工作树时(如 PR 修复跟进)。workingDir 不是 git 仓库 / git 未装 / worktree 创建失败 → 返 WORKTREE_UNAVAILABLE(不静默降级);调用方可视情况去掉该参数重试(新 session 将直接共享当前 workingDir)。jump 模式忽略此参数。",
+ "当前 dispatcher session 不会被本工具关闭或改写,消息投递成功后立即返回。",
+ "",
+ "【典型场景】skill 把某个外部业务对象(issue / jira / pr / 任意自定义 key)绑定到一个 session:首次处理时不传 id 让工具新建并拿回 id 写绑定;二次处理同一对象时传 id 把新消息路由回那个 session,保留完整上下文。",
+ "",
`【create 边界】create 依赖当前 session 上下文继承配置;未绑定具体 ${BRAND_NAME} session 的 MCP 调用会返 LEAD_NOT_SUPPORTED,skill 应静默回退普通流程。注意:传了 id 但目标不存在会返 NOT_FOUND(绝不自动新建)——只有完全不传 id 才走 create。`,
- '',
- '【失败码语义】',
- '- NOT_FOUND: 目标 session 不存在。skill 应清掉自己的绑定并回退到新建/普通流程。',
- '- ARCHIVED: 目标 session 已归档。skill 应决定是清绑定、回退新流程,还是等未来的 unarchive 工具。',
- '- DELETED: 目标 session 已删除。skill 应清绑定并回退。',
- '- BUSY: 仅 create 模式的罕见兜底(新建 session 意外已有 turn 在跑)。jump 模式撞忙不再返 BUSY,而是入队并成功返回 wake_kind=queued。',
- '- WORKTREE_UNAVAILABLE: 仅 create + use_worktree=true:无法创建 worktree(非 git 仓库 / git 未装 / git worktree add 失败,message 带具体原因)。skill 决定是去掉 use_worktree 重试还是放弃。',
- '- AGENT_NOT_READY: 目标 session 恢复或投递时 agent 未能启动。skill 应告知用户稍后重试。',
- '- HOST_NOT_READY: 主进程服务尚未就绪。skill 应告知用户稍等几秒后重试。',
- '',
- '【重要】这不是 chat 对话工具,而是 session 间 handoff 的控制层入口。不要拿它替代普通的 user→agent 对话。',
-].join('\n');
+ "",
+ "【失败码语义】",
+ "- NOT_FOUND: 目标 session 不存在。skill 应清掉自己的绑定并回退到新建/普通流程。",
+ "- ARCHIVED: 目标 session 已归档。skill 应决定是清绑定、回退新流程,还是等未来的 unarchive 工具。",
+ "- DELETED: 目标 session 已删除。skill 应清绑定并回退。",
+ "- BUSY: 仅 create 模式的罕见兜底(新建 session 意外已有 turn 在跑)。jump 模式撞忙不再返 BUSY,而是入队并成功返回 wake_kind=queued。",
+ "- WORKTREE_UNAVAILABLE: 仅 create + use_worktree=true:无法创建 worktree(非 git 仓库 / git 未装 / git worktree add 失败,message 带具体原因)。skill 决定是去掉 use_worktree 重试还是放弃。",
+ "- AGENT_NOT_READY: 目标 session 恢复或投递时 agent 未能启动。skill 应告知用户稍后重试。",
+ "- HOST_NOT_READY: 主进程服务尚未就绪。skill 应告知用户稍等几秒后重试。",
+ "",
+ "【重要】这不是 chat 对话工具,而是 session 间 handoff 的控制层入口。不要拿它替代普通的 user→agent 对话。",
+].join("\n");
/**
* 注册 send_to_session 到 XdtHelperToolRegistry(handoff 类目),经 call_tool 调用。
@@ -94,8 +98,8 @@ export function registerSendToSessionTool(
deps: SendToSessionDeps,
): void {
registry.register({
- name: 'send_to_session',
- category: 'handoff',
+ name: "send_to_session",
+ category: "handoff",
description: DESCRIPTION,
inputShape: {
target_session_id: z
@@ -104,30 +108,40 @@ export function registerSendToSessionTool(
.optional()
.describe(
`目标 ${BRAND_NAME} session 的 business id(UUID)。` +
- '省略 → create:新建一个专属 session 并在返回里回传新建 id;提供 → jump 到该既有 session。',
+ "省略 → create:新建一个专属 session 并在返回里回传新建 id;提供 → jump 到该既有 session。",
),
message: z
.string()
.min(1)
- .describe('要 handoff 给目标 session 的消息正文(create 模式下作为新 session 的首条消息)。'),
+ .describe(
+ "要 handoff 给目标 session 的消息正文(create 模式下作为新 session 的首条消息)。",
+ ),
title: z
.string()
.optional()
- .describe('仅 create 模式可选:新建 session 的标题(建议用业务对象命名,如 "issue #123")。省略则用消息首行兜底。'),
+ .describe(
+ '仅 create 模式可选:新建 session 的标题(建议用业务对象命名,如 "issue #123")。省略则用消息首行兜底。',
+ ),
use_worktree: z
.boolean()
.optional()
.describe(
- '仅 create 模式可选:true = 为新 session 预建独立 git worktree(自动从新 session 的 workingDir 解析 base 仓库)并以其为 workingDir,返回带 worktree_path;失败返 WORKTREE_UNAVAILABLE 不静默降级。新 session 要改代码 / checkout 分支时建议开。jump 模式忽略。',
+ "仅 create 模式可选:true = 为新 session 预建独立 git worktree(自动从新 session 的 workingDir 解析 base 仓库)并以其为 workingDir,返回带 worktree_path;失败返 WORKTREE_UNAVAILABLE 不静默降级。新 session 要改代码 / checkout 分支时建议开。jump 模式忽略。",
),
working_dir: z
.string()
.optional()
.describe(
- '仅 create 模式可选:新 session 的工作目录(绝对路径,目录须已存在)。缺省继承当前 session 的 workingDir;用于把任务 handoff 到另一个项目目录的全新对话。不合法返 INVALID_ARGS。jump 模式忽略。',
+ "仅 create 模式可选:新 session 的工作目录(绝对路径,目录须已存在)。缺省继承当前 session 的 workingDir;用于把任务 handoff 到另一个项目目录的全新对话。不合法返 INVALID_ARGS。jump 模式忽略。",
),
},
- handler: async ({ target_session_id, message, title, use_worktree, working_dir }) => {
+ handler: async ({
+ target_session_id,
+ message,
+ title,
+ use_worktree,
+ working_dir,
+ }) => {
const ctx = deps.getSessionContext();
const result = await deps.sendToSession({
targetSessionId: target_session_id,
@@ -139,9 +153,9 @@ export function registerSendToSessionTool(
});
if (!result.ok) {
- if (result.errorCode === 'HOST_NOT_READY') {
+ if (result.errorCode === "HOST_NOT_READY") {
return errorPayload(
- 'HOST_NOT_READY',
+ "HOST_NOT_READY",
`${BRAND_NAME} 主进程会话服务尚未就绪。请告知用户稍等几秒后重试。`,
);
}