subagent: seed inherited policy events at creation

The parent implementation introduced sandboxMode and approvalPolicy as generic SessionHeader fields, then propagated those fields through both persistence backends, session-query indexes, collision checks, policy-specific seed-boundary folds, catalogs, and a broad test matrix. That storage plane is unnecessary: Session already accepts a validated constructor seed, and persistence captures that seed when the session is announced before committing its first batch.

Capture each parent override synchronously at delegation, append source-tagged sandbox/mode and approval/policy records after the optional fork prefix, and create the child with that combined seed. Keeping header.seedLength at the original fork-prefix length preserves lineage while ordinary last-event-wins folds make the inherited records outrank stale parent history and remain subordinate to later child switches. Unswitched parents still stamp nothing, so children continue to follow deployment defaults.

Remove the generic header fields and every persistence/query/schema branch built around them. Collapse the inheritance suite from ten leaking scenarios to four owned-context cases covering real filesystem confinement, stale fork precedence, delegation-time capture, and the no-override path. The assembled headless snapshot now asserts the persisted inheritance event directly.

This keeps the security behavior while restoring policy ownership to the existing event log and deleting the speculative durability machinery that the original tests did not exercise.
This commit is contained in:
Tianyi Cui
2026-07-28 21:31:17 +08:00
parent afa38c4b2f
commit cfceb8452b
55 changed files with 415 additions and 1371 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/sandbox/sandbox-policy/README.md
README.md: 3e569cebb22cbed9d25642b7208e33e97041323e
README.zh.md: 2d1c30f9d79eada9b38785113a880c4760c7d0f1
README.md: dca54330bc888af9ecac21aa92019d8a2b0140bd
README.zh.md: abf2d9fb8830fdcaf7f1357b393b434de4a5ad8d

View File

@@ -15,18 +15,17 @@ Two families enforce the same mode vocabulary: the sandboxed bash executor (`@de
## Surface
- `ctx.sandboxPolicy.resolve({ session?, mode? })` — resolves one complete per-call policy. An explicit approved mode outranks the session's override chain (`overrideOf`, below), which outranks `defaultMode`; the session's immutable `cwd` is canonicalized with filesystem semantics before becoming `workspaceRoot`, otherwise the configured fallback applies. Canonicalization precedes lexical normalization so `symlink/..` agrees with process working-directory resolution.
- `ctx.sandboxPolicy.resolve({ session?, mode? })` — resolves one complete per-call policy. An explicit approved mode outranks the session's last `sandbox/mode` event, which outranks `defaultMode`; the session's immutable `cwd` is canonicalized with filesystem semantics before becoming `workspaceRoot`, otherwise the configured fallback applies. Canonicalization precedes lexical normalization so `symlink/..` agrees with process working-directory resolution.
- `ctx.sandboxPolicy.defaultMode` / `ctx.sandboxPolicy.workspaceRoot` — the deployment default and fallback root used by `resolve()`.
- `effectiveSandboxMode(events)` — the pure fold of a slice of `sandbox/mode` events (the last switch wins, or `undefined`), the building block `sandboxOverrideOf` composes with the seed boundary and the header baseline.
- `effectiveSandboxMode(events)` — the pure fold of a session's `sandbox/mode` events (the last switch wins, or `undefined`), used inside `resolve()`.
- `setSandboxMode(session, mode)` — THE write path for a per-session override: appends exactly one `sandbox/mode` event. The switch IS its event; nothing mutates the mode out of band.
- `ctx.sandboxPolicy.overrideOf(session)` (the pure `sandboxOverrideOf` export, also consumed by the permission presets) — the session's override chain, never the deployment default: with an inherited `sandboxMode` header baseline (a delegation child), the fold of the session's OWN switches past `SessionHeader.seedLength`, else the baseline, validated against the closed vocabulary on read (throws on foreign values — a durable boundary); without one (a top-level session or a generic `SessionStore.fork` child), the whole-log fold, so seed-carried switches remain the replayed inherited truth. The in-process subagent driver captures this at delegation and writes it into each child's creation-time header, so a delegating parent's tightened mode binds its children with no first-turn timing window ([rationale](../../../.agents/notes/implemented/feature/2026-07-25-subagent-policy-inheritance.md)).
- `SANDBOX_MODES` — every mode, for option advertisement and runtime validation.
The optional `./invariant` companion rejects a forged durable `sandbox/mode` event whose value falls outside that closed vocabulary; Session and its companion own the surrounding storage and core execution-enclosure rules.
## The per-session store
A runtime switch is one log-only `sandbox/mode` event on the session it applies to. `effective = explicit grant ?? override chain ?? deployment default`, where the override chain is `sandboxOverrideOf`'s fold of the session's OWN post-seed switches, else the inherited header baseline — so an override survives restart by replay, a delegation child starts under its parent's captured policy, and two sessions never see each other's state. Workspace identity does not need another event: the immutable `SessionHeader.cwd` recorded at creation is the root for every call in that session. The event is log-only (the `approval/*` precedent): the model learns the mode from the enforcing tools' denial markers, never from the event.
A runtime switch is one log-only `sandbox/mode` event on the session it applies to. `effective = explicit grant ?? fold(events) ?? deployment default`, so an override survives restart by replay and two sessions never see each other's state. Workspace identity does not need another event: the immutable `SessionHeader.cwd` recorded at creation is the root for every call in that session. The event is log-only (the `approval/*` precedent): the model learns the mode from the enforcing tools' denial markers, never from the event.
## Model Experience

View File

@@ -15,18 +15,17 @@
## 表层
- `ctx.sandboxPolicy.resolve({ session?, mode? })`:解析一项完整的逐调用策略。显式批准的模式优先于会话的覆盖链(见下文 `overrideOf`,后者又优先于 `defaultMode`;会话不可变的 `cwd` 会先按文件系统语义规范化,再成为 `workspaceRoot`,否则使用配置的回退值。规范化先于词法归一化,因此 `symlink/..` 与进程工作目录解析保持一致。
- `ctx.sandboxPolicy.resolve({ session?, mode? })`:解析一项完整的逐调用策略。显式批准的模式优先于会话最后一条 `sandbox/mode` 事件,后者又优先于 `defaultMode`;会话不可变的 `cwd` 会先按文件系统语义规范化,再成为 `workspaceRoot`,否则使用配置的回退值。规范化先于词法归一化,因此 `symlink/..` 与进程工作目录解析保持一致。
- `ctx.sandboxPolicy.defaultMode``ctx.sandboxPolicy.workspaceRoot``resolve()` 使用的部署默认值与回退根。
- `effectiveSandboxMode(events)`对一段 `sandbox/mode` 事件切片的纯折叠(最后一次切换胜出,没有则为 `undefined` `sandboxOverrideOf` 与种子边界和会话头基线进行组合时所用的基础构件
- `effectiveSandboxMode(events)`会话 `sandbox/mode` 事件的纯 fold(最后一次切换胜出,没有则为 `undefined` `resolve()` 内使用
- `setSandboxMode(session, mode)`:逐会话覆盖的唯一写入路径:恰好追加一条 `sandbox/mode` 事件。切换本身就是事件;不会在带外修改模式。
- `ctx.sandboxPolicy.overrideOf(session)`(即纯函数导出 `sandboxOverrideOf`,也供权限 preset 消费):会话的覆盖链,绝不包含部署默认值:当存在继承的 `sandboxMode` 会话头基线时(即委派子 agent先折叠会话自己在 `SessionHeader.seedLength` 之后的切换,否则取该基线,读取时按封闭词汇校验(遇到词汇之外的值即抛出异常——这是一条持久边界);没有基线时(顶层会话或通用的 `SessionStore.fork` 子会话),折叠覆盖完整日志,因此种子携带的切换仍是回放所得的继承事实。进程内 subagent 驱动器在委派时捕获该值,并写入每个子 agent 创建时的会话头,使发起委派的父级收紧后的模式约束其子 agent且不存在任何第一轮次的时序窗口参见[设计原理](../../../.agents/notes/implemented/feature/2026-07-25-subagent-policy-inheritance.md))。
- `SANDBOX_MODES`:所有模式,用于选项展示与运行时验证。
可选的 `./invariant` 配套组件会拒绝伪造的持久 `sandbox/mode` 事件只要其值不在该封闭词汇中Session 与其配套组件拥有周围的存储与核心执行封闭规则。
## 逐会话 store
运行时切换是在对应会话日志中追加的一条 `sandbox/mode` 事件。`effective = explicit grant ?? override chain ?? deployment default`其中覆盖链override chain`sandboxOverrideOf` 折叠会话自己在种子之后的切换所得,否则取继承的会话头基线——因此覆盖会通过回放跨重启保留,委派子 agent 会在其父级捕获的策略下启动两个会话也绝不会看到彼此状态。Workspace 标识无需另一条事件:创建时记录的不可变 `SessionHeader.cwd` 是该会话每次调用使用的根。该事件只进入日志(沿用 `approval/*` 先例):模型通过强制执行工具的拒绝标记获知模式,绝不会从事件获知。
运行时切换是在对应会话日志中追加的一条 `sandbox/mode` 事件。`effective = explicit grant ?? fold(events) ?? deployment default`因此覆盖会通过回放跨重启保留两个会话也绝不会看到彼此状态。Workspace 标识无需另一条事件:创建时记录的不可变 `SessionHeader.cwd` 是该会话每次调用使用的根。该事件只进入日志(沿用 `approval/*` 先例):模型通过强制执行工具的拒绝标记获知模式,绝不会从事件获知。
## 模型体验

View File

@@ -19,9 +19,9 @@ import { Context, Service } from 'cordis'
import z from 'schemastery'
import { canonicalPath, type SandboxExecutionPolicy, type SandboxMode } from '@deepseek-ai/dsh-sandbox'
import type { Session } from '@deepseek-ai/dsh-session'
import { sandboxOverrideOf } from './session-mode.ts'
import { effectiveSandboxMode } from './session-mode.ts'
export { SANDBOX_MODES, effectiveSandboxMode, sandboxOverrideOf, setSandboxMode } from './session-mode.ts'
export { SANDBOX_MODES, effectiveSandboxMode, setSandboxMode } from './session-mode.ts'
/** Resolve filesystem identity before lexical normalization can erase symlink-sensitive components. */
function resolveWorkspaceRoot(path: string): string {
@@ -90,36 +90,28 @@ export class SandboxPolicyService extends Service {
/**
* Resolve the complete policy for one capability call. An approved explicit
* mode outranks the session's override chain ({@link overrideOf}: own
* post-seed switches, else the inherited header baseline), which outranks
* the deployment default. A session cwd is its workspace-write boundary;
* the configured root is the fallback for agentless calls and sessions
* without a cwd.
* mode outranks the session's last `sandbox/mode` event, which outranks the
* deployment default. A session cwd is its workspace-write boundary; the
* configured root is the fallback for agentless calls and sessions without a
* cwd.
* @param request - optional session and approved mode override.
* @returns the fully resolved per-call mode and absolute workspace root.
*/
resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy {
const { session } = request
// Resolve the session override FIRST even when an explicit approved mode
// outranks it: the unconditional durable-header validation must hold on
// every resolution — a one-shot grant is not a validation bypass.
const override = session === undefined ? undefined : this.overrideOf(session)
return {
mode: request.mode ?? override ?? this.defaultMode,
mode: request.mode ?? (session === undefined ? undefined : this.overrideOf(session)) ?? this.defaultMode,
workspaceRoot: resolveWorkspaceRoot(session?.header.cwd ?? this.workspaceRoot),
}
}
/**
* {@link sandboxOverrideOf} surfaced on the service, for consumers that
* reach policy through `ctx.get('sandboxPolicy')` (the subagent driver's
* delegation capture, pty-local) rather than a value import.
* @param session - the session whose override chain to resolve.
* @returns the effective override, or `undefined` for a session following
* the deployment default.
* Read the session override without applying the deployment default.
* @param session - session whose log supplies the override.
* @returns the last logged mode, or `undefined` without one.
*/
overrideOf(session: Session): SandboxMode | undefined {
return sandboxOverrideOf(session)
return effectiveSandboxMode(session.events)
}
}

View File

@@ -1,19 +1,15 @@
/**
* Per-session sandbox-mode override: the session log as the store, layered
* over the header's delegation baseline. A runtime switch (a UI policy
* control or test scenario) is recorded as one `sandbox/mode` event on the
* session it applies to; `effective = override chain ?? the deployment
* default`, where the override chain ({@link sandboxOverrideOf}) is the fold
* of the session's OWN post-seed switches, else the inherited
* `SessionHeader.sandboxMode` baseline. An override survives restart by
* replay, a delegation child starts under its parent's captured policy, two
* sessions can never see each other's state, and there is no external config
* store. The event is log-only (the `approval/*` precedent): the model
* learns the mode from the boundary markers in the enforcing tools, never
* from the event itself. EXECUTION honors the chain through
* `ctx.sandboxPolicy.resolve()` — it stamps the mode together with the
* calling session's workspace root onto each capability call,
* weakest-precedence beneath an escalation grant.
* Per-session sandbox-mode override: the session log as the store. A runtime
* switch (a UI policy control or test scenario) is recorded as one
* `sandbox/mode` event on the session it applies to;
* `effective = fold(events) ?? the deployment default`, so an override
* survives restart by replay, two sessions can never see each other's state,
* and there is no external config store. The event is log-only (the
* `approval/*` precedent): the model learns the mode from the boundary
* markers in the enforcing tools, never from the event itself. EXECUTION
* honors the fold through `ctx.sandboxPolicy.resolve()` — it stamps the mode
* together with the calling session's workspace root onto each capability
* call, weakest-precedence beneath an escalation grant.
*
* The override is policy state shared by every enforcing family (bash and
* filesystem alike), so it lives here in the policy package rather than in any
@@ -30,13 +26,15 @@ declare module '@deepseek-ai/dsh-session' {
/**
* The session's sandbox mode was switched — log-only (like `approval/*`;
* NOT a surface event, carries no `surfaceOp`): durable and replayable,
* never in the model transcript. The last such OWN (post-seed) event is
* the session's override ({@link sandboxOverrideOf}); who asked for it is
* derivable from position (an event after the log's last
* `request/header*` was a runtime switch by the user; see the tool
* layer's narrator).
* never in the model transcript. The LAST such event is the session's
* override ({@link effectiveSandboxMode}). `source: 'delegation'` marks
* an override seeded into a child; an absent source is a runtime switch.
*/
'sandbox/mode': { mode: SandboxMode }
'sandbox/mode': {
mode: SandboxMode
/** Marks an override seeded into a child at delegation. */
source?: 'delegation'
}
}
}
@@ -44,11 +42,10 @@ declare module '@deepseek-ai/dsh-session' {
export const SANDBOX_MODES: readonly SandboxMode[] = ['read-only', 'workspace-write', 'danger-full-access']
/**
* The pure fold of a slice of `sandbox/mode` events: the last switch wins,
* or undefined without one. The building block {@link sandboxOverrideOf}
* composes with the seed boundary and the header baseline — consumers
* resolving a SESSION's policy go through that chain, not this raw fold.
* Resume needs no catch-up machinery because replaying the log IS the state.
* The session's sandbox-mode override: the last `sandbox/mode` event in the
* log, or undefined when the session never switched (callers apply the
* deployment default). The pure fold — resume needs no catch-up machinery
* because replaying the log IS the state.
* @param events - session events in log order (other event types are skipped).
* @returns the mode of the last switch event, or undefined without one.
*/
@@ -60,41 +57,6 @@ export function effectiveSandboxMode(events: readonly SessionEvent[]): SandboxMo
return undefined
}
/**
* The session's complete sandbox-mode OVERRIDE chain — the one home every
* consumer (the policy service, the permission presets) resolves through.
* With a header baseline (a delegation child), the fold covers only the
* session's OWN switches past the seed boundary — the baseline was captured
* from the parent's FULL log at delegation, so any seed-carried switch is
* already subsumed by it, stale or not. Without a baseline (a top-level
* session, or a generic `SessionStore.fork` child that captured no policy
* meta), the fold covers the whole log: seeded switches ARE the replayed
* inherited truth, and slicing them away would silently widen the child to
* the deployment default. Never the deployment default itself. The durable
* baseline is validated UNCONDITIONALLY — a corrupt or foreign header must
* fail loud on every read, not only when no own switch happens to shadow it.
* @param session - the session whose override chain to resolve.
* @returns the effective override, or `undefined` for a session following
* the deployment default.
* @throws when the header baseline is outside the closed mode vocabulary.
*/
export function sandboxOverrideOf(session: Session): SandboxMode | undefined {
const baseline = session.header.sandboxMode
if (baseline === undefined) return effectiveSandboxMode(session.events)
if (!SANDBOX_MODES.includes(baseline as SandboxMode)) {
throw new Error(`session header sandboxMode "${baseline}" is outside the closed mode vocabulary`)
}
// A boundary past the log would make the own-switch slice empty until the
// log grows past it — a wide baseline would then shadow a REAL later
// tightening. Malformed durable metadata fails loud, never fails open.
const seedLength = session.header.seedLength ?? 0
if (seedLength > session.events.length) {
throw new Error(`session header seedLength ${seedLength} exceeds the log length ${session.events.length}`)
}
const own = effectiveSandboxMode(session.events.slice(seedLength))
return own ?? baseline as SandboxMode
}
/**
* THE write path for a session's sandbox-mode override: appends exactly one
* `sandbox/mode` event — the switch IS its event; nothing mutates mode state

View File

@@ -63,6 +63,8 @@ describe('SandboxPolicyService', () => {
mode: 'read-only',
workspaceRoot: resolve('/projects/second'),
})
expect(ctx.sandboxPolicy.overrideOf(first)).toBeUndefined()
expect(ctx.sandboxPolicy.overrideOf(second)).toBe('read-only')
expect(ctx.sandboxPolicy.resolve()).toEqual({
mode: 'workspace-write',
workspaceRoot: resolve('/fallback'),
@@ -142,100 +144,3 @@ describe('the sandbox/mode session kit', () => {
expect(modeEvents[0]?.data).toEqual({ mode: 'danger-full-access' })
})
})
describe('delegation inheritance (overrideOf over the header baseline)', () => {
/** A session whose header carries the delegation-inheritance baseline. */
function inheritedSession(id: string, meta: { sandboxMode?: string; seedLength?: number } = {}): Session {
const sessionId = SessionId(id)
return new Session(sessionId, undefined, {
version: 0,
id: sessionId,
createdAt: 0,
...meta.sandboxMode === undefined ? {} : { sandboxMode: meta.sandboxMode },
...meta.seedLength === undefined ? {} : { seedLength: meta.seedLength },
})
}
it('overrideOf folds the session log and never falls back to the deployment default', async () => {
const ctx = await mounted({ mode: 'workspace-write' })
const parent = session('sess-inherit-parent')
setSandboxMode(parent, 'workspace-write')
setSandboxMode(parent, 'read-only')
expect(ctx.sandboxPolicy.overrideOf(parent)).toBe('read-only')
// undefined, NOT the deployment default — a child whose header froze the
// default would stop following the LIVE default across resumes.
expect(ctx.sandboxPolicy.overrideOf(session('sess-inherit-unswitched'))).toBeUndefined()
})
it('overrideOf reads the header baseline when the log has no own switch', async () => {
const ctx = await mounted({ mode: 'workspace-write' })
const child = inheritedSession('sess-inherit-baseline', { sandboxMode: 'read-only' })
expect(ctx.sandboxPolicy.overrideOf(child)).toBe('read-only')
// resolve() consumes the same chain, so enforcement sees the baseline.
expect(ctx.sandboxPolicy.resolve({ session: child }).mode).toBe('read-only')
})
it('a seed-carried stale switch loses to the baseline; an OWN later switch wins over it', async () => {
const ctx = await mounted({ mode: 'workspace-write' })
// The fork seed carried the parent's OLD workspace-write switch (one
// event, so seedLength 1); the delegation-time baseline is read-only.
const child = inheritedSession('sess-inherit-slice', { sandboxMode: 'read-only', seedLength: 1 })
setSandboxMode(child, 'workspace-write')
expect(ctx.sandboxPolicy.overrideOf(child)).toBe('read-only')
// A switch the child makes ITSELF (after the seed boundary) outranks it.
setSandboxMode(child, 'danger-full-access')
expect(ctx.sandboxPolicy.overrideOf(child)).toBe('danger-full-access')
})
it('rejects a header baseline outside the closed mode vocabulary (durable boundary)', async () => {
const ctx = await mounted()
const child = inheritedSession('sess-inherit-invalid', { sandboxMode: 'yolo' })
expect(() => ctx.sandboxPolicy.overrideOf(child)).toThrow(/sandboxMode/)
})
it('rejects a malformed baseline even when an own switch would win (validation is unconditional)', async () => {
const ctx = await mounted()
const child = inheritedSession('sess-inherit-invalid-own', { sandboxMode: 'yolo' })
// A corrupt or foreign durable record must fail loud on EVERY read — an
// own override must not paper over the malformed header.
setSandboxMode(child, 'read-only')
expect(() => ctx.sandboxPolicy.overrideOf(child)).toThrow(/sandboxMode/)
})
it('a generic SessionStore.fork child (seedLength, NO baseline) keeps its seed-carried override', async () => {
const ctx = await mounted({ mode: 'workspace-write' })
// The public fork path sets seedLength but captures no delegation
// baseline; the seed boundary must not discard the replayed policy state
// it exists to subsume — with nothing to subsume it, seeded switches ARE
// the child's inherited truth.
const child = inheritedSession('sess-generic-fork', { seedLength: 1 })
setSandboxMode(child, 'read-only')
expect(ctx.sandboxPolicy.overrideOf(child)).toBe('read-only')
expect(ctx.sandboxPolicy.resolve({ session: child }).mode).toBe('read-only')
})
it('rejects a seed boundary past the log end instead of silently ignoring own switches', async () => {
const ctx = await mounted()
// A malformed durable seedLength beyond the log would make the own-switch
// slice empty until the log grows past it — a wide baseline would then
// shadow a REAL later tightening. Fail loud at the durable boundary.
const child = inheritedSession('sess-inherit-oob', { sandboxMode: 'danger-full-access', seedLength: 100 })
setSandboxMode(child, 'read-only')
expect(() => ctx.sandboxPolicy.overrideOf(child)).toThrow(/seedLength/)
})
it('resolve() validates the durable header even when an explicit approved mode is supplied', async () => {
const ctx = await mounted()
const child = inheritedSession('sess-resolve-invalid', { sandboxMode: 'yolo' })
// The explicit one-shot grant must not become a validation bypass: the
// unconditional durable-header contract holds on EVERY resolution.
expect(() => ctx.sandboxPolicy.resolve({ session: child, mode: 'workspace-write' })).toThrow(/sandboxMode/)
})
})