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

@@ -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)