Skip to content

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

Python

refactor(trace,telemetry): split behavioral trace + telemetry transport into sibling modules (#246)

Rach Pradhan3d9cd8790b5b
diff --git a/src/behavior_trace.zig b/src/behavior_trace.zig
new file mode 100644
index 00000000..0094cae5
--- /dev/null
+++ b/src/behavior_trace.zig
@@ -0,0 +1,340 @@
+//! Per-run behavioral event stream (`codegraff.behavior.v1`): the
+//! experimental lifecycle/belief envelope and the BehaviorTrace producer with
+//! its independent local + upload sinks. Split out of trace.zig (600-line
+//! goal); trace.zig re-exports the public names so call sites are unchanged.
+//! Schema + privacy contract: docs/behavioral-trajectories.md.
+//! Tests live in behavior_trace_tests.zig.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const behavior_upload = @import("behavior_upload.zig");
+
+test {
+ _ = @import("behavior_trace_tests.zig");
+}
+
+// ── Behavioral trace (one experimental event file per run) ────────────────
+
+pub const behavior_dir = ".graff/trajectories";
+pub const behavior_schema = "codegraff.behavior.v1";
+
+/// Task-agnostic behavioral records. Per-kind fields stay flat, matching the
+/// schema-harness event shape; state/action/expect values remain opaque JSON.
+pub const BehaviorKind = enum {
+ run_started,
+ turn_started,
+ text_delta,
+ tool_started,
+ tool_finished,
+ turn_committed,
+ action_taken,
+ model_mispredicted,
+ run_finished,
+};
+
+/// Typed lifecycle status; `.failed` is serialized as the JSON value `error`.
+pub const BehaviorRunStatus = enum {
+ closed,
+ failed,
+};
+
+pub const max_local_behavior_event_bytes = 64 * 1024;
+
+/// Serialize a behavioral event as one flat JSON object. `fields` must be a
+/// struct; its fields are appended after the common envelope. Building the
+/// full line before writing prevents serialization failures from corrupting the
+/// file. The fixed 64 KiB line buffer also prevents an opaque adapter value from
+/// causing unbounded temporary allocation. A write failure disables the stream
+/// so a partial tail is never joined to a later event.
+pub fn writeBehaviorLine(gpa: Allocator, w: *Io.Writer, kind: BehaviorKind, seq: u64, ts: f64, run_id: []const u8, fields: anytype) bool {
+ const backing = gpa.alloc(u8, max_local_behavior_event_bytes + 1) catch return false;
+ defer gpa.free(backing);
+ var line: Io.Writer = .fixed(backing);
+ var s: std.json.Stringify = .{ .writer = &line };
+ s.beginObject() catch return false;
+ s.objectField("kind") catch return false;
+ s.write(@tagName(kind)) catch return false;
+ s.objectField("seq") catch return false;
+ s.write(seq) catch return false;
+ s.objectField("ts") catch return false;
+ s.write(ts) catch return false;
+ s.objectField("run_id") catch return false;
+ s.write(run_id) catch return false;
+ s.objectField("schema") catch return false;
+ s.write(behavior_schema) catch return false;
+ inline for (comptime std.meta.fieldNames(@TypeOf(fields))) |name| {
+ comptime {
+ if (std.mem.eql(u8, name, "kind") or
+ std.mem.eql(u8, name, "seq") or
+ std.mem.eql(u8, name, "ts") or
+ std.mem.eql(u8, name, "run_id") or
+ std.mem.eql(u8, name, "schema"))
+ {
+ @compileError("behavioral event field collides with the common envelope: " ++ name);
+ }
+ }
+ s.objectField(name) catch return false;
+ s.write(@field(fields, name)) catch return false;
+ }
+ s.endObject() catch return false;
+ if (line.buffered().len > max_local_behavior_event_bytes) return false;
+ line.writeByte('\n') catch return false;
+ w.writeAll(line.buffered()) catch return false;
+ w.flush() catch return false;
+ return true;
+}
+
+/// Per-run behavioral event stream written to
+/// `.graff/trajectories/<run_id>.jsonl`. `seq` is contiguous file order for
+/// this run and starts at one. `ts` is Unix time in fractional seconds. Every
+/// event carries `run_id` and `schema`, so it remains attributable even if run
+/// files are later merged. Payload fields are plaintext and are not sanitized;
+/// callers must explicitly avoid secrets and proprietary content.
+pub fn commitmentRef(key: *const [32]u8, commitment_id: []const u8) [16]u8 {
+ // The random key never leaves this process, so low-entropy adapter IDs
+ // cannot be recovered from uploaded references with an offline dictionary.
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ hash.update(key);
+ hash.update(&.{0});
+ hash.update(commitment_id);
+ var digest: [32]u8 = undefined;
+ hash.final(&digest);
+ return std.fmt.bytesToHex(digest[0..8].*, .lower);
+}
+
+pub const BehaviorRunMetadata = struct {
+ provider: []const u8 = "",
+ model: []const u8 = "",
+ prompt_sha: []const u8 = "",
+ effort: []const u8 = "",
+};
+
+pub const BehaviorTrace = struct {
+ mutex: Io.Mutex = .init,
+ io: Io,
+ gpa: Allocator,
+ out: ?*Io.Writer,
+ upload: ?*behavior_upload.Upload = null,
+ run_id: []const u8,
+ seq: u64 = 0,
+ current_turn: u64 = 0,
+ turn_active: bool = false,
+ started: bool = false,
+ closed: bool = false,
+ commitment_key: [32]u8 = undefined,
+ commitment_key_initialized: bool = false,
+
+ fn timestamp(self: *BehaviorTrace) f64 {
+ const now = Io.Timestamp.now(self.io, .real);
+ return @as(f64, @floatFromInt(now.nanoseconds)) / 1_000_000_000.0;
+ }
+
+ /// Emit to the independent local and upload sinks. The return value says
+ /// whether the upload retained this event; callers otherwise do not couple
+ /// sink health. In particular, finish() uses it so `complete=true` cannot
+ /// describe a batch whose terminal event was dropped during admission.
+ fn eventLocked(self: *BehaviorTrace, kind: BehaviorKind, local_fields: anytype, metadata_fields: anytype, content_fields: anytype) bool {
+ if (self.closed or self.seq == std.math.maxInt(u64)) return false;
+ const uploader_active = if (self.upload) |uploader| uploader.active() else false;
+ if (self.out == null and !uploader_active) return false;
+
+ // This is the logical source sequence, reserved before either
+ // independent sink is attempted. A bounded upload may therefore have
+ // gaps, reported by dropped_events, while the local file remains a
+ // contiguous prefix until any terminal write failure.
+ const next = self.seq + 1;
+ self.seq = next;
+ const ts = self.timestamp();
+ if (self.out) |w| {
+ if (!writeBehaviorLine(self.gpa, w, kind, next, ts, self.run_id, local_fields)) {
+ // Do not append after a possible partial write. Upload remains
+ // independent so a local disk failure need not erase metadata.
+ self.out = null;
+ }
+ }
+ if (self.upload) |uploader| {
+ return uploader.appendEvent(@tagName(kind), next, ts, metadata_fields, content_fields);
+ }
+ return false;
+ }
+
+ /// Start this run exactly once. The generic serializer stays private so
+ /// callers cannot accidentally emit a kind without its required fields.
+ pub fn start(self: *BehaviorTrace, version: []const u8, unix_ms: i64) void {
+ self.startWithMetadata(version, unix_ms, .{});
+ }
+
+ pub fn startWithMetadata(self: *BehaviorTrace, version: []const u8, unix_ms: i64, metadata: BehaviorRunMetadata) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (self.started or self.closed) return;
+ self.io.randomSecure(&self.commitment_key) catch self.io.random(&self.commitment_key);
+ self.commitment_key_initialized = true;
+ self.started = true;
+ const local_fields = .{
+ .version = version,
+ .unix_ms = unix_ms,
+ .provider = metadata.provider,
+ .model = metadata.model,
+ .prompt_sha = metadata.prompt_sha,
+ .effort = metadata.effort,
+ };
+ // A deterministic prompt fingerprint is useful in the local trace but
+ // remains prompt-derived data: even a truncated digest can disclose a
+ // low-entropy prompt through enumeration. Never include it in either
+ // network projection.
+ const upload_fields = .{
+ .version = version,
+ .unix_ms = unix_ms,
+ .provider = metadata.provider,
+ .model = metadata.model,
+ .effort = metadata.effort,
+ };
+ _ = self.eventLocked(.run_started, local_fields, upload_fields, upload_fields);
+ }
+
+ /// Begin one root turn. Behavioral turn IDs are dense and independent of
+ /// legacy trajectory node IDs, which can skip as child agents are added.
+ pub fn beginTurn(self: *BehaviorTrace, trajectory_node: u64) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or self.current_turn == std.math.maxInt(u64)) return 0;
+ const parent_turn = self.current_turn;
+ const turn = parent_turn + 1;
+ self.current_turn = turn;
+ self.turn_active = true;
+ const fields = .{
+ .turn = turn,
+ .parent_turn = parent_turn,
+ .trajectory_node = trajectory_node,
+ };
+ _ = self.eventLocked(.turn_started, fields, fields, fields);
+ return turn;
+ }
+
+ /// Clear attribution only for the matching active turn. The last turn ID is
+ /// retained separately in current_turn so the next turn keeps a dense parent
+ /// chain, while late administrative API/tool work is attributed to turn 0.
+ pub fn endTurn(self: *BehaviorTrace, turn: u64) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (turn != 0 and self.turn_active and turn == self.current_turn) self.turn_active = false;
+ }
+
+ pub fn currentTurn(self: *BehaviorTrace) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ return if (self.turn_active) self.current_turn else 0;
+ }
+
+ /// Assert that a task adapter observed a committed action and expectation.
+ /// This records the caller's belief; it does not execute or verify the action.
+ pub fn recordExpectedAction(self: *BehaviorTrace, turn: u64, commitment_id: []const u8, action: anytype, expected: anytype, reason: []const u8) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or commitment_id.len == 0) return;
+ const local_fields = .{
+ .turn = turn,
+ .commitment_id = commitment_id,
+ .action = action,
+ .expect = expected,
+ .reason = reason,
+ };
+ std.debug.assert(self.commitment_key_initialized);
+ const commitment_ref = commitmentRef(&self.commitment_key, commitment_id);
+ _ = self.eventLocked(.turn_committed, local_fields, .{
+ .turn = turn,
+ .commitment_ref = &commitment_ref,
+ }, local_fields);
+ }
+
+ /// Assert that a caller or task-specific verifier found a contradiction.
+ /// No generic semantic comparison is attempted by this backend.
+ pub fn recordMisprediction(self: *BehaviorTrace, turn: u64, commitment_id: []const u8, predicted: anytype, actual: anytype, detail: []const u8) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or commitment_id.len == 0) return;
+ const local_fields = .{
+ .turn = turn,
+ .commitment_id = commitment_id,
+ .predicted = predicted,
+ .actual = actual,
+ .detail = detail,
+ };
+ std.debug.assert(self.commitment_key_initialized);
+ const commitment_ref = commitmentRef(&self.commitment_key, commitment_id);
+ _ = self.eventLocked(.model_mispredicted, local_fields, .{
+ .turn = turn,
+ .commitment_ref = &commitment_ref,
+ }, local_fields);
+ }
+
+ /// Attach content-free operational aggregates to the active root turn.
+ /// These are not behavioral tool events: no invocation identity, argument,
+ /// result, or action semantics are inferred from the operational hook.
+ pub fn recordApiMetric(
+ self: *BehaviorTrace,
+ from_subagent: bool,
+ ms: i64,
+ req_bytes: usize,
+ resp_bytes: usize,
+ context_tokens: u64,
+ cache_read_tokens: u64,
+ is_error: bool,
+ ) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active) return 0;
+ const turn = self.current_turn;
+ if (self.upload) |uploader| uploader.recordApi(turn, from_subagent, ms, req_bytes, resp_bytes, context_tokens, cache_read_tokens, is_error);
+ return turn;
+ }
+
+ pub fn recordToolMetric(self: *BehaviorTrace, name: []const u8, from_subagent: bool, ms: i64, result_bytes: usize, is_error: bool) u64 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (!self.started or self.closed or !self.turn_active) return 0;
+ const turn = self.current_turn;
+ if (self.upload) |uploader| uploader.recordTool(turn, name, from_subagent, ms, result_bytes, is_error);
+ return turn;
+ }
+
+ const FinishState = struct {
+ uploader: ?*behavior_upload.Upload,
+ complete: bool,
+ };
+
+ pub fn prepareFinish(self: *BehaviorTrace, status_name: []const u8) ?FinishState {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (self.closed) return null;
+
+ var terminal_retained = false;
+ if (self.started) {
+ const fields = .{ .status = status_name };
+ terminal_retained = self.eventLocked(.run_finished, fields, fields, fields);
+ }
+ self.turn_active = false;
+ self.closed = true;
+ return .{
+ .uploader = self.upload,
+ // This flag describes the uploaded lifecycle, not merely process
+ // control flow. A dropped terminal event must remain incomplete.
+ .complete = self.started and (self.upload == null or terminal_retained),
+ };
+ }
+
+ /// Mark a normal process/session close. This is deliberately not a task
+ /// success verdict. A missing run_finished record means the run is incomplete.
+ pub fn finish(self: *BehaviorTrace, status: BehaviorRunStatus) void {
+ const status_name: []const u8 = switch (status) {
+ .closed => "closed",
+ .failed => "error",
+ };
+ const state = self.prepareFinish(status_name) orelse return;
+ // Network I/O is terminal and bounded, but it must not hold the mutex
+ // used by concurrent API/tool callbacks.
+ if (state.uploader) |uploader| uploader.send(state.complete, status_name);
+ }
+};
diff --git a/src/behavior_trace_tests.zig b/src/behavior_trace_tests.zig
new file mode 100644
index 00000000..57270e9b
--- /dev/null
+++ b/src/behavior_trace_tests.zig
@@ -0,0 +1,506 @@
+//! Tests for behavior_trace.zig (600-line goal). Reached through the
+//! `test { _ = @import(...) }` hook at the bottom of behavior_trace.zig's
+//! declarations, mirroring the mcp.zig pattern in main.zig.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+const behavior_upload = @import("behavior_upload.zig");
+const trace = @import("trace.zig");
+const btrace = @import("behavior_trace.zig");
+
+const BehaviorTrace = btrace.BehaviorTrace;
+const BehaviorRunMetadata = btrace.BehaviorRunMetadata;
+const behavior_schema = btrace.behavior_schema;
+const writeBehaviorLine = btrace.writeBehaviorLine;
+const max_local_behavior_event_bytes = btrace.max_local_behavior_event_bytes;
+const Tracer = trace.Tracer;
+const Trajectory = trace.Trajectory;
+const beginRootTurn = trace.beginRootTurn;
+const endRootTurn = trace.endRootTurn;
+
+fn expectObjectKeys(object: std.json.ObjectMap, expected: []const []const u8) !void {
+ try std.testing.expectEqual(expected.len, object.count());
+ for (expected) |key| try std.testing.expect(object.get(key) != null);
+}
+
+test "writeBehaviorLine: oversized adapter content is rejected before local allocation can grow" {
+ const gpa = std.testing.allocator;
+ var out: Io.Writer.Allocating = .init(gpa);
+ defer out.deinit();
+ const oversized = try gpa.alloc(u8, max_local_behavior_event_bytes + 1);
+ defer gpa.free(oversized);
+ @memset(oversized, 'x');
+ try std.testing.expect(!writeBehaviorLine(gpa, &out.writer, .turn_committed, 1, 1.0, "0123456789abcdef", .{
+ .turn = @as(u64, 1),
+ .reason = oversized,
+ }));
+ try std.testing.expectEqual(@as(usize, 0), out.writer.buffered().len);
+}
+
+test "BehaviorTrace: events are flat, attributable, and ordered" {
+ 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 = "run-test-1",
+ };
+
+ behavior.start("test", 1_234);
+ behavior.start("ignored-duplicate", 9_999);
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(7));
+ behavior.recordExpectedAction(
+ 1,
+ "commit-1",
+ .{ .tool = "edit_file", .note = "line one\nline two ☃" },
+ .{ .build = "passes", .attempts = @as(u64, 1) },
+ "verify the edit compiles",
+ );
+ behavior.recordMisprediction(
+ 1,
+ "commit-1",
+ .{ .build = "passes" },
+ .{ .build = "fails", .exit_code = @as(i64, 1) },
+ "reported by a task-specific verifier",
+ );
+ behavior.finish(.closed);
+ // Typed lifecycle methods cannot append after closure.
+ behavior.recordExpectedAction(1, "late", .{ .tool = "bash" }, .{ .ok = true }, "too late");
+
+ const out = aw.writer.buffered();
+ try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, out, "\n"));
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, out, "\n"), '\n');
+
+ var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer started.deinit();
+ try std.testing.expectEqualStrings("run_started", started.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 1), started.value.object.get("seq").?.integer);
+ try std.testing.expect(started.value.object.get("ts").? == .float);
+ try std.testing.expectEqualStrings("run-test-1", started.value.object.get("run_id").?.string);
+ try std.testing.expectEqualStrings(behavior_schema, started.value.object.get("schema").?.string);
+ try std.testing.expectEqualStrings("test", started.value.object.get("version").?.string);
+ try std.testing.expectEqual(@as(i64, 1_234), started.value.object.get("unix_ms").?.integer);
+ try std.testing.expect(started.value.object.get("payload") == null);
+
+ var turn = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer turn.deinit();
+ try std.testing.expectEqualStrings("turn_started", turn.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 2), turn.value.object.get("seq").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), turn.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 0), turn.value.object.get("parent_turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 7), turn.value.object.get("trajectory_node").?.integer);
+ try std.testing.expectEqualStrings("run-test-1", turn.value.object.get("run_id").?.string);
+
+ var committed = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer committed.deinit();
+ try std.testing.expectEqualStrings("turn_committed", committed.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 3), committed.value.object.get("seq").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), committed.value.object.get("turn").?.integer);
+ try std.testing.expectEqualStrings("commit-1", committed.value.object.get("commitment_id").?.string);
+ try std.testing.expectEqualStrings("line one\nline two ☃", committed.value.object.get("action").?.object.get("note").?.string);
+ try std.testing.expectEqualStrings("passes", committed.value.object.get("expect").?.object.get("build").?.string);
+ try std.testing.expectEqualStrings("verify the edit compiles", committed.value.object.get("reason").?.string);
+
+ var mismatch = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer mismatch.deinit();
+ try std.testing.expectEqualStrings("model_mispredicted", mismatch.value.object.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 4), mismatch.value.object.get("seq").?.integer);
+ try std.testing.expectEqualStrings("commit-1", mismatch.value.object.get("commitment_id").?.string);
+ try std.testing.expectEqualStrings("fails", mismatch.value.object.get("actual").?.object.get("build").?.string);
+ try std.testing.expectEqualStrings("reported by a task-specific verifier", mismatch.value.object.get("detail").?.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);
+ try std.testing.expectEqual(@as(i64, 5), finished.value.object.get("seq").?.integer);
+ try std.testing.expectEqualStrings("closed", finished.value.object.get("status").?.string);
+ try std.testing.expectEqualStrings("run-test-1", finished.value.object.get("run_id").?.string);
+ try std.testing.expect(lines.next() == null);
+}
+
+test "BehaviorTrace: disabled writes do not consume sequence numbers" {
+ const io = std.testing.io;
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = std.testing.allocator,
+ .out = null,
+ .run_id = "disabled-run",
+ };
+
+ behavior.start("test", 0);
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));
+ try std.testing.expectEqual(@as(u64, 0), behavior.seq);
+ try std.testing.expectEqual(@as(u64, 1), behavior.currentTurn());
+}
+
+test "BehaviorTrace: typed APIs reject out-of-lifecycle adapter events" {
+ 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 = "lifecycle-run",
+ };
+
+ try std.testing.expectEqual(@as(u64, 0), behavior.beginTurn(9));
+ behavior.recordExpectedAction(1, "early", .{ .kind = "edit" }, .{ .ok = true }, "before start");
+ behavior.start("test", 1);
+ behavior.recordExpectedAction(1, "early", .{ .kind = "edit" }, .{ .ok = true }, "before turn");
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(9));
+ behavior.recordExpectedAction(0, "zero-turn", .{ .kind = "edit" }, .{ .ok = true }, "invalid turn");
+ behavior.recordExpectedAction(2, "future-turn", .{ .kind = "edit" }, .{ .ok = true }, "invalid turn");
+ behavior.recordExpectedAction(1, "", .{ .kind = "edit" }, .{ .ok = true }, "empty commitment");
+ behavior.recordMisprediction(1, "", .{ .ok = true }, .{ .ok = false }, "empty commitment");
+
+ try std.testing.expectEqual(@as(u64, 2), behavior.seq);
+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, aw.writer.buffered(), "\n"));
+ behavior.finish(.failed);
+ behavior.finish(.closed); // the first terminal status wins
+ try std.testing.expectEqual(@as(u64, 3), behavior.seq);
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
+ _ = lines.next();
+ _ = lines.next();
+ var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer finished.deinit();
+ try std.testing.expectEqualStrings("error", finished.value.object.get("status").?.string);
+}
+
+test "BehaviorTrace: a full upload queue cannot claim a complete terminal lifecycle" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('q'),
+ .client_name = "harness",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+
+ behavior.start("test", 1);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+ const placeholder = upload.events.items[0][0..0];
+ try upload.events.resize(gpa, behavior_upload.max_events);
+ for (upload.events.items[1..]) |*event| event.* = placeholder;
+
+ const state = behavior.prepareFinish("closed").?;
+ try std.testing.expect(!state.complete);
+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);
+ try std.testing.expectEqual(@as(usize, behavior_upload.max_events), upload.events.items.len);
+
+ // Remove synthetic queue entries before normal deinit and payload parsing.
+ upload.events.shrinkRetainingCapacity(1);
+ const payload = try upload.buildPayload(state.complete, "closed");
+ defer gpa.free(payload);
+ var parsed = try std.json.parseFromSlice(Value, gpa, payload, .{});
+ defer parsed.deinit();
+ try std.testing.expect(!parsed.value.object.get("complete").?.bool);
+ try std.testing.expectEqual(@as(usize, 1), parsed.value.object.get("events").?.array.items.len);
+}
+
+test "BehaviorTrace: terminal allocation failure leaves upload incomplete" {
+ const backing_gpa = std.testing.allocator;
+ const io = std.testing.io;
+ // run_started uses one allocation for its event and one for ArrayList
+ // storage. Fail the next allocation, which is run_finished serialization.
+ var failing = std.testing.FailingAllocator.init(backing_gpa, .{ .fail_index = 2 });
+ const failing_gpa = failing.allocator();
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = failing_gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('a'),
+ .client_name = "harness",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .metadata,
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = backing_gpa,
+ .out = null,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+
+ behavior.start("test", 1);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+ const state = behavior.prepareFinish("error").?;
+ try std.testing.expect(failing.has_induced_failure);
+ try std.testing.expect(!state.complete);
+ try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+
+ failing.fail_index = std.math.maxInt(usize);
+ const payload = try upload.buildPayload(state.complete, "error");
+ defer failing_gpa.free(payload);
+ var parsed = try std.json.parseFromSlice(Value, backing_gpa, payload, .{});
+ defer parsed.deinit();
+ try std.testing.expect(!parsed.value.object.get("complete").?.bool);
+}
+
+test "BehaviorTrace: metadata-default upload is an exact content-free projection" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var local: Io.Writer.Allocating = .init(gpa);
+ defer local.deinit();
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('c'),
+ .client_name = "test",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = behavior_upload.resolveMode(null, true),
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &local.writer,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+ behavior.startWithMetadata("test", 1_234, .{
+ .provider = "anthropic",
+ .model = "test-model",
+ .prompt_sha = "0011223344556677",
+ .effort = "high",
+ });
+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(7));
+ behavior.recordExpectedAction(
+ 1,
+ "COMMITMENT_SECRET",
+ .{ .source = "SOURCE_SECRET", .tool_args = "TOOL_ARGUMENT_SECRET" },
+ .{ .tool_result = "TOOL_RESULT_SECRET" },
+ "REASON_SECRET",
+ );
+ behavior.recordMisprediction(
+ 1,
+ "COMMITMENT_SECRET",
+ .{ .model_output = "MODEL_OUTPUT_SECRET" },
+ .{ .workspace_path = "PRIVATE_PATH_SECRET" },
+ "DETAIL_SECRET",
+ );
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+ tracer.api("repl", false, "test-model", 20, 100, 200, 300, 250, false);
+ tracer.tool("mcp__private_server__lookup_customer", 7, true, 80, true);
+ behavior.finish(.closed);
+ behavior.finish(.failed);
+ // Late callbacks may race terminal teardown. They must observe closure and
+ // leave the uploader untouched after send can begin.
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordApiMetric(false, 99, 999, 999, 999, 999, true));
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordToolMetric("bash", false, 99, 999, true));
+
+ const secrets = [_][]const u8{
+ "COMMITMENT_SECRET",
+ "SOURCE_SECRET",
+ "TOOL_ARGUMENT_SECRET",
+ "TOOL_RESULT_SECRET",
+ "REASON_SECRET",
+ "MODEL_OUTPUT_SECRET",
+ "PRIVATE_PATH_SECRET",
+ "DETAIL_SECRET",
+ "0011223344556677",
+ "private_server",
+ "lookup_customer",
+ };
+ const local_jsonl = local.writer.buffered();
+ for (secrets[0..9]) |secret| try std.testing.expect(std.mem.indexOf(u8, local_jsonl, secret) != null);
+
+ const payload = try upload.buildPayload(true, "closed");
+ defer gpa.free(payload);
+ for (&secrets) |secret| try std.testing.expect(std.mem.indexOf(u8, payload, secret) == null);
+ var parsed = try std.json.parseFromSlice(Value, gpa, payload, .{});
+ defer parsed.deinit();
+ const batch = parsed.value.object;
+ try expectObjectKeys(batch, &.{
+ "schema",
+ "event_schema",
+ "privacy",
+ "run_id",
+ "install_id",
+ "client_name",
+ "service_version",
+ "complete",
+ "terminal_status",
+ "dropped_events",
+ "dropped_metrics",
+ "events",
+ "turn_metrics",
+ });
+ 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);
+ try expectObjectKeys(events[0].object, &.{ "kind", "seq", "ts", "run_id", "schema", "version", "unix_ms", "provider", "model", "effort" });
+ 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" });
+ try expectObjectKeys(events[4].object, &.{ "kind", "seq", "ts", "run_id", "schema", "status" });
+ try std.testing.expectEqualStrings(events[2].object.get("commitment_ref").?.string, events[3].object.get("commitment_ref").?.string);
+
+ const metrics = batch.get("turn_metrics").?.array.items;
+ try std.testing.expectEqual(@as(usize, 1), metrics.len);
+ try std.testing.expectEqual(@as(i64, 0), metrics[0].object.get("api_subagent_calls").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_subagent_calls").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_mcp").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_errors").?.integer);
+}
+
+test "BehaviorTrace: prompt fingerprint stays local in content mode" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var local: Io.Writer.Allocating = .init(gpa);
+ defer local.deinit();
+ var upload: behavior_upload.Upload = .{
+ .io = io,
+ .gpa = gpa,
+ .client = null,
+ .endpoint = "https://collector.example/v1/logs",
+ .install_id = @splat('c'),
+ .client_name = "harness",
+ .service_version = "test",
+ .run_id = "0123456789abcdef",
+ .mode = .content,
+ };
+ defer upload.deinit();
+ var behavior: BehaviorTrace = .{
+ .io = io,
+ .gpa = gpa,
+ .out = &local.writer,
+ .upload = &upload,
+ .run_id = "0123456789abcdef",
+ };
+ behavior.startWithMetadata("test", 1, .{ .prompt_sha = "0011223344556677" });
+ try std.testing.expect(std.mem.indexOf(u8, local.writer.buffered(), "0011223344556677") != null);
+ try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
+ try std.testing.expect(std.mem.indexOf(u8, upload.events.items[0], "0011223344556677") == null);
+ try std.testing.expect(std.mem.indexOf(u8, upload.events.items[0], "prompt_sha") == null);
+}
+
+test "beginRootTurn: correlates without allocating a legacy node" {
+ 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 = "root-turn-run",
+ };
+ var trajectory: Trajectory = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ };
+ defer trajectory.deinit();
+
+ behavior.start("test", 1);
+ const trajectory_node = trajectory.nextId();
+ trajectory.setTurn(trajectory_node);
+ const legacy_next_id = trajectory.next_id;
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+ const previous_trajectory = trace.g_traj;
+ trace.g_traj = &trajectory;
+ defer trace.g_traj = previous_trajectory;
+
+ try std.testing.expectEqual(@as(u64, 1), beginRootTurn(&tracer));
+ try std.testing.expectEqual(legacy_next_id, trajectory.next_id);
+ try std.testing.expectEqual(trajectory_node, trajectory.currentTurn());
+
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
+ _ = lines.next(); // run_started
+ var turn = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer turn.deinit();
+ try std.testing.expectEqual(@as(i64, 1), turn.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, @intCast(trajectory_node)), turn.value.object.get("trajectory_node").?.integer);
+}
+
+test "endRootTurn: clears attribution while preserving the dense parent chain" {
+ 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 = "root-scope-run",
+ };
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = gpa,
+ .out = null,
+ .start = Io.Timestamp.now(io, .awake),
+ .behavior = &behavior,
+ };
+ const previous_trajectory = trace.g_traj;
+ trace.g_traj = null;
+ defer trace.g_traj = previous_trajectory;
+
+ behavior.start("test", 1);
+ const first = beginRootTurn(&tracer);
+ try std.testing.expectEqual(@as(u64, 1), first);
+ try std.testing.expectEqual(first, behavior.recordApiMetric(false, 1, 1, 1, 1, 1, false));
+ try std.testing.expectEqual(first, behavior.recordToolMetric("bash", false, 1, 1, false));
+
+ endRootTurn(&tracer, first);
+ try std.testing.expectEqual(@as(u64, 0), behavior.currentTurn());
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordApiMetric(false, 1, 1, 1, 1, 1, false));
+ try std.testing.expectEqual(@as(u64, 0), behavior.recordToolMetric("bash", false, 1, 1, false));
+ behavior.recordExpectedAction(first, "late", .{ .tool = "bash" }, .{ .ok = true }, "outside the root turn");
+
+ const second = beginRootTurn(&tracer);
+ try std.testing.expectEqual(@as(u64, 2), second);
+ endRootTurn(&tracer, first); // a stale scope cannot clear the new turn
+ try std.testing.expectEqual(second, behavior.currentTurn());
+ endRootTurn(&tracer, second);
+ try std.testing.expectEqual(@as(u64, 0), behavior.currentTurn());
+ try std.testing.expectEqual(@as(u64, 3), behavior.seq);
+
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
+ _ = lines.next(); // run_started
+ _ = lines.next(); // first turn_started
+ var second_started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
+ defer second_started.deinit();
+ try std.testing.expectEqual(@as(i64, 2), second_started.value.object.get("turn").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), second_started.value.object.get("parent_turn").?.integer);
+ try std.testing.expect(lines.next() == null);
+}
diff --git a/src/telemetry.zig b/src/telemetry.zig
index 49ad095a..df2f03e4 100644
--- a/src/telemetry.zig
+++ b/src/telemetry.zig
@@ -29,7 +29,6 @@ const scoring = @import("scoring.zig");
const root = @import("main.zig");
const harness_version = root.harness_version;
-// ── Telemetry (OTEL) ────────────────────────────────────────────────────────
// ── Telemetry (OTEL) ────────────────────────────────────────────────────────
/// Anonymous usage telemetry, exported as OTLP/HTTP JSON log records in one
@@ -41,27 +40,17 @@ const harness_version = root.harness_version;
/// anonymous id (~/.simple-harness-install-id) identifies the install; SDKs
/// pass their own id via HARNESS_SDK_INSTALL_ID + HARNESS_CLIENT so SDK
/// users are counted separately. Flush failures never disturb the session.
-pub fn validatedAuthKey(value: ?[]const u8) ?[]const u8 {
- const key = value orelse return null;
- if (key.len == 0 or key.len > 1024) return null;
- // Header values must not admit control/whitespace injection. Collector keys
- // are intentionally a single visible token rather than generic OTLP header
- // syntax, which also keeps secrets out of parsing diagnostics.
- for (key) |byte| if (byte < 0x21 or byte > 0x7e) return null;
- return key;
-}
-
-fn otlpLogsUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {
- // Append the signal path to the URL path rather than to a query value. URL
- // fragments are client-side only and must not be sent to the collector.
- const fragment_at = std.mem.indexOfScalar(u8, endpoint, '#') orelse endpoint.len;
- const without_fragment = endpoint[0..fragment_at];
- const query_at = std.mem.indexOfScalar(u8, without_fragment, '?') orelse without_fragment.len;
- const query = without_fragment[query_at..];
- const base = std.mem.trimEnd(u8, without_fragment[0..query_at], "/");
- if (base.len == 0) return null;
- if (std.mem.endsWith(u8, base, "/v1/logs")) return try std.fmt.allocPrint(gpa, "{s}{s}", .{ base, query });
- return try std.fmt.allocPrint(gpa, "{s}/v1/logs{s}", .{ base, query });
+///
+/// Transport helpers (collector key validation, signal-URL derivation, the
+/// bounded-deadline POST path's mock collectors and tests) live in
+/// telemetry_net.zig (600-line goal).
+const telemetry_net = @import("telemetry_net.zig");
+pub const validatedAuthKey = telemetry_net.validatedAuthKey;
+const otlpLogsUrl = telemetry_net.otlpLogsUrl;
+
+test {
+ _ = telemetry_net;
+ _ = @import("telemetry_tests.zig");
}
pub const Telemetry = struct {
@@ -93,7 +82,7 @@ pub const Telemetry = struct {
/// One buffered log record. body "error": kind/detail set. body
/// "workflow": phases/tasks/failed/duration set. body "score":
/// detail = prompt_sha, score = the evaluation value.
- const Event = struct {
+ pub const Event = struct {
t_ms: i64,
body: []const u8, // "error" | "workflow" | "ultracode" | "score" (static)
kind: []const u8 = "", // error source: "api" | "tool" | "turn" (static)
@@ -379,7 +368,7 @@ pub const Telemetry = struct {
self.sendBatchWithDeadline(events, include_summary, .fromSeconds(3));
}
- fn sendBatchWithDeadline(self: *Telemetry, events: []const Event, include_summary: bool, deadline: Io.Duration) void {
+ pub fn sendBatchWithDeadline(self: *Telemetry, events: []const Event, include_summary: bool, deadline: Io.Duration) void {
if (!self.on()) return;
const client = self.client orelse return;
if (events.len == 0 and !include_summary) return;
@@ -591,209 +580,6 @@ pub const Telemetry = struct {
}
};
-fn stallTelemetryCollector(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);
- io.sleep(.fromSeconds(5), .awake) catch {};
-}
-
-fn answerTelemetryCollector(
- io: Io,
- server: *Io.net.Server,
- expected_key: []const u8,
- saw_key: *std.atomic.Value(bool),
-) void {
- const stream = server.accept(io) catch return;
- defer stream.close(io);
- var read_buf: [16 * 1024]u8 = undefined;
- var reader = Io.net.Stream.Reader.init(stream, io, &read_buf);
- while (reader.interface.takeDelimiter('\n') catch null) |line| {
- if (std.mem.eql(u8, line, "\r") or line.len == 0) break;
- const prefix = "x-harness-key:";
- if (!std.ascii.startsWithIgnoreCase(line, prefix)) continue;
- const value = std.mem.trim(u8, line[prefix.len..], " \t\r\n");
- saw_key.store(std.mem.eql(u8, value, expected_key), .release);
- }
- const response = "HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
- var write_buf: [256]u8 = undefined;
- var writer = Io.net.Stream.Writer.init(stream, io, &write_buf);
- writer.interface.writeAll(response) catch return;
- writer.interface.flush() catch {};
-}
-
/// Set once in main() when telemetry is configured; Tracer and the workflow
/// runner feed it through this. Null → every hook is a no-op.
pub var g_telem: ?*Telemetry = null;
-
-test "telemetry collector key accepts one bounded visible token" {
- try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey(null));
- try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey(""));
- try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("secret key"));
- try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("secret\r\ninjected"));
- try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("nön-ascii"));
- try std.testing.expectEqualStrings("safe-token_123", validatedAuthKey("safe-token_123").?);
-}
-
-test "OTLP URL derivation preserves queries and drops fragments" {
- const gpa = std.testing.allocator;
- const appended = (try otlpLogsUrl(gpa, "https://collector.example/base/?token=x#ignored")).?;
- defer gpa.free(appended);
- try std.testing.expectEqualStrings("https://collector.example/base/v1/logs?token=x", appended);
-
- const exact = (try otlpLogsUrl(gpa, "https://collector.example/v1/logs/?token=x#ignored")).?;
- defer gpa.free(exact);
- try std.testing.expectEqualStrings("https://collector.example/v1/logs?token=x", exact);
-
- var long_host: [600]u8 = undefined;
- @memset(&long_host, 'a');
- const long_endpoint = try std.fmt.allocPrint(gpa, "https://{s}.example?token=x", .{long_host});
- defer gpa.free(long_endpoint);
- const long_url = (try otlpLogsUrl(gpa, long_endpoint)).?;
- defer gpa.free(long_url);
- try std.testing.expect(long_url.len > 512);
- try std.testing.expect(std.mem.endsWith(u8, long_url, ".example/v1/logs?token=x"));
-}
-
-test "OTLP POST sends the collector key" {
- 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 saw_key: std.atomic.Value(bool) = .init(false);
- var server_group: Io.Group = .init;
- defer server_group.cancel(io);
- try server_group.concurrent(io, answerTelemetryCollector, .{ io, &server, "collector-secret", &saw_key });
-
- 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}/v1/logs", .{server.socket.address.getPort()});
- try std.testing.expect(Telemetry.postOtlp(&client, endpoint, "{}", "collector-secret"));
- try std.testing.expect(saw_key.load(.acquire));
-}
-
-test "OTLP flush arms its deadline before network I/O" {
- 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, stallTelemetryCollector, .{ 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 telemetry: Telemetry = .{
- .io = io,
- .gpa = gpa,
- .endpoint = endpoint,
- .client = &client,
- .install_id = @splat('0'),
- .client_name = "harness",
- .sdk_install_id = "",
- .start = Io.Timestamp.now(io, .awake),
- .start_unix_ms = 0,
- };
- defer telemetry.deinit();
- const started = Io.Timestamp.now(io, .awake).nanoseconds;
- telemetry.sendBatchWithDeadline(&.{}, true, .fromMilliseconds(250));
- const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - started;
- try std.testing.expect(accepted.load(.acquire));
- try std.testing.expect(elapsed >= 100 * std.time.ns_per_ms);
- try std.testing.expect(elapsed < 3 * std.time.ns_per_s);
-}
-
-test "telemetry dupDetail never yields invalid UTF-8" {
- var t: Telemetry = .{
- .io = undefined, // dupDetail only touches gpa
- .gpa = std.testing.allocator,
- .endpoint = "x",
- .install_id = @splat('0'),
- .client_name = "harness",
- .sdk_install_id = "",
- .start = undefined,
- .start_unix_ms = 0,
- };
- // The 200-byte cap lands mid-codepoint: 199 ASCII bytes + 2-byte 'é'.
- var buf: [201]u8 = undefined;
- @memset(buf[0..199], 'a');
- buf[199] = 0xC3;
- buf[200] = 0xA9;
- const cut = t.dupDetail(&buf);
- defer std.testing.allocator.free(cut);
- try std.testing.expect(std.unicode.utf8ValidateSlice(cut));
- try std.testing.expectEqual(@as(usize, 199), cut.len); // split lead byte dropped
- // Raw invalid bytes mid-string (unparseable provider response) degrade
- // to ASCII instead of corrupting the OTLP payload.
- const garbage = t.dupDetail("ok\xff\xfe more text here");
- defer std.testing.allocator.free(garbage);
- try std.testing.expect(std.unicode.utf8ValidateSlice(garbage));
- try std.testing.expect(std.mem.startsWith(u8, garbage, "ok??"));
-}
-test "telemetry writeOtlp emits a fleet record with kind + split prov attrs" {
- var t: Telemetry = .{
- .io = undefined, // writeOtlp(.., include_summary=false) never touches io
- .gpa = std.testing.allocator,
- .endpoint = "x",
- .install_id = @splat('0'),
- .client_name = "harness",
- .sdk_install_id = "",
- .start = undefined,
- .start_unix_ms = 0,
- };
- const events = [_]Telemetry.Event{.{
- .t_ms = 0,
- .body = "fleet",
- .kind = "propose",
- .detail = "abcd1234", // prompt_sha
- .extra = "reviewer", // niche
- .run_id = "deadbeef", // parent_sha
- .prov = "frontier\ta9134381", // provider_class \t eval_set_hash
- }};
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- try t.writeOtlp(&aw.writer, &events, false);
- const out = aw.writer.buffered();
- try std.testing.expect(std.mem.indexOf(u8, out, "\"stringValue\":\"fleet\"") != null);
- try std.testing.expect(std.mem.indexOf(u8, out, "\"propose\"") != null); // kind
- try std.testing.expect(std.mem.indexOf(u8, out, "\"reviewer\"") != null); // niche
- try std.testing.expect(std.mem.indexOf(u8, out, "parent_sha") != null);
- try std.testing.expect(std.mem.indexOf(u8, out, "\"frontier\"") != null); // provider_class (split from prov)
- try std.testing.expect(std.mem.indexOf(u8, out, "\"a9134381\"") != null); // eval_set_hash (split from prov)
-}
-test "telemetry writeOtlp stamps run records with run_id (issue #168 Gap 6)" {
- var t: Telemetry = .{
- .io = undefined, // writeOtlp(.., include_summary=false) never touches io
- .gpa = std.testing.allocator,
- .endpoint = "x",
- .install_id = @splat('0'),
- .client_name = "harness",
- .sdk_install_id = "",
- .start = undefined,
- .start_unix_ms = 0,
- };
- const events = [_]Telemetry.Event{.{
- .t_ms = 0,
- .body = "run",
- .kind = "default",
- .detail = "abcd1234", // prompt_sha
- .extra = "read,edit", // tools
- .run_id = "cafef00dcafef00d",
- .ms = 42,
- .flag = true,
- }};
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- try t.writeOtlp(&aw.writer, &events, false);
- const out = aw.writer.buffered();
- try std.testing.expect(std.mem.indexOf(u8, out, "\"stringValue\":\"run\"") != null);
- try std.testing.expect(std.mem.indexOf(u8, out, "run_id") != null);
- try std.testing.expect(std.mem.indexOf(u8, out, "\"cafef00dcafef00d\"") != null);
- try std.testing.expect(std.mem.indexOf(u8, out, "\"read,edit\"") != null); // tools
-}
diff --git a/src/telemetry_net.zig b/src/telemetry_net.zig
new file mode 100644
index 00000000..db9c780a
--- /dev/null
+++ b/src/telemetry_net.zig
@@ -0,0 +1,147 @@
+//! OTLP/HTTP transport helpers for telemetry.zig: collector auth-key
+//! validation, signal-URL derivation, and the mock collectors + tests that
+//! exercise the bounded-deadline POST path. Split out of telemetry.zig
+//! (600-line goal); telemetry.zig re-exports the shared names.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const telemetry_mod = @import("telemetry.zig");
+const Telemetry = telemetry_mod.Telemetry;
+
+pub fn validatedAuthKey(value: ?[]const u8) ?[]const u8 {
+ const key = value orelse return null;
+ if (key.len == 0 or key.len > 1024) return null;
+ // Header values must not admit control/whitespace injection. Collector keys
+ // are intentionally a single visible token rather than generic OTLP header
+ // syntax, which also keeps secrets out of parsing diagnostics.
+ for (key) |byte| if (byte < 0x21 or byte > 0x7e) return null;
+ return key;
+}
+
+pub fn otlpLogsUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {
+ // Append the signal path to the URL path rather than to a query value. URL
+ // fragments are client-side only and must not be sent to the collector.
+ const fragment_at = std.mem.indexOfScalar(u8, endpoint, '#') orelse endpoint.len;
+ const without_fragment = endpoint[0..fragment_at];
+ const query_at = std.mem.indexOfScalar(u8, without_fragment, '?') orelse without_fragment.len;
+ const query = without_fragment[query_at..];
+ const base = std.mem.trimEnd(u8, without_fragment[0..query_at], "/");
+ if (base.len == 0) return null;
+ if (std.mem.endsWith(u8, base, "/v1/logs")) return try std.fmt.allocPrint(gpa, "{s}{s}", .{ base, query });
+ return try std.fmt.allocPrint(gpa, "{s}/v1/logs{s}", .{ base, query });
+}
+
+fn stallTelemetryCollector(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);
+ io.sleep(.fromSeconds(5), .awake) catch {};
+}
+
+fn answerTelemetryCollector(
+ io: Io,
+ server: *Io.net.Server,
+ expected_key: []const u8,
+ saw_key: *std.atomic.Value(bool),
+) void {
+ const stream = server.accept(io) catch return;
+ defer stream.close(io);
+ var read_buf: [16 * 1024]u8 = undefined;
+ var reader = Io.net.Stream.Reader.init(stream, io, &read_buf);
+ while (reader.interface.takeDelimiter('\n') catch null) |line| {
+ if (std.mem.eql(u8, line, "\r") or line.len == 0) break;
+ const prefix = "x-harness-key:";
+ if (!std.ascii.startsWithIgnoreCase(line, prefix)) continue;
+ const value = std.mem.trim(u8, line[prefix.len..], " \t\r\n");
+ saw_key.store(std.mem.eql(u8, value, expected_key), .release);
+ }
+ const response = "HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
+ var write_buf: [256]u8 = undefined;
+ var writer = Io.net.Stream.Writer.init(stream, io, &write_buf);
+ writer.interface.writeAll(response) catch return;
+ writer.interface.flush() catch {};
+}
+
+test "telemetry collector key accepts one bounded visible token" {
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey(null));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey(""));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("secret key"));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("secret\r\ninjected"));
+ try std.testing.expectEqual(@as(?[]const u8, null), validatedAuthKey("nön-ascii"));
+ try std.testing.expectEqualStrings("safe-token_123", validatedAuthKey("safe-token_123").?);
+}
+
+test "OTLP URL derivation preserves queries and drops fragments" {
+ const gpa = std.testing.allocator;
+ const appended = (try otlpLogsUrl(gpa, "https://collector.example/base/?token=x#ignored")).?;
+ defer gpa.free(appended);
+ try std.testing.expectEqualStrings("https://collector.example/base/v1/logs?token=x", appended);
+
+ const exact = (try otlpLogsUrl(gpa, "https://collector.example/v1/logs/?token=x#ignored")).?;
+ defer gpa.free(exact);
+ try std.testing.expectEqualStrings("https://collector.example/v1/logs?token=x", exact);
+
+ var long_host: [600]u8 = undefined;
+ @memset(&long_host, 'a');
+ const long_endpoint = try std.fmt.allocPrint(gpa, "https://{s}.example?token=x", .{long_host});
+ defer gpa.free(long_endpoint);
+ const long_url = (try otlpLogsUrl(gpa, long_endpoint)).?;
+ defer gpa.free(long_url);
+ try std.testing.expect(long_url.len > 512);
+ try std.testing.expect(std.mem.endsWith(u8, long_url, ".example/v1/logs?token=x"));
+}
+
+test "OTLP POST sends the collector key" {
+ 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 saw_key: std.atomic.Value(bool) = .init(false);
+ var server_group: Io.Group = .init;
+ defer server_group.cancel(io);
+ try server_group.concurrent(io, answerTelemetryCollector, .{ io, &server, "collector-secret", &saw_key });
+
+ 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}/v1/logs", .{server.socket.address.getPort()});
+ try std.testing.expect(Telemetry.postOtlp(&client, endpoint, "{}", "collector-secret"));
+ try std.testing.expect(saw_key.load(.acquire));
+}
+
+test "OTLP flush arms its deadline before network I/O" {
+ 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, stallTelemetryCollector, .{ 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 telemetry: Telemetry = .{
+ .io = io,
+ .gpa = gpa,
+ .endpoint = endpoint,
+ .client = &client,
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = Io.Timestamp.now(io, .awake),
+ .start_unix_ms = 0,
+ };
+ defer telemetry.deinit();
+ const started = Io.Timestamp.now(io, .awake).nanoseconds;
+ telemetry.sendBatchWithDeadline(&.{}, true, .fromMilliseconds(250));
+ const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - started;
+ try std.testing.expect(accepted.load(.acquire));
+ try std.testing.expect(elapsed >= 100 * std.time.ns_per_ms);
+ try std.testing.expect(elapsed < 3 * std.time.ns_per_s);
+}
diff --git a/src/telemetry_tests.zig b/src/telemetry_tests.zig
new file mode 100644
index 00000000..71a1397f
--- /dev/null
+++ b/src/telemetry_tests.zig
@@ -0,0 +1,98 @@
+//! Payload-format tests for telemetry.zig (dupDetail UTF-8 safety, OTLP
+//! record emission). Split out of telemetry.zig (600-line goal); reached
+//! through the `test { _ = ... }` hook there, mirroring the mcp.zig pattern.
+
+const std = @import("std");
+const Io = std.Io;
+const telemetry = @import("telemetry.zig");
+const Telemetry = telemetry.Telemetry;
+const Event = Telemetry.Event;
+
+test "telemetry dupDetail never yields invalid UTF-8" {
+ var t: Telemetry = .{
+ .io = undefined, // dupDetail only touches gpa
+ .gpa = std.testing.allocator,
+ .endpoint = "x",
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = undefined,
+ .start_unix_ms = 0,
+ };
+ // The 200-byte cap lands mid-codepoint: 199 ASCII bytes + 2-byte 'é'.
+ var buf: [201]u8 = undefined;
+ @memset(buf[0..199], 'a');
+ buf[199] = 0xC3;
+ buf[200] = 0xA9;
+ const cut = t.dupDetail(&buf);
+ defer std.testing.allocator.free(cut);
+ try std.testing.expect(std.unicode.utf8ValidateSlice(cut));
+ try std.testing.expectEqual(@as(usize, 199), cut.len); // split lead byte dropped
+ // Raw invalid bytes mid-string (unparseable provider response) degrade
+ // to ASCII instead of corrupting the OTLP payload.
+ const garbage = t.dupDetail("ok\xff\xfe more text here");
+ defer std.testing.allocator.free(garbage);
+ try std.testing.expect(std.unicode.utf8ValidateSlice(garbage));
+ try std.testing.expect(std.mem.startsWith(u8, garbage, "ok??"));
+}
+test "telemetry writeOtlp emits a fleet record with kind + split prov attrs" {
+ var t: Telemetry = .{
+ .io = undefined, // writeOtlp(.., include_summary=false) never touches io
+ .gpa = std.testing.allocator,
+ .endpoint = "x",
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = undefined,
+ .start_unix_ms = 0,
+ };
+ const events = [_]Telemetry.Event{.{
+ .t_ms = 0,
+ .body = "fleet",
+ .kind = "propose",
+ .detail = "abcd1234", // prompt_sha
+ .extra = "reviewer", // niche
+ .run_id = "deadbeef", // parent_sha
+ .prov = "frontier\ta9134381", // provider_class \t eval_set_hash
+ }};
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ try t.writeOtlp(&aw.writer, &events, false);
+ const out = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"stringValue\":\"fleet\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"propose\"") != null); // kind
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"reviewer\"") != null); // niche
+ try std.testing.expect(std.mem.indexOf(u8, out, "parent_sha") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"frontier\"") != null); // provider_class (split from prov)
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"a9134381\"") != null); // eval_set_hash (split from prov)
+}
+test "telemetry writeOtlp stamps run records with run_id (issue #168 Gap 6)" {
+ var t: Telemetry = .{
+ .io = undefined, // writeOtlp(.., include_summary=false) never touches io
+ .gpa = std.testing.allocator,
+ .endpoint = "x",
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = undefined,
+ .start_unix_ms = 0,
+ };
+ const events = [_]Telemetry.Event{.{
+ .t_ms = 0,
+ .body = "run",
+ .kind = "default",
+ .detail = "abcd1234", // prompt_sha
+ .extra = "read,edit", // tools
+ .run_id = "cafef00dcafef00d",
+ .ms = 42,
+ .flag = true,
+ }};
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ try t.writeOtlp(&aw.writer, &events, false);
+ const out = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"stringValue\":\"run\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "run_id") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"cafef00dcafef00d\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"read,edit\"") != null); // tools
+}
diff --git a/src/trace.zig b/src/trace.zig
index 17a1dc22..65084c75 100644
--- a/src/trace.zig
+++ b/src/trace.zig
@@ -183,329 +183,16 @@ pub const Tracer = struct {
};
// ── Behavioral trace (one experimental event file per run) ────────────────
+// Implementation lives in behavior_trace.zig (600-line goal); re-exported so
+// existing trace.X call sites are unchanged.
-pub const behavior_dir = ".graff/trajectories";
-pub const behavior_schema = "codegraff.behavior.v1";
-
-/// Task-agnostic behavioral records. Per-kind fields stay flat, matching the
-/// schema-harness event shape; state/action/expect values remain opaque JSON.
-pub const BehaviorKind = enum {
- run_started,
- turn_started,
- text_delta,
- tool_started,
- tool_finished,
- turn_committed,
- action_taken,
- model_mispredicted,
- run_finished,
-};
-
-/// Typed lifecycle status; `.failed` is serialized as the JSON value `error`.
-pub const BehaviorRunStatus = enum {
- closed,
- failed,
-};
-
-const max_local_behavior_event_bytes = 64 * 1024;
-
-/// Serialize a behavioral event as one flat JSON object. `fields` must be a
-/// struct; its fields are appended after the common envelope. Building the
-/// full line before writing prevents serialization failures from corrupting the
-/// file. The fixed 64 KiB line buffer also prevents an opaque adapter value from
-/// causing unbounded temporary allocation. A write failure disables the stream
-/// so a partial tail is never joined to a later event.
-fn writeBehaviorLine(gpa: Allocator, w: *Io.Writer, kind: BehaviorKind, seq: u64, ts: f64, run_id: []const u8, fields: anytype) bool {
- const backing = gpa.alloc(u8, max_local_behavior_event_bytes + 1) catch return false;
- defer gpa.free(backing);
- var line: Io.Writer = .fixed(backing);
- var s: std.json.Stringify = .{ .writer = &line };
- s.beginObject() catch return false;
- s.objectField("kind") catch return false;
- s.write(@tagName(kind)) catch return false;
- s.objectField("seq") catch return false;
- s.write(seq) catch return false;
- s.objectField("ts") catch return false;
- s.write(ts) catch return false;
- s.objectField("run_id") catch return false;
- s.write(run_id) catch return false;
- s.objectField("schema") catch return false;
- s.write(behavior_schema) catch return false;
- inline for (comptime std.meta.fieldNames(@TypeOf(fields))) |name| {
- comptime {
- if (std.mem.eql(u8, name, "kind") or
- std.mem.eql(u8, name, "seq") or
- std.mem.eql(u8, name, "ts") or
- std.mem.eql(u8, name, "run_id") or
- std.mem.eql(u8, name, "schema"))
- {
- @compileError("behavioral event field collides with the common envelope: " ++ name);
- }
- }
- s.objectField(name) catch return false;
- s.write(@field(fields, name)) catch return false;
- }
- s.endObject() catch return false;
- if (line.buffered().len > max_local_behavior_event_bytes) return false;
- line.writeByte('\n') catch return false;
- w.writeAll(line.buffered()) catch return false;
- w.flush() catch return false;
- return true;
-}
-
-/// Per-run behavioral event stream written to
-/// `.graff/trajectories/<run_id>.jsonl`. `seq` is contiguous file order for
-/// this run and starts at one. `ts` is Unix time in fractional seconds. Every
-/// event carries `run_id` and `schema`, so it remains attributable even if run
-/// files are later merged. Payload fields are plaintext and are not sanitized;
-/// callers must explicitly avoid secrets and proprietary content.
-fn commitmentRef(key: *const [32]u8, commitment_id: []const u8) [16]u8 {
- // The random key never leaves this process, so low-entropy adapter IDs
- // cannot be recovered from uploaded references with an offline dictionary.
- var hash = std.crypto.hash.sha2.Sha256.init(.{});
- hash.update(key);
- hash.update(&.{0});
- hash.update(commitment_id);
- var digest: [32]u8 = undefined;
- hash.final(&digest);
- return std.fmt.bytesToHex(digest[0..8].*, .lower);
-}
-
-pub const BehaviorRunMetadata = struct {
- provider: []const u8 = "",
- model: []const u8 = "",
- prompt_sha: []const u8 = "",
- effort: []const u8 = "",
-};
-
-pub const BehaviorTrace = struct {
- mutex: Io.Mutex = .init,
- io: Io,
- gpa: Allocator,
- out: ?*Io.Writer,
- upload: ?*behavior_upload.Upload = null,
- run_id: []const u8,
- seq: u64 = 0,
- current_turn: u64 = 0,
- turn_active: bool = false,
- started: bool = false,
- closed: bool = false,
- commitment_key: [32]u8 = undefined,
- commitment_key_initialized: bool = false,
-
- fn timestamp(self: *BehaviorTrace) f64 {
- const now = Io.Timestamp.now(self.io, .real);
- return @as(f64, @floatFromInt(now.nanoseconds)) / 1_000_000_000.0;
- }
-
- /// Emit to the independent local and upload sinks. The return value says
- /// whether the upload retained this event; callers otherwise do not couple
- /// sink health. In particular, finish() uses it so `complete=true` cannot
- /// describe a batch whose terminal event was dropped during admission.
- fn eventLocked(self: *BehaviorTrace, kind: BehaviorKind, local_fields: anytype, metadata_fields: anytype, content_fields: anytype) bool {
- if (self.closed or self.seq == std.math.maxInt(u64)) return false;
- const uploader_active = if (self.upload) |uploader| uploader.active() else false;
- if (self.out == null and !uploader_active) return false;
-
- // This is the logical source sequence, reserved before either
- // independent sink is attempted. A bounded upload may therefore have
- // gaps, reported by dropped_events, while the local file remains a
- // contiguous prefix until any terminal write failure.
- const next = self.seq + 1;
- self.seq = next;
- const ts = self.timestamp();
- if (self.out) |w| {
- if (!writeBehaviorLine(self.gpa, w, kind, next, ts, self.run_id, local_fields)) {
- // Do not append after a possible partial write. Upload remains
- // independent so a local disk failure need not erase metadata.
- self.out = null;
- }
- }
- if (self.upload) |uploader| {
- return uploader.appendEvent(@tagName(kind), next, ts, metadata_fields, content_fields);
- }
- return false;
- }
-
- /// Start this run exactly once. The generic serializer stays private so
- /// callers cannot accidentally emit a kind without its required fields.
- pub fn start(self: *BehaviorTrace, version: []const u8, unix_ms: i64) void {
- self.startWithMetadata(version, unix_ms, .{});
- }
-
- pub fn startWithMetadata(self: *BehaviorTrace, version: []const u8, unix_ms: i64, metadata: BehaviorRunMetadata) void {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (self.started or self.closed) return;
- self.io.randomSecure(&self.commitment_key) catch self.io.random(&self.commitment_key);
- self.commitment_key_initialized = true;
- self.started = true;
- const local_fields = .{
- .version = version,
- .unix_ms = unix_ms,
- .provider = metadata.provider,
- .model = metadata.model,
- .prompt_sha = metadata.prompt_sha,
- .effort = metadata.effort,
- };
- // A deterministic prompt fingerprint is useful in the local trace but
- // remains prompt-derived data: even a truncated digest can disclose a
- // low-entropy prompt through enumeration. Never include it in either
- // network projection.
- const upload_fields = .{
- .version = version,
- .unix_ms = unix_ms,
- .provider = metadata.provider,
- .model = metadata.model,
- .effort = metadata.effort,
- };
- _ = self.eventLocked(.run_started, local_fields, upload_fields, upload_fields);
- }
-
- /// Begin one root turn. Behavioral turn IDs are dense and independent of
- /// legacy trajectory node IDs, which can skip as child agents are added.
- pub fn beginTurn(self: *BehaviorTrace, trajectory_node: u64) u64 {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (!self.started or self.closed or self.current_turn == std.math.maxInt(u64)) return 0;
- const parent_turn = self.current_turn;
- const turn = parent_turn + 1;
- self.current_turn = turn;
- self.turn_active = true;
- const fields = .{
- .turn = turn,
- .parent_turn = parent_turn,
- .trajectory_node = trajectory_node,
- };
- _ = self.eventLocked(.turn_started, fields, fields, fields);
- return turn;
- }
-
- /// Clear attribution only for the matching active turn. The last turn ID is
- /// retained separately in current_turn so the next turn keeps a dense parent
- /// chain, while late administrative API/tool work is attributed to turn 0.
- pub fn endTurn(self: *BehaviorTrace, turn: u64) void {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (turn != 0 and self.turn_active and turn == self.current_turn) self.turn_active = false;
- }
-
- pub fn currentTurn(self: *BehaviorTrace) u64 {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- return if (self.turn_active) self.current_turn else 0;
- }
-
- /// Assert that a task adapter observed a committed action and expectation.
- /// This records the caller's belief; it does not execute or verify the action.
- pub fn recordExpectedAction(self: *BehaviorTrace, turn: u64, commitment_id: []const u8, action: anytype, expected: anytype, reason: []const u8) void {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (!self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or commitment_id.len == 0) return;
- const local_fields = .{
- .turn = turn,
- .commitment_id = commitment_id,
- .action = action,
- .expect = expected,
- .reason = reason,
- };
- std.debug.assert(self.commitment_key_initialized);
- const commitment_ref = commitmentRef(&self.commitment_key, commitment_id);
- _ = self.eventLocked(.turn_committed, local_fields, .{
- .turn = turn,
- .commitment_ref = &commitment_ref,
- }, local_fields);
- }
-
- /// Assert that a caller or task-specific verifier found a contradiction.
- /// No generic semantic comparison is attempted by this backend.
- pub fn recordMisprediction(self: *BehaviorTrace, turn: u64, commitment_id: []const u8, predicted: anytype, actual: anytype, detail: []const u8) void {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (!self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or commitment_id.len == 0) return;
- const local_fields = .{
- .turn = turn,
- .commitment_id = commitment_id,
- .predicted = predicted,
- .actual = actual,
- .detail = detail,
- };
- std.debug.assert(self.commitment_key_initialized);
- const commitment_ref = commitmentRef(&self.commitment_key, commitment_id);
- _ = self.eventLocked(.model_mispredicted, local_fields, .{
- .turn = turn,
- .commitment_ref = &commitment_ref,
- }, local_fields);
- }
-
- /// Attach content-free operational aggregates to the active root turn.
- /// These are not behavioral tool events: no invocation identity, argument,
- /// result, or action semantics are inferred from the operational hook.
- pub fn recordApiMetric(
- self: *BehaviorTrace,
- from_subagent: bool,
- ms: i64,
- req_bytes: usize,
- resp_bytes: usize,
- context_tokens: u64,
- cache_read_tokens: u64,
- is_error: bool,
- ) u64 {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (!self.started or self.closed or !self.turn_active) return 0;
- const turn = self.current_turn;
- if (self.upload) |uploader| uploader.recordApi(turn, from_subagent, ms, req_bytes, resp_bytes, context_tokens, cache_read_tokens, is_error);
- return turn;
- }
-
- pub fn recordToolMetric(self: *BehaviorTrace, name: []const u8, from_subagent: bool, ms: i64, result_bytes: usize, is_error: bool) u64 {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (!self.started or self.closed or !self.turn_active) return 0;
- const turn = self.current_turn;
- if (self.upload) |uploader| uploader.recordTool(turn, name, from_subagent, ms, result_bytes, is_error);
- return turn;
- }
-
- const FinishState = struct {
- uploader: ?*behavior_upload.Upload,
- complete: bool,
- };
-
- fn prepareFinish(self: *BehaviorTrace, status_name: []const u8) ?FinishState {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- if (self.closed) return null;
-
- var terminal_retained = false;
- if (self.started) {
- const fields = .{ .status = status_name };
- terminal_retained = self.eventLocked(.run_finished, fields, fields, fields);
- }
- self.turn_active = false;
- self.closed = true;
- return .{
- .uploader = self.upload,
- // This flag describes the uploaded lifecycle, not merely process
- // control flow. A dropped terminal event must remain incomplete.
- .complete = self.started and (self.upload == null or terminal_retained),
- };
- }
-
- /// Mark a normal process/session close. This is deliberately not a task
- /// success verdict. A missing run_finished record means the run is incomplete.
- pub fn finish(self: *BehaviorTrace, status: BehaviorRunStatus) void {
- const status_name: []const u8 = switch (status) {
- .closed => "closed",
- .failed => "error",
- };
- const state = self.prepareFinish(status_name) orelse return;
- // Network I/O is terminal and bounded, but it must not hold the mutex
- // used by concurrent API/tool callbacks.
- if (state.uploader) |uploader| uploader.send(state.complete, status_name);
- }
-};
+const behavior_trace = @import("behavior_trace.zig");
+pub const behavior_dir = behavior_trace.behavior_dir;
+pub const behavior_schema = behavior_trace.behavior_schema;
+pub const BehaviorKind = behavior_trace.BehaviorKind;
+pub const BehaviorRunStatus = behavior_trace.BehaviorRunStatus;
+pub const BehaviorRunMetadata = behavior_trace.BehaviorRunMetadata;
+pub const BehaviorTrace = behavior_trace.BehaviorTrace;
// ── Trajectory (DGM-style archive tree) ────────────────────────────────────
@@ -703,11 +390,6 @@ pub const ToolSink = struct {
}
};
-fn expectObjectKeys(object: std.json.ObjectMap, expected: []const []const u8) !void {
- try std.testing.expectEqual(expected.len, object.count());
- for (expected) |key| try std.testing.expect(object.get(key) != null);
-}
-
test "writeJsonLine: one complete newline-terminated JSON record per call" {
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
@@ -751,483 +433,3 @@ test "run-scoped paths separate traces and trajectories" {
try std.testing.expectEqualStrings(".graff/traces/abc123.jsonl", trace_path);
try std.testing.expectEqualStrings(".graff/trajectories/abc123.jsonl", trajectory_path);
}
-
-test "writeBehaviorLine: oversized adapter content is rejected before local allocation can grow" {
- const gpa = std.testing.allocator;
- var out: Io.Writer.Allocating = .init(gpa);
- defer out.deinit();
- const oversized = try gpa.alloc(u8, max_local_behavior_event_bytes + 1);
- defer gpa.free(oversized);
- @memset(oversized, 'x');
- try std.testing.expect(!writeBehaviorLine(gpa, &out.writer, .turn_committed, 1, 1.0, "0123456789abcdef", .{
- .turn = @as(u64, 1),
- .reason = oversized,
- }));
- try std.testing.expectEqual(@as(usize, 0), out.writer.buffered().len);
-}
-
-test "BehaviorTrace: events are flat, attributable, and ordered" {
- 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 = "run-test-1",
- };
-
- behavior.start("test", 1_234);
- behavior.start("ignored-duplicate", 9_999);
- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(7));
- behavior.recordExpectedAction(
- 1,
- "commit-1",
- .{ .tool = "edit_file", .note = "line one\nline two ☃" },
- .{ .build = "passes", .attempts = @as(u64, 1) },
- "verify the edit compiles",
- );
- behavior.recordMisprediction(
- 1,
- "commit-1",
- .{ .build = "passes" },
- .{ .build = "fails", .exit_code = @as(i64, 1) },
- "reported by a task-specific verifier",
- );
- behavior.finish(.closed);
- // Typed lifecycle methods cannot append after closure.
- behavior.recordExpectedAction(1, "late", .{ .tool = "bash" }, .{ .ok = true }, "too late");
-
- const out = aw.writer.buffered();
- try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, out, "\n"));
- var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, out, "\n"), '\n');
-
- var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
- defer started.deinit();
- try std.testing.expectEqualStrings("run_started", started.value.object.get("kind").?.string);
- try std.testing.expectEqual(@as(i64, 1), started.value.object.get("seq").?.integer);
- try std.testing.expect(started.value.object.get("ts").? == .float);
- try std.testing.expectEqualStrings("run-test-1", started.value.object.get("run_id").?.string);
- try std.testing.expectEqualStrings(behavior_schema, started.value.object.get("schema").?.string);
- try std.testing.expectEqualStrings("test", started.value.object.get("version").?.string);
- try std.testing.expectEqual(@as(i64, 1_234), started.value.object.get("unix_ms").?.integer);
- try std.testing.expect(started.value.object.get("payload") == null);
-
- var turn = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
- defer turn.deinit();
- try std.testing.expectEqualStrings("turn_started", turn.value.object.get("kind").?.string);
- try std.testing.expectEqual(@as(i64, 2), turn.value.object.get("seq").?.integer);
- try std.testing.expectEqual(@as(i64, 1), turn.value.object.get("turn").?.integer);
- try std.testing.expectEqual(@as(i64, 0), turn.value.object.get("parent_turn").?.integer);
- try std.testing.expectEqual(@as(i64, 7), turn.value.object.get("trajectory_node").?.integer);
- try std.testing.expectEqualStrings("run-test-1", turn.value.object.get("run_id").?.string);
-
- var committed = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
- defer committed.deinit();
- try std.testing.expectEqualStrings("turn_committed", committed.value.object.get("kind").?.string);
- try std.testing.expectEqual(@as(i64, 3), committed.value.object.get("seq").?.integer);
- try std.testing.expectEqual(@as(i64, 1), committed.value.object.get("turn").?.integer);
- try std.testing.expectEqualStrings("commit-1", committed.value.object.get("commitment_id").?.string);
- try std.testing.expectEqualStrings("line one\nline two ☃", committed.value.object.get("action").?.object.get("note").?.string);
- try std.testing.expectEqualStrings("passes", committed.value.object.get("expect").?.object.get("build").?.string);
- try std.testing.expectEqualStrings("verify the edit compiles", committed.value.object.get("reason").?.string);
-
- var mismatch = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
- defer mismatch.deinit();
- try std.testing.expectEqualStrings("model_mispredicted", mismatch.value.object.get("kind").?.string);
- try std.testing.expectEqual(@as(i64, 4), mismatch.value.object.get("seq").?.integer);
- try std.testing.expectEqualStrings("commit-1", mismatch.value.object.get("commitment_id").?.string);
- try std.testing.expectEqualStrings("fails", mismatch.value.object.get("actual").?.object.get("build").?.string);
- try std.testing.expectEqualStrings("reported by a task-specific verifier", mismatch.value.object.get("detail").?.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);
- try std.testing.expectEqual(@as(i64, 5), finished.value.object.get("seq").?.integer);
- try std.testing.expectEqualStrings("closed", finished.value.object.get("status").?.string);
- try std.testing.expectEqualStrings("run-test-1", finished.value.object.get("run_id").?.string);
- try std.testing.expect(lines.next() == null);
-}
-
-test "BehaviorTrace: disabled writes do not consume sequence numbers" {
- const io = std.testing.io;
- var behavior: BehaviorTrace = .{
- .io = io,
- .gpa = std.testing.allocator,
- .out = null,
- .run_id = "disabled-run",
- };
-
- behavior.start("test", 0);
- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));
- try std.testing.expectEqual(@as(u64, 0), behavior.seq);
- try std.testing.expectEqual(@as(u64, 1), behavior.currentTurn());
-}
-
-test "BehaviorTrace: typed APIs reject out-of-lifecycle adapter events" {
- 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 = "lifecycle-run",
- };
-
- try std.testing.expectEqual(@as(u64, 0), behavior.beginTurn(9));
- behavior.recordExpectedAction(1, "early", .{ .kind = "edit" }, .{ .ok = true }, "before start");
- behavior.start("test", 1);
- behavior.recordExpectedAction(1, "early", .{ .kind = "edit" }, .{ .ok = true }, "before turn");
- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(9));
- behavior.recordExpectedAction(0, "zero-turn", .{ .kind = "edit" }, .{ .ok = true }, "invalid turn");
- behavior.recordExpectedAction(2, "future-turn", .{ .kind = "edit" }, .{ .ok = true }, "invalid turn");
- behavior.recordExpectedAction(1, "", .{ .kind = "edit" }, .{ .ok = true }, "empty commitment");
- behavior.recordMisprediction(1, "", .{ .ok = true }, .{ .ok = false }, "empty commitment");
-
- try std.testing.expectEqual(@as(u64, 2), behavior.seq);
- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, aw.writer.buffered(), "\n"));
- behavior.finish(.failed);
- behavior.finish(.closed); // the first terminal status wins
- try std.testing.expectEqual(@as(u64, 3), behavior.seq);
- var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
- _ = lines.next();
- _ = lines.next();
- var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
- defer finished.deinit();
- try std.testing.expectEqualStrings("error", finished.value.object.get("status").?.string);
-}
-
-test "BehaviorTrace: a full upload queue cannot claim a complete terminal lifecycle" {
- const gpa = std.testing.allocator;
- const io = std.testing.io;
- var upload: behavior_upload.Upload = .{
- .io = io,
- .gpa = gpa,
- .client = null,
- .endpoint = "https://collector.example/v1/logs",
- .install_id = @splat('q'),
- .client_name = "harness",
- .service_version = "test",
- .run_id = "0123456789abcdef",
- .mode = .metadata,
- };
- defer upload.deinit();
- var behavior: BehaviorTrace = .{
- .io = io,
- .gpa = gpa,
- .out = null,
- .upload = &upload,
- .run_id = "0123456789abcdef",
- };
-
- behavior.start("test", 1);
- try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
- const placeholder = upload.events.items[0][0..0];
- try upload.events.resize(gpa, behavior_upload.max_events);
- for (upload.events.items[1..]) |*event| event.* = placeholder;
-
- const state = behavior.prepareFinish("closed").?;
- try std.testing.expect(!state.complete);
- try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);
- try std.testing.expectEqual(@as(usize, behavior_upload.max_events), upload.events.items.len);
-
- // Remove synthetic queue entries before normal deinit and payload parsing.
- upload.events.shrinkRetainingCapacity(1);
- const payload = try upload.buildPayload(state.complete, "closed");
- defer gpa.free(payload);
- var parsed = try std.json.parseFromSlice(Value, gpa, payload, .{});
- defer parsed.deinit();
- try std.testing.expect(!parsed.value.object.get("complete").?.bool);
- try std.testing.expectEqual(@as(usize, 1), parsed.value.object.get("events").?.array.items.len);
-}
-
-test "BehaviorTrace: terminal allocation failure leaves upload incomplete" {
- const backing_gpa = std.testing.allocator;
- const io = std.testing.io;
- // run_started uses one allocation for its event and one for ArrayList
- // storage. Fail the next allocation, which is run_finished serialization.
- var failing = std.testing.FailingAllocator.init(backing_gpa, .{ .fail_index = 2 });
- const failing_gpa = failing.allocator();
- var upload: behavior_upload.Upload = .{
- .io = io,
- .gpa = failing_gpa,
- .client = null,
- .endpoint = "https://collector.example/v1/logs",
- .install_id = @splat('a'),
- .client_name = "harness",
- .service_version = "test",
- .run_id = "0123456789abcdef",
- .mode = .metadata,
- };
- defer upload.deinit();
- var behavior: BehaviorTrace = .{
- .io = io,
- .gpa = backing_gpa,
- .out = null,
- .upload = &upload,
- .run_id = "0123456789abcdef",
- };
-
- behavior.start("test", 1);
- try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
- const state = behavior.prepareFinish("error").?;
- try std.testing.expect(failing.has_induced_failure);
- try std.testing.expect(!state.complete);
- try std.testing.expectEqual(@as(u64, 1), upload.dropped_events);
- try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
-
- failing.fail_index = std.math.maxInt(usize);
- const payload = try upload.buildPayload(state.complete, "error");
- defer failing_gpa.free(payload);
- var parsed = try std.json.parseFromSlice(Value, backing_gpa, payload, .{});
- defer parsed.deinit();
- try std.testing.expect(!parsed.value.object.get("complete").?.bool);
-}
-
-test "BehaviorTrace: metadata-default upload is an exact content-free projection" {
- const gpa = std.testing.allocator;
- const io = std.testing.io;
- var local: Io.Writer.Allocating = .init(gpa);
- defer local.deinit();
- var upload: behavior_upload.Upload = .{
- .io = io,
- .gpa = gpa,
- .client = null,
- .endpoint = "https://collector.example/v1/logs",
- .install_id = @splat('c'),
- .client_name = "test",
- .service_version = "test",
- .run_id = "0123456789abcdef",
- .mode = behavior_upload.resolveMode(null, true),
- };
- defer upload.deinit();
- var behavior: BehaviorTrace = .{
- .io = io,
- .gpa = gpa,
- .out = &local.writer,
- .upload = &upload,
- .run_id = "0123456789abcdef",
- };
- behavior.startWithMetadata("test", 1_234, .{
- .provider = "anthropic",
- .model = "test-model",
- .prompt_sha = "0011223344556677",
- .effort = "high",
- });
- try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(7));
- behavior.recordExpectedAction(
- 1,
- "COMMITMENT_SECRET",
- .{ .source = "SOURCE_SECRET", .tool_args = "TOOL_ARGUMENT_SECRET" },
- .{ .tool_result = "TOOL_RESULT_SECRET" },
- "REASON_SECRET",
- );
- behavior.recordMisprediction(
- 1,
- "COMMITMENT_SECRET",
- .{ .model_output = "MODEL_OUTPUT_SECRET" },
- .{ .workspace_path = "PRIVATE_PATH_SECRET" },
- "DETAIL_SECRET",
- );
- var tracer: Tracer = .{
- .io = io,
- .gpa = gpa,
- .out = null,
- .start = Io.Timestamp.now(io, .awake),
- .behavior = &behavior,
- };
- tracer.api("repl", false, "test-model", 20, 100, 200, 300, 250, false);
- tracer.tool("mcp__private_server__lookup_customer", 7, true, 80, true);
- behavior.finish(.closed);
- behavior.finish(.failed);
- // Late callbacks may race terminal teardown. They must observe closure and
- // leave the uploader untouched after send can begin.
- try std.testing.expectEqual(@as(u64, 0), behavior.recordApiMetric(false, 99, 999, 999, 999, 999, true));
- try std.testing.expectEqual(@as(u64, 0), behavior.recordToolMetric("bash", false, 99, 999, true));
-
- const secrets = [_][]const u8{
- "COMMITMENT_SECRET",
- "SOURCE_SECRET",
- "TOOL_ARGUMENT_SECRET",
- "TOOL_RESULT_SECRET",
- "REASON_SECRET",
- "MODEL_OUTPUT_SECRET",
- "PRIVATE_PATH_SECRET",
- "DETAIL_SECRET",
- "0011223344556677",
- "private_server",
- "lookup_customer",
- };
- const local_jsonl = local.writer.buffered();
- for (secrets[0..9]) |secret| try std.testing.expect(std.mem.indexOf(u8, local_jsonl, secret) != null);
-
- const payload = try upload.buildPayload(true, "closed");
- defer gpa.free(payload);
- for (&secrets) |secret| try std.testing.expect(std.mem.indexOf(u8, payload, secret) == null);
- var parsed = try std.json.parseFromSlice(Value, gpa, payload, .{});
- defer parsed.deinit();
- const batch = parsed.value.object;
- try expectObjectKeys(batch, &.{
- "schema",
- "event_schema",
- "privacy",
- "run_id",
- "install_id",
- "client_name",
- "service_version",
- "complete",
- "terminal_status",
- "dropped_events",
- "dropped_metrics",
- "events",
- "turn_metrics",
- });
- 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);
- try expectObjectKeys(events[0].object, &.{ "kind", "seq", "ts", "run_id", "schema", "version", "unix_ms", "provider", "model", "effort" });
- 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" });
- try expectObjectKeys(events[4].object, &.{ "kind", "seq", "ts", "run_id", "schema", "status" });
- try std.testing.expectEqualStrings(events[2].object.get("commitment_ref").?.string, events[3].object.get("commitment_ref").?.string);
-
- const metrics = batch.get("turn_metrics").?.array.items;
- try std.testing.expectEqual(@as(usize, 1), metrics.len);
- try std.testing.expectEqual(@as(i64, 0), metrics[0].object.get("api_subagent_calls").?.integer);
- try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_subagent_calls").?.integer);
- try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_mcp").?.integer);
- try std.testing.expectEqual(@as(i64, 1), metrics[0].object.get("tool_errors").?.integer);
-}
-
-test "BehaviorTrace: prompt fingerprint stays local in content mode" {
- const gpa = std.testing.allocator;
- const io = std.testing.io;
- var local: Io.Writer.Allocating = .init(gpa);
- defer local.deinit();
- var upload: behavior_upload.Upload = .{
- .io = io,
- .gpa = gpa,
- .client = null,
- .endpoint = "https://collector.example/v1/logs",
- .install_id = @splat('c'),
- .client_name = "harness",
- .service_version = "test",
- .run_id = "0123456789abcdef",
- .mode = .content,
- };
- defer upload.deinit();
- var behavior: BehaviorTrace = .{
- .io = io,
- .gpa = gpa,
- .out = &local.writer,
- .upload = &upload,
- .run_id = "0123456789abcdef",
- };
- behavior.startWithMetadata("test", 1, .{ .prompt_sha = "0011223344556677" });
- try std.testing.expect(std.mem.indexOf(u8, local.writer.buffered(), "0011223344556677") != null);
- try std.testing.expectEqual(@as(usize, 1), upload.events.items.len);
- try std.testing.expect(std.mem.indexOf(u8, upload.events.items[0], "0011223344556677") == null);
- try std.testing.expect(std.mem.indexOf(u8, upload.events.items[0], "prompt_sha") == null);
-}
-
-test "beginRootTurn: correlates without allocating a legacy node" {
- 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 = "root-turn-run",
- };
- var trajectory: Trajectory = .{
- .io = io,
- .gpa = gpa,
- .out = null,
- .start = Io.Timestamp.now(io, .awake),
- };
- defer trajectory.deinit();
-
- behavior.start("test", 1);
- const trajectory_node = trajectory.nextId();
- trajectory.setTurn(trajectory_node);
- const legacy_next_id = trajectory.next_id;
- var tracer: Tracer = .{
- .io = io,
- .gpa = gpa,
- .out = null,
- .start = Io.Timestamp.now(io, .awake),
- .behavior = &behavior,
- };
- const previous_trajectory = g_traj;
- g_traj = &trajectory;
- defer g_traj = previous_trajectory;
-
- try std.testing.expectEqual(@as(u64, 1), beginRootTurn(&tracer));
- try std.testing.expectEqual(legacy_next_id, trajectory.next_id);
- try std.testing.expectEqual(trajectory_node, trajectory.currentTurn());
-
- var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
- _ = lines.next(); // run_started
- var turn = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
- defer turn.deinit();
- try std.testing.expectEqual(@as(i64, 1), turn.value.object.get("turn").?.integer);
- try std.testing.expectEqual(@as(i64, @intCast(trajectory_node)), turn.value.object.get("trajectory_node").?.integer);
-}
-
-test "endRootTurn: clears attribution while preserving the dense parent chain" {
- 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 = "root-scope-run",
- };
- var tracer: Tracer = .{
- .io = io,
- .gpa = gpa,
- .out = null,
- .start = Io.Timestamp.now(io, .awake),
- .behavior = &behavior,
- };
- const previous_trajectory = g_traj;
- g_traj = null;
- defer g_traj = previous_trajectory;
-
- behavior.start("test", 1);
- const first = beginRootTurn(&tracer);
- try std.testing.expectEqual(@as(u64, 1), first);
- try std.testing.expectEqual(first, behavior.recordApiMetric(false, 1, 1, 1, 1, 1, false));
- try std.testing.expectEqual(first, behavior.recordToolMetric("bash", false, 1, 1, false));
-
- endRootTurn(&tracer, first);
- try std.testing.expectEqual(@as(u64, 0), behavior.currentTurn());
- try std.testing.expectEqual(@as(u64, 0), behavior.recordApiMetric(false, 1, 1, 1, 1, 1, false));
- try std.testing.expectEqual(@as(u64, 0), behavior.recordToolMetric("bash", false, 1, 1, false));
- behavior.recordExpectedAction(first, "late", .{ .tool = "bash" }, .{ .ok = true }, "outside the root turn");
-
- const second = beginRootTurn(&tracer);
- try std.testing.expectEqual(@as(u64, 2), second);
- endRootTurn(&tracer, first); // a stale scope cannot clear the new turn
- try std.testing.expectEqual(second, behavior.currentTurn());
- endRootTurn(&tracer, second);
- try std.testing.expectEqual(@as(u64, 0), behavior.currentTurn());
- try std.testing.expectEqual(@as(u64, 3), behavior.seq);
-
- var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');
- _ = lines.next(); // run_started
- _ = lines.next(); // first turn_started
- var second_started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});
- defer second_started.deinit();
- try std.testing.expectEqual(@as(i64, 2), second_started.value.object.get("turn").?.integer);
- try std.testing.expectEqual(@as(i64, 1), second_started.value.object.get("parent_turn").?.integer);
- try std.testing.expect(lines.next() == null);
-}