diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml index 49a9f432ee..5a1a0d4b5a 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml @@ -9,8 +9,8 @@ en: 31fba384d90ce7d2 zh: f8b814868f3280c3 /agent-note-session-working-directory/decision: - en: 9ccde1c5e635b9c0 - zh: 4dc76229703d3ef7 + en: f8af193899e790ad + zh: b3df4a59727ff3a3 /agent-note-session-working-directory/alternatives-considered: en: f0995feb9b6bcce8 zh: 97417085fd17f70f diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md index 8151c0e85a..bec052f9ec 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md @@ -10,7 +10,7 @@ A fixed Session creation directory cannot represent a task that changes checkout ## Decision -`dsh-working-directory` owns one logged effective directory per Session. Its projection initializes from the immutable original project and folds `working-directory/change`; consumers read that owner instead of deriving execution paths from the header or sandbox root. Directory changes validate through the filesystem provider, serialize within the Session, and publish only after the new directory is available. +`dsh-working-directory` owns one logged effective directory per Session. Its projection initializes from the immutable original project and folds `working-directory/change`; consumers read that owner instead of deriving execution paths from the header or sandbox root. Directory changes validate through the filesystem provider, serialize within the Session, and publish only after the new directory is available. The [workspace-root note](2026-11-03-session-workspace-root.md) adds the workspace root and its anchors on top of this owner. The `dsh-base` composition mounts `working_directory({ cd? })` globally. The tool reads or changes the Session directory, so every Agent preset can select or recover it, including presets without file-editing tools. The Web composition keeps action tools in preset scopes. diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md index 46246a9d67..e5254d9525 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md @@ -10,7 +10,7 @@ Status: implemented ## Decision -`dsh-working-directory` 拥有每个 Session 的一个日志化有效目录。投影从不可变的原始项目初始化,并折叠 `working-directory/change`;消费者读取该服务,而不是从 header 或沙箱根目录派生执行路径。目录变更通过文件系统 provider 验证,在 Session 内串行执行,并只在新目录可用后发布。 +`dsh-working-directory` 拥有每个 Session 的一个日志化有效目录。投影从不可变的原始项目初始化,并折叠 `working-directory/change`;消费者读取该服务,而不是从 header 或沙箱根目录派生执行路径。目录变更通过文件系统 provider 验证,在 Session 内串行执行,并只在新目录可用后发布。[工作区根记录](2026-11-03-session-workspace-root.zh.md)在该服务之上增加工作区根及其锚。 `dsh-base` 组合在全局挂载 `working_directory({ cd? })`。该工具读取或改变 Session 目录,使每个 Agent preset 都能选择或恢复它,包括没有文件编辑工具的 preset。Web 组合把操作工具放在 preset 作用域中。 diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml new file mode 100644 index 0000000000..ac78e9858c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-11-03-session-workspace-root.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md +/agent-note-session-workspace-root: + en: f746e6645bc11001 + zh: b7666200c98a96fc +/agent-note-session-workspace-root/problem: + en: cb5864da99a92145 + zh: 210f8b4282f99c93 +/agent-note-session-workspace-root/decision: + en: 2aa85360b92e618d + zh: 079b815ab1e6ece4 +/agent-note-session-workspace-root/deferred: + en: d8167590081dfa4e + zh: 208630aac853773b +/agent-note-session-workspace-root/alternatives-considered: + en: 9d267bf955897821 + zh: 45b7d2cddd34a811 +/agent-note-session-workspace-root/consequences: + en: 9a6bdd11a719b7ea + zh: 9350f11c1097804b diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md new file mode 100644 index 0000000000..7572674a37 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md @@ -0,0 +1,37 @@ +# Agent Note: Session workspace root + +Status: implemented + +English | [中文](2026-11-03-session-workspace-root.zh.md) + +## Problem + +A Session that enters a Git worktree records only a changed current directory. The same event records an ordinary `cd` into a subdirectory, so a consumer cannot tell a moved cursor from a changed checkout: a file view, a change summary, or a write boundary either follows every `cd` or stays on the original project. The original project is the only directory the header records, and a Session opened inside a linked worktree records nothing about the checkout it is in. Peer products that support entering another checkout in one conversation keep an immutable session origin and record each relocation as an event, and they separate the shell cursor from the checkout it is in. + +## Decision + +Each Session has three directories with one owner each. `header.cwd` remains the immutable original project: Session identity, workspace grouping, and the recovery destination. `dsh-working-directory` owns the other two. The current directory is the cursor relative paths resolve from; its `workingDirectory` projection and `set` are unchanged. The workspace root is the checkout that cursor is in; the `workspaceRoot` projection folds it from the same `working-directory/change` events as the longest registered anchor containing the current directory. The anchors are the original project and every checkout `relocate(agent, root, { cwd? })` entered. + +`relocate` validates the root and the directory inside it, then commits one `working-directory/change` whose optional `anchor` names the root. A `set` inside the root moves only the cursor; a `set` into another anchor selects that anchor as the root; a `set` outside every anchor moves the cursor and leaves the root. Recovery to the original project selects it again. The event's optional property is a same-version persistence change recorded in the [acknowledgement](../../../../docs/persistence-changes/2026-11-03-working-directory-anchor.md); a log without `anchor` folds to the original project as its only anchor. + +Worktree creation enters the checkout through `relocate`; leaving it is the existing `set` back into the original project, which the anchor rule turns into a root change. A child subagent keeps the parent's original project in its header; when the parent's root is another checkout and the child starts inside it, the child relocates into that root, so its root matches the parent's. The user-context snapshot adds a `Workspace root` line while the cursor differs from the root, and a change notice ends with the new root when the change selects another root. The SDK working-directory methods return `{ cwd, root }`, and `getWorkspaceRoot` (`get_workspace_root` in Python) reads the root. + +## Deferred + +The sandbox write boundary, the workspace file service, desktop file drag, the change recorder, and the client file tree, deliverables, open-in-app actions, and Session rows still read `header.cwd`. The sidebar terminal, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace still read the current directory although they belong to the root. Until those consumers move, they behave as they did before this decision, and a worktree outside the original project is writable only where the original project's boundary already allows it. + +## Alternatives considered + +**Rewrite the header on relocation.** The header is identity metadata for storage, grouping, and permission roots; the [working-directory note](2026-09-13-session-working-directory.md) rejected rewriting it, and every peer product keeps an immutable origin. + +**A new event type for relocation.** Adding an ordinary event type is also same-version, but an older reader refuses to reconstruct a log holding an unknown required event, so a Session that entered a worktree would not open there. An optional property on the existing event leaves older readers with the current directory they already understood. + +**Let the root follow every `cd`.** A `cd` into `packages/foo` would re-root the file tree and shrink the write boundary to that subdirectory while the user still works on the same project. + +**Derive the root from Git at read time.** The directory service would need Git and filesystem I/O inside a projection; anchors and lexical containment are pure and deterministic over the log. + +**One new Session per worktree, never a relocation.** The model-facing worktree tool already continues one Session in the new checkout; forge's new-Session worktree path and that tool both resolve to the same relocation. + +## Consequences + +Consumers can ask the directory service three questions with three answers: where the Session started, which checkout it works in, and where relative paths resolve. Existing logs change meaning for no reader: they hold no anchor, so the root is the original project. Anchors compare as recorded, so a header recorded through a symlink or with different casing never contains the canonical paths later changes record; the root then stays on the original project. The worktree snapshot fixture and the directory notices carry the root text. Moving the consumers listed under Deferred is a separate change. diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md new file mode 100644 index 0000000000..3603197c8e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md @@ -0,0 +1,37 @@ +# Agent Note: Session workspace root + +Status: implemented + +[English](2026-11-03-session-workspace-root.md) | 中文 + +## Problem + +进入 Git 工作树的 Session 只记录了当前目录的变化。同一事件也记录普通的 `cd` 进入子目录,因此消费方无法区分移动的光标与换掉的检出目录:文件视图、变更摘要或写边界要么跟随每次 `cd`,要么停留在原始项目上。header 只记录原始项目这一个目录,而直接在链接工作树内打开的 Session 不记录它所在的检出目录。支持在一段对话内进入另一个检出目录的同类产品都保留不可变的会话起点,把每次迁移记录为事件,并把 shell 光标与它所在的检出目录区分开。 + +## Decision + +每个 Session 有三个目录,各有一个所有者。`header.cwd` 仍是不可变的原始项目:Session 身份、工作区分组和恢复目的地。`dsh-working-directory` 拥有另外两个。当前目录是相对路径解析的光标;它的 `workingDirectory` 投影与 `set` 不变。工作区根是该光标所在的检出目录;`workspaceRoot` 投影从同样的 `working-directory/change` 事件折叠出它,取包含当前目录的最长已登记锚。锚是原始项目以及 `relocate(agent, root, { cwd? })` 进入过的每个检出目录。 + +`relocate` 验证根及其内部的目录,然后提交一条可选 `anchor` 指向该根的 `working-directory/change`。根内部的 `set` 只移动光标;进入另一个锚的 `set` 把该锚选为根;所有锚之外的 `set` 移动光标并保留根。恢复到原始项目时再次把它选为根。事件的可选属性是一次同版本持久化变更,记录在[确认记录](../../../../docs/persistence-changes/2026-11-03-working-directory-anchor.zh.md)中;没有 `anchor` 的日志折叠后以原始项目为唯一的锚。 + +工作树创建通过 `relocate` 进入检出目录;离开它就是既有的 `set` 回到原始项目,锚规则将其变为根的变化。子代理在 header 中保留父级的原始项目;当父级的根是另一个检出目录且子级在其中启动时,子级迁入该根,因此子级的根与父级一致。光标与根不同时,用户上下文快照增加一行 `Workspace root`,选中另一个根的变更在通知末尾给出新根。SDK 的工作目录方法返回 `{ cwd, root }`,`getWorkspaceRoot`(Python 中为 `get_workspace_root`)读取根。 + +## Deferred + +沙箱写边界、工作区文件服务、桌面文件拖拽、变更记录器,以及客户端的文件树、交付物、在应用中打开操作和 Session 行仍读取 `header.cwd`。侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区仍读取当前目录,尽管它们属于根。在这些消费方迁移之前,它们的行为与本决策之前相同,原始项目之外的工作树仅在原始项目的边界已经允许之处可写。 + +## Alternatives considered + +**迁移时改写 header。** header 是用于存储、分组和权限根的身份元数据;[工作目录记录](2026-09-13-session-working-directory.zh.md)否决了改写它,所有同类产品也都保留不可变的起点。 + +**为迁移新增事件类型。** 新增普通事件类型同样是同版本变更,但旧读者遇到未知的必需事件会拒绝重建日志,进入过工作树的 Session 在旧读者那里将无法打开。在既有事件上增加可选属性让旧读者保留它们本已理解的当前目录。 + +**让根跟随每次 `cd`。** `cd` 进入 `packages/foo` 会把文件树重新定根并把写边界缩到该子目录,而用户仍在同一个项目上工作。 + +**读取时从 Git 推导根。** 目录服务需要在投影内使用 Git 和文件系统 I/O;锚与词法包含关系对日志而言是纯粹且确定的。 + +**每个工作树一个新 Session,从不迁移。** 面向模型的工作树工具已经让同一个 Session 在新检出目录中继续;forge 的新 Session 工作树路径与该工具最终都落到同一种迁移。 + +## Consequences + +消费方可以向目录服务提出三个问题并得到三个答案:Session 从哪里开始、在哪个检出目录中工作、相对路径从哪里解析。既有日志对任何读者的含义都不变:它们没有锚,因此根就是原始项目。锚按记录原样比较,因此通过符号链接或以不同大小写记录的 header 永远不包含后续变更记录的规范路径;此时根停留在原始项目上。工作树快照夹具与目录通知携带根的文本。迁移 Deferred 中列出的消费方是另一次变更。 diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 4dc23c45e6..1caf287104 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 6215d15e0e273fa4 - zh: dec5c7779e0a42f5 + en: ad4b3313be398248 + zh: fca927401411bbcc diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 334e3757bc..11a3702def 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -665,7 +665,7 @@ flowchart LR | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | A Session projection derives bindings from shell results and binding records and publishes their URLs without status to clients; push results trigger head-branch discovery, and Session watchers poll bound change requests through the forge registry. | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | Streams one panel state per followed Session: Git inspection using Session permissions, the recognized code host and its sign-in, and the bound change requests with polled status. | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | Explicit experimental creation from a pinned local commit. Existing write permissions govern checkout and shared Git metadata; the working-directory service owns the resulting Session directory. | -| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | One Session projection owns the effective execution directory. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed. | +| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | Two Session projections own the effective execution directory and the workspace root it is in. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed. | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | Connection-owned providers serve shared resource tools in the calling agent scope. | | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | One provider-owned name per service instance. Providers own their tools and browser resources per live Session; the shared service has no browser operation API. | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | One provider-owned name per service instance. Each provider also owns its model tools; the service has no common action API, runtime selection, or Session workflow lock. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index d0f0bdffb0..140ccaa977 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -667,7 +667,7 @@ flowchart LR | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Session 投影从 shell 结果与绑定记录派生绑定,并把不含状态的 URL 发布给客户端;推送结果触发按 head 分支的发现,Session 监听方通过 forge 注册表轮询已绑定的变更请求。 | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | 为每个被跟随的 Session 推送一份面板状态:使用 Session 权限进行的 Git 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | 显式实验组合从固定的本地提交创建工作树。检出目录与共享 Git 元数据受现有写权限约束;工作目录服务拥有创建后的 Session 目录。 | -| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | 一个 Session 投影拥有有效执行目录。文件系统验证变更,用户上下文报告目录信息,原始元数据与写入授权保持不变。 | +| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | 两个 Session 投影拥有有效执行目录及其所在的工作区根。文件系统验证变更,用户上下文报告目录信息,原始元数据与写入授权保持不变。 | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | 连接所有者提供的操作在调用 agent 的作用域内服务于共享资源工具。 | | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | 每个服务实例注册一个提供方拥有的名称。提供方按实时 Session 拥有自己的工具与浏览器资源;共享服务不提供浏览器操作 API。 | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | 每个服务实例只注册一个提供方自定的名称。各提供方也拥有自己的模型工具;服务不提供通用操作 API、运行时选择或 Session 流程锁。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index b60380b102..55fb2b093b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4808,7 +4808,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:51`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:58`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 95af04f5dd..82b7a01ac1 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4810,7 +4810,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:51`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:58`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 8f7366da1c..61cbdefdd7 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 1387c4505dde2faf zh: 48570fa1c13d6910 /session-persistence-event-catalog/persistence-type-fingerprints: - en: d334560286daab57 - zh: ddece2494dd2131c + en: 6b366238525d037f + zh: 49653a3c928069a2 /session-persistence-event-catalog/event-envelope: en: 56414ffd00cdc32a zh: 6dc11eb013e95e41 @@ -1425,8 +1425,11 @@ en: 1282a0b3d5fa8d4d zh: aa533aea643dbefb /session-persistence-event-catalog/resolved-persistence-types/allowedmodels: - en: 6178321110ceb69d - zh: 0a9d94cab9d57487 + en: 874fb1c541bbca1d + zh: 1aa7e89654cd041a +/session-persistence-event-catalog/resolved-persistence-types/anchor-cwd: + en: 4c7cc91c89725a3f + zh: 5c91de8c4713cc89 /session-persistence-event-catalog/resolved-persistence-types/args-commandid-name-source: en: a117573a5d58cb3c zh: d5ad59e17a3a815d @@ -1479,11 +1482,8 @@ en: 45f1d815198508e1 zh: 5c2818b0e38e1356 /session-persistence-event-catalog/resolved-persistence-types/compactionid-sourcecommandid-turn: - en: bef51e0442ebb903 - zh: 240ebeb160533d8c -/session-persistence-event-catalog/resolved-persistence-types/cwd: - en: 1bc55be85a68f0a3 - zh: 9e84a55ed11bba5d + en: 4ba70efccc268763 + zh: 06ba9b3e824c80a7 /session-persistence-event-catalog/resolved-persistence-types/decision-durationms-exitcode-handlerid: en: a99ac57bbec0370f zh: 9073329e324a66e0 @@ -2190,11 +2190,11 @@ en: 99c8837344178a47 zh: bf746f5678346596 /session-persistence-event-catalog/resolved-persistence-types/type-web-search-20250305: - en: e0071555851c7cee - zh: 1f368baf78a7d689 + en: 0e6874b6a152ec27 + zh: 58222e2549999f41 /session-persistence-event-catalog/resolved-persistence-types/type-working-directory-change: - en: 2fcb09b83898ee18 - zh: 44c7f987f0bf3588 + en: 34d36f207f755da1 + zh: 833668c798a92d9f /session-persistence-event-catalog/resolved-persistence-types/type-workspace-changes: en: 411ecd58c4405c8a zh: e53709d457a1f118 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 16c1cb90f8..d13d8b4112 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -83,7 +83,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | | `event:user/message` | event | `dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450` | [`{ type: "user/message" }`](#persistence-type-sha256-dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | -| `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | +| `event:working-directory/change` | event | `376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | ## Event envelope @@ -1326,6 +1326,11 @@ Source: [`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/ 'working-directory/change': { /** Absolute directory used by subsequent directory-based operations. */ cwd: string + /** + * Absolute checkout directory this change registers as a workspace anchor of the Session; it contains `cwd`. + * Present only when the change enters another checkout, such as a created worktree; an ordinary `cd` omits it. + */ + anchor?: string } ``` @@ -5880,6 +5885,19 @@ Sources: [`packages/subagent/tool-subagent/src/model-selection-state.ts:17`](../ |---|---|---| | `allowedModels` | required | [`SessionTitleModelIdentity[]`](#persistence-type-sha256-ba77b58995e36f14bb13886b0493d0a1a63d5db10b1a6cd9f6ac65a72cf832ec) | + + +### `{ anchor?, cwd }` + +SHA-256: `40a4c38943f2e5ee0eaa0ea48238ec425e7900022a4b08e57c8335f0fd6eb435` + +Sources: [`packages/session/working-directory/src/index.ts:36`](../packages/session/working-directory/src/index.ts) + +| Property | Presence | Type | +|---|---|---| +| `anchor` | optional | `string` | +| `cwd` | required | `string` | + ### `{ args?, commandId, name, source }` @@ -6153,18 +6171,6 @@ Sources: [`packages/compaction/compaction/src/types.ts:24`](../packages/compacti | `sourceCommandId` | optional | `string` | | `turn` | required | [`OptionalSessionSeq`](#persistence-type-sha256-3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f) | - - -### `{ cwd }` - -SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582` - -Sources: [`packages/session/working-directory/src/index.ts:36`](../packages/session/working-directory/src/index.ts) - -| Property | Presence | Type | -|---|---|---| -| `cwd` | required | `string` | - ### `{ decision, durationMs, exitCode?, handlerId, … }` @@ -9306,17 +9312,17 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:71`](../packages/web | `name` | required | `"web_search"` | | `type` | required | `"web_search_20250305"` | - + ### `{ type: "working-directory/change" }` -SHA-256: `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` +SHA-256: `376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ cwd }`](#persistence-type-sha256-da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582) | +| `data` | required | [`{ anchor?, cwd }`](#persistence-type-sha256-40a4c38943f2e5ee0eaa0ea48238ec425e7900022a4b08e57c8335f0fd6eb435) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 5e045309fd..4f67950b5a 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -85,7 +85,7 @@ | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | | `event:user/message` | event | `dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450` | [`{ type: "user/message" }`](#persistence-type-sha256-dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | -| `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | +| `event:working-directory/change` | event | `376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | ## 事件信封 @@ -1328,6 +1328,11 @@ export type SessionEvent = { 'working-directory/change': { /** Absolute directory used by subsequent directory-based operations. */ cwd: string + /** + * Absolute checkout directory this change registers as a workspace anchor of the Session; it contains `cwd`. + * Present only when the change enters another checkout, such as a created worktree; an ordinary `cd` omits it. + */ + anchor?: string } ``` @@ -5882,6 +5887,19 @@ SHA-256: `0d47a8f3d847243c4488e755ad4cab7a04ac5d4621b9c81865524cf3f4d8536f` |---|---|---| | `allowedModels` | 必需 | [`SessionTitleModelIdentity[]`](#persistence-type-sha256-ba77b58995e36f14bb13886b0493d0a1a63d5db10b1a6cd9f6ac65a72cf832ec) | + + +### `{ anchor?, cwd }` + +SHA-256: `40a4c38943f2e5ee0eaa0ea48238ec425e7900022a4b08e57c8335f0fd6eb435` + +来源:[`packages/session/working-directory/src/index.ts:36`](../packages/session/working-directory/src/index.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `anchor` | 可选 | `string` | +| `cwd` | 必需 | `string` | + ### `{ args?, commandId, name, source }` @@ -6155,18 +6173,6 @@ SHA-256: `3e4e7683b0192c9f0e6a75c59076108f017892cdb302a98032c2632fd79c356f` | `sourceCommandId` | 可选 | `string` | | `turn` | 必需 | [`OptionalSessionSeq`](#persistence-type-sha256-3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f) | - - -### `{ cwd }` - -SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582` - -来源:[`packages/session/working-directory/src/index.ts:36`](../packages/session/working-directory/src/index.ts) - -| 属性 | 存在性 | 类型 | -|---|---|---| -| `cwd` | 必需 | `string` | - ### `{ decision, durationMs, exitCode?, handlerId, … }` @@ -9308,17 +9314,17 @@ SHA-256: `2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3` | `name` | 必需 | `"web_search"` | | `type` | 必需 | `"web_search_20250305"` | - + ### `{ type: "working-directory/change" }` -SHA-256: `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` +SHA-256: `376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ cwd }`](#persistence-type-sha256-da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582) | +| `data` | 必需 | [`{ anchor?, cwd }`](#persistence-type-sha256-40a4c38943f2e5ee0eaa0ea48238ec425e7900022a4b08e57c8335f0fd6eb435) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | diff --git a/docs/persistence-changes/2026-11-03-working-directory-anchor.i18n.yaml b/docs/persistence-changes/2026-11-03-working-directory-anchor.i18n.yaml new file mode 100644 index 0000000000..3c06c3d52e --- /dev/null +++ b/docs/persistence-changes/2026-11-03-working-directory-anchor.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-11-03-working-directory-anchor.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/persistence-changes/2026-11-03-working-directory-anchor.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-11-03-working-directory-anchor: + en: cbe770c3f2460721 + zh: e256ec6a9329e44f +/2026-11-03-working-directory-anchor/summary: + en: b77753a6d1fbd48d + zh: b0a8f76fca20614b +/2026-11-03-working-directory-anchor/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-11-03-working-directory-anchor/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-11-03-working-directory-anchor/compatibility: + en: 9c8b04663d2cfeef + zh: 887a30707ecf44b7 +/2026-11-03-working-directory-anchor/verification: + en: 6a06103fc25891a3 + zh: 70cfa189bd680bba +/2026-11-03-working-directory-anchor/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-11-03-working-directory-anchor.md b/docs/persistence-changes/2026-11-03-working-directory-anchor.md new file mode 100644 index 0000000000..433743aee6 --- /dev/null +++ b/docs/persistence-changes/2026-11-03-working-directory-anchor.md @@ -0,0 +1,48 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-11-03-working-directory-anchor + +English | [中文](2026-11-03-working-directory-anchor.zh.md) + +## Summary + +Adds an optional anchor to working-directory/change so one change can register the entered checkout as a workspace anchor of the Session. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-03-working-directory-anchor +baseline: false +changes: + - root: "event:working-directory/change" + previous: "2026-09-13-working-directory" + after: "376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88" + decision: same-version +``` + + +## Compatibility + +Existing events without anchor fold as before: the current-directory projection ignores the property, and the new workspaceRoot projection reads an absent anchor as a move of the current directory with no new anchor, so a stored log keeps its original project as the only anchor. Older readers keep the event type and its cwd; they ignore the optional property and never derived a workspace root, so nothing they interpret changes. + + +## Verification + +pnpm exec vitest run packages/session/working-directory: 37 tests passed, including replay of logs with and without anchor and the user-context text both produce. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-11-03-working-directory-anchor.schema.json b/docs/persistence-changes/2026-11-03-working-directory-anchor.schema.json new file mode 100644 index 0000000000..73b752c223 --- /dev/null +++ b/docs/persistence-changes/2026-11-03-working-directory-anchor.schema.json @@ -0,0 +1,15 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:working-directory/change","kind":"event","event":"working-directory/change","surface":false,"digest":"376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88"} + ], + "types": [], + "nodes": { + "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, + "376ab95962d99133": {"kind":"object","properties":[{"name":"data","type":"40a4c38943f2e5ee","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d4c799e3d51cae10","optional":false}],"indices":[]}, + "40a4c38943f2e5ee": {"kind":"object","properties":[{"name":"anchor","type":"4cd48f3e5108bd6e","optional":true},{"name":"cwd","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4cd48f3e5108bd6e": {"kind":"primitive","type":"string"}, + "d4c799e3d51cae10": {"kind":"literal","value":"working-directory/change"}, + "dacf3d5f3e4ff619": {"kind":"literal","value":true} + } +} diff --git a/docs/persistence-changes/2026-11-03-working-directory-anchor.zh.md b/docs/persistence-changes/2026-11-03-working-directory-anchor.zh.md new file mode 100644 index 0000000000..6ab743575c --- /dev/null +++ b/docs/persistence-changes/2026-11-03-working-directory-anchor.zh.md @@ -0,0 +1,48 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-11-03-working-directory-anchor + +[English](2026-11-03-working-directory-anchor.md) | 中文 + +## 概述 + +为 working-directory/change 增加可选的 anchor,使一次变更即可把进入的检出目录登记为 Session 的工作区锚。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-03-working-directory-anchor +baseline: false +changes: + - root: "event:working-directory/change" + previous: "2026-09-13-working-directory" + after: "376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88" + decision: same-version +``` + + +## 兼容性 + +没有 anchor 的已有事件折叠结果不变:当前目录投影忽略该属性,新的 workspaceRoot 投影把缺失的 anchor 读作仅移动当前目录、不新增锚,因此已存储日志仍只有原始项目一个锚。旧读者保留事件类型及其 cwd,忽略该可选属性;它们从未推导工作区根,解释结果不变。 + + +## 验证 + +pnpm exec vitest run packages/session/working-directory:37 个测试通过,包括带与不带 anchor 的日志回放以及两者产生的用户上下文文本。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 3a30b6f025..9396697d7f 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -65,7 +65,7 @@ {"key":"event:turn/start","kind":"event","event":"turn/start","surface":false,"digest":"aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8"}, {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450"}, {"key":"event:web/deepseek-search-llm-request","kind":"event","event":"web/deepseek-search-llm-request","surface":false,"digest":"0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52"}, - {"key":"event:working-directory/change","kind":"event","event":"working-directory/change","surface":false,"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3"}, + {"key":"event:working-directory/change","kind":"event","event":"working-directory/change","surface":false,"digest":"376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88"}, {"key":"event:workspace/changes","kind":"event","event":"workspace/changes","surface":false,"digest":"e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72"} ], "types": [ @@ -109,7 +109,6 @@ {"digest":"11638dc58a31496fb6706ced3e23e3a2db1f3b2a8845968c810827a72b5fc811","names":[],"sources":[]}, {"digest":"119abe2b9c0b2f46ecb31d82b9acba4d4b30e049f655e2475e8b4ae12d5a9e25","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:19"]}, {"digest":"11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912","names":[],"sources":["packages/interaction/user-approval/src/index.ts:41"]}, - {"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3","names":[],"sources":[]}, {"digest":"12a0cfa619ac4a5fc6c3e8e359c8dae15769edc61497a575935c78d5842f8e42","names":[],"sources":[]}, {"digest":"12d5808fac1996b9b3c2afa806e03022252ba2d7b88f835862ae1896591f60c7","names":["packages/llm/llm/src/types.ts#ImageBlock"],"sources":["packages/llm/llm/src/types.ts:86"]}, {"digest":"1379f0b72275994d20f1ddca2d60a96ab16ec80397ca9f1af21bdc67ba5c269c","names":[],"sources":[]}, @@ -203,6 +202,7 @@ {"digest":"36d6a9a871d949ea4f3edd919d81d66aa69218bebef38899d2a1282c39420a1f","names":[],"sources":[]}, {"digest":"37184378c6439257d105c4e2022d80fc9c3a3f7c7f6ac661b00bc9f18d871006","names":[],"sources":[]}, {"digest":"374fdd68aee5ff844e378c0cbdd961d247a0f22e4ade0bb03d800cd2a46a2b8b","names":[],"sources":["packages/llm/llm-retry/src/types.ts:30"]}, + {"digest":"376ab95962d99133db02add3a1dda91a257affb2c2e71e64da139b679d82cb88","names":[],"sources":[]}, {"digest":"378f90f9f6022a0991928a1eaf7991094ea1920fe89a9248358a1da106e1a970","names":[],"sources":[]}, {"digest":"37cbc9cf06d494cfe5c67f078af1605eacb8e4c2c853e9e26455b73de0ee7ccf","names":[],"sources":[]}, {"digest":"37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:82"]}, @@ -228,6 +228,7 @@ {"digest":"3f74ba74acd10644c1ed6947a411d8088bd2cfac74f61bb8540f96d68e31f004","names":[],"sources":[]}, {"digest":"3fdf9582c3b5597df104d32d97dab6c6ee3a93794f3034ec6ada6272404ea27f","names":["packages/schedule/schedule/src/types.ts#LegacyAfterScheduleRecord"],"sources":["packages/schedule/schedule/src/types.ts:161"]}, {"digest":"408927267422a7b2beb6df354ff7c1406d929a5646554f48adf85eb8372f811c","names":[],"sources":[]}, + {"digest":"40a4c38943f2e5ee0eaa0ea48238ec425e7900022a4b08e57c8335f0fd6eb435","names":[],"sources":["packages/session/working-directory/src/index.ts:36"]}, {"digest":"4208123b50df5006b181481ab45fcf1cde807b88d3fd4d340090bc2e202fac41","names":[],"sources":[]}, {"digest":"42e0916e0dda5f6d1e7bb05d8514717147c036a79c9f36085683469516c1fd3f","names":[],"sources":[]}, {"digest":"4312134fc6f9cad507c31390bd3d147535492dd77621ec517c5e85f853d53a03","names":[],"sources":[]}, @@ -599,7 +600,6 @@ {"digest":"d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca","names":[],"sources":[]}, {"digest":"d9c462b9f62fdd3efc76a44b9524dc8781f6b91cd9c7e584b17d971defafebab","names":["packages/llm/llm/src/message.ts#ToolMessageSource"],"sources":["packages/llm/llm/src/message.ts:29"]}, {"digest":"d9edf1862e4471d6ad8a106a3f4160e0643874368707d50ecd8e27e5ee7a2567","names":[],"sources":[]}, - {"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:36"]}, {"digest":"dacf3d5f3e4ff619c1320e64a48dec5e7ecd7870bece65fbd449a0e63adfa521","names":[],"sources":[]}, {"digest":"db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c","names":[],"sources":[]}, {"digest":"db6c5246911d47a7969f6b4cb47c7d0dbbde75c402710b22ace3672fa97bebe0","names":[],"sources":[]}, @@ -742,7 +742,6 @@ "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "119abe2b9c0b2f46": {"kind":"object","properties":[{"name":"dialect","type":"a6b41f5bede8094d","optional":false},{"name":"handlerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"matcher","type":"4cd48f3e5108bd6e","optional":true},{"name":"point","type":"4cd48f3e5108bd6e","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "11f70b595aa76897": {"kind":"object","properties":[{"name":"policy","type":"05d2ae1e0c7f8770","optional":false},{"name":"source","type":"76632533f67879dc","optional":true}],"indices":[]}, - "124aa62078ca3311": {"kind":"object","properties":[{"name":"data","type":"da60ed58a8fa23d7","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d4c799e3d51cae10","optional":false}],"indices":[]}, "12a0cfa619ac4a5f": {"kind":"literal","value":"read-only"}, "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, @@ -836,6 +835,7 @@ "36d6a9a871d949ea": {"kind":"literal","value":"approval/policy"}, "37184378c6439257": {"kind":"object","properties":[{"name":"data","type":"a853902cfab417b8","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"f1996af2602e6f62","optional":false}],"indices":[]}, "374fdd68aee5ff84": {"kind":"object","properties":[{"name":"delayMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"mode","type":"142c37d302aa22a0","optional":false},{"name":"policyKey","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"retry","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "376ab95962d99133": {"kind":"object","properties":[{"name":"data","type":"40a4c38943f2e5ee","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d4c799e3d51cae10","optional":false}],"indices":[]}, "378f90f9f6022a09": {"kind":"literal","value":"approval/decided"}, "37cbc9cf06d494cf": {"kind":"object","properties":[{"name":"data","type":"b158f3ff69237148","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"70b082fe78991edf","optional":false}],"indices":[]}, "37ff65426bcf130f": {"kind":"object","properties":[{"name":"type","type":"0b9b8facbe2c1977","optional":false}],"indices":[]}, @@ -861,6 +861,7 @@ "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, "3fdf9582c3b5597d": {"kind":"object","properties":[{"name":"afterSeconds","type":"0657d3ca5ac4e7bf","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"5b232a9b9bfcc0fc","optional":false},{"name":"prompt","type":"4cd48f3e5108bd6e","optional":false},{"name":"scheduledAt","type":"4cd48f3e5108bd6e","optional":false},{"name":"title","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "40a4c38943f2e5ee": {"kind":"object","properties":[{"name":"anchor","type":"4cd48f3e5108bd6e","optional":true},{"name":"cwd","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4208123b50df5006": {"kind":"object","properties":[{"name":"data","type":"ad0c38a0adb82a94","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"3e0eff5946255ff0","optional":false}],"indices":[]}, "42e0916e0dda5f6d": {"kind":"object","properties":[{"name":"data","type":"7f9365bae9fcb73e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"fe792a6cd4304945","optional":false}],"indices":[]}, "4312134fc6f9cad5": {"kind":"literal","value":"turn/end"}, @@ -1232,7 +1233,6 @@ "d95c624eddecdacf": {"kind":"object","properties":[{"name":"data","type":"601327bedca5f98a","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, - "da60ed58a8fa23d7": {"kind":"object","properties":[{"name":"cwd","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "dacf3d5f3e4ff619": {"kind":"literal","value":true}, "db06ef35b27a3842": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "db6c5246911d47a7": {"kind":"literal","value":"webhook"}, diff --git a/docs/subsystems/working-directory.i18n.yaml b/docs/subsystems/working-directory.i18n.yaml index de4ffb228e..dd96f83e3c 100644 --- a/docs/subsystems/working-directory.i18n.yaml +++ b/docs/subsystems/working-directory.i18n.yaml @@ -6,8 +6,11 @@ en: 0882d8b4c09c2890 zh: a75af7ce19f661fa /working-directory/directory-selection: - en: b67e268cc9422d31 - zh: 4c7243c87aadcd7a + en: d0461ccad1bf9474 + zh: f503835eb2937e3e /working-directory/model-context: - en: 9789081854cbdd35 - zh: 1f6712c4e5b9c47e + en: 2c27d5dfe7abbd4c + zh: 4e6dc26dff03edad +/working-directory/relocation: + en: 2a57d0017ecf9658 + zh: 44113e49d3a079fd diff --git a/docs/subsystems/working-directory.md b/docs/subsystems/working-directory.md index 4e9ae74c57..d583fbd69e 100644 --- a/docs/subsystems/working-directory.md +++ b/docs/subsystems/working-directory.md @@ -8,11 +8,37 @@ A Session's active directory is owned by [`dsh-working-directory`](../../package `ctx.workingDirectory.get(session)` reads the logged value. `ensure(agent)` validates it and restores the original project when the directory disappeared. `set(agent, path)` validates and records a requested change. Sessions without a header directory use the configured runtime fallback; an unavailable fallback produces an error. +`rootOf(session)` reads the workspace root: the longest registered anchor that contains the current directory. The anchors are the original project and every checkout `relocate(agent, root, { cwd? })` entered; that operation validates the root and the directory inside it, then records both in one `working-directory/change` whose `anchor` names the root. `anchorsOf(session)` lists them. A `set` inside the root moves only the current directory; a `set` into another anchor selects that anchor as the root; a `set` outside every anchor leaves the root unchanged. Recovery to the original project selects it as the root again. Anchors are compared as recorded. + Changes are local to one Session. Relative filesystem operations, newly started processes, instruction discovery, skills, and file completion use the active directory. Existing terminals and persistent shells retain their own directories. Sandbox writable roots and project membership remain anchored to the original project. ## Model context -The initial value and subsequent current values reach the model as required user-context snapshots, even when optional runtime context is disabled. Each committed change attempts to queue a notice through the ordinary Agent inbox; cancellation or disposal can discard notices before request admission. The directory event survives, and the next admitted request receives the current value. Directory context never enters the system prompt. [`working_directory`](../../packages/session/tool-working-directory/README.md) exposes one optional `cd` argument. +The initial value and subsequent current values reach the model as required user-context snapshots, even when optional runtime context is disabled; a snapshot adds a `Workspace root` line while the current directory differs from the root. Each committed change attempts to queue a notice through the ordinary Agent inbox, and a change that selects another root ends its notice with that root; cancellation or disposal can discard notices before request admission. The directory event survives, and the next admitted request receives the current value. Directory context never enters the system prompt. [`working_directory`](../../packages/session/tool-working-directory/README.md) exposes one optional `cd` argument. + +## Relocation + +`relocate` takes the new root and these options, and resolves to the directories it committed. + +```ts type-equiv +/** Options of {@link WorkingDirectoryService.relocate}. */ +interface RelocateOptions { + /** Directory to enter inside the new root, absolute or relative to that root; omission enters the root itself. */ + cwd?: string + /** Cancellation before the durable change. */ + signal?: AbortSignal +} +``` + +```ts type-equiv +/** The committed outcome of {@link WorkingDirectoryService.relocate}. */ +interface RelocatedDirectories { + /** Canonical absolute workspace root, now a registered anchor of the Session. */ + root: string + /** Canonical absolute current directory inside `root`. */ + cwd: string +} +``` @@ -26,7 +52,9 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.workingDirectory` — `WorkingDirectoryService` -One owner for each Session's effective directory and its model-visible changes. +One owner for each Session's effective directory, its workspace root, and their model-visible changes. + +The current directory is the cursor every relative path resolves from. The workspace root is the checkout that cursor is in: the longest registered anchor containing it. Anchors are the original project plus every checkout a relocate entered, so an ordinary set inside the root moves only the cursor, a `set` into another anchor switches the root to that anchor, and a `set` outside every anchor moves the cursor and leaves the root. ```ts cordis-catalog /** @@ -36,6 +64,20 @@ One owner for each Session's effective directory and its model-visible changes. */ get(session: Session): string +/** + * Read the committed workspace root without filesystem I/O. + * @param session - Session whose root is requested. + * @returns the registered anchor containing the current directory, or the deployment default when none is recorded. + */ +rootOf(session: Session): string + +/** + * Read the registered workspace anchors without filesystem I/O. + * @param session - Session whose anchors are requested. + * @returns anchors in registration order, the original project first when the header records one. + */ +anchorsOf(session: Session): readonly string[] + /** * Validate the current directory and restore the original project when it disappeared. * @param agent - live or unpublished Agent owning the Session. @@ -48,6 +90,9 @@ ensure(agent: Agent, signal?: AbortSignal): Promise /** * Change one Session's directory without changing existing processes or permissions. + * The workspace root follows the registered anchors: a path inside the current + * root keeps it, a path inside another anchor selects that anchor, and a path + * outside every anchor leaves the root unchanged. * @param agent - live or unpublished Agent owning the Session. * @param path - absolute path or a path relative to its current directory. * @param signal - cancellation before the durable change. @@ -56,6 +101,19 @@ ensure(agent: Agent, signal?: AbortSignal): Promise * @throws when the requested path is not an existing directory. */ set(agent: Agent, path: string, signal?: AbortSignal): Promise + +/** + * Enter another checkout: register `root` as a workspace anchor of the Session and + * move its current directory to `options.cwd`, or to the root itself. One committed + * event carries both; existing processes and permissions are unchanged. + * @param agent - live or unpublished Agent owning the Session. + * @param root - absolute checkout directory, or a path relative to the current directory. + * @param options - directory to enter inside the root and cancellation before the durable change. + * @returns the canonical root and current directory, committed before fulfillment. + * A notice failure is warned; the next request still receives the committed directories. + * @throws when either path is not an existing directory or the directory lies outside the root. + */ +relocate(agent: Agent, root: string, options: RelocateOptions = {}): Promise ``` Types: [Agent](core.md) · [Session](session.md) diff --git a/docs/subsystems/working-directory.zh.md b/docs/subsystems/working-directory.zh.md index bb239ddc43..fc6cf9ef72 100644 --- a/docs/subsystems/working-directory.zh.md +++ b/docs/subsystems/working-directory.zh.md @@ -8,11 +8,37 @@ Session 的当前目录由 [`dsh-working-directory`](../../packages/session/work `ctx.workingDirectory.get(session)` 读取日志中的值。`ensure(agent)` 验证它,并在目录消失时恢复原始项目。`set(agent, path)` 验证并记录请求的变更。header 没有目录的 Session 使用配置的运行时回退目录;回退目录不可用时返回错误。 +`rootOf(session)` 读取工作区根:包含当前目录的最长已登记锚。锚是原始项目以及 `relocate(agent, root, { cwd? })` 进入过的每个检出目录;该操作验证根及其内部的目录,然后用一条 `anchor` 指向该根的 `working-directory/change` 同时记录两者。`anchorsOf(session)` 列出这些锚。根内部的 `set` 只移动当前目录;进入另一个锚的 `set` 把该锚选为根;所有锚之外的 `set` 不改变根。恢复到原始项目时再次把它选为根。锚按记录的原样比较。 + 变更仅影响一个 Session。相对路径文件系统操作、新启动的进程、指令发现、技能和文件补全使用当前目录。已有终端和持久 shell 保留自己的目录。沙箱可写根目录与项目归属继续绑定原始项目。 ## 模型上下文 -初始值与后续当前值通过必需的用户上下文快照到达模型,即使可选运行时上下文被禁用也不例外。每次已提交变更都会尝试通过普通 Agent 收件箱排入通知;取消或销毁可能丢弃尚未进入请求的通知。目录事件仍然保留,下一次获准进入的请求会收到当前值。目录上下文不进入系统提示词。[`working_directory`](../../packages/session/tool-working-directory/README.zh.md) 提供一个可选的 `cd` 参数。 +初始值与后续当前值通过必需的用户上下文快照到达模型,即使可选运行时上下文被禁用也不例外;当前目录与根不同时,快照增加一行 `Workspace root`。每次已提交变更都会尝试通过普通 Agent 收件箱排入通知,选中另一个根的变更在通知末尾给出该根;取消或销毁可能丢弃尚未进入请求的通知。目录事件仍然保留,下一次获准进入的请求会收到当前值。目录上下文不进入系统提示词。[`working_directory`](../../packages/session/tool-working-directory/README.zh.md) 提供一个可选的 `cd` 参数。 + +## 迁移 + +`relocate` 接收新的根与以下选项,并解析为它提交的目录。 + +```ts type-equiv +/** Options of {@link WorkingDirectoryService.relocate}. */ +interface RelocateOptions { + /** Directory to enter inside the new root, absolute or relative to that root; omission enters the root itself. */ + cwd?: string + /** Cancellation before the durable change. */ + signal?: AbortSignal +} +``` + +```ts type-equiv +/** The committed outcome of {@link WorkingDirectoryService.relocate}. */ +interface RelocatedDirectories { + /** Canonical absolute workspace root, now a registered anchor of the Session. */ + root: string + /** Canonical absolute current directory inside `root`. */ + cwd: string +} +``` @@ -26,7 +52,9 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.workingDirectory` — `WorkingDirectoryService` -One owner for each Session's effective directory and its model-visible changes. +One owner for each Session's effective directory, its workspace root, and their model-visible changes. + +The current directory is the cursor every relative path resolves from. The workspace root is the checkout that cursor is in: the longest registered anchor containing it. Anchors are the original project plus every checkout a relocate entered, so an ordinary set inside the root moves only the cursor, a `set` into another anchor switches the root to that anchor, and a `set` outside every anchor moves the cursor and leaves the root. ```ts cordis-catalog /** @@ -36,6 +64,20 @@ One owner for each Session's effective directory and its model-visible changes. */ get(session: Session): string +/** + * Read the committed workspace root without filesystem I/O. + * @param session - Session whose root is requested. + * @returns the registered anchor containing the current directory, or the deployment default when none is recorded. + */ +rootOf(session: Session): string + +/** + * Read the registered workspace anchors without filesystem I/O. + * @param session - Session whose anchors are requested. + * @returns anchors in registration order, the original project first when the header records one. + */ +anchorsOf(session: Session): readonly string[] + /** * Validate the current directory and restore the original project when it disappeared. * @param agent - live or unpublished Agent owning the Session. @@ -48,6 +90,9 @@ ensure(agent: Agent, signal?: AbortSignal): Promise /** * Change one Session's directory without changing existing processes or permissions. + * The workspace root follows the registered anchors: a path inside the current + * root keeps it, a path inside another anchor selects that anchor, and a path + * outside every anchor leaves the root unchanged. * @param agent - live or unpublished Agent owning the Session. * @param path - absolute path or a path relative to its current directory. * @param signal - cancellation before the durable change. @@ -56,6 +101,19 @@ ensure(agent: Agent, signal?: AbortSignal): Promise * @throws when the requested path is not an existing directory. */ set(agent: Agent, path: string, signal?: AbortSignal): Promise + +/** + * Enter another checkout: register `root` as a workspace anchor of the Session and + * move its current directory to `options.cwd`, or to the root itself. One committed + * event carries both; existing processes and permissions are unchanged. + * @param agent - live or unpublished Agent owning the Session. + * @param root - absolute checkout directory, or a path relative to the current directory. + * @param options - directory to enter inside the root and cancellation before the durable change. + * @returns the canonical root and current directory, committed before fulfillment. + * A notice failure is warned; the next request still receives the committed directories. + * @throws when either path is not an existing directory or the directory lies outside the root. + */ +relocate(agent: Agent, root: string, options: RelocateOptions = {}): Promise ``` Types: [Agent](core.zh.md) · [Session](session.zh.md) diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index f771dd3cf2..687cdc1af9 100644 --- a/docs/subsystems/worktrees.i18n.yaml +++ b/docs/subsystems/worktrees.i18n.yaml @@ -3,11 +3,11 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/worktrees.md /git-worktrees: - en: 21ec4a3b825d7e81 - zh: c841c5ca4b4e8959 + en: 91c24c47db0fbea3 + zh: 2b4f29400a7813b1 /git-worktrees/creation-and-retention: - en: 53f643c5d30e00b2 - zh: ba9e52efc62c7656 + en: 195894ced2e675dc + zh: 5ed3a6ff729496c2 /git-worktrees/request-and-result: en: fbab866bf824d6e0 zh: 73d2a1ee350e1434 diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index 8d4fec853a..6ca1f3d17e 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -2,13 +2,13 @@ English | [中文](worktrees.zh.md) -The experimental [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.md) service provides `ctx.worktrees`. Its [`create_worktree`](../../packages/experimental/tool-worktree/README.md) consumer creates a new Git branch and checkout, then selects it through the [working-directory service](working-directory.md). The [Git Worktrees optional bundle](../../packages/experimental/tool-worktree/README.md#use-this-package) loads both packages through the GUI plugin manager. It ships switched off; explicit compositions can also mount the two packages. +The experimental [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.md) service provides `ctx.worktrees`. Its [`create_worktree`](../../packages/experimental/tool-worktree/README.md) consumer creates a new Git branch and checkout, then relocates the Session into it through the [working-directory service](working-directory.md), which makes the checkout the Session's workspace root. The [Git Worktrees optional bundle](../../packages/experimental/tool-worktree/README.md#use-this-package) loads both packages through the GUI plugin manager. It ships switched off; explicit compositions can also mount the two packages. ## Creation and retention The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. Each name must identify a new branch and an unused checkout path. The operation neither fetches missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout. -The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory change. +The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory relocation. Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index e6a7c71ecc..81a440c011 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -2,13 +2,13 @@ [English](worktrees.md) | 中文 -实验性的 [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.zh.md) 服务提供 `ctx.worktrees`。其消费方 [`create_worktree`](../../packages/experimental/tool-worktree/README.zh.md) 创建新的 Git 分支与检出目录,再通过[工作目录服务](working-directory.zh.md)选中它。[Git 工作树可选 bundle](../../packages/experimental/tool-worktree/README.zh.md#use-this-package)通过 GUI 插件管理器一起加载这两个包。它随安装提供,但默认关闭;显式组合也可以挂载这两个包。 +实验性的 [`dsh-experimental-worktree`](../../packages/experimental/worktree/README.zh.md) 服务提供 `ctx.worktrees`。其消费方 [`create_worktree`](../../packages/experimental/tool-worktree/README.zh.md) 创建新的 Git 分支与检出目录,再通过[工作目录服务](working-directory.zh.md)把 Session 迁入其中,使该检出目录成为 Session 的工作区根。[Git 工作树可选 bundle](../../packages/experimental/tool-worktree/README.zh.md#use-this-package)通过 GUI 插件管理器一起加载这两个包。它随安装提供,但默认关闭;显式组合也可以挂载这两个包。 ## 创建与保留 调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。每个名称必须对应新分支与未使用的检出路径。操作既不获取缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。 -默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。 +默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才迁移工作目录。 通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 7fa9010b81..80d3d5f915 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -27,7 +27,8 @@ import type { Config, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, } from './types.ts' -import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' +import { within } from '@deepseek-ai/dsh-working-directory' +import { forgeWorktreeProjection, messageOf, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' export type * from './types.ts' diff --git a/packages/experimental/client-ui-forge/src/panel.ts b/packages/experimental/client-ui-forge/src/panel.ts index 0c21c934c4..ec64d82ce5 100644 --- a/packages/experimental/client-ui-forge/src/panel.ts +++ b/packages/experimental/client-ui-forge/src/panel.ts @@ -9,7 +9,6 @@ import { pluginRecordOf } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import { deadline } from '@deepseek-ai/dsh-timeout' -import type {} from '@deepseek-ai/dsh-working-directory' import { gitIn, hasBranch, inspectCheckout } from './git.ts' import type { GitConfig, Inspection } from './git.ts' import { localChanges } from './local-diff.ts' @@ -19,7 +18,8 @@ import type { ForgeCheckoutState, ForgeLocalChanges, ForgeMissingWorktree, ForgePanelChangeRequest, ForgePanelState, ForgePanelWorktree, ForgeWorktreeBlocker, ForgeWorktreeState, } from './types.ts' -import { within, WORKTREE_RECORD } from './worktree.ts' +import { within } from '@deepseek-ai/dsh-working-directory' +import { WORKTREE_RECORD } from './worktree.ts' import type { WorktreeCreations } from './worktree.ts' /** Git and diff limits plus the sign-in probe deadline. */ diff --git a/packages/experimental/client-ui-forge/src/worktree.ts b/packages/experimental/client-ui-forge/src/worktree.ts index a6b7ee2cd6..a7a4a638c5 100644 --- a/packages/experimental/client-ui-forge/src/worktree.ts +++ b/packages/experimental/client-ui-forge/src/worktree.ts @@ -1,6 +1,5 @@ /** The worktree a Session requests before it starts: its record, its projection, and its creation. */ -import { isAbsolute, relative, sep } from 'node:path' import type { Context } from '@deepseek-ai/cordis' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { generatedWorktreeName } from '@deepseek-ai/dsh-experimental-worktree' @@ -9,7 +8,7 @@ import { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import { assertNever } from '@deepseek-ai/dsh-util-values' -import type {} from '@deepseek-ai/dsh-working-directory' +import { within } from '@deepseek-ai/dsh-working-directory' import { z } from 'zod' import type { ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRestoration, ForgeWorktreeState, @@ -67,17 +66,6 @@ export const forgeWorktreeProjection = { }, } satisfies ProjectionDefinition<'forgeWorktree', ForgeWorktreeState> -/** - * Whether `path` is `root` or lies below it. - * @param root - absolute directory. - * @param path - absolute path. - * @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 text of a failure: an Error's message, or else the thrown value as a string. * @param error - what was thrown. diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index 44397cbabf..5c6bd272cd 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-worktree/use-this-package: - en: a31b883ab4fed407 - zh: b344c60b2bcb006b + en: 9c903d30822184d1 + zh: 9ed5df5b262cbbf3 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index 550aa2c5a3..df4f42c15a 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -32,7 +32,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, a - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw. +`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.relocate`, which makes the checkout the Session's workspace root. `from` resolves to a local commit before creation and defaults to `HEAD`; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw. `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` checks a removed worktree out again at its recorded directory. It validates the recorded repository root, full commit object name, branch, and canonical target inside the configured pool before mutation. It removes only the missing target's unlocked registration with `git worktree remove`; other worktrees and locked registrations remain unchanged. It then checks out the branch when it still exists, or creates the branch again at `baseCommit` when it does not, and reports which happened as `branchRecreated`. An existing directory is an error. The calling Session's working directory does not change, and changes that were never committed are not recovered. Checkout disables filters as creation does. `onPhase` receives `prepare` before validation, target-registration cleanup, and branch creation, and `checkout` before the files are written; it must not throw. diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 937b057975..ed0997cef2 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -32,7 +32,7 @@ kind: "package-reference" - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。 +`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.relocate` 进入规范化的检出目录,使该检出目录成为 Session 的工作区根。`from` 在创建前解析为本地提交,默认是 `HEAD`;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。 `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它只通过 `git worktree remove` 移除缺失目标的未锁定登记;其他 worktree 与锁定登记保持不变。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。 diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index 2529ae48e8..f947539778 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -195,7 +195,7 @@ export class WorktreeService extends Service { const overrides = await filterOverrides(run, path) onPhase?.('checkout') await run(path, ['--work-tree', path, 'reset', '--hard', '--no-recurse-submodules', baseCommit], undefined, overrides) - const canonicalPath = await this.ctx.workingDirectory.set(agent, path, signal) + const { cwd: canonicalPath } = await this.ctx.workingDirectory.relocate(agent, path, { signal }) return { path: canonicalPath, branch, baseCommit, repositoryRoot } } catch (error) { throw new Error(`Could not finish worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error }) diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index 7db4752462..09496aca9e 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -38,6 +38,8 @@ describe('creating and entering retained worktrees', () => { const result = await ctx.worktrees.create(agent, { name: 'topic' }) expect(result).toEqual({ path: join(root, '.agents/worktrees/topic'), branch: 'topic', baseCommit, repositoryRoot: root }) expect(ctx.workingDirectory.get(agent.session)).toBe(result.path) + expect(ctx.workingDirectory.rootOf(agent.session)).toBe(result.path) + expect(ctx.workingDirectory.anchorsOf(agent.session)).toEqual([root, result.path]) expect(await git(result.path, 'symbolic-ref', '--short', 'HEAD')).toBe('topic') expect(await contents(join(result.path, 'tracked.txt'))).toBe('initial\n') expect(await git(root, 'show', ':tracked.txt')).toBe('staged') @@ -47,6 +49,7 @@ describe('creating and entering retained worktrees', () => { expect(await git(root, 'check-ignore', '.agents/worktrees/.gitignore')).toBe('.agents/worktrees/.gitignore') await ctx.workingDirectory.set(agent, root) + expect(ctx.workingDirectory.rootOf(agent.session)).toBe(root) expect(await git(root, 'rev-parse', 'topic')).toBe(baseCommit) expect(await contents(join(result.path, 'tracked.txt'))).toBe('initial\n') }) @@ -286,7 +289,7 @@ describe('creating and entering retained worktrees', () => { ctx = await harness(root) const agent = testAgent(ctx, root) await ctx.workingDirectory.ensure(agent) - vi.spyOn(ctx.workingDirectory, 'set').mockRejectedValueOnce(new Error('directory publication failed')) + vi.spyOn(ctx.workingDirectory, 'relocate').mockRejectedValueOnce(new Error('directory publication failed')) await expect(ctx.worktrees.create(agent, { name: 'retained' })).rejects.toThrow('Any created checkout and branch are retained') expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await git(root, 'branch', '--list', 'retained')).toContain('retained') diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 5b81794e79..96be2a74d2 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4401,8 +4401,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { key: 'workingDirectory', - summary: 'One owner for each Session\'s effective directory and its model-visible changes.', - description: 'One owner for each Session\'s effective directory and its model-visible changes.', + summary: 'One owner for each Session\'s effective directory, its workspace root, and their model-visible changes.', + description: 'One owner for each Session\'s effective directory, its workspace root, and their model-visible changes.\n\nThe current directory is the cursor every relative path resolves from. The workspace root is the checkout that cursor is in: the longest registered anchor containing it. Anchors are the original project plus every checkout a relocate entered, so an ordinary set inside the root moves only the cursor, a `set` into another anchor switches the root to that anchor, and a `set` outside every anchor moves the cursor and leaves the root.', methods: [ { signature: 'readonly defaultDirectory: string', @@ -4415,6 +4415,18 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'session', description: 'Session whose directory is requested.' }], returns: 'its effective absolute directory.', }, + { + signature: 'rootOf(session: Session): string', + description: 'Read the committed workspace root without filesystem I/O.', + parameters: [{ name: 'session', description: 'Session whose root is requested.' }], + returns: 'the registered anchor containing the current directory, or the deployment default when none is recorded.', + }, + { + signature: 'anchorsOf(session: Session): readonly string[]', + description: 'Read the registered workspace anchors without filesystem I/O.', + parameters: [{ name: 'session', description: 'Session whose anchors are requested.' }], + returns: 'anchors in registration order, the original project first when the header records one.', + }, { signature: 'ensure(agent: Agent, signal?: AbortSignal): Promise', description: 'Validate the current directory and restore the original project when it disappeared.', @@ -4424,11 +4436,18 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'set(agent: Agent, path: string, signal?: AbortSignal): Promise', - description: 'Change one Session\'s directory without changing existing processes or permissions.', + description: 'Change one Session\'s directory without changing existing processes or permissions. The workspace root follows the registered anchors: a path inside the current root keeps it, a path inside another anchor selects that anchor, and a path outside every anchor leaves the root unchanged.', parameters: [{ name: 'agent', description: 'live or unpublished Agent owning the Session.' }, { name: 'path', description: 'absolute path or a path relative to its current directory.' }, { name: 'signal', description: 'cancellation before the durable change.' }], returns: 'the canonical absolute directory, committed before fulfillment. A notice failure is warned; the next request still receives the committed directory.', throws: ['when the requested path is not an existing directory.'], }, + { + signature: 'relocate(agent: Agent, root: string, options: RelocateOptions = {}): Promise', + description: 'Enter another checkout: register `root` as a workspace anchor of the Session and move its current directory to `options.cwd`, or to the root itself. One committed event carries both; existing processes and permissions are unchanged.', + parameters: [{ name: 'agent', description: 'live or unpublished Agent owning the Session.' }, { name: 'root', description: 'absolute checkout directory, or a path relative to the current directory.' }, { name: 'options', description: 'directory to enter inside the root and cancellation before the durable change.' }], + returns: 'the canonical root and current directory, committed before fulfillment. A notice failure is warned; the next request still receives the committed directories.', + throws: ['when either path is not an existing directory or the directory lies outside the root.'], + }, ], }, { @@ -7774,6 +7793,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'Reload', declaration: 'export interface Reload {\n filename: string;\n modules: ReloadModules;\n runtime?: Plugin.Runtime | undefined;\n}', }, + { + name: 'RelocatedDirectories', + declaration: 'export interface RelocatedDirectories {\n root: string;\n cwd: string;\n}', + }, + { + name: 'RelocateOptions', + declaration: 'export interface RelocateOptions {\n cwd?: string;\n signal?: AbortSignal;\n}', + }, { name: 'RemoteAccessAction', declaration: 'export type RemoteAccessAction = RemoteAccessEndpoint | `event:${string}`;', diff --git a/packages/sdk/client/README.i18n.yaml b/packages/sdk/client/README.i18n.yaml index 69eb4586c6..f09d71e902 100644 --- a/packages/sdk/client/README.i18n.yaml +++ b/packages/sdk/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-sdk-client/use-this-package: - en: e4a67206e52d524e - zh: db85694ac394a8ea + en: 57e8b2f9a5321c27 + zh: 0af1d3e4ed6f6fd3 /deepseek-ai-dsh-sdk-client/use-this-package/running-agent-turns-with-deepseekharness: en: 1a36c54463e17340 zh: ad67f9cbccc56def diff --git a/packages/sdk/client/README.md b/packages/sdk/client/README.md index 9638de2b3d..a9b55134da 100644 --- a/packages/sdk/client/README.md +++ b/packages/sdk/client/README.md @@ -55,7 +55,7 @@ try { `await harness.resumeSession(savedId)` restores a persisted session from the configured `dshHome` and returns a `HarnessSession` ready for `run()`. Save the original session id and reuse its home and workspace. Restoration preserves conversation history and its directory, repairs an interrupted final turn, and sends no new input. Missing, unreadable, incompatible, or occupied sessions reject without creating a replacement. `session(id)` remains a lazy handle for an in-process session; it does not request persisted restoration. Shell, browser, and other external processes are not restored by this API. -`HarnessSession.getWorkingDirectory()` reads the effective directory; `setWorkingDirectory(path)` changes it and returns the validated absolute path. Either method creates an unknown Session without starting a model turn. Relative paths use the Session's current directory. Origin metadata, permissions, and existing processes remain unchanged. `HarnessClient` exposes the same methods with a leading `sessionId` argument. +`HarnessSession.getWorkingDirectory()` reads the effective directory; `getWorkspaceRoot()` reads the workspace root that directory is in; `setWorkingDirectory(path)` changes the directory and returns the validated absolute path. Each method creates an unknown Session without starting a model turn. Relative paths use the Session's current directory. Origin metadata, permissions, and existing processes remain unchanged. `HarnessClient` exposes the same methods with a leading `sessionId` argument. ### Running agent turns with DeepSeekHarness diff --git a/packages/sdk/client/README.zh.md b/packages/sdk/client/README.zh.md index 289cf114e8..4413d0ba8b 100644 --- a/packages/sdk/client/README.zh.md +++ b/packages/sdk/client/README.zh.md @@ -55,7 +55,7 @@ try { `await harness.resumeSession(savedId)` 从配置的 `dshHome` 恢复持久化会话,并返回可调用 `run()` 的 `HarnessSession`。请保存原会话 id,并沿用其 home 和工作区。恢复会保留对话历史及其目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时,请求失败且不创建替代会话。`session(id)` 仍是当前进程内会话的惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。 -`HarnessSession.getWorkingDirectory()` 读取有效目录;`setWorkingDirectory(path)` 修改目录并返回校验后的绝对路径。两个方法都可创建未知 Session,而不启动模型轮次。相对路径以 Session 当前目录解析。起始目录元数据、权限与已有进程保持不变。`HarnessClient` 提供同名方法,并以 `sessionId` 作为首个参数。 +`HarnessSession.getWorkingDirectory()` 读取有效目录;`getWorkspaceRoot()` 读取该目录所在的工作区根;`setWorkingDirectory(path)` 修改目录并返回校验后的绝对路径。每个方法都可创建未知 Session,而不启动模型轮次。相对路径以 Session 当前目录解析。起始目录元数据、权限与已有进程保持不变。`HarnessClient` 提供同名方法,并以 `sessionId` 作为首个参数。 ### 用 DeepSeekHarness 运行 agent 轮次 diff --git a/packages/sdk/client/src/api.ts b/packages/sdk/client/src/api.ts index 34b644aadf..bb9ff80155 100644 --- a/packages/sdk/client/src/api.ts +++ b/packages/sdk/client/src/api.ts @@ -238,6 +238,15 @@ export class HarnessSession { return this.harness.client.getWorkingDirectory(this.id) } + /** + * Read the workspace root the effective directory is in, recovering a missing directory to the Session origin. + * @returns the absolute checkout directory that file views and the write boundary follow. + */ + async getWorkspaceRoot(): Promise { + await this.harness.start() + return this.harness.client.getWorkspaceRoot(this.id) + } + /** * Change the effective directory without moving existing processes or changing permissions. * @param path - absolute or Session-current-directory-relative directory. diff --git a/packages/sdk/client/src/client.ts b/packages/sdk/client/src/client.ts index 078acbbff6..5dd6f06a1c 100644 --- a/packages/sdk/client/src/client.ts +++ b/packages/sdk/client/src/client.ts @@ -374,8 +374,17 @@ export class HarnessClient { * @param sessionId - target Session; an unknown id creates it. * @returns the absolute effective directory. */ - getWorkingDirectory(sessionId: string): Promise { - return this.workingDirectoryRequest('session/working-directory/get', { sessionId }) + async getWorkingDirectory(sessionId: string): Promise { + return (await this.workingDirectoryRequest('session/working-directory/get', { sessionId })).cwd + } + + /** + * Read the workspace root a Session's effective directory is in, recovering the directory if missing. + * @param sessionId - target Session; an unknown id creates it. + * @returns the absolute workspace root. + */ + async getWorkspaceRoot(sessionId: string): Promise { + return (await this.workingDirectoryRequest('session/working-directory/get', { sessionId })).root } /** @@ -384,16 +393,16 @@ export class HarnessClient { * @param path - absolute or Session-current-directory-relative path. * @returns the validated absolute directory. */ - setWorkingDirectory(sessionId: string, path: string): Promise { - return this.workingDirectoryRequest('session/working-directory/set', { sessionId, path }) + async setWorkingDirectory(sessionId: string, path: string): Promise { + return (await this.workingDirectoryRequest('session/working-directory/set', { sessionId, path })).cwd } - private async workingDirectoryRequest(method: string, params: object): Promise { + private async workingDirectoryRequest(method: string, params: object): Promise<{ cwd: string; root: string }> { const result = await this.request(method, params) - if (!isRecord(result) || typeof result.cwd !== 'string') { + if (!isRecord(result) || typeof result.cwd !== 'string' || typeof result.root !== 'string') { throw new SdkProtocolError(`${method} returned no working directory: ${JSON.stringify(result)}`) } - return result.cwd + return { cwd: result.cwd, root: result.root } } /** diff --git a/packages/sdk/client/tests/fake-runtime.ts b/packages/sdk/client/tests/fake-runtime.ts index 8ff3cd6445..fdc3655b7b 100644 --- a/packages/sdk/client/tests/fake-runtime.ts +++ b/packages/sdk/client/tests/fake-runtime.ts @@ -314,7 +314,7 @@ reader.on('line', (line) => { ? resolve(previous, String(frame.params?.path)) : previous workingDirectories.set(sessionId, cwd) - respond({ cwd }) + respond({ cwd, root: originCwd }) return } case 'session/query': diff --git a/packages/sdk/client/tests/sdk-client.spec.ts b/packages/sdk/client/tests/sdk-client.spec.ts index 7cb2b2ea65..f9a1cc649c 100644 --- a/packages/sdk/client/tests/sdk-client.spec.ts +++ b/packages/sdk/client/tests/sdk-client.spec.ts @@ -105,12 +105,14 @@ describe('DeepSeekHarness', () => { const origin = await first.getWorkingDirectory() expect(await first.setWorkingDirectory('child')).toBe(join(origin, 'child')) expect(await first.getWorkingDirectory()).toBe(join(origin, 'child')) + expect(await first.getWorkspaceRoot()).toBe(origin) expect(await second.getWorkingDirectory()).toBe(origin) }) it('rejects a malformed working-directory response', async () => { const harness = harnessWith({ FAKE_MALFORMED_DIRECTORY: '1' }) await expect(harness.session().getWorkingDirectory()).rejects.toThrow('returned no working directory') + await expect(harness.session().getWorkspaceRoot()).rejects.toThrow('returned no working directory') await expect(harness.session().setWorkingDirectory('.')).rejects.toThrow('returned no working directory') }) it('ignores notifications that precede the submitted message receipt', async () => { diff --git a/packages/sdk/protocol/src/types.ts b/packages/sdk/protocol/src/types.ts index 6bcd2de704..3d76ea7ee8 100644 --- a/packages/sdk/protocol/src/types.ts +++ b/packages/sdk/protocol/src/types.ts @@ -143,6 +143,8 @@ export interface SessionWorkingDirectorySetParams extends SessionWorkingDirector export interface SessionWorkingDirectoryResult { /** Absolute directory used by future independent operations and new processes. */ cwd: string + /** Absolute workspace root: the checkout `cwd` is in, which file views and the write boundary follow. */ + root: string } /** Deployment-mapped SDK outcome: `ok` for an accepted result, `error` otherwise. */ diff --git a/packages/sdk/server/README.i18n.yaml b/packages/sdk/server/README.i18n.yaml index fcc20f3d98..58789ed0e0 100644 --- a/packages/sdk/server/README.i18n.yaml +++ b/packages/sdk/server/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package: - en: 1a8598a9ca7ec995 - zh: dbbd0dd3aecb7d24 + en: ab783c9bddff0173 + zh: 33af618c0f01aaa9 /deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package/wiring: en: 47a33e9397e36e15 zh: e6d173820f9ea6e5 diff --git a/packages/sdk/server/README.md b/packages/sdk/server/README.md index b2fe1e211a..9a6585e8c8 100644 --- a/packages/sdk/server/README.md +++ b/packages/sdk/server/README.md @@ -53,7 +53,7 @@ Without attachments, `/plan` and `/plan off` change only native plan state. `/pl Creation and edit accept images as reference material before the next round; show, pause, resume, and clear reject attachments without changing goal state. Compact and permission commands also reject attachments. Handler refusals never fall back to ordinary prompts; an image may already be stored before the handler refuses, as on Desktop. These SDK inputs accept raster images, not general file uploads or client-supplied attachment references. -`session/working-directory/get` accepts `{ sessionId }`; `session/working-directory/set` accepts `{ sessionId, path }`. Both return `{ cwd }` and create an unknown Session without starting a model turn. Reads recover missing directories through the working-directory service; changes preserve origin metadata and permissions, and reach the model through logged user context. +`session/working-directory/get` accepts `{ sessionId }`; `session/working-directory/set` accepts `{ sessionId, path }`. Both return `{ cwd, root }`, the effective directory and the workspace root it is in, and create an unknown Session without starting a model turn. Reads recover missing directories through the working-directory service; changes preserve origin metadata and permissions, and reach the model through logged user context. ### Wiring diff --git a/packages/sdk/server/README.zh.md b/packages/sdk/server/README.zh.md index ac9bc98399..15a80fcd3f 100644 --- a/packages/sdk/server/README.zh.md +++ b/packages/sdk/server/README.zh.md @@ -53,7 +53,7 @@ Host 与桌面适配器共用 `dsh-commands/builtin` 的定义身份及中英文 创建和编辑接受图片,作为下一轮前的参考材料;查看、暂停、恢复和清除拒绝附件,不修改目标状态。压缩和权限命令也拒绝附件。处理器拒绝后绝不回退为普通提示词;与 Desktop 相同,图片可能在处理器拒绝前已被存储。这些 SDK 输入接受栅格图片,不接受一般文件上传或客户端提供的附件引用。 -`session/working-directory/get` 接收 `{ sessionId }`;`session/working-directory/set` 接收 `{ sessionId, path }`。两者均返回 `{ cwd }`,并可创建未知 Session,而不启动模型轮次。读取通过工作目录服务恢复缺失目录;修改保留起始目录元数据与权限,并通过已记录的用户上下文告知模型。 +`session/working-directory/get` 接收 `{ sessionId }`;`session/working-directory/set` 接收 `{ sessionId, path }`。两者均返回 `{ cwd, root }`,即有效目录及其所在的工作区根,并可创建未知 Session,而不启动模型轮次。读取通过工作目录服务恢复缺失目录;修改保留起始目录元数据与权限,并通过已记录的用户上下文告知模型。 ### 组装 diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts index bccfa6634e..40638cd20e 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -412,23 +412,25 @@ export class HarnessSdkJsonRpcServer { } /** - * Read a Session's effective directory, recovering a missing directory to its origin. + * Read a Session's effective directory and workspace root, recovering a missing directory to its origin. * @param params - target Session; an unknown id creates it. - * @returns the absolute effective directory. + * @returns the absolute effective directory and the root it is in. */ async getWorkingDirectory(params: SessionWorkingDirectoryParams): Promise { const agent = await this.workingDirectoryAgent(params.sessionId) - return { cwd: await this.ctx.workingDirectory.ensure(agent) } + const cwd = await this.ctx.workingDirectory.ensure(agent) + return { cwd, root: this.ctx.workingDirectory.rootOf(agent.session) } } /** * Change a Session's directory and queue its model-visible transition. * @param params - target Session and absolute or current-directory-relative path. - * @returns the validated absolute directory; origin and permissions are unchanged. + * @returns the validated absolute directory and the root it is in; origin and permissions are unchanged. */ async setWorkingDirectory(params: SessionWorkingDirectorySetParams): Promise { const agent = await this.workingDirectoryAgent(params.sessionId) - return { cwd: await this.ctx.workingDirectory.set(agent, params.path) } + const cwd = await this.ctx.workingDirectory.set(agent, params.path) + return { cwd, root: this.ctx.workingDirectory.rootOf(agent.session) } } private async workingDirectoryAgent(sessionId: string): Promise { diff --git a/packages/sdk/server/tests/server.spec.ts b/packages/sdk/server/tests/server.spec.ts index e58168f893..033c4c8203 100644 --- a/packages/sdk/server/tests/server.spec.ts +++ b/packages/sdk/server/tests/server.spec.ts @@ -236,10 +236,10 @@ describe('HarnessSdkJsonRpcServer', () => { .rejects.toThrow('SDK server is not initialized') expect(ctx.agents.list()).toEqual([]) await server.initialize({ cwd: root, provider: 'mock', model: 'mock' }) - await expect(server.handleRequest('session/working-directory/get', { sessionId: 'a' })).resolves.toEqual({ cwd: root }) + await expect(server.handleRequest('session/working-directory/get', { sessionId: 'a' })).resolves.toEqual({ cwd: root, root }) const selected = await realpath(child) - await expect(server.handleRequest('session/working-directory/set', { sessionId: 'a', path: 'child' })).resolves.toEqual({ cwd: selected }) - await expect(server.handleRequest('session/working-directory/get', { sessionId: 'b' })).resolves.toEqual({ cwd: root }) + await expect(server.handleRequest('session/working-directory/set', { sessionId: 'a', path: 'child' })).resolves.toEqual({ cwd: selected, root }) + await expect(server.handleRequest('session/working-directory/get', { sessionId: 'b' })).resolves.toEqual({ cwd: root, root }) const agent = ctx.agents.get(SessionId('a'))! expect(agent.session.header.cwd).toBe(root) await server.prompt({ sessionId: 'a', contentBlocks: [{ type: 'text', text: 'where' }] }) diff --git a/packages/session/README.i18n.yaml b/packages/session/README.i18n.yaml index f94ee7dd79..2d1ca1a8ce 100644 --- a/packages/session/README.i18n.yaml +++ b/packages/session/README.i18n.yaml @@ -21,8 +21,8 @@ en: cbe033c3f37b8aa7 zh: 69aa84f0712d0111 /session-durable-session-data-plane/packages/projection: - en: 706441e1ab2fa853 - zh: a7fa44caab3ddada + en: 771237f055ad360c + zh: 418d3284a574cbec /session-durable-session-data-plane/packages/titles: en: 81245e5ca5f8b773 zh: 0abee7434238c342 diff --git a/packages/session/README.md b/packages/session/README.md index 2f14e2ca11..012b5248b8 100644 --- a/packages/session/README.md +++ b/packages/session/README.md @@ -45,7 +45,7 @@ The group splits into four families: durable storage (persistence seam, backends | Package | Role | ctx key | |---|---|---| | [`session-projection/`](session-projection/README.md) | Defines and drives projection units that fold committed events into whole current values | `ctx.sessionProjections` | -| [`working-directory/`](working-directory/README.md) | Owns each Session's effective execution directory and user-context changes | `ctx.workingDirectory` | +| [`working-directory/`](working-directory/README.md) | Owns each Session's effective execution directory, the workspace root it is in, and user-context changes | `ctx.workingDirectory` | | [`tool-working-directory/`](tool-working-directory/README.md) | Reads or changes the active directory through one tool | `working_directory` | | [`session-projection-cache/`](session-projection-cache/README.md) | Persists projection checkpoints so cold reads skip full log loads | `ctx.sessionProjectionCache` | | [`session-stats/`](session-stats/README.md) | Serves whole-log conversation counts and wall times through the `sessionStats` unit | registers on `ctx.sessionProjections` | diff --git a/packages/session/README.zh.md b/packages/session/README.zh.md index 5067461a15..b93c815f28 100644 --- a/packages/session/README.zh.md +++ b/packages/session/README.zh.md @@ -45,7 +45,7 @@ session 组让对话持久保存,恢复已发布的日志格式,并使已提 | 包 | 职责 | ctx key | |---|---|---| | [`session-projection/`](session-projection/README.zh.md) | 定义并驱动把已提交事件折叠为完整当前值的投影单元 | `ctx.sessionProjections` | -| [`working-directory/`](working-directory/README.zh.md) | 拥有每个 Session 的有效执行目录和用户上下文变更 | `ctx.workingDirectory` | +| [`working-directory/`](working-directory/README.zh.md) | 拥有每个 Session 的有效执行目录、它所在的工作区根和用户上下文变更 | `ctx.workingDirectory` | | [`tool-working-directory/`](tool-working-directory/README.zh.md) | 通过一个工具读取或改变当前目录 | `working_directory` | | [`session-projection-cache/`](session-projection-cache/README.zh.md) | 持久化投影检查点,使冷读跳过全量日志加载 | `ctx.sessionProjectionCache` | | [`session-stats/`](session-stats/README.zh.md) | 通过 `sessionStats` 单元提供全日志会话计数与墙钟时间 | 注册到 `ctx.sessionProjections` | diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index a593c37b80..86c5b566d1 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: 0cd615b8f987f950 zh: ccf4964df789011c /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: f0458147d29631b1 - zh: 6a288670dd084ffb + en: 2955afc111e1bc2a + zh: a10d20cc4746c31e /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 @@ -30,8 +30,8 @@ en: 6fcebaf8006123ef zh: 950162891001da33 /deepseek-ai-dsh-working-directory/model-experience/working-directory-context/what-the-model-sees: - en: 9a9f7113edc9f15f - zh: 56ac4fbd55b73ef0 + en: 6bb8af74078aa3b8 + zh: 8c4d054cc4013185 /deepseek-ai-dsh-working-directory/model-experience/working-directory-context/token-effect: en: a02a00deaddbccea zh: b3f216eb7e95f5ce @@ -39,8 +39,8 @@ en: f5a095acef81df3b zh: 758796edbc4337fc /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work: - en: a0f7bcd972f4a4fb - zh: 051ec0eb0fa92bea + en: 4575f09bddc12766 + zh: ef545626d0e141cd /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: a4b126f9a4eaca6f diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 1f54ad8c92..493353892d 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -39,7 +39,7 @@ Mount alongside `fs`, `sessionProjections`, and `systemPrompt`. `defaultDirector
Implementation internals — click to expand -The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. +The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. A second projection folds the workspace anchors and the root they select from the same event, and `relocate` validates the root and the directory inside it before committing one event that carries `anchor`. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use. @@ -63,7 +63,7 @@ No runtime invariant companion is published because the service reads its only d #### What the model sees -The current value is `Current working directory: .` Each committed change, including automatic recovery, attempts to queue a user-context notice through the ordinary Agent inbox. Cancellation or disposal may discard unadmitted notices; the durable directory remains available to the next request. Directory context stays outside the system prompt and remains enabled when optional runtime context is disabled. +The current value is `Current working directory: .`, followed by `Workspace root: .` on a second line while the two differ. Each committed change, including automatic recovery, attempts to queue a user-context notice through the ordinary Agent inbox; a change that selects another root ends its notice with ` is now the workspace root.` Cancellation or disposal may discard unadmitted notices; the durable directory remains available to the next request. Directory context stays outside the system prompt and remains enabled when optional runtime context is disabled. #### Token effect @@ -78,6 +78,7 @@ Directory transitions append context without replacing the stable system-prompt - **Missing original project** — when the current directory and the original project are both unavailable, prompt assembly rejects every model turn, including chat-only turns. The service does not choose or recreate a repository. Restore the original directory, or use SDK `setWorkingDirectory` (`set_working_directory` in Python) or `ctx.workingDirectory.set` to select an existing absolute directory before retrying. Existing shells retain their process-local directories. +- **Anchors compare as recorded** — the original project is the header's recorded path, while `set` and `relocate` record canonical paths from the filesystem provider. A header recorded through a symlink or with different casing never contains those paths, so the root stays on the original project as it does for a directory outside every anchor. ### Dev Note diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index ad92f21b59..ffba8b29c9 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -39,7 +39,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。第二个投影从同一事件折叠工作区锚及其选出的根,`relocate` 在提交一条携带 `anchor` 的事件前验证根及其内部的目录。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 @@ -63,7 +63,7 @@ Session 投影拥有当前目录,并通过 Session observation 暴露它,因 #### 模型可见内容 -当前值为 `Current working directory: .` 每次已提交变更(包括自动恢复)都会尝试通过普通 Agent 收件箱排入用户上下文通知。取消或销毁可能丢弃尚未进入请求的通知;持久化目录仍可供下一次请求使用。目录上下文不进入系统提示词,即使可选运行时上下文被禁用,也仍然保留。 +当前值为 `Current working directory: .`,当前目录与工作区根不同时,第二行为 `Workspace root: .`。每次已提交变更(包括自动恢复)都会尝试通过普通 Agent 收件箱排入用户上下文通知;选中另一个根的变更在通知末尾给出 ` is now the workspace root.`。取消或销毁可能丢弃尚未进入请求的通知;持久化目录仍可供下一次请求使用。目录上下文不进入系统提示词,即使可选运行时上下文被禁用,也仍然保留。 #### Token 影响 @@ -78,6 +78,7 @@ Session 投影拥有当前目录,并通过 Session observation 暴露它,因 - **原始项目缺失** — 当前目录与原始项目均不可用时,提示词组装会拒绝每个模型轮次,包括纯聊天轮次。服务不会另选或重建仓库。请先恢复原始目录,或通过 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)或 `ctx.workingDirectory.set` 选择现有的绝对目录,再重试。已有 shell 保留各自进程的目录。 +- **锚按记录原样比较** — 原始项目是 header 记录的路径,而 `set` 与 `relocate` 记录文件系统 provider 给出的规范路径。通过符号链接或以不同大小写记录的 header 永远不包含这些路径,因此根停留在原始项目上,与目录位于所有锚之外时相同。 ### 开发备注 diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 8664a8aca1..006521d322 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -1,9 +1,9 @@ /** - * Session working directories, durable changes, and model context. + * Session working directories, workspace roots, durable changes, and model context. * @module @deepseek-ai/dsh-working-directory */ -import { isAbsolute } from 'node:path' +import { isAbsolute, relative, sep } from 'node:path' import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' @@ -36,6 +36,11 @@ declare module '@deepseek-ai/dsh-session/types' { 'working-directory/change': { /** Absolute directory used by subsequent directory-based operations. */ cwd: string + /** + * Absolute checkout directory this change registers as a workspace anchor of the Session; it contains `cwd`. + * Present only when the change enters another checkout, such as a created worktree; an ordinary `cd` omits it. + */ + anchor?: string } } } @@ -44,6 +49,8 @@ declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionMap { /** Recorded current directory for Session observations, or null when none is recorded. */ workingDirectory: string | null + /** Workspace root: the registered anchor containing the current directory, or null when none is recorded. */ + workspaceRoot: string | null } } @@ -53,7 +60,61 @@ export interface Config { defaultDirectory?: string } -/** One owner for each Session's effective directory and its model-visible changes. */ +/** Options of {@link WorkingDirectoryService.relocate}. */ +export interface RelocateOptions { + /** Directory to enter inside the new root, absolute or relative to that root; omission enters the root itself. */ + cwd?: string + /** Cancellation before the durable change. */ + signal?: AbortSignal +} + +/** The committed outcome of {@link WorkingDirectoryService.relocate}. */ +export interface RelocatedDirectories { + /** Canonical absolute workspace root, now a registered anchor of the Session. */ + root: string + /** Canonical absolute current directory inside `root`. */ + cwd: string +} + +/** Workspace anchors and the root they select, folded from the Session log. */ +interface WorkspaceRootState { + /** The longest registered anchor containing the current directory, or null while no anchor contains it. */ + root: string | null + /** Registered anchors in registration order; the original project comes first when the header records one. */ + anchors: string[] +} + +/** + * Whether `path` is `root` or lies below it. Both paths 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 true for `root` itself and every path below it. + */ +export function within(root: string, path: string): boolean { + const rest = relative(root, path) + return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest)) +} + +/** The longest anchor containing `path`, or undefined when none does. */ +function anchorContaining(anchors: readonly string[], path: string): string | undefined { + let selected: string | undefined + for (const anchor of anchors) { + if (within(anchor, path) && (selected === undefined || anchor.length > selected.length)) selected = anchor + } + return selected +} + +/** + * One owner for each Session's effective directory, its workspace root, and their model-visible changes. + * + * The current directory is the cursor every relative path resolves from. The + * workspace root is the checkout that cursor is in: the longest registered + * anchor containing it. Anchors are the original project plus every checkout a + * {@link relocate} entered, so an ordinary {@link set} inside the root moves + * only the cursor, a `set` into another anchor switches the root to that + * anchor, and a `set` outside every anchor moves the cursor and leaves the root. + */ export class WorkingDirectoryService extends Service { static inject = ['fs', 'sessionProjections', 'systemPrompt'] @@ -68,6 +129,7 @@ export class WorkingDirectoryService extends Service { private readonly lifecycle = new AbortController() private workingDirectoryProjectionHandle!: ProjectionHandle + private workspaceRootProjectionHandle!: ProjectionHandle constructor(ctx: Context, config: Config) { super(ctx, 'workingDirectory') @@ -79,6 +141,7 @@ export class WorkingDirectoryService extends Service { protected async [Service.init](): Promise { const ctx = this.ctx const directorySchema = zod.string().min(1).refine(isAbsolute).nullable() + const anchorSchema = zod.string().min(1).refine(isAbsolute) this.workingDirectoryProjectionHandle = await ctx.sessionProjections.register({ key: 'workingDirectory', stateVersion: 1, @@ -87,6 +150,20 @@ export class WorkingDirectoryService extends Service { apply: (state, event) => event.type === 'working-directory/change' ? event.data.cwd : state, wire: { viewSchema: directorySchema, view: state => state }, }) + this.workspaceRootProjectionHandle = await ctx.sessionProjections.register({ + key: 'workspaceRoot', + stateVersion: 1, + stateSchema: zod.object({ root: directorySchema, anchors: zod.array(anchorSchema) }), + init: header => header.cwd === undefined ? { root: null, anchors: [] } : { root: header.cwd, anchors: [header.cwd] }, + apply: (state, event) => { + if (event.type !== 'working-directory/change') return state + const { cwd, anchor } = event.data + const anchors = anchor === undefined || state.anchors.includes(anchor) ? state.anchors : [...state.anchors, anchor] + const root = anchorContaining(anchors, cwd) ?? state.root + return root === state.root && anchors === state.anchors ? state : { root, anchors } + }, + wire: { viewSchema: directorySchema, view: state => state.root }, + }) ctx.systemPrompt.context({ name: 'working-directory:current', order: ctx.systemPrompt.getContextOrder('WORKING_DIRECTORY'), @@ -123,6 +200,24 @@ export class WorkingDirectoryService extends Service { return this.workingDirectoryProjectionHandle.stateOf(session) ?? this.defaultDirectory } + /** + * Read the committed workspace root without filesystem I/O. + * @param session - Session whose root is requested. + * @returns the registered anchor containing the current directory, or the deployment default when none is recorded. + */ + rootOf(session: Session): string { + return this.workspaceRootProjectionHandle.stateOf(session).root ?? this.defaultDirectory + } + + /** + * Read the registered workspace anchors without filesystem I/O. + * @param session - Session whose anchors are requested. + * @returns anchors in registration order, the original project first when the header records one. + */ + anchorsOf(session: Session): readonly string[] { + return this.workspaceRootProjectionHandle.stateOf(session).anchors + } + /** * Validate the current directory and restore the original project when it disappeared. * @param agent - live or unpublished Agent owning the Session. @@ -153,6 +248,9 @@ export class WorkingDirectoryService extends Service { /** * Change one Session's directory without changing existing processes or permissions. + * The workspace root follows the registered anchors: a path inside the current + * root keeps it, a path inside another anchor selects that anchor, and a path + * outside every anchor leaves the root unchanged. * @param agent - live or unpublished Agent owning the Session. * @param path - absolute path or a path relative to its current directory. * @param signal - cancellation before the durable change. @@ -169,8 +267,36 @@ export class WorkingDirectoryService extends Service { }) } + /** + * Enter another checkout: register `root` as a workspace anchor of the Session and + * move its current directory to `options.cwd`, or to the root itself. One committed + * event carries both; existing processes and permissions are unchanged. + * @param agent - live or unpublished Agent owning the Session. + * @param root - absolute checkout directory, or a path relative to the current directory. + * @param options - directory to enter inside the root and cancellation before the durable change. + * @returns the canonical root and current directory, committed before fulfillment. + * A notice failure is warned; the next request still receives the committed directories. + * @throws when either path is not an existing directory or the directory lies outside the root. + */ + relocate(agent: Agent, root: string, options: RelocateOptions = {}): Promise { + return this.serialize(agent, options.signal, async (control) => { + if (root.length === 0) throw new Error('working-directory: root must not be empty') + if (options.cwd !== undefined && options.cwd.length === 0) throw new Error('working-directory: cwd must not be empty') + const anchor = await this.directory(root, this.get(agent.session), control) + const cwd = options.cwd === undefined ? anchor : await this.directory(options.cwd, anchor, control) + if (!within(anchor, cwd)) { + throw new Error(`working-directory: ${JSON.stringify(cwd)} lies outside the workspace root ${JSON.stringify(anchor)}`) + } + this.commit(agent, cwd, false, control, anchor) + return { root: anchor, cwd } + }) + } + private contextText(session: Session): string { - return `Current working directory: ${JSON.stringify(this.get(session))}.` + const cwd = this.get(session) + const root = this.rootOf(session) + const current = `Current working directory: ${JSON.stringify(cwd)}.` + return root === cwd ? current : `${current}\nWorkspace root: ${JSON.stringify(root)}.` } private async directory(path: string, cwd: string, signal: AbortSignal): Promise { @@ -183,19 +309,25 @@ export class WorkingDirectoryService extends Service { return this.ctx.fs.processPath(target) } - private commit(agent: Agent, directory: string, recovered: boolean, signal: AbortSignal): void { + private commit(agent: Agent, directory: string, recovered: boolean, signal: AbortSignal, anchor?: string): void { signal.throwIfAborted() agent.ctx.fiber.assertActive() - const previous = this.get(agent.session) - if (previous === directory) return - agent.session.append('working-directory/change', { cwd: directory }) + const session = agent.session + const previous = this.get(session) + const previousRoot = this.rootOf(session) + if (previous === directory && (anchor === undefined || this.anchorsOf(session).includes(anchor))) return + session.append('working-directory/change', { cwd: directory, ...anchor === undefined ? {} : { anchor } }) + const root = this.rootOf(session) + const rootChange = root === previousRoot ? '' : `${JSON.stringify(root)} is now the workspace root.` + const directoryChange = previous === directory + ? '' + : recovered + ? `The working directory ${JSON.stringify(previous)} is unavailable. The working directory is now ${JSON.stringify(directory)}.` + : `The working directory changed from ${JSON.stringify(previous)} to ${JSON.stringify(directory)}.` + const text = [directoryChange, rootChange].filter(part => part !== '').join(' ') + if (text === '') return const notice = createUserMessage({ - content: [{ - type: 'text', - text: recovered - ? `The working directory ${JSON.stringify(previous)} is unavailable. The working directory is now ${JSON.stringify(directory)}.` - : `The working directory changed from ${JSON.stringify(previous)} to ${JSON.stringify(directory)}.`, - }], + content: [{ type: 'text', text }], source: { kind: 'working-directory' }, }) try { diff --git a/packages/session/working-directory/tests/workspace-root.spec.ts b/packages/session/working-directory/tests/workspace-root.spec.ts new file mode 100644 index 0000000000..2e436b45ec --- /dev/null +++ b/packages/session/working-directory/tests/workspace-root.spec.ts @@ -0,0 +1,200 @@ +/** Workspace roots: anchors registered by relocation, the root the cursor selects, and the context both reach the model through. */ +import { mkdtemp, mkdir, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it } from 'vitest' +import LocalFileSystem from '@deepseek-ai/dsh-fs-local' +import WorkingDirectory, { within } from '@deepseek-ai/dsh-working-directory' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' +import { SessionId } from '@deepseek-ai/dsh-session' +import { renderContextSnapshot } from '@deepseek-ai/dsh-system-prompt' + +async function fixture() { + const scratch = await realpath(await mkdtemp(join(tmpdir(), 'dsh-workspace-root-'))) + const root = join(scratch, 'repo') + const worktree = join(scratch, 'elsewhere', 'wt') + const outside = join(scratch, 'outside') + await mkdir(join(root, 'packages', 'foo'), { recursive: true }) + await mkdir(join(root, '.agents', 'worktrees', 'nested', 'src'), { recursive: true }) + await mkdir(join(worktree, 'src'), { recursive: true }) + await mkdir(outside) + const ctx = new Context() + try { + await mountAgentLoopTestDependencies(ctx, { systemPrompt: { includeRuntimeContext: false } }) + await ctx.plugin(LocalFileSystem, { cwd: root }) + await ctx.plugin(WorkingDirectory, {}) + const harness = await mountAgentLoopTestHarness(ctx) + const agent = await harness.create(SessionId('root-owner'), {}, { cwd: root }) + return { + ctx, root, worktree, outside, nested: join(root, '.agents', 'worktrees', 'nested'), agent, harness, + notices: () => harness.claim(agent, 'next-step', 1).map(message => message.content.map(block => block.type === 'text' ? block.text : '').join('')), + context: async () => renderContextSnapshot(await ctx.systemPrompt.assemble({ agent, scope: agent })), + async [Symbol.asyncDispose]() { + await ctx.fiber.dispose() + await rm(scratch, { recursive: true, force: true }) + }, + } + } catch (error) { + await ctx.fiber.dispose() + await rm(scratch, { recursive: true, force: true }) + throw error + } +} + +describe('Session workspace roots', () => { + it('starts with the original project as the only anchor and root', async () => { + await using f = await fixture() + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + expect(f.ctx.workingDirectory.anchorsOf(f.agent.session)).toEqual([f.root]) + expect(f.ctx.sessionProjections.snapshot(f.agent.session).values.workspaceRoot).toBe(f.root) + expect(await f.context()).toContain(`Current working directory: ${JSON.stringify(f.root)}.`) + expect(await f.context()).not.toContain('Workspace root:') + }) + + it('moves only the cursor inside the root and reports both to the model', async () => { + await using f = await fixture() + const foo = join(f.root, 'packages', 'foo') + await f.ctx.workingDirectory.set(f.agent, 'packages/foo') + expect(f.ctx.workingDirectory.get(f.agent.session)).toBe(foo) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + expect(f.notices()).toEqual([`The working directory changed from ${JSON.stringify(f.root)} to ${JSON.stringify(foo)}.`]) + expect(await f.context()).toContain(`Current working directory: ${JSON.stringify(foo)}.\nWorkspace root: ${JSON.stringify(f.root)}.`) + expect(f.agent.session.snapshotEvents().filter(event => event.type === 'working-directory/change')) + .toEqual([expect.objectContaining({ data: { cwd: foo } })]) + }) + + it('leaves the root behind when the cursor goes outside every anchor', async () => { + await using f = await fixture() + await f.ctx.workingDirectory.set(f.agent, f.outside) + expect(f.ctx.workingDirectory.get(f.agent.session)).toBe(f.outside) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + expect(f.notices()).toEqual([`The working directory changed from ${JSON.stringify(f.root)} to ${JSON.stringify(f.outside)}.`]) + expect(await f.context()).toContain(`Workspace root: ${JSON.stringify(f.root)}.`) + }) + + it('relocates into another checkout with one event, then returns to the original project through an ordinary change', async () => { + await using f = await fixture() + await expect(f.ctx.workingDirectory.relocate(f.agent, f.worktree)).resolves.toEqual({ root: f.worktree, cwd: f.worktree }) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.worktree) + expect(f.ctx.workingDirectory.anchorsOf(f.agent.session)).toEqual([f.root, f.worktree]) + expect(f.ctx.sessionProjections.snapshot(f.agent.session).values.workspaceRoot).toBe(f.worktree) + expect(f.notices()).toEqual([ + `The working directory changed from ${JSON.stringify(f.root)} to ${JSON.stringify(f.worktree)}. ${JSON.stringify(f.worktree)} is now the workspace root.`, + ]) + expect(f.agent.session.snapshotEvents().filter(event => event.type === 'working-directory/change')) + .toEqual([expect.objectContaining({ data: { cwd: f.worktree, anchor: f.worktree } })]) + expect(await f.context()).not.toContain('Workspace root:') + + await f.ctx.workingDirectory.set(f.agent, 'src') + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.worktree) + expect(f.notices()).toEqual([`The working directory changed from ${JSON.stringify(f.worktree)} to ${JSON.stringify(join(f.worktree, 'src'))}.`]) + + await f.ctx.workingDirectory.set(f.agent, f.root) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + expect(f.ctx.workingDirectory.anchorsOf(f.agent.session)).toEqual([f.root, f.worktree]) + expect(f.notices()).toEqual([ + `The working directory changed from ${JSON.stringify(join(f.worktree, 'src'))} to ${JSON.stringify(f.root)}. ${JSON.stringify(f.root)} is now the workspace root.`, + ]) + }) + + it('selects the longest anchor when checkouts nest and enters a directory inside the new root', async () => { + await using f = await fixture() + const src = join(f.nested, 'src') + await expect(f.ctx.workingDirectory.relocate(f.agent, '.agents/worktrees/nested', { cwd: 'src' })).resolves.toEqual({ root: f.nested, cwd: src }) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.nested) + expect(f.notices()).toEqual([ + `The working directory changed from ${JSON.stringify(f.root)} to ${JSON.stringify(src)}. ${JSON.stringify(f.nested)} is now the workspace root.`, + ]) + expect(await f.context()).toContain(`Current working directory: ${JSON.stringify(src)}.\nWorkspace root: ${JSON.stringify(f.nested)}.`) + await f.ctx.workingDirectory.set(f.agent, join(f.root, 'packages')) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + }) + + it('registers an anchor without moving the cursor and ignores a repeated anchor', async () => { + await using f = await fixture() + const src = join(f.nested, 'src') + await f.ctx.workingDirectory.set(f.agent, src) + f.notices() + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + await expect(f.ctx.workingDirectory.relocate(f.agent, f.nested, { cwd: src })).resolves.toEqual({ root: f.nested, cwd: src }) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.nested) + expect(f.notices()).toEqual([`${JSON.stringify(f.nested)} is now the workspace root.`]) + await expect(f.ctx.workingDirectory.relocate(f.agent, f.nested, { cwd: src })).resolves.toEqual({ root: f.nested, cwd: src }) + expect(f.notices()).toEqual([]) + expect(f.agent.session.snapshotEvents().filter(event => event.type === 'working-directory/change')).toHaveLength(2) + }) + + it('records an enclosing anchor that changes neither the cursor nor the root without a notice', async () => { + await using f = await fixture() + const packages = join(f.root, 'packages') + const agent = await f.harness.create(SessionId('enclosed-origin'), {}, { cwd: packages }) + await expect(f.ctx.workingDirectory.relocate(agent, f.root, { cwd: packages })).resolves.toEqual({ root: f.root, cwd: packages }) + expect(f.ctx.workingDirectory.rootOf(agent.session)).toBe(packages) + expect(f.ctx.workingDirectory.anchorsOf(agent.session)).toEqual([packages, f.root]) + expect(f.harness.claim(agent, 'next-step', 1)).toEqual([]) + expect(agent.session.snapshotEvents().filter(event => event.type === 'working-directory/change')) + .toEqual([expect.objectContaining({ data: { cwd: packages, anchor: f.root } })]) + await f.ctx.workingDirectory.set(agent, f.root) + expect(f.ctx.workingDirectory.rootOf(agent.session)).toBe(f.root) + }) + + it('rejects a relocation whose directory lies outside the root, a missing root, and empty paths without committing', async () => { + await using f = await fixture() + await expect(f.ctx.workingDirectory.relocate(f.agent, f.worktree, { cwd: f.outside })).rejects.toThrow('lies outside the workspace root') + await expect(f.ctx.workingDirectory.relocate(f.agent, join(f.root, 'missing'))).rejects.toThrow('directory does not exist') + await expect(f.ctx.workingDirectory.relocate(f.agent, '')).rejects.toThrow('root must not be empty') + await expect(f.ctx.workingDirectory.relocate(f.agent, f.worktree, { cwd: '' })).rejects.toThrow('cwd must not be empty') + const controller = new AbortController() + controller.abort(new Error('cancelled relocation')) + await expect(f.ctx.workingDirectory.relocate(f.agent, f.worktree, { signal: controller.signal })).rejects.toThrow('cancelled relocation') + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + expect(f.ctx.workingDirectory.anchorsOf(f.agent.session)).toEqual([f.root]) + expect(f.agent.session.snapshotEvents().filter(event => event.type === 'working-directory/change')).toEqual([]) + }) + + it('returns root and cursor to the original project when the entered checkout disappears', async () => { + await using f = await fixture() + await f.ctx.workingDirectory.relocate(f.agent, f.worktree, { cwd: 'src' }) + f.notices() + await rm(f.worktree, { recursive: true }) + await expect(f.ctx.workingDirectory.ensure(f.agent)).resolves.toBe(f.root) + expect(f.ctx.workingDirectory.rootOf(f.agent.session)).toBe(f.root) + expect(f.notices()).toEqual([ + `The working directory ${JSON.stringify(join(f.worktree, 'src'))} is unavailable. The working directory is now ${JSON.stringify(f.root)}. ${JSON.stringify(f.root)} is now the workspace root.`, + ]) + }) + + it('restores anchors and root from the log and from a log without anchors', async () => { + await using f = await fixture() + await f.ctx.workingDirectory.relocate(f.agent, f.worktree, { cwd: 'src' }) + const restored = f.ctx.sessions.create(SessionId('restored'), { meta: { cwd: f.root }, seed: f.agent.session.snapshotEvents() }) + expect(f.ctx.workingDirectory.rootOf(restored)).toBe(f.worktree) + expect(f.ctx.workingDirectory.anchorsOf(restored)).toEqual([f.root, f.worktree]) + expect(f.ctx.sessionProjections.snapshot(restored).values.workspaceRoot).toBe(f.worktree) + const legacy = f.ctx.sessions.create(SessionId('legacy'), { meta: { cwd: f.root } }) + legacy.append('working-directory/change', { cwd: join(f.worktree, 'src') }) + expect(f.ctx.workingDirectory.get(legacy)).toBe(join(f.worktree, 'src')) + expect(f.ctx.workingDirectory.rootOf(legacy)).toBe(f.root) + expect(f.ctx.workingDirectory.anchorsOf(legacy)).toEqual([f.root]) + }) + + it('falls back to the deployment default for a Session without origin metadata until it relocates', async () => { + await using f = await fixture() + const agent = await f.harness.create(SessionId('without-origin')) + expect(f.ctx.workingDirectory.rootOf(agent.session)).toBe(f.ctx.workingDirectory.defaultDirectory) + expect(f.ctx.workingDirectory.anchorsOf(agent.session)).toEqual([]) + expect(f.ctx.sessionProjections.snapshot(agent.session).values.workspaceRoot).toBeNull() + await f.ctx.workingDirectory.relocate(agent, f.worktree) + expect(f.ctx.workingDirectory.rootOf(agent.session)).toBe(f.worktree) + expect(f.ctx.workingDirectory.anchorsOf(agent.session)).toEqual([f.worktree]) + }) + + it('tests containment lexically on canonical absolute paths', () => { + expect(within('/repo', '/repo')).toBe(true) + expect(within('/repo', '/repo/src')).toBe(true) + expect(within('/repo', '/repo-sibling')).toBe(false) + expect(within('/repo', '/')).toBe(false) + expect(within('/repo/src', '/repo')).toBe(false) + }) +}) diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 106360686c..72b0cd706e 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-subagent/use-this-package: - en: 924b8c15f9529028 - zh: 9fb0c399b5a79e3e + en: c5438ea39eeea4e7 + zh: 44512a484f795f10 /deepseek-ai-dsh-subagent/use-this-package/enabling-delegation: en: 025605eddae02478 zh: 5659cba4340735d8 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index 4803cff356..5732e06d0e 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -25,7 +25,7 @@ Use `dsh-subagent` to delegate work through named providers and collect managed ## Use this package -Each start accepts an optional `cwd`; relative paths resolve against the parent's current working directory, and omission captures that current directory. The child keeps its parent's origin metadata and permission roots. A child-owned directory value follows any inherited history, survives continuation and restart, and is independent of later parent changes. +Each start accepts an optional `cwd`; relative paths resolve against the parent's current working directory, and omission captures that current directory. The child keeps its parent's origin metadata and permission roots. When the parent works in a checkout other than its original project, a child that starts inside that checkout inherits it as its workspace root. A child-owned directory value follows any inherited history, survives continuation and restart, and is independent of later parent changes. This package is the contract every delegation setup shares. You enable it by mounting the service together with one or more provider backends and the model-facing delegation tool; from then on, an agent can delegate work and the service routes each request to the named provider. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index c73f19f5ba..4cc5d833c0 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -每次启动可传入可选的 `cwd`;相对路径以父级当前工作目录解析,省略时捕获该当前目录。子级保留父级的起始目录元数据与权限根目录。子级自己的目录值位于继承历史之后,在继续与重启后保留,并独立于父级之后的目录变化。 +每次启动可传入可选的 `cwd`;相对路径以父级当前工作目录解析,省略时捕获该当前目录。子级保留父级的起始目录元数据与权限根目录。父级在原始项目之外的检出目录中工作时,在该检出目录内启动的子级继承它作为工作区根。子级自己的目录值位于继承历史之后,在继续与重启后保留,并独立于父级之后的目录变化。 本包是每个委派组合都共享的约定。你通过把服务与一个或多个提供方后端以及面向模型的委派工具一起挂载来启用它;此后 agent 即可委派工作,服务会把每个请求路由到具名提供方。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index dbd9d3a382..19f27b5569 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -8,7 +8,7 @@ import { randomUUID } from 'node:crypto' import { isAbsolute, resolve } from 'node:path' -import type {} from '@deepseek-ai/dsh-working-directory' +import { within } from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import { brandString } from '@deepseek-ai/dsh-brand' @@ -747,7 +747,14 @@ export class SubagentManager { appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies) const workingDirectory = childCtx.get('workingDirectory') if (workingDirectory === undefined) throw new Error('local subagents require the working-directory service') - await workingDirectory.set(child, create.cwd, inputs.signal) + // The child header records the parent's original project; a parent working in another + // checkout passes that checkout on as the child's root when the child starts inside it. + const parentRoot = workingDirectory.rootOf(create.parent.session) + if (parentRoot !== child.session.header.cwd && within(parentRoot, create.cwd)) { + await workingDirectory.relocate(child, parentRoot, { cwd: create.cwd, signal: inputs.signal }) + } else { + await workingDirectory.set(child, create.cwd, inputs.signal) + } } if (inputs.composition.agentPreset === undefined) await applyChildComposition(childCtx, create?.parent, inputs.composition) if (inputs.outputSchema !== undefined) { diff --git a/packages/subagent/subagent/tests/working-directory-fixture.ts b/packages/subagent/subagent/tests/working-directory-fixture.ts index ca60970f36..91536aed44 100644 --- a/packages/subagent/subagent/tests/working-directory-fixture.ts +++ b/packages/subagent/subagent/tests/working-directory-fixture.ts @@ -2,10 +2,13 @@ import { Context, Service } from '@deepseek-ai/cordis' import { resolve } from 'node:path' import type { Agent } from '@deepseek-ai/dsh-agent' import type { Session } from '@deepseek-ai/dsh-session' +import { within } from '@deepseek-ai/dsh-working-directory' +import type { RelocateOptions, RelocatedDirectories } from '@deepseek-ai/dsh-working-directory' /** Directory selection for orchestration fixtures whose paths are symbolic and whose logs exclude context providers. */ class FixtureWorkingDirectory extends Service { private readonly directories = new WeakMap() + private readonly anchors = new WeakMap() constructor(ctx: Context) { super(ctx, 'workingDirectory') @@ -15,6 +18,16 @@ class FixtureWorkingDirectory extends Service { return this.directories.get(session) ?? session?.header.cwd ?? process.cwd() } + rootOf(session: Session): string { + const cwd = this.get(session) + return this.anchorsOf(session).filter(anchor => within(anchor, cwd)).sort((a, b) => b.length - a.length)[0] + ?? session?.header.cwd ?? process.cwd() + } + + anchorsOf(session: Session): readonly string[] { + return this.anchors.get(session) ?? [session?.header.cwd ?? process.cwd()] + } + async ensure(agent: Agent, signal?: AbortSignal): Promise { signal?.throwIfAborted() return this.get(agent.session) @@ -26,6 +39,17 @@ class FixtureWorkingDirectory extends Service { this.directories.set(agent.session, cwd) return cwd } + + async relocate(agent: Agent, root: string, options: RelocateOptions = {}): Promise { + options.signal?.throwIfAborted() + const anchor = resolve(this.get(agent.session), root) + const cwd = options.cwd === undefined ? anchor : resolve(anchor, options.cwd) + const anchors = [...this.anchorsOf(agent.session)] + if (!anchors.includes(anchor)) anchors.push(anchor) + this.anchors.set(agent.session, anchors) + this.directories.set(agent.session, cwd) + return { root: anchor, cwd } + } } /** Mount the directory collaborator without filesystem or model-context behavior unrelated to an orchestration test. */ diff --git a/packages/subagent/subagent/tests/working-directory.spec.ts b/packages/subagent/subagent/tests/working-directory.spec.ts index f3cb6aa47d..a87efb8dfc 100644 --- a/packages/subagent/subagent/tests/working-directory.spec.ts +++ b/packages/subagent/subagent/tests/working-directory.spec.ts @@ -60,11 +60,29 @@ describe('subagent working directories', () => { const child = run.localAgent expect(child.session.header.cwd).toBe(origin) expect(ctx.workingDirectory.get(child.session)).toBe(selected) + expect(ctx.workingDirectory.rootOf(child.session)).toBe(origin) await ctx.workingDirectory.set(parent, first) expect(ctx.workingDirectory.get(child.session)).toBe(selected) await run.dispose() }) + it.each(['spawn', 'fork'])('%s inherits the parent workspace root when the parent works in another checkout', async (provider) => { + const { ctx, parent, origin, second } = await fixture() + const inside = join(second, 'inside') + await mkdir(inside) + await ctx.workingDirectory.relocate(parent, second, { cwd: inside }) + const run = await startTestActivation(ctx, provider, { + parent, prompt: [{ type: 'text', text: 'child' }], signal: new AbortController().signal, + }) + await run.result + const child = run.localAgent + expect(child.session.header.cwd).toBe(origin) + expect(ctx.workingDirectory.get(child.session)).toBe(await realpath(inside)) + expect(ctx.workingDirectory.rootOf(child.session)).toBe(await realpath(second)) + expect(ctx.workingDirectory.anchorsOf(child.session)).toEqual([origin, await realpath(second)]) + await run.dispose() + }) + it.each(['relative', 'absolute'])('retains an explicit %s directory when a continuable child cold-resumes', async (form) => { const { ctx, parent, origin, first, second } = await fixture() const selected = await realpath(second) diff --git a/python/sdk/README.i18n.yaml b/python/sdk/README.i18n.yaml index d9c0c19992..cdbaf74304 100644 --- a/python/sdk/README.i18n.yaml +++ b/python/sdk/README.i18n.yaml @@ -24,5 +24,5 @@ en: 979ad00fe498b2be zh: 4b656bd268292a13 /deepseek-harness-python-sdk/results-and-notifications: - en: 6b81899ea865ffd2 - zh: d9e326a3fb04e696 + en: 5ffe82e8d28abdbf + zh: 94de9eeee9acb32f diff --git a/python/sdk/README.md b/python/sdk/README.md index 80ee3952f4..af7f726fc3 100644 --- a/python/sdk/README.md +++ b/python/sdk/README.md @@ -149,4 +149,4 @@ The selected home stores profiles, plugins, and every profile-owned durable reso See the [Python tutorial](../../docs/user/guide/python-sdk.md), [runnable example](examples/README.md), and [runtime wheel reference](../sdk-runtime/README.md). -`Session.get_working_directory()` reads the effective working directory; `set_working_directory(path)` changes it and returns the validated absolute path. Both create an unknown Session without running a model turn. Relative paths use that Session's current directory. Origin metadata, permissions, and existing processes remain unchanged. The low-level client provides the same methods with a leading `session_id` argument. +`Session.get_working_directory()` reads the effective working directory; `get_workspace_root()` reads the workspace root that directory is in; `set_working_directory(path)` changes the directory and returns the validated absolute path. Each creates an unknown Session without running a model turn. Relative paths use that Session's current directory. Origin metadata, permissions, and existing processes remain unchanged. The low-level client provides the same methods with a leading `session_id` argument. diff --git a/python/sdk/README.zh.md b/python/sdk/README.zh.md index 9c5c6e0621..4582927e10 100644 --- a/python/sdk/README.zh.md +++ b/python/sdk/README.zh.md @@ -149,4 +149,4 @@ with DeepSeekHarness( 另见 [Python 教程](../../docs/user/guide/python-sdk.zh.md)、[可运行示例](examples/README.zh.md) 和 [运行时 wheel 包参考](../sdk-runtime/README.zh.md)。 -`Session.get_working_directory()` 读取有效工作目录;`set_working_directory(path)` 修改目录并返回校验后的绝对路径。两者都可创建未知 Session,而不运行模型轮次。相对路径以该 Session 当前目录解析。起始目录元数据、权限与已有进程保持不变。底层客户端提供同名方法,并以 `session_id` 作为首个参数。 +`Session.get_working_directory()` 读取有效工作目录;`get_workspace_root()` 读取该目录所在的工作区根;`set_working_directory(path)` 修改目录并返回校验后的绝对路径。每个方法都可创建未知 Session,而不运行模型轮次。相对路径以该 Session 当前目录解析。起始目录元数据、权限与已有进程保持不变。底层客户端提供同名方法,并以 `session_id` 作为首个参数。 diff --git a/python/sdk/src/deepseek_harness/api.py b/python/sdk/src/deepseek_harness/api.py index fdf46e1bfa..659fdb8937 100644 --- a/python/sdk/src/deepseek_harness/api.py +++ b/python/sdk/src/deepseek_harness/api.py @@ -206,6 +206,11 @@ class Session: self.harness.start() return self.harness.client.get_working_directory(self.id) + def get_workspace_root(self) -> str: + """Read the workspace root the effective directory is in, recovering a missing directory first.""" + self.harness.start() + return self.harness.client.get_workspace_root(self.id) + def set_working_directory(self, path: str) -> str: """Change the effective directory while existing processes retain their own directories.""" self.harness.start() diff --git a/python/sdk/src/deepseek_harness/client.py b/python/sdk/src/deepseek_harness/client.py index 2717eb85c8..eaf7825a12 100644 --- a/python/sdk/src/deepseek_harness/client.py +++ b/python/sdk/src/deepseek_harness/client.py @@ -249,6 +249,15 @@ class HarnessClient: ) return response.cwd + def get_workspace_root(self, session_id: str) -> str: + """Read the workspace root the effective directory is in, recovering a missing directory first.""" + response = self.request( + "session/working-directory/get", + {"sessionId": session_id}, + response_model=_WorkingDirectoryResponse, + ) + return response.root + def set_working_directory(self, session_id: str, path: str) -> str: """Enter an absolute or Session-relative directory without changing origin or permissions.""" response = self.request( @@ -717,6 +726,7 @@ class _SessionPromptResponse(BaseModel): class _WorkingDirectoryResponse(BaseModel): cwd: str + root: str class _EmptyResponse(BaseModel): diff --git a/python/sdk/tests/test_working_directory.py b/python/sdk/tests/test_working_directory.py index 3d46793af2..a7901bc271 100644 --- a/python/sdk/tests/test_working_directory.py +++ b/python/sdk/tests/test_working_directory.py @@ -31,13 +31,13 @@ for line in sys.stdin: print(json.dumps({'jsonrpc': '2.0', 'id': frame['id'], 'result': {}}), flush=True) break elif method == 'session/working-directory/get': - result = {'cwd': directories.get(params['sessionId'], origin)} + result = {'cwd': directories.get(params['sessionId'], origin), 'root': origin} elif method == 'session/working-directory/set': assert not os.path.isabs(params['path']), 'client must preserve relative paths' previous = directories.get(params['sessionId'], origin) current = os.path.normpath(os.path.join(previous, params['path'])) directories[params['sessionId']] = current - result = {'cwd': 7 if params['path'] == 'malformed' else current} + result = {'cwd': 7 if params['path'] == 'malformed' else current, 'root': origin} else: raise AssertionError(method) print(json.dumps({'jsonrpc': '2.0', 'id': frame['id'], 'result': result}), flush=True) @@ -49,6 +49,7 @@ for line in sys.stdin: assert first.get_working_directory() == str(tmp_path) assert first.set_working_directory("child") == str(tmp_path / "child") assert first.get_working_directory() == str(tmp_path / "child") + assert first.get_workspace_root() == str(tmp_path) assert second.get_working_directory() == str(tmp_path) with pytest.raises(ValidationError): second.set_working_directory("malformed") diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 4c41bc1ec0..b2551d597c 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -395,6 +395,8 @@ export const LINK_MAP: Readonly> = { CreateWorktreePhase: 'worktrees.md', RestoreWorktreeRequest: 'worktrees.md', RestoredWorktree: 'worktrees.md', + RelocateOptions: 'working-directory.md', + RelocatedDirectories: 'working-directory.md', ChangeRequestListener: 'forge.md', ChangeRequestRef: 'forge.md', ChangeRequestSnapshot: 'forge.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 5152091c77..416d1850b6 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -234,7 +234,7 @@ const SERVICE_ROLES: ServiceRole[] = [ mode: 'seam', implementations: ['working-directory'], consumers: ['tool-working-directory', 'tool-fs', 'tool-bash', 'tool-pwsh', 'subagent', 'sdk-jsonrpc-server'], - note: 'One Session projection owns the effective execution directory. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed.', + note: 'Two Session projections own the effective execution directory and the workspace root it is in. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed.', }, { key: 'mcpResources', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 4896bf681f..aae535eea4 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2412,6 +2412,16 @@ "symbol": "CreatedWorktree", "source": "packages/experimental/worktree/src/types.ts" }, + { + "doc": "docs/subsystems/working-directory.md", + "symbol": "RelocateOptions", + "source": "packages/session/working-directory/src/index.ts" + }, + { + "doc": "docs/subsystems/working-directory.md", + "symbol": "RelocatedDirectories", + "source": "packages/session/working-directory/src/index.ts" + }, { "doc": "docs/subsystems/forge.md", "symbol": "ForgeRepository", diff --git a/snapshots/session/compaction-output-reserve/session.v4.jsonl b/snapshots/session/compaction-output-reserve/session.v4.jsonl index 71c259d418..1a8ba895ef 100644 --- a/snapshots/session/compaction-output-reserve/session.v4.jsonl +++ b/snapshots/session/compaction-output-reserve/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Establish a durable compaction premise before continuing. Record every part of this historical evidence: the snapshot uses keyless replay; persistence uses JSONL; the assembled headless application loads its real Cordis composition; model-visible inputs remain logged; tool calls and results remain paired and ordered; output reservation reduces the message budget before proactive compaction; compaction opens with compaction/start and closes with compaction/end; a successful auxiliary summary records compaction/summary source metadata; the replacement surface shadows only an older balanced range; the checkpoint remains smaller than the history it replaces; the newest tool result remains verbatim; the next request sees that checkpoint; the final response proves the same turn continued; deterministic snapshot evidence stays separate from the live-provider smoke; and no external API key is needed. Emit one alpha marker through bash, then finish the task after proactive compaction with the exact words PROACTIVE COMPACTION COMPLETE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":1000},"adapterDefaults":{"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":8780}} {"type":"session/title","data":{"title":"Establish a durable compaction premise","messageSeqs":[9],"source":{"kind":"fallback"}}} @@ -20,11 +20,11 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_compaction_marker"},"toolCallId":"call_compaction_marker","content":[{"type":"text","text":"alpha\n"}],"isError":false,"id":"{{message:5}}"},"meta":{"cwd":"/tmp"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"compaction/start","data":{"compactionId":"{{id:2}}","turn":1}} -{"type":"compaction/summary","data":{"compactionId":"{{id:2}}","summary":[{"type":"text","text":"The request established a durable compaction premise."}],"rawOutput":[{"type":"text","text":"The request established a durable compaction premise."}],"llmStreamCall":true,"shadowedRange":{"start":9,"end":10},"shadowedSeqs":[9,10],"shadowedTokenCount":445,"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":32,"usage":{"inputTokens":20,"outputTokens":4}}} +{"type":"compaction/summary","data":{"compactionId":"{{id:2}}","summary":[{"type":"text","text":"The request established a durable compaction premise."}],"rawOutput":[{"type":"text","text":"The request established a durable compaction premise."}],"llmStreamCall":true,"shadowedRange":{"start":9,"end":10},"shadowedSeqs":[9,10],"shadowedTokenCount":469,"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":32,"usage":{"inputTokens":20,"outputTokens":4}}} {"type":"user/message","data":{"content":[{"type":"text","text":"This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.\n\n"},{"type":"text","text":"The request established a durable compaction premise."},{"type":"text","text":""}],"source":{"kind":"compact-checkpoint","compactionId":"{{id:2}}"},"role":"user","id":"{{message:6}}"},"sourceEventSeqs":[20,21,9,10],"surfaceOp":{"op":"replace","startSeq":9,"endSeq":10}} {"type":"compaction/end","data":{"compactionId":"{{id:2}}","turn":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":1000},"adapterDefaults":{"maxTokens":true},"tools":"{{tools}}"},"reason":"series"}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"PROACTIVE COMPACTION COMPLETE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":20,"outputTokens":4},"stream":[{"type":"chunk","time":1791427805357,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791427805357,"index":0,"dt":[],"texts":["PROACTIVE COMPACTION COMPLETE"]},{"type":"chunk","time":1791427805357,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROACTIVE COMPACTION COMPLETE"}}},{"type":"chunk","time":1791427805357,"chunk":{"type":"usage","usage":{"inputTokens":20,"outputTokens":4}}},{"type":"chunk","time":1791427805357,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} diff --git a/snapshots/session/compaction-summary-headroom/session.v4.jsonl b/snapshots/session/compaction-summary-headroom/session.v4.jsonl index 7d8fa0a699..611951e486 100644 --- a/snapshots/session/compaction-summary-headroom/session.v4.jsonl +++ b/snapshots/session/compaction-summary-headroom/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Establish a durable compaction premise before continuing. Record every part of this historical evidence: the snapshot uses keyless replay; persistence uses JSONL; the assembled headless application loads its real Cordis composition; model-visible inputs remain logged; tool calls and results remain paired and ordered; output reservation reduces the message budget before proactive compaction; compaction opens with compaction/start and closes with compaction/end; a successful auxiliary summary records compaction/summary source metadata; the replacement surface shadows only an older balanced range; the checkpoint remains smaller than the history it replaces; the newest tool result remains verbatim; the next request sees that checkpoint; the final response proves the same turn continued; deterministic snapshot evidence stays separate from the live-provider smoke; and no external API key is needed. Emit one alpha marker through bash, then finish the task after proactive compaction with the exact words PROACTIVE COMPACTION COMPLETE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":1000},"adapterDefaults":{"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":8780}} {"type":"session/title","data":{"title":"Establish a durable compaction premise","messageSeqs":[9],"source":{"kind":"fallback"}}} @@ -20,11 +20,11 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_compaction_marker"},"toolCallId":"call_compaction_marker","content":[{"type":"text","text":"alpha\n"}],"isError":false,"id":"{{message:5}}"},"meta":{"cwd":"/tmp"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"compaction/start","data":{"compactionId":"{{id:2}}","turn":1}} -{"type":"compaction/summary","data":{"compactionId":"{{id:2}}","summary":[{"type":"text","text":"The request established a durable compaction premise."}],"rawOutput":[{"type":"text","text":"The request established a durable compaction premise."}],"llmStreamCall":true,"shadowedRange":{"start":9,"end":10},"shadowedSeqs":[9,10],"shadowedTokenCount":445,"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":1800,"usage":{"inputTokens":20,"outputTokens":4}}} +{"type":"compaction/summary","data":{"compactionId":"{{id:2}}","summary":[{"type":"text","text":"The request established a durable compaction premise."}],"rawOutput":[{"type":"text","text":"The request established a durable compaction premise."}],"llmStreamCall":true,"shadowedRange":{"start":9,"end":10},"shadowedSeqs":[9,10],"shadowedTokenCount":469,"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":1800,"usage":{"inputTokens":20,"outputTokens":4}}} {"type":"user/message","data":{"content":[{"type":"text","text":"This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.\n\n"},{"type":"text","text":"The request established a durable compaction premise."},{"type":"text","text":""}],"source":{"kind":"compact-checkpoint","compactionId":"{{id:2}}"},"role":"user","id":"{{message:6}}"},"sourceEventSeqs":[20,21,9,10],"surfaceOp":{"op":"replace","startSeq":9,"endSeq":10}} {"type":"compaction/end","data":{"compactionId":"{{id:2}}","turn":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":1000},"adapterDefaults":{"maxTokens":true},"tools":"{{tools}}"},"reason":"series"}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"PROACTIVE COMPACTION COMPLETE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":20,"outputTokens":4},"stream":[{"type":"chunk","time":1791427807070,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791427807070,"index":0,"dt":[],"texts":["PROACTIVE COMPACTION COMPLETE"]},{"type":"chunk","time":1791427807070,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROACTIVE COMPACTION COMPLETE"}}},{"type":"chunk","time":1791427807070,"chunk":{"type":"usage","usage":{"inputTokens":20,"outputTokens":4}}},{"type":"chunk","time":1791427807070,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} diff --git a/snapshots/session/headless.snapshot.ts b/snapshots/session/headless.snapshot.ts index 37fd50c0c4..5fe465f11d 100644 --- a/snapshots/session/headless.snapshot.ts +++ b/snapshots/session/headless.snapshot.ts @@ -874,8 +874,11 @@ function verifyWorkingDirectory(log: string, cwd: string): void { return (source.sections as JsonObject[]).filter(section => section.name === 'working-directory:current') .map(section => section.text) }) + // Inside the original project the snapshot names the root only while the cursor is below it. expect(contexts).toEqual([cwd, join(cwd, 'selected'), join(cwd, 'second'), cwd] - .map(directory => `Current working directory: ${JSON.stringify(directory)}.`)) + .map(directory => directory === cwd + ? `Current working directory: ${JSON.stringify(directory)}.` + : `Current working directory: ${JSON.stringify(directory)}.\nWorkspace root: ${JSON.stringify(cwd)}.`)) const notices = users.filter(message => (message.source as JsonObject).kind === 'working-directory') .map(message => (message.content as JsonObject[]).map(block => block.text).join('')) expect(notices).toEqual([ diff --git a/snapshots/session/model-switch-compaction/session.v4.jsonl b/snapshots/session/model-switch-compaction/session.v4.jsonl index c278fd77df..cc04a82c30 100644 --- a/snapshots/session/model-switch-compaction/session.v4.jsonl +++ b/snapshots/session/model-switch-compaction/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Establish a durable compaction premise before continuing. Record every part of this historical evidence: the snapshot uses keyless replay; persistence uses JSONL; the assembled headless application loads its real Cordis composition; model-visible inputs remain logged; tool calls and results remain paired and ordered; output reservation reduces the message budget before proactive compaction; compaction opens with compaction/start and closes with compaction/end; a successful auxiliary summary records compaction/summary source metadata; the replacement surface shadows only an older balanced range; the checkpoint remains smaller than the history it replaces; the newest tool result remains verbatim; the next request sees that checkpoint; the final response proves the same turn continued; deterministic snapshot evidence stays separate from the live-provider smoke; and no external API key is needed. Emit one alpha marker through bash, then finish the task after proactive compaction with the exact words PROACTIVE COMPACTION COMPLETE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":1000},"adapterDefaults":{"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":100000}} {"type":"session/title","data":{"title":"Establish a durable compaction premise","messageSeqs":[9],"source":{"kind":"fallback"}}} @@ -22,12 +22,12 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"compaction/start","data":{"compactionId":"{{id:2}}","turn":1}} -{"type":"compaction/summary","data":{"compactionId":"{{id:2}}","summary":[{"type":"text","text":"The request established a durable compaction premise."}],"rawOutput":[{"type":"text","text":"The request established a durable compaction premise."}],"llmStreamCall":true,"shadowedRange":{"start":9,"end":10},"shadowedSeqs":[9,10],"shadowedTokenCount":445,"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":32,"usage":{"inputTokens":20,"outputTokens":4}}} +{"type":"compaction/summary","data":{"compactionId":"{{id:2}}","summary":[{"type":"text","text":"The request established a durable compaction premise."}],"rawOutput":[{"type":"text","text":"The request established a durable compaction premise."}],"llmStreamCall":true,"shadowedRange":{"start":9,"end":10},"shadowedSeqs":[9,10],"shadowedTokenCount":469,"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":32,"usage":{"inputTokens":20,"outputTokens":4}}} {"type":"user/message","data":{"content":[{"type":"text","text":"This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.\n\n"},{"type":"text","text":"The request established a durable compaction premise."},{"type":"text","text":""}],"source":{"kind":"compact-checkpoint","compactionId":"{{id:2}}"},"role":"user","id":"{{message:6}}"},"sourceEventSeqs":[22,23,9,10],"surfaceOp":{"op":"replace","startSeq":9,"endSeq":10}} {"type":"compaction/end","data":{"compactionId":"{{id:2}}","turn":1}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:7}}"}},"sourceEventSeqs":[8],"surfaceOp":{"op":"replace","startSeq":8,"endSeq":8}} {"type":"user/message","data":{"content":[{"type":"text","text":"[model changed: assistant turns above this point were generated by deepseek-v4-flash; the session continues with deepseek-v4-pro]"}],"source":{"kind":"model-selection","form":"notice","summary":"deepseek-v4-flash → deepseek-v4-pro"},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"/tmp\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro","maxTokens":1000},"adapterDefaults":{"maxTokens":true},"tools":"{{tools}}"},"reason":"change","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro","contextWindow":8780}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"PROACTIVE COMPACTION COMPLETE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"{{message:10}}"},"usage":{"inputTokens":20,"outputTokens":4},"stream":[{"type":"chunk","time":1792380141229,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792380141229,"index":0,"dt":[],"texts":["PROACTIVE COMPACTION COMPLETE"]},{"type":"chunk","time":1792380141229,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROACTIVE COMPACTION COMPLETE"}}},{"type":"chunk","time":1792380141229,"chunk":{"type":"usage","usage":{"inputTokens":20,"outputTokens":4}}},{"type":"chunk","time":1792380141229,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/working-directory-admission/session.v4.jsonl b/snapshots/session/working-directory-admission/session.v4.jsonl index 991f036ab2..07c7505ffe 100644 --- a/snapshots/session/working-directory-admission/session.v4.jsonl +++ b/snapshots/session/working-directory-admission/session.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:3}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read the current directory with working_directory, then reply with exactly WORKING_DIRECTORY_ADMISSION_OK."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/selected\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/selected\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/selected\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/selected\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Read the current directory with","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/working-directory-consumers/session.v4.jsonl b/snapshots/session/working-directory-consumers/session.v4.jsonl index 1c39a538a2..b46b0f9b5f 100644 --- a/snapshots/session/working-directory-consumers/session.v4.jsonl +++ b/snapshots/session/working-directory-consumers/session.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/selected\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/selected\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/selected\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/selected\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/selected\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"directory-3","name":"write","arguments":"{\"file_path\":\"result.txt\",\"content\":\"created inside selected\\n\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427907883,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427907883,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"directory-3","name":"write","arguments":"{\"file_path\":\"result.txt\",\"content\":\"created inside selected\\n\"}"}}},{"type":"chunk","time":1791427907883,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427907883,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"directory-3","name":"write","arguments":"{\"file_path\":\"result.txt\",\"content\":\"created inside selected\\n\"}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"directory-3"},"toolCallId":"directory-3","content":[{"type":"text","text":"{{cwd}}/selected/result.txt\nfile\n\nCreated file\n"}],"isError":false,"id":"{{message:11}}"},"meta":{"operation":"create","path":"{{cwd}}/selected/result.txt","diffs":[]}},"sourceEventSeqs":[29],"surfaceOp":"append"} @@ -41,7 +41,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/selected\" to \"{{cwd}}/second\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/second\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/second\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/second\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/second\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"directory-5","name":"read","arguments":"{\"file_path\":\"witness.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427907955,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427907955,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"directory-5","name":"read","arguments":"{\"file_path\":\"witness.txt\"}"}}},{"type":"chunk","time":1791427907955,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427907955,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"directory-5","name":"read","arguments":"{\"file_path\":\"witness.txt\"}"}} {"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"directory-5"},"toolCallId":"directory-5","content":[{"type":"text","text":"{{cwd}}/second/witness.txt\nfile\n\n1: second directory\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:17}}"},"meta":{"path":"{{cwd}}/second/witness.txt","offset":1,"lines":[{"number":1,"text":"second directory"}],"totalLines":1}},"sourceEventSeqs":[44],"surfaceOp":"append"} diff --git a/snapshots/session/working-directory/session.v4.jsonl b/snapshots/session/working-directory/session.v4.jsonl index 31bb460f22..ffbff9bc45 100644 --- a/snapshots/session/working-directory/session.v4.jsonl +++ b/snapshots/session/working-directory/session.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/selected\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/selected\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/selected\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/selected\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/selected\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"directory-3","name":"write","arguments":"{\"file_path\":\"result.txt\",\"content\":\"created inside selected\\n\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427906150,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427906150,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"directory-3","name":"write","arguments":"{\"file_path\":\"result.txt\",\"content\":\"created inside selected\\n\"}"}}},{"type":"chunk","time":1791427906150,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427906150,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"directory-3","name":"write","arguments":"{\"file_path\":\"result.txt\",\"content\":\"created inside selected\\n\"}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"directory-3"},"toolCallId":"directory-3","content":[{"type":"text","text":"{{cwd}}/selected/result.txt\nfile\n\nCreated file\n"}],"isError":false,"id":"{{message:11}}"},"meta":{"operation":"create","path":"{{cwd}}/selected/result.txt","diffs":[]}},"sourceEventSeqs":[29],"surfaceOp":"append"} @@ -41,7 +41,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/selected\" to \"{{cwd}}/second\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/second\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/second\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/second\".\nWorkspace root: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/second\".\nWorkspace root: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"directory-5","name":"read","arguments":"{\"file_path\":\"witness.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427906188,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427906188,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"directory-5","name":"read","arguments":"{\"file_path\":\"witness.txt\"}"}}},{"type":"chunk","time":1791427906188,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427906188,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"directory-5","name":"read","arguments":"{\"file_path\":\"witness.txt\"}"}} {"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"directory-5"},"toolCallId":"directory-5","content":[{"type":"text","text":"{{cwd}}/second/witness.txt\nfile\n\n1: second directory\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:17}}"},"meta":{"path":"{{cwd}}/second/witness.txt","offset":1,"lines":[{"number":1,"text":"second directory"}],"totalLines":1}},"sourceEventSeqs":[44],"surfaceOp":"append"} diff --git a/snapshots/session/worktree/session.v4.jsonl b/snapshots/session/worktree/session.v4.jsonl index 2524d6b28b..28837673b1 100644 --- a/snapshots/session/worktree/session.v4.jsonl +++ b/snapshots/session/worktree/session.v4.jsonl @@ -14,13 +14,13 @@ {"type":"session/title","data":{"title":"Create a worktree named isolated","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-1","name":"create_worktree","arguments":"{\"name\":\"isolated\",\"from\":\"HEAD\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427910472,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427910472,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-1","name":"create_worktree","arguments":"{\"name\":\"isolated\",\"from\":\"HEAD\"}"}}},{"type":"chunk","time":1791427910472,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427910472,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"worktree-1","name":"create_worktree","arguments":"{\"name\":\"isolated\",\"from\":\"HEAD\"}"}} -{"type":"working-directory/change","data":{"cwd":"{{cwd}}/.agents/worktrees/isolated"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/isolated\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:5}}"}]}} +{"type":"working-directory/change","data":{"cwd":"{{cwd}}/.agents/worktrees/isolated","anchor":"{{cwd}}/.agents/worktrees/isolated"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/isolated\". \"{{cwd}}/.agents/worktrees/isolated\" is now the workspace root."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:5}}"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-1"},"toolCallId":"worktree-1","content":[{"type":"text","text":"{\"path\":\"{{cwd}}/.agents/worktrees/isolated\",\"branch\":\"isolated\",\"baseCommit\":\"86e2ed339bd583c54e29aaf0698fb8fb176ddcbb\",\"repositoryRoot\":\"{{cwd}}\"}"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/isolated\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}\" to \"{{cwd}}/.agents/worktrees/isolated\". \"{{cwd}}/.agents/worktrees/isolated\" is now the workspace root."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}/.agents/worktrees/isolated\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}/.agents/worktrees/isolated\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-2","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427910591,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427910591,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-2","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}}},{"type":"chunk","time":1791427910591,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427910591,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"worktree-2","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}} @@ -35,12 +35,12 @@ {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-4","name":"working_directory","arguments":"{\"cd\":\"../../..\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427910629,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427910629,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-4","name":"working_directory","arguments":"{\"cd\":\"../../..\"}"}}},{"type":"chunk","time":1791427910629,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427910629,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"worktree-4","name":"working_directory","arguments":"{\"cd\":\"../../..\"}"}} {"type":"working-directory/change","data":{"cwd":"{{cwd}}"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/.agents/worktrees/isolated\" to \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:13}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/.agents/worktrees/isolated\" to \"{{cwd}}\". \"{{cwd}}\" is now the workspace root."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:13}}"}]}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"worktree-4"},"toolCallId":"worktree-4","content":[{"type":"text","text":"{{cwd}}"}],"isError":false,"id":"{{message:14}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/.agents/worktrees/isolated\" to \"{{cwd}}\"."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"The working directory changed from \"{{cwd}}/.agents/worktrees/isolated\" to \"{{cwd}}\". \"{{cwd}}\" is now the workspace root."}],"source":{"kind":"working-directory"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{session:1}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"worktree-5","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427910646,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791427910646,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"worktree-5","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}}},{"type":"chunk","time":1791427910646,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427910646,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"worktree-5","name":"read","arguments":"{\"file_path\":\"tracked.txt\"}"}}