graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(learn): verifier parity, init recovery, and safer defaults (#246)
Rach Pradhan7c817cccd107
diff --git a/src/learn_cli.zig b/src/learn_cli.zigindex 76b7fc89..a4c3403a 100644--- a/src/learn_cli.zig+++ b/src/learn_cli.zig@@ -249,9 +249,15 @@ fn verifyRun(for (run.candidates, 0..) |candidate, index| {_ = try store.readGenome(arena, candidate.genome_id, config.value.limits.genome_bytes);try verifyMutationEvidence(arena, store, config.value, run, index, candidate);+ // Mirror runCommand's precedence exactly: identical_parent wins and+ // skips the prior-duplicate scan. Letting duplicate_candidate+ // overwrite it made a run with two parent-identical candidates+ // permanently unverifiable (writer said identical_parent, verifier+ // demanded duplicate_candidate).var duplicate_reason: ?[]const u8 = null;- if (std.mem.eql(u8, candidate.genome_id, run.parent_genome_id)) duplicate_reason = "identical_parent";- for (run.candidates[0..index]) |prior| if (std.mem.eql(u8, candidate.genome_id, prior.genome_id)) {+ if (std.mem.eql(u8, candidate.genome_id, run.parent_genome_id)) {+ duplicate_reason = "identical_parent";+ } else for (run.candidates[0..index]) |prior| if (std.mem.eql(u8, candidate.genome_id, prior.genome_id)) {duplicate_reason = "duplicate_candidate";break;};@@ -291,6 +297,12 @@ fn initCommand(gpa: Allocator, arena: Allocator, io: Io, args: InitArgs, out: *Itry store_mod.validateConfig(config);try verifyPins(io, arena, config);const parent = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.parent, arena, config.limits.genome_bytes);+ // Validate the genome BEFORE creating the store tree: a rejected parent+ // must not leave a half-initialized .graff/learn behind (which used to+ // wedge every later init with AlreadyInitialized).+ if (!std.unicode.utf8ValidateSlice(parent) or+ std.mem.indexOfScalar(u8, parent, 0) != null or+ std.mem.trim(u8, parent, " \t\r\n").len == 0) return error.InvalidParentGenome;var store = try store_mod.Store.initAt(io, Io.Dir.cwd());defer store.deinit();@@ -316,7 +328,7 @@ fn runCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.procif (args.auto and config.value.holdout_suite == null) return error.AutoRequiresHoldout;try out.writeAll("warning: mutator and evaluator execute as your OS user; scratch isolation is not a sandbox\n");- const nonce = store_mod.randomId(io);+ const nonce = try store_mod.randomId(io);const trial_id = trialId(&config.id, active.ref.genome_id, active.ref.generation, active.ref.transaction_id, &nonce);const candidates = try arena.alloc(eval.CandidateRecord, candidate_count);@@ -444,6 +456,11 @@ fn promoteCommand(gpa: Allocator, arena: Allocator, io: Io, args: PromoteArgs, o}fn ancestorTarget(arena: Allocator, store: *store_mod.Store, active: store_mod.LoadedActive, requested: ?[]const u8) ![]const u8 {+ // After a rollback, previous_genome_id names the genome just rolled AWAY+ // from, so a default-target rollback would move forward and reinstate it.+ // Require an explicit --to instead of silently undoing the rollback.+ if (requested == null and std.mem.eql(u8, active.transaction.operation, "rollback"))+ return error.RollbackNeedsExplicitTarget;const default_target = active.transaction.previous_genome_id orelse return error.NoRollbackAvailable;const target = requested orelse default_target;if (std.mem.eql(u8, target, active.ref.genome_id)) return error.AlreadyActive;diff --git a/src/learn_eval.zig b/src/learn_eval.zigindex 7c51c5f1..cd82b78d 100644--- a/src/learn_eval.zig+++ b/src/learn_eval.zig@@ -195,13 +195,17 @@ pub fn createScratch(io: Io, store: *store_mod.Store) !struct { name: [32]u8, divar attempts: usize = 0;while (attempts < 16) : (attempts += 1) {var raw: [16]u8 = undefined;- io.randomSecure(&raw) catch io.random(&raw);+ try io.randomSecure(&raw);const name = std.fmt.bytesToHex(raw, .lower);store.tmp.createDir(io, &name, dir_permissions) catch |err| switch (err) {error.PathAlreadyExists => continue,else => return err,};+ // The directory exists from here on: clean it up if the open or the+ // permission tightening fails, instead of leaking it into store.tmp.+ errdefer store.tmp.deleteTree(io, &name) catch {};const dir = try store.tmp.openDir(io, &name, .{ .iterate = true, .follow_symlinks = false });+ errdefer dir.close(io);if (builtin.os.tag != .windows) try dir.setPermissions(io, dir_permissions);return .{ .name = name, .dir = dir };}@@ -327,8 +331,18 @@ pub fn invoke(gpa.free(run.stdout);gpa.free(run.stderr);}- if (run.timed_out) return error.ProcessTimedOut;- if (run.term != .exited or run.term.exited != 0) return error.ProcessFailed;+ if (run.timed_out) {+ std.debug.print("learn: {s} timed out after {d} ms\n", .{ program.program, timeout_ms });+ return error.ProcessTimedOut;+ }+ if (run.term != .exited or run.term.exited != 0) {+ // The bare error alone cost real debugging time: surface which tool+ // failed and a bounded stderr excerpt before the scratch dir (and the+ // request/response evidence in it) is deleted by the caller.+ const excerpt = run.stderr[0..@min(run.stderr.len, 512)];+ std.debug.print("learn: {s} failed ({any}); stderr (first {d} of {d} bytes):\n{s}\n", .{ program.program, run.term, excerpt.len, run.stderr.len, excerpt });+ return error.ProcessFailed;+ }}fn validDescription(value: []const u8) bool {diff --git a/src/learn_store.zig b/src/learn_store.zigindex fed7507b..9b08a560 100644--- a/src/learn_store.zig+++ b/src/learn_store.zig@@ -205,9 +205,12 @@ pub fn jsonBytes(gpa: Allocator, value: anytype) ![]u8 {return gpa.dupe(u8, allocating.writer.buffered());}-pub fn randomId(io: Io) [64]u8 {+pub fn randomId(io: Io) ![64]u8 {var raw: [32]u8 = undefined;- io.randomSecure(&raw) catch io.random(&raw);+ // Fail closed: trial nonces feed trial-ID derivation, so degrading to+ // non-cryptographic randomness silently would weaken an integrity+ // boundary rather than a convenience.+ try io.randomSecure(&raw);return std.fmt.bytesToHex(raw, .lower);}@@ -231,7 +234,7 @@ pub fn readPinnedFileAlloc(io: Io, gpa: Allocator, pin: PinnedFile, max: u64) ![if (!std.fs.path.isAbsolute(pin.path)) return error.PathNotAbsolute;var real_buf: [std.fs.max_path_bytes]u8 = undefined;const real_len = try Io.Dir.realPathFileAbsolute(io, pin.path, &real_buf);- if (!std.mem.eql(u8, pin.path, real_buf[0..real_len])) return error.NonCanonicalPath;+ if (!canonicalPathEql(pin.path, real_buf[0..real_len])) return error.NonCanonicalPath;const file = try openFileNoFollow(io, .cwd(), pin.path, .{});defer file.close(io);@@ -251,11 +254,23 @@ pub fn readPinnedFileAlloc(io: Io, gpa: Allocator, pin: PinnedFile, max: u64) ![return bytes;}+/// Byte equality, except case-insensitive on the platforms whose default+/// filesystems are case-insensitive. The kernel canonicalizes casing in+/// realPath output there, so an exact compare rejected valid pinned paths+/// that differ only by case; symlinked components still differ after+/// resolution and are still rejected. Content authenticity comes from the+/// sha256 pin, not from this check.+fn canonicalPathEql(configured: []const u8, canonical: []const u8) bool {+ if (builtin.os.tag == .windows or builtin.os.tag.isDarwin())+ return std.ascii.eqlIgnoreCase(configured, canonical);+ return std.mem.eql(u8, configured, canonical);+}+pub fn hashFileNoFollow(io: Io, path: []const u8) ![64]u8 {if (!std.fs.path.isAbsolute(path)) return error.PathNotAbsolute;var real_buf: [std.fs.max_path_bytes]u8 = undefined;const real_len = try Io.Dir.realPathFileAbsolute(io, path, &real_buf);- if (!std.mem.eql(u8, path, real_buf[0..real_len])) return error.NonCanonicalPath;+ if (!canonicalPathEql(path, real_buf[0..real_len])) return error.NonCanonicalPath;const file = try openFileNoFollow(io, .cwd(), path, .{});defer file.close(io);@@ -317,6 +332,36 @@ fn createPrivateDir(io: Io, parent: Io.Dir, name: []const u8) !Io.Dir {return dir;}+/// createPrivateDir that tolerates an existing directory, reopening it with+/// the same permission checks as openPrivateDir. Used when resuming an+/// interrupted init: leftovers must be adopted only if they are still+/// private.+fn ensurePrivateDir(io: Io, parent: Io.Dir, name: []const u8) !Io.Dir {+ parent.createDir(io, name, dir_permissions) catch |err| switch (err) {+ error.PathAlreadyExists => return openPrivateDir(io, parent, name),+ else => return err,+ };+ var dir = try parent.openDir(io, name, .{ .iterate = true, .follow_symlinks = false });+ errdefer dir.close(io);+ if (builtin.os.tag != .windows) try dir.setPermissions(io, dir_permissions);+ try syncDirectory(io, dir);+ try syncDirectory(io, parent);+ return dir;+}++/// A store is complete once refs/active.json exists (bootstrap's final+/// write). Unreadable state is treated as initialized so nothing is adopted+/// or overwritten blindly.+fn hasActiveRef(io: Io, graff: Io.Dir) bool {+ const root = graff.openDir(io, "learn", .{ .iterate = true, .follow_symlinks = false }) catch return true;+ defer root.close(io);+ const refs = root.openDir(io, "refs", .{ .iterate = true, .follow_symlinks = false }) catch return false;+ defer refs.close(io);+ const file = openFileNoFollow(io, refs, "active.json", .{}) catch return false;+ file.close(io);+ return true;+}+pub const Store = struct {io: Io,root: Io.Dir,@@ -338,7 +383,13 @@ pub const Store = struct {defer graff.close(io);try syncDirectory(io, base);graff.createDir(io, "learn", dir_permissions) catch |err| switch (err) {- error.PathAlreadyExists => return error.AlreadyInitialized,+ // A completed store has refs/active.json (bootstrap's final+ // write). A learn tree without it is the residue of a failed or+ // interrupted init and used to wedge every later `learn init`+ // with AlreadyInitialized until the tree was deleted by hand.+ // Resume initializing instead: every write below is+ // create-or-verify, and reopened leftovers must still be private.+ error.PathAlreadyExists => if (hasActiveRef(io, graff)) return error.AlreadyInitialized,else => return err,};var root = try graff.openDir(io, "learn", .{ .iterate = true, .follow_symlinks = false });@@ -347,28 +398,32 @@ pub const Store = struct {try syncDirectory(io, root);try syncDirectory(io, graff);- var configs = try createPrivateDir(io, root, "configs");+ var configs = try ensurePrivateDir(io, root, "configs");errdefer configs.close(io);- var genomes = try createPrivateDir(io, root, "genomes");+ var genomes = try ensurePrivateDir(io, root, "genomes");errdefer genomes.close(io);- var evidence = try createPrivateDir(io, root, "evidence");+ var evidence = try ensurePrivateDir(io, root, "evidence");errdefer evidence.close(io);- var runs = try createPrivateDir(io, root, "runs");+ var runs = try ensurePrivateDir(io, root, "runs");errdefer runs.close(io);- var transactions = try createPrivateDir(io, root, "transactions");+ var transactions = try ensurePrivateDir(io, root, "transactions");errdefer transactions.close(io);- var refs = try createPrivateDir(io, root, "refs");+ var refs = try ensurePrivateDir(io, root, "refs");errdefer refs.close(io);- var locks = try createPrivateDir(io, root, "locks");+ var locks = try ensurePrivateDir(io, root, "locks");errdefer locks.close(io);- var tmp = try createPrivateDir(io, root, "tmp");+ var tmp = try ensurePrivateDir(io, root, "tmp");errdefer tmp.close(io);var store: Store = .{ .io = io, .root = root, .configs = configs, .genomes = genomes, .evidence = evidence, .runs = runs, .transactions = transactions, .refs = refs, .locks = locks, .tmp = tmp };try store.writeImmutable(store.root, "VERSION", version_bytes, std.heap.page_allocator);- const lock = try store.locks.createFile(io, "engine.lock", .{ .exclusive = true, .permissions = file_permissions });- defer lock.close(io);- try lock.sync(io);+ if (store.locks.createFile(io, "engine.lock", .{ .exclusive = true, .permissions = file_permissions })) |lock| {+ defer lock.close(io);+ try lock.sync(io);+ } else |err| switch (err) {+ error.PathAlreadyExists => {},+ else => return err,+ }try syncDirectory(io, store.locks);return store;}diff --git a/src/learn_store_validate.zig b/src/learn_store_validate.zigindex a8197d55..ad31c717 100644--- a/src/learn_store_validate.zig+++ b/src/learn_store_validate.zig@@ -37,11 +37,20 @@ pub fn validEnvName(value: []const u8) bool {if (value.len == 0 or value.len > 128) return false;if (!(std.ascii.isAlphabetic(value[0]) or value[0] == '_')) return false;for (value[1..]) |c| if (!(std.ascii.isAlphanumeric(c) or c == '_')) return false;- return !std.mem.eql(u8, value, "HOME") and- !std.mem.eql(u8, value, "USERPROFILE") and- !std.mem.eql(u8, value, "TMPDIR") and- !std.mem.eql(u8, value, "TMP") and- !std.mem.eql(u8, value, "TEMP") and+ // Case-insensitive: Windows environment lookups are case-insensitive,+ // and a case-variant of a denied name must not slip through. PATH and+ // the dynamic-linker variables would otherwise let a config override the+ // scrubbed execution environment that buildEnvironment constructs.+ return !std.ascii.eqlIgnoreCase(value, "HOME") and+ !std.ascii.eqlIgnoreCase(value, "USERPROFILE") and+ !std.ascii.eqlIgnoreCase(value, "TMPDIR") and+ !std.ascii.eqlIgnoreCase(value, "TMP") and+ !std.ascii.eqlIgnoreCase(value, "TEMP") and+ !std.ascii.eqlIgnoreCase(value, "PATH") and+ !std.ascii.eqlIgnoreCase(value, "COMSPEC") and+ !std.ascii.eqlIgnoreCase(value, "SYSTEMROOT") and+ !std.ascii.startsWithIgnoreCase(value, "LD_") and+ !std.ascii.startsWithIgnoreCase(value, "DYLD_") and!std.mem.startsWith(u8, value, "GRAFF_LEARN_");}diff --git a/tests/learn_e2e.py b/tests/learn_e2e.pyindex 2b5b95eb..e455cd9c 100644--- a/tests/learn_e2e.py+++ b/tests/learn_e2e.py@@ -252,6 +252,12 @@ pathlib.Path(response_path).write_text(json.dumps(response, separators=(\",\", \assert rolled_back["generation"] == 2assert rolled_back["active_genome_id"] == initial_genome+ # A second default-target rollback would move FORWARD (previous_genome_id+ # of a rollback transaction names the genome just rolled away from) and+ # silently reinstate it; it must demand an explicit --to instead.+ invoke(graff, workspace, env, "rollback", succeeds=False)+ assert status(graff, workspace, env)["generation"] == 2+# Returning to identical parent bytes does not make old evidence fresh: the# parent generation and transaction ID must also match.invoke(graff, workspace, env, "promote", manual_run, succeeds=False)@@ -275,6 +281,111 @@ pathlib.Path(response_path).write_text(json.dumps(response, separators=(\",\", \verified = invoke(graff, workspace, env, "verify")assert json.loads(verified.stdout)["integrity"] == "ok"+ exercise_identical_parent(graff, root, evaluator, holdout_suite, evaluation_suite, parent, env)+ exercise_init_recovery(graff, root, config_path, parent, env)+++def exercise_identical_parent(+ graff: Path,+ root: Path,+ evaluator: Path,+ holdout_suite: Path,+ evaluation_suite: Path,+ parent: Path,+ env: dict[str, str],+) -> None:+ """Regression: a run whose first candidates reproduce the parent byte for+ byte must stay verifiable and promotable. verifyRun used to let+ duplicate_candidate overwrite identical_parent (diverging from the+ writer), which made such a run permanently unpromotable."""+ workspace = root / "workspace-identical"+ workspace.mkdir(mode=0o700)+ tools = root / "tools"+ python = Path(sys.executable).resolve()+ mutator = tools / "mutator-identical.py"+ mutator_source = f"""#!{python}+import hashlib, json, pathlib, sys+operation, request_path, response_path = sys.argv[1:4]+assert operation == \"mutate\"+request = json.loads(pathlib.Path(request_path).read_text())+parent = pathlib.Path(request[\"parent\"][\"path\"]).read_text()+child = parent if request[\"candidate_index\"] < 2 else parent.rstrip() + \"\\n\\nLearned fixture policy.\\n\"+child_bytes = child.encode()+pathlib.Path(request[\"child_path\"]).write_bytes(child_bytes)+response = {{+ \"schema\": \"codegraff.learn.mutation.response.v1\",+ \"trial_id\": request[\"trial_id\"],+ \"candidate_index\": request[\"candidate_index\"],+ \"parent_id\": request[\"parent\"][\"id\"],+ \"child_path\": request[\"child_path\"],+ \"child_sha256\": hashlib.sha256(child_bytes).hexdigest(),+ \"description\": \"parent-identical below index 2\",+}}+pathlib.Path(response_path).write_text(json.dumps(response, separators=(\",\", \":\")) + \"\\n\")+"""+ write_private(mutator, mutator_source.encode(), 0o700)++ config_path = root / "config-identical.json"+ config = {+ "schema": "codegraff.learn.config.v1",+ "agent_name": "fixture-identical",+ "agent_description": "parent-identical candidate regression",+ "mutation_instruction": "reproduce the parent for the first two candidates",+ "mutator": {"program": str(mutator.resolve()), "sha256": raw_sha256(mutator)},+ "evaluator": {+ "program": str(evaluator.resolve()),+ "sha256": raw_sha256(evaluator),+ "pass_env": ["FIXTURE_EVALUATOR_SOURCE"],+ },+ "evaluation_suite": {"path": str(evaluation_suite.resolve()), "sha256": raw_sha256(evaluation_suite)},+ "holdout_suite": {"path": str(holdout_suite.resolve()), "sha256": raw_sha256(holdout_suite)},+ "gate": {+ "alpha_ppm": 50000,+ "minimum_delta_ppm": 100000,+ "minimum_pairs": 6,+ "default_candidates": 3,+ "default_repetitions": 3,+ },+ "auto": {"enabled": False},+ "cohort": {+ "provider": "fixture",+ "model": "fixture",+ "task_family": "local-e2e",+ "adapter_version": "v1",+ "verifier_version": "v1",+ },+ }+ write_private(config_path, json_bytes(config))++ invoke(graff, workspace, env, "init", "--parent", str(parent.resolve()), "--config", str(config_path.resolve()))+ run_output = invoke(graff, workspace, env, "run").stdout+ run_id = run_id_from(run_output)+ record = json.loads((workspace / ".graff" / "learn" / "runs" / f"{run_id}.json").read_text())+ reasons = [candidate["reason"] for candidate in record["candidates"]]+ assert reasons[0] == "identical_parent" and reasons[1] == "identical_parent", reasons+ assert record["candidates"][2]["eligible"], reasons+ invoke(graff, workspace, env, "promote", run_id)+ assert status(graff, workspace, env)["generation"] == 1+++def exercise_init_recovery(graff: Path, root: Path, config_path: Path, parent: Path, env: dict[str, str]) -> None:+ """Regression: a rejected parent must not create the store tree, and the+ residue of an interrupted init must be re-initializable rather than+ wedging every later init with AlreadyInitialized."""+ workspace = root / "workspace-wedge"+ workspace.mkdir(mode=0o700)+ bad_parent = root / "bad-parent.md"+ write_private(bad_parent, b" \n\t\n")+ invoke(graff, workspace, env, "init", "--parent", str(bad_parent.resolve()), "--config", str(config_path.resolve()), succeeds=False)+ assert not (workspace / ".graff" / "learn").exists(), "rejected parent must not create the store"++ # Crash residue: a partial tree without refs/active.json must be adopted.+ (workspace / ".graff").mkdir(mode=0o700)+ (workspace / ".graff" / "learn").mkdir(mode=0o700)+ (workspace / ".graff" / "learn" / "configs").mkdir(mode=0o700)+ invoke(graff, workspace, env, "init", "--parent", str(parent.resolve()), "--config", str(config_path.resolve()))+ assert status(graff, workspace, env)["generation"] == 0+def main() -> int:parser = argparse.ArgumentParser()