Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(sandbox): pluggable sandbox seam with snapshot/rewind and a Docker backend

Rach Pradhan947177253885
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 8a330e53..440532df 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -55,7 +55,8 @@ pub const commands = [_]Item{
.{ .name = "/doctor", .desc = "read-only health check: goal/todo invariants, and why steering will or will not be appended" },
.{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — no tools, billed, never added to the session" },
.{ .name = "/compact", .desc = "compact history into a fresh context (OpenAI server-side when available)" },
- .{ .name = "/rewind", .usage = "/rewind [n]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits" },
+ .{ .name = "/rewind", .usage = "/rewind [n|<snapshot>]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits; /rewind <snapshot id> restores a sandbox filesystem instead, never the conversation" },
+ .{ .name = "/snapshot", .usage = "/snapshot [attach [image]|detach|list]", .desc = "capture the attached sandbox's filesystem under .graff/sessions/<session>/snapshots; attach puts this session in a Docker sandbox, list shows what it has captured" },
.{ .name = "/image", .usage = "/image <path>", .desc = "attach an image to your next message (vision models only)" },
.{ .name = "/images", .desc = "open image URLs from the last response (e.g. issue attachments) in your browser" },
.{ .name = "/paste", .desc = "attach the clipboard image — macOS; also Ctrl-V (⌘V can't be captured)" },
diff --git a/src/commands_sandbox.zig b/src/commands_sandbox.zig
new file mode 100644
index 00000000..04f6a342
--- /dev/null
+++ b/src/commands_sandbox.zig
@@ -0,0 +1,255 @@
+//! #554's REPL surface: `/snapshot` captures the active sandbox's filesystem
+//! into `.graff/sessions/<session>/snapshots/<id>/`, `/rewind <id>` brings one
+//! back up.
+//!
+//! `/rewind` was already taken by the CONVERSATION rewind (commands_model.zig,
+//! `/rewind <n>`), and the two are deliberately the same word: they are the
+//! same gesture on two different substrates. The argument decides which — a
+//! number is a prompt index and falls through to the old handler untouched,
+//! anything else is a snapshot id. This module is dispatched from
+//! commands_session.tryHandle, which runs BEFORE commands_model, so the
+//! numeric path is reached exactly as it was.
+//!
+//! A sandbox rewind restores FILESYSTEM state and nothing else. The
+//! conversation and the event log stay canonical, every output here says so,
+//! and processes inside the sandbox are relaunched rather than resumed.
+//!
+//! Every failure here is an explanation. No sandbox attached, no docker
+//! installed, no such snapshot, a backend that cannot capture at all: each
+//! prints what is true and returns, because a slash command that panics on a
+//! missing container runtime is worse than one that does nothing.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+const ansi = @import("ansi.zig");
+const style = &ansi.style;
+const main_mod = @import("main.zig");
+const sandbox = @import("sandbox.zig");
+const sandbox_docker = @import("sandbox_docker.zig");
+const util = @import("util.zig");
+
+/// The process's Docker backend, once `/snapshot attach` has built one. A
+/// live `Handle` points into a Sandbox that points back here, so this outlives
+/// any one command — the same process-wide shape as sandbox.active().
+var g_docker: sandbox_docker.Docker = undefined;
+
+/// The sentence every rewind output carries. A user who believed the
+/// transcript had moved too would read it as the record of a run that never
+/// happened, so this is pinned by a test rather than left to phrasing.
+pub const log_note = "the conversation and event log are NOT rewound — filesystem state only";
+
+/// True when `/rewind <arg>` means a snapshot rather than a prompt index.
+/// An empty or all-digit argument belongs to the conversation rewind.
+pub fn isSnapshotArg(arg: []const u8) bool {
+ if (arg.len == 0) return false;
+ for (arg) |c| if (!std.ascii.isDigit(c)) return true;
+ return false;
+}
+
+/// What went wrong, in words a user can act on.
+pub fn explain(err: anyerror) []const u8 {
+ return switch (err) {
+ error.SandboxUnavailable => "the sandbox backend is not usable here — `docker` is not on PATH, or the daemon refused the command",
+ error.SnapshotUnsupported => "this backend cannot capture state (the local backend runs without isolation, so there is nothing to snapshot) — attach a Docker sandbox instead",
+ error.SnapshotFailed => "the capture failed — `docker commit`/`docker save` did not succeed",
+ error.RestoreFailed => "the restore failed — `docker load`/`docker run` did not succeed, and the previous sandbox was already released; nothing is attached now, so `/snapshot attach` starts a fresh one",
+ error.ExecFailed => "the sandbox command could not be run",
+ else => "the sandbox operation failed",
+ };
+}
+
+/// `/snapshot` (capture), `/snapshot attach [image]`, `/snapshot detach`,
+/// `/snapshot list`, and `/rewind <id>`. Returns false for anything else,
+/// including `/rewind` with a numeric or absent argument.
+pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
+ if (argOf(line, "/snapshot")) |arg| {
+ if (std.mem.eql(u8, arg, "list") or std.mem.eql(u8, arg, "ls")) {
+ try renderList(root, arena, out);
+ } else if (argOf(arg, "attach")) |image| {
+ try attach(root, image, out);
+ } else if (std.mem.eql(u8, arg, "detach")) {
+ try detach(out);
+ } else {
+ try capture(root, arena, out);
+ }
+ try out.flush();
+ return true;
+ }
+ if (argOf(line, "/rewind")) |arg| {
+ if (!isSnapshotArg(arg)) return false; // the conversation rewind owns it
+ try restore(root, arena, arg, out);
+ try out.flush();
+ return true;
+ }
+ return false;
+}
+
+/// The argument after `cmd`, or null when `line` is a different command.
+/// `/rewinds` is not `/rewind`: the next byte has to be a space or the end.
+fn argOf(line: []const u8, cmd: []const u8) ?[]const u8 {
+ if (!std.mem.startsWith(u8, line, cmd)) return null;
+ const rest = line[cmd.len..];
+ if (rest.len > 0 and rest[0] != ' ' and rest[0] != '\t') return null;
+ return std.mem.trim(u8, rest, " \t");
+}
+
+/// Put this session in a Docker sandbox so there is something to capture.
+/// Nothing attaches one automatically in the MVP — the bot runner and the DGM
+/// trials that #554 exists for will call sandbox.attach directly — so this is
+/// how a person drives the seam by hand.
+fn attach(root: *Agent, image: []const u8, out: *Io.Writer) !void {
+ // One Docker slot per process, and a live Handle points into it, so a
+ // second attach would move the ground under the first. Refusing is the
+ // honest answer; `/snapshot detach` is one keystroke away.
+ if (sandbox.active()) |prev| {
+ try out.print("a sandbox is already attached ({s}) — /snapshot detach first\n", .{prev.handle.id});
+ return;
+ }
+ g_docker = .{
+ .io = root.io,
+ .path_env = main_mod.g_path_env,
+ .image = if (image.len > 0) image else sandbox_docker.default_image,
+ };
+ const backend = g_docker.backend();
+ if (!backend.available()) {
+ try out.print("docker backend: {s}\n", .{explain(error.SandboxUnavailable)});
+ return;
+ }
+ const handle = backend.acquire(root.gpa, root.session_name) catch |err| {
+ try out.print("could not start a sandbox — {s}\n", .{explain(err)});
+ return;
+ };
+ sandbox.attach(.{ .backend = backend, .handle = handle });
+ try out.print("sandbox attached — {s} on {s} (key {s})\n", .{ handle.id, g_docker.image, handle.key });
+}
+
+fn detach(out: *Io.Writer) !void {
+ const act = sandbox.active() orelse {
+ try out.writeAll("no sandbox is attached\n");
+ return;
+ };
+ act.handle.release();
+ sandbox.detach();
+ try out.writeAll("sandbox released — its snapshots stay on disk\n");
+}
+
+fn capture(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
+ if (!sandbox.safeName(root.session_name)) {
+ try out.writeAll("this session has no name a snapshot directory could be built from\n");
+ return;
+ }
+ const act = sandbox.active() orelse {
+ try out.print("no sandbox is active — {s}/snapshot{s} captures the filesystem of a sandbox this session is running in, and there is none attached\n", .{ style.accent, style.reset });
+ try renderList(root, arena, out);
+ return;
+ };
+ if (!act.backend.available()) {
+ try out.print("{s} backend: {s}\n", .{ act.backend.name(), explain(error.SandboxUnavailable) });
+ return;
+ }
+ const id = try sandbox.newId(arena, root.io);
+ const blob: sandbox.Blob = .{
+ .io = root.io,
+ .dir = sandbox.workspace(),
+ .rel = try sandbox.payloadPath(arena, root.session_name, id),
+ };
+ const payload = act.handle.snapshot(root.gpa, blob) catch |err| {
+ try out.print("snapshot failed — {s}\n", .{explain(err)});
+ return;
+ };
+ sandbox.writeManifest(root.io, sandbox.workspace(), arena, root.session_name, .{
+ .id = id,
+ .backend = act.backend.name(),
+ .kind = payload.kind.tag(),
+ .ref = payload.ref,
+ .len = payload.len,
+ .created_ms = util.unixMs(root.io),
+ }) catch |err| {
+ try out.print("captured the payload but could not record it: {s}\n", .{@errorName(err)});
+ return;
+ };
+ try out.print("📸 snapshot {s}{s}{s} — {d} bytes at {s}\n", .{ style.accent, id, style.reset, payload.len, blob.rel });
+ try out.print("{s} /rewind {s} brings this filesystem back; {s}{s}\n", .{ style.dim, id, log_note, style.reset });
+}
+
+fn restore(root: *Agent, arena: Allocator, id: []const u8, out: *Io.Writer) !void {
+ const found = sandbox.find(root.io, sandbox.workspace(), arena, root.session_name, id) orelse {
+ try out.print("no snapshot {s} in this session — {s}/snapshot list{s} shows what there is\n", .{ id, style.accent, style.reset });
+ return;
+ };
+ const act = sandbox.active() orelse {
+ try out.print("no sandbox is active — a rewind restores a snapshot ONTO a backend, and there is none attached\n", .{});
+ return;
+ };
+ if (!act.backend.available()) {
+ try out.print("{s} backend: {s}\n", .{ act.backend.name(), explain(error.SandboxUnavailable) });
+ return;
+ }
+ const blob: sandbox.Blob = .{
+ .io = root.io,
+ .dir = sandbox.workspace(),
+ .rel = try sandbox.payloadPath(arena, root.session_name, found.id),
+ };
+ // Release BEFORE restoring, not after. The restore acquires the same key,
+ // and a backend evicts the warm container on a key before it starts one —
+ // so releasing afterwards would `docker rm -f` the container the restore
+ // had just brought up. The old sandbox is doomed either way; this order is
+ // the one where the new one survives.
+ const key = try arena.dupe(u8, act.handle.key);
+ act.handle.release();
+ sandbox.detach();
+ const fresh = act.backend.acquireFromSnapshot(root.gpa, key, found.payload(), blob) catch |err| {
+ try out.print("rewind failed — {s}\n", .{explain(err)});
+ return;
+ };
+ sandbox.attach(.{ .backend = act.backend, .handle = fresh });
+ try out.print("⏪ sandbox rewound to {s}{s}{s} ({s}, {d} bytes)\n", .{ style.accent, found.id, style.reset, found.backend, found.len });
+ try out.print("{s} {s}; processes inside the sandbox were relaunched, not resumed{s}\n", .{ style.dim, log_note, style.reset });
+}
+
+fn renderList(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
+ const items = try sandbox.list(root.io, sandbox.workspace(), arena, root.session_name);
+ if (items.len == 0) {
+ try out.writeAll("no snapshots in this session yet\n");
+ return;
+ }
+ try out.print("{s}snapshots{s}\n", .{ style.bold, style.reset });
+ for (items) |m| {
+ try out.print(" {s}{s}{s} {s:<8} {d:>10} B {s}\n", .{ style.accent, m.id, style.reset, m.backend, m.len, m.ref });
+ }
+ try out.print("{s}usage: /rewind <id> — restores that filesystem; {s}{s}\n", .{ style.dim, log_note, style.reset });
+}
+
+test "a numeric /rewind argument stays with the conversation rewind" {
+ try std.testing.expect(!isSnapshotArg(""));
+ try std.testing.expect(!isSnapshotArg("3"));
+ try std.testing.expect(!isSnapshotArg("12"));
+ try std.testing.expect(isSnapshotArg("1754000000-ab12cd34"));
+ try std.testing.expect(isSnapshotArg("abc"));
+}
+
+test "argOf claims only the exact command" {
+ try std.testing.expectEqualStrings("", argOf("/snapshot", "/snapshot").?);
+ try std.testing.expectEqualStrings("list", argOf("/snapshot list", "/snapshot").?);
+ try std.testing.expect(argOf("/snapshots", "/snapshot") == null);
+ try std.testing.expect(argOf("/rewinds 3", "/rewind") == null);
+ try std.testing.expectEqualStrings("3", argOf("/rewind 3", "/rewind").?);
+}
+
+test "every sandbox failure has an explanation, and rewind never claims the log moved" {
+ inline for (.{
+ error.SandboxUnavailable,
+ error.SnapshotUnsupported,
+ error.SnapshotFailed,
+ error.RestoreFailed,
+ error.ExecFailed,
+ }) |err| {
+ try std.testing.expect(explain(err).len > 20);
+ }
+ try std.testing.expect(std.mem.indexOf(u8, log_note, "NOT rewound") != null);
+ try std.testing.expect(std.mem.indexOf(u8, log_note, "filesystem state only") != null);
+}
diff --git a/src/commands_session.zig b/src/commands_session.zig
index 59078931..8637635a 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -1,6 +1,7 @@
//! Session/environment slash commands, split out of main.zig's handleCommand
//! (600-line goal, issue #123): /clear /new /rename /goal /loop /bash /agents
-//! /animation /theme /hooks /skills /trajectory /plan.
+//! /animation /theme /hooks /skills /trajectory /plan, plus #554's /snapshot
+//! and the snapshot half of /rewind (dispatched to commands_sandbox.zig).
const std = @import("std");
const Io = std.Io;
@@ -30,6 +31,7 @@ const style = &ansi.style;
const exec = @import("exec.zig");
const execTool = exec.execTool;
+const commands_sandbox = @import("commands_sandbox.zig"); // #554 /snapshot + /rewind <id>
const fleet = @import("fleet.zig");
const promoteAgents = fleet.promoteAgents;
@@ -81,6 +83,9 @@ pub fn resetConversationSteering(root: *Agent) void {
/// (handleCommand in main.zig) then tries the next peer module.
pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
_ = keys; // unused in this file's command set; kept for a uniform tryHandle signature
+ // #554: claims /snapshot, and /rewind ONLY when its argument is a snapshot
+ // id — a numeric /rewind falls through to the conversation rewind below.
+ if (try commands_sandbox.tryHandle(root, arena, line, out)) return true;
if (std.mem.eql(u8, line, "/clear")) {
root.messages = std.json.Array.init(arena);
root.last_context_tokens = 0;
diff --git a/src/help.zig b/src/help.zig
index 7b787398..aaaf5c1c 100644
--- a/src/help.zig
+++ b/src/help.zig
@@ -28,7 +28,7 @@ const peers_blurb =
;
pub const sections = [_]Section{
- .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/rename", "/rewind" } },
+ .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/rename", "/rewind", "/snapshot" } },
.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },
.{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },
.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek" }, .blurb = peers_blurb },
diff --git a/src/sandbox.zig b/src/sandbox.zig
new file mode 100644
index 00000000..5c04cf24
--- /dev/null
+++ b/src/sandbox.zig
@@ -0,0 +1,448 @@
+//! #554: the pluggable sandbox seam — acquire a sandbox, run things in it,
+//! capture its filesystem state, and bring that state back up later (on this
+//! backend or another one).
+//!
+//! Two roles, both the `ctx`/`vt` pair engine_sink.zig uses:
+//! - `Backend`: `acquire(key)` for a fresh sandbox, `acquireFromSnapshot`
+//! for one restored from a captured payload. One WARM sandbox per key —
+//! acquiring a key that already has one evicts it first, so a key names a
+//! lane rather than an ever-growing pile of containers.
+//! - `Handle`: `exec(argv)` inside it, `snapshot()` to capture it.
+//!
+//! THE PAYLOAD NEVER ENTERS THIS ADDRESS SPACE. A `Payload` carries the blob's
+//! KIND, LENGTH and backend REF, not its bytes: the backend streams the blob
+//! straight through a file handle at `Blob.rel` (the child's stdout on
+//! capture, its stdin on restore). A container image tar is routinely
+//! gigabytes, and holding one in memory is the exo limitation #554 names as
+//! the thing not to repeat.
+//!
+//! WHAT A REWIND IS NOT. Restoring a snapshot puts FILESYSTEM state back. The
+//! conversation and the event log are canonical and are never rewound with it
+//! — commands_sandbox.zig says so in the user-facing output, because a user
+//! who believed both had moved would read the transcript as the record of a
+//! run that never happened.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const session_index = @import("session_index.zig");
+const tool_spill = @import("tool_spill.zig");
+const util = @import("util.zig");
+
+/// Every way a sandbox operation can fail, flat: the vtable entries below are
+/// function POINTERS, so every backend has to name exactly this set.
+pub const Error = error{
+ /// The backend's CLI is absent (no `docker` on PATH) or refused to run.
+ /// The one error a REPL command must render as an explanation, never a crash.
+ SandboxUnavailable,
+ /// This backend cannot capture state at all (LocalProcess).
+ SnapshotUnsupported,
+ SnapshotFailed,
+ RestoreFailed,
+ ExecFailed,
+ OutOfMemory,
+};
+
+/// What a captured payload IS. One kind in the MVP; a second (an AppleContainer
+/// or Daytona-native blob) is the same wire with a different producer, which is
+/// why the manifest records the kind rather than assuming it.
+pub const Kind = enum {
+ docker_image_tar,
+
+ pub fn tag(k: Kind) []const u8 {
+ return @tagName(k);
+ }
+
+ pub fn parse(s: []const u8) ?Kind {
+ return std.meta.stringToEnum(Kind, s);
+ }
+};
+
+/// A captured snapshot, minus its bytes (see the file header). `ref` is what
+/// the blob names inside itself — for `.docker_image_tar`, the image tag
+/// `docker load` brings back.
+pub const Payload = struct {
+ kind: Kind = .docker_image_tar,
+ len: u64 = 0,
+ ref: []const u8 = "",
+};
+
+/// Where a snapshot's blob lives on disk. `dir` is the directory `.graff` sits
+/// under (the cwd in production, a tmp dir in tests) and `rel` is the
+/// forward-slashed relative path of `payload.bin` under it — the `.graff/`
+/// path invariant in session_index.zig governs every path built here.
+pub const Blob = struct {
+ io: Io,
+ dir: Io.Dir,
+ rel: []const u8,
+};
+
+pub const ExecResult = struct {
+ exit_code: i32 = 0,
+ stdout: []u8 = &.{},
+ stderr: []u8 = &.{},
+
+ pub fn deinit(self: ExecResult, gpa: Allocator) void {
+ gpa.free(self.stdout);
+ gpa.free(self.stderr);
+ }
+};
+
+pub const HandleVTable = struct {
+ exec: *const fn (ctx: *anyopaque, gpa: Allocator, argv: []const []const u8) Error!ExecResult,
+ /// Capture this sandbox into `blob`, returning what to record. The blob is
+ /// written by the backend; the caller only supplies where it goes.
+ snapshot: *const fn (ctx: *anyopaque, gpa: Allocator, blob: Blob) Error!Payload,
+ release: *const fn (ctx: *anyopaque) void,
+};
+
+pub const Handle = struct {
+ ctx: *anyopaque,
+ vt: *const HandleVTable,
+ /// The lane this sandbox occupies. One warm sandbox per key.
+ key: []const u8 = "default",
+ /// Backend-assigned identity (a container id), for display.
+ id: []const u8 = "",
+
+ pub fn exec(self: Handle, gpa: Allocator, argv: []const []const u8) Error!ExecResult {
+ return self.vt.exec(self.ctx, gpa, argv);
+ }
+
+ pub fn snapshot(self: Handle, gpa: Allocator, blob: Blob) Error!Payload {
+ return self.vt.snapshot(self.ctx, gpa, blob);
+ }
+
+ pub fn release(self: Handle) void {
+ self.vt.release(self.ctx);
+ }
+};
+
+pub const BackendVTable = struct {
+ name: []const u8,
+ /// False when the backend cannot run here at all (its CLI is missing).
+ /// Checked before acquiring so the caller can explain rather than fail.
+ available: *const fn (ctx: *anyopaque) bool,
+ acquire: *const fn (ctx: *anyopaque, gpa: Allocator, key: []const u8) Error!Handle,
+ acquireFromSnapshot: *const fn (
+ ctx: *anyopaque,
+ gpa: Allocator,
+ key: []const u8,
+ payload: Payload,
+ blob: Blob,
+ ) Error!Handle,
+};
+
+pub const Backend = struct {
+ ctx: *anyopaque,
+ vt: *const BackendVTable,
+
+ pub fn name(self: Backend) []const u8 {
+ return self.vt.name;
+ }
+
+ pub fn available(self: Backend) bool {
+ return self.vt.available(self.ctx);
+ }
+
+ pub fn acquire(self: Backend, gpa: Allocator, key: []const u8) Error!Handle {
+ return self.vt.acquire(self.ctx, gpa, key);
+ }
+
+ pub fn acquireFromSnapshot(
+ self: Backend,
+ gpa: Allocator,
+ key: []const u8,
+ payload: Payload,
+ blob: Blob,
+ ) Error!Handle {
+ return self.vt.acquireFromSnapshot(self.ctx, gpa, key, payload, blob);
+ }
+};
+
+// ── Persistence layout ─────────────────────────────────────────────────────
+// .graff/sessions/<session>/snapshots/<id>/{manifest.json,payload.bin}
+// A sibling of #409's artifacts/ dir under the same session, so one session's
+// leftovers stay one subtree and tool_spill's sweep reclaims them together.
+
+pub const snapshots_leaf = "snapshots";
+pub const manifest_name = "manifest.json";
+pub const payload_name = "payload.bin";
+
+/// True when `s` can only ever name something INSIDE the session subtree.
+/// Session names come from /save and from AI titles, snapshot ids from
+/// `newId`, and neither may become a write outside `.graff/sessions`.
+pub fn safeName(s: []const u8) bool {
+ return tool_spill.safeName(s);
+}
+
+pub fn snapshotsDir(arena: Allocator, session: []const u8) Allocator.Error![]const u8 {
+ return std.fmt.allocPrint(arena, "{s}/{s}/{s}", .{ session_index.sessions_dir, session, snapshots_leaf });
+}
+
+pub fn snapshotDir(arena: Allocator, session: []const u8, id: []const u8) Allocator.Error![]const u8 {
+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ try snapshotsDir(arena, session), id });
+}
+
+pub fn manifestPath(arena: Allocator, session: []const u8, id: []const u8) Allocator.Error![]const u8 {
+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ try snapshotDir(arena, session, id), manifest_name });
+}
+
+pub fn payloadPath(arena: Allocator, session: []const u8, id: []const u8) Allocator.Error![]const u8 {
+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ try snapshotDir(arena, session, id), payload_name });
+}
+
+/// A fresh snapshot id: sortable by capture time, unique per process.
+/// `io.random` rather than a counter, so two graffs sharing a session dir
+/// cannot collide inside the same millisecond.
+pub fn newId(arena: Allocator, io: Io) Allocator.Error![]const u8 {
+ var raw: [4]u8 = undefined;
+ io.random(&raw);
+ const nonce = std.fmt.bytesToHex(raw, .lower);
+ return std.fmt.allocPrint(arena, "{d}-{s}", .{ util.unixMs(io), &nonce });
+}
+
+/// What `manifest.json` holds. Everything a restore needs WITHOUT the blob:
+/// which backend produced it, what shape the payload is, what it refers to,
+/// and how big it is.
+pub const Manifest = struct {
+ id: []const u8 = "",
+ backend: []const u8 = "",
+ kind: []const u8 = "docker_image_tar",
+ ref: []const u8 = "",
+ len: u64 = 0,
+ created_ms: i64 = 0,
+
+ pub fn payload(m: Manifest) Payload {
+ return .{
+ .kind = Kind.parse(m.kind) orelse .docker_image_tar,
+ .len = m.len,
+ .ref = m.ref,
+ };
+ }
+};
+
+pub fn renderManifest(arena: Allocator, m: Manifest) Allocator.Error![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer, .options = .{ .whitespace = .indent_2 } };
+ s.write(m) catch return error.OutOfMemory;
+ return aw.writer.buffered();
+}
+
+/// Null for anything that is not a manifest we wrote — a half-written file, a
+/// directory someone dropped in by hand. Listing must skip those, not fail.
+pub fn parseManifest(arena: Allocator, bytes: []const u8) ?Manifest {
+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{ .allocate = .alloc_always }) catch return null;
+ if (parsed != .object) return null;
+ const obj = parsed.object;
+ const id = util.strFieldObj(obj, "id") orelse return null;
+ if (id.len == 0) return null;
+ return .{
+ .id = id,
+ .backend = util.strFieldObj(obj, "backend") orelse "",
+ .kind = util.strFieldObj(obj, "kind") orelse "docker_image_tar",
+ .ref = util.strFieldObj(obj, "ref") orelse "",
+ .len = @intCast(@max(0, util.intFieldObj(obj, "len", 0))),
+ .created_ms = util.intFieldObj(obj, "created_ms", 0),
+ };
+}
+
+/// Write `manifest.json` beside a blob the backend has already streamed out.
+pub fn writeManifest(io: Io, dir: Io.Dir, arena: Allocator, session: []const u8, m: Manifest) !void {
+ try dir.writeFile(io, .{
+ .sub_path = try manifestPath(arena, session, m.id),
+ .data = try renderManifest(arena, m),
+ });
+}
+
+/// Every snapshot this session has on disk, oldest capture first. Unreadable
+/// or unparseable entries are skipped: a listing is a convenience and must
+/// never be the thing that fails a command.
+pub fn list(io: Io, dir: Io.Dir, arena: Allocator, session: []const u8) Allocator.Error![]Manifest {
+ var found: std.ArrayList(Manifest) = .empty;
+ if (!safeName(session)) return found.items;
+ var d = dir.openDir(io, try snapshotsDir(arena, session), .{ .iterate = true }) catch return found.items;
+ defer d.close(io);
+ var it = d.iterate();
+ while (it.next(io) catch null) |entry| {
+ if (entry.kind != .directory) continue;
+ const id = arena.dupe(u8, entry.name) catch continue;
+ const path = manifestPath(arena, session, id) catch continue;
+ const bytes = dir.readFileAlloc(io, path, arena, .limited(64 * 1024)) catch continue;
+ const m = parseManifest(arena, bytes) orelse continue;
+ try found.append(arena, m);
+ }
+ std.mem.sort(Manifest, found.items, {}, byCapture);
+ return found.items;
+}
+
+fn byCapture(_: void, a: Manifest, b: Manifest) bool {
+ if (a.created_ms != b.created_ms) return a.created_ms < b.created_ms;
+ return std.mem.lessThan(u8, a.id, b.id);
+}
+
+pub fn find(io: Io, dir: Io.Dir, arena: Allocator, session: []const u8, id: []const u8) ?Manifest {
+ if (!safeName(session) or !safeName(id)) return null;
+ const path = manifestPath(arena, session, id) catch return null;
+ const bytes = dir.readFileAlloc(io, path, arena, .limited(64 * 1024)) catch return null;
+ return parseManifest(arena, bytes);
+}
+
+// ── The active sandbox ─────────────────────────────────────────────────────
+// A process-wide pair rather than an Agent field: nothing in the MVP attaches
+// a sandbox automatically, so the REPL commands need a seam they can read that
+// is EMPTY by default and that a test (or a future `--sandbox` launch flag)
+// can fill. Empty is the normal state and must render as an explanation.
+
+/// The directory `.graff` sits under. The cwd in production; tool_spill.zig's
+/// sink carries the same seam for the same reason — a test must be able to
+/// write a session subtree without touching the developer's working copy.
+var g_workspace: ?Io.Dir = null;
+
+pub fn setWorkspace(dir: ?Io.Dir) void {
+ g_workspace = dir;
+}
+
+pub fn workspace() Io.Dir {
+ return g_workspace orelse Io.Dir.cwd();
+}
+
+pub const Active = struct {
+ backend: Backend,
+ handle: Handle,
+};
+
+var g_active: ?Active = null;
+
+pub fn attach(a: Active) void {
+ g_active = a;
+}
+
+pub fn detach() void {
+ g_active = null;
+}
+
+pub fn active() ?Active {
+ return g_active;
+}
+
+// ── LocalProcess: the no-isolation backend ─────────────────────────────────
+// Runs argv in this very process's world. It exists so the seam has a second
+// implementation that is not Docker (a one-implementation interface proves
+// nothing), and so dev/test paths can hold a Handle without a container
+// runtime. It cannot capture state, and says so rather than pretending.
+
+pub const LocalProcess = struct {
+ io: Io,
+
+ const handle_vtable: HandleVTable = .{
+ .exec = localExec,
+ .snapshot = localSnapshot,
+ .release = localRelease,
+ };
+ const backend_vtable: BackendVTable = .{
+ .name = "local",
+ .available = localAvailable,
+ .acquire = localAcquire,
+ .acquireFromSnapshot = localAcquireFromSnapshot,
+ };
+
+ pub fn backend(self: *LocalProcess) Backend {
+ return .{ .ctx = @ptrCast(self), .vt = &backend_vtable };
+ }
+
+ fn localAvailable(_: *anyopaque) bool {
+ return true;
+ }
+
+ fn localAcquire(ctx: *anyopaque, gpa: Allocator, key: []const u8) Error!Handle {
+ _ = gpa;
+ return .{ .ctx = ctx, .vt = &handle_vtable, .key = key, .id = "local" };
+ }
+
+ fn localAcquireFromSnapshot(_: *anyopaque, _: Allocator, _: []const u8, _: Payload, _: Blob) Error!Handle {
+ return error.SnapshotUnsupported;
+ }
+
+ fn localExec(ctx: *anyopaque, gpa: Allocator, argv: []const []const u8) Error!ExecResult {
+ const self: *LocalProcess = @ptrCast(@alignCast(ctx));
+ const run = process_runner.runCapped(gpa, self.io, argv, 64 * 1024, 64 * 1024, 120_000) catch
+ return error.ExecFailed;
+ return .{
+ .exit_code = if (run.term == .exited) @intCast(run.term.exited) else -1,
+ .stdout = run.stdout,
+ .stderr = run.stderr,
+ };
+ }
+
+ fn localSnapshot(_: *anyopaque, _: Allocator, _: Blob) Error!Payload {
+ return error.SnapshotUnsupported;
+ }
+
+ fn localRelease(_: *anyopaque) void {}
+};
+
+const process_runner = @import("process_runner.zig");
+
+test "snapshot paths are forward-slashed and rooted in the session subtree" {
+ var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ try std.testing.expectEqualStrings(".graff/sessions/wf/snapshots", try snapshotsDir(arena, "wf"));
+ try std.testing.expectEqualStrings(".graff/sessions/wf/snapshots/a1", try snapshotDir(arena, "wf", "a1"));
+ try std.testing.expectEqualStrings(".graff/sessions/wf/snapshots/a1/manifest.json", try manifestPath(arena, "wf", "a1"));
+ try std.testing.expectEqualStrings(".graff/sessions/wf/snapshots/a1/payload.bin", try payloadPath(arena, "wf", "a1"));
+}
+
+test "a session or snapshot name can never escape the sessions dir" {
+ try std.testing.expect(safeName("wf"));
+ try std.testing.expect(!safeName(".."));
+ try std.testing.expect(!safeName("a/b"));
+ try std.testing.expect(!safeName(""));
+}
+
+test "a sandbox manifest round-trips through JSON" {
+ var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const m: Manifest = .{
+ .id = "17-abcd",
+ .backend = "docker",
+ .kind = "docker_image_tar",
+ .ref = "graff-snap-17-abcd",
+ .len = 4096,
+ .created_ms = 17,
+ };
+ const back = parseManifest(arena, try renderManifest(arena, m)) orelse return error.ManifestUnparseable;
+ try std.testing.expectEqualStrings(m.id, back.id);
+ try std.testing.expectEqualStrings(m.ref, back.ref);
+ try std.testing.expectEqual(m.len, back.len);
+ try std.testing.expectEqual(Kind.docker_image_tar, back.payload().kind);
+ try std.testing.expect(parseManifest(arena, "not json") == null);
+ try std.testing.expect(parseManifest(arena, "{}") == null); // no id: not ours
+}
+
+test "LocalProcess acquires but refuses to snapshot" {
+ var local: LocalProcess = .{ .io = std.testing.io };
+ const backend = local.backend();
+ try std.testing.expect(backend.available());
+ try std.testing.expectEqualStrings("local", backend.name());
+ const handle = try backend.acquire(std.testing.allocator, "k");
+ try std.testing.expectEqualStrings("k", handle.key);
+ const blob: Blob = .{ .io = std.testing.io, .dir = Io.Dir.cwd(), .rel = "payload.bin" };
+ try std.testing.expectError(error.SnapshotUnsupported, handle.snapshot(std.testing.allocator, blob));
+ try std.testing.expectError(error.SnapshotUnsupported, backend.acquireFromSnapshot(std.testing.allocator, "k", .{}, blob));
+ handle.release();
+}
+
+test "the active sandbox is empty until something attaches one" {
+ detach();
+ try std.testing.expect(active() == null);
+ var local: LocalProcess = .{ .io = std.testing.io };
+ const backend = local.backend();
+ attach(.{ .backend = backend, .handle = try backend.acquire(std.testing.allocator, "k") });
+ try std.testing.expect(active() != null);
+ try std.testing.expectEqualStrings("local", active().?.backend.name());
+ detach();
+ try std.testing.expect(active() == null);
+}
diff --git a/src/sandbox_docker.zig b/src/sandbox_docker.zig
new file mode 100644
index 00000000..7ac54554
--- /dev/null
+++ b/src/sandbox_docker.zig
@@ -0,0 +1,397 @@
+//! #554's first sandbox backend: Docker, driven purely through the `docker`
+//! CLI as child processes. No SDK, no daemon socket of our own — the same wire
+//! an AppleContainer backend would use with a different binary name, which is
+//! the point of keeping it CLI-shaped.
+//!
+//! The four verbs:
+//! acquire docker rm -f graff-sbx-<key> (evict the warm one)
+//! docker run -d --name graff-sbx-<key> <image>
+//! snapshot docker commit -p <ctr> graff-snap-<uuid>
+//! docker save graff-snap-<uuid> -> payload.bin
+//! docker image rm graff-snap-<uuid>
+//! acquireFromSnapshot docker rm -f graff-sbx-<key> (evict FIRST)
+//! docker load <- payload.bin
+//! docker run -d --name graff-sbx-<key> <loaded ref>
+//! exec docker exec <ctr> <argv...>
+//!
+//! `docker save` writes to the payload FILE HANDLE and `docker load` reads from
+//! it, so an image tar of any size moves between disk and the daemon without a
+//! byte of it living in this process (sandbox.zig's header says why).
+//!
+//! The binary is resolved against a PATH string rather than left to the
+//! spawner: `std.process.spawn` documents that argv[0] resolution always uses
+//! the PARENT environment, so an injected PATH would be ignored, and resolving
+//! first is also how "docker is not installed" becomes an explanation instead
+//! of a spawn error.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const sandbox = @import("sandbox.zig");
+const Error = sandbox.Error;
+
+pub const container_prefix = "graff-sbx-";
+pub const snapshot_prefix = "graff-snap-";
+/// What a fresh sandbox boots from when nothing else is configured. Small,
+/// present on most machines, and it has a shell for `exec`.
+pub const default_image = "alpine:latest";
+/// The command a sandbox container runs so it stays up for `docker exec`.
+pub const idle_argv = [_][]const u8{ "sleep", "infinity" };
+
+const output_cap = 64 * 1024;
+
+pub const Docker = struct {
+ io: Io,
+ /// PATH to resolve `docker` against: `main.g_path_env` in production, a
+ /// shim directory in tests.
+ path_env: []const u8,
+ /// Image a fresh (non-restored) sandbox starts from.
+ image: []const u8 = default_image,
+ /// Binary name to resolve. `container` would make this an AppleContainer
+ /// backend; the wire below is unchanged.
+ bin_name: []const u8 = "docker",
+
+ const backend_vtable: sandbox.BackendVTable = .{
+ .name = "docker",
+ .available = availableImpl,
+ .acquire = acquireImpl,
+ .acquireFromSnapshot = acquireFromSnapshotImpl,
+ };
+
+ const handle_vtable: sandbox.HandleVTable = .{
+ .exec = execImpl,
+ .snapshot = snapshotImpl,
+ .release = releaseImpl,
+ };
+
+ pub fn backend(self: *Docker) sandbox.Backend {
+ return .{ .ctx = @ptrCast(self), .vt = &backend_vtable };
+ }
+
+ /// One live sandbox. Allocated per `acquire` and freed by `release`, so two
+ /// keys held at once cannot alias each other's container name or tag.
+ pub const Sandbox = struct {
+ docker: *Docker,
+ gpa: Allocator,
+ bin: []const u8,
+ /// `graff-sbx-<key>`, which IS the eviction identity: eviction is
+ /// `docker rm -f` on this name, so it works across process restarts
+ /// without any in-memory bookkeeping to go stale.
+ container: []const u8,
+ /// The most recent `docker commit` tag. Owned here so a returned
+ /// `Payload.ref` stays valid until the next snapshot on this sandbox.
+ tag: []const u8 = "",
+
+ fn free(self: *Sandbox) void {
+ const gpa = self.gpa;
+ gpa.free(self.bin);
+ gpa.free(self.container);
+ if (self.tag.len > 0) gpa.free(self.tag);
+ gpa.destroy(self);
+ }
+ };
+
+ fn availableImpl(ctx: *anyopaque) bool {
+ const self: *Docker = @ptrCast(@alignCast(ctx));
+ var buf: [4096]u8 = undefined;
+ return resolveInto(self.io, self.path_env, self.bin_name, &buf) != null;
+ }
+
+ fn acquireImpl(ctx: *anyopaque, gpa: Allocator, key: []const u8) Error!sandbox.Handle {
+ const self: *Docker = @ptrCast(@alignCast(ctx));
+ const box = try self.open(gpa, key);
+ errdefer box.free();
+ try self.start(box, self.image);
+ return .{ .ctx = @ptrCast(box), .vt = &handle_vtable, .key = box.container[container_prefix.len..], .id = box.container };
+ }
+
+ fn acquireFromSnapshotImpl(
+ ctx: *anyopaque,
+ gpa: Allocator,
+ key: []const u8,
+ payload: sandbox.Payload,
+ blob: sandbox.Blob,
+ ) Error!sandbox.Handle {
+ const self: *Docker = @ptrCast(@alignCast(ctx));
+ if (payload.kind != .docker_image_tar) return error.RestoreFailed;
+ const box = try self.open(gpa, key); // evicts the warm container FIRST
+ errdefer box.free();
+ const file = blob.dir.openFile(blob.io, blob.rel, .{}) catch return error.RestoreFailed;
+ defer file.close(blob.io);
+ const loaded = run(gpa, self.io, &.{ box.bin, "load" }, .{ .stdin_file = file }) catch return error.RestoreFailed;
+ defer loaded.deinit(gpa);
+ if (!loaded.ok()) return error.RestoreFailed;
+ const ref = loadedRef(loaded.stdout) orelse payload.ref;
+ if (ref.len == 0) return error.RestoreFailed;
+ self.start(box, ref) catch return error.RestoreFailed;
+ return .{ .ctx = @ptrCast(box), .vt = &handle_vtable, .key = box.container[container_prefix.len..], .id = box.container };
+ }
+
+ /// Resolve the binary, name the container, and evict whatever is warm on
+ /// that name. Shared by both acquire paths: a restore that skipped the
+ /// eviction would collide with the live container on its own key.
+ fn open(self: *Docker, gpa: Allocator, key: []const u8) Error!*Sandbox {
+ var buf: [4096]u8 = undefined;
+ const resolved = resolveInto(self.io, self.path_env, self.bin_name, &buf) orelse return error.SandboxUnavailable;
+ const box = try gpa.create(Sandbox);
+ errdefer gpa.destroy(box);
+ const bin = try gpa.dupe(u8, resolved);
+ errdefer gpa.free(bin);
+ box.* = .{
+ .docker = self,
+ .gpa = gpa,
+ .bin = bin,
+ .container = try containerName(gpa, key),
+ };
+ evict(gpa, self.io, box.bin, box.container);
+ return box;
+ }
+
+ fn start(self: *Docker, box: *Sandbox, image: []const u8) Error!void {
+ var argv: std.ArrayList([]const u8) = .empty;
+ defer argv.deinit(box.gpa);
+ try argv.appendSlice(box.gpa, &.{ box.bin, "run", "-d", "--name", box.container, image });
+ try argv.appendSlice(box.gpa, &idle_argv);
+ const started = run(box.gpa, self.io, argv.items, .{}) catch return error.SandboxUnavailable;
+ defer started.deinit(box.gpa);
+ if (!started.ok()) return error.SandboxUnavailable;
+ }
+
+ fn execImpl(ctx: *anyopaque, gpa: Allocator, argv: []const []const u8) Error!sandbox.ExecResult {
+ const box: *Sandbox = @ptrCast(@alignCast(ctx));
+ var full: std.ArrayList([]const u8) = .empty;
+ defer full.deinit(gpa);
+ try full.appendSlice(gpa, &.{ box.bin, "exec", box.container });
+ try full.appendSlice(gpa, argv);
+ const done = run(gpa, box.docker.io, full.items, .{}) catch return error.ExecFailed;
+ return .{
+ .exit_code = if (done.term == .exited) @intCast(done.term.exited) else -1,
+ .stdout = done.stdout,
+ .stderr = done.stderr,
+ };
+ }
+
+ fn snapshotImpl(ctx: *anyopaque, gpa: Allocator, blob: sandbox.Blob) Error!sandbox.Payload {
+ const box: *Sandbox = @ptrCast(@alignCast(ctx));
+ const io = box.docker.io;
+ const tag = try snapshotTag(gpa, io);
+ errdefer gpa.free(tag);
+
+ // `tag` is freed by the errdefer on every failure below and adopted by
+ // `box.tag` on success — never both, so no branch frees it by hand.
+ const committed = run(gpa, io, &.{ box.bin, "commit", "-p", box.container, tag }, .{}) catch return error.SnapshotFailed;
+ defer committed.deinit(gpa);
+ if (!committed.ok()) return error.SnapshotFailed;
+
+ // The tar goes straight from the daemon into payload.bin: the child's
+ // stdout IS the file, so nothing is buffered here at any size.
+ ensureBlobDir(blob);
+ const file = blob.dir.createFile(blob.io, blob.rel, .{}) catch {
+ removeImage(gpa, io, box.bin, tag);
+ return error.SnapshotFailed;
+ };
+ const saved = run(gpa, io, &.{ box.bin, "save", tag }, .{ .stdout_file = file }) catch {
+ file.close(blob.io);
+ removeImage(gpa, io, box.bin, tag);
+ return error.SnapshotFailed;
+ };
+ defer saved.deinit(gpa);
+ file.close(blob.io);
+ removeImage(gpa, io, box.bin, tag); // the blob is the artifact; the image was scaffolding
+ if (!saved.ok()) return error.SnapshotFailed;
+ // Sized by PATH, not by the write handle: `stat` on a write-only handle
+ // is ACCESS_DENIED on Windows and only there (#462), and a size read
+ // that silently returns 0 on one platform is worse than no size at all.
+ const size: u64 = if (blob.dir.statFile(blob.io, blob.rel, .{})) |st| st.size else |_| 0;
+
+ if (box.tag.len > 0) gpa.free(box.tag);
+ box.tag = tag;
+ return .{ .kind = .docker_image_tar, .len = size, .ref = box.tag };
+ }
+
+ fn releaseImpl(ctx: *anyopaque) void {
+ const box: *Sandbox = @ptrCast(@alignCast(ctx));
+ evict(box.gpa, box.docker.io, box.bin, box.container);
+ box.free();
+ }
+};
+
+fn ensureBlobDir(blob: sandbox.Blob) void {
+ // `.graff/` paths are forward-slashed on every platform by invariant
+ // (session_index.zig), so the POSIX dirname is the right one everywhere.
+ const parent = std.fs.path.dirnamePosix(blob.rel) orelse return;
+ blob.dir.createDirPath(blob.io, parent) catch {};
+}
+
+fn evict(gpa: Allocator, io: Io, bin: []const u8, container: []const u8) void {
+ const removed = run(gpa, io, &.{ bin, "rm", "-f", container }, .{}) catch return;
+ removed.deinit(gpa);
+}
+
+fn removeImage(gpa: Allocator, io: Io, bin: []const u8, tag: []const u8) void {
+ const removed = run(gpa, io, &.{ bin, "image", "rm", tag }, .{}) catch return;
+ removed.deinit(gpa);
+}
+
+/// `graff-sbx-<key>`, with the key reduced to what Docker accepts in a name
+/// ([A-Za-z0-9_.-]). A key is a lane label, not a path, so folding the rest to
+/// '-' cannot collide two lanes a user would think of as distinct.
+pub fn containerName(gpa: Allocator, key: []const u8) Allocator.Error![]const u8 {
+ const use = if (key.len == 0) "default" else key;
+ const out = try gpa.alloc(u8, container_prefix.len + @min(use.len, 100));
+ @memcpy(out[0..container_prefix.len], container_prefix);
+ for (out[container_prefix.len..], use[0 .. out.len - container_prefix.len]) |*slot, c| {
+ slot.* = if (std.ascii.isAlphanumeric(c) or c == '_' or c == '.' or c == '-') c else '-';
+ }
+ return out;
+}
+
+pub fn snapshotTag(gpa: Allocator, io: Io) Allocator.Error![]const u8 {
+ var raw: [8]u8 = undefined;
+ io.random(&raw);
+ const hex = std.fmt.bytesToHex(raw, .lower);
+ return std.fmt.allocPrint(gpa, snapshot_prefix ++ "{s}", .{&hex});
+}
+
+/// The image reference `docker load` reports, or null when its output does not
+/// name one (older daemons, an unexpected format). The caller falls back to the
+/// ref the manifest recorded, so a parse miss is never fatal.
+pub fn loadedRef(stdout: []const u8) ?[]const u8 {
+ inline for (.{ "Loaded image: ", "Loaded image ID: " }) |needle| {
+ if (std.mem.indexOf(u8, stdout, needle)) |at| {
+ const rest = stdout[at + needle.len ..];
+ const end = std.mem.indexOfAny(u8, rest, "\r\n") orelse rest.len;
+ const ref = std.mem.trim(u8, rest[0..end], " \t");
+ if (ref.len > 0) return ref;
+ }
+ }
+ return null;
+}
+
+/// First `name` on `path_env` that exists, written into `buf`. Null when the
+/// binary is not installed — the "docker is absent" answer, decided before any
+/// process is spawned.
+pub fn resolveInto(io: Io, path_env: []const u8, name: []const u8, buf: []u8) ?[]const u8 {
+ var it = std.mem.splitScalar(u8, path_env, ':');
+ while (it.next()) |dir| {
+ if (dir.len == 0) continue;
+ const full = std.fmt.bufPrint(buf, "{s}/{s}", .{ dir, name }) catch continue;
+ Io.Dir.cwd().access(io, full, .{}) catch continue;
+ return full;
+ }
+ return null;
+}
+
+// ── Child-process plumbing ─────────────────────────────────────────────────
+
+pub const Run = struct {
+ term: std.process.Child.Term,
+ stdout: []u8,
+ stderr: []u8,
+
+ pub fn ok(self: Run) bool {
+ return self.term == .exited and self.term.exited == 0;
+ }
+
+ pub fn deinit(self: Run, gpa: Allocator) void {
+ gpa.free(self.stdout);
+ gpa.free(self.stderr);
+ }
+};
+
+/// Which end of the child is a file rather than a pipe. Exactly one of these
+/// is ever set: `save` streams stdout out to the payload, `load` streams the
+/// payload in on stdin.
+pub const Redirect = struct {
+ stdin_file: ?Io.File = null,
+ stdout_file: ?Io.File = null,
+};
+
+fn run(gpa: Allocator, io: Io, argv: []const []const u8, redirect: Redirect) Error!Run {
+ var child = std.process.spawn(io, .{
+ .argv = argv,
+ .stdin = if (redirect.stdin_file) |f| .{ .file = f } else .ignore,
+ .stdout = if (redirect.stdout_file) |f| .{ .file = f } else .pipe,
+ .stderr = .pipe,
+ }) catch return error.SandboxUnavailable;
+ // `kill` is documented as a no-op once `wait` has returned, so this covers
+ // the error paths without a flag and costs nothing on the success path.
+ defer child.kill(io);
+ if (child.stdout) |out| {
+ const both = try collect(2, gpa, io, .{ out, child.stderr.? });
+ const term = child.wait(io) catch return error.ExecFailed;
+ return .{ .term = term, .stdout = both[0], .stderr = both[1] };
+ }
+ const only = try collect(1, gpa, io, .{child.stderr.?});
+ const term = child.wait(io) catch return error.ExecFailed;
+ return .{ .term = term, .stdout = try gpa.alloc(u8, 0), .stderr = only[0] };
+}
+
+/// Drain every pipe the child has CONCURRENTLY. Reading one to the end first
+/// would deadlock the moment the other filled its pipe buffer, which for
+/// `docker save` is a certainty rather than a corner case. Each stream keeps
+/// its first `output_cap` bytes and discards the rest.
+fn collect(comptime n: usize, gpa: Allocator, io: Io, files: [n]Io.File) Error![n][]u8 {
+ var storage: Io.File.MultiReader.Buffer(n) = undefined;
+ var mr: Io.File.MultiReader = undefined;
+ mr.init(gpa, io, storage.toStreams(), &files);
+ defer mr.deinit();
+ var saved: [n]?[]u8 = @splat(null);
+ errdefer for (saved) |item| if (item) |bytes| gpa.free(bytes);
+ while (true) {
+ mr.fill(64, .none) catch |err| switch (err) {
+ error.EndOfStream => break,
+ else => return error.ExecFailed,
+ };
+ for (0..n) |i| {
+ const reader = mr.reader(i);
+ const buffered = reader.buffered();
+ if (saved[i] == null and buffered.len > output_cap) saved[i] = try gpa.dupe(u8, buffered[0..output_cap]);
+ if (saved[i] != null) reader.toss(buffered.len);
+ }
+ }
+ var out: [n][]u8 = undefined;
+ var made: usize = 0;
+ errdefer for (out[0..made]) |bytes| gpa.free(bytes);
+ while (made < n) : (made += 1) {
+ out[made] = if (saved[made]) |bytes| bytes else try gpa.dupe(u8, mr.reader(made).buffered());
+ saved[made] = null;
+ }
+ return out;
+}
+
+test "a container name is the eviction identity and is Docker-legal" {
+ const gpa = std.testing.allocator;
+ const plain = try containerName(gpa, "lane1");
+ defer gpa.free(plain);
+ try std.testing.expectEqualStrings("graff-sbx-lane1", plain);
+ const dirty = try containerName(gpa, "a/b c");
+ defer gpa.free(dirty);
+ try std.testing.expectEqualStrings("graff-sbx-a-b-c", dirty);
+ const empty = try containerName(gpa, "");
+ defer gpa.free(empty);
+ try std.testing.expectEqualStrings("graff-sbx-default", empty);
+}
+
+test "the loaded image ref is read back out of docker load's output" {
+ try std.testing.expectEqualStrings("graff-snap-ab12", loadedRef("Loaded image: graff-snap-ab12\n").?);
+ try std.testing.expectEqualStrings("sha256:beef", loadedRef("Loaded image ID: sha256:beef\n").?);
+ try std.testing.expect(loadedRef("nothing here\n") == null);
+}
+
+test "a snapshot tag is prefixed and unique" {
+ const gpa = std.testing.allocator;
+ const a = try snapshotTag(gpa, std.testing.io);
+ defer gpa.free(a);
+ const b = try snapshotTag(gpa, std.testing.io);
+ defer gpa.free(b);
+ try std.testing.expect(std.mem.startsWith(u8, a, snapshot_prefix));
+ try std.testing.expect(!std.mem.eql(u8, a, b));
+}
+
+test "a missing docker resolves to nothing rather than spawning" {
+ var buf: [4096]u8 = undefined;
+ try std.testing.expect(resolveInto(std.testing.io, "", "docker", &buf) == null);
+ try std.testing.expect(resolveInto(std.testing.io, "/nonexistent-graff-path", "docker", &buf) == null);
+}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 532907a6..760ae9fc 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -194,6 +194,14 @@ const proc_identity = @import("proc_identity.zig");
// (agent_context.zig, subagent.zig) sit at the 600-line cap.
const usage_attribution_tests = @import("usage_attribution_tests.zig");
+// #554: the sandbox seam, its Docker backend, and the /snapshot + /rewind <id>
+// commands. Production reaches commands_sandbox.zig from commands_session's
+// tryHandle and the rest only through calls, so without these hooks the whole
+// subsystem's tests compile to nothing.
+const sandbox = @import("sandbox.zig");
+const sandbox_docker = @import("sandbox_docker.zig");
+const commands_sandbox = @import("commands_sandbox.zig");
+
test {
_ = learn_holdout;
_ = learn_receipt;
@@ -266,4 +274,7 @@ test {
_ = side_question_tests;
_ = json_controls;
_ = effort_route;
+ _ = sandbox;
+ _ = sandbox_docker;
+ _ = commands_sandbox;
}