Skip to content

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

Python

fix(tools): close the three imagegen holes an adversarial review found (#352)

justrach55f25b1ebd37
diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zig
index 539f0424..85e05f64 100644
--- a/src/agent_tool_gate.zig
+++ b/src/agent_tool_gate.zig
@@ -148,6 +148,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
if (main_mod.plan_mode) {
if (std.mem.eql(u8, call.name, "learn_candidate") or
std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or
+ std.mem.eql(u8, call.name, "imagegen") or // #352: writes a file and spawns a workspace-write child
(mcp.Registry.isMcp(call.name) and !companionReadOnly(call.name, call.input))) return .{
.text = try self.arena.dupe(u8, "plan mode is on — read-only. Fold this change into the plan you present; the user applies it after approving (/plan toggles the mode off)."),
.is_error = true,
diff --git a/src/exec.zig b/src/exec.zig
index 698ae3c0..2420fb3c 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -163,7 +163,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// Plan mode backstop: the root gate already denies these with a nicer
// message; this catches subagents (which skip the gate entirely).
if (main_mod.plan_mode) {
- if (std.mem.eql(u8, call.name, "learn_candidate") or std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or mcp.Registry.isMcp(call.name)) return .{
+ if (std.mem.eql(u8, call.name, "learn_candidate") or std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or std.mem.eql(u8, call.name, imagegen.tool_name) or mcp.Registry.isMcp(call.name)) return .{
.text = try gpa.dupe(u8, "plan mode is on — read-only; describe the change instead of making it"),
.is_error = true,
};
diff --git a/src/imagegen.zig b/src/imagegen.zig
index e1bcc9c3..0d4a37a8 100644
--- a/src/imagegen.zig
+++ b/src/imagegen.zig
@@ -50,6 +50,7 @@ const approvals_mod = @import("approvals.zig");
const confinedPath = approvals_mod.confinedPath;
const noSymlinkEscape = approvals_mod.noSymlinkEscape;
const skills = @import("skills.zig");
+const edit_verify = @import("edit_verify.zig"); // same per-path lock stripe write_file/edit_file use
const skill = @import("imagegen_skill.zig");
const verify = @import("imagegen_verify.zig");
const run_mod = @import("imagegen_run.zig");
@@ -81,8 +82,10 @@ pub var script_path: []const u8 = "";
pub var api_key_present: bool = false;
/// A `codex` binary is on PATH and $CODEX_HOME/auth.json exists.
pub var codex_ready: bool = false;
-/// $CODEX_HOME/generated_images — where graff goes looking for the artifact.
-pub var save_root: []const u8 = "";
+/// The user's real $CODEX_HOME. Each run links its credentials into a PRIVATE
+/// CODEX_HOME (imagegen_codex.prepareHome) and scans that instead, so parallel
+/// callers can never see each other's artifacts.
+pub var codex_home: []const u8 = "";
/// Parent for the private empty cwd each codex run gets.
pub var scratch_root: []const u8 = "/tmp";
@@ -102,7 +105,7 @@ pub fn detect(io: Io, arena: Allocator, env: Env) void {
available = false;
script_path = "";
skill_dir = "";
- save_root = "";
+ codex_home = "";
codex_ready = false;
api_key_present = if (env.openai_api_key) |value| value.len > 0 else false;
if (env.tmp_dir) |t| if (t.len > 0) {
@@ -123,8 +126,13 @@ pub fn detect(io: Io, arena: Allocator, env: Env) void {
}
}
if (script_path.len == 0) {
- script_path = engineScript(io, arena, src) orelse return;
- skill_dir = src;
+ // The script is the FALLBACK engine's, not a precondition for the tool:
+ // a skill whose scripts/ is missing or unreadable still documents the
+ // codex engine, which needs no Python at all. Leaving script_path empty
+ // simply makes `openai_api` unavailable (see the `api_ok` term below).
+ script_path = engineScript(io, arena, src) orelse "";
+ skill_dir = if (script_path.len > 0) src else skill_dir;
+ if (skill_dir.len == 0) skill_dir = src;
}
detectCodex(io, arena, env);
available = true;
@@ -134,11 +142,11 @@ pub fn detect(io: Io, arena: Allocator, env: Env) void {
/// auth.json only ever produces an interactive login prompt, which in a tool
/// call is an unkillable hang rather than an error.
fn detectCodex(io: Io, arena: Allocator, env: Env) void {
- const codex_home = skill.codexHomeDir(arena, env.codex_home, env.home) orelse return;
- const auth = std.fmt.allocPrint(arena, "{s}/auth.json", .{codex_home}) catch return;
+ const home = skill.codexHomeDir(arena, env.codex_home, env.home) orelse return;
+ const auth = std.fmt.allocPrint(arena, "{s}/auth.json", .{home}) catch return;
_ = Io.Dir.cwd().statFile(io, auth, .{}) catch return;
if (!skills.binOnPath(io, "codex")) return;
- save_root = std.fmt.allocPrint(arena, "{s}/{s}", .{ codex_home, codex.save_root_rel }) catch return;
+ codex_home = home;
codex_ready = true;
}
@@ -236,6 +244,17 @@ pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
args.out = resolved;
const before = verify.snapshot(io, resolved);
+ // /rewind parity with write_file: capture what we are about to overwrite
+ // before anything runs, so an imagegen that clobbers a file is undoable.
+ if (ctx.snapshots) |snaps| if (!ctx.from_sub and before.existed) {
+ const prior = Io.Dir.cwd().readFileAlloc(io, resolved, arena, .limited(16 * 1024 * 1024)) catch null;
+ snaps.record(out_rel, prior);
+ };
+ // Same stripe as edit_file/write_file, so an imagegen and an edit_file
+ // landing on one path in the same turn take turns instead of interleaving.
+ const lock = edit_verify.lockPath(io, resolved);
+ defer lock.unlock(io);
+
// Taken BEFORE the spawn: anything a generator produces must be at least
// this new, and a file older than this is by definition not from this run.
const started_ns = Io.Timestamp.now(io, .real).nanoseconds;
@@ -270,12 +289,31 @@ pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
// Resize last, on the already-verified copy, with graff's own hands (#352:
// leaving the resize to the model is how a stale file became "64x64").
var note: []const u8 = "";
- if (resize_to) |size| if (!sips.resize(arena, io, resolved, size)) {
- note = if (sips.available)
- " — WARNING: the requested resize failed, so this is the native-size image"
- else
- " — note: native size (the codex engine cannot request a size, and sips resizing is macOS-only)";
- };
+ if (resize_to) |size| {
+ if (sips.resize(arena, io, resolved, size)) {
+ // The receipt below claims a size and a signature; after a resize
+ // those are claims about DIFFERENT bytes, so they get re-checked
+ // rather than inherited from the pre-resize file.
+ const after_resize: ?verify.Snapshot = blk: {
+ const shot = verify.snapshot(io, resolved);
+ break :blk if (shot.existed) shot else null;
+ };
+ const post = verify.evaluate(before, after_resize, started_ns, headBytes(io, resolved, &head_buf), produced);
+ if (post != .ok) return .{
+ .text = try std.fmt.allocPrint(
+ gpa,
+ "the image was generated and verified, but resizing it to {d}x{d} left a file that no longer verifies.\nfailed check: {s}\nwhat that means: {s}\npath: {s}\nDo not report this as a generated image.",
+ .{ size.w, size.h, post.failedCheck(), post.detail(), out_rel },
+ ),
+ .is_error = true,
+ };
+ } else {
+ note = if (sips.available)
+ " — WARNING: the requested resize failed, so this is the native-size image"
+ else
+ " — note: native size (the codex engine cannot request a size, and sips resizing is macOS-only)";
+ }
+ }
const measured = sips.dims(arena, io, resolved);
const final = verify.snapshot(io, resolved);
return .{ .text = try std.fmt.allocPrint(
@@ -298,16 +336,29 @@ const EngineResult = union(enum) { ok: verify.Format, fail: ToolOutput };
/// The codex engine: spawn, then do every piece of artifact handling ourselves.
fn runCodex(gpa: Allocator, arena: Allocator, io: Io, prompt: []const u8, resolved: []const u8, started_ns: i128) !EngineResult {
- if (save_root.len == 0) return .{ .fail = try errText(gpa, select.no_skill_text) };
- // A private empty cwd: --sandbox workspace-write makes the working
- // directory writable, and an image generation has no business being able
- // to write into the repo it was called from.
+ if (codex_home.len == 0) return .{ .fail = try errText(gpa, select.no_skill_text) };
+ // One scratch tree per run holding two things: a private empty cwd
+ // (--sandbox workspace-write makes the working directory writable, and an
+ // image generation has no business writing into the repo it was called
+ // from) and a private CODEX_HOME, so this run's generated_images is ours
+ // alone and a parallel sibling's artifact can never be adopted as our own.
const scratch = makeScratch(io, arena) orelse
return .{ .fail = try errText(gpa, "could not create a private scratch directory for the codex engine — set TMPDIR to a writable location, or pass engine \"openai_api\". Nothing was generated.") };
- defer Io.Dir.cwd().deleteTree(io, scratch) catch {};
+ const private_home = try std.fmt.allocPrint(arena, "{s}/home", .{scratch});
+ const child_cwd = try std.fmt.allocPrint(arena, "{s}/cwd", .{scratch});
+ defer {
+ codex.unlinkHome(io, arena, private_home); // before the tree walk, never through a symlink
+ Io.Dir.cwd().deleteTree(io, scratch) catch {};
+ }
+ Io.Dir.cwd().createDirPath(io, child_cwd) catch {};
+ codex.prepareHome(io, arena, private_home, codex_home) catch |err| return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "could not set up a private CODEX_HOME for this run ({t}) — nothing was generated.", .{err}),
+ .is_error = true,
+ } };
+ const save_root = try codex.saveRoot(arena, private_home);
- const argv = try codex.buildArgv(arena, try codex.buildPrompt(arena, prompt));
- const out = run_mod.run(arena, io, argv, codex.deadline_ms, scratch) catch |err| switch (err) {
+ const argv = try codex.buildArgv(arena, private_home, try codex.buildPrompt(arena, prompt));
+ const out = run_mod.run(arena, io, argv, codex.deadline_ms, child_cwd) catch |err| switch (err) {
error.FileNotFound => return .{ .fail = try errText(gpa, "the codex CLI is no longer on PATH, so the preferred imagegen engine cannot run. Reinstall it (bun install -g @openai/codex) or pass engine \"openai_api\". Nothing was generated.") },
else => return .{ .fail = tools.failure(gpa, err) },
};
@@ -422,151 +473,8 @@ pub fn defaultOutPath(io: Io, arena: Allocator, base: ?[]const u8, ext: []const
return error.PathAlreadyExists;
}
-const testing = std.testing;
-
-test "#352: default out paths stay unique across many rapid calls (the subagent fan-out case)" {
- const io = testing.io;
- var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
- defer arena_state.deinit();
- const arena = arena_state.allocator();
-
- var tmp = testing.tmpDir(.{});
- defer tmp.cleanup();
- var real_buf: [std.fs.max_path_bytes]u8 = undefined;
- const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
-
- var seen: std.StringHashMapUnmanaged(void) = .empty;
- defer seen.deinit(testing.allocator);
- for (0..256) |_| {
- const path = try defaultOutPath(io, arena, base, "png");
- try testing.expect(std.mem.startsWith(u8, path, "imagegen-"));
- try testing.expect(confinedPath(path)); // a default path is always writable by the file tools
- try testing.expect((try seen.fetchPut(testing.allocator, path, {})) == null);
- }
- const taken = try defaultOutPath(io, arena, base, "png");
- try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ base, taken }), .data = "x" });
- try testing.expect(!std.mem.eql(u8, taken, try defaultOutPath(io, arena, base, "png")));
-}
-
-test "#352: detect gates on the Codex skill, mirrors it, and decides which engines this machine has" {
- const io = testing.io;
- var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
- defer arena_state.deinit();
- const arena = arena_state.allocator();
-
- const saved = .{ available, script_path, skill_dir, api_key_present, codex_ready, save_root };
- defer {
- available = saved[0];
- script_path = saved[1];
- skill_dir = saved[2];
- api_key_present = saved[3];
- codex_ready = saved[4];
- save_root = saved[5];
- }
-
- var tmp = testing.tmpDir(.{});
- defer tmp.cleanup();
- var real_buf: [std.fs.max_path_bytes]u8 = undefined;
- const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
- const codex_home = try std.fmt.allocPrint(arena, "{s}/codex", .{base});
- const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});
-
- // A CODEX_HOME with no skill in it: the tool does not exist.
- try Io.Dir.cwd().createDirPath(io, codex_home);
- detect(io, arena, .{ .codex_home = codex_home, .home = home });
- try testing.expect(!available);
- try testing.expectEqualStrings("", script_path);
- try testing.expect(!api_key_present and !codex_ready);
-
- // Install the skill where Codex keeps it.
- const src = try std.fmt.allocPrint(arena, "{s}/{s}", .{ codex_home, skill.codex_rel });
- try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/scripts", .{src}));
- for ([_]struct { path: []const u8, data: []const u8 }{
- .{ .path = "SKILL.md", .data = "---\nname: imagegen\ndescription: d\n---\n\n# Image Generation Skill\nuse image_gen\n" },
- .{ .path = "LICENSE.txt", .data = "LICENSE BODY" },
- .{ .path = "scripts/image_gen.py", .data = "print('gen')" },
- }) |f| try Io.Dir.cwd().writeFile(io, .{
- .sub_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ src, f.path }),
- .data = f.data,
- });
-
- detect(io, arena, .{ .codex_home = codex_home, .home = home, .openai_api_key = "sk-test" });
- try testing.expect(available and api_key_present);
- // No auth.json in this fake CODEX_HOME, so the codex engine is not offered
- // however the real CLI happens to be installed on the test machine.
- try testing.expect(!codex_ready);
-
- const dest = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, skill.install_rel });
- try testing.expectEqualStrings(dest, skill_dir);
- const license = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/LICENSE.txt", .{dest}), arena, .limited(4096));
- try testing.expectEqualStrings("LICENSE BODY", license);
- const md = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{dest}), arena, .limited(1 << 16));
- try testing.expect(std.mem.indexOf(u8, md, "<!-- graff addendum -->") != null);
- try testing.expect(std.mem.indexOf(u8, md, "one subagent per") != null);
- try testing.expect(std.mem.indexOf(u8, md, "use image_gen") != null); // original body kept
-
- // An empty key is not a key.
- detect(io, arena, .{ .codex_home = codex_home, .home = home, .openai_api_key = "" });
- try testing.expect(available and !api_key_present);
-}
-
-test "#352: with no usable engine the tool refuses up front and spawns nothing" {
- const gpa = testing.allocator;
- const saved = .{ available, script_path, api_key_present, codex_ready };
- defer {
- available = saved[0];
- script_path = saved[1];
- api_key_present = saved[2];
- codex_ready = saved[3];
- }
- // Any spawn at all is a test failure: nothing below should reach one.
- const S = struct {
- fn boom(_: Allocator, _: Io, _: []const []const u8, _: u64, _: ?[]const u8) anyerror!run_mod.Outcome {
- return error.TestUnexpectedSpawn;
- }
- };
- const saved_hook = run_mod.hook;
- defer run_mod.hook = saved_hook;
- run_mod.hook = S.boom;
-
- var parsed = try std.json.parseFromSlice(Value, gpa, "{\"prompt\":\"a red circle\"}", .{});
- defer parsed.deinit();
- var client: std.http.Client = undefined;
- const ctx: ToolCtx = .{
- .gpa = gpa,
- .io = testing.io,
- .client = &client,
- .provider = undefined,
- .registry = null,
- .from_sub = false,
- .approvals = null,
- .tracer = null,
- };
-
- available = false;
- const off = try execImagegen(ctx, parsed.value);
- defer gpa.free(off.text);
- try testing.expect(off.is_error and std.mem.indexOf(u8, off.text, "CODEX_HOME") != null);
-
- // Detected, but neither engine usable: the refusal names both requirements.
- available = true;
- codex_ready = false;
- api_key_present = false;
- script_path = "/nonexistent/image_gen.py";
- const none = try execImagegen(ctx, parsed.value);
- defer gpa.free(none.text);
- try testing.expect(none.is_error);
- for ([_][]const u8{ "codex login", "OPENAI_API_KEY", "#352", "NOTHING was generated" }) |needle|
- try testing.expect(std.mem.indexOf(u8, none.text, needle) != null);
-
- var empty = try std.json.parseFromSlice(Value, gpa, "{}", .{});
- defer empty.deinit();
- const no_prompt = try execImagegen(ctx, empty.value);
- defer gpa.free(no_prompt.text);
- try testing.expect(no_prompt.is_error and std.mem.indexOf(u8, no_prompt.text, "prompt") != null);
-}
-
test {
+ _ = @import("imagegen_tests.zig"); // an unreferenced module's tests never run
_ = skill;
_ = verify;
_ = select;
diff --git a/src/imagegen_codex.zig b/src/imagegen_codex.zig
index 9ff7c357..ab8d9103 100644
--- a/src/imagegen_codex.zig
+++ b/src/imagegen_codex.zig
@@ -42,18 +42,76 @@ pub const save_root_rel = "generated_images";
const max_scan_depth: u8 = 4; // real layout is <save_root>/<session>/<call>.png
/// codex exec, non-interactive, with the feature flag forced on so the tool is
-/// offered even when the user's config.toml never enabled it. The model comes
+/// offered even when the user's config.toml never enabled it, and pointed at a
+/// PRIVATE CODEX_HOME for this one run (see `prepareHome`). The model comes
/// from the user's own codex config — graff does not pick one, because which
/// models carry the image capabilities is codex's business, not ours.
-pub fn buildArgv(arena: Allocator, prompt: []const u8) ![]const []const u8 {
+///
+/// `env` rather than a shell: CODEX_HOME has to reach the child, and `sh -c`
+/// would put a model-supplied prompt through a quoting layer for no reason.
+pub fn buildArgv(arena: Allocator, private_home: []const u8, prompt: []const u8) ![]const []const u8 {
return arena.dupe([]const u8, &.{
- "codex", "exec",
- "--sandbox", "workspace-write",
- "-c", "features.image_generation=true",
+ "env",
+ try std.fmt.allocPrint(arena, "CODEX_HOME={s}", .{private_home}),
+ "codex",
+ "exec",
+ "--sandbox",
+ "workspace-write",
+ "-c",
+ "features.image_generation=true",
prompt,
});
}
+/// Credentials that make a private CODEX_HOME usable. Symlinked rather than
+/// copied so a token never lands as a second plaintext file in a temp dir.
+pub const linked_files = [_][]const u8{ "auth.json", "config.toml" };
+
+/// Build a private CODEX_HOME for ONE run.
+///
+/// Why this exists: `generated_images` is shared state. Scanning the user's
+/// real save_root for "the newest fresh file" is safe with one caller and
+/// unsafe with the N-parallel-subagents pattern this tool documents — a run
+/// that fabricated (wrote nothing, exited 0) would happily adopt a SIBLING's
+/// artifact, pass every freshness and magic check, and hand back an image it
+/// did not generate. That is #352 again, and the checks cannot catch it,
+/// because the file really is fresh and really is an image; it just belongs
+/// to someone else. Two callers could equally be handed the same bytes, and a
+/// human using the Codex app during the run could have their image captured
+/// into a tool result.
+///
+/// So each invocation gets its own CODEX_HOME holding only the credential
+/// files, and therefore its own empty `generated_images`. Our scan cannot see
+/// anyone else's artifacts, and nobody else can see ours.
+///
+/// Accepted caveat: if codex refreshes its token during the run and writes it
+/// by atomic replace, the replacement lands on the private copy and is
+/// discarded with it. The next real run refreshes again — a refresh is
+/// idempotent, and losing one is far cheaper than cross-attributing an image.
+pub fn prepareHome(io: Io, arena: Allocator, private_home: []const u8, real_home: []const u8) !void {
+ try Io.Dir.cwd().createDirPath(io, private_home);
+ for (linked_files) |name| {
+ const target = try std.fmt.allocPrint(arena, "{s}/{s}", .{ real_home, name });
+ _ = Io.Dir.cwd().statFile(io, target, .{}) catch continue; // config.toml is optional
+ const link = try std.fmt.allocPrint(arena, "{s}/{s}", .{ private_home, name });
+ Io.Dir.cwd().symLink(io, target, link, .{}) catch {};
+ }
+}
+
+/// Remove the credential symlinks BEFORE the tree is deleted, so a delete can
+/// never walk into the user's real CODEX_HOME through one of them.
+pub fn unlinkHome(io: Io, arena: Allocator, private_home: []const u8) void {
+ for (linked_files) |name| {
+ const link = std.fmt.allocPrint(arena, "{s}/{s}", .{ private_home, name }) catch continue;
+ Io.Dir.cwd().deleteFile(io, link) catch {};
+ }
+}
+
+/// This run's private save_root.
+pub fn saveRoot(arena: Allocator, private_home: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ private_home, save_root_rel });
+}
+
/// The instruction codex actually receives. It pins the tool, forbids the file
/// handling graff is about to do itself, and asks for a short reply so a long
/// narrative cannot crowd out the stderr tail we keep for diagnostics.
@@ -104,8 +162,14 @@ fn scan(io: Io, arena: Allocator, dir_path: []const u8, since_ns: i128, depth: u
const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ dir_path, entry.name }) catch continue;
switch (entry.kind) {
.directory => scan(io, arena, path, since_ns, depth + 1, best),
- .file => {
+ // Some filesystems (and some network mounts) report `.unknown` from
+ // readdir rather than a type; stat decides instead of skipping.
+ .file, .unknown => {
const st = Io.Dir.cwd().statFile(io, path, .{}) catch continue;
+ if (st.kind == .directory) {
+ scan(io, arena, path, since_ns, depth + 1, best);
+ continue;
+ }
if (st.kind != .file) continue;
if (st.mtime.nanoseconds < since_ns) continue; // predates this run
if (best.*) |cur| {
@@ -154,12 +218,87 @@ test "#352: argv forces the feature flag on and runs codex non-interactively" {
defer arena_state.deinit();
const arena = arena_state.allocator();
- const argv = try buildArgv(arena, "PROMPT");
- const want = [_][]const u8{ "codex", "exec", "--sandbox", "workspace-write", "-c", "features.image_generation=true", "PROMPT" };
+ const argv = try buildArgv(arena, "/tmp/priv", "PROMPT");
+ const want = [_][]const u8{
+ "env", "CODEX_HOME=/tmp/priv", "codex", "exec",
+ "--sandbox", "workspace-write", "-c", "features.image_generation=true",
+ "PROMPT",
+ };
try testing.expectEqual(want.len, argv.len);
for (want, argv) |w, got| try testing.expectEqualStrings(w, got);
// No model is pinned: which models carry the capability is codex's call.
for (argv) |a| try testing.expect(!std.mem.eql(u8, a, "--model") and !std.mem.eql(u8, a, "-m"));
+ // The prompt is a single argv slot; no shell is involved, so no quoting
+ // layer can reinterpret it.
+ try testing.expectEqualStrings("env", argv[0]);
+ try testing.expectEqualStrings("PROMPT", argv[argv.len - 1]);
+}
+
+test "#352: a private CODEX_HOME links only credentials, so its save_root starts empty and isolated" {
+ const io = testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+
+ // A "real" CODEX_HOME with credentials AND somebody else's artifacts.
+ const real_home = try std.fmt.allocPrint(arena, "{s}/codex", .{base});
+ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/generated_images/other", .{real_home}));
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/auth.json", .{real_home}), .data = "{\"tok\":1}" });
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/generated_images/other/exec-theirs.png", .{real_home}), .data = "\x89PNG\r\n\x1a\n" ++ "theirs" });
+
+ const private_home = try std.fmt.allocPrint(arena, "{s}/run-a/home", .{base});
+ try prepareHome(io, arena, private_home, real_home);
+
+ // Credentials reachable through the link...
+ const auth = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/auth.json", .{private_home}), arena, .limited(64));
+ try testing.expectEqualStrings("{\"tok\":1}", auth);
+ // ...and no config.toml link, because the source had none.
+ try testing.expect(Io.Dir.cwd().statFile(io, try std.fmt.allocPrint(arena, "{s}/config.toml", .{private_home}), .{}) == error.FileNotFound);
+
+ // The private save_root is empty: a sibling's fresh artifact is invisible.
+ const mine = try saveRoot(arena, private_home);
+ try testing.expect(newestFresh(io, arena, mine, 0) == null);
+ // ...while the real one obviously still has it — proving the isolation is
+ // what hides it, not an empty fixture.
+ try testing.expect(newestFresh(io, arena, try std.fmt.allocPrint(arena, "{s}/generated_images", .{real_home}), 0) != null);
+
+ // Cleanup unlinks credentials first, so deleting the tree cannot reach
+ // through a symlink into the user's real CODEX_HOME.
+ unlinkHome(io, arena, private_home);
+ try Io.Dir.cwd().deleteTree(io, try std.fmt.allocPrint(arena, "{s}/run-a", .{base}));
+ const survived = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/auth.json", .{real_home}), arena, .limited(64));
+ try testing.expectEqualStrings("{\"tok\":1}", survived);
+}
+
+test "#352: two concurrent runs cannot see each other's artifacts" {
+ const io = testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+
+ const a_root = try std.fmt.allocPrint(arena, "{s}/a/generated_images/s1", .{base});
+ const b_root = try std.fmt.allocPrint(arena, "{s}/b/generated_images/s1", .{base});
+ try Io.Dir.cwd().createDirPath(io, a_root);
+ try Io.Dir.cwd().createDirPath(io, b_root);
+ // Only run A produced something. Run B fabricated: exit 0, no file.
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/exec-a.png", .{a_root}), .data = "\x89PNG\r\n\x1a\n" ++ "aaaa" });
+
+ const a_save = try std.fmt.allocPrint(arena, "{s}/a/generated_images", .{base});
+ const b_save = try std.fmt.allocPrint(arena, "{s}/b/generated_images", .{base});
+ try testing.expect(newestFresh(io, arena, a_save, 0) != null);
+ // The whole point: B finds nothing even though a fresh, valid, sibling
+ // image exists on the same machine at the same moment.
+ try testing.expect(newestFresh(io, arena, b_save, 0) == null);
}
test "#352: the controlled prompt carries the user's text and forbids the file handling graff does itself" {
diff --git a/src/imagegen_openai.zig b/src/imagegen_openai.zig
index 2a251c0d..9fc5d953 100644
--- a/src/imagegen_openai.zig
+++ b/src/imagegen_openai.zig
@@ -35,12 +35,20 @@ pub const Args = struct {
///
/// `--dry-run` is deliberately never assembled: it prints a plan and writes no
/// file, so it could only ever produce an unverifiable "success".
+/// `--prompt=<v>` / `--out=<v>` rather than two argv slots: those two values are
+/// free-form (a prompt is model-supplied, a path is caller-supplied), and a
+/// leading '-' in the separate form is eaten by argparse as a flag. The `=`
+/// form binds the value to its option no matter what it starts with.
pub fn buildArgv(arena: Allocator, script: []const u8, a: Args) ![]const []const u8 {
var argv: std.ArrayList([]const u8) = .empty;
try argv.appendSlice(arena, &.{
- "python3", script, "generate",
- "--prompt", a.prompt, "--out",
- a.out, "--force", "--model",
+ "python3",
+ script,
+ "generate",
+ try std.fmt.allocPrint(arena, "--prompt={s}", .{a.prompt}),
+ try std.fmt.allocPrint(arena, "--out={s}", .{a.out}),
+ "--force",
+ "--model",
a.model,
});
if (a.size) |v| try argv.appendSlice(arena, &.{ "--size", v });
@@ -75,12 +83,18 @@ test "#352: argv is a generate call with the required flags, optionals only when
const minimal = try buildArgv(arena, "/s/image_gen.py", .{ .prompt = "a red circle", .out = "out.png" });
const want = [_][]const u8{
- "python3", "/s/image_gen.py", "generate", "--prompt", "a red circle",
- "--out", "out.png", "--force", "--model", default_model,
+ "python3", "/s/image_gen.py", "generate", "--prompt=a red circle",
+ "--out=out.png", "--force", "--model", default_model,
};
try testing.expectEqual(want.len, minimal.len);
for (want, minimal) |w, got| try testing.expectEqualStrings(w, got);
+ // A prompt or path starting with '-' must stay bound to its option rather
+ // than being read as a flag.
+ const dashed = try buildArgv(arena, "/s/g.py", .{ .prompt = "--force a wireframe", .out = "-weird.png" });
+ try testing.expectEqualStrings("--prompt=--force a wireframe", dashed[3]);
+ try testing.expectEqualStrings("--out=-weird.png", dashed[4]);
+
const full = try buildArgv(arena, "/s/image_gen.py", .{
.prompt = "p",
.out = "o.webp",
@@ -90,7 +104,7 @@ test "#352: argv is a generate call with the required flags, optionals only when
.background = "transparent",
.output_format = "webp",
});
- try testing.expectEqual(@as(usize, 18), full.len);
+ try testing.expectEqual(@as(usize, 16), full.len);
for ([_][]const u8{ "--size", "1024x1536", "--quality", "high", "--background", "transparent", "--output-format", "webp" }) |needle| {
var found = false;
for (full) |arg| {
diff --git a/src/imagegen_tests.zig b/src/imagegen_tests.zig
new file mode 100644
index 00000000..19fa9424
--- /dev/null
+++ b/src/imagegen_tests.zig
@@ -0,0 +1,350 @@
+//! #352 imagegen behaviour tests. Split out of imagegen.zig (600-line
+//! ceiling); referenced from its test block so they actually run.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const imagegen = @import("imagegen.zig");
+const codex = @import("imagegen_codex.zig");
+const skill = @import("imagegen_skill.zig");
+const run_mod = @import("imagegen_run.zig");
+const tools = @import("tools.zig");
+const ToolCtx = tools.ToolCtx;
+const confinedPath = @import("approvals.zig").confinedPath;
+const detect = imagegen.detect;
+const execImagegen = imagegen.execImagegen;
+const defaultOutPath = imagegen.defaultOutPath;
+
+const testing = std.testing;
+
+test "#352: default out paths stay unique across many rapid calls (the subagent fan-out case)" {
+ const io = testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+
+ var seen: std.StringHashMapUnmanaged(void) = .empty;
+ defer seen.deinit(testing.allocator);
+ for (0..256) |_| {
+ const path = try defaultOutPath(io, arena, base, "png");
+ try testing.expect(std.mem.startsWith(u8, path, "imagegen-"));
+ try testing.expect(confinedPath(path)); // a default path is always writable by the file tools
+ try testing.expect((try seen.fetchPut(testing.allocator, path, {})) == null);
+ }
+ const taken = try defaultOutPath(io, arena, base, "png");
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ base, taken }), .data = "x" });
+ try testing.expect(!std.mem.eql(u8, taken, try defaultOutPath(io, arena, base, "png")));
+}
+
+test "#352: detect gates on the Codex skill, mirrors it, and decides which engines this machine has" {
+ const io = testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const saved = .{ imagegen.available, imagegen.script_path, imagegen.skill_dir, imagegen.api_key_present, imagegen.codex_ready, imagegen.codex_home };
+ defer {
+ imagegen.available = saved[0];
+ imagegen.script_path = saved[1];
+ imagegen.skill_dir = saved[2];
+ imagegen.api_key_present = saved[3];
+ imagegen.codex_ready = saved[4];
+ imagegen.codex_home = saved[5];
+ }
+
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+ const fake_codex_home = try std.fmt.allocPrint(arena, "{s}/codex", .{base});
+ const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});
+
+ // A CODEX_HOME with no skill in it: the tool does not exist.
+ try Io.Dir.cwd().createDirPath(io, fake_codex_home);
+ detect(io, arena, .{ .codex_home = fake_codex_home, .home = home });
+ try testing.expect(!imagegen.available);
+ try testing.expectEqualStrings("", imagegen.script_path);
+ try testing.expect(!imagegen.api_key_present and !imagegen.codex_ready);
+
+ // Install the skill where Codex keeps it.
+ const src = try std.fmt.allocPrint(arena, "{s}/{s}", .{ fake_codex_home, skill.codex_rel });
+ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/scripts", .{src}));
+ for ([_]struct { path: []const u8, data: []const u8 }{
+ .{ .path = "SKILL.md", .data = "---\nname: imagegen\ndescription: d\n---\n\n# Image Generation Skill\nuse image_gen\n" },
+ .{ .path = "LICENSE.txt", .data = "LICENSE BODY" },
+ .{ .path = "scripts/image_gen.py", .data = "print('gen')" },
+ }) |f| try Io.Dir.cwd().writeFile(io, .{
+ .sub_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ src, f.path }),
+ .data = f.data,
+ });
+
+ detect(io, arena, .{ .codex_home = fake_codex_home, .home = home, .openai_api_key = "sk-test" });
+ try testing.expect(imagegen.available and imagegen.api_key_present);
+ // No auth.json in this fake CODEX_HOME, so the codex engine is not offered
+ // however the real CLI happens to be installed on the test machine.
+ try testing.expect(!imagegen.codex_ready);
+
+ const dest = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, skill.install_rel });
+ try testing.expectEqualStrings(dest, imagegen.skill_dir);
+ const license = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/LICENSE.txt", .{dest}), arena, .limited(4096));
+ try testing.expectEqualStrings("LICENSE BODY", license);
+ const md = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{dest}), arena, .limited(1 << 16));
+ try testing.expect(std.mem.indexOf(u8, md, "<!-- graff addendum -->") != null);
+ try testing.expect(std.mem.indexOf(u8, md, "one subagent per") != null);
+ try testing.expect(std.mem.indexOf(u8, md, "use image_gen") != null); // original body kept
+
+ // An empty key is not a key.
+ detect(io, arena, .{ .codex_home = fake_codex_home, .home = home, .openai_api_key = "" });
+ try testing.expect(imagegen.available and !imagegen.api_key_present);
+}
+
+test "#352: with no usable engine the tool refuses up front and spawns nothing" {
+ const gpa = testing.allocator;
+ const saved = .{ imagegen.available, imagegen.script_path, imagegen.api_key_present, imagegen.codex_ready };
+ defer {
+ imagegen.available = saved[0];
+ imagegen.script_path = saved[1];
+ imagegen.api_key_present = saved[2];
+ imagegen.codex_ready = saved[3];
+ }
+ // Any spawn at all is a test failure: nothing below should reach one.
+ const S = struct {
+ fn boom(_: Allocator, _: Io, _: []const []const u8, _: u64, _: ?[]const u8) anyerror!run_mod.Outcome {
+ return error.TestUnexpectedSpawn;
+ }
+ };
+ const saved_hook = run_mod.hook;
+ defer run_mod.hook = saved_hook;
+ run_mod.hook = S.boom;
+
+ var parsed = try std.json.parseFromSlice(Value, gpa, "{\"prompt\":\"a red circle\"}", .{});
+ defer parsed.deinit();
+ var client: std.http.Client = undefined;
+ const ctx: ToolCtx = .{
+ .gpa = gpa,
+ .io = testing.io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ };
+
+ imagegen.available = false;
+ const off = try execImagegen(ctx, parsed.value);
+ defer gpa.free(off.text);
+ try testing.expect(off.is_error and std.mem.indexOf(u8, off.text, "CODEX_HOME") != null);
+
+ // Detected, but neither engine usable: the refusal names both requirements.
+ imagegen.available = true;
+ imagegen.codex_ready = false;
+ imagegen.api_key_present = false;
+ imagegen.script_path = "/nonexistent/image_gen.py";
+ const none = try execImagegen(ctx, parsed.value);
+ defer gpa.free(none.text);
+ try testing.expect(none.is_error);
+ for ([_][]const u8{ "codex login", "OPENAI_API_KEY", "#352", "NOTHING was generated" }) |needle|
+ try testing.expect(std.mem.indexOf(u8, none.text, needle) != null);
+
+ var empty = try std.json.parseFromSlice(Value, gpa, "{}", .{});
+ defer empty.deinit();
+ const no_prompt = try execImagegen(ctx, empty.value);
+ defer gpa.free(no_prompt.text);
+ try testing.expect(no_prompt.is_error and std.mem.indexOf(u8, no_prompt.text, "prompt") != null);
+}
+
+/// A fake `codex exec` for the replay tests below. It reads the private
+/// CODEX_HOME out of the argv graff built, plants whatever artifact the
+/// scenario calls for, and always exits 0 with a confident success narrative —
+/// because that is exactly what #352 did.
+const FakeCodex = struct {
+ /// What to leave in the private save_root before "succeeding".
+ var plant: enum { nothing, stale_png, fresh_png, fresh_junk } = .nothing;
+ var transcript: []const u8 = "Generated your 64x64 PNG. Verified it is a 64x64 PNG.";
+
+ fn privateHome(argv: []const []const u8) ?[]const u8 {
+ for (argv) |a| {
+ if (std.mem.startsWith(u8, a, "CODEX_HOME=")) return a["CODEX_HOME=".len..];
+ }
+ return null;
+ }
+
+ fn run(a: Allocator, io: Io, argv: []const []const u8, _: u64, _: ?[]const u8) anyerror!run_mod.Outcome {
+ // sips (dimension reporting) also goes through the seam.
+ if (std.mem.eql(u8, argv[0], "sips"))
+ return .{ .exit_code = 0, .stdout = "f\n pixelWidth: 64\n pixelHeight: 64\n" };
+
+ const home = privateHome(argv) orelse return error.TestMissingCodexHome;
+ if (plant != .nothing) {
+ const dir = try std.fmt.allocPrint(a, "{s}/generated_images/019f-session", .{home});
+ try Io.Dir.cwd().createDirPath(io, dir);
+ const path = try std.fmt.allocPrint(a, "{s}/exec-call.png", .{dir});
+ const png = "\x89PNG\r\n\x1a\n" ++ ("p" ** 4096);
+ try Io.Dir.cwd().writeFile(io, .{
+ .sub_path = path,
+ .data = if (plant == .fresh_junk) "{\"error\": \"no\"}" ++ ("x" ** 4096) else png,
+ });
+ if (plant == .stale_png) {
+ const two_weeks: i128 = 14 * 24 * 60 * 60 * std.time.ns_per_s;
+ const then = Io.Timestamp.now(io, .real).nanoseconds - two_weeks;
+ try Io.Dir.cwd().setTimestamps(io, path, .{ .modify_timestamp = .{ .new = .{ .nanoseconds = @intCast(then) } } });
+ }
+ }
+ // Exit 0, every time. The transcript is confident, every time.
+ return .{ .exit_code = 0, .stdout = transcript };
+ }
+};
+
+// The whole point of the tool, end to end: a codex run that says it succeeded
+// but produced nothing this run must come back as an ERROR.
+test "#352 replay: codex exits 0 with a confident success transcript and NO fresh artifact — reported as failure" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ // A real-looking CODEX_HOME (credentials only) plus a work dir for output.
+ const home = try std.fmt.allocPrint(arena, "{s}/codex", .{base});
+ try Io.Dir.cwd().createDirPath(io, home);
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/auth.json", .{home}), .data = "{}" });
+ const work = try std.fmt.allocPrint(arena, "{s}/work", .{base});
+ try Io.Dir.cwd().createDirPath(io, work);
+
+ const saved = .{ imagegen.available, imagegen.codex_ready, imagegen.codex_home, imagegen.scratch_root, imagegen.api_key_present, run_mod.hook };
+ defer {
+ imagegen.available = saved[0];
+ imagegen.codex_ready = saved[1];
+ imagegen.codex_home = saved[2];
+ imagegen.scratch_root = saved[3];
+ imagegen.api_key_present = saved[4];
+ run_mod.hook = saved[5];
+ }
+ imagegen.available = true;
+ imagegen.codex_ready = true;
+ imagegen.codex_home = home;
+ imagegen.scratch_root = base;
+ imagegen.api_key_present = false; // codex engine only
+ run_mod.hook = FakeCodex.run;
+
+ var client: std.http.Client = undefined;
+ const ctx: ToolCtx = .{
+ .gpa = gpa,
+ .io = io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ .agent_cwd = work, // output lands in the temp work dir, not the repo
+ };
+ var input = try std.json.parseFromSlice(Value, gpa, "{\"prompt\":\"a 64x64 red circle\",\"out\":\"shot.png\"}", .{});
+ defer input.deinit();
+ const out_path = try std.fmt.allocPrint(arena, "{s}/shot.png", .{work});
+
+ // 1. THE #352 CASE: exit 0, confident transcript, nothing written.
+ FakeCodex.plant = .nothing;
+ {
+ const r = try execImagegen(ctx, input.value);
+ defer gpa.free(r.text);
+ try std.testing.expect(r.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "#352") != null);
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "no image was generated") != null);
+ // and no file was invented at the output path
+ try std.testing.expect(Io.Dir.cwd().statFile(io, out_path, .{}) == error.FileNotFound);
+ }
+
+ // 2. A STALE artifact in our own save_root is still not this run's work.
+ FakeCodex.plant = .stale_png;
+ {
+ const r = try execImagegen(ctx, input.value);
+ defer gpa.free(r.text);
+ try std.testing.expect(r.is_error);
+ try std.testing.expect(Io.Dir.cwd().statFile(io, out_path, .{}) == error.FileNotFound);
+ }
+
+ // 3. A fresh file that is not an image fails on its signature.
+ FakeCodex.plant = .fresh_junk;
+ {
+ const r = try execImagegen(ctx, input.value);
+ defer gpa.free(r.text);
+ try std.testing.expect(r.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "not a PNG, JPEG or WebP") != null);
+ }
+
+ // 4. The happy path, to prove the failures above are the checks working
+ // rather than the tool being broken: a fresh valid PNG is copied out and
+ // reported with a receipt naming the checks that passed.
+ FakeCodex.plant = .fresh_png;
+ {
+ const r = try execImagegen(ctx, input.value);
+ defer gpa.free(r.text);
+ try std.testing.expect(!r.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "generated and verified: shot.png") != null);
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "engine codex") != null);
+ const copied = try Io.Dir.cwd().readFileAlloc(io, out_path, arena, .limited(1 << 16));
+ try std.testing.expect(std.mem.startsWith(u8, copied, "\x89PNG\r\n\x1a\n"));
+ }
+
+ // The private CODEX_HOME is cleaned up, and the real one still has its
+ // credentials (the symlinks were unlinked, not followed).
+ const auth = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/auth.json", .{home}), arena, .limited(16));
+ try std.testing.expectEqualStrings("{}", auth);
+ try std.testing.expect(Io.Dir.cwd().statFile(io, try std.fmt.allocPrint(arena, "{s}/generated_images", .{home}), .{}) == error.FileNotFound);
+}
+
+test "#352 + plan mode: imagegen is refused like write_file, and nothing is spawned" {
+ const gpa = std.testing.allocator;
+ const main_mod = @import("main.zig");
+ const exec = @import("exec.zig");
+
+ const saved_plan = main_mod.plan_mode;
+ const saved_available = imagegen.available;
+ const saved_hook = run_mod.hook;
+ defer {
+ main_mod.plan_mode = saved_plan;
+ imagegen.available = saved_available;
+ run_mod.hook = saved_hook;
+ }
+ const S = struct {
+ fn boom(_: Allocator, _: Io, _: []const []const u8, _: u64, _: ?[]const u8) anyerror!run_mod.Outcome {
+ return error.TestUnexpectedSpawn;
+ }
+ };
+ run_mod.hook = S.boom;
+ imagegen.available = true;
+ main_mod.plan_mode = true;
+
+ var input = try std.json.parseFromSlice(Value, gpa, "{\"prompt\":\"a red circle\"}", .{});
+ defer input.deinit();
+ var client: std.http.Client = undefined;
+ const ctx: ToolCtx = .{
+ .gpa = gpa,
+ .io = std.testing.io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = true, // the subagent path, which skips the root gate
+ .approvals = null,
+ .tracer = null,
+ };
+ const denied = exec.execTool(ctx, .{ .id = "c1", .name = "imagegen", .input = input.value });
+ defer gpa.free(denied.text);
+ try std.testing.expect(denied.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, denied.text, "plan mode") != null);
+}
diff --git a/src/no_local_tools.zig b/src/no_local_tools.zig
index 39a4030c..4afe8632 100644
--- a/src/no_local_tools.zig
+++ b/src/no_local_tools.zig
@@ -41,6 +41,13 @@ pub const gated_tools = [_][]const u8{
"edit_file",
"write_file",
"codedb",
+ // #352: imagegen looks like a content tool but is a local write-and-spawn
+ // primitive — it starts `codex exec --sandbox workspace-write` or python3
+ // on THIS host and writes a file into the working tree. Being optional
+ // (tool_gates.zig) does not exempt it: an embedder that removed bash and
+ // write_file would otherwise still be handed a way to run a process and
+ // land bytes on disk.
+ "imagegen",
};
/// A name test only, independent of whether the gate is on, so the comptime
@@ -105,7 +112,8 @@ test "#330: the gated set is exactly the host-touching built-ins; webfetch, meta
defer enabled = saved;
for (gated_tools) |tool| try std.testing.expect(isLocalTool(tool));
- try std.testing.expectEqual(@as(usize, 7), gated_tools.len);
+ try std.testing.expectEqual(@as(usize, 8), gated_tools.len);
+ try std.testing.expect(isLocalTool("imagegen")); // #352: optional, but still a local spawn+write
for ([_][]const u8{ "webfetch", "skill", "subagent", "workflow", "todo_write", "eval", "mcp__sandbox__exec", "mcp__sandbox__bash" }) |tool|
try std.testing.expect(!isLocalTool(tool));
@@ -157,7 +165,15 @@ test "#330: neither catalog advertises a local tool under the gate, and webfetch
const arena = arena_state.allocator();
const saved = enabled;
- defer enabled = saved;
+ // #352: imagegen is optional, so the ungated catalog only carries every
+ // gated name while it is available — turn it on for this comparison.
+ const imagegen = @import("imagegen.zig");
+ const saved_imagegen = imagegen.available;
+ defer {
+ enabled = saved;
+ imagegen.available = saved_imagegen;
+ }
+ imagegen.available = true;
// Root catalog (runtime-assembled, and the one MCP tools are appended to).
enabled = false;
diff --git a/src/schema.zig b/src/schema.zig
index 2f1378ff..b7d8abdb 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -320,8 +320,9 @@ pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {
(if (learn_store.active_agent_loaded) &root_specs else &root_specs_without_learning)
else
(if (learn_store.active_agent_loaded) &root_specs_without_clock else &root_specs_without_optional);
- const filtered = try no_local_tools.filterRootSpecs(ToolSpec, arena, chosen);
- return tool_gates.withAvailable(ToolSpec, arena, filtered, &optional_specs);
+ // Optionals are appended BEFORE the #330 filter, never after: being
+ // optional does not exempt a tool from the hard gate.
+ return no_local_tools.filterRootSpecs(ToolSpec, arena, try tool_gates.withAvailable(ToolSpec, arena, chosen, &optional_specs));
}
const Schema = union(enum) { raw: []const u8, value: Value };
diff --git a/src/tool_gates.zig b/src/tool_gates.zig
index a8ff8772..bd03d281 100644
--- a/src/tool_gates.zig
+++ b/src/tool_gates.zig
@@ -172,11 +172,12 @@ test "#352: neither the root nor the SUBAGENT catalog mentions imagegen until it
try std.testing.expect(root_has);
for (kinds) |kind| for ([_]bool{ false, true }) |gated| {
const catalog = schema.subToolsJson(kind, gated);
- try std.testing.expect(std.mem.indexOf(u8, catalog, "\"imagegen\"") != null);
- // --no-local-tools still subtracts inside the optional twin: the two
- // gates compose rather than one cancelling the other.
- try std.testing.expectEqual(!gated, std.mem.indexOf(u8, catalog, "\"name\":\"bash\"") != null or
- std.mem.indexOf(u8, catalog, "\"name\": \"bash\"") != null);
+ // #352 + #330: available AND not hard-gated. imagegen spawns a child
+ // and writes a file, so --no-local-tools must remove it even when the
+ // skill gate says yes — the two gates compose, and the subtractive one
+ // always wins.
+ try std.testing.expectEqual(!gated, std.mem.indexOf(u8, catalog, "\"imagegen\"") != null);
+ try std.testing.expectEqual(!gated, std.mem.indexOf(u8, catalog, "\"name\":\"bash\"") != null);
var parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, catalog, .{});
defer parsed.deinit();
try std.testing.expect(parsed.value.array.items.len > 1);
@@ -184,3 +185,50 @@ test "#352: neither the root nor the SUBAGENT catalog mentions imagegen until it
// Subagents still cannot spawn subagents, optional tools or not.
try std.testing.expect(std.mem.indexOf(u8, schema.subToolsJson(.anthropic, false), "\"name\":\"subagent\"") == null);
}
+
+test "#352 + #330: an AVAILABLE imagegen is still removed by --no-local-tools, in every catalog and at dispatch" {
+ const schema = @import("schema.zig");
+ const exec = @import("exec.zig");
+ const tools = @import("tools.zig");
+ const no_local_tools = @import("no_local_tools.zig");
+ const gpa = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const saved_gate = no_local_tools.enabled;
+ const saved_available = imagegen.available;
+ defer {
+ no_local_tools.enabled = saved_gate;
+ imagegen.available = saved_available;
+ }
+ imagegen.available = true; // the skill IS installed: only #330 may remove it
+
+ no_local_tools.enabled = true;
+ for (try schema.effectiveRootSpecs(arena)) |spec|
+ try std.testing.expect(!std.mem.eql(u8, spec.name, "imagegen"));
+ for ([_]@import("provider.zig").Provider.Kind{ .anthropic, .openai, .responses }) |kind|
+ try std.testing.expect(std.mem.indexOf(u8, schema.subToolsJson(kind, true), "\"imagegen\"") == null);
+
+ // Layer 2: a hallucinated call is refused before anything is spawned.
+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"prompt\":\"a red circle\"}", .{});
+ defer parsed.deinit();
+ var client: std.http.Client = undefined;
+ var ctx: tools.ToolCtx = .{
+ .gpa = gpa,
+ .io = std.testing.io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ };
+ for ([_]bool{ false, true }) |from_sub| {
+ ctx.from_sub = from_sub;
+ const out = exec.execTool(ctx, .{ .id = "c1", .name = "imagegen", .input = parsed.value });
+ defer gpa.free(out.text);
+ try std.testing.expect(out.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "--no-local-tools") != null);
+ }
+}