From a850cda7fd9e73182f6023e381f63936b367ac87 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 20:18:56 +0800 Subject: [PATCH] feat(worktree): add enter_worktree for existing worktrees of the pool `ctx.worktrees.enter(agent, { name })` and the model tool `enter_worktree` move a Session into an existing worktree in the pool of the checkout it works in. The directory must resolve inside that pool and be a registered worktree of the repository; otherwise the call fails with the new code `WORKTREE_NOT_FOUND` and the Session stays where it is. Entry changes neither Git state nor files. Each entry appends a `plugin:worktree/entered` record. `exit` reads it to return the Session to the checkout it entered from, so `exit_worktree` now also leaves entered worktrees. Archive reclamation still removes only checkouts a Session created. The `worktree` projection keeps one entry per entered directory; its state version is 2. The recorded worktree scenario enters the first worktree again, reads the file it wrote there, and leaves. --- ...026-11-03-session-workspace-root.i18n.yaml | 12 +- .../2026-11-03-session-workspace-root.md | 6 +- .../2026-11-03-session-workspace-root.zh.md | 6 +- apps/web/tests/worktree-opt-in.e2e.ts | 3 + docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- ...experimental-persistence-catalog.i18n.yaml | 4 +- docs/experimental-persistence-catalog.md | 1 + docs/experimental-persistence-catalog.zh.md | 1 + docs/subsystems/worktrees.i18n.yaml | 12 +- docs/subsystems/worktrees.md | 55 +++++++-- docs/subsystems/worktrees.zh.md | 55 +++++++-- docs/tool-catalog.i18n.yaml | 15 ++- docs/tool-catalog.md | 29 ++++- docs/tool-catalog.zh.md | 29 ++++- .../guide.i18n.yaml | 8 +- .../working-directory-tool-removed/guide.md | 4 +- .../guide.zh.md | 4 +- .../core/tools/tests/gen-tool-catalog.spec.ts | 2 +- .../forge-bundle/README.i18n.yaml | 8 +- packages/experimental/forge-bundle/README.md | 4 +- .../experimental/forge-bundle/README.zh.md | 4 +- .../tool-worktree/README.i18n.yaml | 24 ++-- packages/experimental/tool-worktree/README.md | 14 +-- .../experimental/tool-worktree/README.zh.md | 14 +-- .../experimental/tool-worktree/src/index.ts | 58 ++++++++-- .../tests/loader-composition.spec.ts | 24 +++- .../experimental/worktree/README.i18n.yaml | 12 +- packages/experimental/worktree/README.md | 11 +- packages/experimental/worktree/README.zh.md | 11 +- packages/experimental/worktree/src/error.ts | 5 +- packages/experimental/worktree/src/index.ts | 85 +++++++++++--- .../experimental/worktree/src/projection.ts | 47 ++++++-- packages/experimental/worktree/src/removal.ts | 10 +- packages/experimental/worktree/src/types.ts | 21 +++- .../worktree/tests/archive.spec.ts | 18 +++ .../worktree/tests/worktree.spec.ts | 108 ++++++++++++++++++ .../extensions/tool-cordis/src/api-catalog.ts | 23 +++- scripts/gen-cordis-catalog.ts | 2 + scripts/gen-tool-catalog.ts | 3 +- scripts/type-equiv.manifest.json | 10 ++ snapshots/session/headless.snapshot.ts | 5 +- snapshots/session/worktree/session.v4.jsonl | 72 ++++++++---- .../worktree/tool-schemas.expected.json | 20 +++- 44 files changed, 684 insertions(+), 179 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml index 5f8001a3c9..99bf37fe39 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml @@ -9,14 +9,14 @@ en: 6938aa715106bb99 zh: ea1497b337712f33 /agent-note-session-workspace-root/decision: - en: 7b010f574e64a586 - zh: 2469a120c8847852 + en: 35b00c73a8898442 + zh: a45b349487491c8c /agent-note-session-workspace-root/deferred: en: d8167590081dfa4e zh: a030f78230192206 /agent-note-session-workspace-root/alternatives-considered: - en: 598cbbcb1e2c4f3f - zh: b6c0a13e0c272cb5 + en: 1f06a00497effec7 + zh: ac97aa5f9f98047d /agent-note-session-workspace-root/consequences: - en: ac7376a31c08f9cc - zh: c44c08566e781be7 + en: 8e7b91f65af92657 + zh: 7a140c796d395c6a diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md index bb371e6c14..8c1ec063de 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md @@ -14,7 +14,7 @@ A Session works in one directory, and only Host operations move it. The model-fa `workspace-root/change` is a new ordinary event type, recorded as a same-version persistence change in the [acknowledgement](../../../../docs/persistence-changes/2026-11-13-workspace-root-change.md). `working-directory/change` stays in the event vocabulary, deprecated and without a writer. A stored one, written while the model could move the directory, moves only the current directory, so a stored Session keeps the root it had. An older build refuses a log that holds `workspace-root/change`; a Session that never moves its workspace holds none. -Worktree creation enters the checkout through `set`. `ctx.worktrees.exit`, exposed to the model as `exit_worktree`, returns the Session to the source checkout of the recorded worktree that contains its directory. A child subagent keeps the parent's original project in its header and starts, through `set`, in the parent's workspace root or a Host-chosen directory. +Worktree creation enters the checkout through `set`. `ctx.worktrees.enter`, exposed to the model as `enter_worktree`, moves the Session into an existing worktree that a name selects inside the pool of the checkout it works in; the name cannot leave that pool, so the model still cannot choose an arbitrary directory. `ctx.worktrees.exit`, exposed as `exit_worktree`, returns the Session from the recorded worktree that contains its directory to the checkout it created or entered that worktree from. A child subagent keeps the parent's original project in its header and starts, through `set`, in the parent's workspace root or a Host-chosen directory. ## Deferred @@ -32,10 +32,12 @@ The sandbox write boundary, the workspace file service, desktop file drag, the c **Retire `working-directory/change` through a format migration.** The stored event carries no origin, so a migration would classify each one by its neighbouring events, and a stored model `cd` still needs a record that moves only the directory. The [compatibility rules](../../../../docs/persistence-changes/README.md#compatibility-rules) reserve a version bump for changes that an existing discriminator cannot make safe. +**Enter a worktree by path, or fold creation and entry into one tool.** A model-supplied path would move the write boundary to any registered worktree without the user's approval, which removing the directory tool ruled out, and the harness has no approval step for a directory move. One tool with a creation mode would rename `create_worktree`, which stored Sessions and recorded scenarios call. A name inside the pool keeps the boundary inside the checkout and adds one tool. + **Persist the shell's `cd` between calls.** That is an implicit cursor. In that developer's Sessions, 68% of `cd` prefixes named a directory outside the Session directory and 30% the Session directory itself, so a persisted directory confined to the workspace would apply to about 2%. **Read stored changes as workspace moves.** A stored model `cd` would narrow or move the write boundary of an existing Session; a log that lacks a feature keeps its old behavior. ## Consequences -Consumers read one directory: `get` for relative paths and `rootOf` for everything that belongs to the workspace. The two differ only in a Session that holds `working-directory/change` events, and the next Host move brings them together. Readers keep folding that event as a directory-only change, so a later cursor needs no format change. The model can no longer enter a checkout it created through the shell; entering a checkout is a Host operation. The ACP, SDK, and Web producers record the original project by its canonical spelling, so a Host move back to it records no change. The worktree snapshot fixture covers entering, leaving, and losing a worktree. Moving the consumers listed under Deferred is a separate change. +Consumers read one directory: `get` for relative paths and `rootOf` for everything that belongs to the workspace. The two differ only in a Session that holds `working-directory/change` events, and the next Host move brings them together. Readers keep folding that event as a directory-only change, so a later cursor needs no format change. The model enters a checkout only through the worktree tools: a new one with `create_worktree`, a registered one in the pool with `enter_worktree`. A checkout elsewhere needs a Host operation. The ACP, SDK, and Web producers record the original project by its canonical spelling, so a Host move back to it records no change. The worktree snapshot fixture covers entering, leaving, and losing a worktree. Moving the consumers listed under Deferred is a separate change. diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md index 4ba43be95c..24f5f75c0b 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md @@ -14,7 +14,7 @@ Status: implemented `workspace-root/change` 是新增的普通事件类型,作为同版本持久化变更记录在[确认记录](../../../../docs/persistence-changes/2026-11-13-workspace-root-change.zh.md)中。`working-directory/change` 保留在事件词汇表中,已标为 deprecated,没有写入方。已存储的这类事件写于模型还能移动目录的时期,它只移动当前目录,因此已存储的 Session 保持原有的根。旧版本拒绝含有 `workspace-root/change` 的日志;从未移动工作区的 Session 不含该事件。 -工作树创建通过 `set` 进入检出目录。`ctx.worktrees.exit` 以 `exit_worktree` 的形式提供给模型,它找到包含 Session 目录的已记录工作树,把 Session 送回其源检出。子代理的 header 保留父级的原始项目,并通过 `set` 从父级的工作区根或 Host 选定的目录启动。 +工作树创建通过 `set` 进入检出目录。`ctx.worktrees.enter` 以 `enter_worktree` 的形式提供给模型,它把 Session 移入名称在所在检出的池中选中的已有工作树;名称无法离开该池,因此模型仍然不能选择任意目录。`ctx.worktrees.exit` 以 `exit_worktree` 的形式提供,它找到包含 Session 目录的已记录工作树,把 Session 送回创建或进入该工作树时所在的检出。子代理的 header 保留父级的原始项目,并通过 `set` 从父级的工作区根或 Host 选定的目录启动。 ## Deferred @@ -32,10 +32,12 @@ Status: implemented **通过格式迁移退役 `working-directory/change`。** 已存储的事件不带来源,迁移只能依据相邻事件逐条分类,而已存储的模型 `cd` 仍需要一种只移动目录的记录。[兼容性规则](../../../../docs/persistence-changes/README.zh.md#compatibility-rules)只在现有判别符无法保证安全时才要求升版本。 +**按路径进入工作树,或把创建与进入合并为一个工具。** 模型提供的路径可以不经用户批准就把写边界移到任意已登记的工作树,这正是移除目录工具所排除的;harness 也没有针对目录移动的审批步骤。带创建模式的单一工具需要给 `create_worktree` 改名,而已存储的 Session 和录制场景都在调用它。池内的名称把边界留在检出之内,只新增一个工具。 + **在调用之间保留 shell 的 `cd`。** 这是一个隐式的光标。在该开发者的 Session 中,68% 的 `cd` 前缀指向 Session 目录之外,30% 指向 Session 目录本身,限制在工作区内的保留只对约 2% 生效。 **把已存储的变更读作工作区移动。** 已存储的模型 `cd` 会收窄或移动现有 Session 的写边界;缺少某项特性的日志保持旧行为。 ## Consequences -消费方读取一个目录:相对路径用 `get`,属于工作区的一切用 `rootOf`。两者只在含有 `working-directory/change` 事件的 Session 中不同,下一次 Host 移动会让它们重新一致。读者继续把该事件折叠为只移动目录的变更,因此以后增加光标不需要改格式。模型不能再进入它通过 shell 创建的检出;进入检出是 Host 操作。ACP、SDK 与 Web 的生产方以规范拼写记录原始项目,因此 Host 移回原始项目时不记录变更。工作树快照夹具覆盖进入、离开和失去工作树。迁移 Deferred 中列出的消费方是另一项变更。 +消费方读取一个目录:相对路径用 `get`,属于工作区的一切用 `rootOf`。两者只在含有 `working-directory/change` 事件的 Session 中不同,下一次 Host 移动会让它们重新一致。读者继续把该事件折叠为只移动目录的变更,因此以后增加光标不需要改格式。模型只能通过工作树工具进入检出:用 `create_worktree` 进入新建的检出,用 `enter_worktree` 进入池中已登记的检出。其他位置的检出需要 Host 操作。ACP、SDK 与 Web 的生产方以规范拼写记录原始项目,因此 Host 移回原始项目时不记录变更。工作树快照夹具覆盖进入、离开和失去工作树。迁移 Deferred 中列出的消费方是另一项变更。 diff --git a/apps/web/tests/worktree-opt-in.e2e.ts b/apps/web/tests/worktree-opt-in.e2e.ts index 8613380762..d5a51d83d2 100644 --- a/apps/web/tests/worktree-opt-in.e2e.ts +++ b/apps/web/tests/worktree-opt-in.e2e.ts @@ -84,6 +84,7 @@ it('persists the unified review and worktree switch and retains checkouts after expect(scaffold.ctx.get('worktrees')).toBeUndefined() expect(scaffold.ctx.get('forgePanel')).toBeUndefined() expect(tools()).not.toContain('create_worktree') + expect(tools()).not.toContain('enter_worktree') expect(tools()).not.toContain('exit_worktree') await toggle.click() @@ -91,6 +92,7 @@ it('persists the unified review and worktree switch and retains checkouts after await expect.poll(() => toggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('true') expect(await selectedBundles()).toContain(BUNDLE) expect(tools()).toContain('create_worktree') + expect(tools()).toContain('enter_worktree') expect(tools()).toContain('exit_worktree') expect(scaffold.ctx.get('forgePanel')).toBeDefined() const created = { path: join(repository, '.agents/worktrees/gui-opt-in'), baseCommit: (await git('rev-parse', 'HEAD')).stdout.trim() } @@ -116,6 +118,7 @@ it('persists the unified review and worktree switch and retains checkouts after expect(scaffold.ctx.get('worktrees')).toBeUndefined() expect(scaffold.ctx.get('forgePanel')).toBeUndefined() expect(tools()).not.toContain('create_worktree') + expect(tools()).not.toContain('enter_worktree') expect(tools()).not.toContain('exit_worktree') expect(await readFile(join(created.path, 'retained.txt'), 'utf8')).toBe('retained checkout\n') expect((await git('show-ref', '--verify', 'refs/heads/gui-opt-in')).stdout).toContain(created.baseCommit) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 4cac4fd898..2140a05c72 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1579,7 +1579,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:42`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:45`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f1082f21fd..851af70c8e 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1581,7 +1581,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:42`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:45`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ diff --git a/docs/experimental-persistence-catalog.i18n.yaml b/docs/experimental-persistence-catalog.i18n.yaml index da79791337..97abcdbfad 100644 --- a/docs/experimental-persistence-catalog.i18n.yaml +++ b/docs/experimental-persistence-catalog.i18n.yaml @@ -6,5 +6,5 @@ en: a11f106978c9dce7 zh: a11f106978c9dce7 /experimental-plugin-record-catalog: - en: 70a326c106662bf9 - zh: 876f8036b96985d2 + en: eb63e54f4ce301b7 + zh: b2ec1013b131de5e diff --git a/docs/experimental-persistence-catalog.md b/docs/experimental-persistence-catalog.md index 01904c1cf9..5c9e197254 100644 --- a/docs/experimental-persistence-catalog.md +++ b/docs/experimental-persistence-catalog.md @@ -19,6 +19,7 @@ Shared Session event declarations and resolved schemas appear in the [Session pe | `plugin:translator/request` | `@deepseek-ai/dsh-experimental-translator` | Provider-independent translation input, retained before dispatch. | TranslationRequestRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | | `plugin:translator/result` | `@deepseek-ai/dsh-experimental-translator` | Successful translation, retained before it is returned to the consumer. | TranslationResultRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | | `plugin:worktree/created` | `@deepseek-ai/dsh-experimental-worktree` | A checkout the worktree service created for the Session, which entered it in the same operation. | CreatedWorktree · [`packages/experimental/worktree/src/projection.ts`](../packages/experimental/worktree/src/projection.ts) | +| `plugin:worktree/entered` | `@deepseek-ai/dsh-experimental-worktree` | An existing checkout the Session entered, and the checkout it entered from. | EnteredWorktree · [`packages/experimental/worktree/src/projection.ts`](../packages/experimental/worktree/src/projection.ts) | | `plugin:timeline/annotation` | `@deepseek-ai/dsh-timeline` | Record a discussion or control request from the user. | { version: 1; sessionId: SessionId; annotation: Annotation; } · [`packages/experimental/timeline/src/records.ts`](../packages/experimental/timeline/src/records.ts) | | `plugin:timeline/delivery` | `@deepseek-ai/dsh-timeline` | Record whether the agent accepted a control request. | { version: 1; sessionId: SessionId; id: Annotation['id']; delivery: 'accepted' | 'unknown'; } · [`packages/experimental/timeline/src/records.ts`](../packages/experimental/timeline/src/records.ts) | | `plugin:timeline/failure` | `@deepseek-ai/dsh-timeline` | Record a failed interval report attempt. | { version: 1; sessionId: SessionId; id: IntervalReport['id']; message: string; } · [`packages/experimental/timeline/src/records.ts`](../packages/experimental/timeline/src/records.ts) | diff --git a/docs/experimental-persistence-catalog.zh.md b/docs/experimental-persistence-catalog.zh.md index 93cc558eea..ae6ae6b7da 100644 --- a/docs/experimental-persistence-catalog.zh.md +++ b/docs/experimental-persistence-catalog.zh.md @@ -19,6 +19,7 @@ | `plugin:translator/request` | `@deepseek-ai/dsh-experimental-translator` | Provider-independent translation input, retained before dispatch. | TranslationRequestRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | | `plugin:translator/result` | `@deepseek-ai/dsh-experimental-translator` | Successful translation, retained before it is returned to the consumer. | TranslationResultRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | | `plugin:worktree/created` | `@deepseek-ai/dsh-experimental-worktree` | A checkout the worktree service created for the Session, which entered it in the same operation. | CreatedWorktree · [`packages/experimental/worktree/src/projection.ts`](../packages/experimental/worktree/src/projection.ts) | +| `plugin:worktree/entered` | `@deepseek-ai/dsh-experimental-worktree` | An existing checkout the Session entered, and the checkout it entered from. | EnteredWorktree · [`packages/experimental/worktree/src/projection.ts`](../packages/experimental/worktree/src/projection.ts) | | `plugin:timeline/annotation` | `@deepseek-ai/dsh-timeline` | Record a discussion or control request from the user. | { version: 1; sessionId: SessionId; annotation: Annotation; } · [`packages/experimental/timeline/src/records.ts`](../packages/experimental/timeline/src/records.ts) | | `plugin:timeline/delivery` | `@deepseek-ai/dsh-timeline` | Record whether the agent accepted a control request. | { version: 1; sessionId: SessionId; id: Annotation['id']; delivery: 'accepted' | 'unknown'; } · [`packages/experimental/timeline/src/records.ts`](../packages/experimental/timeline/src/records.ts) | | `plugin:timeline/failure` | `@deepseek-ai/dsh-timeline` | Record a failed interval report attempt. | { version: 1; sessionId: SessionId; id: IntervalReport['id']; message: string; } · [`packages/experimental/timeline/src/records.ts`](../packages/experimental/timeline/src/records.ts) | diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index bfa5bbad54..845b35867b 100644 --- a/docs/subsystems/worktrees.i18n.yaml +++ b/docs/subsystems/worktrees.i18n.yaml @@ -3,11 +3,11 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/worktrees.md /git-worktrees: - en: 3a3d69d2b12a78f9 - zh: a7a7d12487968bbc + en: 2b8bd1769282a1b6 + zh: 3da9c6b3459fbb2e /git-worktrees/creation-and-retention: - en: 92fa7dfcd2afabe2 - zh: 8de3ceee4763166a + en: 86c9fe64306517b7 + zh: e2d087afe24d2ef5 /git-worktrees/request-and-result: - en: fbab866bf824d6e0 - zh: 73d2a1ee350e1434 + en: 5801c5909e1873a0 + zh: 5c36a4c4ea97ecad diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index bf85239b51..c387ead94a 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -2,7 +2,7 @@ English | [中文](worktrees.zh.md) -The experimental [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.md) service provides `ctx.worktrees`. Its [`create_worktree`](../../packages/experimental/tool-worktree/README.md) consumer creates a new Git branch and checkout, then selects it through the [working-directory service](working-directory.md). The [Change requests & worktrees bundle](../../packages/experimental/forge-bundle/README.md#use-this-package) loads both packages through the GUI plugin manager and ships switched off. Other profiles can select the [standalone worktree bundle](../../packages/experimental/tool-worktree/README.md#use-this-package) or mount the two packages explicitly. +The experimental [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.md) service provides `ctx.worktrees`. Its [`create_worktree`](../../packages/experimental/tool-worktree/README.md) consumer creates a new Git branch and checkout, then selects it through the [working-directory service](working-directory.md); `enter_worktree` selects an existing checkout of the pool, and `exit_worktree` returns to the checkout the Session came from. The [Change requests & worktrees bundle](../../packages/experimental/forge-bundle/README.md#use-this-package) loads both packages through the GUI plugin manager and ships switched off. Other profiles can select the [standalone worktree bundle](../../packages/experimental/tool-worktree/README.md#use-this-package) or mount the two packages explicitly. ## Creation and retention @@ -10,11 +10,13 @@ The calling Session's current directory selects the source repository. Creation The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory change. -`ctx.worktrees.exit(agent)`, which the `exit_worktree` tool calls, returns the Session to the source checkout of the recorded worktree that contains its current directory; the checkout and branch remain. Nested worktrees exit one level at a time. Cancellation or failure can also retain partial artifacts; the error identifies their location. Worktree failures throw `WorktreeError` with a `WORKTREE_*` code; a failure after allocation keeps the wrapped error's `name` and `code`, and caller cancellation stays an `AbortError`. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. +`ctx.worktrees.enter(agent, { name })`, which the `enter_worktree` tool calls, moves the Session into an existing worktree in the pool of the checkout it works in. The directory must lie inside that pool and be a registered worktree of the repository: a missing name, an unregistered directory, and a link that leaves the pool fail with `WORKTREE_NOT_FOUND`. Entry changes neither Git state nor files and records itself in the Session log. + +`ctx.worktrees.exit(agent)`, which the `exit_worktree` tool calls, returns the Session from the recorded worktree that contains its current directory to the checkout it created or entered that worktree from; the checkout and branch remain. Nested worktrees exit one level at a time. Cancellation or failure can also retain partial artifacts; the error identifies their location. Worktree failures throw `WorktreeError` with a `WORKTREE_*` code; a failure after allocation keeps the wrapped error's `name` and `code`, and caller cancellation stays an `AbortError`. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. ## Request and result -The request selects only the new name and local revision. The result identifies the created checkout and exact commit; it does not change the Session's original project or write permissions. An optional callback receives each stage of the creation before it begins. A restoration checks a removed checkout out again at its recorded directory, from its branch or, when the branch is gone, from its base commit. +The creation request selects only the new name and local revision. The result identifies the created checkout and exact commit; it does not change the Session's original project or write permissions. An entry request names a worktree inside the pool; its result identifies the checkout, the branch checked out there, and the checkout the Session entered from. An optional callback receives each stage of the creation before it begins. A restoration checks a removed checkout out again at its recorded directory, from its branch or, when the branch is gone, from its base commit. ```ts type-equiv /** A new checkout from a locally available Git commit, branch, or tag. */ @@ -40,6 +42,26 @@ interface CreatedWorktree { } ``` +```ts type-equiv +/** An existing checkout in the worktree pool of the checkout the calling Session works in. */ +interface EnterWorktreeRequest { + /** Checkout directory relative to the pool: the name `create` gave the worktree. */ + name: string +} +``` + +```ts type-equiv +/** An existing checkout the calling Session entered. */ +interface EnteredWorktree { + /** Canonical absolute checkout directory in the filesystem provider's execution world. */ + path: string + /** Branch checked out there at entry; absent on a detached HEAD. */ + branch?: string + /** Canonical root of the checkout whose pool holds the worktree; `exit` returns the Session there. */ + repositoryRoot: string +} +``` + ```ts type-equiv /** * Stage of one creation or restoration, reported before it begins: `prepare` @@ -109,7 +131,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.worktrees` — `WorktreeService` -Creates retained Git worktrees under the mounted filesystem and sandbox providers, records each creation in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived. +Creates retained Git worktrees under the mounted filesystem and sandbox providers, moves Sessions into and out of them, records each creation and entry in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived. ```ts cordis-catalog /** @@ -148,9 +170,26 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise /** - * Return the calling Session from the worktree it works in to the source checkout that worktree was - * created from. The worktree is the recorded creation, the Session's own or fork-inherited, with the - * longest directory containing the Session's current directory. Its checkout and branch remain. + * Move the calling Session into an existing worktree in the pool of the checkout it works in. The + * directory `name` selects must lie inside that pool and be a registered worktree of the repository; + * neither Git state nor files change. The Session's log records the entry, so {@link exit} returns it to + * the checkout it entered from. Archiving the Session never removes a checkout it only entered. + * @param agent - caller whose current directory selects the checkout and its pool. + * @param request - name of the worktree inside the pool. + * @param signal - cancellation of lookup and of the working-directory change. + * @returns the entered checkout, its branch, and the checkout the Session entered from. + * @throws {WorktreeError} `WORKTREE_INVALID_ARGUMENT` for a name that is not a relative path inside the pool, + * `WORKTREE_NOT_FOUND` when the pool holds no registered worktree of that name, a command failure, and + * `WORKTREE_UNAVAILABLE` after service disposal; or the working-directory service's error when the + * registered directory no longer exists. + */ +async enter(agent: Agent, request: EnterWorktreeRequest, signal?: AbortSignal): Promise + +/** + * Return the calling Session from the worktree it works in to the checkout it entered that worktree + * from: the source checkout of a creation, or the checkout whose pool holds an entered worktree. The + * worktree is the recorded creation or entry, the Session's own or fork-inherited, with the longest + * directory containing the Session's current directory. Its checkout and branch remain. * @param agent - caller whose current directory lies in a recorded worktree. * @param signal - cancellation of directory validation and of the working-directory change. * @returns the worktree the Session left; the Session now works in its `repositoryRoot`. @@ -158,7 +197,7 @@ async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSign * `WORKTREE_UNAVAILABLE` after service disposal, or the working-directory service's error when the source * checkout no longer exists. */ -async exit(agent: Agent, signal?: AbortSignal): Promise +async exit(agent: Agent, signal?: AbortSignal): Promise /** * Read the archive cleanup of a Session's created checkout; waiting never diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index 1a17b5c8ca..59495fca74 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -2,7 +2,7 @@ [English](worktrees.md) | 中文 -实验性的 [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.zh.md) 服务提供 `ctx.worktrees`。其消费方 [`create_worktree`](../../packages/experimental/tool-worktree/README.zh.md) 创建新的 Git 分支与检出目录,再通过[工作目录服务](working-directory.zh.md)选中它。[变更请求与工作树组合包](../../packages/experimental/forge-bundle/README.zh.md#use-this-package)通过 GUI 插件管理器一起加载这两个包,随安装提供但默认关闭。其他 profile 可以选择[独立工作树组合包](../../packages/experimental/tool-worktree/README.zh.md#use-this-package),或显式挂载这两个包。 +实验性的 [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.zh.md) 服务提供 `ctx.worktrees`。其消费方 [`create_worktree`](../../packages/experimental/tool-worktree/README.zh.md) 创建新的 Git 分支与检出目录,再通过[工作目录服务](working-directory.zh.md)选中它;`enter_worktree` 选中池中已有的检出目录,`exit_worktree` 回到 Session 来自的检出目录。[变更请求与工作树组合包](../../packages/experimental/forge-bundle/README.zh.md#use-this-package)通过 GUI 插件管理器一起加载这两个包,随安装提供但默认关闭。其他 profile 可以选择[独立工作树组合包](../../packages/experimental/tool-worktree/README.zh.md#use-this-package),或显式挂载这两个包。 ## 创建与保留 @@ -10,11 +10,13 @@ 默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。 -`exit_worktree` 工具调用的 `ctx.worktrees.exit(agent)` 找到包含 Session 当前目录的已记录工作树,把 Session 送回它的源检出;检出目录与分支保留。嵌套的工作树每次退出一层。取消或失败也可能留下部分产物;错误会指出它们的位置。worktree 失败抛出带 `WORKTREE_*` code 的 `WorktreeError`;分配开始后的失败保留被包装错误的 `name` 与 `code`,调用方取消仍为 `AbortError`。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 +`enter_worktree` 工具调用的 `ctx.worktrees.enter(agent, { name })` 把 Session 移入它所在检出的池中已有的工作树。该目录必须位于池内,并且是仓库已登记的工作树:名称不存在、目录未登记、链接指向池外都以 `WORKTREE_NOT_FOUND` 失败。进入不改变 Git 状态和文件,并在 Session 日志中记录这次进入。 + +`exit_worktree` 工具调用的 `ctx.worktrees.exit(agent)` 找到包含 Session 当前目录的已记录工作树,把 Session 送回创建或进入该工作树时所在的检出;检出目录与分支保留。嵌套的工作树每次退出一层。取消或失败也可能留下部分产物;错误会指出它们的位置。worktree 失败抛出带 `WORKTREE_*` code 的 `WorktreeError`;分配开始后的失败保留被包装错误的 `name` 与 `code`,调用方取消仍为 `AbortError`。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 ## 请求与结果 -请求只选择新名称与本地版本。结果标识创建的检出目录与确切提交;它不会改变 Session 的原始项目或写权限。可选的回调会在创建的每个阶段开始之前收到该阶段。恢复会在记录的目录重新检出已删除的检出目录:从它的分支检出;分支也已删除时,从它的基准提交检出。 +创建请求只选择新名称与本地版本。结果标识创建的检出目录与确切提交;它不会改变 Session 的原始项目或写权限。进入请求给出池内工作树的名称;结果标识检出目录、其中检出的分支,以及 Session 进入前所在的检出。可选的回调会在创建的每个阶段开始之前收到该阶段。恢复会在记录的目录重新检出已删除的检出目录:从它的分支检出;分支也已删除时,从它的基准提交检出。 ```ts type-equiv /** A new checkout from a locally available Git commit, branch, or tag. */ @@ -40,6 +42,26 @@ interface CreatedWorktree { } ``` +```ts type-equiv +/** An existing checkout in the worktree pool of the checkout the calling Session works in. */ +interface EnterWorktreeRequest { + /** Checkout directory relative to the pool: the name `create` gave the worktree. */ + name: string +} +``` + +```ts type-equiv +/** An existing checkout the calling Session entered. */ +interface EnteredWorktree { + /** Canonical absolute checkout directory in the filesystem provider's execution world. */ + path: string + /** Branch checked out there at entry; absent on a detached HEAD. */ + branch?: string + /** Canonical root of the checkout whose pool holds the worktree; `exit` returns the Session there. */ + repositoryRoot: string +} +``` + ```ts type-equiv /** * Stage of one creation or restoration, reported before it begins: `prepare` @@ -109,7 +131,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.worktrees` — `WorktreeService` -Creates retained Git worktrees under the mounted filesystem and sandbox providers, records each creation in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived. +Creates retained Git worktrees under the mounted filesystem and sandbox providers, moves Sessions into and out of them, records each creation and entry in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived. ```ts cordis-catalog /** @@ -148,9 +170,26 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise /** - * Return the calling Session from the worktree it works in to the source checkout that worktree was - * created from. The worktree is the recorded creation, the Session's own or fork-inherited, with the - * longest directory containing the Session's current directory. Its checkout and branch remain. + * Move the calling Session into an existing worktree in the pool of the checkout it works in. The + * directory `name` selects must lie inside that pool and be a registered worktree of the repository; + * neither Git state nor files change. The Session's log records the entry, so {@link exit} returns it to + * the checkout it entered from. Archiving the Session never removes a checkout it only entered. + * @param agent - caller whose current directory selects the checkout and its pool. + * @param request - name of the worktree inside the pool. + * @param signal - cancellation of lookup and of the working-directory change. + * @returns the entered checkout, its branch, and the checkout the Session entered from. + * @throws {WorktreeError} `WORKTREE_INVALID_ARGUMENT` for a name that is not a relative path inside the pool, + * `WORKTREE_NOT_FOUND` when the pool holds no registered worktree of that name, a command failure, and + * `WORKTREE_UNAVAILABLE` after service disposal; or the working-directory service's error when the + * registered directory no longer exists. + */ +async enter(agent: Agent, request: EnterWorktreeRequest, signal?: AbortSignal): Promise + +/** + * Return the calling Session from the worktree it works in to the checkout it entered that worktree + * from: the source checkout of a creation, or the checkout whose pool holds an entered worktree. The + * worktree is the recorded creation or entry, the Session's own or fork-inherited, with the longest + * directory containing the Session's current directory. Its checkout and branch remain. * @param agent - caller whose current directory lies in a recorded worktree. * @param signal - cancellation of directory validation and of the working-directory change. * @returns the worktree the Session left; the Session now works in its `repositoryRoot`. @@ -158,7 +197,7 @@ async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSign * `WORKTREE_UNAVAILABLE` after service disposal, or the working-directory service's error when the source * checkout no longer exists. */ -async exit(agent: Agent, signal?: AbortSignal): Promise +async exit(agent: Agent, signal?: AbortSignal): Promise /** * Read the archive cleanup of a Session's created checkout; waiting never diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 6d033331c8..2eaa505d5a 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 56c5b98d1014acdf - zh: a4a89e68640bd6aa + en: 57f5bdf5d35d5bc5 + zh: 41d4446d7b7f4eca /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -324,11 +324,14 @@ en: d5f5679abe86e316 zh: d5f5679abe86e316 /tool-schema-catalog/deepseek-ai-dsh-experimental-tool-worktree/create-worktree: - en: d06b107645e340bf - zh: 1b996d4980edf6fc + en: 5c3d354aa18e8d19 + zh: 275bff3958cf465a +/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-worktree/enter-worktree: + en: 644de5ca0bc1d312 + zh: 7a2f4860089bfcb8 /tool-schema-catalog/deepseek-ai-dsh-experimental-tool-worktree/exit-worktree: - en: 499364c213893caf - zh: 1f08cbfce523be98 + en: 834d21fd914b7211 + zh: ea1501ee1fc8a754 /tool-schema-catalog/deepseek-ai-dsh-tool-workflow: en: bb38a9d29f46563c zh: bb38a9d29f46563c diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index eac751b2c5..ad33324ef1 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -47,7 +47,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-jobs` | `job_kill`, `job_list`, `job_output` | `ctx.tools`, `ctx.jobs`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-job controller: background bash commands and PTY sends are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers' `ctx.jobs.start()`. | | `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist. `allowParallelInProgress` is required with no default, so the catalog states its choice: `true`, whose description invites several `in_progress` items. A deployment choosing `false` receives the same tool with a description asking for exactly one active task. | -| `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree`, `exit_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `workspace-root/change`, `tool/result` | - | Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. `exit_worktree` returns the Session to the source checkout; the branch and checkout remain. | +| `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree`, `enter_worktree`, `exit_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `workspace-root/change`, `tool/result` | - | Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. `enter_worktree` moves the Session into an existing worktree in the pool of the checkout it works in; `exit_worktree` returns the Session to the checkout it came from; the branch and checkout remain. | | `@deepseek-ai/dsh-tool-workflow` | `workflow` | `ctx.tools`, `ctx.workflowEngine`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents the script children)` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-tool-workspace-dependencies` | `load_workspace_dependencies` | `ctx.tools` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-tool-web` | `web_fetch`, `web_search` | `ctx.tools`, `ctx.web`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | web_search and web_fetch keep provider selection behind ctx.web so model-visible schemas stay stable across backend swaps. | @@ -2643,7 +2643,7 @@ todo_write is session-owned state; UIs render the latest todo/write event as a c ### `create_worktree` -Create a new Git branch and worktree from a local commit, branch, or tag, then change this session's working directory to it. Uncommitted files stay in the source checkout. Existing names fail. exit_worktree returns to the source checkout. +Create a new Git branch and worktree from a local commit, branch, or tag, then change this session's working directory to it. Uncommitted files stay in the source checkout. Existing names fail; enter_worktree enters an existing worktree. exit_worktree returns to the source checkout. ```json { @@ -2663,9 +2663,30 @@ Create a new Git branch and worktree from a local commit, branch, or tag, then c Source: [`packages/experimental/tool-worktree/src/index.ts`](../packages/experimental/tool-worktree/src/index.ts) +### `enter_worktree` + +Change this session's working directory to an existing worktree that was created from the checkout this session is in. Branches and files stay as they are. exit_worktree returns to that checkout. + +```json +{ + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name the worktree was created with." + } + }, + "required": [ + "name" + ] +} +``` + +Source: [`packages/experimental/tool-worktree/src/index.ts`](../packages/experimental/tool-worktree/src/index.ts) + ### `exit_worktree` -Change this session's working directory from the worktree it is in back to the checkout that worktree was created from, and report the worktree left. The worktree and its branch remain. +Change this session's working directory from the worktree it is in back to the checkout it entered that worktree from, and report the worktree left. The worktree and its branch remain. ```json { @@ -2676,7 +2697,7 @@ Change this session's working directory from the worktree it is in back to the c Source: [`packages/experimental/tool-worktree/src/index.ts`](../packages/experimental/tool-worktree/src/index.ts) -Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. `exit_worktree` returns the Session to the source checkout; the branch and checkout remain. +Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. `enter_worktree` moves the Session into an existing worktree in the pool of the checkout it works in; `exit_worktree` returns the Session to the checkout it came from; the branch and checkout remain. diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 05e84a872b..07f86709a0 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -51,7 +51,7 @@ | `@deepseek-ai/dsh-tool-jobs` | `job_kill`、`job_list`、`job_output` | `ctx.tools`、`ctx.jobs`、`ctx.systemPrompt` | `tool/call`、`tool/result`、`user/message via agent.inject() for background completion notices` | - | 与任务种类无关的后台任务控制器:后台 bash 命令与 PTY 发送 都通过相同的 3 个工具读取、列出和终止。加载该插件会挂接控制器,从而启用生产方的 `ctx.jobs.start()`。 | | `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响。 | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`、`owning Agent session` | `tool/call`、`todo/write`、`tool/result` | - | todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为检查清单。`allowParallelInProgress` 是没有默认值的必填项,因此本目录明确选择 `true`,对应描述允许同时存在多个 `in_progress` 项。选择 `false` 的部署会获得同一工具,但描述会要求只能有 1 个活动任务。 | -| `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree`, `exit_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `workspace-root/change`, `tool/result` | - | 在 Web 和 Desktop 上通过变更请求与工作树组合包启用;其他 profile 可以选择独立组合包。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。`exit_worktree` 把 Session 送回源检出目录;分支与检出目录保留。 | +| `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree`, `enter_worktree`, `exit_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `workspace-root/change`, `tool/result` | - | 在 Web 和 Desktop 上通过变更请求与工作树组合包启用;其他 profile 可以选择独立组合包。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。`enter_worktree` 把 Session 移入它所在检出的池中已有的工作树;`exit_worktree` 把 Session 送回它来自的检出目录;分支与检出目录保留。 | | `@deepseek-ai/dsh-tool-workflow` | `workflow` | `ctx.tools`、`ctx.workflowEngine`、`ctx.systemPrompt`、`a calling Agent (exec.agent parents the script children)` | `tool/call`、`tool/result` | - | - | | `@deepseek-ai/dsh-tool-workspace-dependencies` | `load_workspace_dependencies` | `ctx.tools` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-tool-web` | `web_fetch`、`web_search` | `ctx.tools`、`ctx.web`、`ctx.systemPrompt` | `tool/call`、`tool/result` | - | web_search 和 web_fetch 将提供方选择置于 ctx.web 之后,使模型可见 schema 在更换后端时保持稳定。 | @@ -2649,7 +2649,7 @@ todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为 ### `create_worktree` -从本地提交、分支或标签创建新的 Git 分支与工作树,再将本 Session 的工作目录切换到该位置。未提交文件保留在源检出目录中。名称已存在时失败。exit_worktree 返回源检出目录。 +从本地提交、分支或标签创建新的 Git 分支与工作树,再将本 Session 的工作目录切换到该位置。未提交文件保留在源检出目录中。名称已存在时失败;enter_worktree 进入已有的工作树。exit_worktree 返回源检出目录。 ```json { @@ -2669,9 +2669,30 @@ todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为 来源:[`packages/experimental/tool-worktree/src/index.ts`](../packages/experimental/tool-worktree/src/index.ts) +### `enter_worktree` + +把本 Session 的工作目录切换到一个已有的工作树,该工作树须是从本 Session 所在的检出目录创建的。分支与文件保持原样。exit_worktree 返回该检出目录。 + +```json +{ + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name the worktree was created with." + } + }, + "required": [ + "name" + ] +} +``` + +来源:[`packages/experimental/tool-worktree/src/index.ts`](../packages/experimental/tool-worktree/src/index.ts) + ### `exit_worktree` -把本 Session 的工作目录从所在的工作树切换回创建该工作树的检出目录,并报告所离开的工作树。工作树及其分支保留。 +把本 Session 的工作目录从所在的工作树切换回进入该工作树时所在的检出目录,并报告所离开的工作树。工作树及其分支保留。 ```json { @@ -2682,7 +2703,7 @@ todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为 来源:[`packages/experimental/tool-worktree/src/index.ts`](../packages/experimental/tool-worktree/src/index.ts) -在 Web 和 Desktop 上通过变更请求与工作树组合包启用;其他 profile 可以选择独立组合包。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。`exit_worktree` 把 Session 送回源检出目录;分支与检出目录保留。 +在 Web 和 Desktop 上通过变更请求与工作树组合包启用;其他 profile 可以选择独立组合包。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。`enter_worktree` 把 Session 移入它所在检出的池中已有的工作树;`exit_worktree` 把 Session 送回它来自的检出目录;分支与检出目录保留。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.i18n.yaml index 81f90b591b..bd65e7e8f5 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 9f20155a3198221f zh: 4e8fbfcc6e819ac6 /the-working-directory-tool-and-the-subagent-cwd-parameter-are-removed/change: - en: 0f2e456440c8f4f1 - zh: 723098d30ce5a077 + en: 1a4d05e4e678a400 + zh: 41dd47d57aaea5dc /the-working-directory-tool-and-the-subagent-cwd-parameter-are-removed/migration: - en: 718c75ffcd864127 - zh: 58e9ffd13646ef52 + en: 7be13e241868a3c2 + zh: 78fbf7a8ca905597 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.md index 3ae683b846..52bad8d881 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.md @@ -10,7 +10,7 @@ English | [中文](guide.zh.md) The model tool `working_directory` and its package `@deepseek-ai/dsh-tool-working-directory` no longer exist; the `dsh-base` and `dsh-sdk-minimal` bundles no longer mount the `tool-working-directory` entry. The delegation tools registered by `@deepseek-ai/dsh-tool-subagent`, and `subagent_oar`, no longer accept `cwd`: a child starts in the caller's workspace directory. -A Session's directory now changes only through Host operations: `create_worktree`, the new `exit_worktree`, the forge panel, SDK `setWorkingDirectory` (`set_working_directory` in Python), and recovery when the directory disappears. Each change is recorded as `workspace-root/change`; the [persistence record](../../../persistence-changes/2026-11-13-workspace-root-change.md) covers stored logs and readers of earlier releases. A stored Session whose model changed the directory resumes in that directory. Its recorded `working_directory` calls remain history, and a new call returns `unknown tool "working_directory"`. +A Session's directory now changes only through Host operations: `create_worktree`, the new `enter_worktree` and `exit_worktree`, the forge panel, SDK `setWorkingDirectory` (`set_working_directory` in Python), and recovery when the directory disappears. Each change is recorded as `workspace-root/change`; the [persistence record](../../../persistence-changes/2026-11-13-workspace-root-change.md) covers stored logs and readers of earlier releases. A stored Session whose model changed the directory resumes in that directory. Its recorded `working_directory` calls remain history, and a new call returns `unknown tool "working_directory"`. Who observes it: prompts, skills, and evaluation sets that expect the tool or the parameter in the tool list; profiles and patches that name the `tool-working-directory` entry or the package; Host plugins that pass a model-supplied path to `ctx.subagents.start({ cwd })` or `ctx.workingDirectory.set`, which now also moves the Session's workspace root. @@ -18,6 +18,6 @@ Who observes it: prompts, skills, and evaluation sets that expect the tool or th 1. Remove `tool-working-directory` rows and `@deepseek-ai/dsh-tool-working-directory` dependencies from profiles, patches, and package manifests. A patch that still names the entry reports `patch: entry "tool-working-directory" not found` at load. 2. In prompts, skills, and scripted model turns, replace `working_directory({ cd })` with paths relative to the Session directory or absolute paths, and with the `workdir` argument of `bash` or `pwsh` for commands. The `Current working directory:` line of the user context replaces `working_directory()` as the way to read the directory. -3. To leave a worktree, call `exit_worktree()`. It returns the Session to the checkout the worktree was created from. +3. To leave a worktree, call `exit_worktree()`. It returns the Session to the checkout the worktree was created or entered from. To return to an existing worktree, call `enter_worktree({ name })` from the checkout it was created from. 4. Remove `cwd` from `subagent` and `subagent_oar` calls and name the subdirectory in the task. A Host that needs another start directory passes a path it chose itself to `ctx.subagents.start({ cwd })`. 5. Confirm: `dsh --profile headless --dump-config` lists no `tool-working-directory` entry, and the tool list of a first request contains neither `working_directory` nor a `cwd` property on `subagent`. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.zh.md index 75ab8a0ace..3ae338c5dd 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/working-directory-tool-removed/guide.zh.md @@ -10,7 +10,7 @@ description: "模型工具 `working_directory`、它的包以及子代理工具 模型工具 `working_directory` 及其包 `@deepseek-ai/dsh-tool-working-directory` 不再存在;`dsh-base` 与 `dsh-sdk-minimal` 组合包不再挂载 `tool-working-directory` 条目。`@deepseek-ai/dsh-tool-subagent` 注册的委派工具以及 `subagent_oar` 不再接受 `cwd`:子代理从调用方的工作区目录启动。 -Session 的目录现在只通过 Host 操作改变:`create_worktree`、新增的 `exit_worktree`、forge 面板、SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`),以及目录消失时的恢复。每次变更都记录为 `workspace-root/change`;[持久化记录](../../../persistence-changes/2026-11-13-workspace-root-change.zh.md)说明已存储日志的读法和早期版本读者的行为。模型曾改变过目录的已存储 Session 会在该目录恢复。其中记录的 `working_directory` 调用仍是历史,新的调用返回 `unknown tool "working_directory"`。 +Session 的目录现在只通过 Host 操作改变:`create_worktree`、新增的 `enter_worktree` 与 `exit_worktree`、forge 面板、SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`),以及目录消失时的恢复。每次变更都记录为 `workspace-root/change`;[持久化记录](../../../persistence-changes/2026-11-13-workspace-root-change.zh.md)说明已存储日志的读法和早期版本读者的行为。模型曾改变过目录的已存储 Session 会在该目录恢复。其中记录的 `working_directory` 调用仍是历史,新的调用返回 `unknown tool "working_directory"`。 受影响的对象:期望工具列表中有该工具或该参数的提示词、技能与评测集;引用 `tool-working-directory` 条目或该包的 profile 与 patch;把模型提供的路径传给 `ctx.subagents.start({ cwd })` 或 `ctx.workingDirectory.set` 的 Host 插件,后者现在同时移动 Session 的工作区根。 @@ -18,6 +18,6 @@ Session 的目录现在只通过 Host 操作改变:`create_worktree`、新增 1. 从 profile、patch 和包清单中移除 `tool-working-directory` 行与 `@deepseek-ai/dsh-tool-working-directory` 依赖。仍然引用该条目的 patch 在加载时报告 `patch: entry "tool-working-directory" not found`。 2. 在提示词、技能和脚本化的模型轮次中,把 `working_directory({ cd })` 替换为相对 Session 目录的路径或绝对路径,命令使用 `bash` 或 `pwsh` 的 `workdir` 参数。读取目录改用用户上下文中的 `Current working directory:` 一行,不再调用 `working_directory()`。 -3. 离开工作树时调用 `exit_worktree()`。它把 Session 送回创建该工作树的检出目录。 +3. 离开工作树时调用 `exit_worktree()`。它把 Session 送回创建或进入该工作树时所在的检出目录。要回到已有的工作树,在创建它的检出目录中调用 `enter_worktree({ name })`。 4. 从 `subagent` 与 `subagent_oar` 调用中移除 `cwd`,把子目录写进任务。需要其他起始目录的 Host 把自己选定的路径传给 `ctx.subagents.start({ cwd })`。 5. 确认:`dsh --profile headless --dump-config` 不再列出 `tool-working-directory` 条目,首个请求的工具列表中既没有 `working_directory`,`subagent` 也没有 `cwd` 属性。 diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index b61d38077f..ac1017ada7 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -29,7 +29,7 @@ describe('gen-tool-catalog collectToolCatalog', () => { expect(names).toEqual([ 'apply_patch', 'ask_user_question', 'bash', 'bash', 'cordis_inspect_list', 'cordis_inspect_query', - 'create_goal', 'create_worktree', 'edit', 'exit_plan_mode', 'exit_worktree', 'get_goal', 'glob', 'grep', + 'create_goal', 'create_worktree', 'edit', 'enter_worktree', 'exit_plan_mode', 'exit_worktree', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', 'list_subagent_models', 'load_workspace_dependencies', 'lsp', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'plugin_market', 'present', 'propose_action', 'pwsh', 'pwsh', 'ralph', diff --git a/packages/experimental/forge-bundle/README.i18n.yaml b/packages/experimental/forge-bundle/README.i18n.yaml index b83bfcba9f..016b4ca42c 100644 --- a/packages/experimental/forge-bundle/README.i18n.yaml +++ b/packages/experimental/forge-bundle/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-bundle/use-this-package: - en: 33679bed06be4e74 - zh: 77dcfac9570d1fbc + en: e5299486a672bc02 + zh: d43b01e6f30564cd /deepseek-ai-dsh-experimental-forge-bundle/understand-the-implementation: en: 3afaeb5efc183949 zh: c916499192d320f3 @@ -24,8 +24,8 @@ en: ab1f524b8ad79c55 zh: 137cfcb6d192c269 /deepseek-ai-dsh-experimental-forge-bundle/model-experience: - en: 48e871ea5f1238c8 - zh: 6d40dddf8de9d610 + en: 644b2bf5400cc89f + zh: d796d4c675e6970c /deepseek-ai-dsh-experimental-forge-bundle/model-experience/kv-cache-effect: en: 0192ab064b8000a7 zh: 1a1de04f87631b9a diff --git a/packages/experimental/forge-bundle/README.md b/packages/experimental/forge-bundle/README.md index 63a0756d38..4e7a5ffbd1 100644 --- a/packages/experimental/forge-bundle/README.md +++ b/packages/experimental/forge-bundle/README.md @@ -27,7 +27,7 @@ Review each Session's change requests, checks, and diffs, start a new Session in Open Plugins and enable Change requests & worktrees in the Official group. In a Git workspace, check Worktree in the composer before the first message to start the Session in a new worktree. In a Session whose directory is inside a Git checkout, the header button opens the panel. GitHub pull requests that the Session creates with `gh pr create`, opens with `gh pr view`, `gh pr edit`, or `gh pr checkout`, or works on as its branch or updates with a later `git push`, appear as change requests without further steps. Run `gh auth login --hostname ` in a terminal to sign in; the panel shows the command when sign-in is missing. The [panel package](../client-ui-forge/README.md#use-this-package) describes each control. -The same switch enables the model's [`create_worktree`](../tool-worktree/README.md) tool. Turning it off removes both the panel and the tool while retaining existing checkouts and branches. For profiles that already selected the standalone worktree bundle, follow the [upgrade guide](../../../docs/upgrade-guide/v0.2.2-alpha.2/forge-worktree-entry/guide.md) before enabling this bundle. +The same switch enables the model's [worktree tools](../tool-worktree/README.md): `create_worktree`, `enter_worktree`, and `exit_worktree`. Turning it off removes both the panel and the tools while retaining existing checkouts and branches. For profiles that already selected the standalone worktree bundle, follow the [upgrade guide](../../../docs/upgrade-guide/v0.2.2-alpha.2/forge-worktree-entry/guide.md) before enabling this bundle. ----- @@ -53,7 +53,7 @@ The bundle mounts the forge registry, the GitHub and GitLab providers, Session b ## Model Experience -Indirectly, through the [`create_worktree`](../tool-worktree/README.md#model-experience) tool and the [panel’s directory notice](../client-ui-forge/README.md#model-experience) for Sessions that start in a worktree. +Indirectly, through the [worktree tools](../tool-worktree/README.md#model-experience) and the [panel’s directory notice](../client-ui-forge/README.md#model-experience) for Sessions that start in a worktree. #### KV Cache effect diff --git a/packages/experimental/forge-bundle/README.zh.md b/packages/experimental/forge-bundle/README.zh.md index 9281ae93d1..b8838efbc4 100644 --- a/packages/experimental/forge-bundle/README.zh.md +++ b/packages/experimental/forge-bundle/README.zh.md @@ -27,7 +27,7 @@ kind: "package-bundle" 打开插件页面,在官方分组中启用“变更请求与工作树”。在 Git 工作区中,发出第一条消息之前在输入框中勾选“工作树”,Session 就会在新的 worktree 中开始。Session 的目录位于 Git 检出中时,标题栏按钮会打开面板。Session 用 `gh pr create` 创建、用 `gh pr view`、`gh pr edit` 或 `gh pr checkout` 打开的 GitHub pull request,以及 Session 所在分支上或之后 `git push` 更新的 pull request,无需额外操作即会作为变更请求出现。在终端运行 `gh auth login --hostname ` 登录;缺少登录时,面板会显示这条命令。[面板包](../client-ui-forge/README.zh.md#use-this-package)说明了每个控件。 -同一个开关也启用模型的 [`create_worktree`](../tool-worktree/README.zh.md) 工具。关闭后面板和工具一起移除,已有检出目录与分支仍然保留。已选中独立工作树组合包的 profile,请在启用本组合包前按[升级指南](../../../docs/upgrade-guide/v0.2.2-alpha.2/forge-worktree-entry/guide.zh.md)调整配置。 +同一个开关也启用模型的[工作树工具](../tool-worktree/README.zh.md):`create_worktree`、`enter_worktree` 与 `exit_worktree`。关闭后面板和工具一起移除,已有检出目录与分支仍然保留。已选中独立工作树组合包的 profile,请在启用本组合包前按[升级指南](../../../docs/upgrade-guide/v0.2.2-alpha.2/forge-worktree-entry/guide.zh.md)调整配置。 ----- @@ -53,7 +53,7 @@ kind: "package-bundle" ## 模型体验 -间接影响:通过 [`create_worktree`](../tool-worktree/README.zh.md#model-experience) 工具,以及以工作树开始的 Session 的[面板目录通知](../client-ui-forge/README.zh.md#model-experience)。 +间接影响:通过[工作树工具](../tool-worktree/README.zh.md#model-experience),以及以工作树开始的 Session 的[面板目录通知](../client-ui-forge/README.zh.md#model-experience)。 #### KV Cache 影响 diff --git a/packages/experimental/tool-worktree/README.i18n.yaml b/packages/experimental/tool-worktree/README.i18n.yaml index 94b59a39d6..1a4f3bcff7 100644 --- a/packages/experimental/tool-worktree/README.i18n.yaml +++ b/packages/experimental/tool-worktree/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/experimental/tool-worktree/README.md /: - en: 7c7c8316f315eee0 - zh: dfd3abcef256029e + en: 09a4b4d95b664d1c + zh: c229106b16e9ecd9 /deepseek-ai-dsh-experimental-tool-worktree: en: db61f6b6ad671f45 zh: 9f3083d7f5605cbb /deepseek-ai-dsh-experimental-tool-worktree/summary: - en: 106bccb04bd14134 - zh: 579b316a56bebbb8 + en: c978e8e0be90d5f8 + zh: 75c20376f2e9d45f /deepseek-ai-dsh-experimental-tool-worktree/table-of-contents: en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-tool-worktree/use-this-package: - en: 3da61bef9ee229bf - zh: 3a83507f3365fe38 + en: 59068f72c326c780 + zh: 0c0f3687d971063c /deepseek-ai-dsh-experimental-tool-worktree/understand-the-implementation: - en: c03f875211ab69a8 - zh: 8f49b82f90a60223 + en: 20d2b29ce103e6f0 + zh: 4e705758734ddb97 /deepseek-ai-dsh-experimental-tool-worktree/further-exploration: en: 6ec5bb0f5bfbbaa4 zh: 45009dd139621d0e @@ -30,8 +30,8 @@ en: 4062fcaa4794bed7 zh: b56d35fc675fc430 /deepseek-ai-dsh-experimental-tool-worktree/model-experience/creation-tool/what-the-model-sees: - en: 07fc4bda6b786621 - zh: 149a7c5474b709b3 + en: 6e1fdb5ed5494542 + zh: 2ed8dcf7777f9ee9 /deepseek-ai-dsh-experimental-tool-worktree/model-experience/creation-tool/token-effect: en: 6c3f73ba01233a36 zh: d64d87a425db4fbd @@ -39,8 +39,8 @@ en: 365f8ccedfa61bbb zh: aa328044ba2528b8 /deepseek-ai-dsh-experimental-tool-worktree/known-limitations-and-deferred-work: - en: 7cfc071dfc3f9c83 - zh: f36ae822e801db12 + en: f0e0c0f36b6252a2 + zh: b2cd1fdcad570ce9 /deepseek-ai-dsh-experimental-tool-worktree/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/tool-worktree/README.md b/packages/experimental/tool-worktree/README.md index 5467a8b2d7..51dce1e83a 100644 --- a/packages/experimental/tool-worktree/README.md +++ b/packages/experimental/tool-worktree/README.md @@ -1,5 +1,5 @@ --- -description: "Model tool that creates a new local Git worktree and changes the current Session directory." +description: "Model tools that create a local Git worktree, enter an existing one, and return to the source checkout." kind: "package-bundle" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Let a model create and enter a new Git worktree with one call. Web and Desktop expose this tool through Change requests & worktrees; other profiles can select this standalone bundle. Native tool calls and PTC programs receive the same typed result, and the existing file policy governs creation. +Let a model create and enter a new Git worktree with one call, enter an existing one by name, and return to the checkout it came from. Web and Desktop expose these tools through Change requests & worktrees; other profiles can select this standalone bundle. Native tool calls and PTC programs receive the same typed result, and the existing file policy governs creation. ## Table of Contents @@ -25,7 +25,7 @@ Let a model create and enter a new Git worktree with one call. Web and Desktop e ## Use this package -In the GUI, enable [Change requests & worktrees](../forge-bundle/README.md). The standalone bundle has no Plugins page card. Profiles without the Web application may select it in `dsh.profile.bundles`; it loads the [worktree runtime](../worktree/README.md) and this tool together. Turning it off removes `create_worktree` and `exit_worktree` without deleting existing checkouts or branches; a Session inside a worktree stays there until a Host operation moves it. +In the GUI, enable [Change requests & worktrees](../forge-bundle/README.md). The standalone bundle has no Plugins page card. Profiles without the Web application may select it in `dsh.profile.bundles`; it loads the [worktree runtime](../worktree/README.md) and this tool together. Turning it off removes `create_worktree`, `enter_worktree`, and `exit_worktree` without deleting existing checkouts or branches; a Session inside a worktree stays there until a Host operation moves it. For an explicit composition, mount this function plugin after the worktree runtime and tool registry. @@ -34,7 +34,7 @@ For an explicit composition, mount this function plugin after the worktree runti - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -Call `create_worktree({ name?: string, from?: string })`. Success returns the canonical checkout `path`, new `branch`, pinned `baseCommit`, and source `repositoryRoot`, and changes the calling Session's current working directory. To leave, call `exit_worktree()`: it returns the Session to the source checkout of the worktree it is in and reports that worktree's record; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description. +Call `create_worktree({ name?: string, from?: string })`. Success returns the canonical checkout `path`, new `branch`, pinned `baseCommit`, and source `repositoryRoot`, and changes the calling Session's current working directory. `enter_worktree({ name: string })` moves the Session into an existing worktree that was created from the checkout it is in, and returns the worktree's `path`, its `branch` when one is checked out, and the `repositoryRoot` the Session came from. To leave, call `exit_worktree()`: it returns the Session to the checkout it created or entered the worktree from and reports that worktree's record; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description. ----- @@ -44,7 +44,7 @@ Call `create_worktree({ name?: string, from?: string })`. Success returns the ca
Implementation internals — click to expand -[`cordis.patch.yml`](cordis.patch.yml) inserts the `worktree` runtime row and the `tool-worktree` consumer row. [`src/index.ts`](src/index.ts) registers one typed tool. Runtime creation owns Git behavior, cancellation, and the working-directory change. The tool returns the runtime record as its canonical value and renders that record as JSON; its Host presentation uses the generic card. Disposal unregisters the tool. +[`cordis.patch.yml`](cordis.patch.yml) inserts the `worktree` runtime row and the `tool-worktree` consumer row. [`src/index.ts`](src/index.ts) registers three typed tools. The runtime owns Git behavior, cancellation, and the working-directory change. Each tool returns the runtime record as its canonical value and renders that record as JSON; its Host presentation uses the generic card. Disposal unregisters the tools. No runtime invariant companion is published because the tool retains no state independently of the worktree runtime. @@ -68,7 +68,7 @@ No runtime invariant companion is published because the tool retains no state in #### What the model sees -The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) defines `create_worktree` and `exit_worktree`. Each successful result contains the canonical path, branch, base commit, and source checkout’s top-level directory of the worktree created or left. Failed calls report the operation error. +The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) defines `create_worktree`, `enter_worktree`, and `exit_worktree`. Each successful result contains the canonical path and branch of the worktree created, entered, or left, and the top-level directory of the checkout the Session came from; a creation, and the exit of a created worktree, add the base commit. Failed calls report the operation error. #### Token effect @@ -83,7 +83,7 @@ Unchanged tool schemas retain their existing prefix. Calls append after prior hi - **Calling Agent required** — the tool changes a Session directory and rejects calls without an Agent. -- **Creation only** — inspection, merging, and checkout or branch removal are outside this tool; the [runtime limitations](../worktree/README.md#known-limitations-and-deferred-work) also apply. +- **Creation and entry only** — listing, inspection, merging, and checkout or branch removal are outside these tools, and `enter_worktree` reaches only worktrees in the pool of the checkout the Session is in; the [runtime limitations](../worktree/README.md#known-limitations-and-deferred-work) also apply. ### Dev Note diff --git a/packages/experimental/tool-worktree/README.zh.md b/packages/experimental/tool-worktree/README.zh.md index 49313254ef..2fd828b254 100644 --- a/packages/experimental/tool-worktree/README.zh.md +++ b/packages/experimental/tool-worktree/README.zh.md @@ -1,5 +1,5 @@ --- -description: "创建新的本地 Git 工作树并改变当前 Session 目录的模型工具。" +description: "创建本地 Git 工作树、进入已有工作树并返回源检出的模型工具。" kind: "package-bundle" --- @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -让模型通过一次调用创建并进入新的 Git 工作树。Web 与 Desktop 通过“变更请求与工作树”提供本工具;其他 profile 可以选择本独立组合包。原生工具调用与 PTC 程序获得相同的带类型结果,创建操作沿用现有文件策略。 +让模型通过一次调用创建并进入新的 Git 工作树,按名称进入已有的工作树,并回到它来自的检出。Web 与 Desktop 通过“变更请求与工作树”提供这些工具;其他 profile 可以选择本独立组合包。原生工具调用与 PTC 程序获得相同的带类型结果,创建操作沿用现有文件策略。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-bundle" ## 使用本包 -在 GUI 中启用[变更请求与工作树](../forge-bundle/README.zh.md)。独立组合包在插件页没有卡片。未组合 Web 应用的 profile 可以在 `dsh.profile.bundles` 中选择它;它一起加载[工作树运行时](../worktree/README.zh.md)与本工具。关闭后会移除 `create_worktree` 与 `exit_worktree`,已有检出目录与分支会保留;已在工作树中的 Session 会留在原处,直到 Host 操作移动它。 +在 GUI 中启用[变更请求与工作树](../forge-bundle/README.zh.md)。独立组合包在插件页没有卡片。未组合 Web 应用的 profile 可以在 `dsh.profile.bundles` 中选择它;它一起加载[工作树运行时](../worktree/README.zh.md)与本工具。关闭后会移除 `create_worktree`、`enter_worktree` 与 `exit_worktree`,已有检出目录与分支会保留;已在工作树中的 Session 会留在原处,直到 Host 操作移动它。 在显式组合中,将此函数插件挂载到工作树运行时和工具注册表之后。 @@ -34,7 +34,7 @@ kind: "package-bundle" - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -调用 `create_worktree({ name?: string, from?: string })`。成功会返回规范化检出路径 `path`、新分支 `branch`、固定提交 `baseCommit` 和源仓库根目录 `repositoryRoot`,并改变调用 Session 的当前工作目录。离开时调用 `exit_worktree()`:它把 Session 送回所在工作树的源检出,并返回该工作树的记录;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。 +调用 `create_worktree({ name?: string, from?: string })`。成功会返回规范化检出路径 `path`、新分支 `branch`、固定提交 `baseCommit` 和源仓库根目录 `repositoryRoot`,并改变调用 Session 的当前工作目录。`enter_worktree({ name: string })` 把 Session 移入从它所在检出创建的已有工作树,返回该工作树的 `path`、检出了分支时的 `branch`,以及 Session 进入前所在的 `repositoryRoot`。离开时调用 `exit_worktree()`:它把 Session 送回创建或进入该工作树时所在的检出,并返回该工作树的记录;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。 ----- @@ -44,7 +44,7 @@ kind: "package-bundle"
实现细节——点击展开 -[`cordis.patch.yml`](cordis.patch.yml) 插入 `worktree` 运行时行与 `tool-worktree` 消费方行。[`src/index.ts`](src/index.ts) 注册一个带类型的工具。运行时创建操作拥有 Git 行为、取消处理与工作目录切换。工具将运行时记录作为规范返回值,并渲染为 JSON;Host 展示使用通用卡片。销毁插件会注销工具。 +[`cordis.patch.yml`](cordis.patch.yml) 插入 `worktree` 运行时行与 `tool-worktree` 消费方行。[`src/index.ts`](src/index.ts) 注册三个带类型的工具。运行时拥有 Git 行为、取消处理与工作目录切换。每个工具将运行时记录作为规范返回值,并渲染为 JSON;Host 展示使用通用卡片。销毁插件会注销这些工具。 本包不发布运行时不变量伴随入口,因为工具不保留独立于工作树运行时的状态。 @@ -68,7 +68,7 @@ kind: "package-bundle" #### 模型看到什么 -[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)定义 `create_worktree` 与 `exit_worktree`。每个成功结果包含所创建或所离开工作树的规范路径、分支、基准提交与源检出目录的顶层目录。失败调用报告操作错误。 +[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)定义 `create_worktree`、`enter_worktree` 与 `exit_worktree`。每个成功结果包含所创建、所进入或所离开工作树的规范路径与分支,以及 Session 来自的检出的顶层目录;创建以及离开自己创建的工作树时还包含基准提交。失败调用报告操作错误。 #### Token 影响 @@ -83,7 +83,7 @@ kind: "package-bundle" - **必须有调用 Agent**——工具改变 Session 目录,没有 Agent 的调用会被拒绝。 -- **仅负责创建**——检查、合并、移除检出目录或删除分支不属于此工具;[运行时限制](../worktree/README.zh.md#known-limitations-and-deferred-work)同样适用。 +- **仅负责创建与进入**——列出、检查、合并、移除检出目录或删除分支不属于这些工具,`enter_worktree` 只能到达 Session 所在检出的池中的工作树;[运行时限制](../worktree/README.zh.md#known-limitations-and-deferred-work)同样适用。 ### 开发备注 diff --git a/packages/experimental/tool-worktree/src/index.ts b/packages/experimental/tool-worktree/src/index.ts index 4362b1bfcc..f182226993 100644 --- a/packages/experimental/tool-worktree/src/index.ts +++ b/packages/experimental/tool-worktree/src/index.ts @@ -1,4 +1,7 @@ -/** Model tools for creating and entering a new Git worktree, and for returning to its source checkout, through the shared runtime. */ +/** + * Model tools for creating and entering a new Git worktree, entering an existing one, and returning to the + * source checkout, through the shared runtime. + */ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-experimental-worktree' @@ -9,8 +12,8 @@ export const name = 'tool-worktree' /** Services required to register and execute the worktree tools. */ export const inject = ['tools', 'worktrees'] -/** Result fields both tools report for one worktree. */ -const WORKTREE_SCHEMA = { +/** Result fields of a created worktree. */ +const CREATED_SCHEMA = { type: 'object', additionalProperties: false, properties: { @@ -21,20 +24,43 @@ const WORKTREE_SCHEMA = { }, } as const +/** Result fields of an entered worktree; `branch` is absent on a detached HEAD. */ +const ENTERED_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + path: { type: 'string', required: true }, + branch: { type: 'string' }, + repositoryRoot: { type: 'string', required: true }, + }, +} as const + +/** Result fields of the worktree a Session left: those of its creation, or of its entry. */ +const EXITED_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + path: { type: 'string', required: true }, + branch: { type: 'string' }, + baseCommit: { type: 'string' }, + repositoryRoot: { type: 'string', required: true }, + }, +} as const + /** - * Register create_worktree and exit_worktree for model and PTC callers. + * Register create_worktree, enter_worktree, and exit_worktree for model and PTC callers. * @param ctx - tool registry and worktree runtime. */ export function apply(ctx: Context): void { ctx.tools.register(defineTool({ name: 'create_worktree', - description: 'Create a new Git branch and worktree from a local commit, branch, or tag, then change this session\'s working directory to it. Uncommitted files stay in the source checkout. Existing names fail. exit_worktree returns to the source checkout.', + description: 'Create a new Git branch and worktree from a local commit, branch, or tag, then change this session\'s working directory to it. Uncommitted files stay in the source checkout. Existing names fail; enter_worktree enters an existing worktree. exit_worktree returns to the source checkout.', parameters: { name: { type: 'string', description: 'New branch name, also used as the checkout directory: a few lowercase words joined by hyphens that describe the task, such as fix-login-retry. Omit to generate a unique name.' }, from: { type: 'string', description: 'Local commit, branch, or tag to start from. Defaults to HEAD; no fetch is performed.' }, }, output: { - schema: WORKTREE_SCHEMA, + schema: CREATED_SCHEMA, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, async execute(args, exec) { @@ -43,12 +69,28 @@ export function apply(ctx: Context): void { }, presentCall: args => ({ card: 'generic', title: 'create_worktree', rawInput: args }), })) + ctx.tools.register(defineTool({ + name: 'enter_worktree', + description: 'Change this session\'s working directory to an existing worktree that was created from the checkout this session is in. Branches and files stay as they are. exit_worktree returns to that checkout.', + parameters: { + name: { type: 'string', required: true, description: 'Name the worktree was created with.' }, + }, + output: { + schema: ENTERED_SCHEMA, + render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], + }, + async execute(args, exec) { + if (exec.agent === undefined) throw new ToolContextUnavailableError('enter_worktree requires a calling agent') + return ctx.worktrees.enter(exec.agent, args, exec.signal) + }, + presentCall: args => ({ card: 'generic', title: 'enter_worktree', rawInput: args }), + })) ctx.tools.register(defineTool({ name: 'exit_worktree', - description: 'Change this session\'s working directory from the worktree it is in back to the checkout that worktree was created from, and report the worktree left. The worktree and its branch remain.', + description: 'Change this session\'s working directory from the worktree it is in back to the checkout it entered that worktree from, and report the worktree left. The worktree and its branch remain.', parameters: {}, output: { - schema: WORKTREE_SCHEMA, + schema: EXITED_SCHEMA, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, async execute(_args: Record, exec) { diff --git a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts index 511d856282..28e4618bb0 100644 --- a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts +++ b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts @@ -38,7 +38,7 @@ afterEach(async () => { }) describe('worktree tool through real Loader composition', () => { - it('creates and enters a new checkout, exits it to the source checkout, reports canonical fields, and unregisters on disposal', async () => { + it('creates and enters a new checkout, exits it to the source checkout, enters it again by name, reports canonical fields, and unregisters on disposal', async () => { root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-worktree-loader-'))) const repository = join(root, 'repo') await mkdir(repository) @@ -126,8 +126,28 @@ describe('worktree tool through real Loader composition', () => { expect(agentless.isError && agentless.error.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(context.tools.get('exit_worktree')!.presentCall!({})).toEqual({ card: 'generic', title: 'exit_worktree', rawInput: {} }) + const enter = (name: string, agentValue?: typeof agent) => executeToolFixture(context!, { + name: 'enter_worktree', callId: brandString(`enter-${name}`), arguments: { name }, signal: new AbortController().signal, + ...agentValue === undefined ? {} : { agent: agentValue }, + }) + const entered = await enter('new-checkout', agent) + expect(entered.isError).not.toBe(true) + expect(entered.value).toEqual({ path, branch: 'new-checkout', repositoryRoot: repository }) + expect(entered.content).toEqual([{ type: 'text', text: JSON.stringify(entered.value) }]) + expect(context.workingDirectory.get(agent.session)).toBe(path) + expect((await exit(agent)).value).toEqual(result.value) + const missing = await enter('absent', agent) + expect(missing.isError && missing.error.info).toEqual({ name: 'WorktreeError', code: 'WORKTREE_NOT_FOUND' }) + expect(missing.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')).toContain('holds no registered worktree of that name') + expect(context.workingDirectory.get(agent.session)).toBe(repository) + const unowned = await enter('new-checkout') + expect(unowned.isError && unowned.error.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) + expect(context.tools.get('enter_worktree')!.presentCall!({ name: 'named' })).toEqual({ + card: 'generic', title: 'enter_worktree', rawInput: { name: 'named' }, + }) + const entry = [...context.loader.entries()].find(candidate => candidate.options.name === 'cordis:@deepseek-ai/dsh-experimental-tool-worktree') await entry!.fiber!.dispose() - expect(context.tools.schemas().some(tool => tool.name === 'create_worktree' || tool.name === 'exit_worktree')).toBe(false) + expect(context.tools.schemas().some(tool => tool.name.endsWith('_worktree'))).toBe(false) }) }) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index 13eccab406..e3dd2a678a 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/experimental/worktree/README.md /: - en: abb4e123de7c0434 - zh: 40f28bb7301d3d0a + en: 734dfee12501df90 + zh: f927271b878df1dc /deepseek-ai-dsh-experimental-worktree: en: 0fbe7569a8801a86 zh: 794c1773e8825da5 @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-worktree/use-this-package: - en: c095f4b4cf204808 - zh: 33a3e63f4c30ed3e + en: e2ecd292a52a7284 + zh: 1fe98990612ba2c0 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 @@ -30,8 +30,8 @@ en: 6826dfaadb24f3da zh: 2e2ee715247fc015 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work: - en: 9115db41d1c8eed7 - zh: 87857659a8a47c1d + en: 5fd0cba55c3f5990 + zh: 633ce8bb3a94db9e /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work/dev-note: en: ad12746a6cc96d8a zh: 66275f30a35c88e4 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index f357722948..45198dbddd 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -1,5 +1,5 @@ --- -description: "Create and enter a retained Git worktree under the calling Session file policy." +description: "Create, enter, and leave retained Git worktrees under the calling Session file policy." kind: "package-reference" --- @@ -34,13 +34,15 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, ` `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.exit(agent, signal?)` returns the Session from the recorded worktree that contains its current directory to that worktree's `repositoryRoot` through `ctx.workingDirectory.set`, and resolves to the record of the worktree it left. The record can be the Session's own or fork-inherited, and nested worktrees exit one level per call. The checkout and branch remain. The call rejects with `WORKTREE_NOT_ENTERED` when no recorded worktree contains the current directory, and with the working-directory service's error when the source checkout no longer exists. +`ctx.worktrees.enter(agent, { name }, signal?)` moves the Session into an existing worktree in the pool of the checkout it works in, through `ctx.workingDirectory.set`. `name` is the directory relative to that pool, the name `create` gave the worktree. The directory must resolve inside the pool and be a registered worktree of the repository; otherwise the call rejects with `WORKTREE_NOT_FOUND` and the Session stays where it is. Entry runs no Git command that writes, and resolves to the checkout's `path`, its `branch` unless HEAD is detached, and the `repositoryRoot` the Session entered from. + +`ctx.worktrees.exit(agent, signal?)` returns the Session from the recorded worktree that contains its current directory to that worktree's `repositoryRoot` through `ctx.workingDirectory.set`, and resolves to the record of the worktree it left: its creation when the log holds one, otherwise its entry. The record can be the Session's own or fork-inherited, and nested worktrees exit one level per call. The checkout and branch remain. The call rejects with `WORKTREE_NOT_ENTERED` when no recorded worktree contains the current directory, and with the working-directory service's error when the source checkout no longer exists. `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. -Every creation appends a `plugin:worktree/created` record to the Session log after the directory change, so the `worktree` projection lists the Session's checkouts with `owned` false for one inside a fork-inherited prefix. When the Workspace archives a Session, the service registers one `scheduled` cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While `retainOnArchive` is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the [Forge panel](../client-ui-forge/README.md) edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force `git worktree remove` under the creator's policy after a second use check inside the path lock, which also holds `ensure` and `set` into that path through `working-directory/access`; the branch and its commits remain. Tracked changes, untracked files, an initialized submodule (a repository in the checkout's administrative `modules` directory), locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout. Ignored files and edits to skip-worktree or assume-unchanged files do not: `git status` reports neither, and Git discards them with the checkout. A committed embedded repository is not inspected; Git refuses that removal, so the attempt settles as `failed`. Inspection stops reading `git status` at its first entry and streams the worktree listing, keeping its entries in memory while it looks for the checkout; neither output is bounded by `maxOutputBytes`. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. `cleanupOf(session, revision)` reads the attempt, or waits for a named revision to settle, as `scheduled`, `retained`, `removed`, or `failed`; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept. +Every creation appends a `plugin:worktree/created` record to the Session log after the directory change, so the `worktree` projection lists the Session's checkouts with `owned` false for one inside a fork-inherited prefix. Every entry appends a `plugin:worktree/entered` record, which only `exit` reads: archiving a Session never removes a checkout it only entered, and an entry does not retain a checkout the Session has left. When the Workspace archives a Session, the service registers one `scheduled` cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While `retainOnArchive` is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the [Forge panel](../client-ui-forge/README.md) edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force `git worktree remove` under the creator's policy after a second use check inside the path lock, which also holds `ensure` and `set` into that path through `working-directory/access`; the branch and its commits remain. Tracked changes, untracked files, an initialized submodule (a repository in the checkout's administrative `modules` directory), locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout. Ignored files and edits to skip-worktree or assume-unchanged files do not: `git status` reports neither, and Git discards them with the checkout. A committed embedded repository is not inspected; Git refuses that removal, so the attempt settles as `failed`. Inspection stops reading `git status` at its first entry and streams the worktree listing, keeping its entries in memory while it looks for the checkout; neither output is bounded by `maxOutputBytes`. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. `cleanupOf(session, revision)` reads the attempt, or waits for a named revision to settle, as `scheduled`, `retained`, `removed`, or `failed`; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept. -Expected failures throw `WorktreeError` with a stable `code`: `WORKTREE_INVALID_ARGUMENT` for a name Git or the pool rules reject, an empty start revision, or a restoration record that violates a documented constraint, while a start revision or base commit Git cannot resolve fails as `WORKTREE_COMMAND_FAILED`; `WORKTREE_ALREADY_EXISTS` for an existing branch or path; `WORKTREE_LOCKED` for a locked registration; `WORKTREE_NOT_ENTERED` for an exit while the Session's directory lies in no recorded worktree; `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, and `WORKTREE_TIMEOUT` for a command that exits unsuccessfully, exceeds `maxOutputBytes`, or exceeds `timeoutMs`; and `WORKTREE_UNAVAILABLE` after service disposal. A failure after directory allocation adds the retained-artifact context to its message and keeps the original error's `name` and `code`; caller cancellation stays an `AbortError`. +Expected failures throw `WorktreeError` with a stable `code`: `WORKTREE_INVALID_ARGUMENT` for a name Git or the pool rules reject, an empty start revision, or a restoration record that violates a documented constraint, while a start revision or base commit Git cannot resolve fails as `WORKTREE_COMMAND_FAILED`; `WORKTREE_ALREADY_EXISTS` for an existing branch or path; `WORKTREE_LOCKED` for a locked registration; `WORKTREE_NOT_FOUND` for an entry whose name selects no registered worktree in the pool; `WORKTREE_NOT_ENTERED` for an exit while the Session's directory lies in no recorded worktree; `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, and `WORKTREE_TIMEOUT` for a command that exits unsuccessfully, exceeds `maxOutputBytes`, or exceeds `timeoutMs`; and `WORKTREE_UNAVAILABLE` after service disposal. A failure after directory allocation adds the retained-artifact context to its message and keeps the original error's `name` and `code`; caller cancellation stays an `AbortError`. The default checkout directory is `/.agents/worktrees/`. 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. Each Git and Node command runs under its own `timeoutMs` deadline, 5 minutes by default, so checking out a large repository on a slow filesystem can finish; cancellation still stops the running command. Relative `directory`, generated `namePrefix`, executable choices, process limits, and `retainOnArchive` are configurable in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-worktree). @@ -90,6 +92,7 @@ This package contributes no prompt text. Its consumers own the appended tool res +- **Entry by pool name** — `enter` reaches only registered worktrees inside the configured pool of the checkout the Session works in. A worktree in another checkout's pool is entered from that checkout, and one outside every pool is not reachable. - **Retained artifacts** — leaving a worktree keeps its branch and files, and archive cleanup never deletes a branch. Setup failures can also retain partial artifacts, and a failed removal can leave a partial directory for the retained branch to be restored over. - **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail. - **Filtered representations** — checkout skips configured filters to avoid executing repository-configured programs or triggering implicit downloads. Git LFS pointers and encrypted blobs stay in their stored representation; hydration or decryption is a separate user-controlled operation. diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index fa7e6f7eb0..06fa17a3a8 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -1,5 +1,5 @@ --- -description: "按照调用 Session 的文件策略创建并进入保留的 Git 工作树。" +description: "按照调用 Session 的文件策略创建、进入并离开保留的 Git 工作树。" kind: "package-reference" --- @@ -34,13 +34,15 @@ 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.exit(agent, signal?)` 找到包含 Session 当前目录的已记录工作树,通过 `ctx.workingDirectory.set` 把 Session 送回该工作树的 `repositoryRoot`,并返回所离开工作树的记录。记录可以是 Session 自己的,也可以是 fork 继承的;嵌套的工作树每次调用退出一层。检出目录与分支保留。没有已记录的工作树包含当前目录时,调用以 `WORKTREE_NOT_ENTERED` 拒绝;源检出已不存在时,以工作目录服务的错误拒绝。 +`ctx.worktrees.enter(agent, { name }, signal?)` 通过 `ctx.workingDirectory.set` 把 Session 移入它所在检出的池中已有的工作树。`name` 是相对该池的目录,即 `create` 给工作树的名称。该目录必须解析到池内,并且是仓库已登记的工作树;否则调用以 `WORKTREE_NOT_FOUND` 拒绝,Session 留在原处。进入不执行任何会写入的 Git 命令,返回检出目录的 `path`、HEAD 未分离时的 `branch`,以及 Session 进入前所在的 `repositoryRoot`。 + +`ctx.worktrees.exit(agent, signal?)` 找到包含 Session 当前目录的已记录工作树,通过 `ctx.workingDirectory.set` 把 Session 送回该工作树的 `repositoryRoot`,并返回所离开工作树的记录:日志中有创建记录时返回创建记录,否则返回进入记录。记录可以是 Session 自己的,也可以是 fork 继承的;嵌套的工作树每次调用退出一层。检出目录与分支保留。没有已记录的工作树包含当前目录时,调用以 `WORKTREE_NOT_ENTERED` 拒绝;源检出已不存在时,以工作目录服务的错误拒绝。 `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它只通过 `git worktree remove` 移除缺失目标的未锁定登记;其他 worktree 与锁定登记保持不变。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。 -每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。`retainOnArchive` 开启时,归档不登记任何清理,所有检出目录都保留;该字段是 volatile 字段,每次归档时读取,[Forge 面板](../client-ui-forge/README.zh.md)在插件页该套件的 worktree 行上以开关编辑它。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、已初始化的子模块(仓库位于检出目录管理目录的 `modules` 中)、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录。被忽略的文件以及对 skip-worktree 或 assume-unchanged 文件的改动不会:`git status` 不报告这两类内容,Git 删除目录时一并丢弃它们。检查不识别已提交的内嵌仓库;Git 会拒绝这类删除,本次尝试以 `failed` 结束。检查读到 `git status` 的第一条记录即停止,并以流式读取工作树列表,查找该检出目录期间在内存中保留其条目;两者的输出都不受 `maxOutputBytes` 限制。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。 +每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。每次进入都会追加一条 `plugin:worktree/entered` 记录,只有 `exit` 读取它:归档 Session 从不移除它只是进入过的检出目录,进入记录也不会让 Session 已离开的检出目录保留下来。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。`retainOnArchive` 开启时,归档不登记任何清理,所有检出目录都保留;该字段是 volatile 字段,每次归档时读取,[Forge 面板](../client-ui-forge/README.zh.md)在插件页该套件的 worktree 行上以开关编辑它。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、已初始化的子模块(仓库位于检出目录管理目录的 `modules` 中)、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录。被忽略的文件以及对 skip-worktree 或 assume-unchanged 文件的改动不会:`git status` 不报告这两类内容,Git 删除目录时一并丢弃它们。检查不识别已提交的内嵌仓库;Git 会拒绝这类删除,本次尝试以 `failed` 结束。检查读到 `git status` 的第一条记录即停止,并以流式读取工作树列表,查找该检出目录期间在内存中保留其条目;两者的输出都不受 `maxOutputBytes` 限制。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。 -预期失败抛出 `WorktreeError`,其 `code` 为:名称被 Git 或池规则拒绝、起始修订为空或恢复记录违反文档约束时为 `WORKTREE_INVALID_ARGUMENT`,Git 无法解析的起始修订或基础提交则以 `WORKTREE_COMMAND_FAILED` 失败;分支或路径已存在时为 `WORKTREE_ALREADY_EXISTS`;登记被锁定时为 `WORKTREE_LOCKED`;Session 的目录不在任何已记录工作树内却调用退出时为 `WORKTREE_NOT_ENTERED`;命令以失败状态退出、超过 `maxOutputBytes` 或超过 `timeoutMs` 时分别为 `WORKTREE_COMMAND_FAILED`、`WORKTREE_OUTPUT_TOO_LARGE` 和 `WORKTREE_TIMEOUT`;服务释放后为 `WORKTREE_UNAVAILABLE`。目录分配之后的失败会在消息中加入保留产物的说明,并保留原错误的 `name` 与 `code`;调用方取消仍是 `AbortError`。 +预期失败抛出 `WorktreeError`,其 `code` 为:名称被 Git 或池规则拒绝、起始修订为空或恢复记录违反文档约束时为 `WORKTREE_INVALID_ARGUMENT`,Git 无法解析的起始修订或基础提交则以 `WORKTREE_COMMAND_FAILED` 失败;分支或路径已存在时为 `WORKTREE_ALREADY_EXISTS`;登记被锁定时为 `WORKTREE_LOCKED`;进入时名称在池中选不到已登记的工作树为 `WORKTREE_NOT_FOUND`;Session 的目录不在任何已记录工作树内却调用退出时为 `WORKTREE_NOT_ENTERED`;命令以失败状态退出、超过 `maxOutputBytes` 或超过 `timeoutMs` 时分别为 `WORKTREE_COMMAND_FAILED`、`WORKTREE_OUTPUT_TOO_LARGE` 和 `WORKTREE_TIMEOUT`;服务释放后为 `WORKTREE_UNAVAILABLE`。目录分配之后的失败会在消息中加入保留产物的说明,并保留原错误的 `name` 与 `code`;调用方取消仍是 `AbortError`。 默认检出目录是 `/.agents/worktrees/`。返回的 `repositoryRoot` 是调用方当前检出目录的顶层目录;如果它是链接检出目录,工作树父目录就嵌套在其中。省略名称时,名称由前缀 `dsh-`、Session id 中 UUID 的前 8 位十六进制数、一个连字符和 4 位随机十六进制数组成,例如 `dsh-6b1f02c4-9a3e`;Session id 不含 UUID 时,前缀后接 8 位随机十六进制数。`generatedWorktreeName` 导出同一规则,供在创建前确定名称的调用方使用。仅当服务的分配操作创建了父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`;已有文件与忽略规则保持不变。每条 Git 和 Node 命令各自受 `timeoutMs` 时限约束,默认 5 分钟,使大仓库在较慢的文件系统上也能完成检出;取消仍会终止正在运行的命令。相对路径 `directory`、生成名称使用的 `namePrefix`、可执行程序、进程限制与 `retainOnArchive` 可在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-worktree)中查阅。 @@ -90,6 +92,7 @@ Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调 +- **按池内名称进入**——`enter` 只能到达 Session 所在检出的配置池中已登记的工作树。位于另一个检出的池中的工作树要从那个检出进入,位于所有池之外的工作树无法到达。 - **保留的产物**——离开工作树时保留其分支和文件,归档清理也从不删除分支。安装失败同样可能保留部分产物;删除失败可能留下部分目录,可在保留的分支上恢复覆盖。 - **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。 - **过滤器处理前的内容**——检出时跳过已配置的过滤器,以避免执行仓库配置的程序或隐式下载。Git LFS 指针与加密 blob 保持存储时的形式;拉取实体内容或解密由用户另行执行。 diff --git a/packages/experimental/worktree/src/error.ts b/packages/experimental/worktree/src/error.ts index 1ab3ce3fad..14250671bf 100644 --- a/packages/experimental/worktree/src/error.ts +++ b/packages/experimental/worktree/src/error.ts @@ -1,4 +1,4 @@ -/** Machine-routable worktree creation, exit, and restoration failures. @module */ +/** Machine-routable worktree creation, entry, exit, and restoration failures. @module */ import { HarnessError } from '@deepseek-ai/dsh-error' @@ -8,6 +8,8 @@ import { HarnessError } from '@deepseek-ai/dsh-error' * constraint; correct it and retry. * - `WORKTREE_ALREADY_EXISTS` — the branch or checkout path already exists; choose another name or reuse the existing checkout. * - `WORKTREE_LOCKED` — Git keeps the missing checkout's registration locked; unlock it before restoring. + * - `WORKTREE_NOT_FOUND` — the pool of the checkout the Session works in holds no registered worktree of that name; + * create one, or list the repository's worktrees. * - `WORKTREE_NOT_ENTERED` — the Session's working directory lies in no worktree its log records, so there is none to exit. * - `WORKTREE_COMMAND_FAILED` — a Git or directory-allocation command exited unsuccessfully; the message carries its status and stderr. * - `WORKTREE_OUTPUT_TOO_LARGE` — a command's output exceeded the configured `maxOutputBytes`; raise the limit or inspect the repository. @@ -18,6 +20,7 @@ export const WORKTREE_ERROR_CODES = [ 'WORKTREE_INVALID_ARGUMENT', 'WORKTREE_ALREADY_EXISTS', 'WORKTREE_LOCKED', + 'WORKTREE_NOT_FOUND', 'WORKTREE_NOT_ENTERED', 'WORKTREE_COMMAND_FAILED', 'WORKTREE_OUTPUT_TOO_LARGE', diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index a5a7f5a2f4..0e2b12f5c4 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -1,6 +1,7 @@ /** - * Creates a new Git branch and checkout, then changes the calling Session's working directory; returns - * the Session to the source checkout; restores a removed checkout. + * Creates a new Git branch and checkout, then changes the calling Session's working directory; moves the + * Session into an existing checkout of the pool; returns the Session to the source checkout; restores a + * removed checkout. */ import { Context, Service, type Volatile } from '@deepseek-ai/cordis' @@ -22,16 +23,18 @@ import { PREPARE_DIRECTORY } from './directory.ts' import { generatedWorktreeName } from './name.ts' import { runCommand, scanCommand } from './process.ts' import type { ProcessConfig } from './process.ts' -import { CREATED_RECORD, worktreeProjection } from './projection.ts' +import { CREATED_RECORD, ENTERED_RECORD, worktreeProjection } from './projection.ts' import type { WorktreeProjectionState } from './projection.ts' import { checkoutIdentity, registration, removeCheckout } from './removal.ts' import type { GitScan } from './removal.ts' import type { - CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest, WorktreeCleanup, + CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, EnteredWorktree, EnterWorktreeRequest, RestoredWorktree, + RestoreWorktreeRequest, WorktreeCleanup, } from './types.ts' export type { - CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest, WorktreeCleanup, WorktreeCreation, + CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, EnteredWorktree, EnterWorktreeRequest, RestoredWorktree, + RestoreWorktreeRequest, WorktreeCleanup, WorktreeCreation, } from './types.ts' export { generatedWorktreeName } from './name.ts' export { CREATED_RECORD, createdWorktreeSchema, worktreeProjection } from './projection.ts' @@ -86,8 +89,9 @@ function relativePath(value: string): boolean { /** * Creates retained Git worktrees under the mounted filesystem and sandbox - * providers, records each creation in the Session log, and reclaims a clean, - * unreferenced checkout when the Session that created it is archived. + * providers, moves Sessions into and out of them, records each creation and + * entry in the Session log, and reclaims a clean, unreferenced checkout when + * the Session that created it is archived. */ export class WorktreeService extends Service { static inject = ['workingDirectory', 'fs', 'subprocess', 'sandbox', 'sandboxPolicy', 'sessionProjections'] @@ -215,9 +219,36 @@ export class WorktreeService extends Service { } /** - * Return the calling Session from the worktree it works in to the source checkout that worktree was - * created from. The worktree is the recorded creation, the Session's own or fork-inherited, with the - * longest directory containing the Session's current directory. Its checkout and branch remain. + * Move the calling Session into an existing worktree in the pool of the checkout it works in. The + * directory `name` selects must lie inside that pool and be a registered worktree of the repository; + * neither Git state nor files change. The Session's log records the entry, so {@link exit} returns it to + * the checkout it entered from. Archiving the Session never removes a checkout it only entered. + * @param agent - caller whose current directory selects the checkout and its pool. + * @param request - name of the worktree inside the pool. + * @param signal - cancellation of lookup and of the working-directory change. + * @returns the entered checkout, its branch, and the checkout the Session entered from. + * @throws {WorktreeError} `WORKTREE_INVALID_ARGUMENT` for a name that is not a relative path inside the pool, + * `WORKTREE_NOT_FOUND` when the pool holds no registered worktree of that name, a command failure, and + * `WORKTREE_UNAVAILABLE` after service disposal; or the working-directory service's error when the + * registered directory no longer exists. + */ + async enter(agent: Agent, request: EnterWorktreeRequest, signal?: AbortSignal): Promise { + const operationSignal = signal === undefined ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal]) + operationSignal.throwIfAborted() + const operation = this.enterCheckout(agent, request, operationSignal) + this.pending.add(operation) + try { + return await operation + } finally { + this.pending.delete(operation) + } + } + + /** + * Return the calling Session from the worktree it works in to the checkout it entered that worktree + * from: the source checkout of a creation, or the checkout whose pool holds an entered worktree. The + * worktree is the recorded creation or entry, the Session's own or fork-inherited, with the longest + * directory containing the Session's current directory. Its checkout and branch remain. * @param agent - caller whose current directory lies in a recorded worktree. * @param signal - cancellation of directory validation and of the working-directory change. * @returns the worktree the Session left; the Session now works in its `repositoryRoot`. @@ -225,12 +256,14 @@ export class WorktreeService extends Service { * `WORKTREE_UNAVAILABLE` after service disposal, or the working-directory service's error when the source * checkout no longer exists. */ - async exit(agent: Agent, signal?: AbortSignal): Promise { + async exit(agent: Agent, signal?: AbortSignal): Promise { const operationSignal = signal === undefined ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal]) operationSignal.throwIfAborted() const cwd = await this.ctx.workingDirectory.ensure(agent, operationSignal) - let left: CreatedWorktree | undefined - for (const { worktree } of this.projection.stateOf(agent.session).created) { + const state = this.projection.stateOf(agent.session) + let left: CreatedWorktree | EnteredWorktree | undefined + // Among records of one directory the last wins: a creation, which carries the base commit, over an entry. + for (const worktree of [...state.entered, ...state.created.map(creation => creation.worktree)]) { if (within(worktree.path, cwd) && (left === undefined || worktree.path.length >= left.path.length)) left = worktree } if (left === undefined) { @@ -322,6 +355,30 @@ export class WorktreeService extends Service { } } + private async enterCheckout(agent: Agent, { name }: EnterWorktreeRequest, signal: AbortSignal): Promise { + if (!relativePath(name)) throw new WorktreeError('worktree name must be a relative path inside the worktree pool', 'WORKTREE_INVALID_ARGUMENT') + const cwd = await this.ctx.workingDirectory.ensure(agent, signal) + const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) + const rootOutput = await this.gitRunner(policy, signal)(cwd, ['rev-parse', '--show-toplevel']) + const rootTarget = await this.ctx.fs.resolve(rootOutput.stdout.replace(/\r?\n$/, ''), { cwd, signal }) + const repositoryRoot = this.ctx.fs.processPath(rootTarget) + const pool = await this.ctx.fs.resolve(this.config.directory, { cwd: repositoryRoot, signal }) + const poolPath = this.ctx.fs.processPath(pool) + const target = await this.ctx.fs.resolve(name, { cwd: poolPath, signal }) + // A link that leaves the pool resolves outside it; only a directory inside the pool may become the workspace. + const fields = this.ctx.fs.contains(pool, target) + ? await registration(this.ctx, repositoryRoot, target, this.gitScanner(policy, signal), signal) + : undefined + if (fields === undefined) { + throw new WorktreeError(`cannot enter worktree ${JSON.stringify(name)}: ${poolPath} holds no registered worktree of that name`, 'WORKTREE_NOT_FOUND') + } + const branch = fields.find(field => field.startsWith('branch refs/heads/'))?.slice('branch refs/heads/'.length) + const path = await this.ctx.workingDirectory.set(agent, this.ctx.fs.processPath(target), signal) + const entered: EnteredWorktree = { path, ...branch === undefined ? {} : { branch }, repositoryRoot } + appendPluginRecord(agent.session, ENTERED_RECORD, entered) + return entered + } + private async restoreCheckout( agent: Agent, { path, branch, baseCommit, repositoryRoot }: RestoreWorktreeRequest, @@ -341,7 +398,7 @@ export class WorktreeService extends Service { await assertBranchName(run, repositoryRoot, branch, 'worktree branch') await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${baseCommit}^{commit}`]) const scan = this.gitScanner(policy, signal) - const fields = await registration(this.ctx, { path, branch, baseCommit, repositoryRoot }, identity.target, scan, signal) + const fields = await registration(this.ctx, repositoryRoot, identity.target, scan, signal) if (fields !== undefined) { if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new WorktreeError(`worktree is locked: ${path}`, 'WORKTREE_LOCKED') if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new WorktreeError(`worktree path already exists: ${path}`, 'WORKTREE_ALREADY_EXISTS') diff --git a/packages/experimental/worktree/src/projection.ts b/packages/experimental/worktree/src/projection.ts index 07329685b5..b603cf47fe 100644 --- a/packages/experimental/worktree/src/projection.ts +++ b/packages/experimental/worktree/src/projection.ts @@ -1,18 +1,26 @@ -/** The `worktree` projection: every checkout this service recorded creating for a Session, and which of them the Session created itself. */ +/** + * The `worktree` projection: every checkout this service recorded creating for a Session, which of them the + * Session created itself, and the existing checkouts it entered. + */ import { pluginRecordOf } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import { z } from 'zod' -import type { CreatedWorktree, WorktreeCreation } from './types.ts' +import type { CreatedWorktree, EnteredWorktree, WorktreeCreation } from './types.ts' /** Plugin record type of a checkout this service created for the Session, written after the Session entered it. */ export const CREATED_RECORD = 'plugin:worktree/created' +/** Plugin record type of an existing checkout the Session entered, written after the Session entered it. */ +export const ENTERED_RECORD = 'plugin:worktree/entered' + declare module '@deepseek-ai/dsh-session/types' { interface PluginRecordMap { /** A checkout the worktree service created for the Session, which entered it in the same operation. */ 'plugin:worktree/created': CreatedWorktree + /** An existing checkout the Session entered, and the checkout it entered from. */ + 'plugin:worktree/entered': EnteredWorktree } } @@ -23,9 +31,13 @@ declare module '@deepseek-ai/dsh-session-projection/types' { } } -/** Host state of the `worktree` unit: creations so far and the fork boundary that decides ownership. */ +/** + * Host state of the `worktree` unit: creations so far, the fork boundary that decides ownership, and the + * entered checkouts, one entry per directory. + */ export interface WorktreeProjectionState { readonly created: readonly WorktreeCreation[] + readonly entered: readonly EnteredWorktree[] readonly inheritedEventCount: number } @@ -37,6 +49,13 @@ export const createdWorktreeSchema: z.ZodType = z.object({ repositoryRoot: z.string().min(1), }).strict() +/** Validates a `plugin:worktree/entered` payload before the fold trusts it. */ +const enteredWorktreeSchema: z.ZodType = z.object({ + path: z.string().min(1), + branch: z.string().min(1).exactOptional(), + repositoryRoot: z.string().min(1), +}).strict() + const creationSchema: z.ZodType = z.object({ worktree: createdWorktreeSchema, owned: z.boolean(), @@ -44,23 +63,31 @@ const creationSchema: z.ZodType = z.object({ const stateSchema: z.ZodType = z.object({ created: z.array(creationSchema), + entered: z.array(enteredWorktreeSchema), inheritedEventCount: z.number().int().nonnegative(), }).strict() /** - * Fold `plugin:worktree/created` records; a record whose payload fails - * validation is skipped, as a restored record carries whatever an earlier - * build wrote. A creation whose seq lies inside the fork-inherited prefix is a - * reference the fork carries, not a checkout it created, so `owned` is false - * there and true for the Session's own records. + * Fold `plugin:worktree/created` and `plugin:worktree/entered` records; a + * record whose payload fails validation is skipped, as a restored record + * carries whatever an earlier build wrote. A creation whose seq lies inside + * the fork-inherited prefix is a reference the fork carries, not a checkout it + * created, so `owned` is false there and true for the Session's own records. + * A later entry of one directory replaces the earlier one, so the entered + * list grows with the directories entered, not with the entries. */ export const worktreeProjection = { key: 'worktree', - stateVersion: 1, + stateVersion: 2, stateSchema, - init: (_header, inheritedEventCount) => ({ created: [], inheritedEventCount }), + init: (_header, inheritedEventCount) => ({ created: [], entered: [], inheritedEventCount }), apply: (state, event: SessionEvent) => { const record = pluginRecordOf(event) + if (record?.type === ENTERED_RECORD) { + const parsed = enteredWorktreeSchema.safeParse(record.data) + if (!parsed.success) return state + return { ...state, entered: [...state.entered.filter(entered => entered.path !== parsed.data.path), parsed.data] } + } if (record?.type !== CREATED_RECORD) return state const parsed = createdWorktreeSchema.safeParse(record.data) if (!parsed.success) return state diff --git a/packages/experimental/worktree/src/removal.ts b/packages/experimental/worktree/src/removal.ts index 4681c0c708..9ff0fecfd8 100644 --- a/packages/experimental/worktree/src/removal.ts +++ b/packages/experimental/worktree/src/removal.ts @@ -58,19 +58,19 @@ export async function checkoutIdentity( * The listing grows with the number of worktrees; it is streamed without an * output limit, and its entries are kept in memory while `target` is resolved. * @param ctx - execution-world filesystem provider. - * @param request - saved checkout identity. + * @param repositoryRoot - a checkout of the repository whose worktrees are listed. * @param target - resolved checkout directory. * @param scan - streaming Git runner with the owner's policy. * @param signal - cancellation of the lookups. * @returns the porcelain fields of the matching entry, or undefined when none is registered. */ export async function registration( - ctx: Context, request: RestoreWorktreeRequest, target: CheckoutIdentity['target'], scan: GitScan, signal: AbortSignal, + ctx: Context, repositoryRoot: string, target: CheckoutIdentity['target'], scan: GitScan, signal: AbortSignal, ): Promise { const entries: { path: string; fields: string[] }[] = [] // Each entry of the -z porcelain listing starts with its worktree line and ends with an empty field. let fields: string[] = [] - await scan(request.repositoryRoot, ['worktree', 'list', '--porcelain', '-z'], (field) => { + await scan(repositoryRoot, ['worktree', 'list', '--porcelain', '-z'], (field) => { if (field.startsWith('worktree ')) { fields = [field] entries.push({ path: field.slice('worktree '.length), fields }) @@ -78,7 +78,7 @@ export async function registration( return true }) for (const entry of entries) { - const recorded = await ctx.fs.resolve(entry.path, { cwd: request.repositoryRoot, signal }) + const recorded = await ctx.fs.resolve(entry.path, { cwd: repositoryRoot, signal }) if (recorded.targetKey === target.targetKey) return entry.fields } return undefined @@ -128,7 +128,7 @@ export async function inspectRemoval( const identity = await checkoutIdentity(ctx, directory, request, git.read, signal) if (identity === null) return false if ((await ctx.fs.lstat(path, undefined, signal))?.type !== 'directory') return false - const fields = await registration(ctx, request, identity.target, git.scan, signal) + const fields = await registration(ctx, request.repositoryRoot, identity.target, git.scan, signal) // The primary registration is excluded even when the configured pool contains it. if (fields === undefined || !fields.includes(`branch refs/heads/${branch}`) || fields.some(field => field === 'detached' || field.startsWith('locked') || field.startsWith('prunable'))) return false diff --git a/packages/experimental/worktree/src/types.ts b/packages/experimental/worktree/src/types.ts index da85333e13..e8a4515d5c 100644 --- a/packages/experimental/worktree/src/types.ts +++ b/packages/experimental/worktree/src/types.ts @@ -1,4 +1,7 @@ -/** Public requests and results for creating a Git worktree and entering it, and for restoring a removed one. */ +/** + * Public requests and results for creating a Git worktree and entering it, for entering an existing one, and + * for restoring a removed one. + */ /** A new checkout from a locally available Git commit, branch, or tag. */ export interface CreateWorktreeRequest { @@ -20,6 +23,22 @@ export interface CreatedWorktree { repositoryRoot: string } +/** An existing checkout in the worktree pool of the checkout the calling Session works in. */ +export interface EnterWorktreeRequest { + /** Checkout directory relative to the pool: the name `create` gave the worktree. */ + name: string +} + +/** An existing checkout the calling Session entered. */ +export interface EnteredWorktree { + /** Canonical absolute checkout directory in the filesystem provider's execution world. */ + path: string + /** Branch checked out there at entry; absent on a detached HEAD. */ + branch?: string + /** Canonical root of the checkout whose pool holds the worktree; `exit` returns the Session there. */ + repositoryRoot: string +} + /** * Stage of one creation or restoration, reported before it begins: `prepare` * validates the request, allocates the checkout directory, and creates the diff --git a/packages/experimental/worktree/tests/archive.spec.ts b/packages/experimental/worktree/tests/archive.spec.ts index 680527e712..b6599ddb59 100644 --- a/packages/experimental/worktree/tests/archive.spec.ts +++ b/packages/experimental/worktree/tests/archive.spec.ts @@ -23,6 +23,7 @@ import WorkspaceRegistry from '@deepseek-ai/dsh-workspace' import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts' import type {} from '../src/archive.ts' import WorktreeService, { CREATED_RECORD, worktreeProjection } from '../src/index.ts' +import { ENTERED_RECORD } from '../src/projection.ts' import type { WorktreeCleanup } from '../src/index.ts' import * as removal from '../src/removal.ts' import { git, repository, UnusedSandbox } from './harness.ts' @@ -456,6 +457,23 @@ describe('archive-triggered worktree cleanup', () => { expect(handle.stateOf(f.session).created).toEqual(before) }) + it('keeps one entry per entered directory, skips an entry record whose payload fails validation, and reclaims only creations', async () => { + const f = await fixture() + const handle = await f.ctx.sessionProjections.register(worktreeProjection) + const visitor = f.ctx.sessions.create(brandString('visitor'), { meta: { cwd: f.root } }) + appendPluginRecord(visitor, ENTERED_RECORD, { path: f.worktree.path, branch: 'first', repositoryRoot: f.root }) + appendPluginRecord(visitor, ENTERED_RECORD, { path: f.worktree.path, repositoryRoot: f.root }) + const state = handle.stateOf(visitor) + expect(state).toMatchObject({ created: [], entered: [{ path: f.worktree.path, repositoryRoot: f.root }] }) + appendPluginRecord(visitor, ENTERED_RECORD, { path: '', repositoryRoot: f.root }) + expect(handle.stateOf(visitor)).toBe(state) + expect(f.ctx.sessionProjections.snapshot(visitor).values.worktree).toEqual([]) + + await f.ctx.workspaceRegistry.archiveSession(visitor.id) + expect(await f.ctx.worktrees.cleanupOf(visitor, null)).toBeNull() + await access(f.worktree.path) + }) + it('registers no attempt while retainOnArchive is set, and resumes once it is cleared', async () => { const f = await fixture({ retainOnArchive: true }) await f.ctx.workspaceRegistry.archiveSession(f.session.id) diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index 0a46915890..0a1974c095 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -91,6 +91,114 @@ describe('creating and entering retained worktrees', () => { expect(ctx.workingDirectory.get(agent.session)).toBe(root) }) + it('enters an existing worktree of the pool by name, records the entry, and exits to the checkout it entered from', async () => { + const root = await repo() + ctx = await harness(root) + const agent = testAgent(ctx, root) + const path = join(root, '.agents/worktrees/other') + await git(root, 'worktree', 'add', '-b', 'other', path) + await writeFile(join(path, 'local.txt'), 'kept\n') + const before = await git(root, 'worktree', 'list', '--porcelain') + + const entered = await ctx.worktrees.enter(agent, { name: 'other' }, new AbortController().signal) + expect(entered).toEqual({ path, branch: 'other', repositoryRoot: root }) + expect(ctx.workingDirectory.get(agent.session)).toBe(path) + expect(ctx.workingDirectory.rootOf(agent.session)).toBe(path) + const events = agent.session.snapshotEvents() + const record = events.findIndex(event => pluginRecordOf(event)?.type === 'plugin:worktree/entered') + expect(record).toBeGreaterThan(events.findIndex(event => event.type === 'workspace-root/change')) + expect(pluginRecordOf(events[record]!)?.data).toEqual(entered) + expect(events.some(event => pluginRecordOf(event)?.type === 'plugin:worktree/created')).toBe(false) + expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before) + expect(await contents(join(path, 'local.txt'))).toBe('kept\n') + + await expect(ctx.worktrees.exit(agent)).resolves.toEqual(entered) + expect(ctx.workingDirectory.get(agent.session)).toBe(root) + await expect(ctx.worktrees.exit(agent)).rejects.toMatchObject({ code: 'WORKTREE_NOT_ENTERED' }) + }) + + it('enters a worktree again after leaving it, reporting its creation on exit, and lets another Session enter it', async () => { + const root = await repo() + ctx = await harness(root) + const agent = testAgent(ctx, root) + const created = await ctx.worktrees.create(agent, { name: 'topic' }) + await ctx.worktrees.exit(agent) + const entered = { path: created.path, branch: 'topic', repositoryRoot: root } + await expect(ctx.worktrees.enter(agent, { name: 'topic' })).resolves.toEqual(entered) + await expect(ctx.worktrees.enter(agent, { name: 'topic' })).rejects.toMatchObject({ code: 'WORKTREE_NOT_FOUND' }) + expect(ctx.workingDirectory.get(agent.session)).toBe(created.path) + await expect(ctx.worktrees.exit(agent)).resolves.toEqual(created) + + const other = testAgent(ctx, root, 'second-session') + await ctx.worktrees.enter(other, { name: 'topic' }) + await ctx.worktrees.exit(other) + await ctx.worktrees.enter(other, { name: 'topic' }) + expect(other.session.snapshotEvents().filter(event => pluginRecordOf(event)?.type === 'plugin:worktree/entered')).toHaveLength(2) + await expect(ctx.worktrees.exit(other)).resolves.toEqual(entered) + expect(ctx.workingDirectory.get(other.session)).toBe(root) + }) + + it('enters a detached worktree without a branch, and a nested worktree only from the checkout that holds it', async () => { + const root = await repo() + ctx = await harness(root) + const agent = testAgent(ctx, root) + const detached = join(root, '.agents/worktrees/detached') + await git(root, 'worktree', 'add', '--detach', detached) + const entered = await ctx.worktrees.enter(agent, { name: 'detached' }) + expect(entered).toEqual({ path: detached, repositoryRoot: root }) + expect(entered).not.toHaveProperty('branch') + await ctx.worktrees.exit(agent) + + const outer = await ctx.worktrees.create(agent, { name: 'outer' }) + const inner = await ctx.worktrees.create(agent, { name: 'inner' }) + await ctx.worktrees.exit(agent) + await expect(ctx.worktrees.enter(agent, { name: 'outer' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_NOT_FOUND', + message: `cannot enter worktree "outer": ${join(outer.path, '.agents/worktrees')} holds no registered worktree of that name`, + }) + await expect(ctx.worktrees.enter(agent, { name: 'inner' })).resolves.toEqual({ path: inner.path, branch: 'inner', repositoryRoot: outer.path }) + await expect(ctx.worktrees.exit(agent)).resolves.toEqual(inner) + expect(ctx.workingDirectory.get(agent.session)).toBe(outer.path) + }) + + it('refuses a name outside the pool, an unregistered directory, and a link that leaves the pool, without moving', async () => { + const root = await repo() + ctx = await harness(root) + const agent = testAgent(ctx, root) + const pool = join(root, '.agents/worktrees') + await mkdir(join(pool, 'plain'), { recursive: true }) + const outside = join(root, 'elsewhere') + await git(root, 'worktree', 'add', '-b', 'elsewhere', outside) + await symlink(outside, join(pool, 'redirect'), 'junction') + + for (const name of ['', '.', '..', '../elsewhere', 'plain/../redirect', '/elsewhere', 'a\\b', 'c:d']) { + await expect(ctx.worktrees.enter(agent, { name })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_INVALID_ARGUMENT', message: 'worktree name must be a relative path inside the worktree pool', + }) + } + for (const name of ['missing', 'plain', 'redirect']) { + await expect(ctx.worktrees.enter(agent, { name })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_NOT_FOUND', + message: `cannot enter worktree ${JSON.stringify(name)}: ${pool} holds no registered worktree of that name`, + }) + } + expect(ctx.workingDirectory.get(agent.session)).toBe(root) + expect(agent.session.snapshotEvents().some(event => event.type === 'workspace-root/change' || pluginRecordOf(event) !== undefined)).toBe(false) + }) + + it('rejects an entry cancelled before it starts, and every entry after service disposal, without changing the directory', async () => { + const root = await repo() + ctx = await harness(root) + const agent = testAgent(ctx, root) + await git(root, 'worktree', 'add', '-b', 'other', join(root, '.agents/worktrees/other')) + await expect(ctx.worktrees.enter(agent, { name: 'other' }, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left') + expect(ctx.workingDirectory.get(agent.session)).toBe(root) + const worktrees = ctx.worktrees + await ctx.fiber.dispose() + ctx = undefined + await expect(worktrees.enter(agent, { name: 'other' })).rejects.toMatchObject({ name: 'WorktreeError', code: 'WORKTREE_UNAVAILABLE', message: 'worktree service disposed' }) + }) + it('rejects an exit cancelled before it starts, and every exit after service disposal, without changing the directory', async () => { const root = await repo() ctx = await harness(root) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index b8728b8ba6..91b25a675a 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -5044,8 +5044,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { key: 'worktrees', - summary: 'Creates retained Git worktrees under the mounted filesystem and sandbox providers, records each creation in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived.', - description: 'Creates retained Git worktrees under the mounted filesystem and sandbox providers, records each creation in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived.', + summary: 'Creates retained Git worktrees under the mounted filesystem and sandbox providers, moves Sessions into and out of them, records each creation and entry in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived.', + description: 'Creates retained Git worktrees under the mounted filesystem and sandbox providers, moves Sessions into and out of them, records each creation and entry in the Session log, and reclaims a clean, unreferenced checkout when the Session that created it is archived.', methods: [ { signature: 'async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise', @@ -5062,8 +5062,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['{WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], }, { - signature: 'async exit(agent: Agent, signal?: AbortSignal): Promise', - description: 'Return the calling Session from the worktree it works in to the source checkout that worktree was created from. The worktree is the recorded creation, the Session\'s own or fork-inherited, with the longest directory containing the Session\'s current directory. Its checkout and branch remain.', + signature: 'async enter(agent: Agent, request: EnterWorktreeRequest, signal?: AbortSignal): Promise', + description: 'Move the calling Session into an existing worktree in the pool of the checkout it works in. The directory `name` selects must lie inside that pool and be a registered worktree of the repository; neither Git state nor files change. The Session\'s log records the entry, so exit returns it to the checkout it entered from. Archiving the Session never removes a checkout it only entered.', + parameters: [{ name: 'agent', description: 'caller whose current directory selects the checkout and its pool.' }, { name: 'request', description: 'name of the worktree inside the pool.' }, { name: 'signal', description: 'cancellation of lookup and of the working-directory change.' }], + returns: 'the entered checkout, its branch, and the checkout the Session entered from.', + throws: ['{WorktreeError} `WORKTREE_INVALID_ARGUMENT` for a name that is not a relative path inside the pool, `WORKTREE_NOT_FOUND` when the pool holds no registered worktree of that name, a command failure, and `WORKTREE_UNAVAILABLE` after service disposal; or the working-directory service\'s error when the registered directory no longer exists.'], + }, + { + signature: 'async exit(agent: Agent, signal?: AbortSignal): Promise', + description: 'Return the calling Session from the worktree it works in to the checkout it entered that worktree from: the source checkout of a creation, or the checkout whose pool holds an entered worktree. The worktree is the recorded creation or entry, the Session\'s own or fork-inherited, with the longest directory containing the Session\'s current directory. Its checkout and branch remain.', parameters: [{ name: 'agent', description: 'caller whose current directory lies in a recorded worktree.' }, { name: 'signal', description: 'cancellation of directory validation and of the working-directory change.' }], returns: 'the worktree the Session left; the Session now works in its `repositoryRoot`.', throws: ['{WorktreeError} `WORKTREE_NOT_ENTERED` when no recorded worktree contains the current directory and `WORKTREE_UNAVAILABLE` after service disposal, or the working-directory service\'s error when the source checkout no longer exists.'], @@ -6844,6 +6851,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'EncodedImageAttachment', declaration: 'export interface EncodedImageAttachment {\n mediaType: ImageMediaType;\n data: string;\n name?: string;\n}', }, + { + name: 'EnteredWorktree', + declaration: 'export interface EnteredWorktree {\n path: string;\n branch?: string;\n repositoryRoot: string;\n}', + }, + { + name: 'EnterWorktreeRequest', + declaration: 'export interface EnterWorktreeRequest {\n name: string;\n}', + }, { name: 'EpochHeader', declaration: 'export interface EpochHeader {\n config: LlmCallConfig;\n adapterDefaults?: LlmCallConfigAdapterDefaults;\n tools?: ToolSchema[];\n system?: never;\n}', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 6e429ca382..8bef651a6e 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -422,6 +422,8 @@ export const LINK_MAP: Readonly> = { CreateWorktreeRequest: 'worktrees.md', CreatedWorktree: 'worktrees.md', CreateWorktreePhase: 'worktrees.md', + EnterWorktreeRequest: 'worktrees.md', + EnteredWorktree: 'worktrees.md', RestoreWorktreeRequest: 'worktrees.md', WorktreeCleanup: 'worktrees.md', WorktreeCreation: 'worktrees.md', diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 022b173cff..8fe18579a6 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -705,11 +705,12 @@ const TOOL_PACKAGES: ToolPackage[] = [ async mount(ctx) { ctx.provide('worktrees', { create: () => Promise.reject(new Error('gen-tool-catalog: worktree creation is unavailable during schema harvest')), + enter: () => Promise.reject(new Error('gen-tool-catalog: entering a worktree is unavailable during schema harvest')), exit: () => Promise.reject(new Error('gen-tool-catalog: leaving a worktree is unavailable during schema harvest')), }) await ctx.plugin(ToolWorktree) }, - note: 'Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. `exit_worktree` returns the Session to the source checkout; the branch and checkout remain.', + note: 'Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. `enter_worktree` moves the Session into an existing worktree in the pool of the checkout it works in; `exit_worktree` returns the Session to the checkout it came from; the branch and checkout remain.', }, { pkg: '@deepseek-ai/dsh-tool-workflow', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index e3e15b1cc4..1539f044f8 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2648,6 +2648,16 @@ "symbol": "CreateWorktreePhase", "source": "packages/experimental/worktree/src/types.ts" }, + { + "doc": "docs/subsystems/worktrees.md", + "symbol": "EnterWorktreeRequest", + "source": "packages/experimental/worktree/src/types.ts" + }, + { + "doc": "docs/subsystems/worktrees.md", + "symbol": "EnteredWorktree", + "source": "packages/experimental/worktree/src/types.ts" + }, { "doc": "docs/subsystems/worktrees.md", "symbol": "RestoreWorktreeRequest", diff --git a/snapshots/session/headless.snapshot.ts b/snapshots/session/headless.snapshot.ts index 5d3bc8f7cb..7273793ebf 100644 --- a/snapshots/session/headless.snapshot.ts +++ b/snapshots/session/headless.snapshot.ts @@ -916,12 +916,15 @@ async function verifyWorktree(log: string, cwd: string): Promise { expect(snapshotGit(cwd, ['rev-parse', '--verify', 'refs/heads/doomed'])).toBe(snapshotGit(cwd, ['rev-parse', 'HEAD'])) const events = records(log) expect(events.filter(event => event.type === 'workspace-root/change').map(event => event.data)) - .toEqual([checkout, cwd, removed, cwd].map(directory => ({ cwd: directory }))) + .toEqual([checkout, cwd, checkout, cwd, removed, cwd].map(directory => ({ cwd: directory }))) expect(events.filter(event => event.type === 'system/message')).toHaveLength(1) const notices = events.filter(event => event.type === 'user/message').map(event => event.data as JsonObject) .filter(message => (message.source as JsonObject).kind === 'working-directory') .map(message => (message.content as JsonObject[]).map(block => block.text).join('')) expect(notices).toEqual([ + `The working directory changed from ${JSON.stringify(cwd)} to ${JSON.stringify(checkout)}.`, + `The working directory changed from ${JSON.stringify(checkout)} to ${JSON.stringify(cwd)}.`, + // enter_worktree returns the Session to the first worktree, and exit_worktree leaves it again. `The working directory changed from ${JSON.stringify(cwd)} to ${JSON.stringify(checkout)}.`, `The working directory changed from ${JSON.stringify(checkout)} to ${JSON.stringify(cwd)}.`, `The working directory changed from ${JSON.stringify(cwd)} to ${JSON.stringify(removed)}.`, diff --git a/snapshots/session/worktree/session.v4.jsonl b/snapshots/session/worktree/session.v4.jsonl index 64d1aa5aa6..67c95b6df9 100644 --- a/snapshots/session/worktree/session.v4.jsonl +++ b/snapshots/session/worktree/session.v4.jsonl @@ -2,12 +2,12 @@ {"type":"permission/preset","data":{"preset":"danger-full-access"}} {"type":"sandbox/mode","data":{"mode":"danger-full-access"}} {"type":"approval/policy","data":{"policy":"never"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Create a worktree named isolated from HEAD, read tracked.txt, write result.txt containing exactly \"WORKTREE RESULT\\n\", leave it with exit_worktree, read tracked.txt, run git status --porcelain=v1, and print the current directory with pwd. Then create a worktree named doomed, remove it from the source checkout with git worktree remove --force, and read tracked.txt again. Reply exactly WORKTREE_OK."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Create a worktree named isolated from HEAD, read tracked.txt, write result.txt containing exactly \"WORKTREE RESULT\\n\", leave it with exit_worktree, read tracked.txt, run git status --porcelain=v1, and print the current directory with pwd. Enter the isolated worktree again with enter_worktree, read result.txt, and leave it with exit_worktree. Then create a worktree named doomed, remove it from the source checkout with git worktree remove --force, and read tracked.txt again. Reply exactly WORKTREE_OK."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Create a worktree named isolated from HEAD, read tracked.txt, write result.txt containing exactly \"WORKTREE RESULT\\n\", leave it with exit_worktree, read tracked.txt, run git status --porcelain=v1, and print the current directory with pwd. Then create a worktree named doomed, remove it from the source checkout with git worktree remove --force, and read tracked.txt again. Reply exactly WORKTREE_OK."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Create a worktree named isolated from HEAD, read tracked.txt, write result.txt containing exactly \"WORKTREE RESULT\\n\", leave it with exit_worktree, read tracked.txt, run git status --porcelain=v1, and print the current directory with pwd. Enter the isolated worktree again with enter_worktree, read result.txt, and leave it with exit_worktree. Then create a worktree named doomed, remove it from the source checkout with git worktree remove --force, and read tracked.txt again. Reply exactly WORKTREE_OK."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}} @@ -62,34 +62,60 @@ {"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-7"},"toolCallId":"worktree-7","content":[{"type":"text","text":"{{cwd}}\n"}],"isError":false,"id":"{{message:21}}"},"meta":{"cwd":"{{cwd}}"}},"sourceEventSeqs":[57],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} {"type":"step/start","data":{"turn":1,"step":8}} -{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-8","name":"create_worktree","arguments":"{\"name\":\"doomed\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:22}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794389455873,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794389455873,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-8","name":"create_worktree","arguments":"{\"name\":\"doomed\"}"}}},{"type":"chunk","time":1794389455873,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794389455873,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":8,"callId":"worktree-8","name":"create_worktree","arguments":"{\"name\":\"doomed\"}"}} -{"type":"workspace-root/change","data":{"cwd":"{{cwd}}/.agents/worktrees/doomed"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/doomed\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:23}}"}]}} -{"type":"plugin:worktree/created","data":{"path":"{{cwd}}/.agents/worktrees/doomed","branch":"doomed","baseCommit":"86e2ed339bd583c54e29aaf0698fb8fb176ddcbb","repositoryRoot":"{{cwd}}"},"ignorable":true} -{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-8"},"toolCallId":"worktree-8","content":[{"type":"text","text":"{\"path\":\"{{cwd}}/.agents/worktrees/doomed\",\"branch\":\"doomed\",\"baseCommit\":\"86e2ed339bd583c54e29aaf0698fb8fb176ddcbb\",\"repositoryRoot\":\"{{cwd}}\"}"}],"isError":false,"id":"{{message:24}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-8","name":"enter_worktree","arguments":"{\"name\":\"isolated\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:22}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794564229503,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794564229503,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-8","name":"enter_worktree","arguments":"{\"name\":\"isolated\"}"}}},{"type":"chunk","time":1794564229503,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794564229503,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":8,"callId":"worktree-8","name":"enter_worktree","arguments":"{\"name\":\"isolated\"}"}} +{"type":"workspace-root/change","data":{"cwd":"{{cwd}}/.agents/worktrees/isolated"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/isolated\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:23}}"}]}} +{"type":"plugin:worktree/entered","data":{"path":"{{cwd}}/.agents/worktrees/isolated","branch":"isolated","repositoryRoot":"{{cwd}}"},"ignorable":true} +{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-8"},"toolCallId":"worktree-8","content":[{"type":"text","text":"{\"path\":\"{{cwd}}/.agents/worktrees/isolated\",\"branch\":\"isolated\",\"repositoryRoot\":\"{{cwd}}\"}"}],"isError":false,"id":"{{message:24}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":8}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":9}} -{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/doomed\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:23}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}/.agents/worktrees/doomed\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/.agents/worktrees/doomed\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:25}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-9","name":"bash","arguments":"{\"command\":\"cd ../../.. && git worktree remove --force .agents/worktrees/doomed\",\"description\":\"Remove the worktree this session works in\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:26}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794389456056,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794389456056,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-9","name":"bash","arguments":"{\"command\":\"cd ../../.. && git worktree remove --force .agents/worktrees/doomed\",\"description\":\"Remove the worktree this session works in\"}"}}},{"type":"chunk","time":1794389456056,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794389456056,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":9,"callId":"worktree-9","name":"bash","arguments":"{\"command\":\"cd ../../.. && git worktree remove --force .agents/worktrees/doomed\",\"description\":\"Remove the worktree this session works in\"}"}} -{"type":"job/registered","data":{"jobId":"{{id:3}}","owner":"{{session:1}}","kind":"bash","label":"cd ../../.. && git worktree remove --force .agents/worktrees/doomed","startedAt":1794389456063,"toolCall":{"callId":"worktree-9","rootCallId":"worktree-9"}}} -{"type":"job/settled","data":{"jobId":"{{id:3}}","owner":"{{session:1}}","kind":"bash","label":"cd ../../.. && git worktree remove --force .agents/worktrees/doomed","startedAt":1794389456063,"toolCall":{"callId":"worktree-9","rootCallId":"worktree-9"},"finishedAt":1794389456240,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} -{"type":"tool/result","data":{"turn":1,"step":9,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-9"},"toolCallId":"worktree-9","content":[{"type":"text","text":"(no output)"}],"isError":false,"id":"{{message:27}}"},"meta":{"cwd":"{{cwd}}/.agents/worktrees/doomed"}},"sourceEventSeqs":[75],"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/isolated\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:23}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}/.agents/worktrees/isolated\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/.agents/worktrees/isolated\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:25}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-9","name":"read","arguments":"{\"file_path\":\"result.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:26}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794564229559,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794564229559,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-9","name":"read","arguments":"{\"file_path\":\"result.txt\"}"}}},{"type":"chunk","time":1794564229559,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794564229559,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":9,"callId":"worktree-9","name":"read","arguments":"{\"file_path\":\"result.txt\"}"}} +{"type":"tool/result","data":{"turn":1,"step":9,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-9"},"toolCallId":"worktree-9","content":[{"type":"text","text":"{{cwd}}/.agents/worktrees/isolated/result.txt\nfile\n\n1: WORKTREE RESULT\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:27}}"},"meta":{"path":"{{cwd}}/.agents/worktrees/isolated/result.txt","offset":1,"lines":[{"number":1,"text":"WORKTREE RESULT"}],"totalLines":1}},"sourceEventSeqs":[75],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":9}} -{"type":"workspace-root/change","data":{"cwd":"{{cwd}}"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory \"{{cwd}}/.agents/worktrees/doomed\" is unavailable. The working directory is now \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:28}}"}]}} {"type":"step/start","data":{"turn":1,"step":10}} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:29}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-10","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:30}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794389456254,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794389456255,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-10","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}}},{"type":"chunk","time":1794389456255,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794389456255,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":10,"callId":"worktree-10","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}} -{"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-10"},"toolCallId":"worktree-10","content":[{"type":"text","text":"{{cwd}}/tracked.txt\nfile\n\n1: DIRTY SOURCE\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:31}}"},"meta":{"path":"{{cwd}}/tracked.txt","offset":1,"lines":[{"number":1,"text":"DIRTY SOURCE"}],"totalLines":1}},"sourceEventSeqs":[85],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-10","name":"exit_worktree","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:28}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794564229587,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794564229587,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-10","name":"exit_worktree","arguments":"{}"}}},{"type":"chunk","time":1794564229587,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794564229587,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":10,"callId":"worktree-10","name":"exit_worktree","arguments":"{}"}} +{"type":"workspace-root/change","data":{"cwd":"{{cwd}}"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/.agents/worktrees/isolated\" to \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:29}}"}]}} +{"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-10"},"toolCallId":"worktree-10","content":[{"type":"text","text":"{\"path\":\"{{cwd}}/.agents/worktrees/isolated\",\"branch\":\"isolated\",\"baseCommit\":\"86e2ed339bd583c54e29aaf0698fb8fb176ddcbb\",\"repositoryRoot\":\"{{cwd}}\"}"}],"isError":false,"id":"{{message:30}}"}},"sourceEventSeqs":[80],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":10}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":11}} -{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory \"{{cwd}}/.agents/worktrees/doomed\" is unavailable. The working directory is now \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:28}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"text","text":"WORKTREE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:32}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794389456273,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794389456273,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKTREE_OK"}}},{"type":"chunk","time":1794389456273,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794389456273,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/.agents/worktrees/isolated\" to \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:29}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:31}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-11","name":"create_worktree","arguments":"{\"name\":\"doomed\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:32}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794564229610,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794564229610,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-11","name":"create_worktree","arguments":"{\"name\":\"doomed\"}"}}},{"type":"chunk","time":1794564229610,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794564229610,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":11,"callId":"worktree-11","name":"create_worktree","arguments":"{\"name\":\"doomed\"}"}} +{"type":"workspace-root/change","data":{"cwd":"{{cwd}}/.agents/worktrees/doomed"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/doomed\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:33}}"}]}} +{"type":"plugin:worktree/created","data":{"path":"{{cwd}}/.agents/worktrees/doomed","branch":"doomed","baseCommit":"86e2ed339bd583c54e29aaf0698fb8fb176ddcbb","repositoryRoot":"{{cwd}}"},"ignorable":true} +{"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-11"},"toolCallId":"worktree-11","content":[{"type":"text","text":"{\"path\":\"{{cwd}}/.agents/worktrees/doomed\",\"branch\":\"doomed\",\"baseCommit\":\"86e2ed339bd583c54e29aaf0698fb8fb176ddcbb\",\"repositoryRoot\":\"{{cwd}}\"}"}],"isError":false,"id":"{{message:34}}"}},"sourceEventSeqs":[90],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":11}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":12}} +{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/doomed\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:33}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}/.agents/worktrees/doomed\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/.agents/worktrees/doomed\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:35}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-12","name":"bash","arguments":"{\"command\":\"cd ../../.. && git worktree remove --force .agents/worktrees/doomed\",\"description\":\"Remove the worktree this session works in\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:36}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794564229759,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794564229759,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-12","name":"bash","arguments":"{\"command\":\"cd ../../.. && git worktree remove --force .agents/worktrees/doomed\",\"description\":\"Remove the worktree this session works in\"}"}}},{"type":"chunk","time":1794564229759,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794564229759,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":12,"callId":"worktree-12","name":"bash","arguments":"{\"command\":\"cd ../../.. && git worktree remove --force .agents/worktrees/doomed\",\"description\":\"Remove the worktree this session works in\"}"}} +{"type":"job/registered","data":{"jobId":"{{id:3}}","owner":"{{session:1}}","kind":"bash","label":"cd ../../.. && git worktree remove --force .agents/worktrees/doomed","startedAt":1794564229772,"toolCall":{"callId":"worktree-12","rootCallId":"worktree-12"}}} +{"type":"job/settled","data":{"jobId":"{{id:3}}","owner":"{{session:1}}","kind":"bash","label":"cd ../../.. && git worktree remove --force .agents/worktrees/doomed","startedAt":1794564229772,"toolCall":{"callId":"worktree-12","rootCallId":"worktree-12"},"finishedAt":1794564229857,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} +{"type":"tool/result","data":{"turn":1,"step":12,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-12"},"toolCallId":"worktree-12","content":[{"type":"text","text":"(no output)"}],"isError":false,"id":"{{message:37}}"},"meta":{"cwd":"{{cwd}}/.agents/worktrees/doomed"}},"sourceEventSeqs":[101],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":12}} +{"type":"workspace-root/change","data":{"cwd":"{{cwd}}"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory \"{{cwd}}/.agents/worktrees/doomed\" is unavailable. The working directory is now \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:38}}"}]}} +{"type":"step/start","data":{"turn":1,"step":13}} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:39}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-13","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:40}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794564229882,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794564229882,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-13","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}}},{"type":"chunk","time":1794564229882,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794564229882,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":13,"callId":"worktree-13","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}} +{"type":"tool/result","data":{"turn":1,"step":13,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-13"},"toolCallId":"worktree-13","content":[{"type":"text","text":"{{cwd}}/tracked.txt\nfile\n\n1: DIRTY SOURCE\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:41}}"},"meta":{"path":"{{cwd}}/tracked.txt","offset":1,"lines":[{"number":1,"text":"DIRTY SOURCE"}],"totalLines":1}},"sourceEventSeqs":[111],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":13}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":14}} +{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory \"{{cwd}}/.agents/worktrees/doomed\" is unavailable. The working directory is now \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:38}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"text","text":"WORKTREE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:42}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794564229905,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794564229905,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKTREE_OK"}}},{"type":"chunk","time":1794564229905,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794564229905,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":14}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/worktree/tool-schemas.expected.json b/snapshots/session/worktree/tool-schemas.expected.json index 99113e0bbe..77defbcf50 100644 --- a/snapshots/session/worktree/tool-schemas.expected.json +++ b/snapshots/session/worktree/tool-schemas.expected.json @@ -95,7 +95,7 @@ }, { "name": "create_worktree", - "description": "Create a new Git branch and worktree from a local commit, branch, or tag, then change this session's working directory to it. Uncommitted files stay in the source checkout. Existing names fail. exit_worktree returns to the source checkout.", + "description": "Create a new Git branch and worktree from a local commit, branch, or tag, then change this session's working directory to it. Uncommitted files stay in the source checkout. Existing names fail; enter_worktree enters an existing worktree. exit_worktree returns to the source checkout.", "parameters": { "type": "object", "properties": { @@ -152,9 +152,25 @@ ] } }, + { + "name": "enter_worktree", + "description": "Change this session's working directory to an existing worktree that was created from the checkout this session is in. Branches and files stay as they are. exit_worktree returns to that checkout.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name the worktree was created with." + } + }, + "required": [ + "name" + ] + } + }, { "name": "exit_worktree", - "description": "Change this session's working directory from the worktree it is in back to the checkout that worktree was created from, and report the worktree left. The worktree and its branch remain.", + "description": "Change this session's working directory from the worktree it is in back to the checkout it entered that worktree from, and report the worktree left. The worktree and its branch remain.", "parameters": { "type": "object", "properties": {}