refactor(sandbox-policy): resolve policies only for Sessions; callers build maintenance policies

Review of the consumers layer:

- `SandboxPolicyRequest.root` is removed. `resolve` answers only for a Session.
  `prepare` accepts a Session or a checkout directory and returns that
  checkout's validated Git administration directories. The worktree service
  builds the policy of removal and restoration itself: the Session's mode and
  grants, the source checkout as the root, and that checkout's derived
  directories. The forge panel swaps the root for its two reads of the source
  repository.
- The Git layout reads move to `src/linked-checkout.ts` with direct tests; the
  security rationale stays in the README, which the function comment links.
- `resolve` and the model-visible policy share one merge of configured,
  registered, and derived writable roots.
- `workspace-files` takes a live Session's root from the sandbox policy instead
  of repeating its fallback chain.
- `TurnRecorder` takes a fixed directory and an explicit `moveTo`, which the
  plugin calls on `workspace-root/change`; each turn keeps its own canonical
  paths.

A real-sandbox test restores a missing worktree of a linked source checkout in
a process that never worked in it.
This commit is contained in:
LegGasai committed 2026-11-17 15:09:22 +08:00
1 parent 0ae2613c98
commit e3cd2edebf
33 files changed
+373 -256

No files matched your search

@@ -9,8 +9,8 @@
en: 6938aa715106bb99
zh: ea1497b337712f33
/agent-note-session-workspace-root/decision:
en: d711554194c8887b
zh: 2033b6742e5064b2
en: 4b03efa72080dcc3
zh: 586af24eb496f56a
/agent-note-session-workspace-root/alternatives-considered:
en: 8a4859a6f96ef49e
zh: fa7088d29ebe3dd6
@@ -18,7 +18,7 @@ Worktree creation enters the checkout through `set`. The model has one tool for
Every consumer reads that directory. The model's file, search, and process tools resolve relative paths from it, and everything the user sees or that describes the project is bounded by it: the sandbox `workspace-write` boundary, the workspace file service and desktop file drag, the change recorder, the Files tree, deliverables, open-in-app actions and Session rows, new sidebar terminals, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace.
The sandbox policy derives the common directory of a linked checkout from the root's `.git` pointer through the execution-world filesystem and adds it to the resolved extra writable roots, accepting only the layout Git writes: `<common>/worktrees/<name>` with a `commondir` naming `<common>` and a `gitdir` naming the checkout's `.git`, since the checkout's own pointer is writable under `workspace-write`. A root's result is kept once read and refreshed when a Host operation moves a Session's workspace to that root or a derived directory disappears; tool executions wait for the derivation, Session creation and directory changes start it early, and the derived directories stay out of the model-visible policy text. On Windows the derived directories follow the [file-tool grant decision](2026-10-29-windows-file-tool-directory-grants.md): `write` and `edit` honor them, and process confinement keeps its workspace and private-temp grants. After a move into a worktree the original project is writable only through the Git administration directories, not as a whole. Host maintenance of a checkout the Session does not work in keeps the original boundary: removing a worktree on archive, restoring a removed one, and reading its branch in the source repository run under the Session's policy with the recorded source checkout as the root, requested through `resolve({ session, root })`; the Session's own root may be the removed directory, and a process sandbox cannot bind a missing or vanishing root.
The sandbox policy derives the common directory of a linked checkout from the root's `.git` pointer through the execution-world filesystem and adds it to the resolved extra writable roots, accepting only the layout Git writes: `<common>/worktrees/<name>` with a `commondir` naming `<common>` and a `gitdir` naming the checkout's `.git`, since the checkout's own pointer is writable under `workspace-write`. A root's result is kept once read and refreshed when a Host operation moves a Session's workspace to that root or a derived directory disappears; tool executions wait for the derivation, Session creation and directory changes start it early, and the derived directories stay out of the model-visible policy text. On Windows the derived directories follow the [file-tool grant decision](2026-10-29-windows-file-tool-directory-grants.md): `write` and `edit` honor them, and process confinement keeps its workspace and private-temp grants. After a move into a worktree the original project is writable only through the Git administration directories, not as a whole. Host maintenance of a checkout the Session does not work in keeps the original boundary: removing a worktree on archive, restoring a removed one, and reading its branch in the source repository run under a policy the worktree service and the forge panel build themselves: the Session's mode and grants with the recorded source checkout as the root, plus that checkout's Git administration directories from `prepare({ directory })`. The sandbox policy resolves policies only for Sessions; the Session's own root may be the removed directory, and a process sandbox cannot bind a missing or vanishing root.
## Alternatives considered
@@ -18,7 +18,7 @@ Status: implemented
每个消费方都读取这个目录。模型的文件、搜索与进程工具从它解析相对路径,用户看到的、以及描述项目的一切都以它为界:沙箱 `workspace-write` 边界、工作区文件服务与桌面文件拖拽、变更记录器、文件树、交付物、在应用中打开操作与 Session 行、新开的侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区。
沙箱策略通过执行环境的文件系统,从根的 `.git` 指针推导出链接检出目录的公共目录并加入解析出的额外可写根,只接受 Git 写出的布局:`<common>/worktrees/<name>`,其 `commondir` 指向 `<common>`、`gitdir` 指回检出目录的 `.git`,因为检出目录自己的指针在 `workspace-write` 下可写。根的结果读取后即保留,在 Host 操作把某个 Session 的工作区移到该根、或已推导目录消失时刷新;工具执行等待该推导完成,会话创建与目录变更提前启动它,推导出的目录不进入模型可见的策略文本。在 Windows 上,推导出的目录遵循[文件工具授权决策](2026-10-29-windows-file-tool-directory-grants.zh.md):`write` 与 `edit` 执行它们,进程限制保留工作区与私有临时目录授权。移入工作树之后,原始项目只能通过 Git 管理目录写入,不再整体可写。Host 对 Session 并不在其中工作的检出目录做维护时保留原来的边界:归档时移除 worktree、恢复被删除的 worktree、在源仓库中读取其分支,都在 Session 的策略下以记录中的源检出目录为根运行,通过 `resolve({ session, root })` 请求;Session 自身的根可能正是被删除的目录,而进程沙箱无法绑定缺失或正在消失的根。
沙箱策略通过执行环境的文件系统,从根的 `.git` 指针推导出链接检出目录的公共目录并加入解析出的额外可写根,只接受 Git 写出的布局:`<common>/worktrees/<name>`,其 `commondir` 指向 `<common>`、`gitdir` 指回检出目录的 `.git`,因为检出目录自己的指针在 `workspace-write` 下可写。根的结果读取后即保留,在 Host 操作把某个 Session 的工作区移到该根、或已推导目录消失时刷新;工具执行等待该推导完成,会话创建与目录变更提前启动它,推导出的目录不进入模型可见的策略文本。在 Windows 上,推导出的目录遵循[文件工具授权决策](2026-10-29-windows-file-tool-directory-grants.zh.md):`write` 与 `edit` 执行它们,进程限制保留工作区与私有临时目录授权。移入工作树之后,原始项目只能通过 Git 管理目录写入,不再整体可写。Host 对 Session 并不在其中工作的检出目录做维护时保留原来的边界:归档时移除 worktree、恢复被删除的 worktree、在源仓库中读取其分支,都在 worktree 服务与 forge 面板自己构造的策略下运行:沿用 Session 的模式与授权,以记录中的源检出目录为根,并加上 `prepare({ directory })` 给出的该检出目录的 Git 管理目录。沙箱策略只为 Session 解析策略;Session 自身的根可能正是被删除的目录,而进程沙箱无法绑定缺失或正在消失的根。
## Alternatives considered
+2 -2
View File
@@ -367,7 +367,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:104`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:100`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page, one listing, or one search. */
@@ -3118,7 +3118,7 @@ export interface Config {
- `inject`: `sessionProjections`
- `refs`: [`SandboxMode`](subsystems/sandbox.md)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:171`](../packages/sandbox/sandbox-policy/src/index.ts)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:112`](../packages/sandbox/sandbox-policy/src/index.ts)
```ts config-catalog
/**
+2 -2
View File
@@ -369,7 +369,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:104`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:100`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page, one listing, or one search. */
@@ -3120,7 +3120,7 @@ export interface Config {
- `inject`: `sessionProjections`
- `refs`: [`SandboxMode`](subsystems/sandbox.zh.md)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:171`](../packages/sandbox/sandbox-policy/src/index.ts)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:112`](../packages/sandbox/sandbox-policy/src/index.ts)
```ts config-catalog
/**
+18 -29
View File
@@ -81,13 +81,6 @@ interface SandboxPolicyRequest {
session?: Session
/** Explicit approved mode override, which outranks session policy. */
mode?: SandboxMode
/**
* Checkout that bounds this call instead of the session's workspace root: Host maintenance of a
* checkout the session does not work in, such as removing or restoring the session's worktree from
* its source repository while the session's own root is that worktree. The session's mode and
* registered grants still apply. Never reachable from model input.
*/
root?: string
}
```
@@ -220,12 +213,11 @@ A session's workspace root comes from the working-directory service when it is m
* boundary, and the Git administration directories {@link prepare} derived
* for that root join the configured extra writable directories; the
* configured root is the fallback for agentless calls and, without the
* working-directory service, sessions without a header directory, and a
* requested `root` replaces the session's root for the call. Configured extra
* roots, this Session's active registrations, and the derived Git directories
* are snapshotted together; existing operations and processes keep their
* policy.
* @param request - optional session, approved mode override, and root override.
* working-directory service, sessions without a header directory. Configured
* extra roots, this Session's active registrations, and the derived Git
* directories are snapshotted together; existing operations and processes
* keep their policy.
* @param request - optional session and approved mode override.
* @returns the fully resolved per-call mode, absolute workspace root, and extra writable directories.
* @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the selected root is relative or
* contains a NUL byte.
@@ -254,24 +246,21 @@ registerWritableRoot(session: Session, directory: string): () => void
overrideOf(session: Session): SandboxMode | undefined
/**
* Derive the Git administration directories of the session's workspace root
* so the next {@link resolve} grants them: a linked checkout's `.git` file
* names `<common>/worktrees/<name>`, whose `commondir` names the repository's
* common directory and whose `gitdir` names the checkout's `.git` again; only
* that layout grants the common directory, since the checkout's own `.git`
* pointer is writable under workspace-write. Any other layout, a root without
* `.git`, and a common directory containing the root add nothing. One
* derivation runs per root and its result is kept once the layout was read,
* so a pointer written later does not widen the policy until a Host operation
* moves a Session's workspace to that root again; a derived directory that disappears is
* derived again, and a failed read is logged once per root and retried on
* the next call.
* @param request - session whose workspace root is inspected, or the root {@link resolve} would select
* for the same request.
* Derive the Git administration directories a linked checkout writes outside itself, as
* `./linked-checkout.ts` reads them. For a Session the checkout is its workspace root, and the next
* {@link resolve} for that Session grants the result. For a named `directory`, a Host operation that
* runs in a checkout no Session works in adds the result to the policy it builds; `resolve` is
* unaffected. One derivation runs per directory and its result is kept once the layout was read, so a
* pointer written later does not widen a policy until a Host operation moves a Session's workspace to
* that directory again; a derived directory that disappears is derived again, and a failed read is
* logged once per directory and retried on the next call.
* @param target - Session whose workspace root is inspected, or the checkout directory itself.
* @param signal - caller cancellation, checked before and after the shared derivation.
* @returns the derived directories outside the root, canonical in the execution world.
* @returns the derived directories outside the checkout, canonical in the execution world.
* @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the directory is relative or
* contains a NUL byte.
*/
async prepare(request: Pick<SandboxPolicyRequest, 'session' | 'root'>, signal?: AbortSignal): Promise<readonly string[]>
async prepare(target: { session: Session } | { directory: string }, signal?: AbortSignal): Promise<readonly string[]>
```
Types: [Session](session.md)
+18 -29
View File
@@ -81,13 +81,6 @@ interface SandboxPolicyRequest {
session?: Session
/** Explicit approved mode override, which outranks session policy. */
mode?: SandboxMode
/**
* Checkout that bounds this call instead of the session's workspace root: Host maintenance of a
* checkout the session does not work in, such as removing or restoring the session's worktree from
* its source repository while the session's own root is that worktree. The session's mode and
* registered grants still apply. Never reachable from model input.
*/
root?: string
}
```
@@ -220,12 +213,11 @@ A session's workspace root comes from the working-directory service when it is m
* boundary, and the Git administration directories {@link prepare} derived
* for that root join the configured extra writable directories; the
* configured root is the fallback for agentless calls and, without the
* working-directory service, sessions without a header directory, and a
* requested `root` replaces the session's root for the call. Configured extra
* roots, this Session's active registrations, and the derived Git directories
* are snapshotted together; existing operations and processes keep their
* policy.
* @param request - optional session, approved mode override, and root override.
* working-directory service, sessions without a header directory. Configured
* extra roots, this Session's active registrations, and the derived Git
* directories are snapshotted together; existing operations and processes
* keep their policy.
* @param request - optional session and approved mode override.
* @returns the fully resolved per-call mode, absolute workspace root, and extra writable directories.
* @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the selected root is relative or
* contains a NUL byte.
@@ -254,24 +246,21 @@ registerWritableRoot(session: Session, directory: string): () => void
overrideOf(session: Session): SandboxMode | undefined
/**
* Derive the Git administration directories of the session's workspace root
* so the next {@link resolve} grants them: a linked checkout's `.git` file
* names `<common>/worktrees/<name>`, whose `commondir` names the repository's
* common directory and whose `gitdir` names the checkout's `.git` again; only
* that layout grants the common directory, since the checkout's own `.git`
* pointer is writable under workspace-write. Any other layout, a root without
* `.git`, and a common directory containing the root add nothing. One
* derivation runs per root and its result is kept once the layout was read,
* so a pointer written later does not widen the policy until a Host operation
* moves a Session's workspace to that root again; a derived directory that disappears is
* derived again, and a failed read is logged once per root and retried on
* the next call.
* @param request - session whose workspace root is inspected, or the root {@link resolve} would select
* for the same request.
* Derive the Git administration directories a linked checkout writes outside itself, as
* `./linked-checkout.ts` reads them. For a Session the checkout is its workspace root, and the next
* {@link resolve} for that Session grants the result. For a named `directory`, a Host operation that
* runs in a checkout no Session works in adds the result to the policy it builds; `resolve` is
* unaffected. One derivation runs per directory and its result is kept once the layout was read, so a
* pointer written later does not widen a policy until a Host operation moves a Session's workspace to
* that directory again; a derived directory that disappears is derived again, and a failed read is
* logged once per directory and retried on the next call.
* @param target - Session whose workspace root is inspected, or the checkout directory itself.
* @param signal - caller cancellation, checked before and after the shared derivation.
* @returns the derived directories outside the root, canonical in the execution world.
* @returns the derived directories outside the checkout, canonical in the execution world.
* @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the directory is relative or
* contains a NUL byte.
*/
async prepare(request: Pick<SandboxPolicyRequest, 'session' | 'root'>, signal?: AbortSignal): Promise<readonly string[]>
async prepare(target: { session: Session } | { directory: string }, signal?: AbortSignal): Promise<readonly string[]>
```
Types: [Session](session.zh.md)
+1 -1
View File
@@ -455,7 +455,7 @@ Host Remote file reads and workspace directory observations over the composed fi
```ts cordis-catalog
/**
* Resolve the scope other Host services use to open the same `session/<id>/<path>` addresses:
* a live Session's directory, else a stored Session's cached directory, else its header directory.
* a live Session's sandbox workspace root, else a stored Session's cached directory, else its header directory.
* @param sessionId - Session identity received on the wire.
* @param signal - cancellation for the persistence read of a stored Session.
* @returns the scope, or undefined when no live or stored Session has that identity.
+1 -1
View File
@@ -455,7 +455,7 @@ Host Remote file reads and workspace directory observations over the composed fi
```ts cordis-catalog
/**
* Resolve the scope other Host services use to open the same `session/<id>/<path>` addresses:
* a live Session's directory, else a stored Session's cached directory, else its header directory.
* a live Session's sandbox workspace root, else a stored Session's cached directory, else its header directory.
* @param sessionId - Session identity received on the wire.
* @param signal - cancellation for the persistence read of a stored Session.
* @returns the scope, or undefined when no live or stored Session has that identity.
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-api-workspace-files/use-this-package:
en: 103a05231612d938
zh: 9b9b5999b2adf3c8
en: 742a72d5336e3d62
zh: 1bb66e5274ab2e96
/deepseek-ai-dsh-api-workspace-files/use-this-package/addressing-and-paths:
en: b9565cfa7a1da451
zh: fc4078a58322fc7f
@@ -48,8 +48,8 @@
en: 42b15ac6321706aa
zh: ce1d25bffb6948cd
/deepseek-ai-dsh-api-workspace-files/understand-the-implementation/design-concept:
en: df174a425a5bbf90
zh: c468554e2beeb4e1
en: b4a0124b26db9dda
zh: de46ef79afc294fa
/deepseek-ai-dsh-api-workspace-files/understand-the-implementation/source-map:
en: c18e235fbd03e6be
zh: da1c4d03bf34657d
+2 -2
View File
@@ -25,7 +25,7 @@ Use this package to preview files readable through a Session's filesystem from t
<a id="use-this-package"></a>
## Use this package
Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, `search(sessionId, request, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host reads a live Session's directory from the working-directory service, or a cold Session's recorded directory from the projection cache beside its persisted header, falling back to the header directory; it does not activate an Agent, read the event body, or borrow a parent Session's root. `workspaceFiles.scopeOf(sessionId, signal)` offers that resolution to other Host services that open the same `session/<id>/<path>` addresses. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`.
Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, `search(sessionId, request, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host uses the workspace root the sandbox policy resolves for a live Session, or a cold Session's recorded directory from the projection cache beside its persisted header, falling back to the header directory; it does not activate an Agent, read the event body, or borrow a parent Session's root. `workspaceFiles.scopeOf(sessionId, signal)` offers that resolution to other Host services that open the same `session/<id>/<path>` addresses. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`.
| Method | Returns | Purpose |
|---|---|---|
@@ -107,7 +107,7 @@ One supervised `changes` stream serves each Session and requested path; consumer
### Design concept
Reads through `ctx.fs` use the backend's read authority; the sandboxing backend fences writes and edits, not reads. A Typert lookup derives `WorkspaceFileScope` from a live Session's directory or a stored Session's cached directory beside the persistence service's header-only `stat`, so cold subagent Sessions need neither Agent activation nor event-body reads. The service adds regular-file checks and bounded transfer, while workspace containment belongs only to directory listing and directory watching. A page is cut from `streamText`, which decodes and rejects non-UTF-8 chunk by chunk: the cutter counts lines before the window without keeping them, admits each in-window segment against the byte cap before buffering it, and returns at the first character past the window. One `stat` before the stream names the version and size the page reports.
Reads through `ctx.fs` use the backend's read authority; the sandboxing backend fences writes and edits, not reads. A Typert lookup derives `WorkspaceFileScope` from a live Session's sandbox workspace root or a stored Session's cached directory beside the persistence service's header-only `stat`, so cold subagent Sessions need neither Agent activation nor event-body reads. The service adds regular-file checks and bounded transfer, while workspace containment belongs only to directory listing and directory watching. A page is cut from `streamText`, which decodes and rejects non-UTF-8 chunk by chunk: the cutter counts lines before the window without keeping them, admits each in-window segment against the byte cap before buffering it, and returns at the first character past the window. One `stat` before the stream names the version and size the page reports.
Complete-file reads delegate size enforcement to `fs.readBytes` and return raw bytes through the binary Remote.
+2 -2
View File
@@ -25,7 +25,7 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)`、`search(sessionId, request, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 从工作目录服务读取 live Session 的目录,cold Session 则读取持久化 header 旁投影缓存中记录的目录,再回退到 header 目录;它不会激活 Agent、读取事件正文或借用父 Session 的根。`workspaceFiles.scopeOf(sessionId, signal)` 把这一解析提供给打开同一种 `session/<id>/<path>` 地址的其他 Host 服务。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。
把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)`、`search(sessionId, request, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 对 live Session 使用沙箱策略解析出的工作区根,cold Session 则读取持久化 header 旁投影缓存中记录的目录,再回退到 header 目录;它不会激活 Agent、读取事件正文或借用父 Session 的根。`workspaceFiles.scopeOf(sessionId, signal)` 把这一解析提供给打开同一种 `session/<id>/<path>` 地址的其他 Host 服务。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。
| 方法 | 返回 | 用途 |
|---|---|---|
@@ -107,7 +107,7 @@ kind: "package-reference"
### 设计概念
经 `ctx.fs` 的读取使用后端的读取权限;沙箱后端限制写与编辑,而不限制读取。Typert lookup 从 live Session 的目录,或 stored Session 在持久层 header-only `stat` 旁缓存的目录导出 `WorkspaceFileScope`,所以 cold subagent Session 不需要激活 Agent 或读取事件正文。本服务增加普通文件检查与有界传输,工作区包含要求只属于目录列举与目录监听。页从 `streamText` 切出,后者逐块解码并拒绝非 UTF-8:切页器对窗口之前的行只计数不保留,对窗口内的每个片段先按字节上限验收再缓冲,并在窗口之后的第一个字符处返回。流之前的一次 `stat` 给出页所报告的版本与大小。
经 `ctx.fs` 的读取使用后端的读取权限;沙箱后端限制写与编辑,而不限制读取。Typert lookup 从 live Session 的沙箱工作区根,或 stored Session 在持久层 header-only `stat` 旁缓存的目录导出 `WorkspaceFileScope`,所以 cold subagent Session 不需要激活 Agent 或读取事件正文。本服务增加普通文件检查与有界传输,工作区包含要求只属于目录列举与目录监听。页从 `streamText` 切出,后者逐块解码并拒绝非 UTF-8:切页器对窗口之前的行只计数不保留,对窗口内的每个片段先按字节上限验收再缓冲,并在窗口之后的第一个字符处返回。流之前的一次 `stat` 给出页所报告的版本与大小。
完整文件读取将大小上限检查交给 `fs.readBytes`,并通过二进制 Remote 返回原始字节。
+7 -11
View File
@@ -62,10 +62,9 @@ export interface WorkspaceFileScope {
/** Session identity received on the wire. */
readonly sessionId: SessionId
/**
* Session workspace root: the directory the Session works in, read from the
* working-directory service for a live Session and from the projection cache
* for a stored one; its header directory when neither is available, and
* the deployment fallback when the header has no directory.
* Session workspace root: for a live Session the root the sandbox policy
* bounds it by; for a stored one its directory in the projection cache, else
* its header directory, else the deployment fallback.
*/
readonly workspaceRoot: string
}
@@ -73,8 +72,8 @@ export interface WorkspaceFileScope {
/**
* Resolve the workspace root a Session's file views and directory listings
* use, without loading its event body or activating an Agent.
* @param ctx - Host context carrying the Session store and the sandbox policy fallback, and optionally persistence,
* the projection cache, and the working-directory service.
* @param ctx - Host context carrying the Session store and the sandbox policy, and optionally persistence
* and the projection cache.
* @param sessionId - Session identity received on the wire.
* @param signal - cancellation for the persistence read of a stored Session.
* @returns the scope, or undefined when no live or stored Session has that identity.
@@ -83,10 +82,7 @@ async function workspaceFileScopeOf(
ctx: Context, sessionId: SessionId, signal?: AbortSignal,
): Promise<WorkspaceFileScope | undefined> {
const live = ctx.get('sessions')?.get(sessionId)
if (live !== undefined) {
const root = ctx.get('workingDirectory')?.get(live) ?? live.header.cwd
return { sessionId, workspaceRoot: root ?? ctx.sandboxPolicy.workspaceRoot }
}
if (live !== undefined) return { sessionId, workspaceRoot: ctx.sandboxPolicy.resolve({ session: live }).workspaceRoot }
const stored = await ctx.get('sessionPersistence')?.stat(sessionId, signal === undefined ? undefined : { signal })
if (stored === undefined) return undefined
const cached = ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header, ['workingDirectory'])?.values.workingDirectory
@@ -256,7 +252,7 @@ export class WorkspaceFiles extends TypertRemoteService {
/**
* Resolve the scope other Host services use to open the same `session/<id>/<path>` addresses:
* a live Session's directory, else a stored Session's cached directory, else its header directory.
* a live Session's sandbox workspace root, else a stored Session's cached directory, else its header directory.
* @param sessionId - Session identity received on the wire.
* @param signal - cancellation for the persistence read of a stored Session.
* @returns the scope, or undefined when no live or stored Session has that identity.
@@ -43,16 +43,18 @@ describe('Workspace Files Session scope lookup', () => {
meta.id === coldId ? { asOfSeq: 4, values: { workingDirectory: coldWorktree } } : undefined)
const ctx = new Context()
ctx.provide('fs', {} as never)
ctx.provide('sandboxPolicy', { workspaceRoot: resolve('fallback-workspace') } as never)
// A live Session's root is the one the sandbox policy bounds it by.
const resolvePolicy = vi.fn(() => ({ mode: 'workspace-write', workspaceRoot: liveWorktree }))
ctx.provide('sandboxPolicy', { workspaceRoot: resolve('fallback-workspace'), resolve: resolvePolicy } as never)
ctx.provide('sessionPersistence', { stat } as never)
ctx.provide('sessionProjectionCache', { cachedSnapshot } as never)
ctx.provide('workingDirectory', { get: () => liveWorktree } as never)
const sessions = await ctx.plugin(SessionStore)
const typert = await ctx.plugin(TypertRegistry)
const workspaceFiles = await ctx.plugin(WorkspaceFiles, CAPS)
try {
ctx.sessions.create(liveId, { meta: { cwd: liveRoot, origin: 'subagent' } })
const live = ctx.sessions.create(liveId, { meta: { cwd: liveRoot, origin: 'subagent' } })
await expect(ctx.workspaceFiles.scopeOf(liveId)).resolves.toEqual({ sessionId: liveId, workspaceRoot: liveWorktree })
expect(resolvePolicy).toHaveBeenCalledWith({ session: live })
await expect(ctx.workspaceFiles.scopeOf(coldId)).resolves.toEqual({ sessionId: coldId, workspaceRoot: coldWorktree })
await expect(ctx.workspaceFiles.scopeOf(plainId)).resolves.toEqual({ sessionId: plainId, workspaceRoot: coldRoot })
expect(cachedSnapshot).toHaveBeenCalledWith(expect.objectContaining({ id: coldId }), ['workingDirectory'])
@@ -82,7 +84,8 @@ describe('Workspace Files Session scope lookup', () => {
})
const ctx = new Context()
ctx.provide('fs', {} as never)
ctx.provide('sandboxPolicy', { workspaceRoot: fallbackRoot } as never)
const resolvePolicy = ({ session }: { session: { header: SessionHeader } }) => ({ mode: 'read-only', workspaceRoot: session.header.cwd ?? fallbackRoot })
ctx.provide('sandboxPolicy', { workspaceRoot: fallbackRoot, resolve: resolvePolicy } as never)
ctx.provide('sessionPersistence', { stat } as never)
const sessions = await ctx.plugin(SessionStore)
const typert = await ctx.plugin(TypertRegistry)
@@ -33,7 +33,9 @@ async function fixture() {
cleanups.push(() => ctx.fiber.dispose())
const session: { cwd?: string } = { cwd }
await ctx.plugin(LocalFileSystem, { cwd })
ctx.provide('sandboxPolicy', { workspaceRoot: cwd } as never)
// The workspace scope asks the policy for a live Session's root; this one applies the header directory, then the deployment root.
const resolvePolicy = ({ session: live }: { session: { header: { cwd?: string } } }) => ({ mode: 'read-only', workspaceRoot: live.header.cwd ?? cwd })
ctx.provide('sandboxPolicy', { workspaceRoot: cwd, resolve: resolvePolicy } as never)
await ctx.plugin({
inject: ['fs', 'sandboxPolicy'],
apply: (scope) => {
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-workspace-changes/use-this-package:
en: d155b851c8613a54
zh: b4d7488ce787b8fb
en: 27239874e99bc94d
zh: 93b437cc02de2064
/deepseek-ai-dsh-workspace-changes/understand-the-implementation:
en: 9bfc66bea548bda2
zh: 7023c42cdb44569b
@@ -45,7 +45,7 @@ This plugin requires the `subprocess` and `fs` services. Every Session with a wo
After a `write`, `edit`, or mutating `str_replace_editor` call resolves its target and obtains its mutation guard, the recorder copies that exact file before the mutation into the Session's temporary directory, once per path per turn, and copies it again at turn end; the copies are named by the SHA-1 of their bytes, so identical content is stored once. This needs no git. Repository discovery and display paths follow the working directory the turn started in; file captures follow the operation's resolved target even after the Session changes directories. Paths the snapshots cover keep their git counts; the copies serve the other paths — files matching an ignore pattern, files outside the repository, and every file-tool edit when there is no snapshot — with counts from a line comparison of the two copies, so repeated edits to one file count once and a shell edit after a file-tool edit is included. A path whose content is unchanged at turn end is not listed. A copy larger than `maxFileBytes` is not stored: the file is listed with `oversized` and no counts, and a path whose both sides are that large is listed too, since unread content is never known to be unchanged. A path whose only difference is a missing final newline compares as unchanged, while git still counts that line. Files under `/tmp` or the platform temporary directory are excluded unless they lie inside the repository. Changes made only through shell commands outside the snapshot coverage are not recorded.
Each turn reads the Session's working directory when it starts, so a Session that entered a worktree is snapshotted in that checkout and lists paths relative to it. Each file carries a durable `path` — relative to the working directory inside it, absolute elsewhere — and a `display` path used for ordering and labels: the relative path, a `../` path for repository files above the working directory, a `~` path under the home directory, otherwise the absolute path. Files sort by `display` in code-unit order, which lists parent and absolute paths before the working directory's own files. The `workspace/changes` event carries only the turn number; `ctx.workspaceChanges.summary(sessionId, seq)` returns the summary the event with that sequence announced, or undefined once the Session is disposed or when this Host process never recorded it. `ctx.workspaceChanges.diff(sessionId, seq, index, signal)` compares the listed file at that index: hunks with three context lines from the two snapshot trees or the two copies, `binary` for a side git reported as binary or that holds a NUL byte, `oversized` for a side larger than `maxFileBytes`. A line comparison that runs longer than `diffTimeoutMs` degrades to one hunk replacing every line, marked `coarse`. A conversation reopened after a Host restart therefore has no card, and no comparison, for its earlier turns.
The recorder follows each Host move of the Session's directory: a turn that starts after a Session entered a worktree is snapshotted in that checkout and lists paths relative to it, and a turn already open keeps the directory it started in. Each file carries a durable `path` — relative to the working directory inside it, absolute elsewhere — and a `display` path used for ordering and labels: the relative path, a `../` path for repository files above the working directory, a `~` path under the home directory, otherwise the absolute path. Files sort by `display` in code-unit order, which lists parent and absolute paths before the working directory's own files. The `workspace/changes` event carries only the turn number; `ctx.workspaceChanges.summary(sessionId, seq)` returns the summary the event with that sequence announced, or undefined once the Session is disposed or when this Host process never recorded it. `ctx.workspaceChanges.diff(sessionId, seq, index, signal)` compares the listed file at that index: hunks with three context lines from the two snapshot trees or the two copies, `binary` for a side git reported as binary or that holds a NUL byte, `oversized` for a side larger than `maxFileBytes`. A line comparison that runs longer than `diffTimeoutMs` degrades to one hunk replacing every line, marked `coarse`. A conversation reopened after a Host restart therefore has no card, and no comparison, for its earlier turns.
The intent listeners capture every add, update, delete, and move target of `apply_patch` after policy admission and before provider mutation; a move captures both ends. Review compares each path against its first baseline and lists net changes, including the completed effects of a stopped patch.
@@ -45,7 +45,7 @@ kind: "package-reference"
在 `write`、`edit`、`apply_patch` 或有修改作用的 `str_replace_editor` 调用解析目标并取得修改防护之后,记录器在实际修改前把该文件复制到 Session 的临时目录,每轮每个路径只复制第一次,轮次结束时再复制一次;副本按其字节的 SHA-1 命名,相同内容只存一份。这一步不需要 git。仓库定位与显示路径跟随该轮开始时的工作目录;即使 Session 切换目录,文件捕获仍跟随该操作已解析的目标。快照覆盖到的路径保留 git 的行数;其余路径由副本提供,也就是匹配忽略模式的文件、仓库之外的文件,以及没有快照时的每一次文件工具编辑,行数来自两份副本的逐行对比,因此同一文件的重复编辑只计一次,文件工具编辑之后的 shell 改动也包含在内。轮次结束时内容没有变化的路径不会列出。超过 `maxFileBytes` 的副本不会保存:该文件列出时带 `oversized`,没有行数;两侧都这么大的路径同样列出,因为没读过的内容永远不能认定为没有改动。只差一个末尾换行的路径对比为两侧相同,而 git 仍会把那一行计入行数。`/tmp` 与平台临时目录下的文件被排除,除非它们位于仓库内。快照覆盖范围之外只通过 shell 命令做出的改动不会被记录。
每个 turn 开始时读取 Session 的工作目录,因此进入 worktree 的 Session 在该检出目录中拍快照,并以它为基准列出相对路径。每个文件携带持久的 `path`——位于工作目录内时为相对路径,否则为绝对路径——以及用于排序和标签的 `display` 路径:相对路径,仓库内位于工作目录之上的文件为 `../` 路径,家目录下的文件为 `~` 路径,其余为绝对路径。文件按 `display` 的码元顺序排序,因此上级路径和绝对路径排在工作目录自身文件之前。`workspace/changes` 事件只携带轮号;`ctx.workspaceChanges.summary(sessionId, seq)` 返回该序号的事件宣告的摘要,Session 已释放或本 Host 进程从未记录时返回 undefined。`ctx.workspaceChanges.diff(sessionId, seq, index, signal)` 对比该下标所列的文件:从两棵快照树或两份副本得出带三行上下文的 hunk;git 报告为二进制或某一侧含 NUL 字节时返回 `binary`;某一侧超过 `maxFileBytes` 时返回 `oversized`。逐行对比运行超过 `diffTimeoutMs` 时退化为一个替换全部行的 hunk,并标记 `coarse`。因此 Host 重启后重新打开的对话,先前轮次既没有卡片也没有对比。
记录器跟随 Host 对 Session 目录的每次移动:Session 进入 worktree 之后开始的 turn 在该检出目录中拍快照,并以它为基准列出相对路径;已经开始的 turn 保留它开始时的目录。每个文件携带持久的 `path`——位于工作目录内时为相对路径,否则为绝对路径——以及用于排序和标签的 `display` 路径:相对路径,仓库内位于工作目录之上的文件为 `../` 路径,家目录下的文件为 `~` 路径,其余为绝对路径。文件按 `display` 的码元顺序排序,因此上级路径和绝对路径排在工作目录自身文件之前。`workspace/changes` 事件只携带轮号;`ctx.workspaceChanges.summary(sessionId, seq)` 返回该序号的事件宣告的摘要,Session 已释放或本 Host 进程从未记录时返回 undefined。`ctx.workspaceChanges.diff(sessionId, seq, index, signal)` 对比该下标所列的文件:从两棵快照树或两份副本得出带三行上下文的 hunk;git 报告为二进制或某一侧含 NUL 字节时返回 `binary`;某一侧超过 `maxFileBytes` 时返回 `oversized`。逐行对比运行超过 `diffTimeoutMs` 时退化为一个替换全部行的 hunk,并标记 `coarse`。因此 Host 重启后重新打开的对话,先前轮次既没有卡片也没有对比。
intent 监听器在策略准入后、提供方修改前捕获 `apply_patch` 的每个新增、更新、删除和移动目标;移动捕获两端。Review 将每个路径与首次基线比较并列出净变化,包括中止补丁已经完成的效果。
@@ -63,11 +63,6 @@ function eligible(session: Session): string | undefined {
return origin === 'subagent' || (delegationDepth ?? 0) > 0 ? undefined : cwd
}
/** The directory a turn starts in: the Session's directory, or the original project without the working-directory service. */
function directoryOf(ctx: Context, session: Session, original: string): string {
return ctx.get('workingDirectory')?.get(session) ?? original
}
/**
* Resolve the git executable once. On macOS the Xcode stub at `/usr/bin/git`
* opens an installer dialog instead of running, so it counts as absent until
@@ -139,7 +134,8 @@ export function apply(ctx: Context, config: Config): void {
const recorderFor = (session: Session, original: string): TurnRecorder => {
let recorder = recorders.get(session)
if (recorder === undefined) {
recorder = new TurnRecorder(session, () => directoryOf(ctx, session, original), {
// The Session's directory now; `workspace-root/change` events report later moves.
recorder = new TurnRecorder(session, ctx.get('workingDirectory')?.get(session) ?? original, {
git: gitRunner(), tempRoot: tmpdir(), maxFiles: config.maxFiles,
maxFileBytes: config.maxFileBytes, diffTimeoutMs: config.diffTimeoutMs,
warn: (message) => { ctx.logger.warn(message) },
@@ -155,7 +151,8 @@ export function apply(ctx: Context, config: Config): void {
if (original !== undefined) recorderFor(session, original).start(event.data.turn)
return
}
if (event.type === 'tool/result') recorders.get(session)?.observe(event)
if (event.type === 'workspace-root/change') recorders.get(session)?.moveTo(event.data.cwd)
else if (event.type === 'tool/result') recorders.get(session)?.observe(event)
else if (event.type === 'turn/end') recorders.get(session)?.end(event.data.turn)
})
ctx.on('session/disposed', (session) => { void forget(session) })
@@ -71,6 +71,8 @@ interface TurnState {
readonly turn: number
/** The Session directory the turn started in, as the directory service spells it. */
readonly cwd: string
/** Canonical paths of that directory, resolved by the turn's baseline; undefined until then. */
paths: Paths | undefined
/**
* The turn-start snapshot once it exists. `null` means no repository or no git, so the turn summarizes file-tool
* captures only; `'failed'` means the repository exists but its snapshot failed, so the turn records nothing.
@@ -86,7 +88,9 @@ interface TurnState {
}
function freshState(turn: number, cwd: string): TurnState {
return { turn, cwd, baseline: null, captures: new Map(), lastToolResultSeq: -1, attemptedAfterSeq: -1, recordedAfterSeq: -1 }
return {
turn, cwd, paths: undefined, baseline: null, captures: new Map(), lastToolResultSeq: -1, attemptedAfterSeq: -1, recordedAfterSeq: -1,
}
}
/** A listed file with the sources of its two sides. */
@@ -104,16 +108,15 @@ const OVERSIZED = Symbol('oversized')
* with the summaries. Tool execution waits for pending work so a snapshot or
* capture never races a mutation. A working directory outside any repository,
* or a Host without git, gets no snapshot; its summary lists the files the file
* tools changed. Each turn reads the Session's directory again, so a turn
* that starts in another checkout is snapshotted there and lists paths
* relative to that directory.
* tools changed. {@link moveTo} tells the recorder that the Session works in
* another directory: turns that start afterwards are snapshotted there and
* list paths relative to it, while the open turn keeps the directory it
* started in.
*/
export class TurnRecorder {
private chain: Promise<void> = Promise.resolve()
/** The open turn; before the first `turn/start` it is an empty placeholder no event can match. */
private state = freshState(0, '')
/** Canonical paths of the open turn, resolved when it starts. */
private paths: Paths | undefined
/** Host facts shared by every turn, resolved by the first. */
private host: Pick<Paths, 'home' | 'temporaryRoots'> | undefined
/** Located repositories by canonical Session directory, reused across turns; an absent entry keeps retrying each turn. */
@@ -126,23 +129,33 @@ export class TurnRecorder {
constructor(
private readonly session: Session,
private readonly directory: () => string,
private cwd: string,
private readonly env: RecorderEnvironment,
) {}
/**
* Record that the Session works in another directory from now on. Turns that
* start afterwards use it; the open turn keeps the directory it started in,
* where its baseline snapshot was taken.
* @param cwd - the Session's directory after the move.
*/
moveTo(cwd: string): void {
this.cwd = cwd
}
/**
* Open a turn with fresh per-turn state and queue its baseline snapshot.
* @param turn - the turn number from `turn/start`.
*/
start(turn: number): void {
const cwd = this.directory()
const cwd = this.cwd
const state = freshState(turn, cwd)
this.state = state
void this.enqueue(async (signal) => {
try {
this.host ??= { home: await canonicalPath(homedir()), temporaryRoots: await temporaryRoots() }
this.paths = { cwd: await realpath(cwd), ...this.host }
const repository = await this.locate(this.paths.cwd, signal)
state.paths = { cwd: await realpath(cwd), ...this.host }
const repository = await this.locate(state.paths.cwd, signal)
if (repository === null) return
const tree = await snapshotTree(repository.git, repository.workspace, signal)
state.baseline = { ...repository, tree }
@@ -163,8 +176,7 @@ export class TurnRecorder {
capture(path: string): void {
const state = this.state
void this.enqueue(async () => {
const paths = this.paths
if (paths === undefined) return
if (state.paths === undefined) return
const absolute = await canonicalPath(path)
if (state.captures.has(absolute)) return
const capture = await captureFile(absolute, join(await this.scratchDir(), 'captures'), this.env.maxFileBytes)
@@ -308,7 +320,7 @@ export class TurnRecorder {
}
private async record(state: TurnState, signal: AbortSignal): Promise<void> {
const paths = this.paths
const { paths } = state
const { baseline } = state
if (paths === undefined || baseline === 'failed' || state.lastToolResultSeq < 0) return
state.attemptedAfterSeq = state.lastToolResultSeq
@@ -177,7 +177,7 @@ describe('TurnRecorder', () => {
const gate = new Promise<GitRunner | null>((resolve) => { release = resolve })
const tempRoot = await scratchDir('dsh-git-store-', cleanups)
const env = { git: gate, tempRoot, maxFiles: 10, maxFileBytes: 1024, diffTimeoutMs: 100, warn: (m: string) => { warnings.push(m) } }
const disposed = new TurnRecorder(session, () => cwd, env)
const disposed = new TurnRecorder(session, cwd, env)
disposed.start(1)
await new Promise(resolve => setTimeout(resolve, 5))
const disposal = disposed.dispose()
@@ -189,7 +189,7 @@ describe('TurnRecorder', () => {
expect(disposed.summary(1)).toBeUndefined()
const { git: missing } = await runner(undefined, '/nonexistent/git-binary')
const failing = new TurnRecorder(session, () => cwd, { ...env, git: Promise.resolve(missing) })
const failing = new TurnRecorder(session, cwd, { ...env, git: Promise.resolve(missing) })
failing.start(1)
await failing.settled()
expect(warnings).toHaveLength(1)
@@ -203,13 +203,13 @@ describe('TurnRecorder', () => {
git: Promise.resolve(runnerGit), tempRoot, maxFiles: 10, maxFileBytes: 1024, diffTimeoutMs: 100,
warn: (m: string) => { throw new Error(m) },
}
const plain = new TurnRecorder(ctx.sessions.create(brandString<SessionId>('plain'), { meta: { cwd: tempRoot } }), () => tempRoot, env)
const plain = new TurnRecorder(ctx.sessions.create(brandString<SessionId>('plain'), { meta: { cwd: tempRoot } }), tempRoot, env)
plain.start(1)
await plain.settled()
await plain.dispose()
const cwd = await scratchDir('dsh-recorder-repo-', cleanups)
git(cwd, 'init', '-q', '-b', 'main')
const repo = new TurnRecorder(ctx.sessions.create(brandString<SessionId>('repo'), { meta: { cwd } }), () => cwd, env)
const repo = new TurnRecorder(ctx.sessions.create(brandString<SessionId>('repo'), { meta: { cwd } }), cwd, env)
repo.start(1)
await repo.settled()
const [objects, ...others] = (await readdir(tempRoot)).filter(entry => entry.startsWith('dsh-workspace-changes-'))
@@ -232,7 +232,7 @@ describe('TurnRecorder', () => {
git: Promise.resolve(runnerGit), tempRoot, maxFiles: 10, maxFileBytes: 1024, diffTimeoutMs: 100,
warn: (m: string) => { throw new Error(m) },
}
const recorder = new TurnRecorder(session, () => cwd, env)
const recorder = new TurnRecorder(session, cwd, env)
startTurn(session, 1)
recorder.start(1)
await recorder.settled()
@@ -178,12 +178,13 @@ export async function hasBranch(
* @param session - Session whose sandbox policy and execution world apply.
* @param directory - working directory of every command.
* @param signal - cancellation of every command.
* @param root - checkout that bounds the commands instead of the Session's workspace root: the source
* repository of the Session's worktree, which may be gone while the repository is read.
* @param root - checkout that bounds the commands in place of the Session's workspace root: the source
* repository of the Session's worktree, which is read while the worktree directory may be gone.
* @returns the runner.
*/
export function gitIn(ctx: Context, config: GitConfig, session: Session, directory: string, signal: AbortSignal, root?: string): Git {
const policy = ctx.sandboxPolicy.resolve({ session, ...root === undefined ? {} : { root } })
const resolved = ctx.sandboxPolicy.resolve({ session })
const policy = root === undefined ? resolved : { ...resolved, workspaceRoot: root }
return (name, args, allowedExitCodes = [0], configOverrides = {}) =>
runGit(ctx, config, policy, directory, name, args, signal, allowedExitCodes, configOverrides)
}
+7 -5
View File
@@ -445,13 +445,15 @@ export class WorktreeService extends Service {
}
/**
* The Session's policy bounded by the source checkout of a recorded worktree, with that checkout's
* shared Git directory derived. Removal and restoration run in the source checkout, which contains
* the worktree directory; the Session's own root may be that directory, removed or being removed.
* The policy removal and restoration run under: the Session's mode and grants, bounded by the source
* checkout of the recorded worktree instead of the Session's own root, which may be the worktree
* directory, removed or being removed. A linked source checkout's shared Git directory is granted too.
*/
private async sourcePolicy(session: Session, repositoryRoot: string, signal: AbortSignal): Promise<SandboxExecutionPolicy> {
await this.ctx.sandboxPolicy.prepare({ session, root: repositoryRoot }, signal)
return this.ctx.sandboxPolicy.resolve({ session, root: repositoryRoot })
const shared = await this.ctx.sandboxPolicy.prepare({ directory: repositoryRoot }, signal)
const policy = this.ctx.sandboxPolicy.resolve({ session })
const additional = [...new Set([...policy.additionalWritableRoots ?? [], ...shared])]
return { ...policy, workspaceRoot: repositoryRoot, ...additional.length === 0 ? {} : { additionalWritableRoots: additional } }
}
/** Confine Git commands to the caller's sandbox policy, collecting bounded stdout. */
@@ -131,7 +131,7 @@ describe('archive-triggered worktree cleanup', () => {
const head = await git(f.worktree.path, 'rev-parse', 'HEAD')
const statuses: WorktreeCleanup['status'][] = []
f.ctx.on('worktree/cleanup', ({ cleanup }) => { statuses.push(cleanup.status) })
const resolve = vi.spyOn(f.ctx.sandboxPolicy, 'resolve')
const prepare = vi.spyOn(f.ctx.sandboxPolicy, 'prepare')
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' })
@@ -141,8 +141,7 @@ describe('archive-triggered worktree cleanup', () => {
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
// The creator's root is the checkout being removed; its commands are bounded by the source checkout instead.
expect(f.ctx.workingDirectory.get(f.session)).toBe(f.worktree.path)
const roots = resolve.mock.calls.filter(([request]) => request?.session === f.session).map(([request]) => request?.root)
expect(roots).toEqual([undefined, f.root])
expect(prepare).toHaveBeenCalledWith({ directory: f.root }, expect.any(AbortSignal))
})
it('removes a clean checkout whose file listing exceeds maxOutputBytes', async () => {
@@ -137,6 +137,32 @@ describe.skipIf(!sandboxUsable)('worktree standing sandbox policy', () => {
expect(fetches[0]![1]).toMatchObject({ mode: 'workspace-write', workspaceRoot: linked, additionalWritableRoots: [join(clone, '.git')] })
})
it('restores a missing worktree of a linked source checkout in a process that never worked in it', async () => {
root = await repository(process.cwd())
const linked = join(root, 'linked')
await git(root, 'worktree', 'add', '-b', 'linked', linked)
const first = await harness(linked, {}, 'workspace-write')
let created
try {
created = await first.worktrees.create(testAgent(first, linked), { name: 'cold' })
} finally {
await first.fiber.dispose()
}
await rm(created.path, { recursive: true, force: true })
// A new process: nothing is derived yet, and the Session's own root no longer exists.
ctx = await harness(linked, {}, 'workspace-write')
const agent = testAgent(ctx, linked, 'cold-resumed')
agent.session.append('workspace-root/change', { cwd: created.path })
expect(ctx.workingDirectory.get(agent.session)).toBe(created.path)
const confine = vi.spyOn(ctx.sandbox, 'confine')
expect(await ctx.worktrees.restore(agent, created)).toEqual({ path: created.path, branchRecreated: false })
// The source checkout's shared Git directory lies outside it; the worktree service adds the derived grant.
expect(await git(created.path, 'branch', '--show-current')).toBe('cold')
expect(confine.mock.calls.every(call => call[1].workspaceRoot === linked && call[1].additionalWritableRoots?.includes(join(root!, '.git')))).toBe(true)
})
it('restores a removed worktree under the source checkout boundary while the Session root is the removed directory', async () => {
root = await repository(process.cwd())
ctx = await harness(root, {}, 'workspace-write')
@@ -2907,8 +2907,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: 'resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy',
description: 'Resolve the complete policy for one capability call. An approved explicit mode outranks the session\'s last `sandbox/mode` event, which outranks the deployment default. A session\'s workspace root is its workspace-write boundary, and the Git administration directories prepare derived for that root join the configured extra writable directories; the configured root is the fallback for agentless calls and, without the working-directory service, sessions without a header directory, and a requested `root` replaces the session\'s root for the call. Configured extra roots, this Session\'s active registrations, and the derived Git directories are snapshotted together; existing operations and processes keep their policy.',
parameters: [{ name: 'request', description: 'optional session, approved mode override, and root override.' }],
description: 'Resolve the complete policy for one capability call. An approved explicit mode outranks the session\'s last `sandbox/mode` event, which outranks the deployment default. A session\'s workspace root is its workspace-write boundary, and the Git administration directories prepare derived for that root join the configured extra writable directories; the configured root is the fallback for agentless calls and, without the working-directory service, sessions without a header directory. Configured extra roots, this Session\'s active registrations, and the derived Git directories are snapshotted together; existing operations and processes keep their policy.',
parameters: [{ name: 'request', description: 'optional session and approved mode override.' }],
returns: 'the fully resolved per-call mode, absolute workspace root, and extra writable directories.',
throws: ['`SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the selected root is relative or contains a NUL byte.'],
},
@@ -2926,10 +2926,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
returns: 'the last logged mode, or `undefined` without one.',
},
{
signature: 'async prepare(request: Pick<SandboxPolicyRequest, \'session\' | \'root\'>, signal?: AbortSignal): Promise<readonly string[]>',
description: 'Derive the Git administration directories of the session\'s workspace root so the next resolve grants them: a linked checkout\'s `.git` file names `<common>/worktrees/<name>`, whose `commondir` names the repository\'s common directory and whose `gitdir` names the checkout\'s `.git` again; only that layout grants the common directory, since the checkout\'s own `.git` pointer is writable under workspace-write. Any other layout, a root without `.git`, and a common directory containing the root add nothing. One derivation runs per root and its result is kept once the layout was read, so a pointer written later does not widen the policy until a Host operation moves a Session\'s workspace to that root again; a derived directory that disappears is derived again, and a failed read is logged once per root and retried on the next call.',
parameters: [{ name: 'request', description: 'session whose workspace root is inspected, or the root {@link resolve} would select for the same request.' }, { name: 'signal', description: 'caller cancellation, checked before and after the shared derivation.' }],
returns: 'the derived directories outside the root, canonical in the execution world.',
signature: 'async prepare(target: { session: Session } | { directory: string }, signal?: AbortSignal): Promise<readonly string[]>',
description: 'Derive the Git administration directories a linked checkout writes outside itself, as `./linked-checkout.ts` reads them. For a Session the checkout is its workspace root, and the next resolve for that Session grants the result. For a named `directory`, a Host operation that runs in a checkout no Session works in adds the result to the policy it builds; `resolve` is unaffected. One derivation runs per directory and its result is kept once the layout was read, so a pointer written later does not widen a policy until a Host operation moves a Session\'s workspace to that directory again; a derived directory that disappears is derived again, and a failed read is logged once per directory and retried on the next call.',
parameters: [{ name: 'target', description: 'Session whose workspace root is inspected, or the checkout directory itself.' }, { name: 'signal', description: 'caller cancellation, checked before and after the shared derivation.' }],
returns: 'the derived directories outside the checkout, canonical in the execution world.',
throws: ['`SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the directory is relative or contains a NUL byte.'],
},
],
},
@@ -4984,7 +4985,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
methods: [
{
signature: 'scopeOf(sessionId: SessionId, signal?: AbortSignal): Promise<WorkspaceFileScope | undefined>',
description: 'Resolve the scope other Host services use to open the same `session/<id>/<path>` addresses: a live Session\'s directory, else a stored Session\'s cached directory, else its header directory.',
description: 'Resolve the scope other Host services use to open the same `session/<id>/<path>` addresses: a live Session\'s sandbox workspace root, else a stored Session\'s cached directory, else its header directory.',
parameters: [{ name: 'sessionId', description: 'Session identity received on the wire.' }, { name: 'signal', description: 'cancellation for the persistence read of a stored Session.' }],
returns: 'the scope, or undefined when no live or stored Session has that identity.',
},
@@ -9000,7 +9001,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'SandboxPolicyRequest',
declaration: 'export interface SandboxPolicyRequest {\n session?: Session;\n mode?: SandboxMode;\n root?: string;\n}',
declaration: 'export interface SandboxPolicyRequest {\n session?: Session;\n mode?: SandboxMode;\n}',
},
{
name: 'SaveFileAttachment',
@@ -36,8 +36,8 @@
en: 2d560aa6681fcfb8
zh: e1c6361a6fa40c63
/deepseek-ai-dsh-sandbox-policy/understand-the-implementation/resolution-precedence:
en: c44816d91f4f8130
zh: 0e93e9307e756f39
en: 9933eebcea794957
zh: 3d0c7b6dd062a2ce
/deepseek-ai-dsh-sandbox-policy/understand-the-implementation/the-per-session-store:
en: a2ff737890a75e54
zh: b166e15ec95f3fd4
@@ -45,8 +45,8 @@
en: af0d19c6de17a272
zh: d90e538f9ac85b77
/deepseek-ai-dsh-sandbox-policy/understand-the-implementation/source-map:
en: cc7dd675c9915f7d
zh: d719c4f9de39873a
en: b5a0c99bb5dee846
zh: 603887d9ea187e3e
/deepseek-ai-dsh-sandbox-policy/further-exploration:
en: 7b110e18967f2754
zh: 823c261edeae750a
+2 -1
View File
@@ -78,7 +78,7 @@ This section explains policy resolution, the per-session store, and the model-vi
### Resolution precedence
`resolve({ session, mode, root })` returns one complete per-call policy: an approved explicit mode outranks the session's last `sandbox/mode` event, which outranks the deployment default. The session's directory from the working-directory service supplies the boundary; without that service its header directory and then the configured root do; the derived Git administration directories of that root join the configured extra directories. A requested `root` replaces the session's root for that call, with the derivation `prepare({ session, root })` made for it: Host maintenance of a checkout the session does not work in, such as removing or restoring the session's worktree from its source repository, uses it with the session's mode and grants, and no model input reaches it. Absolute execution-world spelling is preserved. Enforcing providers canonicalize the root on their own filesystem, so remote `symlink/..` paths are never resolved on the Harness host.
`resolve({ session, mode })` returns one complete per-call policy: an approved explicit mode outranks the session's last `sandbox/mode` event, which outranks the deployment default. The session's directory from the working-directory service supplies the boundary; without that service its header directory and then the configured root do; the derived Git administration directories of that root join the configured extra directories. `prepare({ directory })` derives the same directories for a checkout no session works in and changes no resolved policy: a Host operation that runs in that checkout, such as the worktree service removing or restoring a session's worktree from its source repository, adds the result to the policy it builds itself. Absolute execution-world spelling is preserved. Enforcing providers canonicalize the root on their own filesystem, so remote `symlink/..` paths are never resolved on the Harness host.
### The per-session store
@@ -94,6 +94,7 @@ The `sandbox:policy` contribution states the mode's capability-neutral file-effe
|---|---|
| [`src/index.ts`](src/index.ts) | Plugin entry: `SandboxPolicyService`, `Config` schema, policy resolution and context contribution |
| [`src/session-mode.ts`](src/session-mode.ts) | The `sandbox/mode` event, its fold, and the write path |
| [`src/linked-checkout.ts`](src/linked-checkout.ts) | Reads of a linked checkout's Git administration layout through the filesystem; no service state |
</details>
+2 -1
View File
@@ -78,7 +78,7 @@ kind: "package-reference"
### 解析优先级
`resolve({ session, mode, root })` 返回一份完整的逐调用策略:已批准的显式模式优先于会话最后一条 `sandbox/mode` 事件,后者又优先于部署默认值。工作目录服务给出的会话目录提供边界;没有该服务时依次使用 header 目录和配置的根;该根推导出的 Git 管理目录与配置的额外目录合并。请求中的 `root` 在该次调用里替代会话的根,并配合为它做的推导 `prepare({ session, root })`:Host 对会话并不在其中工作的检出目录做维护时使用它,例如从源仓库移除或恢复会话的 worktree,沿用会话的模式与授权,模型输入无法触及。执行环境中的绝对路径写法保持不变。执行限制的提供方在自己的文件系统上规范化根目录,因此远端 `symlink/..` 路径绝不会在 Harness 主机上解析。
`resolve({ session, mode })` 返回一份完整的逐调用策略:已批准的显式模式优先于会话最后一条 `sandbox/mode` 事件,后者又优先于部署默认值。工作目录服务给出的会话目录提供边界;没有该服务时依次使用 header 目录和配置的根;该根推导出的 Git 管理目录与配置的额外目录合并。`prepare({ directory })` 为没有会话在其中工作的检出目录推导同样的目录,不改变任何已解析的策略:在该检出目录中运行的 Host 操作(例如 worktree 服务从源仓库移除或恢复会话的 worktree)把结果加入它自己构造的策略。执行环境中的绝对路径写法保持不变。执行限制的提供方在自己的文件系统上规范化根目录,因此远端 `symlink/..` 路径绝不会在 Harness 主机上解析。
### 逐会话存储
@@ -94,6 +94,7 @@ kind: "package-reference"
|---|---|
| [`src/index.ts`](src/index.ts) | 插件入口:`SandboxPolicyService`、`Config` schema、策略解析与上下文贡献 |
| [`src/session-mode.ts`](src/session-mode.ts) | `sandbox/mode` 事件、其 fold 与写入路径 |
| [`src/linked-checkout.ts`](src/linked-checkout.ts) | 通过文件系统读取链接检出目录的 Git 管理目录布局;不含服务状态 |
</details>
+35 -101
View File
@@ -23,13 +23,12 @@
* @module @deepseek-ai/dsh-sandbox-policy
*/
import { basename, dirname, isAbsolute, relative, sep } from 'node:path'
import { isAbsolute } from 'node:path'
import { Context, Service } from '@deepseek-ai/cordis'
import { z as zod } from 'zod'
import z from '@deepseek-ai/schemastery'
import type {} from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-fs'
import type { FileSystem } from '@deepseek-ai/dsh-fs'
import { SandboxInvalidRootError } from '@deepseek-ai/dsh-sandbox'
import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
import type { Session } from '@deepseek-ai/dsh-session'
@@ -37,6 +36,7 @@ import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
import type {} from '@deepseek-ai/dsh-system-prompt'
import type {} from '@deepseek-ai/dsh-tools'
import type {} from '@deepseek-ai/dsh-working-directory'
import { linkedCheckoutAdministration, within } from './linked-checkout.ts'
export { SANDBOX_MODES, setSandboxMode } from './session-mode.ts'
@@ -96,65 +96,6 @@ function renderPolicyContext(policy: SandboxExecutionPolicy): string {
}
}
/**
* Whether `path` is `root` or lies below it. Both are canonical absolute paths of one execution
* world; the test is lexical and never touches the filesystem.
*/
function within(root: string, path: string): boolean {
const rest = relative(root, path)
return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest))
}
/** The `gitdir:` pointer line of a linked checkout's `.git` file. */
const GITDIR_POINTER = /^gitdir:[ \t]*(.+?)[ \t\r]*$/m
/**
* Read one short pointer file inside a Git administration directory through the execution-world filesystem.
* @returns the text, or undefined when the path is not a regular file.
*/
async function pointerText(fs: FileSystem, path: string, cwd: string, signal: AbortSignal): Promise<string | undefined> {
const entry = await fs.lstat(path, { cwd }, signal)
if (entry?.type !== 'file') return undefined
return fs.readText(await fs.resolve(path, { cwd, signal }), signal)
}
/** Resolve a pointer target to a canonical directory, or undefined when it is not an existing directory. */
async function pointerDirectory(fs: FileSystem, path: string, cwd: string, signal: AbortSignal): Promise<string | undefined> {
const target = await fs.resolve(path, { cwd, signal })
const info = await fs.stat(target, signal)
return info?.type === 'directory' ? fs.processPath(target) : undefined
}
/**
* The Git administration directories a linked checkout at `root` writes outside itself, in the
* layout Git creates for a linked worktree: `.git` names `<common>/worktrees/<name>`, whose
* `commondir` names `<common>` and whose `gitdir` names `<root>/.git` again. The checkout's own
* tree is writable under workspace-write, so its `.git` pointer is untrusted on its own; the
* reverse pointer lives inside the directory being granted, which a forger would already have to
* write. A common directory containing the root, including the filesystem root, never joins. Every
* other layout yields nothing: a root without `.git`, a `.git` directory, a submodule pointer, or
* a hand-written pointer to an arbitrary directory.
* @returns the common directory and the administration directory, canonical, or an empty list.
*/
async function linkedCheckoutAdministration(fs: FileSystem, root: string, signal: AbortSignal): Promise<string[]> {
const pointer = await fs.lstat('.git', { cwd: root }, signal)
if (pointer?.type !== 'file') return []
const pointerTarget = await fs.resolve('.git', { cwd: root, signal })
const target = GITDIR_POINTER.exec(await fs.readText(pointerTarget, signal))?.[1]
if (target === undefined) return []
const gitDirectory = await pointerDirectory(fs, target, root, signal)
if (gitDirectory === undefined || basename(dirname(gitDirectory)) !== 'worktrees') return []
const common = dirname(dirname(gitDirectory))
const commonPointer = (await pointerText(fs, 'commondir', gitDirectory, signal))?.trim()
if (commonPointer === undefined || commonPointer.length === 0) return []
if (await pointerDirectory(fs, commonPointer, gitDirectory, signal) !== common) return []
const back = (await pointerText(fs, 'gitdir', gitDirectory, signal))?.trim()
if (back === undefined || back.length === 0) return []
if (fs.processPath(await fs.resolve(back, { cwd: gitDirectory, signal })) !== fs.processPath(pointerTarget)) return []
if (within(common, root)) return []
return [common, gitDirectory]
}
declare module '@deepseek-ai/cordis' {
interface Context {
sandboxPolicy: SandboxPolicyService
@@ -195,13 +136,6 @@ export interface SandboxPolicyRequest {
session?: Session
/** Explicit approved mode override, which outranks session policy. */
mode?: SandboxMode
/**
* Checkout that bounds this call instead of the session's workspace root: Host maintenance of a
* checkout the session does not work in, such as removing or restoring the session's worktree from
* its source repository while the session's own root is that worktree. The session's mode and
* registered grants still apply. Never reachable from model input.
*/
root?: string
}
/** The sandbox-mode projection's state schema (state equals the public shape). */
@@ -315,24 +249,19 @@ export class SandboxPolicyService extends Service {
* boundary, and the Git administration directories {@link prepare} derived
* for that root join the configured extra writable directories; the
* configured root is the fallback for agentless calls and, without the
* working-directory service, sessions without a header directory, and a
* requested `root` replaces the session's root for the call. Configured extra
* roots, this Session's active registrations, and the derived Git directories
* are snapshotted together; existing operations and processes keep their
* policy.
* @param request - optional session, approved mode override, and root override.
* working-directory service, sessions without a header directory. Configured
* extra roots, this Session's active registrations, and the derived Git
* directories are snapshotted together; existing operations and processes
* keep their policy.
* @param request - optional session and approved mode override.
* @returns the fully resolved per-call mode, absolute workspace root, and extra writable directories.
* @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the selected root is relative or
* contains a NUL byte.
*/
resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy {
const { session } = request
const workspaceRoot = resolveWorkspaceRoot(request.root ?? this.rootOf(session))
const registrations = session === undefined ? undefined : this.writableRootRegistrations.get(session)
const derived = session === undefined ? undefined : this.gitAdministration.get(workspaceRoot)
const additional = registrations === undefined && (derived === undefined || derived.length === 0)
? this.additionalWritableRoots
: resolveAdditionalWritableRoots([...(this.additionalWritableRoots ?? []), ...(registrations?.values() ?? []), ...(derived ?? [])])
const workspaceRoot = resolveWorkspaceRoot(this.rootOf(session))
const additional = this.writableRootsOf(session, session === undefined ? undefined : this.gitAdministration.get(workspaceRoot))
return {
mode: request.mode ?? (session === undefined ? undefined : this.overrideOf(session)) ?? this.defaultMode,
workspaceRoot,
@@ -382,26 +311,23 @@ export class SandboxPolicyService extends Service {
}
/**
* Derive the Git administration directories of the session's workspace root
* so the next {@link resolve} grants them: a linked checkout's `.git` file
* names `<common>/worktrees/<name>`, whose `commondir` names the repository's
* common directory and whose `gitdir` names the checkout's `.git` again; only
* that layout grants the common directory, since the checkout's own `.git`
* pointer is writable under workspace-write. Any other layout, a root without
* `.git`, and a common directory containing the root add nothing. One
* derivation runs per root and its result is kept once the layout was read,
* so a pointer written later does not widen the policy until a Host operation
* moves a Session's workspace to that root again; a derived directory that disappears is
* derived again, and a failed read is logged once per root and retried on
* the next call.
* @param request - session whose workspace root is inspected, or the root {@link resolve} would select
* for the same request.
* Derive the Git administration directories a linked checkout writes outside itself, as
* `./linked-checkout.ts` reads them. For a Session the checkout is its workspace root, and the next
* {@link resolve} for that Session grants the result. For a named `directory`, a Host operation that
* runs in a checkout no Session works in adds the result to the policy it builds; `resolve` is
* unaffected. One derivation runs per directory and its result is kept once the layout was read, so a
* pointer written later does not widen a policy until a Host operation moves a Session's workspace to
* that directory again; a derived directory that disappears is derived again, and a failed read is
* logged once per directory and retried on the next call.
* @param target - Session whose workspace root is inspected, or the checkout directory itself.
* @param signal - caller cancellation, checked before and after the shared derivation.
* @returns the derived directories outside the root, canonical in the execution world.
* @returns the derived directories outside the checkout, canonical in the execution world.
* @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the directory is relative or
* contains a NUL byte.
*/
async prepare(request: Pick<SandboxPolicyRequest, 'session' | 'root'>, signal?: AbortSignal): Promise<readonly string[]> {
async prepare(target: { session: Session } | { directory: string }, signal?: AbortSignal): Promise<readonly string[]> {
signal?.throwIfAborted()
const root = resolveWorkspaceRoot(request.root ?? this.rootOf(request.session))
const root = resolveWorkspaceRoot('directory' in target ? target.directory : this.rootOf(target.session))
const settled = this.gitAdministration.get(root)
if (settled !== undefined) {
if (await this.present(settled, signal)) return settled
@@ -469,13 +395,21 @@ export class SandboxPolicyService extends Service {
*/
private configuredPolicy(session: Session): SandboxExecutionPolicy {
const { mode, workspaceRoot } = this.resolve({ session })
const registrations = this.writableRootRegistrations.get(session)
const advertised = registrations === undefined
? this.additionalWritableRoots
: resolveAdditionalWritableRoots([...(this.additionalWritableRoots ?? []), ...registrations.values()])
const advertised = this.writableRootsOf(session)
return { mode, workspaceRoot, ...advertised === undefined ? {} : { additionalWritableRoots: advertised } }
}
/**
* The configured extra roots, the Session's registered grants, and `derived` Git administration
* directories as one validated list; undefined when there is none.
*/
private writableRootsOf(session: Session | undefined, derived: readonly string[] = []): readonly string[] | undefined {
const registrations = session === undefined ? undefined : this.writableRootRegistrations.get(session)
return registrations === undefined && derived.length === 0
? this.additionalWritableRoots
: resolveAdditionalWritableRoots([...(this.additionalWritableRoots ?? []), ...(registrations?.values() ?? []), ...derived])
}
/**
* The session's workspace root: its directory from the working-directory service; without that service
* the header directory, else the deployment fallback.
@@ -0,0 +1,78 @@
/**
* The Git administration directories of a linked checkout, read through the
* execution-world filesystem. These functions hold no service state.
* @module
*/
import { basename, dirname, isAbsolute, relative, sep } from 'node:path'
import type { FileSystem } from '@deepseek-ai/dsh-fs'
/**
* Whether `path` is `root` or lies below it. Both are canonical absolute paths of one execution
* world; the test is lexical and never touches the filesystem.
* @param root - canonical absolute directory.
* @param path - canonical absolute path to test.
* @returns whether `root` contains `path`.
*/
export function within(root: string, path: string): boolean {
const rest = relative(root, path)
return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest))
}
/** The `gitdir:` pointer line of a linked checkout's `.git` file. */
const GITDIR_POINTER = /^gitdir:[ \t]*(.+?)[ \t\r]*$/m
/**
* Read one short pointer file inside a Git administration directory.
* @param fs - execution-world filesystem.
* @param path - pointer file, absolute or relative to `cwd`.
* @param cwd - directory a relative `path` resolves from.
* @param signal - cancellation of the reads.
* @returns the text, or undefined when the path is not a regular file.
*/
export async function pointerText(fs: FileSystem, path: string, cwd: string, signal: AbortSignal): Promise<string | undefined> {
const entry = await fs.lstat(path, { cwd }, signal)
if (entry?.type !== 'file') return undefined
return fs.readText(await fs.resolve(path, { cwd, signal }), signal)
}
/**
* Resolve a pointer target to a canonical directory.
* @param fs - execution-world filesystem.
* @param path - pointer target, absolute or relative to `cwd`.
* @param cwd - directory a relative `path` resolves from.
* @param signal - cancellation of the reads.
* @returns the canonical directory, or undefined when the target is not an existing directory.
*/
export async function pointerDirectory(fs: FileSystem, path: string, cwd: string, signal: AbortSignal): Promise<string | undefined> {
const target = await fs.resolve(path, { cwd, signal })
const info = await fs.stat(target, signal)
return info?.type === 'directory' ? fs.processPath(target) : undefined
}
/**
* The Git administration directories a linked checkout at `root` writes outside itself. Only the layout
* Git creates for a linked worktree yields them; the [README](../README.md#use-this-package) states why.
* @param fs - execution-world filesystem.
* @param root - canonical absolute checkout directory.
* @param signal - cancellation of the reads.
* @returns the common directory and the administration directory, canonical, or an empty list.
*/
export async function linkedCheckoutAdministration(fs: FileSystem, root: string, signal: AbortSignal): Promise<string[]> {
const pointer = await fs.lstat('.git', { cwd: root }, signal)
if (pointer?.type !== 'file') return []
const pointerTarget = await fs.resolve('.git', { cwd: root, signal })
const target = GITDIR_POINTER.exec(await fs.readText(pointerTarget, signal))?.[1]
if (target === undefined) return []
const gitDirectory = await pointerDirectory(fs, target, root, signal)
if (gitDirectory === undefined || basename(dirname(gitDirectory)) !== 'worktrees') return []
const common = dirname(dirname(gitDirectory))
const commonPointer = (await pointerText(fs, 'commondir', gitDirectory, signal))?.trim()
if (commonPointer === undefined || commonPointer.length === 0) return []
if (await pointerDirectory(fs, commonPointer, gitDirectory, signal) !== common) return []
const back = (await pointerText(fs, 'gitdir', gitDirectory, signal))?.trim()
if (back === undefined || back.length === 0) return []
if (fs.processPath(await fs.resolve(back, { cwd: gitDirectory, signal })) !== fs.processPath(pointerTarget)) return []
if (within(common, root)) return []
return [common, gitDirectory]
}
@@ -0,0 +1,89 @@
/** The Git layout reads behind the sandbox policy's derived grants, against a real filesystem. */
import { execFile } from 'node:child_process'
import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, sep } from 'node:path'
import { promisify } from 'node:util'
import { afterEach, describe, expect, it } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
import { linkedCheckoutAdministration, pointerDirectory, pointerText, within } from '../src/linked-checkout.ts'
const execute = promisify(execFile)
const signal = new AbortController().signal
const cleanups: Array<() => Promise<unknown>> = []
afterEach(async () => {
for (const cleanup of cleanups.reverse()) await cleanup()
cleanups.length = 0
})
async function scratch() {
const base = await realpath(await mkdtemp(join(tmpdir(), 'dsh-linked-checkout-')))
cleanups.push(() => rm(base, { recursive: true, force: true }))
const ctx = new Context()
cleanups.push(() => ctx.fiber.dispose())
await ctx.plugin(LocalFileSystem, { cwd: base })
return { base, fs: ctx.fs }
}
describe('within', () => {
it('holds for the directory itself and paths below it, not for parents or siblings sharing a prefix', () => {
const root = join(sep, 'work', 'repo')
expect(within(root, root)).toBe(true)
expect(within(root, join(root, 'packages', 'a'))).toBe(true)
expect(within(root, join(sep, 'work'))).toBe(false)
expect(within(root, `${root}-sibling`)).toBe(false)
expect(within(root, join(root, '..', 'other'))).toBe(false)
})
})
describe('pointer reads', () => {
it('reads a regular pointer file relative to its directory and nothing else', async () => {
const { base, fs } = await scratch()
await writeFile(join(base, 'commondir'), '../..\n')
await mkdir(join(base, 'directory'))
expect(await pointerText(fs, 'commondir', base, signal)).toBe('../..\n')
expect(await pointerText(fs, join(base, 'commondir'), tmpdir(), signal)).toBe('../..\n')
expect(await pointerText(fs, 'directory', base, signal)).toBeUndefined()
expect(await pointerText(fs, 'missing', base, signal)).toBeUndefined()
})
it('resolves a pointer target to the canonical directory it names, or to nothing', async () => {
const { base, fs } = await scratch()
const target = join(base, 'target')
await mkdir(target)
await symlink(target, join(base, 'link'))
await writeFile(join(base, 'file'), '')
expect(await pointerDirectory(fs, 'target', base, signal)).toBe(target)
expect(await pointerDirectory(fs, 'link', base, signal)).toBe(target)
expect(await pointerDirectory(fs, target, tmpdir(), signal)).toBe(target)
expect(await pointerDirectory(fs, 'file', base, signal)).toBeUndefined()
expect(await pointerDirectory(fs, 'missing', base, signal)).toBeUndefined()
})
})
describe('linkedCheckoutAdministration', () => {
it('names the common and administration directories of a linked worktree and nothing for its main checkout', async () => {
const { base, fs } = await scratch()
const repo = join(base, 'repo')
await mkdir(repo)
const git = (...args: string[]) => execute('git', ['-c', 'core.hooksPath=/dev/null', ...args], {
cwd: repo,
env: {
...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '', GIT_DIR: undefined, GIT_WORK_TREE: undefined,
GIT_AUTHOR_NAME: 'Policy fixture', GIT_AUTHOR_EMAIL: '[email protected]',
GIT_COMMITTER_NAME: 'Policy fixture', GIT_COMMITTER_EMAIL: '[email protected]',
},
})
await git('init', '-q', '-b', 'main')
await git('config', 'commit.gpgSign', 'false')
await git('commit', '-q', '--allow-empty', '-m', 'initial')
const linked = join(base, 'linked')
await git('worktree', 'add', '-q', '-b', 'linked', linked)
expect(await linkedCheckoutAdministration(fs, linked, signal)).toEqual([join(repo, '.git'), join(repo, '.git', 'worktrees', 'linked')])
expect(await linkedCheckoutAdministration(fs, repo, signal)).toEqual([])
expect(await linkedCheckoutAdministration(fs, base, signal)).toEqual([])
})
})
@@ -112,7 +112,7 @@ describe('workspace root as the write boundary', () => {
expect(ctx.sandboxPolicy.resolve({ session })).toEqual({ mode: 'workspace-write', workspaceRoot: repo, sessionId: session.id })
})
it('bounds a Host operation to another checkout on request and derives that checkout\'s Git administration', async () => {
it('derives the Git administration of a named checkout for a Host operation and leaves Session policies as they are', async () => {
const { base, repo } = await scratch()
const extra = join(base, 'extra')
await mkdir(extra)
@@ -124,15 +124,12 @@ describe('workspace root as the write boundary', () => {
const session = ctx.sessions.create(brandString<SessionId>('maintenance'), { meta: { cwd: worktree } })
expect(await ctx.sandboxPolicy.prepare({ session })).toEqual([join(repo, '.git')])
// The source checkout keeps its Git directory inside itself, so nothing is derived for it.
expect(await ctx.sandboxPolicy.prepare({ session, root: repo })).toEqual([])
expect(ctx.sandboxPolicy.resolve({ session, root: repo })).toEqual({
mode: 'workspace-write', workspaceRoot: repo, additionalWritableRoots: [extra], sessionId: session.id,
expect(await ctx.sandboxPolicy.prepare({ directory: repo })).toEqual([])
expect(await ctx.sandboxPolicy.prepare({ directory: other })).toEqual([join(repo, '.git')])
expect(ctx.sandboxPolicy.resolve({ session })).toEqual({
mode: 'workspace-write', workspaceRoot: worktree, additionalWritableRoots: [extra, join(repo, '.git')], sessionId: session.id,
})
expect(await ctx.sandboxPolicy.prepare({ session, root: other })).toEqual([join(repo, '.git')])
expect(ctx.sandboxPolicy.resolve({ session, root: other }).additionalWritableRoots).toEqual([extra, join(repo, '.git')])
expect(ctx.sandboxPolicy.resolve({ session }).workspaceRoot).toBe(worktree)
expect(() => ctx.sandboxPolicy.resolve({ session, root: 'relative' })).toThrow('absolute execution-world path')
await expect(ctx.sandboxPolicy.prepare({ session, root: 'relative' })).rejects.toThrow('absolute execution-world path')
await expect(ctx.sandboxPolicy.prepare({ directory: 'relative' })).rejects.toThrow('absolute execution-world path')
})
it('bounds a Session without a recorded directory by the directory service\'s default directory', async () => {