diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml index c0f7d394c3..4585409abf 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml @@ -9,8 +9,8 @@ en: cb5864da99a92145 zh: 210f8b4282f99c93 /agent-note-session-workspace-root/decision: - en: ed140682dce26955 - zh: 65d73b329a43ab04 + en: 60855fdb6841d31b + zh: 57aa5b7d6144b241 /agent-note-session-workspace-root/deferred: en: d8167590081dfa4e zh: 208630aac853773b diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md index 6806159790..b3726fb9c3 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md @@ -14,7 +14,7 @@ Each Session has three directories with one owner each. `header.cwd` remains the `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 registered checkout and the child starts inside it, the child relocates into that root. The child's root is then that checkout unless the original project its header registers already contains the child's directory, because the root is always the longest containing anchor; the child registers no other parent anchor, so a later `cd` into another checkout the parent entered leaves the child's root unchanged. 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. +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 and starts its directories through the service's `inherit`, which owns the decision: when the parent's root is another registered checkout and the child starts inside it, the child relocates into that root; otherwise only its directory is set. The child's root is then that checkout unless the original project its header registers already contains the child's directory, because the root is always the longest containing anchor; the child registers no other parent anchor, so a later `cd` into another checkout the parent entered leaves the child's root unchanged. 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 diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md index 8dfdb24d1e..b4a858ab68 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md @@ -14,7 +14,7 @@ Status: implemented `relocate` 验证根及其内部的目录,然后提交一条可选 `anchor` 指向该根的 `working-directory/change`。根内部的 `set` 只移动光标;进入另一个锚的 `set` 把该锚选为根;所有锚之外的 `set` 移动光标并保留根。恢复到原始项目时再次把它选为根。事件的可选属性是一次同版本持久化变更,记录在[确认记录](../../../../docs/persistence-changes/2026-11-03-working-directory-anchor.zh.md)中;没有 `anchor` 的日志折叠后以原始项目为唯一的锚。 -工作树创建通过 `relocate` 进入检出目录;离开它就是既有的 `set` 回到原始项目,锚规则将其变为根的变化。子代理在 header 中保留父级的原始项目;当父级的根是另一个已登记的检出目录且子级在其中启动时,子级迁入该根。子级的根随即是该检出目录,除非其 header 登记的原始项目本身已包含子级目录,因为根始终是包含目录的最长锚;子级不登记父级的其他锚,因此之后 `cd` 进父级进入过的另一个检出目录时子级的根不变。光标与根不同时,用户上下文快照增加一行 `Workspace root`,选中另一个根的变更在通知末尾给出新根。SDK 的工作目录方法返回 `{ cwd, root }`,`getWorkspaceRoot`(Python 中为 `get_workspace_root`)读取根。 +工作树创建通过 `relocate` 进入检出目录;离开它就是既有的 `set` 回到原始项目,锚规则将其变为根的变化。子代理在 header 中保留父级的原始项目,并通过服务的 `inherit` 启动目录,由它做出决定:当父级的根是另一个已登记的检出目录且子级在其中启动时,子级迁入该根;否则只设置目录。子级的根随即是该检出目录,除非其 header 登记的原始项目本身已包含子级目录,因为根始终是包含目录的最长锚;子级不登记父级的其他锚,因此之后 `cd` 进父级进入过的另一个检出目录时子级的根不变。光标与根不同时,用户上下文快照增加一行 `Workspace root`,选中另一个根的变更在通知末尾给出新根。SDK 的工作目录方法返回 `{ cwd, root }`,`getWorkspaceRoot`(Python 中为 `get_workspace_root`)读取根。 ## Deferred diff --git a/docs/subsystems/working-directory.i18n.yaml b/docs/subsystems/working-directory.i18n.yaml index fecbd67ac5..86c237635c 100644 --- a/docs/subsystems/working-directory.i18n.yaml +++ b/docs/subsystems/working-directory.i18n.yaml @@ -12,5 +12,5 @@ en: 2c27d5dfe7abbd4c zh: 4e6dc26dff03edad /working-directory/relocation: - en: 2a57d0017ecf9658 - zh: 44113e49d3a079fd + en: bf5100b06b3c0320 + zh: 976187ef3ed39e17 diff --git a/docs/subsystems/working-directory.md b/docs/subsystems/working-directory.md index 09744ce325..fb08991dd3 100644 --- a/docs/subsystems/working-directory.md +++ b/docs/subsystems/working-directory.md @@ -18,7 +18,7 @@ The initial value and subsequent current values reach the model as required user ## Relocation -`relocate` takes the new root and these options, and resolves to the directories it committed. +`relocate` takes the new root and these options, and resolves to the directories it committed. `inherit(agent, source, { cwd, signal? })` starts one Session's directories from another's: when the source works in a registered checkout other than the starting Session's original project and the canonical `cwd` lies inside it, the checkout is registered through `relocate`; otherwise only the directory is set. The source's other anchors are not passed on, and its later changes do not reach the started Session. ```ts type-equiv /** Options of {@link WorkingDirectoryService.relocate}. */ @@ -31,7 +31,17 @@ interface RelocateOptions { ``` ```ts type-equiv -/** The committed outcome of {@link WorkingDirectoryService.relocate}. */ +/** Options of {@link WorkingDirectoryService.inherit}. */ +interface InheritOptions { + /** Canonical absolute directory the Session starts in, spelled as the service records directories. */ + cwd: string + /** Cancellation before the durable change. */ + signal?: AbortSignal +} +``` + +```ts type-equiv +/** The committed outcome of {@link WorkingDirectoryService.relocate} and {@link WorkingDirectoryService.inherit}. */ interface RelocatedDirectories { /** * Canonical absolute workspace root the commit selected: the longest registered anchor containing @@ -121,6 +131,20 @@ set(agent: Agent, path: string, signal?: AbortSignal): Promise * @throws when either path is not an existing directory or the directory lies outside the root. */ relocate(agent: Agent, root: string, options: RelocateOptions = {}): Promise + +/** + * Start a Session's directories from another Session's. When `source` works in a registered checkout + * other than the starting Session's own original project and `options.cwd` lies inside that checkout, + * the checkout is registered as the starting Session's anchor and `cwd` entered through {@link relocate}; + * otherwise only the current directory is set through {@link set}. Only the source's current root is + * passed on, never its other anchors, and later changes to `source` do not reach the starting Session. + * @param agent - live or unpublished Agent owning the Session that starts. + * @param source - Session whose current root may be passed on; the call leaves it unchanged. + * @param options - canonical absolute directory to start in and cancellation before the durable change. + * @returns the committed current directory and the workspace root selected after the commit. + * @throws when `options.cwd` is not an existing directory, or when a `working-directory/access` listener rejects. + */ +async inherit(agent: Agent, source: Session, options: InheritOptions): 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 6663597bdf..c38f2c3d17 100644 --- a/docs/subsystems/working-directory.zh.md +++ b/docs/subsystems/working-directory.zh.md @@ -18,7 +18,7 @@ Session 的当前目录由 [`dsh-working-directory`](../../packages/session/work ## 迁移 -`relocate` 接收新的根与以下选项,并解析为它提交的目录。 +`relocate` 接收新的根与以下选项,并解析为它提交的目录。`inherit(agent, source, { cwd, signal? })` 让一个 Session 的目录从另一个 Session 出发:来源在其原始项目之外的已登记检出目录中工作、且规范化的 `cwd` 位于其中时,通过 `relocate` 登记该检出目录;否则只设置目录。来源的其他锚不传递,它之后的变化也不影响已启动的 Session。 ```ts type-equiv /** Options of {@link WorkingDirectoryService.relocate}. */ @@ -31,7 +31,17 @@ interface RelocateOptions { ``` ```ts type-equiv -/** The committed outcome of {@link WorkingDirectoryService.relocate}. */ +/** Options of {@link WorkingDirectoryService.inherit}. */ +interface InheritOptions { + /** Canonical absolute directory the Session starts in, spelled as the service records directories. */ + cwd: string + /** Cancellation before the durable change. */ + signal?: AbortSignal +} +``` + +```ts type-equiv +/** The committed outcome of {@link WorkingDirectoryService.relocate} and {@link WorkingDirectoryService.inherit}. */ interface RelocatedDirectories { /** * Canonical absolute workspace root the commit selected: the longest registered anchor containing @@ -121,6 +131,20 @@ set(agent: Agent, path: string, signal?: AbortSignal): Promise * @throws when either path is not an existing directory or the directory lies outside the root. */ relocate(agent: Agent, root: string, options: RelocateOptions = {}): Promise + +/** + * Start a Session's directories from another Session's. When `source` works in a registered checkout + * other than the starting Session's own original project and `options.cwd` lies inside that checkout, + * the checkout is registered as the starting Session's anchor and `cwd` entered through {@link relocate}; + * otherwise only the current directory is set through {@link set}. Only the source's current root is + * passed on, never its other anchors, and later changes to `source` do not reach the starting Session. + * @param agent - live or unpublished Agent owning the Session that starts. + * @param source - Session whose current root may be passed on; the call leaves it unchanged. + * @param options - canonical absolute directory to start in and cancellation before the durable change. + * @returns the committed current directory and the workspace root selected after the commit. + * @throws when `options.cwd` is not an existing directory, or when a `working-directory/access` listener rejects. + */ +async inherit(agent: Agent, source: Session, options: InheritOptions): Promise ``` Types: [Agent](core.zh.md) · [Session](session.zh.md) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index c497e2438e..2e7fcf78ec 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4602,6 +4602,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the committed current directory and the workspace root selected after the commit; the registered root is that root unless a more specific anchor already contains the directory. 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.'], }, + { + signature: 'async inherit(agent: Agent, source: Session, options: InheritOptions): Promise', + description: 'Start a Session\'s directories from another Session\'s. When `source` works in a registered checkout other than the starting Session\'s own original project and `options.cwd` lies inside that checkout, the checkout is registered as the starting Session\'s anchor and `cwd` entered through relocate; otherwise only the current directory is set through set. Only the source\'s current root is passed on, never its other anchors, and later changes to `source` do not reach the starting Session.', + parameters: [{ name: 'agent', description: 'live or unpublished Agent owning the Session that starts.' }, { name: 'source', description: 'Session whose current root may be passed on; the call leaves it unchanged.' }, { name: 'options', description: 'canonical absolute directory to start in and cancellation before the durable change.' }], + returns: 'the committed current directory and the workspace root selected after the commit.', + throws: ['when `options.cwd` is not an existing directory, or when a `working-directory/access` listener rejects.'], + }, ], }, { @@ -6936,6 +6943,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'IndexInjectionPlacement', declaration: 'export type IndexInjectionPlacement = \'head\' | \'body\';', }, + { + name: 'InheritOptions', + declaration: 'export interface InheritOptions {\n cwd: string;\n signal?: AbortSignal;\n}', + }, { name: 'InspectOptions', declaration: 'export interface InspectOptions {\n readonly registry?: Registry;\n}', diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index 0e463f42f6..5c19bdacce 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: e65405026debde7c zh: e12a648eb10ed16b /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: 2955afc111e1bc2a - zh: a10d20cc4746c31e + en: bb6e6764a0f0cc9f + zh: 31f3630709b2c2de /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index b960455d62..fe86358caf 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -41,7 +41,7 @@ Directory validation and publication delegate through `working-directory/access`
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. 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. +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`; `inherit` starts a Session's directories from another Session's, registering the checkout the source works in when the starting directory lies inside it and setting only the directory otherwise. 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. diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index 2b12856195..37a1007178 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。第二个投影从同一事件折叠工作区锚及其选出的根,`relocate` 在提交一条携带 `anchor` 的事件前验证根及其内部的目录。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。第二个投影从同一事件折叠工作区锚及其选出的根,`relocate` 在提交一条携带 `anchor` 的事件前验证根及其内部的目录;`inherit` 让一个 Session 的目录从另一个 Session 出发,起始目录位于来源所在的检出目录内时登记该检出目录,否则只设置目录。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index f58e4e4690..b5c8802ae4 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -85,7 +85,15 @@ export interface RelocateOptions { signal?: AbortSignal } -/** The committed outcome of {@link WorkingDirectoryService.relocate}. */ +/** Options of {@link WorkingDirectoryService.inherit}. */ +export interface InheritOptions { + /** Canonical absolute directory the Session starts in, spelled as the service records directories. */ + cwd: string + /** Cancellation before the durable change. */ + signal?: AbortSignal +} + +/** The committed outcome of {@link WorkingDirectoryService.relocate} and {@link WorkingDirectoryService.inherit}. */ export interface RelocatedDirectories { /** * Canonical absolute workspace root the commit selected: the longest registered anchor containing @@ -314,6 +322,28 @@ export class WorkingDirectoryService extends Service { }) } + /** + * Start a Session's directories from another Session's. When `source` works in a registered checkout + * other than the starting Session's own original project and `options.cwd` lies inside that checkout, + * the checkout is registered as the starting Session's anchor and `cwd` entered through {@link relocate}; + * otherwise only the current directory is set through {@link set}. Only the source's current root is + * passed on, never its other anchors, and later changes to `source` do not reach the starting Session. + * @param agent - live or unpublished Agent owning the Session that starts. + * @param source - Session whose current root may be passed on; the call leaves it unchanged. + * @param options - canonical absolute directory to start in and cancellation before the durable change. + * @returns the committed current directory and the workspace root selected after the commit. + * @throws when `options.cwd` is not an existing directory, or when a `working-directory/access` listener rejects. + */ + async inherit(agent: Agent, source: Session, options: InheritOptions): Promise { + const root = this.rootOf(source) + // The deployment fallback a source without a recorded project reports is no anchor, and the starting + // Session's own original project is registered already. + const checkout = this.anchorsOf(source).includes(root) && root !== agent.session.header.cwd && within(root, options.cwd) + if (checkout) return this.relocate(agent, root, options) + const cwd = await this.set(agent, options.cwd, options.signal) + return { root: this.rootOf(agent.session), cwd } + } + private contextText(session: Session): string { const cwd = this.get(session) const root = this.rootOf(session) diff --git a/packages/session/working-directory/tests/workspace-root.spec.ts b/packages/session/working-directory/tests/workspace-root.spec.ts index 548e58f8a6..fad008c736 100644 --- a/packages/session/working-directory/tests/workspace-root.spec.ts +++ b/packages/session/working-directory/tests/workspace-root.spec.ts @@ -239,6 +239,66 @@ describe('Session workspace roots', () => { expect(f.ctx.workingDirectory.rootOf(agent.session)).toBe(f.worktree) }) + it('passes the checkout a source works in on to a Session starting inside it, and only the directory otherwise', async () => { + await using f = await fixture() + const src = join(f.worktree, 'src') + await f.ctx.workingDirectory.relocate(f.agent, f.worktree, { cwd: src }) + // Starting inside the source's checkout registers it; the child header still records the original project. + const inside = await f.harness.create(SessionId('inherits-checkout'), {}, { cwd: f.root }) + await expect(f.ctx.workingDirectory.inherit(inside, f.agent.session, { cwd: src })) + .resolves.toEqual({ root: f.worktree, cwd: src }) + expect(f.ctx.workingDirectory.anchorsOf(inside.session)).toEqual([f.root, f.worktree]) + expect(inside.session.snapshotEvents().filter(event => event.type === 'working-directory/change')) + .toEqual([expect.objectContaining({ data: { cwd: src, anchor: f.worktree } })]) + // Starting outside the source's checkout sets the directory and keeps the original project as the root. + const outside = await f.harness.create(SessionId('starts-outside'), {}, { cwd: f.root }) + const packages = join(f.root, 'packages') + await expect(f.ctx.workingDirectory.inherit(outside, f.agent.session, { cwd: packages })) + .resolves.toEqual({ root: f.root, cwd: packages }) + expect(f.ctx.workingDirectory.anchorsOf(outside.session)).toEqual([f.root]) + expect(outside.session.snapshotEvents().filter(event => event.type === 'working-directory/change')) + .toEqual([expect.objectContaining({ data: { cwd: packages } })]) + // The source's other anchors are not passed on: a later change into one leaves the child's root alone. + await f.ctx.workingDirectory.set(inside, f.root) + await f.ctx.workingDirectory.relocate(f.agent, f.nested) + await f.ctx.workingDirectory.set(inside, join(f.nested, 'src')) + expect(f.ctx.workingDirectory.rootOf(inside.session)).toBe(f.root) + // A missing directory is refused before anything is committed. + await expect(f.ctx.workingDirectory.inherit(outside, f.agent.session, { cwd: join(f.root, 'missing') })).rejects.toThrow('directory does not exist') + }) + + it('passes no root on from a source whose root is its original project or the deployment fallback', async () => { + await using f = await fixture() + // The source works in its original project: the child's own header already registers it. + const child = await f.harness.create(SessionId('same-project'), {}, { cwd: f.root }) + const foo = join(f.root, 'packages', 'foo') + await expect(f.ctx.workingDirectory.inherit(child, f.agent.session, { cwd: foo })).resolves.toEqual({ root: f.root, cwd: foo }) + expect(child.session.snapshotEvents().filter(event => event.type === 'working-directory/change')) + .toEqual([expect.objectContaining({ data: { cwd: foo } })]) + // A source without a recorded project reports the deployment fallback, which is no anchor to pass on: + // the started Session only sets its directory and registers nothing. + const bare = await f.harness.create(SessionId('bare-source')) + const started = await f.harness.create(SessionId('bare-child')) + await expect(f.ctx.workingDirectory.inherit(started, bare.session, { cwd: f.outside })) + .resolves.toEqual({ root: f.ctx.workingDirectory.defaultDirectory, cwd: f.outside }) + expect(f.ctx.workingDirectory.anchorsOf(started.session)).toEqual([]) + expect(started.session.snapshotEvents().filter(event => event.type === 'working-directory/change')) + .toEqual([expect.objectContaining({ data: { cwd: f.outside } })]) + }) + + it('keeps the original project as the root when it is more specific than the inherited checkout', async () => { + await using f = await fixture() + const packages = join(f.root, 'packages') + // The source relocated into a checkout enclosing the project the child's header records. + const source = await f.harness.create(SessionId('enclosing-source'), {}, { cwd: packages }) + await f.ctx.workingDirectory.relocate(source, f.root) + const child = await f.harness.create(SessionId('enclosed-child'), {}, { cwd: packages }) + const foo = join(packages, 'foo') + await expect(f.ctx.workingDirectory.inherit(child, source.session, { cwd: foo })).resolves.toEqual({ root: packages, cwd: foo }) + expect(f.ctx.workingDirectory.anchorsOf(child.session)).toEqual([packages, f.root]) + expect(f.ctx.workingDirectory.rootOf(child.session)).toBe(packages) + }) + it('tests containment lexically on canonical absolute paths', () => { expect(within('/repo', '/repo')).toBe(true) expect(within('/repo', '/repo/src')).toBe(true) diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 4e373404d2..5fd01917b0 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: f792ac6ae4212936 - zh: 244f69217d96b6a6 + en: f6b1472754d90c07 + zh: 672ad5f7f91fcff4 /deepseek-ai-dsh-subagent/use-this-package/enabling-delegation: en: c0718955687ff245 zh: eb2d3cdbe92e0fe2 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index 507c5da860..a3c755ff17 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. When the parent works in a registered checkout other than its original project, a child that starts inside that checkout registers it as a workspace anchor; the child's root is the longest of its anchors containing its directory, which is that checkout unless the original project recorded in its header already contains the directory. The child registers only the parent's current root, not the parent's other anchors, so a later `cd` into another checkout the parent entered leaves the child's root unchanged. 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. The child's directories start through the working-directory service's `inherit`: when the parent works in a registered checkout other than its original project, a child that starts inside that checkout registers it as a workspace anchor; the child's root is the longest of its anchors containing its directory, which is that checkout unless the original project recorded in its header already contains the directory. The child registers only the parent's current root, not the parent's other anchors, so a later `cd` into another checkout the parent entered leaves the child's root unchanged. 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 46ebd7f757..b3671dad0e 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -每次启动可传入可选的 `cwd`;相对路径以父级当前工作目录解析,省略时捕获该当前目录。子级保留父级的起始目录元数据与权限根目录。父级在原始项目之外的已登记检出目录中工作时,在该检出目录内启动的子级把它登记为工作区锚;子级的根是其锚中包含其目录的最长者,即该检出目录,除非 header 记录的原始项目本身已包含该目录。子级只登记父级当前的根,不登记父级的其他锚,因此之后 `cd` 进父级进入过的另一个检出目录时子级的根不变。子级自己的目录值位于继承历史之后,在继续与重启后保留,并独立于父级之后的目录变化。 +每次启动可传入可选的 `cwd`;相对路径以父级当前工作目录解析,省略时捕获该当前目录。子级保留父级的起始目录元数据与权限根目录。子级的目录通过工作目录服务的 `inherit` 启动:父级在原始项目之外的已登记检出目录中工作时,在该检出目录内启动的子级把它登记为工作区锚;子级的根是其锚中包含其目录的最长者,即该检出目录,除非 header 记录的原始项目本身已包含该目录。子级只登记父级当前的根,不登记父级的其他锚,因此之后 `cd` 进父级进入过的另一个检出目录时子级的根不变。子级自己的目录值位于继承历史之后,在继续与重启后保留,并独立于父级之后的目录变化。 本包是每个委派组合都共享的约定。你通过把服务与一个或多个提供方后端以及面向模型的委派工具一起挂载来启用它;此后 agent 即可委派工作,服务会把每个请求路由到具名提供方。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index daa6f96fcb..a57a162c1d 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -7,7 +7,7 @@ */ import { randomUUID } from 'node:crypto' -import { isAbsolute, relative, resolve, sep } from 'node:path' +import { isAbsolute, resolve } from 'node:path' import type {} from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' @@ -49,12 +49,6 @@ import type { SubagentDelivery } from './control-types.ts' import { ActivationPool, ChildLock, activationAgent, captureLocalResult, observeLocalFailure, requireLocalActivation } from './activation.ts' import type { Activation, ActivationResource, LocalActivation } from './activation.ts' -/** Whether `path` is `root` or lies below it: a lexical test of two canonical absolute paths of one execution world. */ -function within(root: string, path: string): boolean { - const rest = relative(root, path) - return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest)) -} - /** Inputs shared by model steering and human prompt delivery. */ type ChildDeliveryOptions = { readonly delivery: SubagentDelivery @@ -844,16 +838,9 @@ 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') - // The child header records the parent's original project; a parent working in another - // registered checkout passes that checkout on as the child's root when the child starts inside - // it. A parent without a recorded project reports the deployment fallback, which is no anchor. - const parentRoot = workingDirectory.rootOf(create.parent.session) - if (workingDirectory.anchorsOf(create.parent.session).includes(parentRoot) - && 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) - } + // The child header records the parent's original project; the directory service decides whether + // the checkout the parent works in becomes the child's root as well. + await workingDirectory.inherit(child, create.parent.session, { cwd: create.cwd, signal: 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 1032abbb70..e05a67adfb 100644 --- a/packages/subagent/subagent/tests/working-directory-fixture.ts +++ b/packages/subagent/subagent/tests/working-directory-fixture.ts @@ -2,7 +2,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import { isAbsolute, relative, resolve, sep } from 'node:path' import type { Agent } from '@deepseek-ai/dsh-agent' import type { Session } from '@deepseek-ai/dsh-session' -import type { RelocateOptions, RelocatedDirectories } from '@deepseek-ai/dsh-working-directory' +import type { InheritOptions, RelocateOptions, RelocatedDirectories } from '@deepseek-ai/dsh-working-directory' /** Whether `path` is `root` or lies below it, lexically. */ function within(root: string, path: string): boolean { @@ -55,6 +55,15 @@ class FixtureWorkingDirectory extends Service { this.directories.set(agent.session, cwd) return { root: anchor, cwd } } + + async inherit(agent: Agent, source: Session, options: InheritOptions): Promise { + const root = this.rootOf(source) + if (this.anchorsOf(source).includes(root) && root !== agent.session.header.cwd && within(root, options.cwd)) { + return this.relocate(agent, root, options) + } + const cwd = await this.set(agent, options.cwd, options.signal) + return { root: this.rootOf(agent.session), cwd } + } } /** Mount the directory collaborator without filesystem or model-context behavior unrelated to an orchestration test. */ diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 8b68efdbe8..df93331739 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -416,6 +416,7 @@ export const LINK_MAP: Readonly> = { WorktreeCreation: 'worktrees.md', RestoredWorktree: 'worktrees.md', RelocateOptions: 'working-directory.md', + InheritOptions: 'working-directory.md', RelocatedDirectories: 'working-directory.md', ChangeRequestListener: 'forge.md', ChangeRequestRef: 'forge.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 067f06f35a..c6a30ac392 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2427,6 +2427,11 @@ "symbol": "RelocateOptions", "source": "packages/session/working-directory/src/index.ts" }, + { + "doc": "docs/subsystems/working-directory.md", + "symbol": "InheritOptions", + "source": "packages/session/working-directory/src/index.ts" + }, { "doc": "docs/subsystems/working-directory.md", "symbol": "RelocatedDirectories",