Skip to content

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

Python

feat(behavior): wire the eval-driven loop as the first turn_committed/model_mispredicted producer (#256)

Rach Pradhan67fa0d8d939f
diff --git a/README.md b/README.md
index 8883c11d..9397bbab 100644
--- a/README.md
+++ b/README.md
@@ -828,10 +828,13 @@ arguments/results, commands, arbitrary environment values, or exact private MCP
names. Provider and model identifiers are included exactly as configured; Phase
1 does not inspect, classify, or redact those identifier values.
-Ordinary Phase 1 runs contain lifecycle events only (plus tool/action/text
-events with `GRAFF_BEHAVIOR_TRACE=full`, local-only in every upload mode):
-typed commitment/misprediction APIs exist, but no built-in task adapter calls
-them yet.
+Most Phase 1 runs contain lifecycle events only (plus tool/action/text
+events with `GRAFF_BEHAVIOR_TRACE=full`, local-only in every upload mode).
+The eval-driven loop (`--eval`/`--until`) is the first built-in caller of the
+typed commitment/misprediction APIs, committing to a target before running
+the scoring command and recording a misprediction only on a nonzero exit or a
+missed target, with no command text, stdout, or stderr ever entering either
+field. No other built-in adapter calls them.
Content mode adds fields supplied through those APIs, with no redactor or secret
scanner; the local prompt fingerprint remains excluded. This is not yet a
generic predict → act → verify → repair loop
diff --git a/docs/behavioral-trajectories.md b/docs/behavioral-trajectories.md
index 62a3ef00..3b1bf2a6 100644
--- a/docs/behavioral-trajectories.md
+++ b/docs/behavioral-trajectories.md
@@ -19,9 +19,13 @@ scoring, or fleet/DGM selection from those scores.
Behavioral events are deliberately not mixed into the legacy DGM ledger. This
keeps old consumers working and prevents concurrent processes from interleaving
-unattributed event rows. No built-in production task adapter calls the
-commitment or misprediction APIs yet, so ordinary Phase 1 files contain lifecycle
-events only. Adapter rows in the example below are illustrative.
+unattributed event rows. The eval-driven loop (`--eval`/`--until`, `agent_eval.zig`)
+is the first production caller of the commitment and misprediction APIs
+(issue #256): before it runs the configured scoring command it commits to
+`{kind:"eval"}`/`{pass:true}`, then records a misprediction only if the command
+exits nonzero or the parsed score misses `--until`. Every other invocation path
+still contains lifecycle events only. Adapter rows in the example below are
+illustrative.
## Behavioral network upload
@@ -90,8 +94,11 @@ credentials, headers, identity, prompt fingerprints, or free-text adapter
content. Content mode changes typed adapter events: it may include
`commitment_id`, `action`, `expect`, `reason`, `predicted`, `actual`, and `detail`
exactly as supplied. There
-is no redactor, sanitizer, or secret scanner. No built-in production adapter
-currently supplies those fields.
+is no redactor, sanitizer, or secret scanner. The eval-driven loop is the only
+built-in production adapter that currently supplies those fields, and it
+supplies only static/opaque values (`{kind:"eval"}`, `{pass:<bool>}`,
+`{pass:false,exit:<int>}`, and a short fixed reason/detail string) - never the
+configured command text or its stdout/stderr.
The collector stores individual runs privately and has no raw behavioral GET
endpoint; its public stats expose aggregate totals only. Content-opt-in fields
diff --git a/src/agent_eval.zig b/src/agent_eval.zig
index 9c2b9a43..1ab07e18 100644
--- a/src/agent_eval.zig
+++ b/src/agent_eval.zig
@@ -1,4 +1,5 @@
//! Eval-driven scoring loop and its optional LLM-as-judge scorer.
+//! Tests live in agent_eval_tests.zig.
const std = @import("std");
const Io = std.Io;
@@ -19,6 +20,10 @@ const telemetry = @import("telemetry.zig");
const runCapped = @import("jobs.zig").runCapped;
const judgeTask = @import("subagent.zig").judgeTask;
+test {
+ _ = @import("agent_eval_tests.zig");
+}
+
/// Run the configured --eval scoring command, append the result to the
/// scores log (.graff/eval-log.tsv), and return a verdict for the model:
/// score (0-100), best so far, target, and whether the target is met. The
@@ -28,8 +33,28 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
.text = "no eval command configured - relaunch graff with --eval <scoring cmd> and --until <N>, or ask the user to set one",
.is_error = true,
};
- const run = runCapped(self.gpa, self.io, &.{ "/bin/sh", "-c", cmd }, 64 * 1024, 16 * 1024, 0) catch |e|
+
+ // Behavioral commitment (issue #256): the eval-driven loop is the first
+ // production caller of turn_committed/model_mispredicted. The commitment
+ // asserts the loop's own belief - the command will meet the target -
+ // before the command runs, so a later contradiction is provable rather
+ // than reconstructed after the fact. commitment_id is opaque and
+ // per-invocation; the command text and its stdout/stderr are content and
+ // must never reach either typed field (docs/behavioral-trajectories.md).
+ const behavior = if (self.tracer) |tracer| tracer.behavior else null;
+ const eval_turn = if (behavior) |bt| bt.currentTurn() else 0;
+ var commitment_buf: [48]u8 = undefined;
+ const commitment_id = std.fmt.bufPrint(&commitment_buf, "eval-{d}-{d}", .{ eval_turn, self.eval_iter + 1 }) catch "";
+ if (behavior) |bt| bt.recordExpectedAction(eval_turn, commitment_id, .{ .kind = "eval" }, .{ .pass = true }, "eval-driven loop verifier");
+
+ const run = runCapped(self.gpa, self.io, &.{ "/bin/sh", "-c", cmd }, 64 * 1024, 16 * 1024, 0) catch |e| {
+ // The command never ran, so the commitment can never be verified by
+ // the normal exit-code/score path below; resolve it here instead of
+ // leaving a dangling turn_committed that a scorer would misread as
+ // an unresolved success.
+ if (behavior) |bt| bt.recordMisprediction(eval_turn, commitment_id, .{ .pass = true }, .{ .pass = false, .exit = @as(i32, -1) }, "eval command could not run");
return .{ .text = try std.fmt.allocPrint(self.arena, "eval command could not run: {t}", .{e}), .is_error = true };
+ };
defer self.gpa.free(run.stdout);
defer self.gpa.free(run.stderr);
self.eval_iter += 1;
@@ -58,6 +83,13 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
if (self.eval_best < 0 or s > self.eval_best) self.eval_best = s;
}
const met = if (combined) |s| s >= target_f else false;
+ // Resolve the commitment made above: a nonzero exit or an unmet/unparsed
+ // target contradicts "this command will meet the target", so it is a
+ // misprediction. Meeting the target leaves the commitment unresolved by
+ // design - docs/behavioral-trajectories.md: a commitment with no paired
+ // misprediction is itself the success signal.
+ if (behavior) |bt| if (exit_code != 0 or !met)
+ bt.recordMisprediction(eval_turn, commitment_id, .{ .pass = true }, .{ .pass = false, .exit = exit_code }, "target not met");
self.appendEvalLog(note, det, judge, combined, exit_code, met) catch {};
// Feed the eval-driven score into the fleet (docs/hyperagents.md §9.B):
diff --git a/src/agent_eval_tests.zig b/src/agent_eval_tests.zig
new file mode 100644
index 00000000..fc2e7103
--- /dev/null
+++ b/src/agent_eval_tests.zig
@@ -0,0 +1,120 @@
+//! Tests for agent_eval.zig's eval-driven-loop behavioral producer (issue
+//! #256): the first production caller of turn_committed/model_mispredicted.
+//! Reached through the `test { _ = @import(...) }` hook at the bottom of
+//! agent_eval.zig, mirroring behavior_trace.zig's own test-file pattern.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Value = std.json.Value;
+
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+const trace = @import("trace.zig");
+const Tracer = trace.Tracer;
+const btrace = @import("behavior_trace.zig");
+const BehaviorTrace = btrace.BehaviorTrace;
+
+test "runEval: commits before the command runs, mispredicts on a missed target, and leaves a met target commitment-only (#256)" {
+ // The chdir below is POSIX-only, matching session_start.zig's own
+ // --worktree isolation (Windows has no libc chdir link here).
+ if (builtin.os.tag == .windows) return;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+
+ // runEval's appendEvalLog() writes .graff/eval-log.tsv against the real
+ // process cwd (it takes no Dir param), so this test moves the process
+ // into a scratch directory for its duration instead of touching the repo
+ // checkout. fchdir on real directory handles is used instead of
+ // path-based chdir/realPath: realPath on Dir.cwd()'s AT_FDCWD handle is
+ // unreliable on this platform (see session_start.zig's own PWD
+ // fallback), and this way sidesteps it entirely in both directions.
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var orig_dir = try Io.Dir.cwd().openDir(io, ".", .{});
+ defer orig_dir.close(io);
+ defer _ = std.posix.system.fchdir(orig_dir.handle);
+ if (std.posix.system.fchdir(tmp.dir.handle) != 0) return error.ChdirFailed;
+
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &aw.writer,
+ .run_id = "runeval-test",
+ };
+ behavior.start("test", 1);
+ const turn = behavior.beginTurn(0);
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ var agent: Agent = .{
+ .gpa = gpa,
+ .arena = arena_state.allocator(),
+ .io = io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = null,
+ .tracer = &tracer,
+ .eval_cmd = "printf 'score: 10\\n'; exit 1",
+ .eval_target = 90,
+ };
+
+ const failure = try agent.runEval("");
+ try std.testing.expect(!failure.is_error);
+ try std.testing.expectEqual(@as(u32, 1), agent.eval_iter);
+
+ agent.eval_cmd = "printf 'score: 100\\n'";
+ const success = try agent.runEval("");
+ try std.testing.expect(!success.is_error);
+ try std.testing.expectEqual(@as(u32, 2), agent.eval_iter);
+
+ const out = aw.writer.buffered();
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, out, "\n"), '\n');
+ _ = lines.next(); // run_started
+ _ = lines.next(); // turn_started
+
+ var committed1 = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer committed1.deinit();
+ try std.testing.expectEqualStrings("turn_committed", committed1.value.object.get("kind").?.string);
+ const commitment_id_1 = committed1.value.object.get("commitment_id").?.string;
+ try std.testing.expectEqual(@as(i64, @intCast(turn)), committed1.value.object.get("turn").?.integer);
+ try std.testing.expectEqualStrings("eval", committed1.value.object.get("action").?.object.get("kind").?.string);
+ try std.testing.expect(committed1.value.object.get("expect").?.object.get("pass").?.bool);
+
+ var mispredicted = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer mispredicted.deinit();
+ try std.testing.expectEqualStrings("model_mispredicted", mispredicted.value.object.get("kind").?.string);
+ try std.testing.expectEqualStrings(commitment_id_1, mispredicted.value.object.get("commitment_id").?.string);
+ try std.testing.expectEqual(@as(i64, @intCast(turn)), mispredicted.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), mispredicted.value.object.get("actual").?.object.get("exit").?.integer);
+ try std.testing.expect(!mispredicted.value.object.get("actual").?.object.get("pass").?.bool);
+
+ // Privacy contract: the command text and its stdout/stderr are content
+ // and must never reach the local behavioral stream for this producer
+ // (docs/behavioral-trajectories.md).
+ try std.testing.expect(std.mem.indexOf(u8, out, "printf") == null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "exit 1") == null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "score: 10") == null);
+
+ var committed2 = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer committed2.deinit();
+ try std.testing.expectEqualStrings("turn_committed", committed2.value.object.get("kind").?.string);
+ const commitment_id_2 = committed2.value.object.get("commitment_id").?.string;
+ try std.testing.expect(!std.mem.eql(u8, commitment_id_1, commitment_id_2));
+
+ // The met-target commitment has no paired misprediction: absence is the
+ // success signal (docs/behavioral-trajectories.md).
+ try std.testing.expect(lines.next() == null);
+}
diff --git a/src/behavior_trace_tests.zig b/src/behavior_trace_tests.zig
index 6d088109..26487bc8 100644
--- a/src/behavior_trace_tests.zig
+++ b/src/behavior_trace_tests.zig
@@ -34,9 +34,6 @@ test "writeBehaviorLine: oversized adapter content is rejected before local allo
const oversized = try gpa.alloc(u8, max_local_behavior_event_bytes + 1);
defer gpa.free(oversized);
@memset(oversized, 'x');
- // Pre-existing #246 bug fixed in passing: writeBehaviorLine returns
- // LineResult (.written/.dropped/.sink_failed), not bool — this call site
- // still compared against `!bool` and failed to compile.
try std.testing.expectEqual(btrace.LineResult.dropped, writeBehaviorLine(gpa, &out.writer, .turn_committed, 1, 1.0, "0123456789abcdef", .{
.turn = @as(u64, 1),
.reason = oversized,
@@ -366,15 +363,10 @@ test "BehaviorTrace: metadata-default upload is an exact content-free projection
try std.testing.expectEqualStrings("metadata", batch.get("privacy").?.string);
const events = batch.get("events").?.array.items;
try std.testing.expectEqual(@as(usize, 5), events.len);
- // Pre-existing staleness fixed in passing: startWithMetadata's
- // upload_fields already carries local_sink (sink-health diagnostics,
- // #246) but this key list predated that field.
try expectObjectKeys(events[0].object, &.{ "kind", "seq", "ts", "run_id", "schema", "version", "unix_ms", "provider", "model", "effort", "local_sink" });
try expectObjectKeys(events[1].object, &.{ "kind", "seq", "ts", "run_id", "schema", "turn", "parent_turn", "trajectory_node" });
try expectObjectKeys(events[2].object, &.{ "kind", "seq", "ts", "run_id", "schema", "turn", "commitment_ref" });
try expectObjectKeys(events[3].object, &.{ "kind", "seq", "ts", "run_id", "schema", "turn", "commitment_ref" });
- // Same staleness: run_finished's fields already carry local_dropped
- // (#246 audit reconciliation) alongside status.
try expectObjectKeys(events[4].object, &.{ "kind", "seq", "ts", "run_id", "schema", "status", "local_dropped" });
try std.testing.expectEqualStrings(events[2].object.get("commitment_ref").?.string, events[3].object.get("commitment_ref").?.string);
@@ -417,6 +409,64 @@ test "BehaviorTrace: prompt fingerprint stays local in content mode" {
try std.testing.expect(std.mem.indexOf(u8, upload.events.items[0], "prompt_sha") == null);
}
+test "BehaviorTrace: eval-driven loop producer pattern - misprediction on failure, commitment only on success (#256)" {
+ // Mirrors agent_eval.zig's runEval, the first production caller of this
+ // pair: commit before the command runs, then resolve with a
+ // misprediction only when the command failed or missed its target. A
+ // met target intentionally gets no paired misprediction call - the
+ // commitment alone is the success signal (docs/behavioral-trajectories.md).
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &aw.writer,
+ .run_id = "eval-pattern-run",
+ };
+ behavior.start("test", 1);
+ const turn = behavior.beginTurn(0);
+
+ behavior.recordExpectedAction(turn, "eval-1-1", .{ .kind = "eval" }, .{ .pass = true }, "eval-driven loop verifier");
+ behavior.recordMisprediction(turn, "eval-1-1", .{ .pass = true }, .{ .pass = false, .exit = @as(i32, 1) }, "target not met");
+
+ behavior.recordExpectedAction(turn, "eval-1-2", .{ .kind = "eval" }, .{ .pass = true }, "eval-driven loop verifier");
+ // (no recordMisprediction call for the second commitment: success)
+
+ behavior.finish(.closed);
+
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
+ _ = lines.next(); // run_started
+ _ = lines.next(); // turn_started
+
+ var committed1 = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer committed1.deinit();
+ try std.testing.expectEqualStrings("turn_committed", committed1.value.object.get("kind").?.string);
+ try std.testing.expectEqualStrings("eval-1-1", committed1.value.object.get("commitment_id").?.string);
+ try std.testing.expectEqual(@as(i64, @intCast(turn)), committed1.value.object.get("turn").?.integer);
+
+ var mispredicted = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer mispredicted.deinit();
+ try std.testing.expectEqualStrings("model_mispredicted", mispredicted.value.object.get("kind").?.string);
+ try std.testing.expectEqualStrings("eval-1-1", mispredicted.value.object.get("commitment_id").?.string);
+ try std.testing.expectEqual(@as(i64, @intCast(turn)), mispredicted.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), mispredicted.value.object.get("actual").?.object.get("exit").?.integer);
+ try std.testing.expect(!mispredicted.value.object.get("actual").?.object.get("pass").?.bool);
+
+ var committed2 = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer committed2.deinit();
+ try std.testing.expectEqualStrings("turn_committed", committed2.value.object.get("kind").?.string);
+ try std.testing.expectEqualStrings("eval-1-2", committed2.value.object.get("commitment_id").?.string);
+
+ var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer finished.deinit();
+ try std.testing.expectEqualStrings("run_finished", finished.value.object.get("kind").?.string);
+ // Exactly: run_started, turn_started, committed, mispredicted, committed,
+ // run_finished - the second (met-target) commitment has no misprediction.
+ try std.testing.expect(lines.next() == null);
+}
+
test "beginRootTurn: correlates without allocating a legacy node" {
const gpa = std.testing.allocator;
const io = std.testing.io;