graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Write .graff/.gitignore when graff creates .graff (#1273)
Rach Pradhan4f9895a63e39
diff --git a/src/agent_worktree.zig b/src/agent_worktree.zigindex b305d380..e92e5910 100644--- a/src/agent_worktree.zig+++ b/src/agent_worktree.zig@@ -77,6 +77,7 @@ pub fn agentWorktreeCreateAt(gpa: Allocator, io: Io, arena: Allocator, sub_id: [gpa.free(add.stderr);}if (!ranOk(add)) return error.CreateFailed;+ @import("graff_dir.zig").ensureIgnoreAt(io, cwd); // #1273: hide .graff/worktreesvar base: []const u8 = "";if (runCapped(gpa, io, &.{ "git", "-C", names.path, "rev-parse", "HEAD" }, 4096, 4096, 15_000)) |r| {diff --git a/src/experiment_pool.zig b/src/experiment_pool.zigindex cf968fea..23fb3b04 100644--- a/src/experiment_pool.zig+++ b/src/experiment_pool.zig@@ -125,6 +125,7 @@ fn mintOne(gpa: Allocator, io: Io, arena: Allocator, id: []const u8, i: u8) !Seagpa.free(add.stderr);}if (!ranOk(add) and !dirExists(io, rel)) return error.CreateFailed;+ @import("graff_dir.zig").ensureIgnore(io, Io.Dir.cwd()); // #1273: hide .graff/worktrees}const path = try absOrRel(io, arena, rel);return .{ .path = path, .branch = branch, .base = readHead(gpa, io, arena, path) };diff --git a/src/graff_dir.zig b/src/graff_dir.zignew file mode 100644index 00000000..379f1b9b--- /dev/null+++ b/src/graff_dir.zig@@ -0,0 +1,132 @@+//! #1273: graff's `.graff/` run state stays out of git. Sessions, transcripts,+//! traces, trajectories, spilled tool output and nested worktrees all land in+//! the working tree, so in a repository that does not ignore `.graff/` they+//! showed up as untracked, and a model-run `git add -A` committed them.+//!+//! Whenever graff makes (or writes under) `.graff/`, it drops a+//! `.graff/.gitignore` there: only when the file is absent, never over a+//! user's own. The body ignores everything EXCEPT the few files a project is+//! meant to share: `workspace.toml` (ADR 0153 setup scripts), `tools/` (ADR+//! 0039 project-local tools), `policy.json` / `retrieval-policy` (ADR 0084)+//! and `.config.router` (endpoint metadata, no credentials). An allowlist+//! rather than a list of runtime dirs, because new run state keeps appearing+//! under `.graff/` and a denylist would silently fall behind. The file ignores+//! itself too, so a fresh run leaves `git status` empty.+//!+//! Nested worktrees under `.graff/worktrees/` are unaffected: git reads ignore+//! files only from inside a worktree's own root, never its parent directories.++const std = @import("std");+const Io = std.Io;++pub const name = ".graff";++pub const gitignore_body =+ \\# Written by graff: keeps sessions, traces and other run state out of git.+ \\# Shared project config below stays visible. Edit freely; graff never+ \\# rewrites this file once it exists.+ \\*+ \\!workspace.toml+ \\!policy.json+ \\!retrieval-policy+ \\!.config.router+ \\!tools/+ \\!tools/**+ \\+;++/// Create `<base>/.graff` if needed and make sure it has a `.gitignore`.+pub fn ensure(io: Io, base: Io.Dir) void {+ base.createDir(io, name, .default_dir) catch {};+ ensureIgnore(io, base);+}++/// Give an existing `<base>/.graff` its `.gitignore`. A `.graff` that is a+/// symlink is left alone: the write must never land outside the workspace.+pub fn ensureIgnore(io: Io, base: Io.Dir) void {+ var graff = base.openDir(io, name, .{ .follow_symlinks = false }) catch return;+ defer graff.close(io);+ ensureIgnoreIn(io, graff);+}++/// The same, given an already-open handle on `.graff` itself.+pub fn ensureIgnoreIn(io: Io, graff: Io.Dir) void {+ graff.writeFile(io, .{ .sub_path = ".gitignore", .data = gitignore_body, .flags = .{ .exclusive = true } }) catch {};+}++/// `ensureIgnore` for a writer that only has a path relative to `base`: a+/// no-op unless that path lives under `.graff/`.+pub fn ensureFor(io: Io, base: Io.Dir, rel: []const u8) void {+ if (std.mem.startsWith(u8, rel, name ++ "/")) ensureIgnore(io, base);+}++/// `ensureIgnore` for a directory named by path (a worktree creator's cwd).+pub fn ensureIgnoreAt(io: Io, base_path: []const u8) void {+ var base = Io.Dir.cwd().openDir(io, base_path, .{}) catch return;+ defer base.close(io);+ ensureIgnore(io, base);+}++fn gitStatus(gpa: std.mem.Allocator, root: []const u8) ![]u8 {+ const runner = @import("process_runner.zig");+ const r = try runner.runCapped(gpa, std.testing.io, &.{ "git", "-C", root, "status", "--porcelain", "--untracked-files=all" }, 1 << 16, 4096, 15_000);+ defer gpa.free(r.stderr);+ if (!runner.ranOk(r)) {+ gpa.free(r.stdout);+ return error.GitFailed;+ }+ return r.stdout;+}++test "#1273: run state under .graff stays out of git status; shared config does not" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);+ const init = @import("process_runner.zig").runCapped(gpa, io, &.{ "git", "init", "-q", root }, 4096, 4096, 15_000) catch return error.SkipZigTest;+ gpa.free(init.stdout);+ gpa.free(init.stderr);+ if (!@import("process_runner.zig").ranOk(init)) return error.SkipZigTest;++ ensure(io, tmp.dir);+ try tmp.dir.createDirPath(io, ".graff/sessions/s1/artifacts");+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/sessions/s1.session.json", .data = "{}" });+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/sessions/s1/artifacts/tool-0.txt", .data = "x" });+ try tmp.dir.createDirPath(io, ".graff/traces");+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/traces/run.jsonl", .data = "{}\n" });+ const clean = try gitStatus(gpa, root);+ defer gpa.free(clean);+ try std.testing.expectEqualStrings("", clean);++ // A project's shared config is still something it can commit.+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/workspace.toml", .data = "[scripts]\n" });+ try tmp.dir.createDirPath(io, ".graff/tools/fmt");+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/tools/fmt/manifest.json", .data = "{}" });+ const shared = try gitStatus(gpa, root);+ defer gpa.free(shared);+ try std.testing.expect(std.mem.indexOf(u8, shared, ".graff/workspace.toml") != null);+ try std.testing.expect(std.mem.indexOf(u8, shared, ".graff/tools/fmt/manifest.json") != null);+ try std.testing.expect(std.mem.indexOf(u8, shared, "sessions") == null);+}++test "#1273: a user's own .graff/.gitignore is never overwritten" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.createDirPath(io, ".graff");+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/.gitignore", .data = "sessions/\n" });+ ensure(io, tmp.dir);+ ensureFor(io, tmp.dir, ".graff/sessions/x.session.json");+ var buf: [64]u8 = undefined;+ try std.testing.expectEqualStrings("sessions/\n", try tmp.dir.readFile(io, ".graff/.gitignore", &buf));++ // A path outside .graff never creates one.+ var other = std.testing.tmpDir(.{});+ defer other.cleanup();+ ensureFor(io, other.dir, "notes/x.md");+ try std.testing.expectError(error.FileNotFound, other.dir.statFile(io, ".graff", .{}));+}diff --git a/src/session_branch.zig b/src/session_branch.zigindex fe18a7c7..600c88b1 100644--- a/src/session_branch.zig+++ b/src/session_branch.zig@@ -56,6 +56,7 @@ pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocatoif (std.mem.eql(u8, source, dest)) return Error.BranchMatchesSource;if (session.sessionExists(root, arena, dest)) return Error.BranchAlreadyExists;try Io.Dir.cwd().createDirPath(root.io, session.sessions_dir);+ @import("graff_dir.zig").ensureIgnore(root.io, Io.Dir.cwd()); // #1273const path = try session.sessionPath(arena, dest);const claim = Io.Dir.cwd().createFile(root.io, path, .{ .exclusive = true }) catch |err| switch (err) {error.PathAlreadyExists => return Error.BranchAlreadyExists,diff --git a/src/session_lock.zig b/src/session_lock.zigindex d47ffcd9..de76aa87 100644--- a/src/session_lock.zig+++ b/src/session_lock.zig@@ -67,6 +67,7 @@ fn releaseOwner(io: Io, dir: Io.Dir, path: []const u8) void {/// file back to the new length.pub fn writeSession(io: Io, dir: Io.Dir, path: []const u8, data: []const u8) !void {if (std.fs.path.dirname(path)) |parent| dir.createDirPath(io, parent) catch {};+ @import("graff_dir.zig").ensureFor(io, dir, path); // #1273const file = dir.createFile(io, path, .{.truncate = false,.lock = .exclusive,diff --git a/src/session_start.zig b/src/session_start.zigindex 30eef1a5..f6c3dfeb 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -247,7 +247,7 @@ pub const FileWriterOpen = struct {};fn openRunFile(io: Io, dir_path: []const u8, path: []const u8, buf: []u8) FileWriterOpen {- Io.Dir.cwd().createDir(io, ".graff", .default_dir) catch {};+ @import("graff_dir.zig").ensure(io, Io.Dir.cwd()); // #1273: .graff/.gitignoreIo.Dir.cwd().createDir(io, dir_path, .default_dir) catch {};// A random run id makes collision vanishingly unlikely; exclusive creation// turns even that case into a disabled writer instead of truncating another@@ -294,6 +294,7 @@ pub fn openBehaviorFile(io: Io, base: Io.Dir, dir: []const u8, run_id: []const uelse => return .{ .file = null, .writer = undefined },};const next = current.openDir(io, component, .{ .iterate = true, .follow_symlinks = false }) catch return .{ .file = null, .writer = undefined };+ if (!current_owned and std.mem.eql(u8, component, ".graff")) @import("graff_dir.zig").ensureIgnoreIn(io, next); // #1273if (current_owned) current.close(io);current = next;current_owned = true;diff --git a/src/session_transcript.zig b/src/session_transcript.zigindex 41a8aad9..a28f7a64 100644--- a/src/session_transcript.zig+++ b/src/session_transcript.zig@@ -295,6 +295,7 @@ fn flush(io: Io, dir: Io.Dir, arena: Allocator, name: []const u8, pending: []con/// from re-introducing a silent no-write instead of an append.fn appendWhole(io: Io, dir: Io.Dir, path: []const u8, data: []const u8) ?usize {dir.createDirPath(io, session_index.sessions_dir) catch {};+ @import("graff_dir.zig").ensureIgnore(io, dir); // #1273const f = dir.createFile(io, path, .{ .truncate = false, .read = true }) catch return null;defer f.close(io);const end: u64 = if (f.stat(io)) |st| st.size else |_| blk: {diff --git a/src/task_workspace.zig b/src/task_workspace.zigindex 81096ada..3c43673b 100644--- a/src/task_workspace.zig+++ b/src/task_workspace.zig@@ -227,6 +227,7 @@ fn mintOnce(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, rel: []cogpa.free(r.stderr);}if (!ranOk(r)) return error.CreateFailed;+ if (std.mem.indexOf(u8, rel, ".graff/") != null) @import("graff_dir.zig").ensureIgnoreAt(io, cwd); // #1273}pub fn create(gpa: Allocator, io: Io, arena: Allocator, opts: CreateOpts) (CreateError || Allocator.Error)!Workspace {diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 72fc2a09..26919cfb 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -395,4 +395,5 @@ test {_ = @import("tool_env.zig"); // #1267/#1268: tool children's environment_ = @import("destructive_git.zig"); // #1269: destructive-git tokenizer tables_ = @import("output_elide.zig"); // #1271: over-cap output keeps head and tail+ _ = @import("graff_dir.zig"); // #1273: .graff/.gitignore keeps run state out of git}diff --git a/src/tool_handle.zig b/src/tool_handle.zigindex 486ae053..cd97b2ab 100644--- a/src/tool_handle.zig+++ b/src/tool_handle.zig@@ -202,6 +202,7 @@ fn persist(arena: Allocator, target: Target, text: []const u8) ?[]const u8 {if (!reserve(text.len)) return null;// createDirPath is idempotent; `.graff` normally already exists (trace setup).target.dir.createDirPath(target.io, handles_dir) catch return refund(text.len);+ @import("graff_dir.zig").ensureIgnore(target.io, target.dir); // #1273// `g_seq` is per-process. A prior graff in this cwd may have left tr_N;// exclusive create must skip those instead of dropping the handle.var spins: u32 = 0;diff --git a/src/tool_spill.zig b/src/tool_spill.zigindex bfe8ae61..b93326d6 100644--- a/src/tool_spill.zig+++ b/src/tool_spill.zig@@ -141,6 +141,7 @@ fn spill(arena: Allocator, session: []const u8, full: []const u8) ?[]const u8 {const dir = std.fmt.allocPrint(arena, "{s}/{s}/artifacts", .{ session_index.sessions_dir, session }) catch return refund(full.len);sweepOnce(sink, arena, session);sink.dir.createDirPath(sink.io, dir) catch return refund(full.len);+ @import("graff_dir.zig").ensureIgnore(sink.io, sink.dir); // #1273const seq = g_seq.fetchAdd(1, .monotonic);const rel = std.fmt.allocPrint(arena, "{s}/tool-{d}.txt", .{ dir, seq }) catch return refund(full.len);sink.dir.writeFile(sink.io, .{ .sub_path = rel, .data = full, .flags = .{ .exclusive = true } }) catch return refund(full.len);