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

Review of the consumers layer:

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

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

No files matched your search

+7 -5
View File
@@ -445,13 +445,15 @@ export class WorktreeService extends Service {
}
/**
* The Session's policy bounded by the source checkout of a recorded worktree, with that checkout's
* shared Git directory derived. Removal and restoration run in the source checkout, which contains
* the worktree directory; the Session's own root may be that directory, removed or being removed.
* The policy removal and restoration run under: the Session's mode and grants, bounded by the source
* checkout of the recorded worktree instead of the Session's own root, which may be the worktree
* directory, removed or being removed. A linked source checkout's shared Git directory is granted too.
*/
private async sourcePolicy(session: Session, repositoryRoot: string, signal: AbortSignal): Promise<SandboxExecutionPolicy> {
await this.ctx.sandboxPolicy.prepare({ session, root: repositoryRoot }, signal)
return this.ctx.sandboxPolicy.resolve({ session, root: repositoryRoot })
const shared = await this.ctx.sandboxPolicy.prepare({ directory: repositoryRoot }, signal)
const policy = this.ctx.sandboxPolicy.resolve({ session })
const additional = [...new Set([...policy.additionalWritableRoots ?? [], ...shared])]
return { ...policy, workspaceRoot: repositoryRoot, ...additional.length === 0 ? {} : { additionalWritableRoots: additional } }
}
/** Confine Git commands to the caller's sandbox policy, collecting bounded stdout. */
@@ -131,7 +131,7 @@ describe('archive-triggered worktree cleanup', () => {
const head = await git(f.worktree.path, 'rev-parse', 'HEAD')
const statuses: WorktreeCleanup['status'][] = []
f.ctx.on('worktree/cleanup', ({ cleanup }) => { statuses.push(cleanup.status) })
const resolve = vi.spyOn(f.ctx.sandboxPolicy, 'resolve')
const prepare = vi.spyOn(f.ctx.sandboxPolicy, 'prepare')
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
expect(await f.ctx.worktrees.cleanupOf(f.session, null)).toMatchObject({ status: 'scheduled' })
expect(await settled(f)).toMatchObject({ status: 'removed' })
@@ -141,8 +141,7 @@ describe('archive-triggered worktree cleanup', () => {
expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id)
// The creator's root is the checkout being removed; its commands are bounded by the source checkout instead.
expect(f.ctx.workingDirectory.get(f.session)).toBe(f.worktree.path)
const roots = resolve.mock.calls.filter(([request]) => request?.session === f.session).map(([request]) => request?.root)
expect(roots).toEqual([undefined, f.root])
expect(prepare).toHaveBeenCalledWith({ directory: f.root }, expect.any(AbortSignal))
})
it('removes a clean checkout whose file listing exceeds maxOutputBytes', async () => {
@@ -137,6 +137,32 @@ describe.skipIf(!sandboxUsable)('worktree standing sandbox policy', () => {
expect(fetches[0]![1]).toMatchObject({ mode: 'workspace-write', workspaceRoot: linked, additionalWritableRoots: [join(clone, '.git')] })
})
it('restores a missing worktree of a linked source checkout in a process that never worked in it', async () => {
root = await repository(process.cwd())
const linked = join(root, 'linked')
await git(root, 'worktree', 'add', '-b', 'linked', linked)
const first = await harness(linked, {}, 'workspace-write')
let created
try {
created = await first.worktrees.create(testAgent(first, linked), { name: 'cold' })
} finally {
await first.fiber.dispose()
}
await rm(created.path, { recursive: true, force: true })
// A new process: nothing is derived yet, and the Session's own root no longer exists.
ctx = await harness(linked, {}, 'workspace-write')
const agent = testAgent(ctx, linked, 'cold-resumed')
agent.session.append('workspace-root/change', { cwd: created.path })
expect(ctx.workingDirectory.get(agent.session)).toBe(created.path)
const confine = vi.spyOn(ctx.sandbox, 'confine')
expect(await ctx.worktrees.restore(agent, created)).toEqual({ path: created.path, branchRecreated: false })
// The source checkout's shared Git directory lies outside it; the worktree service adds the derived grant.
expect(await git(created.path, 'branch', '--show-current')).toBe('cold')
expect(confine.mock.calls.every(call => call[1].workspaceRoot === linked && call[1].additionalWritableRoots?.includes(join(root!, '.git')))).toBe(true)
})
it('restores a removed worktree under the source checkout boundary while the Session root is the removed directory', async () => {
root = await repository(process.cwd())
ctx = await harness(root, {}, 'workspace-write')