refactor(worktrees): move archive cleanup into the worktree service
The worktree service now records each checkout it creates as a `plugin:worktree/created` record, folds them in its own `worktree` projection with fork-aware ownership, and reclaims a clean, unreferenced checkout when the Session that created it is archived. The Forge panel reads the service's record and forwards its cleanup state; it no longer writes a `created` record, owns a retention projection, or gates every Session's directory access. Admission registers the attempt inside the Workspace write queue and returns; inspection runs afterwards, reading cold Sessions through the projection cache when mounted and from their log otherwise, with subagent children of an archived ancestor counted as archived. Only a path being removed holds `working-directory/access`, whose request now carries the access's `signal`, and listeners withdraw before the drain. Ignored files no longer retain a checkout, matching Git's non-force removal; processes and terminals are not consulted. The Forge bundle mounts one `worktree` service: the `forge-worktree` row and the `optional-forge-panel` group that isolated a second service are gone, and `forge-panel` is a top-level row. `canRemove`, `remove`, the `forgeWorktreeRetention` projection, and `ForgeWorktreeCleanup` are removed; `WorktreeService.cleanupOf`, `WorktreeCleanup`, and the `worktree/cleanup` Host event replace them. The upgrade guide moves to the current version directory and covers the id removals.
This commit is contained in:
1 parent
a2d8340421
commit
691ebd7b6c
81 files changed
+1389
-971
No files matched your search
@@ -9,11 +9,11 @@
|
||||
en: 12ab239ab0c58e31
|
||||
zh: c32874442ce66041
|
||||
/agent-note-explicit-worktree-creation/decision:
|
||||
en: d36bee8b73914811
|
||||
zh: a4c292857a7eeb6b
|
||||
en: 77fd7d1b0f2b4840
|
||||
zh: 0d3b1d86a75c442a
|
||||
/agent-note-explicit-worktree-creation/alternatives-considered:
|
||||
en: 72d42e892a37b94c
|
||||
zh: 92a14a51c6a89c53
|
||||
/agent-note-explicit-worktree-creation/consequences:
|
||||
en: e5c9970bfc20d41b
|
||||
zh: 4ac59eebbf8bea86
|
||||
en: 2643edaca2e8b283
|
||||
zh: 6e2b66ce43638a39
|
||||
@@ -16,9 +16,9 @@ The source repository comes from the calling Session's current directory. Creati
|
||||
|
||||
Git and directory creation use the mounted subprocess and sandbox providers without widening the calling Session's policy. Both destination and shared Git metadata writes must already be permitted. Successful creation changes only the current working directory; the Session identity and original sandbox root remain owned by their existing services.
|
||||
|
||||
Leaving uses the shared working-directory operation and retains the checkout and branch. Failed setup can retain partial artifacts and reports their location. The service does not own a checkout registry, cleanup schedule, branch merge policy, or task association database.
|
||||
Leaving uses the shared working-directory operation and retains the checkout and branch. Failed setup can retain partial artifacts and reports their location. The service does not own a branch merge policy or a task association database.
|
||||
|
||||
The [Forge UI](../../../../packages/experimental/client-ui-forge/README.md) owns archive-triggered cleanup only for checkouts its New Session option created. A Session's inherited prefix proves whether it created the checkout or merely refers to it; cwd alone never grants cleanup ownership. Cold Session inspection reads domain projections and the original sandbox policy without starting an Agent. The archive is durable before cleanup, and unarchive and directory entry wait for cleanup admission to settle. Conservative retention avoids inventing backups of ignored or untracked files: only a clean, unshared checkout is removed, its named branch remains, and uncertain inspection retains it. No startup sweep deletes previously archived worktrees.
|
||||
The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Processes and terminals are not consulted. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -32,4 +32,4 @@ The [Forge UI](../../../../packages/experimental/client-ui-forge/README.md) owns
|
||||
|
||||
## Consequences
|
||||
|
||||
The caller can continue one Session in a new checkout with a reconstructable directory change. Retention avoids deleting work on exit or a failed final publication, while consumers can reclaim eligible UI checkouts on archive without managing branch lifetime. Git and Node must be available in the filesystem provider's execution world. Submodule setup and dependency installation remain separate operations.
|
||||
The caller can continue one Session in a new checkout with a reconstructable directory change. Retention avoids deleting work on exit or a failed final publication, while archiving reclaims a clean checkout without touching branch lifetime. Git and Node must be available in the filesystem provider's execution world. Submodule setup and dependency installation remain separate operations.
|
||||
@@ -16,9 +16,9 @@ Status: implemented
|
||||
|
||||
Git 与目录创建使用挂载的子进程及沙箱提供方,不扩大调用 Session 的策略。目标目录与共享 Git 元数据必须均已允许写入。成功创建只改变当前工作目录;Session 身份与原始沙箱根目录仍由已有服务拥有。
|
||||
|
||||
离开使用共享工作目录操作,保留检出目录与分支。初始化失败可能留下部分产物,并报告其位置。该服务不拥有工作树注册表、清理计划、分支合并策略或任务关联数据库。
|
||||
离开使用共享工作目录操作,保留检出目录与分支。初始化失败可能留下部分产物,并报告其位置。该服务不拥有分支合并策略或任务关联数据库。
|
||||
|
||||
[Forge UI](../../../../packages/experimental/client-ui-forge/README.zh.md)仅负责在归档时清理其新会话选项创建的检出目录。Session 的继承前缀证明它创建了该目录,还是仅引用它;当前工作目录本身不授予清理所有权。冷 Session 检查读取领域投影和原始沙箱策略,不启动 Agent。清理前先持久化归档,取消归档与进入目录等待清理准入结束。保守保留避免自行定义忽略文件或未跟踪文件的备份:只删除干净且未共享的检出目录,保留具名分支;检查不确定时保留目录。不在启动时扫描删除此前已归档的工作树。
|
||||
服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。不咨询进程与终端。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -32,4 +32,4 @@ Git 与目录创建使用挂载的子进程及沙箱提供方,不扩大调用
|
||||
|
||||
## Consequences
|
||||
|
||||
调用方可以在新的检出目录继续同一个 Session,且目录切换可重建。保留策略避免在离开或最后发布失败时删除工作,而消费者可以在归档时回收符合条件的 UI 检出目录,不接管分支生命周期。Git 与 Node 必须存在于文件系统提供方的执行环境中。子模块配置与依赖安装仍是独立操作。
|
||||
调用方可以在新的检出目录继续同一个 Session,且目录切换可重建。保留策略避免在离开或最后发布失败时删除工作,而归档会回收干净的检出目录,不触及分支生命周期。Git 与 Node 必须存在于文件系统提供方的执行环境中。子模块配置与依赖安装仍是独立操作。
|
||||
@@ -376,7 +376,9 @@ async function sendPrompt(page: Page, scaffold: WebScaffold): Promise<{ readonly
|
||||
function worktreeRecords(events: readonly SessionEvent[]): unknown[] {
|
||||
return events.flatMap((event) => {
|
||||
const record = pluginRecordOf(event)
|
||||
return record?.type === 'plugin:client-ui-forge/worktree' ? [record.data] : []
|
||||
if (record?.type === 'plugin:client-ui-forge/worktree') return [record.data]
|
||||
if (record?.type === 'plugin:worktree/created') return [{ created: record.data }]
|
||||
return []
|
||||
})
|
||||
}
|
||||
|
||||
@@ -491,13 +493,12 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
expect(worktreeRecords(events)).toEqual([
|
||||
{ action: 'request', from: 'main' },
|
||||
{ action: 'request', from: 'release' },
|
||||
{ action: 'created', worktree: { path: directory, branch, from: 'release', baseCommit, repositoryRoot: project } },
|
||||
{ created: { path: directory, branch, baseCommit, repositoryRoot: project } },
|
||||
])
|
||||
// The worktree existed before the turn, so the first model request carried its directory notice.
|
||||
const created = events.findIndex((event) => {
|
||||
const record = pluginRecordOf(event)
|
||||
const data = record?.type === 'plugin:client-ui-forge/worktree' ? record.data : null
|
||||
return typeof data === 'object' && data !== null && 'action' in data && data.action === 'created'
|
||||
return record?.type === 'plugin:worktree/created'
|
||||
})
|
||||
const turn = events.findIndex(event => event.type === 'turn/start')
|
||||
const notice = events.findIndex(event => event.type === 'user/message' && event.data.source.kind === 'working-directory')
|
||||
|
||||
@@ -1506,8 +1506,8 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official'
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-worktree`
|
||||
|
||||
- `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy`
|
||||
- `source`: [`packages/experimental/worktree/src/index.ts:22`](../packages/experimental/worktree/src/index.ts)
|
||||
- `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections`
|
||||
- `source`: [`packages/experimental/worktree/src/index.ts:34`](../packages/experimental/worktree/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Worktree location, generated names, executables, and subprocess resource limits. */
|
||||
@@ -4887,7 +4887,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-working-directory`
|
||||
|
||||
- `inject`: `fs` · `sessionProjections` · `systemPrompt`
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:60`](../packages/session/working-directory/src/index.ts)
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:67`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment default for Sessions without an original project directory. */
|
||||
|
||||
@@ -1508,8 +1508,8 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official'
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-worktree`
|
||||
|
||||
- `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy`
|
||||
- `source`: [`packages/experimental/worktree/src/index.ts:22`](../packages/experimental/worktree/src/index.ts)
|
||||
- `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections`
|
||||
- `source`: [`packages/experimental/worktree/src/index.ts:34`](../packages/experimental/worktree/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Worktree location, generated names, executables, and subprocess resource limits. */
|
||||
@@ -4889,7 +4889,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-working-directory`
|
||||
|
||||
- `inject`: `fs` · `sessionProjections` · `systemPrompt`
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:60`](../packages/session/working-directory/src/index.ts)
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:67`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment default for Sessions without an original project directory. */
|
||||
|
||||
@@ -98,11 +98,12 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:25`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `client-ui-forge` |
|
||||
| `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | `client-ui-forge` (`waterfall`), [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:154`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `client-ui-forge` |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:29`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` |
|
||||
| `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` |
|
||||
| `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-unarchiving` | `parallel` | [`packages/workspace/workspace/src/index.ts:161`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `client-ui-forge` |
|
||||
| `workspace/session-unarchiving` | `parallel` | [`packages/workspace/workspace/src/index.ts:163`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` |
|
||||
| `worktree/cleanup` | `emit` | [`packages/experimental/worktree/src/archive.ts:25`](../packages/experimental/worktree/src/archive.ts) | `worktree` (`emit`) | - |
|
||||
<!-- END GENERATED event-producer-consumer:events -->
|
||||
|
||||
## Non-harness or undeclared event strings seen in package source
|
||||
|
||||
@@ -100,11 +100,12 @@
|
||||
| `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:25`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `client-ui-forge` |
|
||||
| `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | `client-ui-forge` (`waterfall`), [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:154`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `client-ui-forge` |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:29`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` |
|
||||
| `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` |
|
||||
| `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-unarchiving` | `parallel` | [`packages/workspace/workspace/src/index.ts:161`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `client-ui-forge` |
|
||||
| `workspace/session-unarchiving` | `parallel` | [`packages/workspace/workspace/src/index.ts:163`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` |
|
||||
| `worktree/cleanup` | `emit` | [`packages/experimental/worktree/src/archive.ts:25`](../packages/experimental/worktree/src/archive.ts) | `worktree` (`emit`) | - |
|
||||
<!-- END GENERATED event-producer-consumer:events -->
|
||||
|
||||
## Non-harness or undeclared event strings seen in package source
|
||||
|
||||
@@ -6,5 +6,5 @@
|
||||
en: a11f106978c9dce7
|
||||
zh: a11f106978c9dce7
|
||||
/experimental-plugin-record-catalog:
|
||||
en: 2e4c95aeb435f35e
|
||||
zh: 669270a7e95ad6f2
|
||||
en: 9039e195fcd4a8ac
|
||||
zh: b0d69f6fab00eac2
|
||||
@@ -18,3 +18,4 @@ Shared Session event declarations and resolved schemas appear in the [Session pe
|
||||
| `plugin:forge-session/binding` | `@deepseek-ai/dsh-experimental-forge-session` | A caller or discovery action that binds, restores, or hides one change request. | <code>BindingRecord</code> · [`packages/experimental/forge-session/src/types.ts`](../packages/experimental/forge-session/src/types.ts) |
|
||||
| `plugin:translator/request` | `@deepseek-ai/dsh-experimental-translator` | Provider-independent translation input, retained before dispatch. | <code>TranslationRequestRecord</code> · [`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. | <code>TranslationResultRecord</code> · [`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. | <code>CreatedWorktree</code> · [`packages/experimental/worktree/src/projection.ts`](../packages/experimental/worktree/src/projection.ts) |
|
||||
@@ -18,3 +18,4 @@
|
||||
| `plugin:forge-session/binding` | `@deepseek-ai/dsh-experimental-forge-session` | A caller or discovery action that binds, restores, or hides one change request. | <code>BindingRecord</code> · [`packages/experimental/forge-session/src/types.ts`](../packages/experimental/forge-session/src/types.ts) |
|
||||
| `plugin:translator/request` | `@deepseek-ai/dsh-experimental-translator` | Provider-independent translation input, retained before dispatch. | <code>TranslationRequestRecord</code> · [`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. | <code>TranslationResultRecord</code> · [`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. | <code>CreatedWorktree</code> · [`packages/experimental/worktree/src/projection.ts`](../packages/experimental/worktree/src/projection.ts) |
|
||||
@@ -300,8 +300,8 @@
|
||||
en: e8dd0cebbb930eb7
|
||||
zh: e8dd0cebbb930eb7
|
||||
/session-persistence-event-catalog/events/working-directory/working-directory-change-log-only:
|
||||
en: 574922741b519e92
|
||||
zh: 094d7c6a5d196264
|
||||
en: fc893ed0d93765df
|
||||
zh: 2df365d9d0ac6f6e
|
||||
/session-persistence-event-catalog/events/workspace:
|
||||
en: 63ee1a85e4b59ae3
|
||||
zh: 63ee1a85e4b59ae3
|
||||
@@ -1494,8 +1494,8 @@
|
||||
en: bef51e0442ebb903
|
||||
zh: 240ebeb160533d8c
|
||||
/session-persistence-event-catalog/resolved-persistence-types/cwd:
|
||||
en: 9592a5366d1964b6
|
||||
zh: 98ec6160f47e9f19
|
||||
en: 35feea0430c0f14b
|
||||
zh: d5aaf1d2ca80114a
|
||||
/session-persistence-event-catalog/resolved-persistence-types/decision-durationms-exitcode-handlerid:
|
||||
en: a99ac57bbec0370f
|
||||
zh: 9073329e324a66e0
|
||||
@@ -1929,8 +1929,8 @@
|
||||
en: 0b74295f7c5c8f11
|
||||
zh: 5f1213cec87f6be0
|
||||
/session-persistence-event-catalog/resolved-persistence-types/kind-working-directory:
|
||||
en: 1ba3f980c51e3eac
|
||||
zh: 8dd77f52ad4507a6
|
||||
en: 626ea3180b86e5b6
|
||||
zh: 4b6e0dc1312b3c5a
|
||||
/session-persistence-event-catalog/resolved-persistence-types/max-tokens-messages-model-thinking:
|
||||
en: 3216b23c131d0070
|
||||
zh: 73ca171c6014f16e
|
||||
|
||||
@@ -1329,7 +1329,7 @@ Source: [`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/
|
||||
}
|
||||
```
|
||||
|
||||
Source: [`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts)
|
||||
Source: [`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
### `workspace/*`
|
||||
|
||||
@@ -6209,7 +6209,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:24`](../packages/compacti
|
||||
|
||||
SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582`
|
||||
|
||||
Sources: [`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts)
|
||||
Sources: [`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| Property | Presence | Type |
|
||||
|---|---|---|
|
||||
@@ -7949,7 +7949,7 @@ Sources: [`packages/experimental/webhook/src/types.ts:74`](../packages/experimen
|
||||
|
||||
SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5`
|
||||
|
||||
Sources: [`packages/session/working-directory/src/index.ts:38`](../packages/session/working-directory/src/index.ts)
|
||||
Sources: [`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| Property | Presence | Type |
|
||||
|---|---|---|
|
||||
|
||||
@@ -1331,7 +1331,7 @@ export type SessionEvent<T extends SessionEventType = SessionEventType> = {
|
||||
}
|
||||
```
|
||||
|
||||
来源:[`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts)
|
||||
来源:[`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
### `workspace/*`
|
||||
|
||||
@@ -6211,7 +6211,7 @@ SHA-256: `3e4e7683b0192c9f0e6a75c59076108f017892cdb302a98032c2632fd79c356f`
|
||||
|
||||
SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582`
|
||||
|
||||
来源:[`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts)
|
||||
来源:[`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| 属性 | 存在性 | 类型 |
|
||||
|---|---|---|
|
||||
@@ -7951,7 +7951,7 @@ SHA-256: `9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94`
|
||||
|
||||
SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5`
|
||||
|
||||
来源:[`packages/session/working-directory/src/index.ts:38`](../packages/session/working-directory/src/index.ts)
|
||||
来源:[`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| 属性 | 存在性 | 类型 |
|
||||
|---|---|---|
|
||||
|
||||
Generated
+2
-2
@@ -159,7 +159,7 @@
|
||||
{"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]},
|
||||
{"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/team/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/team/agent-team/src/types.ts:121"]},
|
||||
{"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]},
|
||||
{"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:38"]},
|
||||
{"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:45"]},
|
||||
{"digest":"224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc","names":[],"sources":[]},
|
||||
{"digest":"234142ee4f996f38cc9fa3b8b3e3de29b03c9aefe5ebf6c224eddd564505aa85","names":[],"sources":[]},
|
||||
{"digest":"237c004c73b6b288246816e0d7fde16e09c63a47aa3b1227383d7afe58666163","names":[],"sources":[]},
|
||||
@@ -607,7 +607,7 @@
|
||||
{"digest":"d9196086e41e4dd5c2ce87f5c25529c8112a1731d258cf0728747d41a9ee3241","names":[],"sources":[]},
|
||||
{"digest":"d9c462b9f62fdd3efc76a44b9524dc8781f6b91cd9c7e584b17d971defafebab","names":["packages/llm/llm/src/message.ts#ToolMessageSource"],"sources":["packages/llm/llm/src/message.ts:29"]},
|
||||
{"digest":"d9edf1862e4471d6ad8a106a3f4160e0643874368707d50ecd8e27e5ee7a2567","names":[],"sources":[]},
|
||||
{"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:45"]},
|
||||
{"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:52"]},
|
||||
{"digest":"dacf3d5f3e4ff619c1320e64a48dec5e7ecd7870bece65fbd449a0e63adfa521","names":[],"sources":[]},
|
||||
{"digest":"db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c","names":[],"sources":[]},
|
||||
{"digest":"db6c5246911d47a7969f6b4cb47c7d0dbbde75c402710b22ace3672fa97bebe0","names":[],"sources":[]},
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/subsystems/forge.md
|
||||
/forges:
|
||||
en: 3ee521b77b4601e2
|
||||
en: 3990a17e12c66a23
|
||||
zh: 4170c33e49248f8f
|
||||
/forges/providers-and-change-requests:
|
||||
en: 4ec7d1892b4067db
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
English | [中文](forge.zh.md)
|
||||
|
||||
The experimental forge capability seam reads change requests, meaning pull requests and merge requests, from code hosts. [`dsh-experimental-forge`](../../packages/experimental/forge/README.md) is the Service Definition and provides `ctx.forge`; [`dsh-experimental-forge-github`](../../packages/experimental/forge-github/README.md) is the Service Provider for GitHub hosts; [`dsh-experimental-forge-session`](../../packages/experimental/forge-session/README.md) is the Consumer that binds change requests to Sessions and provides `ctx.forgeSession`; [`dsh-experimental-client-ui-forge`](../../packages/experimental/client-ui-forge/README.md) is the GUI Consumer that provides `ctx.forgePanel`. The default-disabled [forge bundle](../../packages/experimental/forge-bundle/README.md) composes all four, with the [worktree model tool](../../packages/experimental/tool-worktree/README.md) and an isolated [worktree service](../../packages/experimental/worktree/README.md) for the panel, from the Plugins page; otherwise they load only through explicit composition.
|
||||
The experimental forge capability seam reads change requests, meaning pull requests and merge requests, from code hosts. [`dsh-experimental-forge`](../../packages/experimental/forge/README.md) is the Service Definition and provides `ctx.forge`; [`dsh-experimental-forge-github`](../../packages/experimental/forge-github/README.md) is the Service Provider for GitHub hosts; [`dsh-experimental-forge-session`](../../packages/experimental/forge-session/README.md) is the Consumer that binds change requests to Sessions and provides `ctx.forgeSession`; [`dsh-experimental-client-ui-forge`](../../packages/experimental/client-ui-forge/README.md) is the GUI Consumer that provides `ctx.forgePanel`. The default-disabled [forge bundle](../../packages/experimental/forge-bundle/README.md) composes all four, with the [worktree model tool](../../packages/experimental/tool-worktree/README.md) and one shared [worktree service](../../packages/experimental/worktree/README.md), from the Plugins page; otherwise they load only through explicit composition.
|
||||
|
||||
## Providers and change requests
|
||||
|
||||
@@ -378,13 +378,6 @@ interface ForgeSessionWorktree {
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Process-local result of one archive-triggered cleanup attempt. */
|
||||
interface ForgeWorktreeCleanup {
|
||||
readonly revision: number
|
||||
readonly status: 'scheduled' | 'retained' | 'removed' | 'failed'
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Payload of the `plugin:client-ui-forge/worktree` record. */
|
||||
@@ -920,12 +913,12 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote({ mode: 'stream' }) async *changeRequestStates(signal: AbortSignal): AsyncIterable<ForgeChangeRequestStatesFrame>
|
||||
|
||||
/**
|
||||
* Read or await an archive cleanup owned by this Host lifetime.
|
||||
* Read or await the worktree service's archive cleanup of the Session's checkout.
|
||||
* @param session - Session whose cleanup is visible to the caller.
|
||||
* @param revision - null reads now; a matching revision waits for completion.
|
||||
* @returns the cleanup state, or null when none exists or the revision was superseded.
|
||||
* @returns the cleanup state, or null without a worktree service, an attempt, or a current revision.
|
||||
*/
|
||||
@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<ForgeWorktreeCleanup | null>
|
||||
@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null>
|
||||
|
||||
/**
|
||||
* List the local branches that can start a worktree of the Session's current checkout.
|
||||
@@ -1151,7 +1144,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async continueInProject(session: Session, signal: AbortSignal): Promise<void>
|
||||
```
|
||||
|
||||
Types: [Session](session.md)
|
||||
Types: [Session](session.md) · [WorktreeCleanup](worktrees.md)
|
||||
|
||||
Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/experimental/client-ui-forge/src/index.ts)
|
||||
|
||||
|
||||
@@ -378,13 +378,6 @@ interface ForgeSessionWorktree {
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Process-local result of one archive-triggered cleanup attempt. */
|
||||
interface ForgeWorktreeCleanup {
|
||||
readonly revision: number
|
||||
readonly status: 'scheduled' | 'retained' | 'removed' | 'failed'
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Payload of the `plugin:client-ui-forge/worktree` record. */
|
||||
@@ -920,12 +913,12 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote({ mode: 'stream' }) async *changeRequestStates(signal: AbortSignal): AsyncIterable<ForgeChangeRequestStatesFrame>
|
||||
|
||||
/**
|
||||
* Read or await an archive cleanup owned by this Host lifetime.
|
||||
* Read or await the worktree service's archive cleanup of the Session's checkout.
|
||||
* @param session - Session whose cleanup is visible to the caller.
|
||||
* @param revision - null reads now; a matching revision waits for completion.
|
||||
* @returns the cleanup state, or null when none exists or the revision was superseded.
|
||||
* @returns the cleanup state, or null without a worktree service, an attempt, or a current revision.
|
||||
*/
|
||||
@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<ForgeWorktreeCleanup | null>
|
||||
@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null>
|
||||
|
||||
/**
|
||||
* List the local branches that can start a worktree of the Session's current checkout.
|
||||
@@ -1151,7 +1144,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async continueInProject(session: Session, signal: AbortSignal): Promise<void>
|
||||
```
|
||||
|
||||
Types: [Session](session.zh.md)
|
||||
Types: [Session](session.zh.md) · [WorktreeCleanup](worktrees.zh.md)
|
||||
|
||||
Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/experimental/client-ui-forge/src/index.ts)
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ get(session: Session): string
|
||||
* @param signal - cancellation for filesystem inspection.
|
||||
* @returns the existing directory; recovery is committed before fulfillment.
|
||||
* A notice failure is warned without reverting the committed state.
|
||||
* @throws when the original project is also unavailable.
|
||||
* @throws when the original project is also unavailable, or when a `working-directory/access` listener rejects.
|
||||
*/
|
||||
ensure(agent: Agent, signal?: AbortSignal): Promise<string>
|
||||
|
||||
@@ -70,16 +70,20 @@ Source: [`packages/session/working-directory/src/index.ts`](../../packages/sessi
|
||||
|
||||
#### `working-directory/access` — waterfall
|
||||
|
||||
Coordinate directory validation and publication with resource lifecycle operations.
|
||||
Coordinate directory validation and publication with a resource operation on the directory, such as a checkout being removed. A listener that must wait awaits that operation, then calls `next()`; every other listener calls `next()` at once. A rejection fails this access and leaves the recorded directory unchanged; it is not a fallback.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Coordinate directory validation and publication with resource lifecycle operations.
|
||||
* @param request - owner and requested path; null validates the current directory.
|
||||
* @param next - perform validation and commit after competing operations settle.
|
||||
* Coordinate directory validation and publication with a resource operation
|
||||
* on the directory, such as a checkout being removed. A listener that must
|
||||
* wait awaits that operation, then calls `next()`; every other listener
|
||||
* calls `next()` at once. A rejection fails this access and leaves the
|
||||
* recorded directory unchanged; it is not a fallback.
|
||||
* @param request - owner, requested path (null validates the current directory), and the access's cancellation.
|
||||
* @param next - perform validation and commit.
|
||||
* @mode waterfall
|
||||
*/
|
||||
'working-directory/access'(request: { agent: Agent; path: string | null }, next: () => Promise<string>): Promise<string>
|
||||
'working-directory/access'( request: { agent: Agent; path: string | null; signal: AbortSignal }, next: () => Promise<string>, ): Promise<string>
|
||||
```
|
||||
|
||||
Types: [Agent](core.md)
|
||||
|
||||
@@ -42,7 +42,7 @@ get(session: Session): string
|
||||
* @param signal - cancellation for filesystem inspection.
|
||||
* @returns the existing directory; recovery is committed before fulfillment.
|
||||
* A notice failure is warned without reverting the committed state.
|
||||
* @throws when the original project is also unavailable.
|
||||
* @throws when the original project is also unavailable, or when a `working-directory/access` listener rejects.
|
||||
*/
|
||||
ensure(agent: Agent, signal?: AbortSignal): Promise<string>
|
||||
|
||||
@@ -70,16 +70,20 @@ Source: [`packages/session/working-directory/src/index.ts`](../../packages/sessi
|
||||
|
||||
#### `working-directory/access` — waterfall
|
||||
|
||||
Coordinate directory validation and publication with resource lifecycle operations.
|
||||
Coordinate directory validation and publication with a resource operation on the directory, such as a checkout being removed. A listener that must wait awaits that operation, then calls `next()`; every other listener calls `next()` at once. A rejection fails this access and leaves the recorded directory unchanged; it is not a fallback.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Coordinate directory validation and publication with resource lifecycle operations.
|
||||
* @param request - owner and requested path; null validates the current directory.
|
||||
* @param next - perform validation and commit after competing operations settle.
|
||||
* Coordinate directory validation and publication with a resource operation
|
||||
* on the directory, such as a checkout being removed. A listener that must
|
||||
* wait awaits that operation, then calls `next()`; every other listener
|
||||
* calls `next()` at once. A rejection fails this access and leaves the
|
||||
* recorded directory unchanged; it is not a fallback.
|
||||
* @param request - owner, requested path (null validates the current directory), and the access's cancellation.
|
||||
* @param next - perform validation and commit.
|
||||
* @mode waterfall
|
||||
*/
|
||||
'working-directory/access'(request: { agent: Agent; path: string | null }, next: () => Promise<string>): Promise<string>
|
||||
'working-directory/access'( request: { agent: Agent; path: string | null; signal: AbortSignal }, next: () => Promise<string>, ): Promise<string>
|
||||
```
|
||||
|
||||
Types: [Agent](core.zh.md)
|
||||
|
||||
@@ -623,12 +623,14 @@ Source: [`packages/workspace/workspace/src/index.ts`](../../packages/workspace/w
|
||||
|
||||
#### `workspace/session-archived` — parallel
|
||||
|
||||
Admit optional follow-up work after durable archival and any stop requests. Listener failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
Admit optional follow-up work after durable archival and any stop requests. Dispatched inside the registry's write queue: a listener registers its work and returns, and runs the work and any unbounded I/O afterwards. Listener failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Admit optional follow-up work after durable archival and any stop requests.
|
||||
* Listener failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
* Dispatched inside the registry's write queue: a listener registers its work
|
||||
* and returns, and runs the work and any unbounded I/O afterwards. Listener
|
||||
* failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
* @param request - newly archived Session; repeated archive requests do not dispatch.
|
||||
* @mode parallel
|
||||
*/
|
||||
|
||||
@@ -623,12 +623,14 @@ Source: [`packages/workspace/workspace/src/index.ts`](../../packages/workspace/w
|
||||
|
||||
#### `workspace/session-archived` — parallel
|
||||
|
||||
Admit optional follow-up work after durable archival and any stop requests. Listener failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
Admit optional follow-up work after durable archival and any stop requests. Dispatched inside the registry's write queue: a listener registers its work and returns, and runs the work and any unbounded I/O afterwards. Listener failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Admit optional follow-up work after durable archival and any stop requests.
|
||||
* Listener failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
* Dispatched inside the registry's write queue: a listener registers its work
|
||||
* and returns, and runs the work and any unbounded I/O afterwards. Listener
|
||||
* failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
* @param request - newly archived Session; repeated archive requests do not dispatch.
|
||||
* @mode parallel
|
||||
*/
|
||||
|
||||
@@ -74,6 +74,29 @@ interface RestoredWorktree {
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One checkout in a Session's log and whether that Session, rather than a fork ancestor, created it. */
|
||||
interface WorktreeCreation {
|
||||
readonly worktree: CreatedWorktree
|
||||
/** False for a creation inside the fork-inherited prefix. */
|
||||
readonly owned: boolean
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Process-local state of one archive-triggered cleanup of a checkout. */
|
||||
interface WorktreeCleanup {
|
||||
/** Monotonic attempt number within this Host lifetime; a Remote waits on a specific one. */
|
||||
readonly revision: number
|
||||
/**
|
||||
* `scheduled` until the background inspection ends; `retained` when a use,
|
||||
* policy, or Git state keeps the checkout; `removed` after `git worktree
|
||||
* remove`; `failed` when removal threw and may have left a partial directory.
|
||||
*/
|
||||
readonly status: 'scheduled' | 'retained' | 'removed' | 'failed'
|
||||
}
|
||||
```
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
<a id="cordis-surface"></a>
|
||||
@@ -86,7 +109,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.
|
||||
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.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
@@ -121,29 +144,40 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS
|
||||
async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<RestoredWorktree>
|
||||
|
||||
/**
|
||||
* Inspect a recorded checkout for non-destructive removal. Dirty, ignored, locked,
|
||||
* detached, nested, mismatched, and missing checkouts are retained. Inspection errors reject.
|
||||
* @param policy - resolved execution policy of the owning Session.
|
||||
* @param request - recorded checkout identity.
|
||||
* @param signal - cancellation of inspection.
|
||||
* @returns whether the checkout is currently eligible; removal always inspects again.
|
||||
* Read the archive cleanup of a Session's created checkout; waiting never
|
||||
* starts one. Absent without the Workspace and query providers.
|
||||
* @param session - archived Session whose cleanup is read.
|
||||
* @param revision - null reads at once; a matching revision waits for that attempt to settle.
|
||||
* @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
|
||||
*/
|
||||
canRemove(policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal): Promise<boolean>
|
||||
|
||||
/**
|
||||
* Remove an eligible checkout and its registration without force or branch deletion.
|
||||
* Callers must exclude new users until settlement. A rejection can leave a partially
|
||||
* removed directory; the branch remains available for restoration.
|
||||
* @param policy - resolved execution policy of the owning Session.
|
||||
* @param request - recorded checkout identity.
|
||||
* @param signal - cancellation before or during removal.
|
||||
* @param admit - synchronous final admission after inspection; false retains the checkout.
|
||||
* @returns true when removed; false when inspection or admission requires retention.
|
||||
*/
|
||||
remove( policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal, admit: () => boolean = () => true, ): Promise<boolean>
|
||||
async cleanupOf(session: Session, revision: number | null): Promise<WorktreeCleanup | null>
|
||||
```
|
||||
|
||||
Types: [Agent](core.md) · [SandboxExecutionPolicy](sandbox.md)
|
||||
Types: [Agent](core.md) · [Session](session.md)
|
||||
|
||||
Source: [`packages/experimental/worktree/src/index.ts`](../../packages/experimental/worktree/src/index.ts)
|
||||
|
||||
<a id="worktree-events"></a>
|
||||
|
||||
### `worktree/*` events
|
||||
|
||||
<a id="worktreecleanup--emit"></a>
|
||||
|
||||
#### `worktree/cleanup` — emit
|
||||
|
||||
A cleanup attempt changed state. Fires once at admission with `scheduled` and once at settlement with the final status.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* A cleanup attempt changed state. Fires once at admission with
|
||||
* `scheduled` and once at settlement with the final status.
|
||||
* @param info - the archived Session, the checkout, and the attempt state.
|
||||
* @mode emit
|
||||
*/
|
||||
'worktree/cleanup'(info: { sessionId: SessionId; path: string; cleanup: WorktreeCleanup }): void
|
||||
```
|
||||
|
||||
Types: [SessionId](core.md)
|
||||
|
||||
Source: [`packages/experimental/worktree/src/archive.ts`](../../packages/experimental/worktree/src/archive.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
@@ -74,6 +74,29 @@ interface RestoredWorktree {
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One checkout in a Session's log and whether that Session, rather than a fork ancestor, created it. */
|
||||
interface WorktreeCreation {
|
||||
readonly worktree: CreatedWorktree
|
||||
/** False for a creation inside the fork-inherited prefix. */
|
||||
readonly owned: boolean
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Process-local state of one archive-triggered cleanup of a checkout. */
|
||||
interface WorktreeCleanup {
|
||||
/** Monotonic attempt number within this Host lifetime; a Remote waits on a specific one. */
|
||||
readonly revision: number
|
||||
/**
|
||||
* `scheduled` until the background inspection ends; `retained` when a use,
|
||||
* policy, or Git state keeps the checkout; `removed` after `git worktree
|
||||
* remove`; `failed` when removal threw and may have left a partial directory.
|
||||
*/
|
||||
readonly status: 'scheduled' | 'retained' | 'removed' | 'failed'
|
||||
}
|
||||
```
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
<a id="cordis-surface"></a>
|
||||
@@ -86,7 +109,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.
|
||||
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.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
@@ -121,29 +144,40 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS
|
||||
async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<RestoredWorktree>
|
||||
|
||||
/**
|
||||
* Inspect a recorded checkout for non-destructive removal. Dirty, ignored, locked,
|
||||
* detached, nested, mismatched, and missing checkouts are retained. Inspection errors reject.
|
||||
* @param policy - resolved execution policy of the owning Session.
|
||||
* @param request - recorded checkout identity.
|
||||
* @param signal - cancellation of inspection.
|
||||
* @returns whether the checkout is currently eligible; removal always inspects again.
|
||||
* Read the archive cleanup of a Session's created checkout; waiting never
|
||||
* starts one. Absent without the Workspace and query providers.
|
||||
* @param session - archived Session whose cleanup is read.
|
||||
* @param revision - null reads at once; a matching revision waits for that attempt to settle.
|
||||
* @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
|
||||
*/
|
||||
canRemove(policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal): Promise<boolean>
|
||||
|
||||
/**
|
||||
* Remove an eligible checkout and its registration without force or branch deletion.
|
||||
* Callers must exclude new users until settlement. A rejection can leave a partially
|
||||
* removed directory; the branch remains available for restoration.
|
||||
* @param policy - resolved execution policy of the owning Session.
|
||||
* @param request - recorded checkout identity.
|
||||
* @param signal - cancellation before or during removal.
|
||||
* @param admit - synchronous final admission after inspection; false retains the checkout.
|
||||
* @returns true when removed; false when inspection or admission requires retention.
|
||||
*/
|
||||
remove( policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal, admit: () => boolean = () => true, ): Promise<boolean>
|
||||
async cleanupOf(session: Session, revision: number | null): Promise<WorktreeCleanup | null>
|
||||
```
|
||||
|
||||
Types: [Agent](core.zh.md) · [SandboxExecutionPolicy](sandbox.zh.md)
|
||||
Types: [Agent](core.zh.md) · [Session](session.zh.md)
|
||||
|
||||
Source: [`packages/experimental/worktree/src/index.ts`](../../packages/experimental/worktree/src/index.ts)
|
||||
|
||||
<a id="worktree-events"></a>
|
||||
|
||||
### `worktree/*` events
|
||||
|
||||
<a id="worktreecleanup--emit"></a>
|
||||
|
||||
#### `worktree/cleanup` — emit
|
||||
|
||||
A cleanup attempt changed state. Fires once at admission with `scheduled` and once at settlement with the final status.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* A cleanup attempt changed state. Fires once at admission with
|
||||
* `scheduled` and once at settlement with the final status.
|
||||
* @param info - the archived Session, the checkout, and the attempt state.
|
||||
* @mode emit
|
||||
*/
|
||||
'worktree/cleanup'(info: { sessionId: SessionId; path: string; cleanup: WorktreeCleanup }): void
|
||||
```
|
||||
|
||||
Types: [SessionId](core.zh.md)
|
||||
|
||||
Source: [`packages/experimental/worktree/src/archive.ts`](../../packages/experimental/worktree/src/archive.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
@@ -1,18 +0,0 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Archiving a Session can remove its clean UI-created worktree while retaining the branch."
|
||||
---
|
||||
|
||||
# Worktree cleanup on archive
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
Archiving a Session previously retained its checkout. With the Forge bundle enabled, archiving can now remove a clean, unused worktree created by the New Session UI. Branches and commits remain. Dirty, ignored, shared, active, or uncertain checkouts remain without an extra prompt; existing archived Sessions are not swept. See the [Forge panel behavior](../../../../packages/experimental/client-ui-forge/README.md).
|
||||
|
||||
## Migration
|
||||
|
||||
1. If a checkout must remain available outside DSH, keep its Session unarchived or lock it with `git worktree lock <path>` before archiving.
|
||||
2. To resume an archived Session whose checkout was removed, unarchive it and use **Restore worktree**. The retained branch is checked out at the recorded path.
|
||||
3. Confirm the branch and commits are present with `git branch --list` and that **Restore worktree** makes the recorded checkout available. Session logs require no migration.
|
||||
@@ -1,18 +0,0 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "归档 Session 可以删除其干净的 UI 工作树,同时保留分支。"
|
||||
---
|
||||
|
||||
# 归档时清理工作树
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
归档 Session 以前会保留检出目录。启用 Forge bundle 后,归档现在可以删除通过新会话 UI 创建且干净、无人使用的工作树。分支和提交仍会保留。有修改、忽略文件、被共享、仍有活动或无法确认安全的检出目录会保留,不额外提示;不扫描此前已归档的 Session。参见 [Forge 面板行为](../../../../packages/experimental/client-ui-forge/README.zh.md)。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 如果检出目录必须供 DSH 之外继续使用,请保持其 Session 未归档,或在归档前用 `git worktree lock <path>` 锁定它。
|
||||
2. 要继续使用已归档且检出目录已删除的 Session,请取消归档并使用**恢复工作树**。保留的分支会在记录的路径重新检出。
|
||||
3. 用 `git branch --list` 确认分支与提交仍然存在,并确认**恢复工作树**使记录的检出目录重新可用。Session 日志无需迁移。
|
||||
+9
-9
@@ -1,16 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/archive-worktrees/guide.md
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.3/archive-worktrees/guide.md
|
||||
/:
|
||||
en: 68b9eb9365ad9cfc
|
||||
zh: ff34f93cc613e3c2
|
||||
en: bd4ec57ff904967c
|
||||
zh: 4be24cb594ad31ba
|
||||
/worktree-cleanup-on-archive:
|
||||
en: 8fd9ffdeaf212c64
|
||||
zh: 58e3cc51a81193b4
|
||||
en: eabb4a2d86dc3cb2
|
||||
zh: 2f4167d91d74d5ae
|
||||
/worktree-cleanup-on-archive/change:
|
||||
en: ed5b236bcb8ddc04
|
||||
zh: 0f73e6a9a7daf11f
|
||||
en: 587c3f8c7ef85a04
|
||||
zh: 970d67cfaf4c6afe
|
||||
/worktree-cleanup-on-archive/migration:
|
||||
en: fd9f1adec5ffaf14
|
||||
zh: ac47fb8f2535996a
|
||||
en: 2bd42635cf35d5c4
|
||||
zh: 4d9048402216767d
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Archiving a Session can remove its clean worktree while retaining the branch, and the Forge bundle mounts one worktree service."
|
||||
---
|
||||
|
||||
# Worktree cleanup on archive
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
Archiving a Session previously retained its checkout. The worktree service now records each checkout it creates as a `plugin:worktree/created` record and, when the Session that created one is archived, removes it with a non-force `git worktree remove` when no unarchived Session refers to it, its creator's policy is not read-only, and Git finds no tracked changes, untracked files, hidden index flags, submodules, locks, or detached HEAD. Ignored files such as `node_modules` do not retain it. Branches and commits remain. Checkouts created before this release have no such event and are never swept, nor are Sessions archived earlier. See the [worktree service](../../../../packages/experimental/worktree/README.md).
|
||||
|
||||
The Forge bundle mounts one `worktree` service for both the panel and the `create_worktree` tool. The `forge-worktree` row and the `optional-forge-panel` group that isolated a second service are gone; the panel is the top-level `forge-panel` row.
|
||||
|
||||
## Migration
|
||||
|
||||
1. If a checkout must remain available outside DSH, keep its Session unarchived or lock it with `git worktree lock <path>` before archiving. Ignored files are not kept.
|
||||
2. To resume an archived Session whose checkout was removed, unarchive it and use **Restore worktree**. The retained branch is checked out at the recorded path.
|
||||
3. In a profile's `cordis.patch.yml`, move any `forge-worktree` override to the `worktree` row and any `optional-forge-panel` override to the `forge-panel` row; a `disabled: true` on `forge-panel` turns off the panel alone.
|
||||
4. Confirm the branch and commits are present with `git branch --list` and that **Restore worktree** makes the recorded checkout available. Session logs require no migration.
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "归档 Session 可以删除其干净的工作树并保留分支,Forge bundle 只挂载一个工作树服务。"
|
||||
---
|
||||
|
||||
# 归档时清理工作树
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
归档 Session 以前会保留检出目录。工作树服务现在把它创建的每个检出目录记录为 `plugin:worktree/created` Session 事件;当创建它的 Session 被归档时,若没有未归档的 Session 引用该目录、创建者的策略不是只读,且 Git 未发现跟踪文件改动、未跟踪文件、隐藏的索引标记、子模块、锁或分离 HEAD,就用不带 force 的 `git worktree remove` 删除它。`node_modules` 之类被忽略的文件不会保留目录。分支和提交仍会保留。本版本之前创建的检出目录没有该事件,不会被扫描;更早归档的 Session 也不会。参见[工作树服务](../../../../packages/experimental/worktree/README.zh.md)。
|
||||
|
||||
Forge bundle 为面板和 `create_worktree` 工具挂载同一个 `worktree` 服务。隔离第二个服务的 `forge-worktree` 行与 `optional-forge-panel` 组已移除;面板是顶层的 `forge-panel` 行。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 如果检出目录必须供 DSH 之外继续使用,请保持其 Session 未归档,或在归档前用 `git worktree lock <path>` 锁定它。被忽略的文件不会保留。
|
||||
2. 要继续使用已归档且检出目录已删除的 Session,请取消归档并使用**恢复工作树**。保留的分支会在记录的路径重新检出。
|
||||
3. 在 profile 的 `cordis.patch.yml` 中,把针对 `forge-worktree` 的覆盖迁到 `worktree` 行,把针对 `optional-forge-panel` 的覆盖迁到 `forge-panel` 行;对 `forge-panel` 设置 `disabled: true` 可以只关闭面板。
|
||||
4. 用 `git branch --list` 确认分支与提交仍然存在,并确认**恢复工作树**使记录的检出目录重新可用。Session 日志无需迁移。
|
||||
@@ -57,8 +57,8 @@
|
||||
en: 8bcb7bd90d7c5773
|
||||
zh: 17663be926a099d2
|
||||
/deepseek-ai-dsh-client-ui-workspace/further-exploration:
|
||||
en: 28c4981d08f3e95c
|
||||
zh: e44a3fdbd72d25f5
|
||||
en: cb0b5c3c3caa27f5
|
||||
zh: e854ce9c897d1b64
|
||||
/deepseek-ai-dsh-client-ui-workspace/model-experience:
|
||||
en: 3120df665299c634
|
||||
zh: 1d9f365d091d0d2a
|
||||
|
||||
@@ -230,7 +230,7 @@ These pages cover the sidebar host, the hero surface, and the picking backends.
|
||||
|
||||
-----
|
||||
|
||||
The client `workspace/archive-notice` waterfall supplies localized follow-up text and tone for the existing archive notice. `workspace/archive-followup-failed` replaces that notice after an admitted background operation fails, while preserving undo and the archive filter action.
|
||||
The client `workspace/archive-notice` waterfall supplies localized follow-up text and tone for the existing archive notice. `workspace/archive-followup-failed` replaces that notice after an admitted background operation fails, and `workspace/archive-followup-settled` returns to the plain notice when an announced follow-up ended without acting; both preserve undo and the archive filter action.
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## Model Experience
|
||||
|
||||
@@ -231,7 +231,7 @@ Workspace 与 Session 悬浮卡片会复制对应行被截断的值:激活 Wor
|
||||
|
||||
-----
|
||||
|
||||
客户端 `workspace/archive-notice` 瀑布为现有归档提示提供本地化的后续文本与色调。已接纳的后台操作失败时,`workspace/archive-followup-failed` 替换该提示,并保留撤销和归档筛选操作。
|
||||
客户端 `workspace/archive-notice` 瀑布为现有归档提示提供本地化的后续文本与色调。已接纳的后台操作失败时,`workspace/archive-followup-failed` 替换该提示;已宣告的后续工作未执行即结束时,`workspace/archive-followup-settled` 恢复普通提示;两者都保留撤销和归档筛选操作。
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
@@ -91,6 +91,12 @@ declare module '@deepseek-ai/cordis' {
|
||||
* @mode emit
|
||||
*/
|
||||
'workspace/archive-followup-failed'(sessionId: SessionId, text: string): void
|
||||
/**
|
||||
* Restore the plain archive notice when an announced follow-up ended without acting.
|
||||
* @param sessionId - Session whose successful archive remains in effect.
|
||||
* @mode emit
|
||||
*/
|
||||
'workspace/archive-followup-settled'(sessionId: SessionId): void
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,6 +225,9 @@ export function apply(ctx: Context): void {
|
||||
ctx.on('workspace/archive-followup-failed', (sessionId, text) => {
|
||||
if (archivedSet.getSnapshot().has(sessionId)) notify({ kind: 'archived', sessionId, message: text, tone: 'warning' })
|
||||
})
|
||||
ctx.on('workspace/archive-followup-settled', (sessionId) => {
|
||||
if (archivedSet.getSnapshot().has(sessionId)) notify({ kind: 'archived', sessionId })
|
||||
})
|
||||
const archiveNotice = async (sessionId: SessionId, kind: 'archived' | 'stoppedAndArchived'): Promise<void> => {
|
||||
let message: ArchiveNotice | undefined
|
||||
try {
|
||||
|
||||
@@ -950,6 +950,29 @@ it('keeps one archive notice for queued cleanup and replaces it on failure', asy
|
||||
expect(toast.hooks.toast.getSnapshot()?.seq).toBe(2)
|
||||
})
|
||||
|
||||
it('returns to the ordinary archive notice when a queued cleanup settles without acting', async () => {
|
||||
const b = await bench()
|
||||
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
vi.spyOn(b.ctx.uiWorkspace, 'archiveSession').mockResolvedValue(undefined)
|
||||
const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected
|
||||
const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected
|
||||
b.ctx.on('workspace/archive-notice', async (_id, next) => {
|
||||
await next()
|
||||
return { text: '已归档,工作树将被清理', tone: 'success' }
|
||||
})
|
||||
archive.archiveSession(sid('one'))
|
||||
await vi.waitFor(() => { expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'archived', message: '已归档,工作树将被清理', seq: 1 }) })
|
||||
b.setWorkspaces(workspaceState([], [sid('one')]))
|
||||
b.ctx.emit('workspace/archive-followup-settled', sid('one'))
|
||||
const settled = toast.hooks.toast.getSnapshot()
|
||||
expect(settled).toMatchObject({ kind: 'archived', seq: 2 })
|
||||
expect(settled).not.toHaveProperty('message')
|
||||
b.setWorkspaces(workspaceState([]))
|
||||
b.ctx.emit('workspace/archive-followup-settled', sid('one'))
|
||||
expect(toast.hooks.toast.getSnapshot()?.seq).toBe(2)
|
||||
})
|
||||
|
||||
it('falls back to the ordinary notice when a follow-up notice provider fails', async () => {
|
||||
const b = await bench()
|
||||
declare(b.slots, 'sidebar.workspaces', 'shell.overlay')
|
||||
|
||||
@@ -15,10 +15,10 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
|
||||
en: 4c40403cc468933b
|
||||
zh: c6a5c47059b14646
|
||||
en: 87757c920ff2cef4
|
||||
zh: 4bf1925d5d77bfd9
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: 80ba18c47e570e5e
|
||||
en: 0c2dd86b5f6b489d
|
||||
zh: 2f0fce0affa48f59
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
|
||||
@@ -30,7 +30,7 @@ Enable the [forge bundle](../forge-bundle/README.md) on the Plugins page; it com
|
||||
Panel text follows the application language: Chinese, English, Japanese, Spanish, French, German, Russian, or Portuguese.
|
||||
|
||||
- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector; the menu lists recent local branches. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh-<first 8 hexadecimal digits of the Session id>-<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists.
|
||||
- **Archive cleanup** — archiving reclaims clean worktrees created by the New Session option, while retaining branches and local commits. A queued cleanup uses the archive notice “Archived; the worktree will be cleaned up”. Dirty, untracked, ignored, shared, locked, detached, or uncertain checkouts remain without an extra notice. Running work or persistent terminals also retain the checkout. Cleanup failures leave the Session archived and report a warning. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow. Older archived Sessions are not swept.
|
||||
- **Archive cleanup** — archiving a Session lets the [worktree service](../worktree/README.md) reclaim the clean, unreferenced worktree it created, whether through the New Session option or the model's `create_worktree` tool, while retaining the branch and its commits. A scheduled cleanup uses the archive notice “Archived; the worktree will be cleaned up”; one that ends retained returns to the ordinary notice, and one that fails replaces it with a warning while the Session stays archived. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow.
|
||||
- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its two steps, creating the branch and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again with a new branch name, and Continue without a worktree withdraws the request so the message goes on in the current checkout.
|
||||
- **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the tab, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the tab's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the tab's first row shows a warning glyph.
|
||||
- **Code review and changes** — on the right-sidebar start page, opens the same change request tab as the Session header button.
|
||||
@@ -60,7 +60,7 @@ All files opens a searchable directory tree. Single-child directories share a ro
|
||||
|
||||
Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --short HEAD`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `branches` runs `symbolic-ref` and `for-each-ref --count=<maxBranches>`; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes card: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy.
|
||||
|
||||
A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first `created` record of an open request applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, and with `forgePanel/invalid-branch` for an empty branch; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt with a new branch name, publishing the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, failed step, and reason stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, refused with `forgePanel/not-waiting` while none waits or one runs, and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. The bundle isolates its `worktrees` service, so enabling Git Worktrees as well leaves two independent services. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason.
|
||||
A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, and with `forgePanel/invalid-branch` for an empty branch; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt with a new branch name, publishing the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, failed step, and reason stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, refused with `forgePanel/not-waiting` while none waits or one runs, and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason.
|
||||
|
||||
|
||||
Restoration records `restoring` before mutation and `restored` only after success. Projection version 3 retains incomplete restoration across reloads. Directory existence alone cannot release a waiting message: the checkout root and shared Git directory must match the recorded worktree. Plugin unload cancels and joins all creation, restoration, and waiting tasks before releasing panel readers and the projection.
|
||||
|
||||
@@ -30,7 +30,7 @@ kind: "package-reference"
|
||||
面板文案跟随应用语言,支持中文、英文、日语、西班牙语、法语、德语、俄语和葡萄牙语。
|
||||
|
||||
- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器,菜单列出最近的本地分支。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh-<Session id 前 8 位十六进制数>-<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。
|
||||
- **归档清理**——归档会自动回收通过新会话选项创建的干净工作树,保留分支和本地提交。清理排队后,归档提示为“已归档,工作树将被清理”。有修改、未跟踪或忽略文件、仍被共享、锁定、分离 HEAD 或无法确认安全的工作树会保留,不额外提示。仍在运行的任务或持久终端也会阻止清理。清理失败时保留归档并显示警告。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。不会扫描清理此前已归档的会话。
|
||||
- **归档清理**——归档一个会话后,由[工作树服务](../worktree/README.zh.md)回收它创建的干净且无人引用的工作树,无论来自新会话选项还是模型的 `create_worktree` 工具,分支及其提交保留。清理排队后,归档提示为“已归档,工作树将被清理”;最终保留时恢复为普通归档提示,失败时替换为警告而会话仍保持归档。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。
|
||||
- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支以及“创建分支”“检出文件”两个步骤;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”换一个新分支名再试;“不使用工作树”撤回请求,消息在当前检出中继续发送。
|
||||
- **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(标签页中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,标签页中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间标签页顶部一行显示警示图标。
|
||||
- **代码审查和变更**——右侧栏起始页中的入口,与会话标题栏按钮打开同一个变更请求标签页。
|
||||
|
||||
@@ -111,12 +111,7 @@
|
||||
"@deepseek-ai/dsh-timeout": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection-cache": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-query": "workspace:*",
|
||||
"@deepseek-ai/dsh-api-remote-access": "workspace:*",
|
||||
"@deepseek-ai/dsh-workspace": "workspace:*",
|
||||
"@deepseek-ai/dsh-terminal": "workspace:*",
|
||||
"@deepseek-ai/dsh-storage": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*",
|
||||
"@deepseek-ai/dsh-jobs": "workspace:*"
|
||||
"@deepseek-ai/dsh-api-remote-access": "workspace:*"
|
||||
},
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
|
||||
@@ -75,7 +75,9 @@ function registerUi(ctx: Context): void {
|
||||
if (status === 'failed') return { text: t('toast.archiveCleanupFailed'), tone: 'warning' }
|
||||
if (status !== 'scheduled') return fallback
|
||||
void ctx.remote.forgePanel.worktreeCleanup(sessionId, revision).then((completed) => {
|
||||
if (!lifetime.signal.aborted && completed.ok && completed.value?.status === 'failed') ctx.emit('workspace/archive-followup-failed', sessionId, t('toast.archiveCleanupFailed'))
|
||||
if (lifetime.signal.aborted || !completed.ok || completed.value === null) return
|
||||
if (completed.value.status === 'failed') ctx.emit('workspace/archive-followup-failed', sessionId, t('toast.archiveCleanupFailed'))
|
||||
else if (completed.value.status === 'retained') ctx.emit('workspace/archive-followup-settled', sessionId)
|
||||
}).catch((error: unknown) => {
|
||||
if (!lifetime.signal.aborted) console.warn('archive worktree cleanup result unavailable:', error)
|
||||
})
|
||||
|
||||
@@ -7,7 +7,7 @@ import type {} from '@deepseek-ai/dsh-api-remote-access'
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeReviewRequest, ForgeReviewResult, MergeMethod } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
|
||||
import type {} from '@deepseek-ai/dsh-experimental-worktree'
|
||||
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
|
||||
import { appendPluginRecord } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
@@ -27,10 +27,9 @@ import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts'
|
||||
import type { PanelConfig } from './panel.ts'
|
||||
import type {
|
||||
Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope,
|
||||
ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, ForgeWorktreeCleanup, ForgeWorktreeRetention,
|
||||
ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState,
|
||||
} from './types.ts'
|
||||
import { WorktreeArchives } from './worktree-archive.ts'
|
||||
import { forgeWorktreeRetentionProjection, forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts'
|
||||
import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts'
|
||||
import type { HeldWork } from './worktree.ts'
|
||||
|
||||
export type * from './types.ts'
|
||||
@@ -83,8 +82,6 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
private readonly panels = new Map<Session, SessionPanel>()
|
||||
private worktreeStates!: ProjectionHandle<ForgeWorktreeState>
|
||||
private creations!: WorktreeCreations
|
||||
private archives: WorktreeArchives | undefined
|
||||
private retention!: ProjectionHandle<ForgeWorktreeRetention>
|
||||
private readonly patches: PatchCache
|
||||
private states: ChangeRequestStates | undefined
|
||||
private readonly stopPanels: () => Promise<void>
|
||||
@@ -124,7 +121,6 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
inject: ['sessionProjections'],
|
||||
apply: async (scope: Context) => {
|
||||
this.worktreeStates = await scope.sessionProjections.register(forgeWorktreeProjection)
|
||||
this.retention = await scope.sessionProjections.register(forgeWorktreeRetentionProjection)
|
||||
},
|
||||
})
|
||||
await stateOwner
|
||||
@@ -132,11 +128,6 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
this.creations = new WorktreeCreations(ctx, this.worktreeStates, this.config.worktreePrefix, (session) => {
|
||||
this.panels.get(session)?.updateWorktree()
|
||||
})
|
||||
const archiveOwner = ctx.inject(['workspaceRegistry', 'sessionQuery', 'worktrees'], (scope) => {
|
||||
const archives = new WorktreeArchives(scope, this.retention)
|
||||
this.archives = archives
|
||||
scope.effect(() => () => { this.archives = undefined })
|
||||
})
|
||||
const inbox = ctx.on('agent/inbox/inserted', ({ agent }) => { this.holdTurn(agent) })
|
||||
const events = ctx.on('session/event', (session: Session, event: SessionEvent) => {
|
||||
this.panels.get(session)?.observe(event)
|
||||
@@ -154,7 +145,6 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
yield stopPanels
|
||||
yield stopStates
|
||||
yield creations.dispose
|
||||
yield archiveOwner.dispose
|
||||
}, 'forge-panel: drain before releasing state')
|
||||
}
|
||||
|
||||
@@ -190,14 +180,14 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read or await an archive cleanup owned by this Host lifetime.
|
||||
* Read or await the worktree service's archive cleanup of the Session's checkout.
|
||||
* @param session - Session whose cleanup is visible to the caller.
|
||||
* @param revision - null reads now; a matching revision waits for completion.
|
||||
* @returns the cleanup state, or null when none exists or the revision was superseded.
|
||||
* @returns the cleanup state, or null without a worktree service, an attempt, or a current revision.
|
||||
*/
|
||||
@Remote
|
||||
async worktreeCleanup(session: Session, revision: number | null): Promise<ForgeWorktreeCleanup | null> {
|
||||
return await this.archives?.result(session, revision) ?? null
|
||||
async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null> {
|
||||
return await this.home.get('worktrees')?.cleanupOf(session, revision) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -54,19 +54,6 @@ export type WorktreeRecord =
|
||||
/** The recorded worktree was completely restored. */
|
||||
| { readonly action: 'restored' }
|
||||
|
||||
/** Recoverable creation ownership; forks retain references without becoming creators. */
|
||||
export interface ForgeWorktreeRetention {
|
||||
readonly state: ForgeWorktreeState
|
||||
readonly inheritedEventCount: number
|
||||
readonly owned: boolean
|
||||
}
|
||||
|
||||
/** Process-local result of one archive-triggered cleanup attempt. */
|
||||
export interface ForgeWorktreeCleanup {
|
||||
readonly revision: number
|
||||
readonly status: 'scheduled' | 'retained' | 'removed' | 'failed'
|
||||
}
|
||||
|
||||
/** One open worktree request. */
|
||||
export interface ForgeWorktreeRequest {
|
||||
/** Base branch, or null for HEAD of the source checkout. */
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
/** Archive-triggered reclamation of UI-owned checkouts, independent of open panel followers. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type {} from '@deepseek-ai/dsh-session-query'
|
||||
import type {} from '@deepseek-ai/dsh-terminal'
|
||||
import type {} from '@deepseek-ai/dsh-jobs/view'
|
||||
import type {} from '@deepseek-ai/dsh-workspace'
|
||||
import type { ForgeSessionWorktree, ForgeWorktreeCleanup, ForgeWorktreeRetention } from './types.ts'
|
||||
import { within } from './worktree.ts'
|
||||
|
||||
interface Attempt {
|
||||
readonly worktree: ForgeSessionWorktree
|
||||
readonly revision: number
|
||||
status: ForgeWorktreeCleanup['status']
|
||||
cancelled: boolean
|
||||
done: Promise<void>
|
||||
}
|
||||
|
||||
/** Owns pending cleanup, serializes directory entry, and drains before its providers are released. */
|
||||
export class WorktreeArchives {
|
||||
private readonly attempts = new Map<SessionId, Attempt>()
|
||||
private readonly pending = new Set<Promise<unknown>>()
|
||||
private readonly lifetime = new AbortController()
|
||||
private tail: Promise<void> = Promise.resolve()
|
||||
private revision = 0
|
||||
/** Withdraw listeners and settle accepted work. */
|
||||
readonly dispose: () => Promise<void>
|
||||
|
||||
/**
|
||||
* @param ctx - panel context with Workspace, query, and worktree providers.
|
||||
* @param retention - authoritative UI creation and directory projection.
|
||||
*/
|
||||
constructor(private readonly ctx: Context, private readonly retention: ProjectionHandle<ForgeWorktreeRetention>) {
|
||||
const archive = ctx.on('workspace/session-archived', ({ sessionId }) => this.archive(sessionId))
|
||||
const unarchive = ctx.on('workspace/session-unarchiving', async ({ sessionId }) => {
|
||||
// A fork can hold the same checkout as the Session whose archive scheduled removal.
|
||||
const state = await ctx.sessionQuery.inspectSession(sessionId, session => this.retention.stateOf(session)).catch((error: unknown) => {
|
||||
ctx.logger.warn('Cancelling archive cleanup because the restored Session could not be inspected: %s', error)
|
||||
return null
|
||||
})
|
||||
for (const [id, attempt] of this.attempts) {
|
||||
if (state === null || id === sessionId || state.state.created?.path === attempt.worktree.path
|
||||
|| (state.state.cwd !== null && within(attempt.worktree.path, state.state.cwd))) attempt.cancelled = true
|
||||
}
|
||||
await this.exclusive(async () => {})
|
||||
this.attempts.delete(sessionId)
|
||||
})
|
||||
const directory = ctx.on('working-directory/access', ({ agent, path }, next) => this.exclusive(async () => {
|
||||
const state = this.retention.stateOf(agent.session).state
|
||||
const current = ctx.workingDirectory.get(agent.session)
|
||||
if (path === null && state.created !== null && within(state.created.path, current)
|
||||
&& (await ctx.fs.stat(await ctx.fs.resolve(current, { signal: this.lifetime.signal }), this.lifetime.signal))?.type !== 'directory') {
|
||||
throw new Error('The archived worktree is unavailable; restore it or select a working directory before continuing')
|
||||
}
|
||||
return await next()
|
||||
}))
|
||||
const drain = ctx.effect(() => async () => {
|
||||
this.lifetime.abort(new Error('Worktree archive cleanup stopped'))
|
||||
for (const attempt of this.attempts.values()) attempt.cancelled = true
|
||||
await Promise.allSettled(this.pending)
|
||||
this.attempts.clear()
|
||||
})
|
||||
this.dispose = ctx.effect(function* () {
|
||||
yield archive
|
||||
yield unarchive
|
||||
yield directory
|
||||
yield drain
|
||||
}, 'forge-panel: drain archive cleanup')
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the most recent archive attempt; waiting never initiates cleanup.
|
||||
* @param session - archived Session visible to the Remote caller.
|
||||
* @param revision - null reads immediately; a matching revision waits for that attempt.
|
||||
* @returns the attempt state, or null when absent or superseded.
|
||||
*/
|
||||
async result(session: Session, revision: number | null): Promise<ForgeWorktreeCleanup | null> {
|
||||
const attempt = this.attempts.get(session.id)
|
||||
if (attempt === undefined || (revision !== null && revision !== attempt.revision)) return null
|
||||
if (revision !== null) await attempt.done
|
||||
if (this.lifetime.signal.aborted) return null
|
||||
return { revision: attempt.revision, status: attempt.status }
|
||||
}
|
||||
|
||||
private async archive(sessionId: SessionId): Promise<void> {
|
||||
const ctx = this.ctx
|
||||
const worktrees = ctx.worktrees
|
||||
const candidate = await this.exclusive(async () => {
|
||||
const own = await ctx.sessionQuery.inspectSession(sessionId, session => this.retention.stateOf(session), this.lifetime.signal)
|
||||
let worktree = own.state.created
|
||||
if (worktree === null && own.state.cwd !== null) {
|
||||
for (const record of await ctx.sessionQuery.listSessions(this.lifetime.signal)) {
|
||||
const source = await ctx.sessionQuery.inspectSession(
|
||||
record.header.id, session => this.retention.stateOf(session), this.lifetime.signal,
|
||||
)
|
||||
if (source.owned && source.state.created !== null && within(source.state.created.path, own.state.cwd)) {
|
||||
worktree = source.state.created
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (worktree === null) return null
|
||||
const policy = await this.unused(worktree)
|
||||
if (policy === null) return null
|
||||
if (!await worktrees.canRemove(policy, worktree, this.lifetime.signal)) return null
|
||||
return worktree
|
||||
}).catch((error: unknown) => {
|
||||
ctx.logger.warn('Session %s archived; its worktree was retained because inspection failed: %s', sessionId, error)
|
||||
return null
|
||||
})
|
||||
if (candidate === null || this.lifetime.signal.aborted) return
|
||||
const attempt: Attempt = {
|
||||
worktree: candidate, revision: ++this.revision, status: 'scheduled', cancelled: false, done: Promise.resolve(),
|
||||
}
|
||||
this.attempts.set(sessionId, attempt)
|
||||
attempt.done = this.exclusive(async () => {
|
||||
const policy = await this.unused(candidate)
|
||||
if (policy === null) {
|
||||
attempt.status = 'retained'
|
||||
return
|
||||
}
|
||||
// Inspection is repeated by remove, after the final application-level use check.
|
||||
attempt.status = await worktrees.remove(policy, candidate, this.lifetime.signal, () => !attempt.cancelled) ? 'removed' : 'retained'
|
||||
}).catch((error: unknown) => {
|
||||
attempt.status = 'failed'
|
||||
ctx.logger.warn('Session %s archived; cleanup of %s failed and its branch was retained: %s', sessionId, candidate.path, error)
|
||||
})
|
||||
}
|
||||
|
||||
private async unused(worktree: ForgeSessionWorktree): Promise<SandboxExecutionPolicy | null> {
|
||||
const ctx = this.ctx
|
||||
this.lifetime.signal.throwIfAborted()
|
||||
const archived = new Set(ctx.workspaceRegistry.archivedSessionIds)
|
||||
let owners = 0
|
||||
let ownerPolicy: SandboxExecutionPolicy | null = null
|
||||
const records = await ctx.sessionQuery.listSessions(this.lifetime.signal)
|
||||
for (const record of records) {
|
||||
const { value, policy } = await ctx.sessionQuery.inspectSession(record.header.id, session => ({
|
||||
value: this.retention.stateOf(session), policy: ctx.sandboxPolicy.resolve({ session }),
|
||||
}), this.lifetime.signal)
|
||||
const created = value.state.created
|
||||
const same = created?.path === worktree.path && created.branch === worktree.branch
|
||||
&& created.repositoryRoot === worktree.repositoryRoot && created.baseCommit === worktree.baseCommit
|
||||
if (same && value.state.restoring) return null
|
||||
if (same && value.owned) { owners++; ownerPolicy = policy }
|
||||
if (!archived.has(record.header.id) && (same || (value.state.cwd !== null && within(worktree.path, value.state.cwd)))) return null
|
||||
}
|
||||
if (owners !== 1 || ownerPolicy?.mode === 'read-only') return null
|
||||
// Processes keep their original cwd after a Session changes directory. An idle PTY
|
||||
// or a surviving job is conservatively retained even when its present cwd is unknown.
|
||||
for (const agent of ctx.agents.list()) {
|
||||
const current = ctx.workingDirectory.get(agent.session)
|
||||
const origin = this.retention.stateOf(agent.session).state.created
|
||||
const related = within(worktree.path, current) || origin?.path === worktree.path
|
||||
const activity = await ctx.waterfall('workspace/session-activity', { sessionId: agent.session.id }, () => Promise.resolve([]))
|
||||
if ((related && (activity.length > 0 || agent.status === 'running')) || activity.some(item => item.kind === 'job')
|
||||
|| ctx.get('terminals')?.list(agent).some(terminal => terminal.status.kind === 'running') === true) return null
|
||||
if (!archived.has(agent.session.id) && related) return null
|
||||
}
|
||||
return ownerPolicy
|
||||
}
|
||||
|
||||
private exclusive<T>(body: () => Promise<T>): Promise<T> {
|
||||
const operation = this.tail.then(() => {
|
||||
this.lifetime.signal.throwIfAborted()
|
||||
return body()
|
||||
})
|
||||
this.tail = operation.then(() => {}, () => {})
|
||||
this.pending.add(operation)
|
||||
void operation.then(() => { this.pending.delete(operation) }, () => { this.pending.delete(operation) })
|
||||
return operation
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { isAbsolute, relative, sep } from 'node:path'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
|
||||
import { generatedWorktreeName } from '@deepseek-ai/dsh-experimental-worktree'
|
||||
import { CREATED_RECORD, generatedWorktreeName } from '@deepseek-ai/dsh-experimental-worktree'
|
||||
import type { CreatedWorktree, CreateWorktreePhase } from '@deepseek-ai/dsh-experimental-worktree'
|
||||
import { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
@@ -13,7 +13,7 @@ import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import { z } from 'zod'
|
||||
import type {
|
||||
ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRestoration, ForgeWorktreeState,
|
||||
ForgeWorktreeWaiting, WorktreeRecord, ForgeWorktreeRetention,
|
||||
ForgeWorktreeWaiting, WorktreeRecord,
|
||||
} from './types.ts'
|
||||
|
||||
/** Plugin record type of worktree requests, withdrawals, and creations. */
|
||||
@@ -21,6 +21,13 @@ export const WORKTREE_RECORD = 'plugin:client-ui-forge/worktree'
|
||||
|
||||
const EMPTY: Omit<ForgeWorktreeState, 'cwd'> = { request: null, created: null, locked: false, stepped: false, restoring: false }
|
||||
|
||||
const createdSchema: z.ZodType<CreatedWorktree> = z.object({
|
||||
path: z.string().min(1),
|
||||
branch: z.string().min(1),
|
||||
baseCommit: z.string().min(1),
|
||||
repositoryRoot: z.string().min(1),
|
||||
}).strict()
|
||||
|
||||
const worktreeSchema: z.ZodType<ForgeSessionWorktree> = z.object({
|
||||
path: z.string().min(1),
|
||||
branch: z.string().min(1),
|
||||
@@ -48,16 +55,18 @@ const stateSchema: z.ZodType<ForgeWorktreeState> = z.object({
|
||||
|
||||
/**
|
||||
* The `forgeWorktree` unit. `request` and `cancel` records change the request
|
||||
* until the first `turn/start` or creation; the first `created` record of an
|
||||
* open request applies until the first `step/start`. Records outside those
|
||||
* periods leave the state unchanged. The unit also follows the Session's
|
||||
* working directory, so clients, including the Session summary, see the
|
||||
* created worktree only while that directory is the worktree or lies below it.
|
||||
* Restoration records retain incomplete checkout recovery across reloads.
|
||||
* until the first `turn/start` or creation; the first creation of an open
|
||||
* request applies until the first `step/start`, read from the worktree
|
||||
* service's `plugin:worktree/created` record, or from the `created` record that
|
||||
* earlier panels wrote. Records outside those periods leave the state
|
||||
* unchanged. The unit also follows the Session's working directory, so
|
||||
* clients, including the Session summary, see the created worktree only while
|
||||
* that directory is the worktree or lies below it. Restoration records retain
|
||||
* incomplete checkout recovery across reloads.
|
||||
*/
|
||||
export const forgeWorktreeProjection = {
|
||||
key: 'forgeWorktree',
|
||||
stateVersion: 4,
|
||||
stateVersion: 5,
|
||||
stateSchema,
|
||||
init: header => ({ ...EMPTY, cwd: header.cwd ?? null }),
|
||||
apply,
|
||||
@@ -67,27 +76,6 @@ export const forgeWorktreeProjection = {
|
||||
},
|
||||
} satisfies ProjectionDefinition<'forgeWorktree', ForgeWorktreeState>
|
||||
|
||||
const retentionSchema: z.ZodType<ForgeWorktreeRetention> = z.object({
|
||||
state: stateSchema,
|
||||
inheritedEventCount: z.number().int().nonnegative(),
|
||||
owned: z.boolean(),
|
||||
}).strict()
|
||||
|
||||
/** Full UI creation facts for archive safety, including after the Session leaves its checkout. */
|
||||
export const forgeWorktreeRetentionProjection = {
|
||||
key: 'forgeWorktreeRetention',
|
||||
stateVersion: 1,
|
||||
stateSchema: retentionSchema,
|
||||
init: (header, inheritedEventCount) => ({ state: forgeWorktreeProjection.init(header), inheritedEventCount, owned: false }),
|
||||
apply: (retention, event) => {
|
||||
const state = apply(retention.state, event)
|
||||
if (state === retention.state) return retention
|
||||
const owned = retention.owned
|
||||
|| (retention.state.created === null && state.created !== null && event.seq >= retention.inheritedEventCount)
|
||||
return { ...retention, state, owned }
|
||||
},
|
||||
} satisfies ProjectionDefinition<'forgeWorktreeRetention', ForgeWorktreeRetention>
|
||||
|
||||
/**
|
||||
* Whether `path` is `root` or lies below it.
|
||||
* @param root - absolute directory.
|
||||
@@ -124,6 +112,12 @@ function apply(state: ForgeWorktreeState, event: SessionEvent): ForgeWorktreeSta
|
||||
|
||||
function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorktreeState {
|
||||
const record = pluginRecordOf(event)
|
||||
if (record?.type === CREATED_RECORD) {
|
||||
const created = createdSchema.safeParse(record.data)
|
||||
return !created.success || state.created !== null || state.stepped || state.request === null
|
||||
? state
|
||||
: { ...state, created: { ...created.data, from: state.request.from } }
|
||||
}
|
||||
if (record?.type !== WORKTREE_RECORD) return state
|
||||
const parsed = recordSchema.safeParse(record.data)
|
||||
if (!parsed.success) return state
|
||||
@@ -443,13 +437,9 @@ export class WorktreeCreations {
|
||||
throw new CreationFailure(status.branch, status.phase, messageOf(error), error)
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
const worktree: ForgeSessionWorktree = {
|
||||
path: created.path, branch: created.branch, from, baseCommit: created.baseCommit, repositoryRoot: created.repositoryRoot,
|
||||
}
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'created', worktree })
|
||||
return created
|
||||
} finally {
|
||||
// After the record, so a follower never sees the creation end without its result.
|
||||
// After the service's `plugin:worktree/created` record, so a follower never sees the creation end without its result.
|
||||
this.live.delete(session)
|
||||
this.changed(session)
|
||||
}
|
||||
|
||||
@@ -820,7 +820,8 @@ describe('forgePanel worktree requests', () => {
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: null }, locked: false, stepped: false, restoring: false })
|
||||
expect(opened.records).toHaveLength(2)
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('refuses worktree requests and restoration without a worktree service, and keeps a waiting message for the withdrawal', async () => {
|
||||
@@ -952,7 +953,8 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(created?.path)
|
||||
expect(opened.agent.inbox.nextStep).toEqual([notice(created?.path ?? '')])
|
||||
expect(queued(opened)).toEqual(['first'])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }, { action: 'created', worktree: created }])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toEqual([{ path: created?.path, branch: created?.branch, baseCommit: created?.baseCommit, repositoryRoot: created?.repositoryRoot }])
|
||||
})
|
||||
|
||||
it('keeps the message waiting with the failure the panel shows, and tries again with a new branch when asked', async () => {
|
||||
@@ -980,7 +982,8 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
expect(created?.branch).not.toBe(failed.worktree.failure?.branch)
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
expect(queued(opened)).toEqual(['first'])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: 'later' }, { action: 'created', worktree: created }])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: 'later' }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps the message waiting when the request changes, and lets it go on in the current checkout once the request is withdrawn', async () => {
|
||||
@@ -1124,7 +1127,8 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
expect(queued(opened)).toEqual(['first', 'second'])
|
||||
expect(opened.records).toHaveLength(2)
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('leaves a message that arrives while the Agent has other work to the first step', async () => {
|
||||
@@ -1181,7 +1185,8 @@ describe('forgePanel worktree requests during a creation', () => {
|
||||
const created = worktreeState(opened)?.created ?? null
|
||||
expect(created).toMatchObject({ from: null, repositoryRoot: repo })
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(created?.path)
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }, { action: 'created', worktree: created }])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import WorkingDirectoryService from '@deepseek-ai/dsh-working-directory'
|
||||
import ForgePanelController from '../src/index.ts'
|
||||
import type { Config, ForgePanelState, ForgeWorktreeState } from '../src/index.ts'
|
||||
import { CREATED_RECORD } from '@deepseek-ai/dsh-experimental-worktree'
|
||||
import { forgeWorktreeProjection, WORKTREE_RECORD } from '../src/worktree.ts'
|
||||
|
||||
const execute = promisify(execFile)
|
||||
@@ -498,6 +499,8 @@ export interface Runtime {
|
||||
readonly agent: TestAgent
|
||||
/** Data of the Session's worktree records in log order. */
|
||||
readonly records: unknown[]
|
||||
/** Data of the worktree service's creation records for the Session, in log order. */
|
||||
readonly created: unknown[]
|
||||
/** Fiber of the worktree service, or undefined when it is not mounted. */
|
||||
readonly worktrees: ReturnType<Context['plugin']> | undefined
|
||||
}
|
||||
@@ -543,13 +546,16 @@ export async function runtime(cwd: string, options: BenchOptions = {}): Promise<
|
||||
if (worktrees !== undefined) await worktrees
|
||||
const session = ctx.sessions.create(SessionId(`forge-panel-${Math.random().toString(36).slice(2)}`), { meta: { cwd } })
|
||||
const records: unknown[] = []
|
||||
const created: unknown[] = []
|
||||
ctx.on('session/event', (target: Session, event: SessionEvent) => {
|
||||
const record = pluginRecordOf(event)
|
||||
if (target === session && record?.type === WORKTREE_RECORD) records.push(record.data)
|
||||
if (target !== session) return
|
||||
if (record?.type === WORKTREE_RECORD) records.push(record.data)
|
||||
if (record?.type === CREATED_RECORD) created.push(record.data)
|
||||
})
|
||||
const agent = testAgent(ctx, session)
|
||||
await ctx.agents.register(agent)
|
||||
return { ctx, provider, sandbox, session, agent, records, worktrees }
|
||||
return { ctx, provider, sandbox, session, agent, records, created, worktrees }
|
||||
} catch (error) {
|
||||
await ctx.fiber.dispose()
|
||||
throw error
|
||||
|
||||
@@ -29,8 +29,9 @@ import type { NoticeSource } from '../src/client/source.ts'
|
||||
import type { ReviewSelection } from '../src/client/review.ts'
|
||||
import { WorktreeProgress, type WorktreeProgressInjected } from '../src/client/WorktreeProgress.tsx'
|
||||
import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx'
|
||||
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
|
||||
import type {
|
||||
ForgeWorktreeCleanup, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame,
|
||||
ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame,
|
||||
ForgeLocalDiff, ForgeLocalScope, ForgePanelState,
|
||||
} from '../src/types.ts'
|
||||
import { entry, listState, ready, snapshot, unserved } from './client-fixtures.client.ts'
|
||||
@@ -145,7 +146,7 @@ async function base() {
|
||||
stateStreams.push(handle)
|
||||
return handle
|
||||
}),
|
||||
worktreeCleanup: vi.fn(async (_sessionId: SessionId, _revision: number | null): Promise<RemoteResult<ForgeWorktreeCleanup | null>> =>
|
||||
worktreeCleanup: vi.fn(async (_sessionId: SessionId, _revision: number | null): Promise<RemoteResult<WorktreeCleanup | null>> =>
|
||||
({ ok: true, value: null })),
|
||||
track: vi.fn(async (_sessionId: SessionId, _url: string): Promise<RemoteResult<void>> => OK),
|
||||
dismiss: vi.fn(async (_sessionId: SessionId, _url: string): Promise<RemoteResult<void>> => OK),
|
||||
@@ -866,7 +867,7 @@ describe('archive notices', () => {
|
||||
try {
|
||||
const failed = vi.fn()
|
||||
f.ctx.on('workspace/archive-followup-failed', failed)
|
||||
const settled = Promise.withResolvers<RemoteResult<ForgeWorktreeCleanup | null>>()
|
||||
const settled = Promise.withResolvers<RemoteResult<WorktreeCleanup | null>>()
|
||||
f.forgePanel.worktreeCleanup.mockImplementation(async (_id, revision) => revision === null
|
||||
? { ok: true, value: { revision: 1, status: 'scheduled' } }
|
||||
: await settled.promise)
|
||||
@@ -888,6 +889,18 @@ describe('archive notices', () => {
|
||||
} finally { await f.ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('restores the ordinary notice when a scheduled cleanup ends retained', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const settled = vi.fn()
|
||||
f.ctx.on('workspace/archive-followup-settled', settled)
|
||||
f.forgePanel.worktreeCleanup.mockImplementation(async (_id, revision) => ({ ok: true, value: { revision: 1, status: revision === null ? 'scheduled' : 'retained' } }))
|
||||
expect(await f.ctx.waterfall('workspace/archive-notice', S1, () => Promise.resolve({ text: 'fallback', tone: 'success' as const })))
|
||||
.toEqual({ text: en['toast.archiveCleanupScheduled'], tone: 'success' })
|
||||
await vi.waitFor(() => { expect(settled).toHaveBeenCalledWith(S1) })
|
||||
} finally { await f.ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('uses a warning for an already failed cleanup and falls back when its result is unavailable', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
@@ -910,7 +923,7 @@ describe('archive notices', () => {
|
||||
.mockRejectedValueOnce(new Error('connection lost'))
|
||||
await f.ctx.waterfall('workspace/archive-notice', S1, () => Promise.resolve(undefined))
|
||||
await vi.waitFor(() => { expect(warning).toHaveBeenCalledTimes(1) })
|
||||
const completed = Promise.withResolvers<RemoteResult<ForgeWorktreeCleanup | null>>()
|
||||
const completed = Promise.withResolvers<RemoteResult<WorktreeCleanup | null>>()
|
||||
f.forgePanel.worktreeCleanup.mockResolvedValueOnce({ ok: true, value: { revision: 2, status: 'scheduled' } })
|
||||
.mockImplementationOnce(async () => await completed.promise)
|
||||
await f.ctx.waterfall('workspace/archive-notice', S1, () => Promise.resolve(undefined))
|
||||
|
||||
@@ -1,321 +0,0 @@
|
||||
import { access, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import Storage from '@deepseek-ai/dsh-storage'
|
||||
import { DomainFacility } from '@deepseek-ai/dsh-storage-domain'
|
||||
import { appendPluginRecord, Session, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
|
||||
import * as SessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import SessionQueryEngine from '@deepseek-ai/dsh-session-query'
|
||||
import type { SessionEventSearchPage, SessionSearchPage, SessionSearchHit } from '@deepseek-ai/dsh-session-query'
|
||||
import TerminalService, { TerminalSessionId } from '@deepseek-ai/dsh-terminal'
|
||||
import WorkspaceRegistry from '@deepseek-ai/dsh-workspace'
|
||||
import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts'
|
||||
import ForgePanelController from '../src/index.ts'
|
||||
import { WorktreeArchives } from '../src/worktree-archive.ts'
|
||||
import { forgeWorktreeRetentionProjection, WORKTREE_RECORD } from '../src/worktree.ts'
|
||||
import { repository, runtime, scratch, testAgent } from './harness.ts'
|
||||
|
||||
/** Archive tests only use the query service's live and persisted observation APIs. */
|
||||
class ArchiveQueries extends SessionQueryEngine {
|
||||
searchSessions(): Promise<SessionSearchPage<SessionSearchHit>> { throw new Error('search is not used') }
|
||||
searchEvents(): Promise<SessionEventSearchPage> { throw new Error('search is not used') }
|
||||
}
|
||||
|
||||
const cleanups: (() => Promise<void>)[] = []
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function fixture() {
|
||||
const temporary = await scratch('archive-worktree-')
|
||||
cleanups.push(temporary.remove)
|
||||
const root = await repository(temporary.path)
|
||||
const f = await runtime(root, { worktrees: true })
|
||||
cleanups.push(() => f.ctx.fiber.dispose())
|
||||
const ctx = f.ctx
|
||||
await ctx.plugin(SessionPersistence, { root: join(temporary.path, 'sessions'), compression: 'none' })
|
||||
await ctx.plugin(ArchiveQueries)
|
||||
await ctx.plugin(Storage)
|
||||
const pool = new MemoryMediaPool()
|
||||
ctx.storage.backend.register('memory', new MemoryStorageBackend(pool))
|
||||
const domain = new DomainFacility(ctx, { backend: 'memory', routes: {} })
|
||||
ctx.storage.mount('domain', domain)
|
||||
ctx.provide('storageDomain', domain)
|
||||
await ctx.plugin(WorkspaceRegistry)
|
||||
const retention = await ctx.sessionProjections.register(forgeWorktreeRetentionProjection)
|
||||
const archives = new WorktreeArchives(ctx, retention)
|
||||
appendPluginRecord(f.session, WORKTREE_RECORD, { action: 'request', from: null })
|
||||
const worktree = { ...await ctx.worktrees.create(f.agent, { name: 'archive-ui' }), from: null }
|
||||
appendPluginRecord(f.session, WORKTREE_RECORD, { action: 'created', worktree })
|
||||
return { ...f, root, worktree, archives, retention }
|
||||
}
|
||||
|
||||
async function completed(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
const first = await f.archives.result(f.session, null)
|
||||
return first === null ? null : await f.archives.result(f.session, first.revision)
|
||||
}
|
||||
|
||||
describe('UI worktree archive cleanup', () => {
|
||||
it('cleans a UI checkout after the Session moved elsewhere and blocks implicit fallback on restore', async () => {
|
||||
const f = await fixture()
|
||||
await f.ctx.workingDirectory.set(f.agent, f.root)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toMatchObject({ status: 'removed' })
|
||||
await expect(access(f.worktree.path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
await f.ctx.worktrees.restore(f.agent, f.worktree)
|
||||
await f.ctx.workingDirectory.set(f.agent, f.worktree.path)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toMatchObject({ status: 'removed' })
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
await expect(f.ctx.workingDirectory.ensure(f.agent)).rejects.toThrow('restore it')
|
||||
expect(f.ctx.workingDirectory.get(f.session)).toBe(f.worktree.path)
|
||||
})
|
||||
|
||||
it('retains a shared checkout until the last fork archives, without transferring creation ownership', async () => {
|
||||
const f = await fixture()
|
||||
using observation = await f.ctx.sessionQuery.observeSession(f.session.id)
|
||||
const fork = f.ctx.sessions.create(SessionId('archive-fork'), {
|
||||
seed: observation.events, inheritedEventCount: SessionLogOffset(observation.events.length),
|
||||
meta: { cwd: f.root, isSeeded: true },
|
||||
})
|
||||
const agent = testAgent(f.ctx, fork)
|
||||
await f.ctx.agents.register(agent)
|
||||
expect(f.retention.stateOf(f.session).owned).toBe(true)
|
||||
expect(f.retention.stateOf(fork).owned).toBe(false)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
await f.ctx.workspaceRegistry.archiveSession(fork.id)
|
||||
const first = await f.archives.result(fork, null)
|
||||
expect(first).not.toBeNull()
|
||||
expect(await f.archives.result(fork, first!.revision)).toMatchObject({ status: 'removed' })
|
||||
})
|
||||
|
||||
it('silently retains untracked files and never cleans a tool-only worktree', async () => {
|
||||
const f = await fixture()
|
||||
await writeFile(join(f.worktree.path, 'keep.txt'), 'keep')
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
const other = f.ctx.sessions.create(SessionId('tool-created'), { meta: { cwd: f.root } })
|
||||
const agent = testAgent(f.ctx, other)
|
||||
await f.ctx.agents.register(agent)
|
||||
const worktree = await f.ctx.worktrees.create(agent, { name: 'tool-only' })
|
||||
await f.ctx.workspaceRegistry.archiveSession(other.id)
|
||||
expect(await f.archives.result(other, null)).toBeNull()
|
||||
await access(worktree.path)
|
||||
})
|
||||
|
||||
it('retains the checkout until cancelled work actually stops', async () => {
|
||||
const f = await fixture()
|
||||
f.ctx.on('workspace/session-activity', async (_request, next) => [{ kind: 'turn' }, ...await next()])
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id, { stopActivity: true })
|
||||
expect(await completed(f)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('keeps archival successful and reports a failed removal', async () => {
|
||||
const f = await fixture()
|
||||
const warning = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {})
|
||||
vi.spyOn(f.ctx.worktrees, 'remove').mockRejectedValue(new Error('checkout removal denied'))
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toMatchObject({ status: 'failed' })
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
|
||||
expect(warning).toHaveBeenCalled()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('cancels queued deletion before letting the Session resume', async () => {
|
||||
const f = await fixture()
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const remove = f.ctx.worktrees.remove.bind(f.ctx.worktrees)
|
||||
vi.spyOn(f.ctx.worktrees, 'remove').mockImplementation(async (...args) => {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
return await remove(...args)
|
||||
})
|
||||
cleanups.push(async () => { release.resolve(undefined) })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
await entered.promise
|
||||
const unarchive = f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
|
||||
release.resolve(undefined)
|
||||
await unarchive
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).not.toContain(f.session.id)
|
||||
expect(await f.ctx.workingDirectory.ensure(f.agent)).toBe(f.worktree.path)
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('cleans a persisted UI checkout without loading its Agent', async () => {
|
||||
const f = await fixture()
|
||||
const id = SessionId('cold-archive-owner')
|
||||
const session = Session.create(id, [], { ...f.session.header, id })
|
||||
const agent = testAgent(f.ctx, session)
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null })
|
||||
const worktree = { ...await f.ctx.worktrees.create(agent, { name: 'cold-ui' }), from: null }
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'created', worktree })
|
||||
await using writer = await f.ctx.sessionPersistence.create(session.header)
|
||||
await writer.append(session.snapshotEvents())
|
||||
await writer.flush()
|
||||
await writer.close()
|
||||
expect(f.ctx.sessions.get(id)).toBeUndefined()
|
||||
await f.ctx.workspaceRegistry.archiveSession(id)
|
||||
const status = await f.archives.result(session, null)
|
||||
expect(status).not.toBeNull()
|
||||
expect(await f.archives.result(session, status!.revision)).toMatchObject({ status: 'removed' })
|
||||
expect(f.ctx.sessions.get(id)).toBeUndefined()
|
||||
expect(f.ctx.agents.list().some(item => item.session.id === id)).toBe(false)
|
||||
await expect(access(worktree.path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
})
|
||||
|
||||
it('reconsiders cleanup when a Session that entered the checkout by directory is archived last', async () => {
|
||||
const f = await fixture()
|
||||
const other = f.ctx.sessions.create(SessionId('directory-user'), { meta: { cwd: f.worktree.path } })
|
||||
const agent = testAgent(f.ctx, other)
|
||||
await f.ctx.agents.register(agent)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toBeNull()
|
||||
await f.ctx.workspaceRegistry.archiveSession(other.id)
|
||||
const status = await f.archives.result(other, null)
|
||||
expect(status).not.toBeNull()
|
||||
expect(await f.archives.result(other, status!.revision)).toMatchObject({ status: 'removed' })
|
||||
})
|
||||
|
||||
|
||||
it('retains a worktree during restoration or under its creator’s read-only policy', async () => {
|
||||
const f = await fixture()
|
||||
appendPluginRecord(f.session, WORKTREE_RECORD, { action: 'restoring' })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toBeNull()
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
appendPluginRecord(f.session, WORKTREE_RECORD, { action: 'restored' })
|
||||
f.session.append('sandbox/mode', { mode: 'read-only' })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it.each(['job', 'terminal'] as const)('retains a checkout when a %s can still use its old directory', async (kind) => {
|
||||
const f = await fixture()
|
||||
if (kind === 'job') f.ctx.on('workspace/session-activity', async (_request, next) => [{ kind: 'job' }, ...await next()])
|
||||
else {
|
||||
await f.ctx.plugin(TerminalService)
|
||||
vi.spyOn(f.ctx.terminals, 'list').mockReturnValue([{ sessionId: TerminalSessionId('persistent'), type: 'shell', status: { kind: 'running' } }])
|
||||
}
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id, { stopActivity: true })
|
||||
expect(await completed(f)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('retains a checkout on uncertain inspection and still allows unarchive when the log becomes unreadable', async () => {
|
||||
const f = await fixture()
|
||||
const warning = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {})
|
||||
vi.spyOn(f.ctx.worktrees, 'canRemove').mockRejectedValueOnce(new Error('Git unavailable'))
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toBeNull()
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toMatchObject({ status: 'removed' })
|
||||
vi.spyOn(f.ctx.sessionQuery, 'inspectSession').mockRejectedValueOnce(new Error('log unavailable'))
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).not.toContain(f.session.id)
|
||||
expect(warning).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('rechecks references acquired after the eligible inspection', async () => {
|
||||
const f = await fixture()
|
||||
const inspect = f.ctx.worktrees.canRemove.bind(f.ctx.worktrees)
|
||||
vi.spyOn(f.ctx.worktrees, 'canRemove').mockImplementationOnce(async (...args) => {
|
||||
const eligible = await inspect(...args)
|
||||
f.ctx.sessions.create(SessionId('arriving-reference'), { meta: { cwd: f.worktree.path } })
|
||||
return eligible
|
||||
})
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toMatchObject({ status: 'retained' })
|
||||
expect(await f.archives.result(f.session, -1)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('retains a checkout for a live user that appeared after corpus listing', async () => {
|
||||
const f = await fixture()
|
||||
const list = f.ctx.sessionQuery.listSessions.bind(f.ctx.sessionQuery)
|
||||
vi.spyOn(f.ctx.sessionQuery, 'listSessions').mockImplementationOnce(async (...args) => {
|
||||
const records = await list(...args)
|
||||
const late = f.ctx.sessions.create(SessionId('late-live-user'), { meta: { cwd: f.worktree.path } })
|
||||
await f.ctx.agents.register(testAgent(f.ctx, late))
|
||||
return records
|
||||
})
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('does not infer ownership from a fork whose creator is absent', async () => {
|
||||
const f = await fixture()
|
||||
const worktree = { ...await f.ctx.worktrees.create(f.agent, { name: 'missing-owner' }), from: null }
|
||||
await f.ctx.workingDirectory.set(f.agent, f.root)
|
||||
const source = Session.create(SessionId('absent-owner'), [], { ...f.session.header, id: SessionId('absent-owner') })
|
||||
appendPluginRecord(source, WORKTREE_RECORD, { action: 'request', from: null })
|
||||
source.append('working-directory/change', { cwd: worktree.path })
|
||||
appendPluginRecord(source, WORKTREE_RECORD, { action: 'created', worktree })
|
||||
const seed = source.snapshotEvents()
|
||||
const fork = f.ctx.sessions.create(SessionId('orphan-fork'), { seed, inheritedEventCount: SessionLogOffset(seed.length), meta: { isSeeded: true, cwd: f.root } })
|
||||
await f.ctx.workspaceRegistry.archiveSession(fork.id)
|
||||
expect(await f.archives.result(fork, null)).toBeNull()
|
||||
await access(worktree.path)
|
||||
})
|
||||
|
||||
it('does not cancel an unrelated cleanup when another Session is unarchived', async () => {
|
||||
const f = await fixture()
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await completed(f)).toMatchObject({ status: 'removed' })
|
||||
const other = f.ctx.sessions.create(SessionId('unrelated'), { meta: { cwd: f.root } })
|
||||
await f.ctx.workspaceRegistry.archiveSession(other.id)
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(other.id)
|
||||
const blank = f.ctx.sessions.create(SessionId('without-directory'))
|
||||
await f.ctx.workspaceRegistry.archiveSession(blank.id)
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(blank.id)
|
||||
expect(await completed(f)).toMatchObject({ status: 'removed' })
|
||||
})
|
||||
|
||||
it('drains an admitted cleanup on disposal and withdraws its pending result', async () => {
|
||||
const f = await fixture()
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
vi.spyOn(f.ctx.worktrees, 'remove').mockImplementation(async () => {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
return false
|
||||
})
|
||||
cleanups.push(async () => { release.resolve(undefined) })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
await entered.promise
|
||||
const status = await f.archives.result(f.session, null)
|
||||
const result = f.archives.result(f.session, status!.revision)
|
||||
const disposal = f.archives.dispose()
|
||||
release.resolve(undefined)
|
||||
await disposal
|
||||
expect(await result).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
|
||||
it('mounts archive cleanup with its optional providers and serves the Remote result', async () => {
|
||||
const f = await fixture()
|
||||
await f.archives.dispose()
|
||||
const mounted = await f.ctx.plugin(ForgePanelController, {})
|
||||
const controller = f.ctx.forgePanel
|
||||
expect(await controller.worktreeCleanup(f.session, null)).toBeNull()
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
const status = await controller.worktreeCleanup(f.session, null)
|
||||
expect(status).not.toBeNull()
|
||||
expect(await controller.worktreeCleanup(f.session, status!.revision)).toMatchObject({ status: 'removed' })
|
||||
await mounted.dispose()
|
||||
expect(await controller.worktreeCleanup(f.session, null)).toBeNull()
|
||||
})
|
||||
|
||||
})
|
||||
@@ -274,7 +274,8 @@ describe('creating a requested worktree', () => {
|
||||
const created = { path, branch, from: null, baseCommit: head, repositoryRoot: repo }
|
||||
expect(result).toEqual({ path, branch, baseCommit: head, repositoryRoot: repo })
|
||||
expect(worktreeOf(opened)).toEqual(created)
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }, { action: 'created', worktree: created }])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toEqual([{ path, branch, baseCommit: head, repositoryRoot: repo }])
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(path)
|
||||
expect(opened.ctx.sessionProjections.snapshot(opened.session, ['forgeWorktree']).values).toEqual({ forgeWorktree: created })
|
||||
expect(await git(path, 'symbolic-ref', '--short', 'HEAD')).toBe(branch)
|
||||
@@ -403,7 +404,8 @@ describe('worktree creation at the first step proposal', () => {
|
||||
expect(branch).toMatch(/^dsh-[0-9a-f]{8}$/)
|
||||
const path = join(repo, '.agents', 'worktrees', ...branch.split('/'))
|
||||
expect(created).toEqual({ path, branch, from: null, baseCommit: head, repositoryRoot: repo })
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }, { action: 'created', worktree: created }])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(path)
|
||||
expect(await git(path, 'symbolic-ref', '--short', 'HEAD')).toBe(branch)
|
||||
expect(decision).toEqual({ kind: 'enter', messages: [proposed, notice(path)], startsRequestSeries: true })
|
||||
@@ -439,7 +441,8 @@ describe('worktree creation at the first step proposal', () => {
|
||||
expect(path).toBe(worktreeOf(opened)?.path)
|
||||
expect(entered).toEqual({ kind: 'enter', messages: [proposed] })
|
||||
expect(opened.agent.inbox.nextStep).toEqual([notice(path)])
|
||||
expect(opened.records).toHaveLength(2)
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
expect(await branches(repo)).toEqual([worktreeOf(opened)?.branch, 'main'])
|
||||
})
|
||||
|
||||
@@ -488,7 +491,8 @@ describe('worktree creation at the first step proposal', () => {
|
||||
|
||||
expect(decision).toEqual({ kind: 'enter', messages: [proposed] })
|
||||
expect(opened.changes).toHaveLength(reports)
|
||||
expect(opened.records).toHaveLength(2)
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(created.path)
|
||||
expect(await branches(repo)).toEqual([created.branch, 'main'])
|
||||
})
|
||||
|
||||
@@ -70,6 +70,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../forge-session"
|
||||
},
|
||||
{
|
||||
"path": "../worktree"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,8 +15,7 @@
|
||||
"src/patch-cache.ts",
|
||||
"src/states.ts",
|
||||
"src/types.ts",
|
||||
"src/worktree.ts",
|
||||
"src/worktree-archive.ts"
|
||||
"src/worktree.ts"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
@@ -78,15 +77,6 @@
|
||||
},
|
||||
{
|
||||
"path": "../worktree"
|
||||
},
|
||||
{
|
||||
"path": "../../terminal/terminal"
|
||||
},
|
||||
{
|
||||
"path": "../../workspace/workspace"
|
||||
},
|
||||
{
|
||||
"path": "../../jobs/jobs"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 33679bed06be4e74
|
||||
zh: 77dcfac9570d1fbc
|
||||
/deepseek-ai-dsh-experimental-forge-bundle/understand-the-implementation:
|
||||
en: 5cb4136ef2058890
|
||||
zh: 5142828996eef6c7
|
||||
en: 88b97653b7e8cf42
|
||||
zh: f2deac3b624506b9
|
||||
/deepseek-ai-dsh-experimental-forge-bundle/further-exploration:
|
||||
en: ab1f524b8ad79c55
|
||||
zh: 137cfcb6d192c269
|
||||
|
||||
@@ -37,7 +37,7 @@ The same switch enables the model's [`create_worktree`](../tool-worktree/README.
|
||||
<details>
|
||||
<summary>Maintainer details — click to expand</summary>
|
||||
|
||||
The bundle mounts the forge registry, GitHub provider, Session bindings, and the worktree model tool. The tool uses the top-level `worktree` service; the panel keeps its isolated `forge-worktree` service inside `optional-forge-panel`. Their configuration ids and creation flows stay independent. The panel records worktrees requested before a Session starts; model-created worktrees do not acquire the panel's recovery records. The rows use the Session projection, working-directory, filesystem, subprocess, and sandbox services from base-backed profiles.
|
||||
The bundle mounts the forge registry, GitHub provider, Session bindings, the worktree model tool, and the panel as six top-level rows. The tool and the panel share the one `worktree` service, so one `worktree` row override configures both, and one archive of a Session reclaims its checkout once. The panel records worktrees requested before a Session starts; model-created worktrees do not acquire the panel's recovery records, but both kinds take part in archive cleanup. The rows use the Session projection, working-directory, filesystem, subprocess, and sandbox services from base-backed profiles; archive cleanup also needs the Workspace registry and Session query of those profiles.
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ kind: "package-bundle"
|
||||
<details>
|
||||
<summary>维护者细节——点击展开</summary>
|
||||
|
||||
组合包挂载 Forge 注册表、GitHub 提供方、Session 绑定和工作树模型工具。工具使用顶层 `worktree` 服务;面板在 `optional-forge-panel` 内保留隔离的 `forge-worktree` 服务。两者的配置 id 和创建流程各自独立。面板记录 Session 开始前请求的工作树;模型创建的工作树不会获得面板的恢复记录。这些行使用基于 base 的 profile 提供的 Session 投影、工作目录、文件系统、子进程和沙箱服务。
|
||||
组合包以六个顶层行挂载 Forge 注册表、GitHub 提供方、Session 绑定、工作树模型工具和面板。工具与面板共用同一个 `worktree` 服务,因此一条 `worktree` 行覆盖同时配置两者,归档一个 Session 只回收一次其检出目录。面板记录 Session 开始前请求的工作树;模型创建的工作树不会获得面板的恢复记录,但两种工作树都参与归档清理。这些行使用基于 base 的 profile 提供的 Session 投影、工作目录、文件系统、子进程和沙箱服务;归档清理还需要这些 profile 的 Workspace 注册表与 Session 查询。
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -9,13 +9,5 @@
|
||||
name: '@deepseek-ai/dsh-experimental-forge-github'
|
||||
- id: forge-session
|
||||
name: '@deepseek-ai/dsh-experimental-forge-session'
|
||||
- id: optional-forge-panel
|
||||
name: cordis:group
|
||||
group: true
|
||||
isolate:
|
||||
worktrees: true
|
||||
config:
|
||||
- id: forge-worktree
|
||||
name: '@deepseek-ai/dsh-experimental-worktree'
|
||||
- id: forge-panel
|
||||
name: '@deepseek-ai/dsh-experimental-client-ui-forge'
|
||||
- id: forge-panel
|
||||
name: '@deepseek-ai/dsh-experimental-client-ui-forge'
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-worktree/use-this-package:
|
||||
en: a93ecfc35ee1cc22
|
||||
zh: fa963b3345eacdab
|
||||
en: ab16360228013067
|
||||
zh: 48047eb61715aaaa
|
||||
/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: 4fe60580b4ca3eab
|
||||
zh: 9002a38ec60d3ea7
|
||||
en: 9115db41d1c8eed7
|
||||
zh: 87857659a8a47c1d
|
||||
/deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work/dev-note:
|
||||
en: ad12746a6cc96d8a
|
||||
zh: 66275f30a35c88e4
|
||||
@@ -25,7 +25,7 @@ Create an isolated checkout from a local commit and continue the same Session in
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, and `sandboxPolicy` providers. Add the tool package when models need the operation.
|
||||
Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, `sandboxPolicy`, and `sessionProjections` providers. Archive cleanup additionally needs `workspaceRegistry` and `sessionQuery`, and uses `sessionProjectionCache` when it is mounted; without the first two the service only creates and restores. Add the tool package when models need the operation.
|
||||
|
||||
```yaml
|
||||
- name: '@deepseek-ai/dsh-experimental-worktree'
|
||||
@@ -36,7 +36,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, a
|
||||
|
||||
`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.
|
||||
|
||||
`canRemove(policy, request, signal?)` inspects a recorded checkout under an explicitly resolved Session policy; `remove(policy, request, signal?, admit?)` repeats that inspection before non-force removal and never deletes a branch. The caller excludes Session users until completion and can cancel final admission with the synchronous `admit` callback. Tracked changes, untracked or ignored files, hidden index flags, submodules, locks, detached HEAD, a mismatched branch, and targets outside the configured pool are retained. Inspection errors reject without mutation; removal errors can leave a partial directory and retain the branch. Removal and restoration of the same path are serialized.
|
||||
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. 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, hidden index flags, submodules, locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout; ignored files do not, as Git itself discards them. 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.
|
||||
|
||||
The default checkout directory is `<current checkout root>/.agents/worktrees/<name>`. The returned `repositoryRoot` is the top-level directory of the caller’s current checkout; when it is a linked checkout, the pool is nested inside it. Omitted names join the `dsh-` prefix, the first eight hexadecimal digits of the UUID in the Session id, a hyphen, and four random hexadecimal digits, such as `dsh-6b1f02c4-9a3e`; a Session id without a UUID gets eight random hexadecimal digits after the prefix. `generatedWorktreeName` exports the same rule for callers that name a worktree before creating it. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the pool; existing files and ignore rules are preserved. Relative `directory`, generated `namePrefix`, executable choices, and process limits are configurable in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-worktree).
|
||||
|
||||
@@ -86,7 +86,7 @@ This package contributes no prompt text. Its consumers own the appended tool res
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- **Retained artifacts** — leaving a worktree keeps its branch and files. Setup failures can also retain partial artifacts; cleanup scheduling belongs to the owning consumer, and branch deletion remains explicit.
|
||||
- **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.
|
||||
- **Execution requirements** — the subprocess provider must offer Git and Node in the same execution world as the filesystem provider. Git must honor `GIT_NO_LAZY_FETCH`, which Git 2.45 and the 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, and 2.44.1 maintenance releases do; older releases ignore it and proceed instead of failing, so creation can fetch missing partial-clone objects from a promisor remote. The `git --no-lazy-fetch` option would reject these releases, but it exists only in Git 2.45 and later and also rejects the patched maintenance releases. The existing sandbox must permit all checkout and shared Git metadata writes.
|
||||
|
||||
@@ -25,7 +25,7 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
将服务与 `workingDirectory`、`fs`、`subprocess`、`sandbox` 和 `sandboxPolicy` 提供方一起挂载。模型需要此操作时,再添加工具包。
|
||||
将服务与 `workingDirectory`、`fs`、`subprocess`、`sandbox`、`sandboxPolicy` 和 `sessionProjections` 提供方一起挂载。归档清理还需要 `workspaceRegistry` 与 `sessionQuery`,并在挂载了 `sessionProjectionCache` 时使用它;缺少前两者时服务只创建与恢复。模型需要此操作时,再添加工具包。
|
||||
|
||||
```yaml
|
||||
- name: '@deepseek-ai/dsh-experimental-worktree'
|
||||
@@ -36,7 +36,7 @@ kind: "package-reference"
|
||||
|
||||
`ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它只通过 `git worktree remove` 移除缺失目标的未锁定登记;其他 worktree 与锁定登记保持不变。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。
|
||||
|
||||
`canRemove(policy, request, signal?)` 使用显式解析的 Session 策略检查已记录的工作树;`remove(policy, request, signal?, admit?)` 在非强制删除前重新检查,且不删除分支。调用方在操作结束前排除会话使用者,并可通过同步的 `admit` 回调取消最终准入。有已跟踪修改、未跟踪或忽略文件、隐藏索引标记、子模块、锁、分离 HEAD、分支不匹配或位于配置池之外的目标均会保留。检查错误在修改前拒绝;删除错误可能留下不完整目录,但保留分支。同一路径的删除与恢复会串行执行。
|
||||
每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、隐藏的索引标记、子模块、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录;被忽略的文件不会,因为 Git 自身会丢弃它们。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。
|
||||
|
||||
默认检出目录是 `<current checkout root>/.agents/worktrees/<name>`。返回的 `repositoryRoot` 是调用方当前检出目录的顶层目录;如果它是链接检出目录,工作树父目录就嵌套在其中。省略名称时,名称由前缀 `dsh-`、Session id 中 UUID 的前 8 位十六进制数、一个连字符和 4 位随机十六进制数组成,例如 `dsh-6b1f02c4-9a3e`;Session id 不含 UUID 时,前缀后接 8 位随机十六进制数。`generatedWorktreeName` 导出同一规则,供在创建前确定名称的调用方使用。仅当服务的分配操作创建了父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`;已有文件与忽略规则保持不变。相对路径 `directory`、生成名称使用的 `namePrefix`、可执行程序与进程限制可在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-worktree)中查阅。
|
||||
|
||||
@@ -86,7 +86,7 @@ Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- **保留产物**——离开工作树会保留其分支和文件。初始化失败也可能留下部分产物;移除检出目录与删除分支由用户或其他消费方负责。
|
||||
- **保留的产物**——离开工作树时保留其分支和文件,归档清理也从不删除分支。安装失败同样可能保留部分产物;删除失败可能留下部分目录,可在保留的分支上恢复覆盖。
|
||||
- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。
|
||||
- **过滤器处理前的内容**——检出时跳过已配置的过滤器,以避免执行仓库配置的程序或隐式下载。Git LFS 指针与加密 blob 保持存储时的形式;拉取实体内容或解密由用户另行执行。
|
||||
- **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 与 Node。Git 必须识别 `GIT_NO_LAZY_FETCH`:Git 2.45 及 2.39.4、2.40.2、2.41.1、2.42.2、2.43.4、2.44.1 维护版本均支持;更早的版本会忽略该变量并继续执行而不报错,因此创建操作可能从 promisor 远程获取缺失的部分克隆对象。`git --no-lazy-fetch` 选项会拒绝这些版本,但它仅在 Git 2.45 及以后存在,也会拒绝上述已修补的维护版本。现有沙箱必须允许写入检出目录与共享 Git 元数据。
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./types": {
|
||||
"types": "./lib/types/types.d.ts",
|
||||
"default": "./lib/types/types.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./locale/*.json": "./locale/*.json",
|
||||
"./package.json": "./package.json"
|
||||
@@ -33,7 +37,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/schemastery": "workspace:~",
|
||||
"@deepseek-ai/dsh-timeout": "workspace:*"
|
||||
"@deepseek-ai/dsh-timeout": "workspace:*",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
@@ -41,8 +46,13 @@
|
||||
"@deepseek-ai/dsh-fs": "workspace:*",
|
||||
"@deepseek-ai/dsh-sandbox": "workspace:*",
|
||||
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
|
||||
"@deepseek-ai/dsh-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection-cache": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-query": "workspace:*",
|
||||
"@deepseek-ai/dsh-subprocess": "workspace:*",
|
||||
"@deepseek-ai/dsh-working-directory": "workspace:*"
|
||||
"@deepseek-ai/dsh-working-directory": "workspace:*",
|
||||
"@deepseek-ai/dsh-workspace": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
@@ -54,10 +64,16 @@
|
||||
"@deepseek-ai/dsh-sandbox-local": "workspace:*",
|
||||
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
|
||||
"@deepseek-ai/dsh-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection-cache": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-query": "workspace:*",
|
||||
"@deepseek-ai/dsh-storage": "workspace:*",
|
||||
"@deepseek-ai/dsh-storage-domain": "workspace:*",
|
||||
"@deepseek-ai/dsh-subprocess": "workspace:*",
|
||||
"@deepseek-ai/dsh-subprocess-local": "workspace:*",
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:*",
|
||||
"@deepseek-ai/dsh-working-directory": "workspace:*"
|
||||
"@deepseek-ai/dsh-working-directory": "workspace:*",
|
||||
"@deepseek-ai/dsh-workspace": "workspace:*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* Archive-triggered reclamation of checkouts this service created. Installed by
|
||||
* the service constructor, as the job and Agent registries install their own
|
||||
* archive-admission families, so it holds for every Session the Workspace archives.
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type {} from '@deepseek-ai/dsh-session-projection-cache'
|
||||
import type {} from '@deepseek-ai/dsh-session-query'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import type {} from '@deepseek-ai/dsh-workspace'
|
||||
import type { WorktreeProjectionState } from './projection.ts'
|
||||
import type { CreatedWorktree, WorktreeCleanup, WorktreeCreation } from './types.ts'
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Events {
|
||||
/**
|
||||
* A cleanup attempt changed state. Fires once at admission with
|
||||
* `scheduled` and once at settlement with the final status.
|
||||
* @param info - the archived Session, the checkout, and the attempt state.
|
||||
* @mode emit
|
||||
*/
|
||||
'worktree/cleanup'(info: { sessionId: SessionId; path: string; cleanup: WorktreeCleanup }): void
|
||||
}
|
||||
}
|
||||
|
||||
/** The service operations reclamation needs; kept narrow so the archive module never reaches Git directly. */
|
||||
export interface ReclamationHost {
|
||||
/** Run `body` after every operation on `path` that was requested earlier, and before any requested later. */
|
||||
exclusiveCheckout<T>(path: string, body: () => Promise<T>): Promise<T>
|
||||
/** Inspect and, when eligible and admitted, remove the checkout without force. Rejects on Git failure. */
|
||||
removeCheckout(session: Session, request: CreatedWorktree, signal: AbortSignal, admit: () => boolean): Promise<boolean>
|
||||
}
|
||||
|
||||
interface Attempt {
|
||||
readonly worktree: CreatedWorktree
|
||||
readonly revision: number
|
||||
status: WorktreeCleanup['status']
|
||||
cancelled: boolean
|
||||
done: Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `path` is `root` or lies below it. Both are canonical absolute
|
||||
* paths of one execution world, so string prefixing is exact.
|
||||
*/
|
||||
function within(root: string, path: string): boolean {
|
||||
return path === root || path.startsWith(root.endsWith('/') ? root : `${root}/`)
|
||||
}
|
||||
|
||||
/** Owns pending cleanup, gates directory entry into a checkout being removed, and drains before the service is released. */
|
||||
export class WorktreeReclamation {
|
||||
private readonly attempts = new Map<SessionId, Attempt>()
|
||||
private readonly removing = new Map<string, Promise<void>>()
|
||||
private readonly pending = new Set<Promise<unknown>>()
|
||||
private readonly lifetime = new AbortController()
|
||||
private revision = 0
|
||||
|
||||
/**
|
||||
* @param ctx - scope injecting the Workspace registry, Session query, store, working-directory, and
|
||||
* sandbox-policy providers; the projection cache is read when mounted.
|
||||
* @param host - the service operations the module runs through.
|
||||
* @param projection - the `worktree` unit, read live and through the persisted cache.
|
||||
*/
|
||||
constructor(
|
||||
private readonly ctx: Context,
|
||||
private readonly host: ReclamationHost,
|
||||
private readonly projection: ProjectionHandle<WorktreeProjectionState>,
|
||||
) {
|
||||
// Listeners withdraw before the drain so a disposing service never fails
|
||||
// unrelated directory access or an unarchive with its own abort.
|
||||
ctx.on('working-directory/access', ({ agent, path, signal }, next) => {
|
||||
const target = path ?? ctx.workingDirectory.get(agent.session)
|
||||
const blocked = [...this.removing.keys()].find(root => within(root, target))
|
||||
if (blocked === undefined) return next()
|
||||
return this.host.exclusiveCheckout(blocked, async () => {
|
||||
signal.throwIfAborted()
|
||||
return await next()
|
||||
})
|
||||
})
|
||||
ctx.on('workspace/session-archived', ({ sessionId }) => { this.schedule(sessionId) })
|
||||
ctx.on('workspace/session-unarchiving', async ({ sessionId }) => {
|
||||
const attempt = this.attempts.get(sessionId)
|
||||
if (attempt === undefined) return
|
||||
attempt.cancelled = true
|
||||
await attempt.done
|
||||
this.attempts.delete(sessionId)
|
||||
})
|
||||
ctx.effect(() => async () => {
|
||||
this.lifetime.abort(new Error('worktree reclamation stopped'))
|
||||
for (const attempt of this.attempts.values()) attempt.cancelled = true
|
||||
await Promise.allSettled(this.pending)
|
||||
this.attempts.clear()
|
||||
}, 'worktree: drain archive cleanup')
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the most recent cleanup attempt of a Session; waiting never starts one.
|
||||
* @param session - archived Session whose attempt is read.
|
||||
* @param revision - null reads at once; a matching revision waits for that attempt to settle.
|
||||
* @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
|
||||
*/
|
||||
async cleanupOf(session: Session, revision: number | null): Promise<WorktreeCleanup | null> {
|
||||
const attempt = this.attempts.get(session.id)
|
||||
if (attempt === undefined || (revision !== null && revision !== attempt.revision)) return null
|
||||
if (revision !== null) await attempt.done
|
||||
if (this.lifetime.signal.aborted) return null
|
||||
return { revision: attempt.revision, status: attempt.status }
|
||||
}
|
||||
|
||||
/** Register attempts for the Session's own creations and return; every inspection runs in the background. */
|
||||
private schedule(sessionId: SessionId): void {
|
||||
if (this.lifetime.signal.aborted) return
|
||||
const live = this.ctx.sessions.get(sessionId)
|
||||
// A cold Session's creations come from the persisted cache or its log, below.
|
||||
const owned = live === undefined ? undefined : this.projection.stateOf(live).created.filter(creation => creation.owned)
|
||||
if (owned !== undefined && owned.length === 0) return
|
||||
const attempt: Attempt = {
|
||||
worktree: owned?.[0]?.worktree ?? { path: '', branch: '', baseCommit: '', repositoryRoot: '' },
|
||||
revision: ++this.revision, status: 'scheduled', cancelled: false, done: Promise.resolve(),
|
||||
}
|
||||
this.attempts.set(sessionId, attempt)
|
||||
const task = this.run(sessionId, attempt, owned)
|
||||
this.pending.add(task)
|
||||
attempt.done = task.then(() => { this.pending.delete(task) }, () => { this.pending.delete(task) })
|
||||
}
|
||||
|
||||
private async run(sessionId: SessionId, attempt: Attempt, owned: readonly WorktreeCreation[] | undefined): Promise<void> {
|
||||
const ctx = this.ctx
|
||||
try {
|
||||
let creations = owned
|
||||
if (creations === undefined) {
|
||||
const own = await this.creationsOf(sessionId, undefined)
|
||||
creations = own === undefined ? [] : own.filter(creation => creation.owned)
|
||||
}
|
||||
const candidate = creations[0]?.worktree
|
||||
if (candidate === undefined) {
|
||||
this.attempts.delete(sessionId)
|
||||
return
|
||||
}
|
||||
Object.assign(attempt, { worktree: candidate })
|
||||
ctx.emit('worktree/cleanup', {
|
||||
sessionId, path: candidate.path, cleanup: { revision: attempt.revision, status: attempt.status },
|
||||
})
|
||||
const session = await this.creatorSession(sessionId)
|
||||
if (session === undefined || attempt.cancelled || ctx.sandboxPolicy.resolve({ session }).mode === 'read-only'
|
||||
|| !await this.unused(candidate, sessionId)) {
|
||||
attempt.status = 'retained'
|
||||
} else {
|
||||
attempt.status = await this.remove(session, candidate, attempt) ? 'removed' : 'retained'
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
attempt.status = 'failed'
|
||||
ctx.logger.warn(
|
||||
'Session %s archived; cleanup of its worktree %s failed and its branch was retained: %s', sessionId, attempt.worktree.path, error,
|
||||
)
|
||||
}
|
||||
ctx.emit('worktree/cleanup', {
|
||||
sessionId, path: attempt.worktree.path, cleanup: { revision: attempt.revision, status: attempt.status },
|
||||
})
|
||||
}
|
||||
|
||||
/** Remove under the path lock; a second use check runs inside it, after competing operations settled. */
|
||||
private async remove(session: Session, worktree: CreatedWorktree, attempt: Attempt): Promise<boolean> {
|
||||
const previous = this.removing.get(worktree.path) ?? Promise.resolve()
|
||||
const operation = previous.then(() => this.host.exclusiveCheckout(worktree.path, async () => {
|
||||
if (attempt.cancelled || !await this.unused(worktree, undefined)) return false
|
||||
return await this.host.removeCheckout(session, worktree, this.lifetime.signal, () => !attempt.cancelled)
|
||||
}))
|
||||
const settled = operation.then(() => {}, () => {})
|
||||
this.removing.set(worktree.path, settled)
|
||||
try {
|
||||
return await operation
|
||||
} finally {
|
||||
if (this.removing.get(worktree.path) === settled) this.removing.delete(worktree.path)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether no unarchived Session still refers to the checkout: by a recorded
|
||||
* creation, inherited or own, or by a working directory inside it. A Session
|
||||
* beneath an archived subagent ancestor counts as archived, as its own
|
||||
* archive admission does. Processes are not consulted: Git refuses a
|
||||
* removal that would discard changes, and an idle process in a removed
|
||||
* directory fails its next command.
|
||||
*/
|
||||
private async unused(worktree: CreatedWorktree, archivingId: SessionId | undefined): Promise<boolean> {
|
||||
const ctx = this.ctx
|
||||
const signal = this.lifetime.signal
|
||||
signal.throwIfAborted()
|
||||
const records = await ctx.sessionQuery.listSessions(signal)
|
||||
const headers = new Map(records.map(record => [record.header.id, record.header] as const))
|
||||
const archived = new Set(ctx.workspaceRegistry.archivedSessionIds)
|
||||
if (archivingId !== undefined) archived.add(archivingId)
|
||||
for (const record of records) {
|
||||
const id = record.header.id
|
||||
if (archived.has(id) || ancestorArchived(record.header, headers, archived)) continue
|
||||
const live = ctx.sessions.get(id)
|
||||
const cwd = live === undefined ? await this.directoryOf(record.header) : ctx.workingDirectory.get(live)
|
||||
if (cwd !== undefined && cwd !== null && within(worktree.path, cwd)) return false
|
||||
const creations = live === undefined ? await this.creationsOf(id, record.header) : this.projection.stateOf(live).created
|
||||
if (creations?.some(creation => creation.worktree.path === worktree.path)) return false
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** The archived Session itself, prepared cold when not live, whose sandbox policy confines the Git commands. */
|
||||
private async creatorSession(sessionId: SessionId): Promise<Session | undefined> {
|
||||
const live = this.ctx.sessions.get(sessionId)
|
||||
if (live !== undefined) return live
|
||||
return await this.ctx.sessionQuery.inspectSession(sessionId, session => session, this.lifetime.signal)
|
||||
}
|
||||
|
||||
/** The recorded directory of a cold Session: the persisted cache when it has one, else its log. */
|
||||
private async directoryOf(header: SessionHeader): Promise<string | null | undefined> {
|
||||
const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(header, ['workingDirectory'])?.values.workingDirectory
|
||||
if (cached !== undefined) return cached
|
||||
return await this.ctx.sessionQuery.inspectSession(header.id, session => this.ctx.workingDirectory.get(session), this.lifetime.signal)
|
||||
}
|
||||
|
||||
/** The recorded creations of a cold Session: the persisted cache when it has one, else its log. */
|
||||
private async creationsOf(
|
||||
sessionId: SessionId, header: SessionHeader | undefined,
|
||||
): Promise<readonly WorktreeCreation[] | undefined> {
|
||||
const cached = header === undefined
|
||||
? undefined
|
||||
: this.ctx.get('sessionProjectionCache')?.cachedSnapshot(header, ['worktree'])?.values.worktree
|
||||
if (cached !== undefined) return cached
|
||||
return await this.ctx.sessionQuery.inspectSession(sessionId, session => this.projection.stateOf(session).created, this.lifetime.signal)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether any subagent ancestor of `header`, followed through the listed headers, is archived. */
|
||||
function ancestorArchived(
|
||||
header: SessionHeader, headers: ReadonlyMap<SessionId, SessionHeader>, archived: ReadonlySet<SessionId>,
|
||||
): boolean {
|
||||
const visited = new Set<SessionId>([header.id])
|
||||
let current = header
|
||||
while (current.origin === 'subagent' && current.parentSession !== undefined && !visited.has(current.parentSession)) {
|
||||
if (archived.has(current.parentSession)) return true
|
||||
visited.add(current.parentSession)
|
||||
const parent = headers.get(current.parentSession)
|
||||
if (parent === undefined) return false
|
||||
current = parent
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -3,20 +3,32 @@
|
||||
import { Context, Service } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { inspectRemoval } from './removal.ts'
|
||||
import type {} from '@deepseek-ai/dsh-fs'
|
||||
import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
||||
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import { appendPluginRecord } from '@deepseek-ai/dsh-session'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
import { WorktreeReclamation } from './archive.ts'
|
||||
import { PREPARE_DIRECTORY } from './directory.ts'
|
||||
import { generatedWorktreeName } from './name.ts'
|
||||
import { runCommand } from './process.ts'
|
||||
import type { ProcessConfig } from './process.ts'
|
||||
import type { CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest } from './types.ts'
|
||||
import { CREATED_RECORD, worktreeProjection } from './projection.ts'
|
||||
import type { WorktreeProjectionState } from './projection.ts'
|
||||
import { checkoutIdentity, inspectRemoval, registration } from './removal.ts'
|
||||
import type {
|
||||
CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest, WorktreeCleanup,
|
||||
} from './types.ts'
|
||||
|
||||
export type { CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest } from './types.ts'
|
||||
export type {
|
||||
CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest, WorktreeCleanup, WorktreeCreation,
|
||||
} from './types.ts'
|
||||
export { generatedWorktreeName } from './name.ts'
|
||||
export { CREATED_RECORD, worktreeProjection } from './projection.ts'
|
||||
export type { WorktreeProjectionState } from './projection.ts'
|
||||
|
||||
/** Worktree location, generated names, executables, and subprocess resource limits. */
|
||||
export interface Config {
|
||||
@@ -58,9 +70,13 @@ function relativePath(value: string): boolean {
|
||||
&& value.split('/').every(part => part.length > 0 && part !== '.' && part !== '..')
|
||||
}
|
||||
|
||||
/** Creates retained Git worktrees under the mounted filesystem and sandbox providers. */
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export class WorktreeService extends Service {
|
||||
static inject = ['workingDirectory', 'fs', 'subprocess', 'sandbox', 'sandboxPolicy']
|
||||
static inject = ['workingDirectory', 'fs', 'subprocess', 'sandbox', 'sandboxPolicy', 'sessionProjections']
|
||||
|
||||
static Config: z<Config> = z.object({
|
||||
directory: z.string().default('.agents/worktrees'),
|
||||
@@ -76,6 +92,8 @@ export class WorktreeService extends Service {
|
||||
private readonly lifetime = new AbortController()
|
||||
private readonly pending = new Set<Promise<unknown>>()
|
||||
private readonly checkouts = new Map<string, Promise<void>>()
|
||||
private projection!: ProjectionHandle<WorktreeProjectionState>
|
||||
private reclamation: WorktreeReclamation | undefined
|
||||
|
||||
constructor(ctx: Context, config: Config) {
|
||||
super(ctx, 'worktrees')
|
||||
@@ -99,6 +117,20 @@ export class WorktreeService extends Service {
|
||||
})
|
||||
}
|
||||
|
||||
protected async [Service.init](): Promise<void> {
|
||||
this.projection = await this.ctx.sessionProjections.register(worktreeProjection)
|
||||
// Reclamation needs the Workspace archive events and the Session corpus; without
|
||||
// them the service only creates and restores, as a headless profile composes it.
|
||||
this.ctx.inject(['workspaceRegistry', 'sessionQuery', 'sessions', 'workingDirectory', 'sandboxPolicy'], (scope) => {
|
||||
const reclamation = new WorktreeReclamation(scope, {
|
||||
exclusiveCheckout: (path, body) => this.exclusiveCheckout(path, body),
|
||||
removeCheckout: (session, request, signal, admit) => this.removeCheckout(session, request, signal, admit),
|
||||
}, this.projection)
|
||||
this.reclamation = reclamation
|
||||
scope.effect(() => () => { this.reclamation = undefined })
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a fresh branch and checkout at a pinned local revision, then enter it.
|
||||
* Existing branches or checkout paths fail. Uncommitted files stay in the source checkout.
|
||||
@@ -161,49 +193,34 @@ export class WorktreeService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect a recorded checkout for non-destructive removal. Dirty, ignored, locked,
|
||||
* detached, nested, mismatched, and missing checkouts are retained. Inspection errors reject.
|
||||
* @param policy - resolved execution policy of the owning Session.
|
||||
* @param request - recorded checkout identity.
|
||||
* @param signal - cancellation of inspection.
|
||||
* @returns whether the checkout is currently eligible; removal always inspects again.
|
||||
* Read the archive cleanup of a Session's created checkout; waiting never
|
||||
* starts one. Absent without the Workspace and query providers.
|
||||
* @param session - archived Session whose cleanup is read.
|
||||
* @param revision - null reads at once; a matching revision waits for that attempt to settle.
|
||||
* @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
|
||||
*/
|
||||
canRemove(policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal): Promise<boolean> {
|
||||
return this.removal(policy, request, signal, null)
|
||||
async cleanupOf(session: Session, revision: number | null): Promise<WorktreeCleanup | null> {
|
||||
return await this.reclamation?.cleanupOf(session, revision) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an eligible checkout and its registration without force or branch deletion.
|
||||
* Callers must exclude new users until settlement. A rejection can leave a partially
|
||||
* removed directory; the branch remains available for restoration.
|
||||
* @param policy - resolved execution policy of the owning Session.
|
||||
* @param request - recorded checkout identity.
|
||||
* @param signal - cancellation before or during removal.
|
||||
* @param admit - synchronous final admission after inspection; false retains the checkout.
|
||||
* @returns true when removed; false when inspection or admission requires retention.
|
||||
* Inspect a recorded checkout under the Session's policy and, when eligible
|
||||
* and admitted, remove it and its registration without force or branch
|
||||
* deletion. A rejection can leave a partial directory; the branch stays.
|
||||
*/
|
||||
remove(
|
||||
policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal, admit: () => boolean = () => true,
|
||||
private async removeCheckout(
|
||||
session: Session, request: RestoreWorktreeRequest, signal: AbortSignal, admit: () => boolean,
|
||||
): Promise<boolean> {
|
||||
return this.removal(policy, request, signal, admit)
|
||||
}
|
||||
|
||||
private async removal(
|
||||
policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal: AbortSignal | undefined, admit: (() => boolean) | null,
|
||||
): Promise<boolean> {
|
||||
const control = signal === undefined ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal])
|
||||
const control = AbortSignal.any([this.lifetime.signal, signal])
|
||||
control.throwIfAborted()
|
||||
const operation = this.exclusiveCheckout(request.path, async () => {
|
||||
control.throwIfAborted()
|
||||
const run = this.gitRunner(policy, control)
|
||||
const operation = (async () => {
|
||||
const run = this.gitRunner(this.ctx.sandboxPolicy.resolve({ session }), control)
|
||||
if (!await inspectRemoval(this.ctx, this.config.directory, request, run, control)) return false
|
||||
control.throwIfAborted()
|
||||
if (admit !== null) {
|
||||
if (!admit()) return false
|
||||
await run(request.repositoryRoot, ['worktree', 'remove', '--', request.path])
|
||||
}
|
||||
if (!admit()) return false
|
||||
await run(request.repositoryRoot, ['worktree', 'remove', '--', request.path])
|
||||
return true
|
||||
})
|
||||
})()
|
||||
this.pending.add(operation)
|
||||
try { return await operation } finally { this.pending.delete(operation) }
|
||||
}
|
||||
@@ -254,7 +271,9 @@ export class WorktreeService extends Service {
|
||||
onPhase?.('checkout')
|
||||
await run(path, ['--work-tree', path, 'reset', '--hard', '--no-recurse-submodules', baseCommit], undefined, overrides)
|
||||
const canonicalPath = await this.ctx.workingDirectory.set(agent, path, signal)
|
||||
return { path: canonicalPath, branch, baseCommit, repositoryRoot }
|
||||
const created: CreatedWorktree = { path: canonicalPath, branch, baseCommit, repositoryRoot }
|
||||
appendPluginRecord(agent.session, CREATED_RECORD, created)
|
||||
return created
|
||||
} catch (error) {
|
||||
throw new Error(`Could not finish worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error })
|
||||
}
|
||||
@@ -270,27 +289,14 @@ export class WorktreeService extends Service {
|
||||
const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session })
|
||||
const run = this.gitRunner(policy, signal)
|
||||
if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`)
|
||||
const root = await this.ctx.fs.resolve(repositoryRoot, { signal })
|
||||
const pool = await this.ctx.fs.resolve(this.config.directory, { cwd: repositoryRoot, signal })
|
||||
const target = await this.ctx.fs.resolve(path, { cwd: repositoryRoot, signal })
|
||||
if (this.ctx.fs.processPath(root) !== repositoryRoot || this.ctx.fs.processPath(target) !== path
|
||||
|| !this.ctx.fs.contains(root, pool) || !this.ctx.fs.contains(pool, target) || pool.targetKey === target.targetKey) {
|
||||
throw new Error('worktree restoration must use a canonical directory inside the configured pool')
|
||||
}
|
||||
if (!relativePath(branch) || branch.startsWith('-')) throw new Error('worktree branch must be a relative Git branch name')
|
||||
if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(baseCommit)) throw new Error('worktree baseCommit must be a full commit object name')
|
||||
const identity = await checkoutIdentity(this.ctx, this.config.directory, { path, branch, baseCommit, repositoryRoot }, run, signal)
|
||||
if (identity === null) throw new Error('worktree restoration must use a canonical directory inside the configured pool of the source checkout root')
|
||||
await run(repositoryRoot, ['check-ref-format', `refs/heads/${branch}`])
|
||||
const top = await run(repositoryRoot, ['rev-parse', '--show-toplevel'])
|
||||
const actualRoot = await this.ctx.fs.resolve(top.stdout.replace(/\r?\n$/, ''), { cwd: repositoryRoot, signal })
|
||||
if (actualRoot.targetKey !== root.targetKey) throw new Error('worktree repositoryRoot must be the source checkout root')
|
||||
await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${baseCommit}^{commit}`])
|
||||
const registered = await run(repositoryRoot, ['worktree', 'list', '--porcelain', '-z'])
|
||||
for (const entry of registered.stdout.split('\0\0')) {
|
||||
const fields = entry.split('\0')
|
||||
const recordedPath = fields.find(field => field.startsWith('worktree '))?.slice('worktree '.length)
|
||||
if (recordedPath === undefined) continue
|
||||
const recorded = await this.ctx.fs.resolve(recordedPath, { cwd: repositoryRoot, signal })
|
||||
if (recorded.targetKey !== target.targetKey) continue
|
||||
const fields = await registration(this.ctx, { path, branch, baseCommit, repositoryRoot }, identity.target, run, signal)
|
||||
if (fields !== undefined) {
|
||||
if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new Error(`worktree is locked: ${path}`)
|
||||
if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`)
|
||||
await run(repositoryRoot, ['worktree', 'remove', '--', path])
|
||||
@@ -298,6 +304,7 @@ export class WorktreeService extends Service {
|
||||
const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1])
|
||||
const branchRecreated = existing.exitCode !== 0
|
||||
try {
|
||||
const pool = await this.ctx.fs.resolve(this.config.directory, { cwd: repositoryRoot, signal })
|
||||
await this.prepareDirectory(policy, repositoryRoot, this.ctx.fs.processPath(pool), path, signal)
|
||||
await run(repositoryRoot, [
|
||||
'--work-tree', repositoryRoot, 'worktree', 'add', '--no-checkout',
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/** The `worktree` projection: every checkout this service recorded creating for a Session, and which of them the Session created itself. */
|
||||
|
||||
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'
|
||||
|
||||
/** 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'
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/dsh-session-projection/types' {
|
||||
interface SessionProjectionMap {
|
||||
/** Checkouts recorded in the Session's log, in creation order. */
|
||||
worktree: readonly WorktreeCreation[]
|
||||
}
|
||||
}
|
||||
|
||||
/** Host state of the `worktree` unit: creations so far and the fork boundary that decides ownership. */
|
||||
export interface WorktreeProjectionState {
|
||||
readonly created: readonly WorktreeCreation[]
|
||||
readonly inheritedEventCount: number
|
||||
}
|
||||
|
||||
const worktreeSchema: z.ZodType<CreatedWorktree> = z.object({
|
||||
path: z.string().min(1),
|
||||
branch: z.string().min(1),
|
||||
baseCommit: z.string().min(1),
|
||||
repositoryRoot: z.string().min(1),
|
||||
}).strict()
|
||||
|
||||
const creationSchema: z.ZodType<WorktreeCreation> = z.object({
|
||||
worktree: worktreeSchema,
|
||||
owned: z.boolean(),
|
||||
}).strict()
|
||||
|
||||
const stateSchema: z.ZodType<WorktreeProjectionState> = z.object({
|
||||
created: z.array(creationSchema),
|
||||
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.
|
||||
*/
|
||||
export const worktreeProjection = {
|
||||
key: 'worktree',
|
||||
stateVersion: 1,
|
||||
stateSchema,
|
||||
init: (_header, inheritedEventCount) => ({ created: [], inheritedEventCount }),
|
||||
apply: (state, event: SessionEvent) => {
|
||||
const record = pluginRecordOf(event)
|
||||
if (record?.type !== CREATED_RECORD) return state
|
||||
const parsed = worktreeSchema.safeParse(record.data)
|
||||
if (!parsed.success) return state
|
||||
return { ...state, created: [...state.created, { worktree: parsed.data, owned: record.seq >= state.inheritedEventCount }] }
|
||||
},
|
||||
wire: { viewSchema: z.array(creationSchema), view: state => state.created },
|
||||
} satisfies ProjectionDefinition<'worktree', WorktreeProjectionState>
|
||||
@@ -1,12 +1,69 @@
|
||||
/** Conservative inspection of a recorded worktree before its checkout is removed. */
|
||||
/** Identity validation shared by restoration and removal, and the conservative inspection before a checkout is removed. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-fs'
|
||||
import type { RestoreWorktreeRequest } from './types.ts'
|
||||
|
||||
type GitRead = (directory: string, args: string[]) => Promise<{ stdout: string; exitCode: number }>
|
||||
/** Runs one Git command in the owner's confinement and reports its output. */
|
||||
export type GitRead = (directory: string, args: string[]) => Promise<{ stdout: string; exitCode: number }>
|
||||
|
||||
/** Resolved canonical locations of a recorded checkout that validation confirmed. */
|
||||
export interface CheckoutIdentity {
|
||||
readonly root: Awaited<ReturnType<Context['fs']['resolve']>>
|
||||
readonly target: Awaited<ReturnType<Context['fs']['resolve']>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify checkout identity and account for every file Git might discard on removal.
|
||||
* Confirm that a recorded checkout names a canonical directory inside the
|
||||
* configured pool of the source checkout it claims, and that the source is
|
||||
* still that repository's top level.
|
||||
* @param ctx - execution-world filesystem provider.
|
||||
* @param directory - configured relative worktree pool.
|
||||
* @param request - saved checkout identity.
|
||||
* @param run - bounded Git runner with the owner's policy.
|
||||
* @param signal - cancellation of the lookups.
|
||||
* @returns the resolved root and target, or null when any identity check fails.
|
||||
*/
|
||||
export async function checkoutIdentity(
|
||||
ctx: Context, directory: string, request: RestoreWorktreeRequest, run: GitRead, signal: AbortSignal,
|
||||
): Promise<CheckoutIdentity | null> {
|
||||
const { path, repositoryRoot } = request
|
||||
const root = await ctx.fs.resolve(repositoryRoot, { signal })
|
||||
const pool = await ctx.fs.resolve(directory, { cwd: repositoryRoot, signal })
|
||||
const target = await ctx.fs.resolve(path, { cwd: repositoryRoot, signal })
|
||||
if (ctx.fs.processPath(root) !== repositoryRoot || ctx.fs.processPath(target) !== path
|
||||
|| !ctx.fs.contains(root, pool) || !ctx.fs.contains(pool, target) || pool.targetKey === target.targetKey) return null
|
||||
const top = await run(repositoryRoot, ['rev-parse', '--show-toplevel'])
|
||||
const actualRoot = await ctx.fs.resolve(top.stdout.replace(/\r?\n$/, ''), { cwd: repositoryRoot, signal })
|
||||
if (actualRoot.targetKey !== root.targetKey) return null
|
||||
return { root, target }
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the registration of `target` among the source repository's worktrees.
|
||||
* @param ctx - execution-world filesystem provider.
|
||||
* @param request - saved checkout identity.
|
||||
* @param target - resolved checkout directory.
|
||||
* @param run - bounded 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'], run: GitRead, signal: AbortSignal,
|
||||
): Promise<readonly string[] | undefined> {
|
||||
const registered = await run(request.repositoryRoot, ['worktree', 'list', '--porcelain', '-z'])
|
||||
for (const entry of registered.stdout.split('\0\0').map(entry => entry.split('\0'))) {
|
||||
const registeredPath = entry.find(field => field.startsWith('worktree '))?.slice('worktree '.length)
|
||||
if (registeredPath === undefined) continue
|
||||
const recorded = await ctx.fs.resolve(registeredPath, { cwd: request.repositoryRoot, signal })
|
||||
if (recorded.targetKey === target.targetKey) return entry
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify checkout identity and account for every file that Git's non-force
|
||||
* removal would refuse: tracked changes, untracked files, hidden index flags,
|
||||
* and submodules. Ignored files are not counted; `git worktree remove` discards them.
|
||||
* @param ctx - execution-world filesystem provider.
|
||||
* @param directory - configured relative worktree pool.
|
||||
* @param request - saved checkout identity.
|
||||
@@ -17,31 +74,17 @@ type GitRead = (directory: string, args: string[]) => Promise<{ stdout: string;
|
||||
export async function inspectRemoval(
|
||||
ctx: Context, directory: string, request: RestoreWorktreeRequest, run: GitRead, signal: AbortSignal,
|
||||
): Promise<boolean> {
|
||||
const { path, branch, repositoryRoot } = request
|
||||
const root = await ctx.fs.resolve(repositoryRoot, { signal })
|
||||
const pool = await ctx.fs.resolve(directory, { cwd: repositoryRoot, signal })
|
||||
const target = await ctx.fs.resolve(path, { cwd: repositoryRoot, signal })
|
||||
if (ctx.fs.processPath(root) !== repositoryRoot || ctx.fs.processPath(target) !== path
|
||||
|| !ctx.fs.contains(root, pool) || !ctx.fs.contains(pool, target) || pool.targetKey === target.targetKey) return false
|
||||
const { path, branch } = request
|
||||
const identity = await checkoutIdentity(ctx, directory, request, run, signal)
|
||||
if (identity === null) return false
|
||||
if ((await ctx.fs.lstat(path, undefined, signal))?.type !== 'directory') return false
|
||||
const top = await run(repositoryRoot, ['rev-parse', '--show-toplevel'])
|
||||
const actualRoot = await ctx.fs.resolve(top.stdout.replace(/\r?\n$/, ''), { cwd: repositoryRoot, signal })
|
||||
if (actualRoot.targetKey !== root.targetKey) return false
|
||||
const registered = await run(repositoryRoot, ['worktree', 'list', '--porcelain', '-z'])
|
||||
const entries = registered.stdout.split('\0\0').map(entry => entry.split('\0'))
|
||||
let fields: string[] | undefined
|
||||
for (const entry of entries.slice(1)) {
|
||||
const registeredPath = entry.find(field => field.startsWith('worktree '))?.slice('worktree '.length)
|
||||
if (registeredPath === undefined) continue
|
||||
const recorded = await ctx.fs.resolve(registeredPath, { cwd: repositoryRoot, signal })
|
||||
if (recorded.targetKey === target.targetKey) { fields = entry; break }
|
||||
}
|
||||
const fields = await registration(ctx, request, identity.target, run, 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
|
||||
const head = await run(path, ['symbolic-ref', 'HEAD'])
|
||||
if (head.stdout.trim() !== `refs/heads/${branch}`) return false
|
||||
const status = await run(path, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching', '--ignore-submodules=none'])
|
||||
const status = await run(path, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=none'])
|
||||
if (status.stdout.length !== 0) return false
|
||||
// Git status deliberately hides skip-worktree and assume-unchanged files.
|
||||
const flags = await run(path, ['ls-files', '-v', '-z'])
|
||||
|
||||
@@ -47,3 +47,22 @@ export interface RestoredWorktree {
|
||||
/** Whether the branch no longer existed and was created again at the base commit, without the commits it had gained. */
|
||||
branchRecreated: boolean
|
||||
}
|
||||
|
||||
/** One checkout in a Session's log and whether that Session, rather than a fork ancestor, created it. */
|
||||
export interface WorktreeCreation {
|
||||
readonly worktree: CreatedWorktree
|
||||
/** False for a creation inside the fork-inherited prefix. */
|
||||
readonly owned: boolean
|
||||
}
|
||||
|
||||
/** Process-local state of one archive-triggered cleanup of a checkout. */
|
||||
export interface WorktreeCleanup {
|
||||
/** Monotonic attempt number within this Host lifetime; a Remote waits on a specific one. */
|
||||
readonly revision: number
|
||||
/**
|
||||
* `scheduled` until the background inspection ends; `retained` when a use,
|
||||
* policy, or Git state keeps the checkout; `removed` after `git worktree
|
||||
* remove`; `failed` when removal threw and may have left a partial directory.
|
||||
*/
|
||||
readonly status: 'scheduled' | 'retained' | 'removed' | 'failed'
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import { access, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { unsupportedInbox, unsupportedModel } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
|
||||
import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import SessionStore, { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import * as SessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import SessionProjectionCache from '@deepseek-ai/dsh-session-projection-cache'
|
||||
import SessionQueryEngine from '@deepseek-ai/dsh-session-query'
|
||||
import type { SessionEventSearchPage, SessionSearchHit, SessionSearchPage } from '@deepseek-ai/dsh-session-query'
|
||||
import Storage from '@deepseek-ai/dsh-storage'
|
||||
import { DomainFacility } from '@deepseek-ai/dsh-storage-domain'
|
||||
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import WorkingDirectoryService from '@deepseek-ai/dsh-working-directory'
|
||||
import WorkspaceRegistry from '@deepseek-ai/dsh-workspace'
|
||||
import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts'
|
||||
import WorktreeService from '../src/index.ts'
|
||||
import type { CreatedWorktree, WorktreeCleanup } from '../src/index.ts'
|
||||
import { git, repository, UnusedSandbox } from './harness.ts'
|
||||
import { mkdtemp, realpath, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
|
||||
/** Archive tests only use the query service's listing and observation APIs. */
|
||||
class ArchiveQueries extends SessionQueryEngine {
|
||||
searchSessions(): Promise<SessionSearchPage<SessionSearchHit>> { throw new Error('search is not used') }
|
||||
searchEvents(): Promise<SessionEventSearchPage> { throw new Error('search is not used') }
|
||||
}
|
||||
|
||||
const cleanups: (() => Promise<void>)[] = []
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function agentFor(ctx: Context, session: Session): Agent {
|
||||
const scope = ctx.plugin(() => {})
|
||||
const agent: Agent = {
|
||||
id: session.id, session, options: {}, status: 'idle', ctx: scope.ctx, model: unsupportedModel(),
|
||||
inbox: unsupportedInbox(),
|
||||
send() {}, followup() {}, steer() {}, inject() {}, cancel() {},
|
||||
whenIdle: async () => {}, runMaintenance: task => task(new AbortController().signal),
|
||||
}
|
||||
return agent
|
||||
}
|
||||
|
||||
async function fixture(options: { cache?: boolean } = {}) {
|
||||
const temporary = await realpath(await mkdtemp(join(tmpdir(), 'dsh-worktree-archive-')))
|
||||
cleanups.push(() => rm(temporary, { recursive: true, force: true }))
|
||||
const root = await repository(temporary)
|
||||
const ctx = new Context()
|
||||
cleanups.push(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(LocalFileSystem, { cwd: root })
|
||||
await ctx.plugin(LocalSubprocessRuntime)
|
||||
await ctx.plugin(UnusedSandbox)
|
||||
await ctx.plugin(SandboxPolicyService, { mode: 'danger-full-access', workspaceRoot: root })
|
||||
await ctx.plugin(WorkingDirectoryService)
|
||||
await ctx.plugin(SessionPersistence, { root: join(temporary, 'sessions'), compression: 'none' })
|
||||
await ctx.plugin(ArchiveQueries)
|
||||
await ctx.plugin(Storage)
|
||||
ctx.storage.backend.register('memory', new MemoryStorageBackend(new MemoryMediaPool()))
|
||||
const domain = new DomainFacility(ctx, { backend: 'memory', routes: {} })
|
||||
ctx.storage.mount('domain', domain)
|
||||
ctx.provide('storageDomain', domain)
|
||||
if (options.cache === true) await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 1_000, writeIntervalMs: 60_000 })
|
||||
await ctx.plugin(WorkspaceRegistry)
|
||||
await ctx.plugin(WorktreeService, {})
|
||||
const session = ctx.sessions.create(SessionId('archive-owner'), { meta: { cwd: root } })
|
||||
const agent = agentFor(ctx, session)
|
||||
await ctx.agents.register(agent)
|
||||
const worktree = await ctx.worktrees.create(agent, { name: 'archive-me' })
|
||||
return { ctx, root, session, agent, worktree, temporary }
|
||||
}
|
||||
|
||||
type Fixture = Awaited<ReturnType<typeof fixture>>
|
||||
|
||||
/** The settled attempt of `session`, or null when the service registered none. */
|
||||
async function settled(f: Fixture, session: Session = f.session): Promise<WorktreeCleanup | null> {
|
||||
const scheduled = await f.ctx.worktrees.cleanupOf(session, null)
|
||||
return scheduled === null ? null : await f.ctx.worktrees.cleanupOf(session, scheduled.revision)
|
||||
}
|
||||
|
||||
async function persisted(f: Fixture, session: Session): Promise<void> {
|
||||
await using writer = await f.ctx.sessionPersistence.create(session.header)
|
||||
await writer.append(session.snapshotEvents())
|
||||
await writer.flush()
|
||||
await writer.close()
|
||||
}
|
||||
|
||||
/** A live Session whose store entry the test detaches itself, leaving only its persisted log. */
|
||||
function detachable(f: Fixture, id: string, meta: { cwd: string }): { session: Session; detach: () => void } {
|
||||
const session = f.ctx.sessions.prepare(SessionId(id), { meta })
|
||||
const detach = f.ctx.sessions.enter(session)
|
||||
f.ctx.sessions.announce(session)
|
||||
return { session, detach }
|
||||
}
|
||||
|
||||
describe('archive-triggered worktree cleanup', () => {
|
||||
it('removes the clean checkout the archived Session created and keeps its branch and commits', async () => {
|
||||
const f = await fixture()
|
||||
await writeFile(join(f.worktree.path, 'local.txt'), 'not pushed\n')
|
||||
await git(f.worktree.path, 'add', 'local.txt')
|
||||
await git(f.worktree.path, 'commit', '-m', 'local commit')
|
||||
const head = await git(f.worktree.path, 'rev-parse', 'HEAD')
|
||||
const statuses: WorktreeCleanup['status'][] = []
|
||||
f.ctx.on('worktree/cleanup', ({ cleanup }) => { statuses.push(cleanup.status) })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await f.ctx.worktrees.cleanupOf(f.session, null)).toMatchObject({ status: 'scheduled' })
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
expect(statuses).toEqual(['scheduled', 'removed'])
|
||||
await expect(access(f.worktree.path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect(await git(f.root, 'rev-parse', f.worktree.branch)).toBe(head)
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
|
||||
})
|
||||
|
||||
it('returns from admission before the inspection runs', async () => {
|
||||
const f = await fixture()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const list = f.ctx.sessionQuery.listSessions.bind(f.ctx.sessionQuery)
|
||||
vi.spyOn(f.ctx.sessionQuery, 'listSessions').mockImplementation(async (...args) => {
|
||||
await release.promise
|
||||
return await list(...args)
|
||||
})
|
||||
cleanups.push(async () => { release.resolve(undefined) })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await f.ctx.worktrees.cleanupOf(f.session, null)).toMatchObject({ status: 'scheduled' })
|
||||
release.resolve(undefined)
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
})
|
||||
|
||||
it('removes the checkout after the Session moved elsewhere, and the ordinary ensure contract holds afterwards', async () => {
|
||||
const f = await fixture()
|
||||
await f.ctx.workingDirectory.set(f.agent, f.root)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
await f.ctx.worktrees.restore(f.agent, f.worktree)
|
||||
await f.ctx.workingDirectory.set(f.agent, f.worktree.path)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
// The directory is gone: ensure recovers the original project as it documents, with no cleanup-specific failure.
|
||||
expect(await f.ctx.workingDirectory.ensure(f.agent)).toBe(f.root)
|
||||
})
|
||||
|
||||
it('retains an untracked file but not ignored files', async () => {
|
||||
const f = await fixture()
|
||||
await writeFile(join(f.worktree.path, 'keep.txt'), 'keep')
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'retained' })
|
||||
await access(f.worktree.path)
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
await rm(join(f.worktree.path, 'keep.txt'))
|
||||
await git(f.worktree.path, 'config', 'core.excludesFile', join(f.root, 'exclude'))
|
||||
await writeFile(join(f.root, 'exclude'), '.env\n')
|
||||
await writeFile(join(f.worktree.path, '.env'), 'private fixture')
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
})
|
||||
|
||||
it('registers nothing for a Session that created no checkout or only inherited one', async () => {
|
||||
const f = await fixture()
|
||||
const other = f.ctx.sessions.create(SessionId('no-checkout'), { meta: { cwd: f.root } })
|
||||
await f.ctx.workspaceRegistry.archiveSession(other.id)
|
||||
expect(await f.ctx.worktrees.cleanupOf(other, null)).toBeNull()
|
||||
const seed = f.session.snapshotEvents()
|
||||
const fork = f.ctx.sessions.create(SessionId('fork'), {
|
||||
seed, inheritedEventCount: SessionLogOffset(seed.length), meta: { isSeeded: true, cwd: f.root },
|
||||
})
|
||||
await f.ctx.workspaceRegistry.archiveSession(fork.id)
|
||||
expect(await f.ctx.worktrees.cleanupOf(fork, null)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('retains a checkout while a fork or a directory borrower is unarchived, and does not reconsider when they archive', async () => {
|
||||
const f = await fixture()
|
||||
const seed = f.session.snapshotEvents()
|
||||
const fork = f.ctx.sessions.create(SessionId('fork'), {
|
||||
seed, inheritedEventCount: SessionLogOffset(seed.length), meta: { isSeeded: true, cwd: f.root },
|
||||
})
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'retained' })
|
||||
await access(f.worktree.path)
|
||||
await f.ctx.workspaceRegistry.archiveSession(fork.id)
|
||||
expect(await f.ctx.worktrees.cleanupOf(fork, null)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
await f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
const borrower = f.ctx.sessions.create(SessionId('borrower'), { meta: { cwd: f.worktree.path } })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'retained' })
|
||||
await f.ctx.workspaceRegistry.archiveSession(borrower.id)
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('treats a subagent child beneath the archived Session as archived', async () => {
|
||||
const f = await fixture()
|
||||
const child = f.ctx.sessions.create(SessionId('child'), {
|
||||
meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: f.session.id },
|
||||
})
|
||||
const grandchild = f.ctx.sessions.create(SessionId('grandchild'), {
|
||||
meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: child.id },
|
||||
})
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).not.toContain(child.id)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).not.toContain(grandchild.id)
|
||||
})
|
||||
|
||||
it('retains a checkout for an unrelated subagent child that works inside it', async () => {
|
||||
const f = await fixture()
|
||||
const other = f.ctx.sessions.create(SessionId('other-parent'), { meta: { cwd: f.root } })
|
||||
f.ctx.sessions.create(SessionId('other-child'), { meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: other.id } })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'retained' })
|
||||
})
|
||||
|
||||
it('removes a persisted checkout without loading its Agent, reading cold Sessions from the projection cache when present', async () => {
|
||||
const f = await fixture({ cache: true })
|
||||
const owner = detachable(f, 'cold-owner', { cwd: f.root })
|
||||
const agent = agentFor(f.ctx, owner.session)
|
||||
const registration = f.ctx.agents.register(agent)
|
||||
await registration
|
||||
const worktree = await f.ctx.worktrees.create(agent, { name: 'cold-ui' })
|
||||
const bystander = detachable(f, 'cold-bystander', { cwd: f.root })
|
||||
await f.ctx.sessionProjectionCache.write(owner.session)
|
||||
await f.ctx.sessionProjectionCache.write(bystander.session)
|
||||
await persisted(f, owner.session)
|
||||
await persisted(f, bystander.session)
|
||||
await registration()
|
||||
owner.detach()
|
||||
bystander.detach()
|
||||
expect(f.ctx.sessions.get(owner.session.id)).toBeUndefined()
|
||||
const inspect = vi.spyOn(f.ctx.sessionQuery, 'inspectSession')
|
||||
await f.ctx.workspaceRegistry.archiveSession(owner.session.id)
|
||||
expect(await settled(f, owner.session)).toMatchObject({ status: 'removed' })
|
||||
// The creator is prepared once for its own creations and policy; the cached bystander never is.
|
||||
expect(inspect.mock.calls.map(call => call[0])).toEqual([owner.session.id, owner.session.id])
|
||||
expect(f.ctx.sessions.get(owner.session.id)).toBeUndefined()
|
||||
expect(f.ctx.agents.list().some(agent => agent.session.id === owner.session.id)).toBe(false)
|
||||
await expect(access(worktree.path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
})
|
||||
|
||||
it('reads a cold Session from its log without the cache', async () => {
|
||||
const f = await fixture()
|
||||
const borrower = detachable(f, 'cold-borrower', { cwd: f.worktree.path })
|
||||
await persisted(f, borrower.session)
|
||||
borrower.detach()
|
||||
expect(f.ctx.sessions.get(borrower.session.id)).toBeUndefined()
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'retained' })
|
||||
})
|
||||
|
||||
it('does not wait for the archived Session\'s own stopping work', async () => {
|
||||
const f = await fixture()
|
||||
f.ctx.on('workspace/session-activity', async (_request, next) => [{ kind: 'turn' }, ...await next()])
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id, { stopActivity: true })
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
})
|
||||
|
||||
it('retains a checkout under its creator\'s read-only policy', async () => {
|
||||
const f = await fixture()
|
||||
f.session.append('sandbox/mode', { mode: 'read-only' })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'retained' })
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('keeps the archive and reports a failed removal', async () => {
|
||||
const f = await fixture()
|
||||
const warning = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {})
|
||||
const service = f.ctx.worktrees as unknown as { removeCheckout: () => Promise<boolean> }
|
||||
vi.spyOn(service, 'removeCheckout').mockRejectedValue(new Error('checkout removal denied'))
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
expect(await settled(f)).toMatchObject({ status: 'failed' })
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
|
||||
expect(warning).toHaveBeenCalledOnce()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
|
||||
it('cancels an unadmitted removal on unarchive and waits for an admitted one', async () => {
|
||||
const f = await fixture()
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const service = f.ctx.worktrees as unknown as {
|
||||
removeCheckout: (session: Session, request: CreatedWorktree, signal: AbortSignal, admit: () => boolean) => Promise<boolean>
|
||||
}
|
||||
const original = service.removeCheckout.bind(service)
|
||||
vi.spyOn(service, 'removeCheckout').mockImplementation(async (session, request, signal, admit) => {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
return await original(session, request, signal, admit)
|
||||
})
|
||||
cleanups.push(async () => { release.resolve(undefined) })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
await entered.promise
|
||||
const unarchive = f.ctx.workspaceRegistry.unarchiveSession(f.session.id)
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
|
||||
release.resolve(undefined)
|
||||
await unarchive
|
||||
expect(f.ctx.workspaceRegistry.archivedSessionIds).not.toContain(f.session.id)
|
||||
expect(await f.ctx.worktrees.cleanupOf(f.session, null)).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
expect(await f.ctx.workingDirectory.ensure(f.agent)).toBe(f.worktree.path)
|
||||
})
|
||||
|
||||
it('holds directory entry into a checkout being removed and leaves other paths alone', async () => {
|
||||
const f = await fixture()
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const service = f.ctx.worktrees as unknown as { removeCheckout: (...args: unknown[]) => Promise<boolean> }
|
||||
const original = service.removeCheckout.bind(service)
|
||||
vi.spyOn(service, 'removeCheckout').mockImplementation(async (...args) => {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
return await original(...args)
|
||||
})
|
||||
cleanups.push(async () => { release.resolve(undefined) })
|
||||
await f.ctx.workingDirectory.set(f.agent, f.root)
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
await entered.promise
|
||||
const other = f.ctx.sessions.create(SessionId('elsewhere'), { meta: { cwd: f.root } })
|
||||
const otherAgent = agentFor(f.ctx, other)
|
||||
await f.ctx.agents.register(otherAgent)
|
||||
expect(await f.ctx.workingDirectory.ensure(otherAgent)).toBe(f.root)
|
||||
let settledEntry = false
|
||||
const entering = f.ctx.workingDirectory.set(otherAgent, f.worktree.path)
|
||||
.then(() => { settledEntry = true }, () => { settledEntry = true })
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
expect(settledEntry).toBe(false)
|
||||
release.resolve(undefined)
|
||||
await entering
|
||||
expect(await settled(f)).toMatchObject({ status: 'removed' })
|
||||
// Entry ran after removal, against a directory that no longer exists.
|
||||
expect(f.ctx.workingDirectory.get(other)).toBe(f.root)
|
||||
})
|
||||
|
||||
it('withdraws listeners before draining, so disposal neither fails unrelated access nor serves a stale result', async () => {
|
||||
const f = await fixture()
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const service = f.ctx.worktrees as unknown as { removeCheckout: () => Promise<boolean> }
|
||||
vi.spyOn(service, 'removeCheckout').mockImplementation(async () => {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
return false
|
||||
})
|
||||
cleanups.push(async () => { release.resolve(undefined) })
|
||||
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
|
||||
await entered.promise
|
||||
const scheduled = await f.ctx.worktrees.cleanupOf(f.session, null)
|
||||
const result = f.ctx.worktrees.cleanupOf(f.session, scheduled!.revision)
|
||||
const disposing = f.ctx.fiber.dispose()
|
||||
release.resolve(undefined)
|
||||
await disposing
|
||||
expect(await result).toBeNull()
|
||||
await access(f.worktree.path)
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,18 @@ import { access, mkdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { inspectRemoval } from '../src/removal.ts'
|
||||
import type { RestoreWorktreeRequest } from '../src/types.ts'
|
||||
import { git, harness, repository, testAgent } from './harness.ts'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
|
||||
/** The service's inspection-and-removal step, reached as archive cleanup reaches it. */
|
||||
function remove(ctx: Context, agent: Agent, request: RestoreWorktreeRequest, admit: () => boolean = () => true): Promise<boolean> {
|
||||
const service = ctx.worktrees as unknown as {
|
||||
removeCheckout(session: Agent['session'], request: RestoreWorktreeRequest, signal: AbortSignal, admit: () => boolean): Promise<boolean>
|
||||
}
|
||||
return service.removeCheckout(agent.session, request, new AbortController().signal, admit)
|
||||
}
|
||||
|
||||
const disposers: (() => Promise<void>)[] = []
|
||||
afterEach(async () => {
|
||||
@@ -20,14 +31,15 @@ async function fixture() {
|
||||
}
|
||||
|
||||
describe('safe worktree removal', () => {
|
||||
it('removes a clean checkout, preserves local commits and restores the retained branch', async () => {
|
||||
it('removes a clean checkout, preserves local commits and restores the retained branch', { timeout: 15_000 }, async () => {
|
||||
const { ctx, agent, worktree, root } = await fixture()
|
||||
await writeFile(join(worktree.path, 'local.txt'), 'not pushed\n')
|
||||
await git(worktree.path, 'add', 'local.txt')
|
||||
await git(worktree.path, 'commit', '-m', 'local commit')
|
||||
const head = await git(worktree.path, 'rev-parse', 'HEAD')
|
||||
expect(await ctx.worktrees.canRemove(ctx.sandboxPolicy.resolve({ session: agent.session }), worktree)).toBe(true)
|
||||
expect(await ctx.worktrees.remove(ctx.sandboxPolicy.resolve({ session: agent.session }), worktree)).toBe(true)
|
||||
expect(await remove(ctx, agent, worktree, () => false)).toBe(false)
|
||||
await access(worktree.path)
|
||||
expect(await remove(ctx, agent, worktree)).toBe(true)
|
||||
await expect(access(worktree.path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect(await git(root, 'rev-parse', worktree.branch)).toBe(head)
|
||||
expect(await git(root, 'worktree', 'list', '--porcelain')).not.toContain(worktree.path)
|
||||
@@ -35,31 +47,31 @@ describe('safe worktree removal', () => {
|
||||
expect(await git(worktree.path, 'rev-parse', 'HEAD')).toBe(head)
|
||||
})
|
||||
|
||||
it.each(['modified', 'staged', 'untracked', 'ignored', 'assume-unchanged', 'skip-worktree'] as const)(
|
||||
it.each(['modified', 'staged', 'untracked', 'assume-unchanged', 'skip-worktree'] as const)(
|
||||
'retains %s files', async (kind) => {
|
||||
const { ctx, agent, worktree } = await fixture()
|
||||
const tracked = join(worktree.path, 'tracked.txt')
|
||||
if (kind === 'untracked') await writeFile(join(worktree.path, 'new.txt'), 'keep')
|
||||
else if (kind === 'ignored') {
|
||||
await git(worktree.path, 'config', 'core.excludesFile', join(worktree.repositoryRoot, 'exclude'))
|
||||
await writeFile(join(worktree.repositoryRoot, 'exclude'), '.env\n')
|
||||
await writeFile(join(worktree.path, '.env'), 'private fixture')
|
||||
} else {
|
||||
else {
|
||||
await writeFile(tracked, 'keep\n')
|
||||
if (kind === 'staged') await git(worktree.path, 'add', 'tracked.txt')
|
||||
if (kind === 'assume-unchanged' || kind === 'skip-worktree') await git(worktree.path, 'update-index', `--${kind}`, 'tracked.txt')
|
||||
}
|
||||
expect(await ctx.worktrees.remove(ctx.sandboxPolicy.resolve({ session: agent.session }), worktree)).toBe(false)
|
||||
expect(await remove(ctx, agent, worktree)).toBe(false)
|
||||
await access(worktree.path)
|
||||
},
|
||||
)
|
||||
|
||||
it('rechecks after an eligible inspection', async () => {
|
||||
it('removes a checkout that holds only ignored files, as Git does without force', async () => {
|
||||
const { ctx, agent, worktree } = await fixture()
|
||||
expect(await ctx.worktrees.canRemove(ctx.sandboxPolicy.resolve({ session: agent.session }), worktree)).toBe(true)
|
||||
await writeFile(join(worktree.path, 'new.txt'), 'keep')
|
||||
expect(await ctx.worktrees.remove(ctx.sandboxPolicy.resolve({ session: agent.session }), worktree)).toBe(false)
|
||||
await access(worktree.path)
|
||||
await git(worktree.path, 'config', 'core.excludesFile', join(worktree.repositoryRoot, 'exclude'))
|
||||
await writeFile(join(worktree.repositoryRoot, 'exclude'), '.env\nnode_modules/\n')
|
||||
await writeFile(join(worktree.path, '.env'), 'private fixture')
|
||||
await mkdir(join(worktree.path, 'node_modules', 'dep'), { recursive: true })
|
||||
await writeFile(join(worktree.path, 'node_modules', 'dep', 'index.js'), 'module.exports = 1')
|
||||
expect(await remove(ctx, agent, worktree)).toBe(true)
|
||||
await expect(access(worktree.path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect(await git(worktree.repositoryRoot, 'rev-parse', worktree.branch)).toBe(worktree.baseCommit)
|
||||
})
|
||||
|
||||
it.each(['locked', 'detached', 'branch-mismatch', 'outside-pool', 'missing', 'nested-repository'] as const)(
|
||||
@@ -76,7 +88,7 @@ describe('safe worktree removal', () => {
|
||||
await mkdir(nested)
|
||||
await git(nested, 'init')
|
||||
}
|
||||
expect(await ctx.worktrees.remove(ctx.sandboxPolicy.resolve({ session: agent.session }), request)).toBe(false)
|
||||
expect(await remove(ctx, agent, request)).toBe(false)
|
||||
expect(await git(root, 'rev-parse', worktree.branch)).toBe(worktree.baseCommit)
|
||||
},
|
||||
)
|
||||
@@ -97,13 +109,11 @@ describe('safe worktree removal', () => {
|
||||
)
|
||||
|
||||
|
||||
it('serializes a restore requested while the same checkout is being removed', async () => {
|
||||
const { ctx, agent, worktree } = await fixture()
|
||||
const removing = ctx.worktrees.remove(ctx.sandboxPolicy.resolve({ session: agent.session }), worktree)
|
||||
const restoring = ctx.worktrees.restore(agent, worktree)
|
||||
expect(await removing).toBe(true)
|
||||
expect(await restoring).toEqual({ path: worktree.path, branchRecreated: false })
|
||||
expect(await git(worktree.path, 'rev-parse', 'HEAD')).toBe(worktree.baseCommit)
|
||||
it('restores over the identity checks removal shares, rejecting a target outside the pool', async () => {
|
||||
const { ctx, agent, worktree, root } = await fixture()
|
||||
await git(root, 'worktree', 'remove', worktree.path)
|
||||
await expect(ctx.worktrees.restore(agent, { ...worktree, path: join(root, 'outside-pool') })).rejects.toThrow('canonical directory inside the configured pool')
|
||||
expect(await ctx.worktrees.restore(agent, worktree)).toEqual({ path: worktree.path, branchRecreated: false })
|
||||
})
|
||||
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs'
|
||||
import { access, mkdir, readdir, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
import { join, sep } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { pluginRecordOf } from '@deepseek-ai/dsh-session'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import WorktreeService from '../src/index.ts'
|
||||
@@ -38,6 +39,10 @@ describe('creating and entering retained worktrees', () => {
|
||||
const result = await ctx.worktrees.create(agent, { name: 'topic' })
|
||||
expect(result).toEqual({ path: join(root, '.agents/worktrees/topic'), branch: 'topic', baseCommit, repositoryRoot: root })
|
||||
expect(ctx.workingDirectory.get(agent.session)).toBe(result.path)
|
||||
const events = agent.session.snapshotEvents()
|
||||
const created = events.findIndex(event => pluginRecordOf(event)?.type === 'plugin:worktree/created')
|
||||
expect(created).toBeGreaterThan(events.findIndex(event => event.type === 'working-directory/change'))
|
||||
expect(pluginRecordOf(events[created]!)?.data).toEqual(result)
|
||||
expect(await git(result.path, 'symbolic-ref', '--short', 'HEAD')).toBe('topic')
|
||||
expect(await contents(join(result.path, 'tracked.txt'))).toBe('initial\n')
|
||||
expect(await git(root, 'show', ':tracked.txt')).toBe('staged')
|
||||
|
||||
@@ -37,6 +37,21 @@
|
||||
},
|
||||
{
|
||||
"path": "../../util/timeout"
|
||||
},
|
||||
{
|
||||
"path": "../../core/session"
|
||||
},
|
||||
{
|
||||
"path": "../../session/session-projection"
|
||||
},
|
||||
{
|
||||
"path": "../../session/session-projection-cache"
|
||||
},
|
||||
{
|
||||
"path": "../../session-query/session-query"
|
||||
},
|
||||
{
|
||||
"path": "../../workspace/workspace"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1310,10 +1310,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
throws: ['when the Host lacks the Session query, projection cache, storage, or Session store service.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<ForgeWorktreeCleanup | null>',
|
||||
description: 'Read or await an archive cleanup owned by this Host lifetime.',
|
||||
signature: '@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null>',
|
||||
description: 'Read or await the worktree service\'s archive cleanup of the Session\'s checkout.',
|
||||
parameters: [{ name: 'session', description: 'Session whose cleanup is visible to the caller.' }, { name: 'revision', description: 'null reads now; a matching revision waits for completion.' }],
|
||||
returns: 'the cleanup state, or null when none exists or the revision was superseded.',
|
||||
returns: 'the cleanup state, or null without a worktree service, an attempt, or a current revision.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote async branches(session: Session, signal: AbortSignal): Promise<ForgeBranches>',
|
||||
@@ -4518,7 +4518,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
description: 'Validate the current directory and restore the original project when it disappeared.',
|
||||
parameters: [{ name: 'agent', description: 'live or unpublished Agent owning the Session.' }, { name: 'signal', description: 'cancellation for filesystem inspection.' }],
|
||||
returns: 'the existing directory; recovery is committed before fulfillment. A notice failure is warned without reverting the committed state.',
|
||||
throws: ['when the original project is also unavailable.'],
|
||||
throws: ['when the original project is also unavailable, or when a `working-directory/access` listener rejects.'],
|
||||
},
|
||||
{
|
||||
signature: 'set(agent: Agent, path: string, signal?: AbortSignal): Promise<string>',
|
||||
@@ -4735,8 +4735,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
},
|
||||
{
|
||||
key: 'worktrees',
|
||||
summary: 'Creates retained Git worktrees under the mounted filesystem and sandbox providers.',
|
||||
description: 'Creates retained Git worktrees under the mounted filesystem and sandbox providers.',
|
||||
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.',
|
||||
methods: [
|
||||
{
|
||||
signature: 'async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<CreatedWorktree>',
|
||||
@@ -4751,16 +4751,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
returns: 'the directory and whether the branch was created again.',
|
||||
},
|
||||
{
|
||||
signature: 'canRemove(policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal): Promise<boolean>',
|
||||
description: 'Inspect a recorded checkout for non-destructive removal. Dirty, ignored, locked, detached, nested, mismatched, and missing checkouts are retained. Inspection errors reject.',
|
||||
parameters: [{ name: 'policy', description: 'resolved execution policy of the owning Session.' }, { name: 'request', description: 'recorded checkout identity.' }, { name: 'signal', description: 'cancellation of inspection.' }],
|
||||
returns: 'whether the checkout is currently eligible; removal always inspects again.',
|
||||
},
|
||||
{
|
||||
signature: 'remove( policy: SandboxExecutionPolicy, request: RestoreWorktreeRequest, signal?: AbortSignal, admit: () => boolean = () => true, ): Promise<boolean>',
|
||||
description: 'Remove an eligible checkout and its registration without force or branch deletion. Callers must exclude new users until settlement. A rejection can leave a partially removed directory; the branch remains available for restoration.',
|
||||
parameters: [{ name: 'policy', description: 'resolved execution policy of the owning Session.' }, { name: 'request', description: 'recorded checkout identity.' }, { name: 'signal', description: 'cancellation before or during removal.' }, { name: 'admit', description: 'synchronous final admission after inspection; false retains the checkout.' }],
|
||||
returns: 'true when removed; false when inspection or admission requires retention.',
|
||||
signature: 'async cleanupOf(session: Session, revision: number | null): Promise<WorktreeCleanup | null>',
|
||||
description: 'Read the archive cleanup of a Session\'s created checkout; waiting never starts one. Absent without the Workspace and query providers.',
|
||||
parameters: [{ name: 'session', description: 'archived Session whose cleanup is read.' }, { name: 'revision', description: 'null reads at once; a matching revision waits for that attempt to settle.' }],
|
||||
returns: 'the attempt state, or null when none exists, the revision was superseded, or the service is stopping.',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -5475,10 +5469,10 @@ export const EVENT_API: readonly EventApiEntry[] = [
|
||||
{
|
||||
name: 'working-directory/access',
|
||||
mode: 'waterfall',
|
||||
signature: '\'working-directory/access\'(request: { agent: Agent; path: string | null }, next: () => Promise<string>): Promise<string>',
|
||||
summary: 'Coordinate directory validation and publication with resource lifecycle operations.',
|
||||
description: 'Coordinate directory validation and publication with resource lifecycle operations.',
|
||||
parameters: [{ name: 'request', description: 'owner and requested path; null validates the current directory.' }, { name: 'next', description: 'perform validation and commit after competing operations settle.' }],
|
||||
signature: '\'working-directory/access\'( request: { agent: Agent; path: string | null; signal: AbortSignal }, next: () => Promise<string>, ): Promise<string>',
|
||||
summary: 'Coordinate directory validation and publication with a resource operation on the directory, such as a checkout being removed.',
|
||||
description: 'Coordinate directory validation and publication with a resource operation on the directory, such as a checkout being removed. A listener that must wait awaits that operation, then calls `next()`; every other listener calls `next()` at once. A rejection fails this access and leaves the recorded directory unchanged; it is not a fallback.',
|
||||
parameters: [{ name: 'request', description: 'owner, requested path (null validates the current directory), and the access\'s cancellation.' }, { name: 'next', description: 'perform validation and commit.' }],
|
||||
},
|
||||
{
|
||||
name: 'workspace/session-activity',
|
||||
@@ -5493,7 +5487,7 @@ export const EVENT_API: readonly EventApiEntry[] = [
|
||||
mode: 'parallel',
|
||||
signature: '\'workspace/session-archived\'(request: SessionActivityRequest): Promise<void> | void',
|
||||
summary: 'Admit optional follow-up work after durable archival and any stop requests.',
|
||||
description: 'Admit optional follow-up work after durable archival and any stop requests. Listener failures are logged without undoing archival. Listeners own and drain their background work.',
|
||||
description: 'Admit optional follow-up work after durable archival and any stop requests. Dispatched inside the registry\'s write queue: a listener registers its work and returns, and runs the work and any unbounded I/O afterwards. Listener failures are logged without undoing archival. Listeners own and drain their background work.',
|
||||
parameters: [{ name: 'request', description: 'newly archived Session; repeated archive requests do not dispatch.' }],
|
||||
},
|
||||
{
|
||||
@@ -5512,6 +5506,14 @@ export const EVENT_API: readonly EventApiEntry[] = [
|
||||
description: 'Cancel or settle archive follow-up work before making a Session available again. A rejection retains the archived state.',
|
||||
parameters: [{ name: 'request', description: 'Session about to leave the archive set.' }],
|
||||
},
|
||||
{
|
||||
name: 'worktree/cleanup',
|
||||
mode: 'emit',
|
||||
signature: '\'worktree/cleanup\'(info: { sessionId: SessionId; path: string; cleanup: WorktreeCleanup }): void',
|
||||
summary: 'A cleanup attempt changed state.',
|
||||
description: 'A cleanup attempt changed state. Fires once at admission with `scheduled` and once at settlement with the final status.',
|
||||
parameters: [{ name: 'info', description: 'the archived Session, the checkout, and the attempt state.' }],
|
||||
},
|
||||
]
|
||||
|
||||
/** Shapes of every exported type the Service and Event signatures reference (transitively), sorted by name. */
|
||||
@@ -6620,10 +6622,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ForgeWorktreeBlocker',
|
||||
declaration: 'export type ForgeWorktreeBlocker = \'not-git\' | \'outside-writable-root\' | \'read-only\';',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeCleanup',
|
||||
declaration: 'export interface ForgeWorktreeCleanup {\n readonly revision: number;\n readonly status: \'scheduled\' | \'retained\' | \'removed\' | \'failed\';\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeCreation',
|
||||
declaration: 'export interface ForgeWorktreeCreation {\n readonly phase: \'prepare\' | \'checkout\';\n readonly branch: string;\n readonly from: string | null;\n readonly held: boolean;\n}',
|
||||
@@ -10440,6 +10438,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'WorkspaceView',
|
||||
declaration: 'export interface WorkspaceView {\n readonly workspaceId: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly sessionIds: readonly SessionId[];\n readonly createdAt: string;\n readonly updatedAt: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'WorktreeCleanup',
|
||||
declaration: 'export interface WorktreeCleanup {\n readonly revision: number;\n readonly status: \'scheduled\' | \'retained\' | \'removed\' | \'failed\';\n}',
|
||||
},
|
||||
]
|
||||
|
||||
/** The inherited `ctx` API (cordis core + loader/hmr/timer), in curated order. */
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 87d7d2dbd7777429
|
||||
/deepseek-ai-dsh-working-directory/use-this-package:
|
||||
en: ef8b2878e00b0509
|
||||
zh: a590766fa91acd97
|
||||
en: e65405026debde7c
|
||||
zh: e12a648eb10ed16b
|
||||
/deepseek-ai-dsh-working-directory/understand-the-implementation:
|
||||
en: f0458147d29631b1
|
||||
zh: 6a288670dd084ffb
|
||||
|
||||
@@ -33,7 +33,7 @@ Mount alongside `fs`, `sessionProjections`, and `systemPrompt`. `defaultDirector
|
||||
|
||||
-----
|
||||
|
||||
Directory validation and publication delegate through `working-directory/access`, allowing resource owners to serialize checkout removal against `ensure` and `set`. A listener must call `next()` for admitted access; rejecting leaves the recorded directory unchanged. Existing subprocesses keep their own directories.
|
||||
Directory validation and publication delegate through `working-directory/access`, so the owner of a directory being removed can hold `ensure` and `set` into that directory until its operation settles. A listener waits only for an operation on the requested or current path, honours the request's `signal` while waiting, and otherwise calls `next()` at once; a rejection fails that access and leaves the recorded directory unchanged, with no fallback. Existing subprocesses keep their own directories.
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
@@ -33,7 +33,7 @@ kind: "package-reference"
|
||||
|
||||
-----
|
||||
|
||||
目录验证与发布通过 `working-directory/access` 委派,使资源所有者能够协调检出目录删除与 `ensure`、`set` 的执行。监听器必须对允许的访问调用 `next()`;拒绝时不改变已记录的目录。已有子进程保留自己的目录。
|
||||
目录验证与发布通过 `working-directory/access` 委派,使正在删除某目录的所有者可以阻塞进入该目录的 `ensure` 与 `set`,直到其操作结束。监听器只为请求路径或当前路径上的操作等待,等待时遵守请求的 `signal`,其余情况立即调用 `next()`;拒绝会使本次访问失败并保持记录的目录不变,不做回退。已有子进程保留各自的目录。
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
@@ -17,12 +17,19 @@ import type {} from '@deepseek-ai/dsh-system-prompt'
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Events {
|
||||
/**
|
||||
* Coordinate directory validation and publication with resource lifecycle operations.
|
||||
* @param request - owner and requested path; null validates the current directory.
|
||||
* @param next - perform validation and commit after competing operations settle.
|
||||
* Coordinate directory validation and publication with a resource operation
|
||||
* on the directory, such as a checkout being removed. A listener that must
|
||||
* wait awaits that operation, then calls `next()`; every other listener
|
||||
* calls `next()` at once. A rejection fails this access and leaves the
|
||||
* recorded directory unchanged; it is not a fallback.
|
||||
* @param request - owner, requested path (null validates the current directory), and the access's cancellation.
|
||||
* @param next - perform validation and commit.
|
||||
* @mode waterfall
|
||||
*/
|
||||
'working-directory/access'(request: { agent: Agent; path: string | null }, next: () => Promise<string>): Promise<string>
|
||||
'working-directory/access'(
|
||||
request: { agent: Agent; path: string | null; signal: AbortSignal },
|
||||
next: () => Promise<string>,
|
||||
): Promise<string>
|
||||
}
|
||||
interface Context {
|
||||
workingDirectory: WorkingDirectoryService
|
||||
@@ -138,10 +145,10 @@ export class WorkingDirectoryService extends Service {
|
||||
* @param signal - cancellation for filesystem inspection.
|
||||
* @returns the existing directory; recovery is committed before fulfillment.
|
||||
* A notice failure is warned without reverting the committed state.
|
||||
* @throws when the original project is also unavailable.
|
||||
* @throws when the original project is also unavailable, or when a `working-directory/access` listener rejects.
|
||||
*/
|
||||
ensure(agent: Agent, signal?: AbortSignal): Promise<string> {
|
||||
return this.serialize(agent, signal, control => this.ctx.waterfall('working-directory/access', { agent, path: null }, async () => {
|
||||
return this.serialize(agent, signal, control => this.ctx.waterfall('working-directory/access', { agent, path: null, signal: control }, async () => {
|
||||
const current = this.get(agent.session)
|
||||
const target = await this.ctx.fs.resolve(current, { signal: control })
|
||||
const info = await this.ctx.fs.stat(target, control)
|
||||
@@ -170,7 +177,7 @@ export class WorkingDirectoryService extends Service {
|
||||
* @throws when the requested path is not an existing directory.
|
||||
*/
|
||||
set(agent: Agent, path: string, signal?: AbortSignal): Promise<string> {
|
||||
return this.serialize(agent, signal, control => this.ctx.waterfall('working-directory/access', { agent, path }, async () => {
|
||||
return this.serialize(agent, signal, control => this.ctx.waterfall('working-directory/access', { agent, path, signal: control }, async () => {
|
||||
if (path.length === 0) throw new Error('working-directory: cd must not be empty')
|
||||
const directory = await this.directory(path, this.get(agent.session), control)
|
||||
this.commit(agent, directory, false, control)
|
||||
|
||||
@@ -42,8 +42,8 @@
|
||||
en: e969314497b99389
|
||||
zh: 82eafc832617a1eb
|
||||
/deepseek-ai-dsh-workspace/understand-the-implementation/api-behavior:
|
||||
en: 07005249acdde7ad
|
||||
zh: dfd38feaa1b217f7
|
||||
en: 8fcd81ee32f3c01e
|
||||
zh: 08ac92d085bb8147
|
||||
/deepseek-ai-dsh-workspace/understand-the-implementation/source-map:
|
||||
en: 6899c50041c3d1ef
|
||||
zh: ea70fda89cc50465
|
||||
|
||||
@@ -102,7 +102,7 @@ The API has two owners: `WorkspaceRegistry` creates, orders, and deletes project
|
||||
|
||||
Archive admission is a capability seam over two Host events this package declares and dispatches: `workspace/session-activity` (waterfall) asks the composed providers what still runs for a Session, and `workspace/session-stop` (parallel) asks them to stop it. `archiveSession(sessionId)` asks the activity waterfall once and rejects a non-empty answer with `WorkspaceActiveSessionError`, whose `activity` lists each family with its items — the keys are the providers' own, merged into `SessionActivityKindMap`, which this package leaves empty; `archiveSession(sessionId, { stopActivity: true })` skips the activity check, writes the archive, and then dispatches the stop event, so the durable archive set already gates every wake the stops induce; a rejecting provider is logged and the archive stays. The call resolves after stop requests and archive follow-up admission; the stopped work settles independently. Both questions come after the existence check and never for an already archived id. The shipped providers are the Agent registry (the running turn), the job registry seam (owned jobs), the Subagent runtime (running descendants), and the Schedule plugin (active reminders); a composition without providers archives freely.
|
||||
|
||||
`workspace/session-archived` admits optional follow-up work after the durable archive and stop requests. Providers own cancellation, failure reporting, and disposal of that work; an admission failure is logged without undoing archival. `workspace/session-unarchiving` lets those providers cancel or settle follow-up work before the archive flag is removed. The registry carries no Git cleanup policy.
|
||||
`workspace/session-archived` admits optional follow-up work after the durable archive and stop requests. It dispatches inside the registry's write queue, so a listener registers its work and returns; the work itself, and any unbounded I/O it needs, runs afterwards. Providers own cancellation, failure reporting, and disposal of that work; an admission failure is logged without undoing archival. `workspace/session-unarchiving` lets those providers cancel or settle follow-up work before the archive flag is removed. The registry carries no Git cleanup policy.
|
||||
|
||||
### Source map
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操
|
||||
|
||||
归档准入是本包声明并派发的两个宿主事件之上的能力接缝:`workspace/session-activity`(waterfall)向已组合的提供方询问某会话还有什么在跑,`workspace/session-stop`(parallel)请它们停止这些工作。`archiveSession(sessionId)` 只询问一次活动 waterfall,对非空答案以 `WorkspaceActiveSessionError` 拒绝,其 `activity` 按族列出各项——键由各提供方自己合并进本包留空的 `SessionActivityKindMap`;`archiveSession(sessionId, { stopActivity: true })` 跳过活动检查,先写入归档,再派发停止事件,因此持久化的归档集合已经拦住停止所引发的每一次唤醒;提供方抛错只记日志,归档保留。调用在每个提供方的停止请求都已发出后返回,被停止的工作自行收敛。两种询问都在存在性检查之后进行,对已归档 id 从不发生。随附的提供方是 Agent 注册表(运行中的回合)、任务注册表接缝(所属任务)、Subagent runtime(运行中的子孙)与 Schedule 插件(活跃提醒);没有提供方的组合可自由归档。
|
||||
|
||||
`workspace/session-archived` 在归档持久化并发出停止请求后,接纳可选的后续工作。提供方负责取消、失败报告和释放;准入失败会记录日志,但不撤销归档。`workspace/session-unarchiving` 让提供方在移除归档标记前取消或结束后续工作。注册表不包含 Git 清理策略。
|
||||
`workspace/session-archived` 在归档持久化并发出停止请求后,接纳可选的后续工作。它在注册表的写队列内派发,因此监听器只登记工作并返回;工作本身及其所需的无界 I/O 在之后执行。提供方负责取消、失败报告和释放;准入失败会记录日志,但不撤销归档。`workspace/session-unarchiving` 让提供方在移除归档标记前取消或结束后续工作。注册表不包含 Git 清理策略。
|
||||
|
||||
### 源码地图
|
||||
|
||||
|
||||
@@ -147,7 +147,9 @@ declare module '@deepseek-ai/cordis' {
|
||||
'workspace/session-stop'(request: SessionActivityRequest): Promise<void> | void
|
||||
/**
|
||||
* Admit optional follow-up work after durable archival and any stop requests.
|
||||
* Listener failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
* Dispatched inside the registry's write queue: a listener registers its work
|
||||
* and returns, and runs the work and any unbounded I/O afterwards. Listener
|
||||
* failures are logged without undoing archival. Listeners own and drain their background work.
|
||||
* @param request - newly archived Session; repeated archive requests do not dispatch.
|
||||
* @mode parallel
|
||||
*/
|
||||
|
||||
Generated
+21
-15
@@ -9310,9 +9310,6 @@ importers:
|
||||
'@deepseek-ai/dsh-fs-local':
|
||||
specifier: workspace:*
|
||||
version: link:../../fs/fs-local
|
||||
'@deepseek-ai/dsh-jobs':
|
||||
specifier: workspace:*
|
||||
version: link:../../jobs/jobs
|
||||
'@deepseek-ai/dsh-llm':
|
||||
specifier: workspace:*
|
||||
version: link:../../llm/llm
|
||||
@@ -9328,9 +9325,6 @@ importers:
|
||||
'@deepseek-ai/dsh-session':
|
||||
specifier: workspace:*
|
||||
version: link:../../core/session
|
||||
'@deepseek-ai/dsh-session-persistence-jsonl':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/session-persistence-jsonl
|
||||
'@deepseek-ai/dsh-session-projection':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/session-projection
|
||||
@@ -9340,9 +9334,6 @@ importers:
|
||||
'@deepseek-ai/dsh-session-query':
|
||||
specifier: workspace:*
|
||||
version: link:../../session-query/session-query
|
||||
'@deepseek-ai/dsh-storage':
|
||||
specifier: workspace:*
|
||||
version: link:../../storage/storage
|
||||
'@deepseek-ai/dsh-subprocess':
|
||||
specifier: workspace:*
|
||||
version: link:../../subprocess/subprocess
|
||||
@@ -9352,9 +9343,6 @@ importers:
|
||||
'@deepseek-ai/dsh-system-prompt':
|
||||
specifier: workspace:*
|
||||
version: link:../../core/system-prompt
|
||||
'@deepseek-ai/dsh-terminal':
|
||||
specifier: workspace:*
|
||||
version: link:../../terminal/terminal
|
||||
'@deepseek-ai/dsh-timeout':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/timeout
|
||||
@@ -9364,9 +9352,6 @@ importers:
|
||||
'@deepseek-ai/dsh-working-directory':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/working-directory
|
||||
'@deepseek-ai/dsh-workspace':
|
||||
specifier: workspace:*
|
||||
version: link:../../workspace/workspace
|
||||
'@testing-library/react':
|
||||
specifier: ^16.3.3
|
||||
version: 16.3.3(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||
@@ -11793,6 +11778,9 @@ importers:
|
||||
'@deepseek-ai/schemastery':
|
||||
specifier: link:../../../vendor/schemastery
|
||||
version: link:../../../vendor/schemastery
|
||||
zod:
|
||||
specifier: ^4.4.3
|
||||
version: 4.4.3
|
||||
devDependencies:
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: workspace:~
|
||||
@@ -11821,9 +11809,24 @@ importers:
|
||||
'@deepseek-ai/dsh-session':
|
||||
specifier: workspace:*
|
||||
version: link:../../core/session
|
||||
'@deepseek-ai/dsh-session-persistence-jsonl':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/session-persistence-jsonl
|
||||
'@deepseek-ai/dsh-session-projection':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/session-projection
|
||||
'@deepseek-ai/dsh-session-projection-cache':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/session-projection-cache
|
||||
'@deepseek-ai/dsh-session-query':
|
||||
specifier: workspace:*
|
||||
version: link:../../session-query/session-query
|
||||
'@deepseek-ai/dsh-storage':
|
||||
specifier: workspace:*
|
||||
version: link:../../storage/storage
|
||||
'@deepseek-ai/dsh-storage-domain':
|
||||
specifier: workspace:*
|
||||
version: link:../../storage/storage-domain
|
||||
'@deepseek-ai/dsh-subprocess':
|
||||
specifier: workspace:*
|
||||
version: link:../../subprocess/subprocess
|
||||
@@ -11836,6 +11839,9 @@ importers:
|
||||
'@deepseek-ai/dsh-working-directory':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/working-directory
|
||||
'@deepseek-ai/dsh-workspace':
|
||||
specifier: workspace:*
|
||||
version: link:../../workspace/workspace
|
||||
|
||||
packages/extensions/cordis-client-runner:
|
||||
devDependencies:
|
||||
|
||||
@@ -271,6 +271,7 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
|
||||
'workflow': 'workflow.md',
|
||||
'workspace': 'workspace.md',
|
||||
'working-directory': 'working-directory.md',
|
||||
'worktree': 'worktrees.md',
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -286,6 +287,7 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
|
||||
export const EVENT_WALK_EXEMPTIONS: Record<string, string> = {
|
||||
'workspace/archive-notice': 'client-face archive follow-up copy — packages/client/ui-workspace/README.md owns the API',
|
||||
'workspace/archive-followup-failed': 'client-face archive follow-up failure — packages/client/ui-workspace/README.md owns the API',
|
||||
'workspace/archive-followup-settled': 'client-face archive follow-up settlement — packages/client/ui-workspace/README.md owns the API',
|
||||
'agent/request': 'deprecated compatibility hook — packages/core/agent/README.md documents migration',
|
||||
'command/executed': 'client-face local command acknowledgment — packages/client/ui-commands/README.md owns the API',
|
||||
'connection/reset': 'client-face transport signal — packages/api/session-controller/README.md owns the API',
|
||||
@@ -405,6 +407,8 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
CreatedWorktree: 'worktrees.md',
|
||||
CreateWorktreePhase: 'worktrees.md',
|
||||
RestoreWorktreeRequest: 'worktrees.md',
|
||||
WorktreeCleanup: 'worktrees.md',
|
||||
WorktreeCreation: 'worktrees.md',
|
||||
RestoredWorktree: 'worktrees.md',
|
||||
ChangeRequestListener: 'forge.md',
|
||||
ChangeRequestRef: 'forge.md',
|
||||
@@ -422,7 +426,6 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
ForgeLocalDiff: 'forge.md',
|
||||
ForgeLocalScope: 'forge.md',
|
||||
ForgePanelState: 'forge.md',
|
||||
ForgeWorktreeCleanup: 'forge.md',
|
||||
ForgeProvider: 'forge.md',
|
||||
ForgeReadiness: 'forge.md',
|
||||
ForgeRepository: 'forge.md',
|
||||
|
||||
@@ -144,7 +144,7 @@ describe('optional bundles', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('offers the forge panel and model worktree tool together with their separate worktree services', () => {
|
||||
it('offers the forge panel and model worktree tool together over one worktree service', () => {
|
||||
const name = '@deepseek-ai/dsh-experimental-forge-bundle'
|
||||
expect(OPTIONAL_BUNDLES).toContain(name)
|
||||
for (const template of Object.values(PROFILE_TEMPLATES)) expect(template.bundles).not.toContain(name)
|
||||
@@ -159,9 +159,8 @@ describe('optional bundles', () => {
|
||||
expect(flattenRows(composeEntries(shipped)).some(row => row.name === moduleName)).toBe(false)
|
||||
expect(rows.filter(row => row.name === moduleName && row.disabled !== true)).toHaveLength(1)
|
||||
}
|
||||
const group = composeEntries([...shipped, bundle(name).patches]).find(row => row.id === 'optional-forge-panel')
|
||||
expect(group?.isolate).toEqual({ worktrees: true })
|
||||
expect(rows.filter(row => row.name === '@deepseek-ai/dsh-experimental-worktree')).toHaveLength(2)
|
||||
expect(composeEntries([...shipped, bundle(name).patches]).some(row => row.name === 'cordis:group' && row.id === 'optional-forge-panel')).toBe(false)
|
||||
expect(rows.filter(row => row.name === '@deepseek-ai/dsh-experimental-worktree')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps the existing tool and panel row overrides addressable in the unified bundle', () => {
|
||||
@@ -170,12 +169,12 @@ describe('optional bundles', () => {
|
||||
const composed = composeEntries([...shipped, bundle('@deepseek-ai/dsh-experimental-forge-bundle').patches, [
|
||||
{ id: 'worktree', config },
|
||||
{ id: 'tool-worktree', disabled: true },
|
||||
{ id: 'optional-forge-panel', disabled: true },
|
||||
{ id: 'forge-panel', disabled: true },
|
||||
]], message => warnings.push(message))
|
||||
expect(warnings).toEqual([])
|
||||
expect(composed.find(row => row.id === 'worktree')?.config).toEqual(config)
|
||||
expect(composed.find(row => row.id === 'tool-worktree')?.disabled).toBe(true)
|
||||
expect(composed.find(row => row.id === 'optional-forge-panel')?.disabled).toBe(true)
|
||||
expect(composed.find(row => row.id === 'forge-panel')?.disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('ships all five lightweight bundles without selecting them in a default template', () => {
|
||||
|
||||
@@ -2607,6 +2607,16 @@
|
||||
"symbol": "RestoreWorktreeRequest",
|
||||
"source": "packages/experimental/worktree/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/worktrees.md",
|
||||
"symbol": "WorktreeCleanup",
|
||||
"source": "packages/experimental/worktree/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/worktrees.md",
|
||||
"symbol": "WorktreeCreation",
|
||||
"source": "packages/experimental/worktree/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/worktrees.md",
|
||||
"symbol": "RestoredWorktree",
|
||||
@@ -2767,11 +2777,6 @@
|
||||
"symbol": "ForgeLocalChanges",
|
||||
"source": "packages/experimental/client-ui-forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeWorktreeCleanup",
|
||||
"source": "packages/experimental/client-ui-forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeLineComment",
|
||||
|
||||
@@ -377,6 +377,7 @@
|
||||
"@deepseek-ai/dsh-experimental-claude-code-mods": ["./packages/experimental/claude-code-mods/src"],
|
||||
"@deepseek-ai/dsh-tool-agent-team": ["./packages/team/tool-agent-team/src"],
|
||||
"@deepseek-ai/dsh-experimental-worktree": ["./packages/experimental/worktree/src"],
|
||||
"@deepseek-ai/dsh-experimental-worktree/types": ["./packages/experimental/worktree/src/types.ts"],
|
||||
"@deepseek-ai/dsh-experimental-tool-worktree": ["./packages/experimental/tool-worktree/src"],
|
||||
"@deepseek-ai/dsh-experimental-forge": ["./packages/experimental/forge/src"],
|
||||
"@deepseek-ai/dsh-experimental-forge/types": ["./packages/experimental/forge/src/types.ts"],
|
||||
|
||||
Reference in new issue
Block a user