Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server,core): 沙箱在绑定 Session scratchpad 之前先把它建出来(上游 cba091e3 移植)

lmliheng8b257785323b
diff --git a/changelog/unreleased/2026-10-08-sandbox-missing-scratchpad.md b/changelog/unreleased/2026-10-08-sandbox-missing-scratchpad.md
new file mode 100644
index 00000000..a6ca19f3
--- /dev/null
+++ b/changelog/unreleased/2026-10-08-sandbox-missing-scratchpad.md
@@ -0,0 +1,22 @@
+# Commands start in the sandbox before the Session scratchpad exists, or after it is deleted
+
+- **Date:** 2026-10-08
+- **Type:** fix
+- **Scope:** `server`, `core`
+
+[中文版](2026-10-08-sandbox-missing-scratchpad.zh.md)
+
+Under `workspace-write`, the Session scratchpad is bound writable into the sandbox. It is created
+only when something is first written into it, and a command, an agent or the user can remove it
+while the Session lives. While it was missing, bubblewrap — the Linux backend and the one inside
+the Windows WSL backend — refused to start on the missing bind source, so every command and hook of
+that Session failed. Ported from upstream PenguinHarness (#976, commit `cba091e3`), which the fork
+did not carry.
+
+- Under `workspace-write`, the sandbox service creates the Session scratchpad before each confined
+ spawn when it is missing, and leaves an existing one untouched. Other modes do not bind it and do
+ not create it.
+- When the scratchpad cannot be created, the command fails with an error naming the scratchpad and
+ the underlying errno; it does not run without the scratchpad.
+- `SandboxPolicy.writableRoots` documents that each root exists on the host when a backend receives
+ the policy, and that a backend neither creates nor skips one.
diff --git a/changelog/unreleased/2026-10-08-sandbox-missing-scratchpad.zh.md b/changelog/unreleased/2026-10-08-sandbox-missing-scratchpad.zh.md
new file mode 100644
index 00000000..af744f8e
--- /dev/null
+++ b/changelog/unreleased/2026-10-08-sandbox-missing-scratchpad.zh.md
@@ -0,0 +1,19 @@
+# Session scratchpad 尚未创建或已被删除时,沙盒内的命令照常启动
+
+- **Date:** 2026-10-08
+- **Type:** fix
+- **Scope:** `server`, `core`
+
+[English](2026-10-08-sandbox-missing-scratchpad.md)
+
+`workspace-write` 下,Session scratchpad 以可写方式绑定进沙盒。它只在第一次有东西写入时才被创建,
+Session 存续中也可能被某条命令、Agent 或用户删掉。它缺失期间,bubblewrap(Linux 后端,以及 Windows
+WSL 后端内部所用的那一个)会因绑定挂载的源路径不存在而拒绝启动,该 Session 的每一条命令和每一个 hook
+都起不来。本次从上游 PenguinHarness 移植(#976,提交 `cba091e3`),此前本 fork 没有这一条。
+
+- `workspace-write` 下,沙盒服务在每次受约束的 spawn 之前,若 Session scratchpad 不存在就先创建它;
+ 已存在时不做任何改动。其他模式不绑定它,也不创建它。
+- scratchpad 建不出来时,命令以点明 scratchpad 与底层 errno 的错误失败,不会在没有 scratchpad 的
+ 情况下继续运行。
+- `SandboxPolicy.writableRoots` 的文档写明:后端收到策略时,每个可写根在宿主上都已存在;后端既不创建
+ 它,也不跳过缺失的根。
diff --git a/packages/core/src/plugin/sandbox.ts b/packages/core/src/plugin/sandbox.ts
index 618d8b93..e2ec2ca1 100644
--- a/packages/core/src/plugin/sandbox.ts
+++ b/packages/core/src/plugin/sandbox.ts
@@ -63,9 +63,15 @@ export interface SandboxPolicy {
/**
* Further absolute directories `workspace-write` may write under, beside the workspace:
* the Session's scratchpad, where the plan file, a goal's state file and the
- * attachments live. Meaningless under `read-only`. A backend that does not implement
- * the field confines more narrowly than asked, never more widely, so no dimension
- * guards it.
+ * attachments live. The service sets it only under `workspace-write`. A backend that
+ * does not implement the field confines more narrowly than asked, never more widely, so
+ * no dimension guards it.
+ *
+ * Each root EXISTS on the host by the time a backend is handed the policy: the service
+ * creates it first (the scratchpad is made lazily, and can be removed mid-Session), and
+ * refuses the spawn when it cannot. A backend neither creates a root nor skips a missing
+ * one. `workspaceRoot` is not covered: a missing Workspace is a different error, and
+ * surfaces as such.
*/
writableRoots?: readonly string[];
/**
diff --git a/packages/server/src/sandbox/service.ts b/packages/server/src/sandbox/service.ts
index 5ffbc1e0..4a667296 100644
--- a/packages/server/src/sandbox/service.ts
+++ b/packages/server/src/sandbox/service.ts
@@ -11,6 +11,7 @@
* covers fails closed — never a silent unconfined run, and never a silently dropped
* dimension.
*/
+import fs from "node:fs";
import type { SpawnConfiner } from "@lmliheng/penguin-core";
import type {
SandboxDimension,
@@ -217,6 +218,15 @@ export class SandboxService {
// short-circuit is "no confinement dimension beyond fs-write", not "mode is full".
if (settings.mode === "danger-full-access" && required.length === 1) return { argv };
const provider = this.pick(required, settings.mode);
+ // Only workspace-write binds further writable roots; under read-only (or full access
+ // with a network cut) every backend ignores them, so neither the field nor the
+ // directory is made there.
+ const scratchpadDir = settings.mode === "workspace-write" ? opts.scratchpadDir : undefined;
+ // The Session's scratchpad is created lazily (on the first thing written into it), and a
+ // command, an agent or the user can remove it mid-Session, but a backend binding it needs
+ // it on disk: bubblewrap refuses to start on a missing bind source. Ensured on every
+ // spawn, here, where every confined spawn meets — see SandboxPolicy.writableRoots.
+ if (scratchpadDir !== undefined) ensureScratchpad(scratchpadDir);
// workspaceRoot is the Session's Workspace, never the per-command cwd: a command
// running in a workdir outside the Workspace must not widen the writable roots.
const policy: SandboxPolicy = {
@@ -224,7 +234,7 @@ export class SandboxService {
workspaceRoot: opts.workspaceDir,
// The Session's scratchpad is writable beside the Workspace: the plan file, a goal's
// state file and the attachments live there, and hooks and commands both write it.
- ...(opts.scratchpadDir !== undefined ? { writableRoots: [opts.scratchpadDir] } : {}),
+ ...(scratchpadDir !== undefined ? { writableRoots: [scratchpadDir] } : {}),
...(settings.network !== undefined ? { network: settings.network } : {}),
...(settings.maskPaths !== undefined && settings.maskPaths.length > 0
? { maskPaths: settings.maskPaths }
@@ -268,6 +278,29 @@ export class SandboxService {
}
}
+/**
+ * Creates the Session's scratchpad if it is missing (a no-op when it exists). A failure
+ * throws, fail-closed: dropping the root and confining without it would start the command
+ * but leave it unable to write the directory it was told it may write.
+ *
+ * Known race, left as is: deleting a Session removes its scratchpad, and a run that outlives
+ * the delete (a command still being spawned for it) recreates the directory here. The cost is
+ * an empty, orphaned directory under the Agent's scratchpad that nothing cleans up; it holds
+ * only what that last run writes, and no access outlives the Session.
+ */
+function ensureScratchpad(dir: string): void {
+ try {
+ fs.mkdirSync(dir, { recursive: true });
+ } catch (err) {
+ // A filesystem error's message leads with its errno (`EACCES: permission denied, …`).
+ throw new Error(
+ `cannot prepare the Session scratchpad ${dir} for the sandbox ` +
+ `(${err instanceof Error ? err.message : String(err)}); refusing to run the command without it.`,
+ { cause: err },
+ );
+ }
+}
+
function copySettings(settings: SandboxSettings): SandboxSettings {
return {
mode: settings.mode,
diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.ts
index 35eeca73..9d93f54d 100644
--- a/packages/server/test/sandbox.test.ts
+++ b/packages/server/test/sandbox.test.ts
@@ -3,7 +3,10 @@
* dimensions, capability routing across backends, fail-closed refusal, and the
* settings' ride on the parked platform context.
*/
-import { describe, expect, it, vi } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
import { boot, initialDoc, parseManifest } from "@lmliheng/penguin-core/kernel";
import type { Json } from "@lmliheng/penguin-core/kernel";
import { HotResources } from "@lmliheng/penguin-hmr";
@@ -39,6 +42,17 @@ function fake(label: string, dimensions?: readonly SandboxDimension[]) {
return { provider, calls };
}
+const tmpDirs: string[] = [];
+/** A fresh directory on disk, for the cases where the confiner touches the scratchpad. */
+function tmp(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adelie-sandbox-svc-"));
+ tmpDirs.push(dir);
+ return dir;
+}
+afterAll(() => {
+ for (const dir of tmpDirs) fs.rmSync(dir, { recursive: true, force: true });
+});
+
async function service(entries: Array<[string, SandboxProviderSource]>): Promise<SandboxService> {
const svc = new SandboxService(entries);
await svc.whenReady();
@@ -159,18 +173,76 @@ describe("sandbox service — the built-in interface and its optional dimensions
});
it("the Session's scratchpad reaches the backend as a further writable root, and without one no such field does", async () => {
+ const scratchpad = path.join(tmp(), "scratchpad", "session-1");
const dsh = fake("dsh");
const svc = await service([["dsh-local", dsh.provider]]);
const confine = svc.confinerFor(() => ({ mode: "workspace-write" }));
- confine([...ARGV], { ...OPTS, scratchpadDir: "/data/agent/scratchpad/session-1" });
+ confine([...ARGV], { ...OPTS, scratchpadDir: scratchpad });
confine([...ARGV], OPTS);
expect(dsh.calls[0]).toMatchObject({
workspaceRoot: "/work/project",
- writableRoots: ["/data/agent/scratchpad/session-1"],
+ writableRoots: [scratchpad],
});
expect(dsh.calls[1]).not.toHaveProperty("writableRoots");
});
+ it("a scratchpad missing on disk is created before the backend sees it, and an existing one is left as it is", async () => {
+ // bwrap refuses to start on a missing bind source; a command may delete it mid-Session.
+ const scratchpad = path.join(tmp(), "scratchpad", "session-1");
+ const existed: boolean[] = [];
+ const dsh = fake("dsh");
+ const svc = await service([
+ [
+ "dsh-local",
+ {
+ confine(argv, policy) {
+ existed.push(fs.existsSync(policy.writableRoots![0]!));
+ return dsh.provider.confine(argv, policy);
+ },
+ },
+ ],
+ ]);
+ const confine = () =>
+ svc.confinerFor(() => ({ mode: "workspace-write" }))([...ARGV], {
+ ...OPTS,
+ scratchpadDir: scratchpad,
+ });
+ confine();
+ fs.writeFileSync(path.join(scratchpad, "plan.md"), "keep me");
+ confine();
+ expect(fs.readFileSync(path.join(scratchpad, "plan.md"), "utf8")).toBe("keep me");
+ fs.rmSync(scratchpad, { recursive: true });
+ confine();
+ expect(existed).toEqual([true, true, true]);
+ });
+
+ it("a scratchpad that cannot be created fails closed, naming it, instead of confining without it", async () => {
+ // A file where a parent directory belongs fails mkdir for every user, root included.
+ const blocker = path.join(tmp(), "scratchpad");
+ fs.writeFileSync(blocker, "");
+ const dsh = fake("dsh");
+ const svc = await service([["dsh-local", dsh.provider]]);
+ const confine = svc.confinerFor(() => ({ mode: "workspace-write" }));
+ expect(() =>
+ confine([...ARGV], { ...OPTS, scratchpadDir: path.join(blocker, "session-1") }),
+ ).toThrow(/cannot prepare the Session scratchpad .*session-1 for the sandbox \(E[A-Z]+:/);
+ expect(dsh.calls).toHaveLength(0);
+ });
+
+ it("outside workspace-write the scratchpad is neither bound nor created", async () => {
+ const scratchpad = path.join(tmp(), "scratchpad", "session-1");
+ const bwrap = fake("bwrap", ["fs-write", "network"]);
+ const svc = await service([["penguin-bwrap", bwrap.provider]]);
+ for (const policy of [
+ { mode: "read-only" },
+ { mode: "danger-full-access", network: "none" },
+ ] as const)
+ svc.confinerFor(() => policy)([...ARGV], { ...OPTS, scratchpadDir: scratchpad });
+ expect(bwrap.calls).toHaveLength(2);
+ for (const call of bwrap.calls) expect(call).not.toHaveProperty("writableRoots");
+ expect(fs.existsSync(scratchpad)).toBe(false);
+ });
+
it("requiring a dimension nothing implements is refused, naming what each backend does", async () => {
const dsh = fake("dsh");
const svc = await service([["dsh-local", dsh.provider]]);
diff --git a/plugins/sandbox-bwrap/test/live.test.ts b/plugins/sandbox-bwrap/test/live.test.ts
index 111d397f..d2a4c2dc 100644
--- a/plugins/sandbox-bwrap/test/live.test.ts
+++ b/plugins/sandbox-bwrap/test/live.test.ts
@@ -7,15 +7,33 @@
* the profile and the fail-closed path. The backend is driven DIRECTLY here (no
* SandboxService): what a plugin package owes is that its own confinement works, and
* routing/settings are the harness's behavior, tested there with fakes.
+ *
+ * Exception: the last describe drives the server's SandboxService (imported by path; this
+ * package depends on core alone), which creates the scratchpad bwrap binds.
*/
import { afterAll, describe, expect, it } from "vitest";
-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import path from "node:path";
+import { fileURLToPath } from "node:url";
import { CommandSessionManager } from "@lmliheng/penguin-core";
-import type { SandboxPolicy } from "@lmliheng/penguin-core/plugin";
+import type { SpawnConfiner } from "@lmliheng/penguin-core";
+import type { SandboxPolicy, SandboxProviderSource } from "@lmliheng/penguin-core/plugin";
import { createPenguinBwrapProvider } from "../src/index.js";
+/** The slice of the server's SandboxService these cases drive. */
+interface ServiceUnderTest {
+ whenReady(): Promise<void>;
+ confinerFor(policyOf: () => { mode: "workspace-write" }): SpawnConfiner;
+}
+const { SandboxService } = (await import(
+ fileURLToPath(new URL("../../../packages/server/src/sandbox/index.ts", import.meta.url))
+)) as {
+ SandboxService: new (
+ registrations: Iterable<[string, SandboxProviderSource]>,
+ ) => ServiceUnderTest;
+};
+
const ws = mkdtempSync(path.join(tmpdir(), "penguin-bwrap-live-"));
const outsideProbe = path.join(homedir(), `penguin-bwrap-live-${process.pid}.txt`);
const provider = createPenguinBwrapProvider();
@@ -139,3 +157,37 @@ describe.skipIf(!usable)("penguin-bwrap live enforcement (host-gated)", () => {
rmSync(outsideProbe, { force: true });
});
});
+
+describe.skipIf(!usable)("penguin-bwrap behind the sandbox service: the Session scratchpad", () => {
+ it("a command writes to a scratchpad not created yet, or deleted mid-Session", async () => {
+ // Under the read-only home, not /tmp: a file reaching the host came through the bind itself.
+ const agentScratchpad = mkdtempSync(path.join(homedir(), "penguin-bwrap-scratchpad-"));
+ const scratchpad = path.join(agentScratchpad, "session-1");
+ const svc = new SandboxService([["penguin-bwrap", provider]]);
+ await svc.whenReady();
+ const confiner = svc.confinerFor(() => ({ mode: "workspace-write" }));
+ const served = new CommandSessionManager({
+ confineSpawn: () => confiner,
+ workspaceDir: ws,
+ scratchpadDir: scratchpad,
+ });
+ try {
+ for (const file of ["a.txt", "b.txt"]) {
+ // Without the service creating it, bwrap exits first: "Can't find source path".
+ expect(existsSync(scratchpad)).toBe(false);
+ const session = served.spawn({
+ cmd: `echo ${file} > ${JSON.stringify(path.join(scratchpad, file))}`,
+ cwd: ws,
+ });
+ let out = "";
+ for await (const chunk of session.collect(15000)) out += chunk;
+ expect(session.exit?.code, out).toBe(0);
+ expect(readFileSync(path.join(scratchpad, file), "utf8")).toBe(`${file}\n`);
+ rmSync(scratchpad, { recursive: true, force: true });
+ }
+ } finally {
+ served.dispose();
+ rmSync(agentScratchpad, { recursive: true, force: true });
+ }
+ });
+});