fix(worktree): remove only the missing target registration

This commit is contained in:
Yichen Jiang committed 2026-10-26 17:57:07 +08:00
1 parent b740b95424
commit 4969525f33
9 files changed
+54 -15

No files matched your search

+1 -1
View File
@@ -107,7 +107,7 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS
/**
* Check out a removed worktree again at its recorded directory: its branch
* when the branch still exists, otherwise a new branch of the same name at
* `baseCommit`. Stale worktree registrations are pruned first, and an
* `baseCommit`. Only the missing target's unlocked registration is removed, and an
* existing directory fails. Changes that were never committed are not
* recovered. Checkout disables configured clean, smudge, and process filters,
* as creation does. The calling Session's working directory does not change.
+1 -1
View File
@@ -107,7 +107,7 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS
/**
* Check out a removed worktree again at its recorded directory: its branch
* when the branch still exists, otherwise a new branch of the same name at
* `baseCommit`. Stale worktree registrations are pruned first, and an
* `baseCommit`. Only the missing target's unlocked registration is removed, and an
* existing directory fails. Changes that were never committed are not
* recovered. Checkout disables configured clean, smudge, and process filters,
* as creation does. The calling Session's working directory does not change.
@@ -1094,7 +1094,7 @@ describe('forgePanel removed worktrees', () => {
sendPrompt(opened.agent, 'next')
const missing = await follower.until(state => state.worktree.waiting === 'restoration')
expect(opened.agent.wakes).toBe(1)
const pruning = hold(opened.sandbox, 'prune')
const pruning = hold(opened.sandbox, 'list')
const resetting = hold(opened.sandbox, 'reset')
const restoring = opened.ctx.forgePanel.restoreWorktree(opened.session, signal)
await pruning.reached
@@ -1281,7 +1281,7 @@ describe('forgePanel removed worktrees', () => {
await rm(created.path, { recursive: true, force: true })
sendPrompt(opened.agent, 'next')
await follower.until(state => state.worktree.waiting === 'restoration')
const pruning = hold(opened.sandbox, 'prune')
const pruning = hold(opened.sandbox, 'list')
const caller = new AbortController()
const reason = new Error('closed')
@@ -1307,7 +1307,7 @@ describe('forgePanel removed worktrees', () => {
const opened = await open(repo, {}, { worktrees: true })
const created = await startInWorktree(opened)
await rm(created.path, { recursive: true, force: true })
const pruning = hold(opened.sandbox, 'prune')
const pruning = hold(opened.sandbox, 'list')
const caller = new AbortController()
const reason = new Error('closed')
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 2f8a621b991260a1
/deepseek-ai-dsh-experimental-worktree/use-this-package:
en: 235d60f9bd6edf97
zh: db59c7d7144ef8f6
en: a31b883ab4fed407
zh: b344c60b2bcb006b
/deepseek-ai-dsh-experimental-worktree/understand-the-implementation:
en: 6971a7ca9073bef1
zh: b977c28a75c7f963
+1 -1
View File
@@ -34,7 +34,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, a
`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw.
`ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` checks a removed worktree out again at its recorded directory. It validates the recorded repository root, full commit object name, branch, and canonical target inside the configured pool before mutation. It runs `git worktree prune` for the source repository, which can remove stale registrations for other missing, unlocked worktrees as well as the target. It then checks out the branch when it still exists, or creates the branch again at `baseCommit` when it does not, and reports which happened as `branchRecreated`. An existing directory is an error. The calling Session's working directory does not change, and changes that were never committed are not recovered. Checkout disables filters as creation does. `onPhase` receives `prepare` before validation, target-registration cleanup, and branch creation, and `checkout` before the files are written; it must not throw.
`ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` checks a removed worktree out again at its recorded directory. It validates the recorded repository root, full commit object name, branch, and canonical target inside the configured pool before mutation. It removes only the missing target's unlocked registration with `git worktree remove`; other worktrees and locked registrations remain unchanged. It then checks out the branch when it still exists, or creates the branch again at `baseCommit` when it does not, and reports which happened as `branchRecreated`. An existing directory is an error. The calling Session's working directory does not change, and changes that were never committed are not recovered. Checkout disables filters as creation does. `onPhase` receives `prepare` before validation, target-registration cleanup, and branch creation, and `checkout` before the files are written; it must not throw.
The default checkout directory is `<current checkout root>/.agents/worktrees/<name>`. The returned `repositoryRoot` is the top-level directory of the caller’s current checkout; when it is a linked checkout, the pool is nested inside it. Omitted names join the `dsh-` prefix, the first eight hexadecimal digits of the UUID in the Session id, a hyphen, and four random hexadecimal digits, such as `dsh-6b1f02c4-9a3e`; a Session id without a UUID gets eight random hexadecimal digits after the prefix. `generatedWorktreeName` exports the same rule for callers that name a worktree before creating it. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the pool; existing files and ignore rules are preserved. Relative `directory`, generated `namePrefix`, executable choices, and process limits are configurable in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-worktree).
+1 -1
View File
@@ -34,7 +34,7 @@ kind: "package-reference"
`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。
`ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它对源仓库执行 `git worktree prune`,除目标外,也可能清理其他目录缺失且未锁定的 worktree 的失效登记。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。
`ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它只通过 `git worktree remove` 移除缺失目标的未锁定登记;其他 worktree 与锁定登记保持不变。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。
默认检出目录是 `<current checkout root>/.agents/worktrees/<name>`。返回的 `repositoryRoot` 是调用方当前检出目录的顶层目录;如果它是链接检出目录,工作树父目录就嵌套在其中。省略名称时,名称由前缀 `dsh-`、Session id 中 UUID 的前 8 位十六进制数、一个连字符和 4 位随机十六进制数组成,例如 `dsh-6b1f02c4-9a3e`;Session id 不含 UUID 时,前缀后接 8 位随机十六进制数。`generatedWorktreeName` 导出同一规则,供在创建前确定名称的调用方使用。仅当服务的分配操作创建了父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`;已有文件与忽略规则保持不变。相对路径 `directory`、生成名称使用的 `namePrefix`、可执行程序与进程限制可在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-worktree)中查阅。
+12 -2
View File
@@ -130,7 +130,7 @@ export class WorktreeService extends Service {
/**
* Check out a removed worktree again at its recorded directory: its branch
* when the branch still exists, otherwise a new branch of the same name at
* `baseCommit`. Stale worktree registrations are pruned first, and an
* `baseCommit`. Only the missing target's unlocked registration is removed, and an
* existing directory fails. Changes that were never committed are not
* recovered. Checkout disables configured clean, smudge, and process filters,
* as creation does. The calling Session's working directory does not change.
@@ -226,7 +226,17 @@ export class WorktreeService extends Service {
const actualRoot = await this.ctx.fs.resolve(top.stdout.replace(/\r?\n$/, ''), { cwd: repositoryRoot, signal })
if (actualRoot.targetKey !== root.targetKey) throw new Error('worktree repositoryRoot must be the source checkout root')
await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${baseCommit}^{commit}`])
await run(repositoryRoot, ['worktree', 'prune'])
const registered = await run(repositoryRoot, ['worktree', 'list', '--porcelain', '-z'])
for (const entry of registered.stdout.split('\0\0')) {
const fields = entry.split('\0')
const recordedPath = fields.find(field => field.startsWith('worktree '))?.slice('worktree '.length)
if (recordedPath === undefined) continue
const recorded = await this.ctx.fs.resolve(recordedPath, { cwd: repositoryRoot, signal })
if (recorded.targetKey !== target.targetKey) continue
if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new Error(`worktree is locked: ${path}`)
if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`)
await run(repositoryRoot, ['worktree', 'remove', '--', path])
}
const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1])
const branchRecreated = existing.exitCode !== 0
try {
@@ -382,7 +382,7 @@ describe('restoring removed worktrees', () => {
return await git(checkout, 'rev-parse', 'HEAD')
}
it('checks the branch out again at its latest commit after pruning stale registrations, without entering the checkout', async () => {
it('checks the branch out again at its latest commit after removing only its stale registration, without entering the checkout', async () => {
const root = await repo()
ctx = await harness(root)
const agent = testAgent(ctx, root)
@@ -404,7 +404,7 @@ describe('restoring removed worktrees', () => {
expect(await git(created.path, 'rev-parse', 'HEAD')).toBe(tip)
expect(await contents(join(created.path, 'later.txt'))).toBe('later.txt\n')
expect(await git(created.path, 'status', '--porcelain')).toBe('')
expect(await registered(root)).toEqual([gitPath(root), gitPath(created.path)])
expect(await registered(root)).toEqual([gitPath(root), gitPath(abandoned.path), gitPath(created.path)])
expect(await git(root, 'branch', '--list', 'abandoned')).toContain('abandoned')
expect(ctx.workingDirectory.get(agent.session)).toBe(root)
})
@@ -521,7 +521,17 @@ describe('restoration validation', () => {
await expect(access(join(root, 'outside'))).rejects.toMatchObject({ code: 'ENOENT' })
})
it('preserves a locked missing worktree registration', async () => {
const root = await repo()
ctx = await harness(root)
const agent = testAgent(ctx, root)
const created = await ctx.worktrees.create(agent, { name: 'topic' })
await git(root, 'worktree', 'lock', created.path)
await rm(created.path, { recursive: true, force: true })
const before = await git(root, 'worktree', 'list', '--porcelain')
await expect(ctx.worktrees.restore(agent, created)).rejects.toThrow('worktree is locked')
expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before)
})
})
@@ -540,3 +550,22 @@ it('rejects a restore path redirected outside the pool by a symlink', async () =
expect(await readdir(outside)).toEqual([])
expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before)
})
it('does not remove a registration when its directory reappears during restoration validation', async () => {
const root = await repo()
ctx = await harness(root)
const agent = testAgent(ctx, root)
const created = await ctx.worktrees.create(agent, { name: 'topic' })
await rm(created.path, { recursive: true, force: true })
const resolve = ctx.fs.resolve.bind(ctx.fs)
let targetReads = 0
const probe = vi.spyOn(ctx.fs, 'resolve').mockImplementation(async (path, options) => {
if (path === created.path && ++targetReads === 2) await mkdir(created.path)
return resolve(path, options)
})
try {
await expect(ctx.worktrees.restore(agent, created)).rejects.toThrow('worktree path already exists')
expect(await git(root, 'worktree', 'list', '--porcelain')).toContain(`worktree ${created.path.split(sep).join('/')}`)
} finally { probe.mockRestore() }
})
@@ -4503,7 +4503,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<RestoredWorktree>',
description: 'Check out a removed worktree again at its recorded directory: its branch when the branch still exists, otherwise a new branch of the same name at `baseCommit`. Stale worktree registrations are pruned first, and an existing directory fails. Changes that were never committed are not recovered. Checkout disables configured clean, smudge, and process filters, as creation does. The calling Session\'s working directory does not change. Failures may retain newly allocated Git/filesystem artifacts.',
description: 'Check out a removed worktree again at its recorded directory: its branch when the branch still exists, otherwise a new branch of the same name at `baseCommit`. Only the missing target\'s unlocked registration is removed, and an existing directory fails. Changes that were never committed are not recovered. Checkout disables configured clean, smudge, and process filters, as creation does. The calling Session\'s working directory does not change. Failures may retain newly allocated Git/filesystem artifacts.',
parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }],
returns: 'the directory and whether the branch was created again.',
},