graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: hardlink learn pin and detach init on the eval-frontier tree
Cursor Agent9ab785244ddc
diff --git a/src/learn_auto.zig b/src/learn_auto.zigindex 46bdce30..fd4e928f 100644--- a/src/learn_auto.zig+++ b/src/learn_auto.zig@@ -145,6 +145,38 @@ fn hasPendingTrial(store: *store_mod.Store) bool {return true;}+/// Build the automatic `learn init` command. Kept next to the trial argv so+/// both background children are testable without spawning.+pub fn initArgv(argv: *[3][]const u8, exe_path: []const u8) []const []const u8 {+ argv.* = .{ exe_path, "learn", "init" };+ return argv;+}++/// Own process group (when the OS has them): the child outlives this session,+/// and a Ctrl-C aimed at the shell's foreground group afterwards must not+/// kill suite generation or a tournament mid-holdout.+fn spawnDetached(io: Io, argv: []const []const u8, log: ?Io.File) bool {+ _ = std.process.spawn(io, .{+ .argv = argv,+ .stdin = .ignore,+ .stdout = if (log) |file| .{ .file = file } else .ignore,+ .stderr = if (log) |file| .{ .file = file } else .ignore,+ .pgid = if (posix_process_groups) 0 else null,+ }) catch return false;+ return true;+}++/// Detached `graff learn init` of this executable. Session end must not wait+/// on suite generation (~38s of CPU); the next session that finds a store+/// starts counting toward a trial.+pub fn startInit(io: Io, exe_path: []const u8) bool {+ var argv_buf: [3][]const u8 = undefined;+ const argv = initArgv(&argv_buf, exe_path);+ const log = Io.Dir.cwd().createFile(io, ".graff/learn-auto-init.log", .{ .truncate = true }) catch null;+ defer if (log) |file| file.close(io);+ return spawnDetached(io, argv, log);+}+/// Build the trial command. Kept separate from spawning so the shape of an/// automatic trial is testable without starting one.pub fn trialArgv(argv: *[8][]const u8, exe_path: []const u8, resumed: bool, contribute: bool) []const []const u8 {@@ -214,16 +246,7 @@ pub fn maybeStart(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.lock.deinit();lock_held = false;- _ = std.process.spawn(io, .{- .argv = argv,- .stdin = .ignore,- .stdout = if (log) |file| .{ .file = file } else .ignore,- .stderr = if (log) |file| .{ .file = file } else .ignore,- // Its own process group: the trial outlives this session, and a- // Ctrl-C aimed at the shell's foreground group afterwards must not- // kill a tournament mid-holdout.- .pgid = if (posix_process_groups) 0 else null,- }) catch return .{ .skipped = .busy };+ if (!spawnDetached(io, argv, log)) return .{ .skipped = .busy };// Deliberately not waited on. The trial reports through// `graff learn status` and .graff/learn/auto.log.return .{ .started = .{ .resumed = resumed, .contribute = contribute } };@@ -281,3 +304,9 @@ test "an automatic trial always carries the two-key auto flag and never restartsconst resumed = trialArgv(&argv, "graff", true, true);try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "aggregate", "learn", "run", "--auto", "--resume", "--submit" }, resumed);}++test "an automatic init is a bare learn init of this executable" {+ var argv: [3][]const u8 = undefined;+ const got = initArgv(&argv, "graff");+ try std.testing.expectEqualSlices([]const u8, &.{ "graff", "learn", "init" }, got);+}diff --git a/src/learn_bootstrap.zig b/src/learn_bootstrap.zigindex 95f1bfa9..7cf33667 100644--- a/src/learn_bootstrap.zig+++ b/src/learn_bootstrap.zig@@ -101,22 +101,15 @@ fn writePrivateFile(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !vtry file.sync(io);}-/// Copy the running executable into the kit and pin *that* copy. Pinning the-/// installed path instead would make every `graff update` invalidate the-/// configuration, and the configuration is immutable by design.-fn copyExecutable(io: Io, source_path: []const u8, dir: Io.Dir, name: []const u8) !void {- const source = try Io.Dir.openFileAbsolute(io, source_path, .{});- defer source.close(io);- const stat = try source.stat(io);- if (stat.kind != .file) return error.NotRegularFile;- if (stat.size > store_mod.max_program_bytes) return error.FileTooBig;- dir.deleteFile(io, name) catch {};+/// Write source bytes into `name`. Fallback when the filesystem cannot+/// hardlink (cross-device, or a host that does not support links).+fn copyExecutableBytes(io: Io, source: Io.File, size: u64, dir: Io.Dir, name: []const u8) !void {const dest = try dir.createFile(io, name, .{ .exclusive = true, .permissions = file_permissions });defer dest.close(io);var buffer: [64 << 10]u8 = undefined;var offset: u64 = 0;- while (offset < stat.size) {- const want: usize = @intCast(@min(@as(u64, buffer.len), stat.size - offset));+ while (offset < size) {+ const want: usize = @intCast(@min(@as(u64, buffer.len), size - offset));const got = try source.readPositionalAll(io, buffer[0..want], offset);if (got != want) return error.UnexpectedEndOfFile;try dest.writeStreamingAll(io, buffer[0..got]);@@ -125,6 +118,22 @@ fn copyExecutable(io: Io, source_path: []const u8, dir: Io.Dir, name: []const u8try dest.sync(io);}+/// Pin the running executable into the kit. Prefer a hardlink: same inode,+/// O(1), and `graff update` replacing the live path leaves this pin (and its+/// SHA) intact. Do not chmod the dest — that would also chmod the live exe.+/// Copy only when the filesystem cannot hardlink.+fn pinExecutable(io: Io, source_path: []const u8, dir: Io.Dir, name: []const u8) !void {+ const source = try Io.Dir.openFileAbsolute(io, source_path, .{});+ defer source.close(io);+ const stat = try source.stat(io);+ if (stat.kind != .file) return error.NotRegularFile;+ if (stat.size > store_mod.max_program_bytes) return error.FileTooBig;+ dir.deleteFile(io, name) catch {};+ source.hardLink(io, dir, name, .{}) catch {+ try copyExecutableBytes(io, source, stat.size, dir, name);+ };+}+fn joinPath(arena: Allocator, root: []const u8, name: []const u8) ![]const u8 {return std.fmt.allocPrint(arena, "{s}{c}{s}", .{ root, std.fs.path.sep, name });}@@ -347,7 +356,7 @@ pub fn prepare(gpa: Allocator, arena: Allocator, io: Io, options: Options, pass_const exe_path = try std.process.executablePathAlloc(io, gpa);defer gpa.free(exe_path);- try copyExecutable(io, exe_path, kit, binary_file);+ try pinExecutable(io, exe_path, kit, binary_file);const parent = try std.fmt.allocPrint(arena, "{s}\n", .{prompts.main_system_prompt});try writePrivateFile(io, kit, parent_file, parent);@@ -437,3 +446,41 @@ test "a suite generation command names the pinned kit generator" {try std.testing.expectEqualStrings("primary.json", argv[3]);try std.testing.expectEqualStrings("holdout.json", argv[4]);}++test "pinning the executable hardlinks on the same filesystem instead of copying" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ const payload = "graff-pin-fixture";+ {+ const file = try tmp.dir.createFile(io, "src-bin", .{});+ defer file.close(io);+ try file.writeStreamingAll(io, payload);+ }++ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const real_len = try tmp.dir.realPath(io, &real_buf);+ const root = real_buf[0..real_len];+ const src_path = try std.fmt.allocPrint(std.testing.allocator, "{s}{c}src-bin", .{ root, std.fs.path.sep });+ defer std.testing.allocator.free(src_path);++ try pinExecutable(io, src_path, tmp.dir, binary_file);++ const src = try tmp.dir.openFile(io, "src-bin", .{});+ defer src.close(io);+ const dst = try tmp.dir.openFile(io, binary_file, .{});+ defer dst.close(io);+ const src_stat = try src.stat(io);+ const dst_stat = try dst.stat(io);+ try std.testing.expectEqual(src_stat.size, dst_stat.size);+ if (builtin.os.tag != .windows and src_stat.inode != 0) {+ try std.testing.expectEqual(src_stat.inode, dst_stat.inode);+ try std.testing.expect(dst_stat.nlink >= 2);+ }++ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const pin = try pinFor(io, arena_state.allocator(), root, binary_file);+ try std.testing.expectEqual(@as(usize, 64), pin.sha256.len);+}diff --git a/src/session_run.zig b/src/session_run.zigindex bb7bbf17..193d042b 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -59,7 +59,6 @@ const goal_flow = @import("goal_flow.zig");const fleet = @import("fleet.zig");const hooks = @import("hooks.zig");const learn_auto = @import("learn_auto.zig");-const learn_init = @import("learn_init.zig");const run_budget_mod = @import("run_budget.zig");const learning_privacy = @import("learning_privacy.zig");const commands_privacy = @import("commands_privacy.zig");@@ -110,6 +109,9 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agentmodels_buf.appendSlice(mi.name) catch {};}try repl.runScripted(gpa, io, environ_map, in, out, &repl_ctx, repl_glue.replTurnCb, repl_glue.replModelCb, repl_glue.replCancelCb, root.provider.model, models_buf.items);+ // Same stderr footer as `-p`, so evals can score the scripted REPL the+ // same way. TTY `graff repl` is the TUI and keeps the restore tail clean.+ pricing.printUsageFooter(io);return true;}@@ -482,33 +484,33 @@ fn reportTrialStarted(started: learn_auto.Started) void {);}-/// Configure this workspace's learning store from the running binary, the same-/// way `graff learn init` would. Best effort by design: a machine with no-/// python3 or no usable credential simply does not learn, and the marker-/// learn_auto already claimed keeps that from being retried every session.-fn autoInitLearning(gpa: Allocator, arena: Allocator, io: Io, environ_map: *const std.process.Environ.Map) bool {+/// Start a detached `graff learn init` of this binary. Best effort: a machine+/// that cannot spawn simply does not learn, and the marker learn_auto already+/// claimed keeps that from being retried every session. Suite generation+/// (~38s) must not sit on `-p` / REPL / TUI teardown.+fn autoInitLearning(gpa: Allocator, io: Io) bool {std.debug.print("↺ setting this workspace up to learn from sessions like this one\n", .{});- // learn init narrates its own progress; the session's closing lines below- // are the useful summary, so its output goes to a buffer instead.- var buf: [16 * 1024]u8 = undefined;- var sink = std.Io.Writer.fixed(&buf);- learn_init.zeroConfig(gpa, arena, io, environ_map, .{}, &sink) catch |err| {- std.debug.print(- "↺ learning setup skipped ({s}) — `graff learn init` to retry\n",- .{@errorName(err)},- );+ const exe_path = std.process.executablePathAlloc(io, gpa) catch {+ std.debug.print("↺ learning setup skipped — `graff learn init` to retry\n", .{});return false;};+ defer gpa.free(exe_path);+ if (!learn_auto.startInit(io, exe_path)) {+ std.debug.print("↺ learning setup skipped — `graff learn init` to retry\n", .{});+ return false;+ }std.debug.print(- "↺ learning on for this workspace: a trial runs in the background every {d} sessions and spends real model calls — `graff learn status`, off with GRAFF_LEARN_AUTO=off\n",- .{learn_auto.default_every_sessions},+ "↺ learning setup started in the background — `graff learn status`, off with GRAFF_LEARN_AUTO=off\n",+ .{},);return true;}/// Closing the learning loop: a session that did real model work counts toward/// this workspace's next trial and, on cadence, starts one in the background.-/// The first such session in a workspace also creates the store it counts into.+/// The first such session also starts `graff learn init` detached so teardown+/// does not wait on suite generation; the next session that finds a store+/// starts the cadence.pub fn startBackgroundLearning(gpa: Allocator, arena: Allocator, io: Io, environ_map: *const std.process.Environ.Map, budget: *const run_budget_mod.RunBudget, telemetry_allowed: bool) void {const options: learn_auto.Options = .{.model_calls = budget.used(),@@ -518,15 +520,7 @@ pub fn startBackgroundLearning(gpa: Allocator, arena: Allocator, io: Io, environ};switch (learn_auto.maybeStart(gpa, arena, io, environ_map, options)) {.started => |started| reportTrialStarted(started),- // First real session here: build the store, then count this session- // against it so the cadence starts from this one rather than the next.- .needs_store => {- if (!autoInitLearning(gpa, arena, io, environ_map)) return;- switch (learn_auto.maybeStart(gpa, arena, io, environ_map, options)) {- .started => |started| reportTrialStarted(started),- else => {},- }- },+ .needs_store => _ = autoInitLearning(gpa, io),.skipped => {},}}