graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
refactor: split oversized modules to satisfy the zig source size guard (#246)
Rach Pradhan1a33a0152972
diff --git a/src/behavior_trace.zig b/src/behavior_trace.zigindex 0094cae5..8ce127d4 100644--- a/src/behavior_trace.zig+++ b/src/behavior_trace.zig@@ -9,6 +9,9 @@ const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const behavior_upload = @import("behavior_upload.zig");+const session_start = @import("session_start.zig");+const scoring = @import("scoring.zig");+const trace = @import("trace.zig");test {_ = @import("behavior_trace_tests.zig");@@ -338,3 +341,76 @@ pub const BehaviorTrace = struct {if (state.uploader) |uploader| uploader.send(state.complete, status_name);}};++// ── Session bootstrap (main's sink wiring, 600-line goal) ─────────────────++/// The two behavioral sinks owned by main()'s frame: the privacy-projected+/// uploader and the local JSONL behind `behavior`. Construct with boot(),+/// then call link() exactly once after the value has settled at its final+/// address — openBehaviorFile's writer is only safe to point at after the+/// copy has landed (see session_start.zig's FileWriterOpen header).+pub const Boot = struct {+ io: Io,+ uploader: behavior_upload.Upload,+ open: session_start.FileWriterOpen,+ behavior: BehaviorTrace,++ /// Point the behavior stream at this Boot's settled storage and assign+ /// the shared tracer. All root/subagent callbacks already share that+ /// stable tracer, so this single assignment covers every producer.+ pub fn link(self: *Boot, tracer: ?*trace.Tracer) void {+ self.behavior.out = if (self.open.file != null) &self.open.writer.interface else null;+ self.behavior.upload = if (self.uploader.active()) &self.uploader else null;+ if (tracer) |tr| tr.behavior = &self.behavior;+ }++ /// Terminal lifecycle event + upload, then close/deinit both sinks. A+ /// clean return is not a task success verdict; finish() is idempotent and+ /// keeps an earlier error-unwind status terminal.+ pub fn finishAndClose(self: *Boot, tracer: ?*trace.Tracer, status: BehaviorRunStatus) void {+ self.behavior.finish(status);+ if (tracer) |tr| tr.behavior = null;+ if (self.open.file) |f| f.close(self.io);+ self.uploader.deinit();+ }+};++/// Construct the behavioral sinks for an agent session. Behavioral tracing+/// starts only after the root Agent exists, so utility and self-test paths do+/// not create zero-turn behavioral runs. The local JSONL and the+/// privacy-projected upload are independent sinks. `buf` storage is owned by+/// the caller (a stack array in main()) and must outlive the Boot.+pub fn boot(io: Io, gpa: Allocator, client: ?*std.http.Client, environ_map: anytype, endpoint: []const u8, auth_key: ?[]const u8, install_id: [32]u8, client_name: []const u8, service_version: []const u8, buf: []u8) Boot {+ const uploader: behavior_upload.Upload = .{+ .io = io,+ .gpa = gpa,+ .client = client,+ .endpoint = endpoint,+ .auth_key = auth_key,+ .install_id = install_id,+ .client_name = client_name,+ .service_version = service_version,+ .run_id = &scoring.g_run_id,+ .mode = behavior_upload.resolveMode(environ_map.get("GRAFF_BEHAVIOR_UPLOAD"), endpoint.len > 0),+ };+ const enabled = if (environ_map.get("GRAFF_BEHAVIOR_TRACE")) |value|+ !(std.ascii.eqlIgnoreCase(value, "off") or std.mem.eql(u8, value, "0") or std.ascii.eqlIgnoreCase(value, "false") or std.ascii.eqlIgnoreCase(value, "no"))+ else+ true;+ const open = if (enabled)+ session_start.openBehaviorFile(io, Io.Dir.cwd(), behavior_dir, &scoring.g_run_id, buf)+ else+ session_start.FileWriterOpen{ .file = null, .writer = undefined };+ return .{+ .io = io,+ .uploader = uploader,+ .open = open,+ .behavior = .{+ .io = io,+ .gpa = gpa,+ .out = null,+ .upload = null,+ .run_id = &scoring.g_run_id,+ },+ };+}diff --git a/src/behavior_upload.zig b/src/behavior_upload.zigindex 1eebc207..e75e089e 100644--- a/src/behavior_upload.zig+++ b/src/behavior_upload.zig@@ -12,12 +12,12 @@ pub const batch_schema = "codegraff.behavior.batch.v1";pub const event_schema = "codegraff.behavior.v1";pub const max_events = 4096;-const max_event_bytes = 16 * 1024;+pub const max_event_bytes = 16 * 1024;// Leave enough room below the 256 KiB wire limit for worst-case u64 turn// counters, the batch envelope, and JSON punctuation.const max_event_storage = 112 * 1024;-const max_turns = 128;-const max_payload_bytes = 256 * 1024;+pub const max_turns = 128;+pub const max_payload_bytes = 256 * 1024;pub const Mode = enum {off,@@ -62,7 +62,7 @@ pub fn resolveMode(value: ?[]const u8, telemetry_enabled: bool) Mode {/// HARNESS_CLIENT remains an unconstrained ordinary-telemetry attribute, but/// behavioral metadata must not serialize arbitrary environment content./// Preserve only the stable SDK attribution labels that Codegraff defines.-fn controlledClientName(raw: []const u8) []const u8 {+pub fn controlledClientName(raw: []const u8) []const u8 {const allowed = [_][]const u8{ "harness", "sdk-ts", "sdk-py" };for (allowed) |name| if (std.mem.eql(u8, raw, name)) return name;return "harness";@@ -126,7 +126,7 @@ fn toolClass(name: []const u8) ToolClass {return .other;}-const max_safe_json_integer: u64 = 9_007_199_254_740_991;+pub const max_safe_json_integer: u64 = 9_007_199_254_740_991;fn saturatingAdd(dst: *u64, value: u64) void {// The collector validates counters as exactly representable JSON numbers.@@ -378,7 +378,7 @@ pub const Upload = struct {self.sendWithDeadline(complete, terminal_status, .fromSeconds(3));}- fn sendWithDeadline(self: *Upload, complete: bool, terminal_status: []const u8, deadline: Io.Duration) void {+ pub fn sendWithDeadline(self: *Upload, complete: bool, terminal_status: []const u8, deadline: Io.Duration) void {if (!self.active() or self.sent or self.events.items.len == 0) return;self.sent = true;self.last_send_result = .failed;@@ -419,7 +419,7 @@ fn writeJsonValue(w: *Io.Writer, value: anytype) !void {try s.write(value);}-fn behaviorUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {+pub fn behaviorUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {// Derive from the URL path, not from its query. This preserves custom// collector query parameters without appending a path inside their value.const fragment_at = std.mem.indexOfScalar(u8, endpoint, '#') orelse endpoint.len;@@ -433,7 +433,7 @@ fn behaviorUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {return try std.fmt.allocPrint(gpa, "{s}/v1/behavior{s}", .{ base, query });}-fn postBatch(client: *std.http.Client, url: []const u8, payload: []const u8, auth_key: []const u8) bool {+pub fn postBatch(client: *std.http.Client, url: []const u8, payload: []const u8, auth_key: []const u8) bool {const auth_header = [_]std.http.Header{.{ .name = "x-harness-key", .value = auth_key }};const extra_headers: []const std.http.Header = if (auth_key.len > 0) &auth_header else &.{};const response = client.fetch(.{@@ -451,7 +451,7 @@ fn uploadDeadline(io: Io, deadline: Io.Duration) void {io.sleep(deadline, .awake) catch {};}-fn stallBehaviorCollector(io: Io, server: *Io.net.Server, accepted: *std.atomic.Value(bool)) void {+pub fn stallBehaviorCollector(io: Io, server: *Io.net.Server, accepted: *std.atomic.Value(bool)) void {const stream = server.accept(io) catch return;defer stream.close(io);accepted.store(true, .release);@@ -460,7 +460,7 @@ fn stallBehaviorCollector(io: Io, server: *Io.net.Server, accepted: *std.atomic.io.sleep(.fromSeconds(5), .awake) catch {};}-fn answerBehaviorCollector(+pub fn answerBehaviorCollector(io: Io,server: *Io.net.Server,expected_key: []const u8,@@ -488,305 +488,6 @@ fn answerBehaviorCollector(writer.interface.flush() catch {};}-test "behavior upload mode follows telemetry consent and fails closed" {- try std.testing.expectEqual(Mode.off, resolveMode(null, false));- try std.testing.expectEqual(Mode.off, resolveMode("content", false));- try std.testing.expectEqual(Mode.metadata, resolveMode(null, true));- try std.testing.expectEqual(Mode.metadata, resolveMode("metadata", true));- try std.testing.expectEqual(Mode.off, resolveMode("METADATA", true));- try std.testing.expectEqual(Mode.off, resolveMode("metadata ", true));- try std.testing.expectEqual(Mode.off, resolveMode("off", true));- try std.testing.expectEqual(Mode.off, resolveMode("0", true));- try std.testing.expectEqual(Mode.content, resolveMode("content", true));- try std.testing.expectEqual(Mode.off, resolveMode("CONTENT", true));- try std.testing.expectEqual(Mode.off, resolveMode("Content", true));- try std.testing.expectEqual(Mode.off, resolveMode("content ", true));- try std.testing.expectEqual(Mode.off, resolveMode("sanitized", true));- try std.testing.expectEqual(Mode.off, resolveMode("full", true));- try std.testing.expectEqual(Mode.off, resolveMode("typo", true));-}--test "behavior client attribution never serializes arbitrary HARNESS_CLIENT content" {- const gpa = std.testing.allocator;- var upload: Upload = .{- .io = std.testing.io,- .gpa = gpa,- .client = null,- .endpoint = "https://collector.example/v1/logs",- .install_id = @splat('a'),- .client_name = "HARNESS_CLIENT_PRIVATE_SENTINEL",- .service_version = "test",- .run_id = "0123456789abcdef",- .mode = .metadata,- };- defer upload.deinit();-- const metadata_payload = try upload.buildPayload(true, "closed");- defer gpa.free(metadata_payload);- try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "HARNESS_CLIENT_PRIVATE_SENTINEL") == null);-- var parsed = try std.json.parseFromSlice(std.json.Value, gpa, metadata_payload, .{});- defer parsed.deinit();- try std.testing.expectEqualStrings("harness", parsed.value.object.get("client_name").?.string);-- upload.mode = .content;- const content_payload = try upload.buildPayload(true, "closed");- defer gpa.free(content_payload);- try std.testing.expect(std.mem.indexOf(u8, content_payload, "HARNESS_CLIENT_PRIVATE_SENTINEL") == null);-- try std.testing.expectEqualStrings("sdk-ts", controlledClientName("sdk-ts"));- try std.testing.expectEqualStrings("sdk-py", controlledClientName("sdk-py"));-}--test "upload deadline synchronously cancels and joins a stalled POST" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");- var server = try Io.net.IpAddress.listen(&address, io, .{});- defer server.deinit(io);-- var accepted: std.atomic.Value(bool) = .init(false);- var server_group: Io.Group = .init;- defer server_group.cancel(io);- try server_group.concurrent(io, stallBehaviorCollector, .{ io, &server, &accepted });-- var client: std.http.Client = .{ .allocator = gpa, .io = io };- defer client.deinit();- var endpoint_buf: [64]u8 = undefined;- const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});- var upload: Upload = .{- .io = io,- .gpa = gpa,- .client = &client,- .endpoint = endpoint,- .install_id = @splat('a'),- .client_name = "harness",- .service_version = "test",- .run_id = "0123456789abcdef",- .mode = .metadata,- };- defer upload.deinit();- try std.testing.expect(upload.appendEvent("run_started", 1, 1.0, .{}, .{}));-- const started = Io.Timestamp.now(io, .awake).nanoseconds;- upload.sendWithDeadline(true, "closed", .fromMilliseconds(250));- const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - started;-- try std.testing.expect(accepted.load(.acquire));- try std.testing.expectEqual(SendResult.deadline, upload.last_send_result);- try std.testing.expect(elapsed >= 100 * std.time.ns_per_ms);- try std.testing.expect(elapsed < 3 * std.time.ns_per_s);-}--test "behavior POST sends the collector key and rejects non-success status" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var client: std.http.Client = .{ .allocator = gpa, .io = io };- defer client.deinit();-- inline for (.{ true, false }) |accept_request| {- var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");- var server = try Io.net.IpAddress.listen(&address, io, .{});- defer server.deinit(io);- var saw_key: std.atomic.Value(bool) = .init(false);- var server_group: Io.Group = .init;- defer server_group.cancel(io);- try server_group.concurrent(io, answerBehaviorCollector, .{ io, &server, "collector-secret", accept_request, &saw_key });-- var endpoint_buf: [64]u8 = undefined;- const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}/v1/behavior", .{server.socket.address.getPort()});- try std.testing.expectEqual(accept_request, postBatch(&client, endpoint, "{}", "collector-secret"));- try std.testing.expect(saw_key.load(.acquire));- }-}--test "metadata projection omits content while explicit content mode includes it" {- const gpa = std.testing.allocator;- const io = std.testing.io;- const common = .{- .io = io,- .gpa = gpa,- .client = @as(?*std.http.Client, null),- .endpoint = "https://collector.example/v1/logs",- .install_id = @as([32]u8, @splat('a')),- .client_name = "test",- .service_version = "test",- .run_id = "0123456789abcdef",- };-- var metadata: Upload = .{- .io = common.io,- .gpa = common.gpa,- .client = common.client,- .endpoint = common.endpoint,- .install_id = common.install_id,- .client_name = common.client_name,- .service_version = common.service_version,- .run_id = common.run_id,- .mode = .metadata,- };- defer metadata.deinit();- try std.testing.expect(metadata.appendEvent(- "turn_committed",- 1,- 1.5,- .{ .turn = @as(u64, 1), .commitment_ref = "safe-ref" },- .{ .turn = @as(u64, 1), .commitment_id = "private-id", .action = .{ .secret = "TOP_SECRET" }, .expect = .{ .ok = true }, .reason = "private reason" },- ));- const metadata_payload = try metadata.buildPayload(true, "closed");- defer gpa.free(metadata_payload);- try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "safe-ref") != null);- try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "TOP_SECRET") == null);- try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "private reason") == null);-- var content: Upload = .{- .io = common.io,- .gpa = common.gpa,- .client = common.client,- .endpoint = common.endpoint,- .install_id = common.install_id,- .client_name = common.client_name,- .service_version = common.service_version,- .run_id = common.run_id,- .mode = .content,- };- defer content.deinit();- try std.testing.expect(content.appendEvent(- "turn_committed",- 1,- 1.5,- .{ .turn = @as(u64, 1), .commitment_ref = "safe-ref" },- .{ .turn = @as(u64, 1), .commitment_id = "private-id", .action = .{ .secret = "TOP_SECRET" }, .expect = .{ .ok = true }, .reason = "adapter-sanitized reason" },- ));- const content_payload = try content.buildPayload(true, "closed");- defer gpa.free(content_payload);- try std.testing.expect(std.mem.indexOf(u8, content_payload, "TOP_SECRET") != null);- try std.testing.expect(std.mem.indexOf(u8, content_payload, "content_opt_in") != null);-}--test "turn metrics aggregate safe categories without exact MCP names" {- const gpa = std.testing.allocator;- var upload: Upload = .{- .io = std.testing.io,- .gpa = gpa,- .client = null,- .endpoint = "https://collector.example",- .install_id = @splat('b'),- .client_name = "test",- .service_version = "test",- .run_id = "fedcba9876543210",- .mode = .metadata,- };- defer upload.deinit();- upload.recordApi(1, false, 20, 100, 200, 300, 250, false);- upload.recordTool(1, "bash", false, 5, 40, false);- upload.recordTool(1, "mcp__private_server__lookup_customer", true, 7, 80, true);- try std.testing.expectEqual(@as(usize, 1), upload.turns.items.len);- const metrics = upload.turns.items[0];- try std.testing.expectEqual(@as(u64, 1), metrics.api_calls);- try std.testing.expectEqual(@as(u64, 2), metrics.tool_calls);- try std.testing.expectEqual(@as(u64, 1), metrics.tool_shell);- try std.testing.expectEqual(@as(u64, 1), metrics.tool_mcp);- try std.testing.expectEqual(@as(u64, 1), metrics.tool_errors);-- _ = upload.appendEvent("run_started", 1, 1.0, .{ .version = "test", .unix_ms = @as(i64, 1) }, .{ .version = "test", .unix_ms = @as(i64, 1) });- const payload = try upload.buildPayload(true, "closed");- defer gpa.free(payload);- try std.testing.expect(std.mem.indexOf(u8, payload, "lookup_customer") == null);- try std.testing.expect(std.mem.indexOf(u8, payload, "\"tool_mcp\":1") != null);-}--test "batch admission limits always fit the wire cap" {- const gpa = std.testing.allocator;- var upload: Upload = .{- .io = std.testing.io,- .gpa = gpa,- .client = null,- .endpoint = "https://collector.example",- .install_id = @splat('d'),- .client_name = "test",- .service_version = "test",- .run_id = "0123456789abcdef",- .mode = .metadata,- };- defer upload.deinit();-- var turn: u64 = 1;- while (turn <= max_turns) : (turn += 1) {- upload.recordApi(turn, false, std.math.maxInt(i64), std.math.maxInt(usize), std.math.maxInt(usize), std.math.maxInt(u64), std.math.maxInt(u64), true);- upload.recordTool(turn, "bash", true, std.math.maxInt(i64), std.math.maxInt(usize), true);- inline for (comptime std.meta.fieldNames(TurnMetrics)) |name| {- if (!std.mem.eql(u8, name, "turn")) @field(upload.turns.items[@intCast(turn - 1)], name) = max_safe_json_integer;- }- }- upload.recordApi(max_turns + 1, false, 1, 1, 1, 1, 1, false);- try std.testing.expectEqual(@as(u64, 1), upload.dropped_metrics);-- var seq: u64 = 1;- while (seq <= max_events) : (seq += 1) {- if (!upload.appendEvent(- "run_started",- seq,- 1.0,- .{ .version = "test", .unix_ms = @as(i64, 1), .provider = "provider-padding-provider-padding-provider-padding" },- .{ .version = "test", .unix_ms = @as(i64, 1) },- )) break;- }- try std.testing.expect(upload.dropped_events > 0);- const payload = try upload.buildPayload(true, "closed");- defer gpa.free(payload);- try std.testing.expect(payload.len <= max_payload_bytes);- var parsed = try std.json.parseFromSlice(std.json.Value, gpa, payload, .{});- defer parsed.deinit();- try std.testing.expect(parsed.value == .object);-}--test "oversized content event is rejected before queueing" {- const gpa = std.testing.allocator;- var upload: Upload = .{- .io = std.testing.io,- .gpa = gpa,- .client = null,- .endpoint = "https://collector.example",- .install_id = @splat('e'),- .client_name = "test",- .service_version = "test",- .run_id = "0123456789abcdef",- .mode = .content,- };- defer upload.deinit();- var oversized: [max_event_bytes * 2]u8 = @splat('x');- try std.testing.expect(!upload.appendEvent(- "turn_committed",- 1,- 1.0,- .{ .turn = @as(u64, 1), .commitment_ref = "safe" },- .{ .turn = @as(u64, 1), .reason = oversized[0..] },- ));- try std.testing.expectEqual(@as(usize, 0), upload.events.items.len);- try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);-}--test "behavior endpoint derives beside OTLP logs without a fixed URL buffer" {- const gpa = std.testing.allocator;- const Case = struct {- fn expect(gpa_inner: Allocator, endpoint: []const u8, expected: []const u8) !void {- const actual = (try behaviorUrl(gpa_inner, endpoint)).?;- defer gpa_inner.free(actual);- try std.testing.expectEqualStrings(expected, actual);- }- };- try Case.expect(gpa, "https://example.test/v1/logs", "https://example.test/v1/behavior");- try Case.expect(gpa, "https://example.test/base/", "https://example.test/base/v1/behavior");- try Case.expect(gpa, "https://example.test/v1/logs?token=x#ignored", "https://example.test/v1/behavior?token=x");- try Case.expect(gpa, "https://example.test/base/?token=x", "https://example.test/base/v1/behavior?token=x");-- const long_token: [768]u8 = @splat('x');- var endpoint_buf: [1024]u8 = undefined;- const endpoint = try std.fmt.bufPrint(&endpoint_buf, "https://example.test/v1/logs?token={s}", .{long_token});- const actual = (try behaviorUrl(gpa, endpoint)).?;- defer gpa.free(actual);- try std.testing.expect(actual.len > 512);- try std.testing.expect(std.mem.startsWith(u8, actual, "https://example.test/v1/behavior?token="));- try std.testing.expect(std.mem.endsWith(u8, actual, &long_token));+test {+ _ = @import("behavior_upload_tests.zig");}diff --git a/src/behavior_upload_tests.zig b/src/behavior_upload_tests.zignew file mode 100644index 00000000..86268712--- /dev/null+++ b/src/behavior_upload_tests.zig@@ -0,0 +1,328 @@+//! Tests for behavior_upload.zig (600-line goal). Reached through the+//! `test { _ = ... }` hook in behavior_upload.zig, mirroring the mcp.zig+//! pattern in main.zig.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const upload_mod = @import("behavior_upload.zig");+const telemetry = @import("telemetry.zig");++const Upload = upload_mod.Upload;+const Mode = upload_mod.Mode;+const SendResult = upload_mod.SendResult;+const TurnMetrics = upload_mod.TurnMetrics;+const resolveMode = upload_mod.resolveMode;+const behaviorUrl = upload_mod.behaviorUrl;+const max_events = upload_mod.max_events;+const max_payload_bytes = upload_mod.max_payload_bytes;+const max_event_bytes = upload_mod.max_event_bytes;+const max_turns = upload_mod.max_turns;+const controlledClientName = upload_mod.controlledClientName;+const stallBehaviorCollector = upload_mod.stallBehaviorCollector;+const answerBehaviorCollector = upload_mod.answerBehaviorCollector;+const postBatch = upload_mod.postBatch;+const max_safe_json_integer = upload_mod.max_safe_json_integer;++test "behavior upload mode follows telemetry consent and fails closed" {+ try std.testing.expectEqual(Mode.off, resolveMode(null, false));+ try std.testing.expectEqual(Mode.off, resolveMode("content", false));+ try std.testing.expectEqual(Mode.metadata, resolveMode(null, true));+ try std.testing.expectEqual(Mode.metadata, resolveMode("metadata", true));+ try std.testing.expectEqual(Mode.off, resolveMode("METADATA", true));+ try std.testing.expectEqual(Mode.off, resolveMode("metadata ", true));+ try std.testing.expectEqual(Mode.off, resolveMode("off", true));+ try std.testing.expectEqual(Mode.off, resolveMode("0", true));+ try std.testing.expectEqual(Mode.content, resolveMode("content", true));+ try std.testing.expectEqual(Mode.off, resolveMode("CONTENT", true));+ try std.testing.expectEqual(Mode.off, resolveMode("Content", true));+ try std.testing.expectEqual(Mode.off, resolveMode("content ", true));+ try std.testing.expectEqual(Mode.off, resolveMode("sanitized", true));+ try std.testing.expectEqual(Mode.off, resolveMode("full", true));+ try std.testing.expectEqual(Mode.off, resolveMode("typo", true));+}++test "behavior client attribution never serializes arbitrary HARNESS_CLIENT content" {+ const gpa = std.testing.allocator;+ var upload: Upload = .{+ .io = std.testing.io,+ .gpa = gpa,+ .client = null,+ .endpoint = "https://collector.example/v1/logs",+ .install_id = @splat('a'),+ .client_name = "HARNESS_CLIENT_PRIVATE_SENTINEL",+ .service_version = "test",+ .run_id = "0123456789abcdef",+ .mode = .metadata,+ };+ defer upload.deinit();++ const metadata_payload = try upload.buildPayload(true, "closed");+ defer gpa.free(metadata_payload);+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "HARNESS_CLIENT_PRIVATE_SENTINEL") == null);++ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, metadata_payload, .{});+ defer parsed.deinit();+ try std.testing.expectEqualStrings("harness", parsed.value.object.get("client_name").?.string);++ upload.mode = .content;+ const content_payload = try upload.buildPayload(true, "closed");+ defer gpa.free(content_payload);+ try std.testing.expect(std.mem.indexOf(u8, content_payload, "HARNESS_CLIENT_PRIVATE_SENTINEL") == null);++ try std.testing.expectEqualStrings("sdk-ts", controlledClientName("sdk-ts"));+ try std.testing.expectEqualStrings("sdk-py", controlledClientName("sdk-py"));+}++test "upload deadline synchronously cancels and joins a stalled POST" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var server = try Io.net.IpAddress.listen(&address, io, .{});+ defer server.deinit(io);++ var accepted: std.atomic.Value(bool) = .init(false);+ var server_group: Io.Group = .init;+ defer server_group.cancel(io);+ try server_group.concurrent(io, stallBehaviorCollector, .{ io, &server, &accepted });++ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var endpoint_buf: [64]u8 = undefined;+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});+ var upload: Upload = .{+ .io = io,+ .gpa = gpa,+ .client = &client,+ .endpoint = endpoint,+ .install_id = @splat('a'),+ .client_name = "harness",+ .service_version = "test",+ .run_id = "0123456789abcdef",+ .mode = .metadata,+ };+ defer upload.deinit();+ try std.testing.expect(upload.appendEvent("run_started", 1, 1.0, .{}, .{}));++ const started = Io.Timestamp.now(io, .awake).nanoseconds;+ upload.sendWithDeadline(true, "closed", .fromMilliseconds(250));+ const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - started;++ try std.testing.expect(accepted.load(.acquire));+ try std.testing.expectEqual(SendResult.deadline, upload.last_send_result);+ try std.testing.expect(elapsed >= 100 * std.time.ns_per_ms);+ try std.testing.expect(elapsed < 3 * std.time.ns_per_s);+}++test "behavior POST sends the collector key and rejects non-success status" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();++ inline for (.{ true, false }) |accept_request| {+ var address = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var server = try Io.net.IpAddress.listen(&address, io, .{});+ defer server.deinit(io);+ var saw_key: std.atomic.Value(bool) = .init(false);+ var server_group: Io.Group = .init;+ defer server_group.cancel(io);+ try server_group.concurrent(io, answerBehaviorCollector, .{ io, &server, "collector-secret", accept_request, &saw_key });++ var endpoint_buf: [64]u8 = undefined;+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}/v1/behavior", .{server.socket.address.getPort()});+ try std.testing.expectEqual(accept_request, postBatch(&client, endpoint, "{}", "collector-secret"));+ try std.testing.expect(saw_key.load(.acquire));+ }+}++test "metadata projection omits content while explicit content mode includes it" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ const common = .{+ .io = io,+ .gpa = gpa,+ .client = @as(?*std.http.Client, null),+ .endpoint = "https://collector.example/v1/logs",+ .install_id = @as([32]u8, @splat('a')),+ .client_name = "test",+ .service_version = "test",+ .run_id = "0123456789abcdef",+ };++ var metadata: Upload = .{+ .io = common.io,+ .gpa = common.gpa,+ .client = common.client,+ .endpoint = common.endpoint,+ .install_id = common.install_id,+ .client_name = common.client_name,+ .service_version = common.service_version,+ .run_id = common.run_id,+ .mode = .metadata,+ };+ defer metadata.deinit();+ try std.testing.expect(metadata.appendEvent(+ "turn_committed",+ 1,+ 1.5,+ .{ .turn = @as(u64, 1), .commitment_ref = "safe-ref" },+ .{ .turn = @as(u64, 1), .commitment_id = "private-id", .action = .{ .secret = "TOP_SECRET" }, .expect = .{ .ok = true }, .reason = "private reason" },+ ));+ const metadata_payload = try metadata.buildPayload(true, "closed");+ defer gpa.free(metadata_payload);+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "safe-ref") != null);+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "TOP_SECRET") == null);+ try std.testing.expect(std.mem.indexOf(u8, metadata_payload, "private reason") == null);++ var content: Upload = .{+ .io = common.io,+ .gpa = common.gpa,+ .client = common.client,+ .endpoint = common.endpoint,+ .install_id = common.install_id,+ .client_name = common.client_name,+ .service_version = common.service_version,+ .run_id = common.run_id,+ .mode = .content,+ };+ defer content.deinit();+ try std.testing.expect(content.appendEvent(+ "turn_committed",+ 1,+ 1.5,+ .{ .turn = @as(u64, 1), .commitment_ref = "safe-ref" },+ .{ .turn = @as(u64, 1), .commitment_id = "private-id", .action = .{ .secret = "TOP_SECRET" }, .expect = .{ .ok = true }, .reason = "adapter-sanitized reason" },+ ));+ const content_payload = try content.buildPayload(true, "closed");+ defer gpa.free(content_payload);+ try std.testing.expect(std.mem.indexOf(u8, content_payload, "TOP_SECRET") != null);+ try std.testing.expect(std.mem.indexOf(u8, content_payload, "content_opt_in") != null);+}++test "turn metrics aggregate safe categories without exact MCP names" {+ const gpa = std.testing.allocator;+ var upload: Upload = .{+ .io = std.testing.io,+ .gpa = gpa,+ .client = null,+ .endpoint = "https://collector.example",+ .install_id = @splat('b'),+ .client_name = "test",+ .service_version = "test",+ .run_id = "fedcba9876543210",+ .mode = .metadata,+ };+ defer upload.deinit();+ upload.recordApi(1, false, 20, 100, 200, 300, 250, false);+ upload.recordTool(1, "bash", false, 5, 40, false);+ upload.recordTool(1, "mcp__private_server__lookup_customer", true, 7, 80, true);+ try std.testing.expectEqual(@as(usize, 1), upload.turns.items.len);+ const metrics = upload.turns.items[0];+ try std.testing.expectEqual(@as(u64, 1), metrics.api_calls);+ try std.testing.expectEqual(@as(u64, 2), metrics.tool_calls);+ try std.testing.expectEqual(@as(u64, 1), metrics.tool_shell);+ try std.testing.expectEqual(@as(u64, 1), metrics.tool_mcp);+ try std.testing.expectEqual(@as(u64, 1), metrics.tool_errors);++ _ = upload.appendEvent("run_started", 1, 1.0, .{ .version = "test", .unix_ms = @as(i64, 1) }, .{ .version = "test", .unix_ms = @as(i64, 1) });+ const payload = try upload.buildPayload(true, "closed");+ defer gpa.free(payload);+ try std.testing.expect(std.mem.indexOf(u8, payload, "lookup_customer") == null);+ try std.testing.expect(std.mem.indexOf(u8, payload, "\"tool_mcp\":1") != null);+}++test "batch admission limits always fit the wire cap" {+ const gpa = std.testing.allocator;+ var upload: Upload = .{+ .io = std.testing.io,+ .gpa = gpa,+ .client = null,+ .endpoint = "https://collector.example",+ .install_id = @splat('d'),+ .client_name = "test",+ .service_version = "test",+ .run_id = "0123456789abcdef",+ .mode = .metadata,+ };+ defer upload.deinit();++ var turn: u64 = 1;+ while (turn <= max_turns) : (turn += 1) {+ upload.recordApi(turn, false, std.math.maxInt(i64), std.math.maxInt(usize), std.math.maxInt(usize), std.math.maxInt(u64), std.math.maxInt(u64), true);+ upload.recordTool(turn, "bash", true, std.math.maxInt(i64), std.math.maxInt(usize), true);+ inline for (comptime std.meta.fieldNames(TurnMetrics)) |name| {+ if (!std.mem.eql(u8, name, "turn")) @field(upload.turns.items[@intCast(turn - 1)], name) = max_safe_json_integer;+ }+ }+ upload.recordApi(max_turns + 1, false, 1, 1, 1, 1, 1, false);+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_metrics);++ var seq: u64 = 1;+ while (seq <= max_events) : (seq += 1) {+ if (!upload.appendEvent(+ "run_started",+ seq,+ 1.0,+ .{ .version = "test", .unix_ms = @as(i64, 1), .provider = "provider-padding-provider-padding-provider-padding" },+ .{ .version = "test", .unix_ms = @as(i64, 1) },+ )) break;+ }+ try std.testing.expect(upload.dropped_events > 0);+ const payload = try upload.buildPayload(true, "closed");+ defer gpa.free(payload);+ try std.testing.expect(payload.len <= max_payload_bytes);+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, payload, .{});+ defer parsed.deinit();+ try std.testing.expect(parsed.value == .object);+}++test "oversized content event is rejected before queueing" {+ const gpa = std.testing.allocator;+ var upload: Upload = .{+ .io = std.testing.io,+ .gpa = gpa,+ .client = null,+ .endpoint = "https://collector.example",+ .install_id = @splat('e'),+ .client_name = "test",+ .service_version = "test",+ .run_id = "0123456789abcdef",+ .mode = .content,+ };+ defer upload.deinit();+ var oversized: [max_event_bytes * 2]u8 = @splat('x');+ try std.testing.expect(!upload.appendEvent(+ "turn_committed",+ 1,+ 1.0,+ .{ .turn = @as(u64, 1), .commitment_ref = "safe" },+ .{ .turn = @as(u64, 1), .reason = oversized[0..] },+ ));+ try std.testing.expectEqual(@as(usize, 0), upload.events.items.len);+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);+}++test "behavior endpoint derives beside OTLP logs without a fixed URL buffer" {+ const gpa = std.testing.allocator;+ const Case = struct {+ fn expect(gpa_inner: Allocator, endpoint: []const u8, expected: []const u8) !void {+ const actual = (try behaviorUrl(gpa_inner, endpoint)).?;+ defer gpa_inner.free(actual);+ try std.testing.expectEqualStrings(expected, actual);+ }+ };+ try Case.expect(gpa, "https://example.test/v1/logs", "https://example.test/v1/behavior");+ try Case.expect(gpa, "https://example.test/base/", "https://example.test/base/v1/behavior");+ try Case.expect(gpa, "https://example.test/v1/logs?token=x#ignored", "https://example.test/v1/behavior?token=x");+ try Case.expect(gpa, "https://example.test/base/?token=x", "https://example.test/base/v1/behavior?token=x");++ const long_token: [768]u8 = @splat('x');+ var endpoint_buf: [1024]u8 = undefined;+ const endpoint = try std.fmt.bufPrint(&endpoint_buf, "https://example.test/v1/logs?token={s}", .{long_token});+ const actual = (try behaviorUrl(gpa, endpoint)).?;+ defer gpa.free(actual);+ try std.testing.expect(actual.len > 512);+ try std.testing.expect(std.mem.startsWith(u8, actual, "https://example.test/v1/behavior?token="));+ try std.testing.expect(std.mem.endsWith(u8, actual, &long_token));+}diff --git a/src/learn_eval.zig b/src/learn_eval.zigindex dcadf1e7..7c51c5f1 100644--- a/src/learn_eval.zig+++ b/src/learn_eval.zig@@ -20,9 +20,8 @@ pub const evaluation_response_schema = "codegraff.learn.evaluation.response.v1";pub const run_schema = "codegraff.learn.run.v1";const file_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o600);-const executable_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o700);-const dir_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);-const js_exact_max: u64 = 9_007_199_254_740_991;+pub const executable_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_file else .fromMode(0o700);+pub const dir_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .default_dir else .fromMode(0o700);pub const GenomeRef = struct {id: []const u8,@@ -192,7 +191,7 @@ pub fn pairSeed(trial_id: []const u8, suite_sha256: []const u8, candidate_index:return std.fmt.bytesToHex(digest, .lower);}-fn createScratch(io: Io, store: *store_mod.Store) !struct { name: [32]u8, dir: Io.Dir } {+pub fn createScratch(io: Io, store: *store_mod.Store) !struct { name: [32]u8, dir: Io.Dir } {var attempts: usize = 0;while (attempts < 16) : (attempts += 1) {var raw: [16]u8 = undefined;@@ -209,14 +208,14 @@ fn createScratch(io: Io, store: *store_mod.Store) !struct { name: [32]u8, dir: Ireturn error.ScratchNameCollision;}-fn writePrivateWithPermissions(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8, permissions: Io.File.Permissions) !void {+pub fn writePrivateWithPermissions(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8, permissions: Io.File.Permissions) !void {const file = try dir.createFile(io, name, .{ .exclusive = true, .permissions = permissions });defer file.close(io);try file.writeStreamingAll(io, bytes);try file.sync(io);}-fn writePrivate(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {+pub fn writePrivate(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {return writePrivateWithPermissions(io, dir, name, bytes, file_permissions);}@@ -264,7 +263,7 @@ fn snapshotExtension(path: []const u8) []const u8 {return extension;}-fn invoke(+pub fn invoke(gpa: Allocator,io: Io,parent_env: *const std.process.Environ.Map,@@ -432,38 +431,15 @@ fn freePairs(gpa: Allocator, pairs: []PairRequest) void {gpa.free(pairs);}-/// Exact one-sided paired-binomial tail, evaluated stably from the first tail-/// term. A value at or below `alpha / planned_candidates` is significant.-pub fn pairedTail(wins: usize, losses: usize) f64 {- const n = wins + losses;- if (n == 0 or wins * 2 <= n) return 1.0;- const nf: f64 = @floatFromInt(n);- const wf: f64 = @floatFromInt(wins);- const lf: f64 = @floatFromInt(n - wins);- const log_term = std.math.lgamma(f64, nf + 1.0) - std.math.lgamma(f64, wf + 1.0) - std.math.lgamma(f64, lf + 1.0) - nf * @log(2.0);- var term = @exp(log_term);- var total = term;- var k = wins;- while (k < n) : (k += 1) {- term *= @as(f64, @floatFromInt(n - k)) / @as(f64, @floatFromInt(k + 1));- total += term;- }- return @min(1.0, total);-}--fn toPpb(p: f64) u64 {- if (p >= 1.0) return 1_000_000_000;- if (p <= 0.0) return 0;- return @intFromFloat(@ceil(p * 1_000_000_000.0));-}--fn checkedMetricAdd(a: u64, b: u64) !u64 {- const sum = std.math.add(u64, a, b) catch return error.InvalidMetric;- if (sum > js_exact_max) return error.InvalidMetric;- return sum;-}+// Exact paired-binomial statistics + metric guards live in learn_stats.zig+// (600-line goal); re-exported so existing call sites are unchanged.+const learn_stats = @import("learn_stats.zig");+pub const js_exact_max = learn_stats.js_exact_max;+pub const pairedTail = learn_stats.pairedTail;+const toPpb = learn_stats.toPpb;+const checkedMetricAdd = learn_stats.checkedMetricAdd;-fn computeComparison(config: store_mod.Config, suite_sha256: []const u8, request_id: []const u8, response_id: []const u8, requested: []const PairRequest, response: EvaluationResponse, planned_candidates: usize) !ComparisonRecord {+pub fn computeComparison(config: store_mod.Config, suite_sha256: []const u8, request_id: []const u8, response_id: []const u8, requested: []const PairRequest, response: EvaluationResponse, planned_candidates: usize) !ComparisonRecord {if (response.pairs.len != requested.len) return error.MissingPair;var parent_passes: usize = 0;var child_passes: usize = 0;@@ -696,115 +672,6 @@ pub fn validateRun(run: RunRecord) !void {}}-test "paired tail has known exact values" {- try std.testing.expectApproxEqAbs(@as(f64, 0.5), pairedTail(1, 0), 1e-12);- try std.testing.expectApproxEqAbs(@as(f64, 0.0546875), pairedTail(8, 2), 1e-12);- try std.testing.expectEqual(@as(f64, 1.0), pairedTail(2, 2));-}--test "paired gate rejects critical regressions and requires corrected significance" {- const config: store_mod.Config = .{- .schema = store_mod.config_schema,- .agent_name = "test",- .mutation_instruction = "change",- .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },- .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },- .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },- .gate = .{ .alpha_ppm = 50_000, .minimum_delta_ppm = 0, .minimum_pairs = 1 },- .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },- };- const case_ids = [_][]const u8{ "case-0", "case-1", "case-2", "case-3", "case-4", "case-5", "case-6", "case-7", "case-8", "case-9" };- var requested: [10]PairRequest = undefined;- var results: [10]PairResult = undefined;- for (0..10) |i| {- requested[i] = .{ .case_id = case_ids[i], .seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .critical = i == 0 };- results[i] = .{ .case_id = requested[i].case_id, .seed = requested[i].seed, .parent_pass = false, .child_pass = true, .parent_score_ppm = 0, .child_score_ppm = 1_000_000 };- }- const response: EvaluationResponse = .{ .schema = evaluation_response_schema, .trial_id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .candidate_index = 0, .cohort_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", .suite_sha256 = config.evaluation_suite.sha256, .parent_id = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", .child_id = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", .pairs = &results };- const comparison = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);- try std.testing.expect(comparison.eligible);- try std.testing.expectEqual(@as(usize, 10), comparison.statistical_units);-- results[0].parent_cost_micros = js_exact_max;- results[1].parent_cost_micros = 1;- try std.testing.expectError(error.InvalidMetric, computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1));- results[0].parent_cost_micros = 0;- results[1].parent_cost_micros = 0;-- for (0..10) |i| {- requested[i].case_id = "repeated-case";- results[i].case_id = "repeated-case";- }- const repeated = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);- try std.testing.expect(!repeated.eligible);- try std.testing.expectEqual(@as(usize, 1), repeated.statistical_units);- try std.testing.expectEqualStrings("not_significant", repeated.reason);-- results[0].parent_pass = true;- results[0].child_pass = false;- const critical = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);- try std.testing.expect(!critical.eligible);- try std.testing.expectEqualStrings("critical_regression", critical.reason);-}--test "tool invocation executes verified private program and input snapshots" {- if (builtin.os.tag == .windows) return;- const io = std.testing.io;- const allocator = std.testing.allocator;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();-- try writePrivateWithPermissions(io, tmp.dir, "tool.sh",- \\#!/bin/sh- \\set -eu- \\[ "$0" != "$ORIGINAL_PROGRAM" ]- \\[ "$1" != "$ORIGINAL_INPUT" ]- \\[ "$1" = "$GRAFF_LEARN_INPUT_0" ]- \\[ "$GRAFF_LEARN_INPUT_COUNT" = "1" ]- \\[ "$(cat "$1")" = "pinned-data" ]- \\printf 'snapshot-ok' > "$4"- \\- , executable_permissions);- try writePrivate(io, tmp.dir, "input.txt", "pinned-data\n");-- var root_buf: [std.fs.max_path_bytes]u8 = undefined;- const root_len = try tmp.dir.realPath(io, &root_buf);- const root = root_buf[0..root_len];- const program_path = try std.fmt.allocPrint(allocator, "{s}{c}tool.sh", .{ root, std.fs.path.sep });- defer allocator.free(program_path);- const input_path = try std.fmt.allocPrint(allocator, "{s}{c}input.txt", .{ root, std.fs.path.sep });- defer allocator.free(input_path);- const program_bytes = try store_mod.readFileNoFollow(io, tmp.dir, "tool.sh", allocator, 4096);- defer allocator.free(program_bytes);- const input_bytes = try store_mod.readFileNoFollow(io, tmp.dir, "input.txt", allocator, 4096);- defer allocator.free(input_bytes);- const program_hash = store_mod.rawSha256(program_bytes);- const input_hash = store_mod.rawSha256(input_bytes);-- var store = try store_mod.Store.initAt(io, tmp.dir);- defer store.deinit();- var scratch_created = try createScratch(io, &store);- defer store.tmp.deleteTree(io, &scratch_created.name) catch {};- defer scratch_created.dir.close(io);- try scratch_created.dir.createDir(io, "home", dir_permissions);- try scratch_created.dir.createDir(io, "tmp", dir_permissions);-- var parent_env = std.process.Environ.Map.init(allocator);- defer parent_env.deinit();- try parent_env.put("ORIGINAL_PROGRAM", program_path);- try parent_env.put("ORIGINAL_INPUT", input_path);- const inputs = [_]store_mod.PinnedFile{.{ .path = input_path, .sha256 = &input_hash }};- const args = [_][]const u8{input_path};- const pass_env = [_][]const u8{ "ORIGINAL_PROGRAM", "ORIGINAL_INPUT" };- const program: store_mod.Program = .{- .program = program_path,- .sha256 = &program_hash,- .args = &args,- .inputs = &inputs,- .pass_env = &pass_env,- };- try invoke(allocator, io, &parent_env, scratch_created.dir, program, "test", 1024, 1024, 10_000);- const response = try store_mod.readFileNoFollow(io, scratch_created.dir, "response.json", allocator, 1024);- defer allocator.free(response);- try std.testing.expectEqualStrings("snapshot-ok", response);+test {+ _ = @import("learn_eval_tests.zig");}diff --git a/src/learn_eval_tests.zig b/src/learn_eval_tests.zignew file mode 100644index 00000000..e4c8ae59--- /dev/null+++ b/src/learn_eval_tests.zig@@ -0,0 +1,138 @@+//! Tests for learn_eval.zig (600-line goal). Reached through the+//! `test { _ = ... }` hook in learn_eval.zig.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const learn_eval = @import("learn_eval.zig");+const store_mod = @import("learn_store.zig");++const PairRequest = learn_eval.PairRequest;+const PairResult = learn_eval.PairResult;+const EvaluationRequest = learn_eval.EvaluationRequest;+const EvaluationResponse = learn_eval.EvaluationResponse;+const ComparisonRecord = learn_eval.ComparisonRecord;+const pairedTail = learn_eval.pairedTail;+const computeComparison = learn_eval.computeComparison;+const createScratch = learn_eval.createScratch;+const writePrivate = learn_eval.writePrivate;+const invoke = learn_eval.invoke;+const evaluation_response_schema = learn_eval.evaluation_response_schema;+const js_exact_max = learn_eval.js_exact_max;+const writePrivateWithPermissions = learn_eval.writePrivateWithPermissions;+const executable_permissions = learn_eval.executable_permissions;+const dir_permissions = learn_eval.dir_permissions;+const builtin = @import("builtin");++test "paired tail has known exact values" {+ try std.testing.expectApproxEqAbs(@as(f64, 0.5), pairedTail(1, 0), 1e-12);+ try std.testing.expectApproxEqAbs(@as(f64, 0.0546875), pairedTail(8, 2), 1e-12);+ try std.testing.expectEqual(@as(f64, 1.0), pairedTail(2, 2));+}++test "paired gate rejects critical regressions and requires corrected significance" {+ const config: store_mod.Config = .{+ .schema = store_mod.config_schema,+ .agent_name = "test",+ .mutation_instruction = "change",+ .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },+ .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },+ .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },+ .gate = .{ .alpha_ppm = 50_000, .minimum_delta_ppm = 0, .minimum_pairs = 1 },+ .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },+ };+ const case_ids = [_][]const u8{ "case-0", "case-1", "case-2", "case-3", "case-4", "case-5", "case-6", "case-7", "case-8", "case-9" };+ var requested: [10]PairRequest = undefined;+ var results: [10]PairResult = undefined;+ for (0..10) |i| {+ requested[i] = .{ .case_id = case_ids[i], .seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .critical = i == 0 };+ results[i] = .{ .case_id = requested[i].case_id, .seed = requested[i].seed, .parent_pass = false, .child_pass = true, .parent_score_ppm = 0, .child_score_ppm = 1_000_000 };+ }+ const response: EvaluationResponse = .{ .schema = evaluation_response_schema, .trial_id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", .candidate_index = 0, .cohort_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", .suite_sha256 = config.evaluation_suite.sha256, .parent_id = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", .child_id = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", .pairs = &results };+ const comparison = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);+ try std.testing.expect(comparison.eligible);+ try std.testing.expectEqual(@as(usize, 10), comparison.statistical_units);++ results[0].parent_cost_micros = js_exact_max;+ results[1].parent_cost_micros = 1;+ try std.testing.expectError(error.InvalidMetric, computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1));+ results[0].parent_cost_micros = 0;+ results[1].parent_cost_micros = 0;++ for (0..10) |i| {+ requested[i].case_id = "repeated-case";+ results[i].case_id = "repeated-case";+ }+ const repeated = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);+ try std.testing.expect(!repeated.eligible);+ try std.testing.expectEqual(@as(usize, 1), repeated.statistical_units);+ try std.testing.expectEqualStrings("not_significant", repeated.reason);++ results[0].parent_pass = true;+ results[0].child_pass = false;+ const critical = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 1);+ try std.testing.expect(!critical.eligible);+ try std.testing.expectEqualStrings("critical_regression", critical.reason);+}++test "tool invocation executes verified private program and input snapshots" {+ if (builtin.os.tag == .windows) return;+ const io = std.testing.io;+ const allocator = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ try writePrivateWithPermissions(io, tmp.dir, "tool.sh",+ \\#!/bin/sh+ \\set -eu+ \\[ "$0" != "$ORIGINAL_PROGRAM" ]+ \\[ "$1" != "$ORIGINAL_INPUT" ]+ \\[ "$1" = "$GRAFF_LEARN_INPUT_0" ]+ \\[ "$GRAFF_LEARN_INPUT_COUNT" = "1" ]+ \\[ "$(cat "$1")" = "pinned-data" ]+ \\printf 'snapshot-ok' > "$4"+ \\+ , executable_permissions);+ try writePrivate(io, tmp.dir, "input.txt", "pinned-data\n");++ var root_buf: [std.fs.max_path_bytes]u8 = undefined;+ const root_len = try tmp.dir.realPath(io, &root_buf);+ const root = root_buf[0..root_len];+ const program_path = try std.fmt.allocPrint(allocator, "{s}{c}tool.sh", .{ root, std.fs.path.sep });+ defer allocator.free(program_path);+ const input_path = try std.fmt.allocPrint(allocator, "{s}{c}input.txt", .{ root, std.fs.path.sep });+ defer allocator.free(input_path);+ const program_bytes = try store_mod.readFileNoFollow(io, tmp.dir, "tool.sh", allocator, 4096);+ defer allocator.free(program_bytes);+ const input_bytes = try store_mod.readFileNoFollow(io, tmp.dir, "input.txt", allocator, 4096);+ defer allocator.free(input_bytes);+ const program_hash = store_mod.rawSha256(program_bytes);+ const input_hash = store_mod.rawSha256(input_bytes);++ var store = try store_mod.Store.initAt(io, tmp.dir);+ defer store.deinit();+ var scratch_created = try createScratch(io, &store);+ defer store.tmp.deleteTree(io, &scratch_created.name) catch {};+ defer scratch_created.dir.close(io);+ try scratch_created.dir.createDir(io, "home", dir_permissions);+ try scratch_created.dir.createDir(io, "tmp", dir_permissions);++ var parent_env = std.process.Environ.Map.init(allocator);+ defer parent_env.deinit();+ try parent_env.put("ORIGINAL_PROGRAM", program_path);+ try parent_env.put("ORIGINAL_INPUT", input_path);+ const inputs = [_]store_mod.PinnedFile{.{ .path = input_path, .sha256 = &input_hash }};+ const args = [_][]const u8{input_path};+ const pass_env = [_][]const u8{ "ORIGINAL_PROGRAM", "ORIGINAL_INPUT" };+ const program: store_mod.Program = .{+ .program = program_path,+ .sha256 = &program_hash,+ .args = &args,+ .inputs = &inputs,+ .pass_env = &pass_env,+ };+ try invoke(allocator, io, &parent_env, scratch_created.dir, program, "test", 1024, 1024, 10_000);+ const response = try store_mod.readFileNoFollow(io, scratch_created.dir, "response.json", allocator, 1024);+ defer allocator.free(response);+ try std.testing.expectEqualStrings("snapshot-ok", response);+}diff --git a/src/learn_stats.zig b/src/learn_stats.zignew file mode 100644index 00000000..8d6b0805--- /dev/null+++ b/src/learn_stats.zig@@ -0,0 +1,39 @@+//! Exact paired-binomial statistics and metric-addition guards for the local+//! learning evaluator. Split out of learn_eval.zig (600-line goal);+//! learn_eval.zig re-exports the shared names so call sites are unchanged.++const std = @import("std");++/// Largest metric value that survives an f64 round trip exactly.+pub const js_exact_max: u64 = 9_007_199_254_740_991;++/// Exact one-sided paired-binomial tail, evaluated stably from the first tail+/// term. A value at or below `alpha / planned_candidates` is significant.+pub fn pairedTail(wins: usize, losses: usize) f64 {+ const n = wins + losses;+ if (n == 0 or wins * 2 <= n) return 1.0;+ const nf: f64 = @floatFromInt(n);+ const wf: f64 = @floatFromInt(wins);+ const lf: f64 = @floatFromInt(n - wins);+ const log_term = std.math.lgamma(f64, nf + 1.0) - std.math.lgamma(f64, wf + 1.0) - std.math.lgamma(f64, lf + 1.0) - nf * @log(2.0);+ var term = @exp(log_term);+ var total = term;+ var k = wins;+ while (k < n) : (k += 1) {+ term *= @as(f64, @floatFromInt(n - k)) / @as(f64, @floatFromInt(k + 1));+ total += term;+ }+ return @min(1.0, total);+}++pub fn toPpb(p: f64) u64 {+ if (p >= 1.0) return 1_000_000_000;+ if (p <= 0.0) return 0;+ return @intFromFloat(@ceil(p * 1_000_000_000.0));+}++pub fn checkedMetricAdd(a: u64, b: u64) !u64 {+ const sum = std.math.add(u64, a, b) catch return error.InvalidMetric;+ if (sum > js_exact_max) return error.InvalidMetric;+ return sum;+}diff --git a/src/learn_store.zig b/src/learn_store.zigindex ee73dce9..fed7507b 100644--- a/src/learn_store.zig+++ b/src/learn_store.zig@@ -144,7 +144,7 @@ const file_permissions: Io.File.Permissions = if (builtin.os.tag == .windows) .d/// do not portably support FlushFileBuffers (ACCESS_DENIED is common), so/// Windows relies on atomic replacement plus synced file contents and has a/// weaker crash-durability guarantee.-fn syncDirectory(io: Io, dir: Io.Dir) !void {+pub fn syncDirectory(io: Io, dir: Io.Dir) !void {if (builtin.os.tag == .windows) return;const file = try dir.openFile(io, ".", .{.allow_directory = true,@@ -170,94 +170,12 @@ fn openFileNoFollow(io: Io, dir: Io.Dir, path: []const u8, options: Io.Dir.OpenFreturn file;}-pub fn validId(id: []const u8) bool {- if (id.len != 64) return false;- for (id) |c| if (!(std.ascii.isDigit(c) or (c >= 'a' and c <= 'f'))) return false;- return true;-}--fn validName(value: []const u8, max: usize) bool {- if (value.len == 0 or value.len > max or !std.unicode.utf8ValidateSlice(value)) return false;- for (value) |c| {- if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.')) return false;- }- return !std.mem.eql(u8, value, ".") and !std.mem.eql(u8, value, "..");-}--fn validText(value: []const u8, max: usize) bool {- return value.len > 0 and value.len <= max and std.unicode.utf8ValidateSlice(value) and std.mem.indexOfScalar(u8, value, 0) == null;-}--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- !std.mem.startsWith(u8, value, "GRAFF_LEARN_");-}--pub fn validateConfig(config: Config) !void {- if (!std.mem.eql(u8, config.schema, config_schema)) return error.UnsupportedSchema;- if (!validName(config.agent_name, 64)) return error.InvalidAgentName;- if (!validText(config.agent_description, 512)) return error.InvalidDescription;- if (!validText(config.mutation_instruction, 4096)) return error.InvalidMutationInstruction;- try validateProgram(config.mutator);- try validateProgram(config.evaluator);- try validateSuitePin(config.evaluation_suite);- if (config.holdout_suite) |suite| try validateSuitePin(suite);-- if (config.limits.genome_bytes == 0 or config.limits.genome_bytes > 8 << 20) return error.InvalidLimit;- if (config.limits.request_bytes < 1024 or config.limits.request_bytes > max_record_bytes) return error.InvalidLimit;- if (config.limits.response_bytes < 1024 or config.limits.response_bytes > max_record_bytes) return error.InvalidLimit;- if (config.limits.stdout_bytes > 1 << 20 or config.limits.stderr_bytes > 1 << 20) return error.InvalidLimit;- if (config.limits.mutator_timeout_ms == 0 or config.limits.mutator_timeout_ms > 3_600_000) return error.InvalidLimit;- if (config.limits.evaluator_timeout_ms == 0 or config.limits.evaluator_timeout_ms > 3_600_000) return error.InvalidLimit;-- if (config.gate.alpha_ppm == 0 or config.gate.alpha_ppm > 500_000) return error.InvalidGate;- if (config.gate.minimum_delta_ppm > 1_000_000) return error.InvalidGate;- if (config.gate.minimum_pairs == 0 or config.gate.minimum_pairs > max_pairs) return error.InvalidGate;- if (config.gate.default_candidates == 0 or config.gate.default_candidates > 16) return error.InvalidGate;- if (config.gate.default_repetitions == 0 or config.gate.default_repetitions > 100) return error.InvalidGate;- if (config.auto.enabled and config.holdout_suite == null) return error.AutoRequiresHoldout;-- inline for (.{ config.cohort.provider, config.cohort.model, config.cohort.task_family, config.cohort.adapter_version, config.cohort.verifier_version }) |field| {- if (!validText(field, 256)) return error.InvalidCohort;- }-}--fn validateProgram(program: Program) !void {- if (!std.fs.path.isAbsolute(program.program) or !validText(program.program, std.fs.max_path_bytes)) return error.InvalidProgramPath;- if (!validId(program.sha256)) return error.InvalidDigest;- if (program.args.len > 64 or program.inputs.len > 64 or program.pass_env.len > 32) return error.InvalidProgramConfig;- for (program.args) |arg| if (arg.len > 4096 or std.mem.indexOfScalar(u8, arg, 0) != null) return error.InvalidProgramConfig;- for (program.inputs, 0..) |input, i| {- if (!std.fs.path.isAbsolute(input.path) or !validText(input.path, std.fs.max_path_bytes) or !validId(input.sha256)) return error.InvalidProgramConfig;- for (program.inputs[0..i]) |prior| if (std.mem.eql(u8, prior.path, input.path)) return error.DuplicateProgramInput;- }- for (program.pass_env, 0..) |name, i| {- if (!validEnvName(name)) return error.InvalidEnvironmentName;- for (program.pass_env[0..i]) |prior| if (std.mem.eql(u8, prior, name)) return error.DuplicateEnvironmentName;- }-}--fn validateSuitePin(suite: Suite) !void {- if (!std.fs.path.isAbsolute(suite.path) or !validText(suite.path, std.fs.max_path_bytes)) return error.InvalidSuitePath;- if (!validId(suite.sha256)) return error.InvalidDigest;-}--pub fn validateSuite(manifest: SuiteManifest) !void {- if (!std.mem.eql(u8, manifest.schema, suite_schema)) return error.UnsupportedSuiteSchema;- if (!validName(manifest.suite_id, 128)) return error.InvalidSuiteId;- if (manifest.cases.len == 0 or manifest.cases.len > max_pairs) return error.InvalidSuiteCases;- for (manifest.cases, 0..) |case, i| {- if (!validName(case.id, 128)) return error.InvalidCaseId;- for (manifest.cases[0..i]) |prior| if (std.mem.eql(u8, prior.id, case.id)) return error.DuplicateCaseId;- }-}+// Input validation lives in learn_store_validate.zig (600-line goal); the+// public entry points are re-exported so external call sites are unchanged.+const validate_mod = @import("learn_store_validate.zig");+pub const validId = validate_mod.validId;+pub const validateConfig = validate_mod.validateConfig;+const validateSuite = validate_mod.validateSuite;pub fn rawSha256(bytes: []const u8) [64]u8 {var digest: [32]u8 = undefined;@@ -535,7 +453,7 @@ pub const Store = struct {try syncDirectory(self.io, dir);}- fn writeAtomicReplace(self: *Store, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {+ pub fn writeAtomicReplace(self: *Store, dir: Io.Dir, name: []const u8, bytes: []const u8) !void {var atomic = try dir.createFileAtomic(self.io, name, .{ .permissions = file_permissions, .replace = true });defer atomic.deinit(self.io);try atomic.file.writeStreamingAll(self.io, bytes);@@ -756,127 +674,6 @@ pub fn loadActiveAgent(io: Io, arena: Allocator) ?ActiveAgent {};}-test "learning IDs are full, domain-separated, and byte exact" {- const a = domainId("codegraff-learn/genome/v1", "hello\n");- const b = domainId("codegraff-learn/genome/v1", "hello");- const c = domainId("codegraff-learn/evidence/v1", "hello\n");- try std.testing.expect(validId(&a));- try std.testing.expect(!std.mem.eql(u8, &a, &b));- try std.testing.expect(!std.mem.eql(u8, &a, &c));- try std.testing.expect(!validId("ABC"));-}--test "learning config parser rejects unknown fields and unsafe auto" {- const good =- \\{"schema":"codegraff.learn.config.v1","agent_name":"candidate","mutation_instruction":"change one behavior","mutator":{"program":"/bin/a","sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"evaluator":{"program":"/bin/b","sha256":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},"evaluation_suite":{"path":"/suite","sha256":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},"cohort":{"provider":"test","model":"test","task_family":"test","adapter_version":"v1","verifier_version":"v1"}}- ;- var parsed = try std.json.parseFromSlice(Config, std.testing.allocator, good, .{});- defer parsed.deinit();- try validateConfig(parsed.value);- const unknown = good[0 .. good.len - 1] ++ ",\"surprise\":true}";- try std.testing.expectError(error.UnknownField, std.json.parseFromSlice(Config, std.testing.allocator, unknown, .{}));-}--test "directory synchronization reopens path-only handles" {- const io = std.testing.io;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try syncDirectory(io, tmp.dir);-}--test "no-follow reads preserve exact bytes" {- const io = std.testing.io;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.writeFile(io, .{ .sub_path = "sample", .data = "exact bytes" });- const bytes = try readFileNoFollow(io, tmp.dir, "sample", std.testing.allocator, 64);- defer std.testing.allocator.free(bytes);- try std.testing.expectEqualStrings("exact bytes", bytes);-}--test "immutable learning objects and atomic active ref round trip" {- const io = std.testing.io;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var store = try Store.initAt(io, tmp.dir);- defer store.deinit();-- const first = try store.writeGenome(std.testing.allocator, "prompt one");- const again = try store.writeGenome(std.testing.allocator, "prompt one");- try std.testing.expectEqualStrings(&first, &again);- const read = try store.readGenome(std.testing.allocator, &first, 1024);- defer std.testing.allocator.free(read);- try std.testing.expectEqualStrings("prompt one", read);-}--test "learning activation rejects stale refs and broken transaction ancestry" {- const io = std.testing.io;- const allocator = std.testing.allocator;- var arena_state = std.heap.ArenaAllocator.init(allocator);- defer arena_state.deinit();- const arena = arena_state.allocator();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var store = try Store.initAt(io, tmp.dir);- defer store.deinit();-- const config: Config = .{- .schema = config_schema,- .agent_name = "test-agent",- .mutation_instruction = "change",- .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },- .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },- .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },- .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },- };- const config_bytes = try jsonBytes(allocator, config);- defer allocator.free(config_bytes);- _ = try store.bootstrap(allocator, arena, config_bytes, "parent", 1);- const loaded_config = try store.loadConfig(arena);- const active_zero = try store.loadActive(arena, loaded_config);- const second = try store.writeGenome(allocator, "second");- try std.testing.expectError(error.FileTooBig, store.activate(allocator, active_zero.ref, &loaded_config.id, &second, null, "rollback", 1, 2));- try store.activate(allocator, active_zero.ref, &loaded_config.id, &second, null, "rollback", config.limits.genome_bytes, 2);- const active_one = try store.loadActive(arena, loaded_config);- const third = try store.writeGenome(allocator, "third");- try std.testing.expectError(error.ActiveRefChanged, store.activate(allocator, active_zero.ref, &loaded_config.id, &third, null, "rollback", config.limits.genome_bytes, 3));-- const broken_tx: Transaction = .{- .schema = transaction_schema,- .generation = 2,- .operation = "rollback",- .previous_genome_id = active_one.ref.genome_id,- .next_genome_id = &third,- .run_id = null,- .previous_transaction_id = active_zero.ref.transaction_id,- .created_unix_ms = 4,- };- const broken_tx_bytes = try jsonBytes(allocator, broken_tx);- defer allocator.free(broken_tx_bytes);- const broken_tx_id = try store.writeTransaction(allocator, broken_tx_bytes);- const broken_active: ActiveRef = .{- .schema = active_schema,- .config_id = &loaded_config.id,- .generation = 2,- .genome_id = &third,- .transaction_id = &broken_tx_id,- };- const broken_active_bytes = try jsonBytes(allocator, broken_active);- defer allocator.free(broken_active_bytes);- try store.writeAtomicReplace(store.refs, "active.json", broken_active_bytes);- try std.testing.expectError(error.BrokenTransactionChain, store.loadActive(arena, loaded_config));-}--test "learning store rejects symlinked root" {- if (builtin.os.tag == .windows) return;- const io = std.testing.io;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.createDir(io, "outside", .default_dir);- try tmp.dir.symLink(io, "outside", ".graff", .{ .is_directory = true });- if (Store.initAt(io, tmp.dir)) |opened| {- var store = opened;- store.deinit();- return error.TestExpectedError;- } else |_| {}+test {+ _ = @import("learn_store_tests.zig");}diff --git a/src/learn_store_tests.zig b/src/learn_store_tests.zignew file mode 100644index 00000000..83edc060--- /dev/null+++ b/src/learn_store_tests.zig@@ -0,0 +1,147 @@+//! Tests for learn_store.zig (600-line goal). Reached through the+//! `test { _ = ... }` hook in learn_store.zig.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const builtin = @import("builtin");+const store_mod = @import("learn_store.zig");++const Store = store_mod.Store;+const Transaction = store_mod.Transaction;+const ActiveRef = store_mod.ActiveRef;+const domainId = store_mod.domainId;+const jsonBytes = store_mod.jsonBytes;+const readFileNoFollow = store_mod.readFileNoFollow;+const config_schema = store_mod.config_schema;+const active_schema = store_mod.active_schema;+const Config = store_mod.Config;+const validId = store_mod.validId;+const syncDirectory = store_mod.syncDirectory;+const validateConfig = store_mod.validateConfig;+const transaction_schema = store_mod.transaction_schema;++test "learning IDs are full, domain-separated, and byte exact" {+ const a = domainId("codegraff-learn/genome/v1", "hello\n");+ const b = domainId("codegraff-learn/genome/v1", "hello");+ const c = domainId("codegraff-learn/evidence/v1", "hello\n");+ try std.testing.expect(validId(&a));+ try std.testing.expect(!std.mem.eql(u8, &a, &b));+ try std.testing.expect(!std.mem.eql(u8, &a, &c));+ try std.testing.expect(!validId("ABC"));+}++test "learning config parser rejects unknown fields and unsafe auto" {+ const good =+ \\{"schema":"codegraff.learn.config.v1","agent_name":"candidate","mutation_instruction":"change one behavior","mutator":{"program":"/bin/a","sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"evaluator":{"program":"/bin/b","sha256":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},"evaluation_suite":{"path":"/suite","sha256":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},"cohort":{"provider":"test","model":"test","task_family":"test","adapter_version":"v1","verifier_version":"v1"}}+ ;+ var parsed = try std.json.parseFromSlice(Config, std.testing.allocator, good, .{});+ defer parsed.deinit();+ try validateConfig(parsed.value);+ const unknown = good[0 .. good.len - 1] ++ ",\"surprise\":true}";+ try std.testing.expectError(error.UnknownField, std.json.parseFromSlice(Config, std.testing.allocator, unknown, .{}));+}++test "directory synchronization reopens path-only handles" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try syncDirectory(io, tmp.dir);+}++test "no-follow reads preserve exact bytes" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.writeFile(io, .{ .sub_path = "sample", .data = "exact bytes" });+ const bytes = try readFileNoFollow(io, tmp.dir, "sample", std.testing.allocator, 64);+ defer std.testing.allocator.free(bytes);+ try std.testing.expectEqualStrings("exact bytes", bytes);+}++test "immutable learning objects and atomic active ref round trip" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var store = try Store.initAt(io, tmp.dir);+ defer store.deinit();++ const first = try store.writeGenome(std.testing.allocator, "prompt one");+ const again = try store.writeGenome(std.testing.allocator, "prompt one");+ try std.testing.expectEqualStrings(&first, &again);+ const read = try store.readGenome(std.testing.allocator, &first, 1024);+ defer std.testing.allocator.free(read);+ try std.testing.expectEqualStrings("prompt one", read);+}++test "learning activation rejects stale refs and broken transaction ancestry" {+ const io = std.testing.io;+ const allocator = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var store = try Store.initAt(io, tmp.dir);+ defer store.deinit();++ const config: Config = .{+ .schema = config_schema,+ .agent_name = "test-agent",+ .mutation_instruction = "change",+ .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },+ .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },+ .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },+ .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },+ };+ const config_bytes = try jsonBytes(allocator, config);+ defer allocator.free(config_bytes);+ _ = try store.bootstrap(allocator, arena, config_bytes, "parent", 1);+ const loaded_config = try store.loadConfig(arena);+ const active_zero = try store.loadActive(arena, loaded_config);+ const second = try store.writeGenome(allocator, "second");+ try std.testing.expectError(error.FileTooBig, store.activate(allocator, active_zero.ref, &loaded_config.id, &second, null, "rollback", 1, 2));+ try store.activate(allocator, active_zero.ref, &loaded_config.id, &second, null, "rollback", config.limits.genome_bytes, 2);+ const active_one = try store.loadActive(arena, loaded_config);+ const third = try store.writeGenome(allocator, "third");+ try std.testing.expectError(error.ActiveRefChanged, store.activate(allocator, active_zero.ref, &loaded_config.id, &third, null, "rollback", config.limits.genome_bytes, 3));++ const broken_tx: Transaction = .{+ .schema = transaction_schema,+ .generation = 2,+ .operation = "rollback",+ .previous_genome_id = active_one.ref.genome_id,+ .next_genome_id = &third,+ .run_id = null,+ .previous_transaction_id = active_zero.ref.transaction_id,+ .created_unix_ms = 4,+ };+ const broken_tx_bytes = try jsonBytes(allocator, broken_tx);+ defer allocator.free(broken_tx_bytes);+ const broken_tx_id = try store.writeTransaction(allocator, broken_tx_bytes);+ const broken_active: ActiveRef = .{+ .schema = active_schema,+ .config_id = &loaded_config.id,+ .generation = 2,+ .genome_id = &third,+ .transaction_id = &broken_tx_id,+ };+ const broken_active_bytes = try jsonBytes(allocator, broken_active);+ defer allocator.free(broken_active_bytes);+ try store.writeAtomicReplace(store.refs, "active.json", broken_active_bytes);+ try std.testing.expectError(error.BrokenTransactionChain, store.loadActive(arena, loaded_config));+}++test "learning store rejects symlinked root" {+ if (builtin.os.tag == .windows) return;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.createDir(io, "outside", .default_dir);+ try tmp.dir.symLink(io, "outside", ".graff", .{ .is_directory = true });+ if (Store.initAt(io, tmp.dir)) |opened| {+ var store = opened;+ store.deinit();+ return error.TestExpectedError;+ } else |_| {}+}diff --git a/src/learn_store_validate.zig b/src/learn_store_validate.zignew file mode 100644index 00000000..a8197d55--- /dev/null+++ b/src/learn_store_validate.zig@@ -0,0 +1,105 @@+//! Input validation for the local learning store: id/name/text/env-name+//! shape checks plus config/program/suite validation. Split out of+//! learn_store.zig (600-line goal); learn_store.zig re-exports the public+//! entry points so external call sites are unchanged.++const std = @import("std");+const store = @import("learn_store.zig");++const Config = store.Config;+const Program = store.Program;+const Suite = store.Suite;+const SuiteManifest = store.SuiteManifest;+const config_schema = store.config_schema;+const max_record_bytes = store.max_record_bytes;+const max_pairs = store.max_pairs;+const suite_schema = store.suite_schema;++pub fn validId(id: []const u8) bool {+ if (id.len != 64) return false;+ for (id) |c| if (!(std.ascii.isDigit(c) or (c >= 'a' and c <= 'f'))) return false;+ return true;+}++pub fn validName(value: []const u8, max: usize) bool {+ if (value.len == 0 or value.len > max or !std.unicode.utf8ValidateSlice(value)) return false;+ for (value) |c| {+ if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.')) return false;+ }+ return !std.mem.eql(u8, value, ".") and !std.mem.eql(u8, value, "..");+}++pub fn validText(value: []const u8, max: usize) bool {+ return value.len > 0 and value.len <= max and std.unicode.utf8ValidateSlice(value) and std.mem.indexOfScalar(u8, value, 0) == null;+}++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+ !std.mem.startsWith(u8, value, "GRAFF_LEARN_");+}++pub fn validateConfig(config: Config) !void {+ if (!std.mem.eql(u8, config.schema, config_schema)) return error.UnsupportedSchema;+ if (!validName(config.agent_name, 64)) return error.InvalidAgentName;+ if (!validText(config.agent_description, 512)) return error.InvalidDescription;+ if (!validText(config.mutation_instruction, 4096)) return error.InvalidMutationInstruction;+ try validateProgram(config.mutator);+ try validateProgram(config.evaluator);+ try validateSuitePin(config.evaluation_suite);+ if (config.holdout_suite) |suite| try validateSuitePin(suite);++ if (config.limits.genome_bytes == 0 or config.limits.genome_bytes > 8 << 20) return error.InvalidLimit;+ if (config.limits.request_bytes < 1024 or config.limits.request_bytes > max_record_bytes) return error.InvalidLimit;+ if (config.limits.response_bytes < 1024 or config.limits.response_bytes > max_record_bytes) return error.InvalidLimit;+ if (config.limits.stdout_bytes > 1 << 20 or config.limits.stderr_bytes > 1 << 20) return error.InvalidLimit;+ if (config.limits.mutator_timeout_ms == 0 or config.limits.mutator_timeout_ms > 3_600_000) return error.InvalidLimit;+ if (config.limits.evaluator_timeout_ms == 0 or config.limits.evaluator_timeout_ms > 3_600_000) return error.InvalidLimit;++ if (config.gate.alpha_ppm == 0 or config.gate.alpha_ppm > 500_000) return error.InvalidGate;+ if (config.gate.minimum_delta_ppm > 1_000_000) return error.InvalidGate;+ if (config.gate.minimum_pairs == 0 or config.gate.minimum_pairs > max_pairs) return error.InvalidGate;+ if (config.gate.default_candidates == 0 or config.gate.default_candidates > 16) return error.InvalidGate;+ if (config.gate.default_repetitions == 0 or config.gate.default_repetitions > 100) return error.InvalidGate;+ if (config.auto.enabled and config.holdout_suite == null) return error.AutoRequiresHoldout;++ inline for (.{ config.cohort.provider, config.cohort.model, config.cohort.task_family, config.cohort.adapter_version, config.cohort.verifier_version }) |field| {+ if (!validText(field, 256)) return error.InvalidCohort;+ }+}++pub fn validateProgram(program: Program) !void {+ if (!std.fs.path.isAbsolute(program.program) or !validText(program.program, std.fs.max_path_bytes)) return error.InvalidProgramPath;+ if (!validId(program.sha256)) return error.InvalidDigest;+ if (program.args.len > 64 or program.inputs.len > 64 or program.pass_env.len > 32) return error.InvalidProgramConfig;+ for (program.args) |arg| if (arg.len > 4096 or std.mem.indexOfScalar(u8, arg, 0) != null) return error.InvalidProgramConfig;+ for (program.inputs, 0..) |input, i| {+ if (!std.fs.path.isAbsolute(input.path) or !validText(input.path, std.fs.max_path_bytes) or !validId(input.sha256)) return error.InvalidProgramConfig;+ for (program.inputs[0..i]) |prior| if (std.mem.eql(u8, prior.path, input.path)) return error.DuplicateProgramInput;+ }+ for (program.pass_env, 0..) |name, i| {+ if (!validEnvName(name)) return error.InvalidEnvironmentName;+ for (program.pass_env[0..i]) |prior| if (std.mem.eql(u8, prior, name)) return error.DuplicateEnvironmentName;+ }+}++pub fn validateSuitePin(suite: Suite) !void {+ if (!std.fs.path.isAbsolute(suite.path) or !validText(suite.path, std.fs.max_path_bytes)) return error.InvalidSuitePath;+ if (!validId(suite.sha256)) return error.InvalidDigest;+}++pub fn validateSuite(manifest: SuiteManifest) !void {+ if (!std.mem.eql(u8, manifest.schema, suite_schema)) return error.UnsupportedSuiteSchema;+ if (!validName(manifest.suite_id, 128)) return error.InvalidSuiteId;+ if (manifest.cases.len == 0 or manifest.cases.len > max_pairs) return error.InvalidSuiteCases;+ for (manifest.cases, 0..) |case, i| {+ if (!validName(case.id, 128)) return error.InvalidCaseId;+ for (manifest.cases[0..i]) |prior| if (std.mem.eql(u8, prior.id, case.id)) return error.DuplicateCaseId;+ }+}diff --git a/src/main.zig b/src/main.zigindex 96049d02..07a44b44 100644--- a/src/main.zig+++ b/src/main.zig@@ -12,7 +12,7 @@ const Io = std.Io;/// rescan+swap+deinit the bundle, a handshake reading it mid-swap fails instantly/// with error.TlsInitializationFailed (ms=0, resp_bytes=0 — see #131). Warming it/// here sets client.now, so every later connect skips the rescan entirely.-fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) void {+pub fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) void {const now = Io.Clock.real.now(io);client.ca_bundle.rescan(gpa, io, now) catch return;client.now = now;@@ -144,7 +144,7 @@ const schema = @import("schema.zig");// The provider/keys core (ProviderSpec/provider_specs, Provider, Keys) lives in provider.zig; provider_specs/Keys stay local aliases for main()'s credential setup and tests.const provider_mod = @import("provider.zig");const provider_specs = provider_mod.provider_specs;-const Keys = provider_mod.Keys;+pub const Keys = provider_mod.Keys;// Approvals (command/tool approval gate) + confinedPath/noSymlinkEscape live in approvals.zig; main() constructs one directly for the session.const approvals_mod = @import("approvals.zig");const Approvals = approvals_mod.Approvals;@@ -153,6 +153,7 @@ const Approvals = approvals_mod.Approvals;const trace = @import("trace.zig");const Tracer = trace.Tracer;const BehaviorTrace = trace.BehaviorTrace;+const behavior_trace = @import("behavior_trace.zig");const behavior_upload = @import("behavior_upload.zig");const Trajectory = trace.Trajectory;const behavior_dir = trace.behavior_dir;@@ -456,54 +457,15 @@ pub fn main(init: std.process.Init) !void {// Behavioral tracing starts only after the root Agent exists, so utility// and self-test paths do not create zero-turn behavioral runs. The local- // JSONL and the privacy-projected upload are independent sinks.- const behavior_upload_mode = behavior_upload.resolveMode(- init.environ_map.get("GRAFF_BEHAVIOR_UPLOAD"),- telem.endpoint.len > 0,- );- var behavior_uploader: behavior_upload.Upload = .{- .io = io,- .gpa = gpa,- .client = &client,- .endpoint = telem.endpoint,- .auth_key = telem.auth_key,- .install_id = telem.install_id,- .client_name = telem.client_name,- .service_version = harness_version,- .run_id = &scoring.g_run_id,- .mode = behavior_upload_mode,- };- defer behavior_uploader.deinit();-- const behavior_enabled = if (init.environ_map.get("GRAFF_BEHAVIOR_TRACE")) |value|- !(std.ascii.eqlIgnoreCase(value, "off") or std.mem.eql(u8, value, "0") or std.ascii.eqlIgnoreCase(value, "false") or std.ascii.eqlIgnoreCase(value, "no"))- else- true;+ // JSONL and the privacy-projected upload are independent sinks; the Boot+ // owns both, wired and torn down in LIFO order (behavior_trace.zig).var behavior_buf: [8 * 1024]u8 = undefined;- var behavior_open = if (behavior_enabled)- session_start.openBehaviorFile(io, Io.Dir.cwd(), behavior_dir, &scoring.g_run_id, &behavior_buf)- else- session_start.FileWriterOpen{ .file = null, .writer = undefined };- defer if (behavior_open.file) |f| f.close(io);- var behavior: BehaviorTrace = .{- .io = io,- .gpa = gpa,- .out = if (behavior_open.file != null) &behavior_open.writer.interface else null,- .upload = if (behavior_uploader.active()) &behavior_uploader else null,- .run_id = &scoring.g_run_id,- };- // Assigned once; all root/subagent callbacks already share this stable- // tracer. The behavior storage remains alive until main's frame unwinds.- tracer.behavior = &behavior;- defer {- // A clean return is not a task success verdict. Session-owned workers- // are joined by newer defers before this terminal event and upload.- behavior.finish(.closed);- tracer.behavior = null;- }+ var behavior_boot = behavior_trace.boot(io, gpa, &client, init.environ_map, telem.endpoint, telem.auth_key, telem.install_id, telem.client_name, harness_version, &behavior_buf);+ behavior_boot.link(&tracer);+ defer behavior_boot.finishAndClose(&tracer, .closed);// Registered after the normal defer so error unwinding records `error`// first; finish() is idempotent and keeps that status terminal.- errdefer behavior.finish(.failed);+ errdefer behavior_boot.behavior.finish(.failed);// LIFO teardown: joinElites, then background bash pumps, then emit/send// run_finished, then close/deinit the two behavioral sinks. The earlier@@ -519,7 +481,7 @@ pub fn main(init: std.process.Init) !void {// cold-cache compaction until after lifecycle start.try session_run.restoreResumedSession(arena, out, &root, &keys, flags, json_mode, g_cwd_display);const behavior_prompt_sha = scoring.promptFingerprint(root.systemPrompt());- behavior.startWithMetadata(harness_version, telem.start_unix_ms, .{+ behavior_boot.behavior.startWithMetadata(harness_version, telem.start_unix_ms, .{.provider = root.provider.id,.model = root.provider.model,.prompt_sha = &behavior_prompt_sha,@@ -603,7 +565,7 @@ const serve = @import("serve.zig");pub const codegraff_device_base = "https://gateway.codegraff.com";// The Agent struct (fields + smallest methods) + TodoItem live in agent.zig, imported as agent_mod (not agent) since several functions here declare a local `var agent: Agent = ...` that would shadow a bare import.const agent_mod = @import("agent.zig");-const Agent = agent_mod.Agent;+pub const Agent = agent_mod.Agent;// Wire-format message construction lives in messages.zig, imported as messages_mod to avoid shadowing the `messages` params/fields.const messages_mod = @import("messages.zig");/// A base64-encoded image staged by `/image`, sent with the next user turn.@@ -725,47 +687,5 @@ test "incremental markdown streaming renders like renderMdLine" {test { // pull in tests from imported modules (mcp.zig)_ = mcp;-}--test "/bash slash command runs the bash tool and frees its gpa-allocated result" {- // Regression guard for PR #38: the /bash slash handler routes through execTool, whose result.text is gpa-owned (NOT arena-owned — every other- // caller frees it). Forgetting `defer root.gpa.free(result.text)` in handleCommand leaks on every /bash call; std.testing.allocator catches it here.- const gpa = std.testing.allocator;- const io = std.testing.io;-- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const arena = arena_state.allocator();-- var client: std.http.Client = .{ .allocator = gpa, .io = io };- defer client.deinit();- prewarmCaBundle(&client, gpa, io);-- var root: Agent = .{- .gpa = gpa,- .arena = arena,- .io = io,- .client = &client,- .provider = .{- .id = "test",- .kind = .openai,- .auth = .bearer,- .url = "",- .api_key = "",- .model = "m",- .context = 100_000,- },- .messages = std.json.Array.init(arena),- .sub = false,- .label = "test",- .out = null,- };- var keys: Keys = .{ .values = @splat(null) };- var aw: Io.Writer.Allocating = .init(gpa);- defer aw.deinit();- defer root.tools_used.deinit(gpa);- try handleCommand(&root, &keys, arena, "/bash echo leak-guard-XYZ", &aw.writer);-- const written = aw.writer.buffered();- try std.testing.expect(std.mem.indexOf(u8, written, "leak-guard-XYZ") != null);+ _ = @import("main_tests.zig");}diff --git a/src/main_tests.zig b/src/main_tests.zignew file mode 100644index 00000000..7695ce4d--- /dev/null+++ b/src/main_tests.zig@@ -0,0 +1,54 @@+//! Tests for main.zig (600-line goal). Reached through the `test { _ = ... }`+//! hook in main.zig, mirroring the mcp.zig pattern.++const std = @import("std");+const Io = std.Io;+const main_mod = @import("main.zig");++const Agent = main_mod.Agent;+const Keys = main_mod.Keys;+const prewarmCaBundle = main_mod.prewarmCaBundle;+const handleCommand = main_mod.handleCommand;++test "/bash slash command runs the bash tool and frees its gpa-allocated result" {+ // Regression guard for PR #38: the /bash slash handler routes through execTool, whose result.text is gpa-owned (NOT arena-owned — every other+ // caller frees it). Forgetting `defer root.gpa.free(result.text)` in handleCommand leaks on every /bash call; std.testing.allocator catches it here.+ const gpa = std.testing.allocator;+ const io = std.testing.io;++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ prewarmCaBundle(&client, gpa, io);++ var root: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = &client,+ .provider = .{+ .id = "test",+ .kind = .openai,+ .auth = .bearer,+ .url = "",+ .api_key = "",+ .model = "m",+ .context = 100_000,+ },+ .messages = std.json.Array.init(arena),+ .sub = false,+ .label = "test",+ .out = null,+ };+ var keys: Keys = .{ .values = @splat(null) };+ var aw: Io.Writer.Allocating = .init(gpa);+ defer aw.deinit();+ defer root.tools_used.deinit(gpa);+ try handleCommand(&root, &keys, arena, "/bash echo leak-guard-XYZ", &aw.writer);++ const written = aw.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, written, "leak-guard-XYZ") != null);+}