Skip to content

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

Python

fix(#602): checkpoint and expose live turn activity

Rach Pradhanb24d58cef953
diff --git a/src/agent.zig b/src/agent.zig
index cf378c34..031b8eca 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -209,6 +209,8 @@ pub const Agent = struct {
ws_off: bool = false, // codex ws transport disabled for this session after a handshake/transport fallback to SSE (#codex-ws)
ws_transport_failures: u8 = 0, // consecutive WS failures; retry once before latching persistent SSE
streamed_text: bool = false, // the last request printed its text live
+ request_started: ?Io.Timestamp = null, // operational TTFT origin for the active model call (#602)
+ first_token_traced: bool = false,
thinking_open: bool = false, // a live "Thinking" reasoning block is currently streaming (/thinking)
thinking_rows: usize = 0, // on-screen rows the live Thinking block spans (#75 collapse)
thinking_col: usize = 0, // running column within the block, for soft-wrap counting
@@ -480,6 +482,7 @@ pub const Agent = struct {
pub const postStream = @import("agent_stream.zig").postStream;
pub const postStreamWithClient = @import("agent_stream.zig").postStreamWithClient;
pub const printDelta = @import("agent_stream.zig").printDelta;
+ pub const traceFirstToken = @import("agent_observability.zig").firstToken;
// Codex Responses-over-WebSocket transport (+ its fresh-client SSE fallback
// wrapper postLive) lives in agent_ws.zig (#codex-ws). Member-aliased.
pub const postResponsesWs = @import("agent_ws.zig").postResponsesWs;
diff --git a/src/agent_argstream.zig b/src/agent_argstream.zig
index de6d1d1f..cbe90cf4 100644
--- a/src/agent_argstream.zig
+++ b/src/agent_argstream.zig
@@ -352,6 +352,7 @@ fn openLive(self: *Agent, name: []const u8, ix: i64) void {
}
pub fn emitArgText(self: *Agent, tool: ArgTool, text: []const u8) void {
+ if (text.len > 0) self.traceFirstToken();
if (tool == .rlm) {
if (rlm_spec.available and text.len > 0) rlm_spec.feedLive(toolCtx(self), text);
return;
diff --git a/src/agent_observability.zig b/src/agent_observability.zig
new file mode 100644
index 00000000..731b4843
--- /dev/null
+++ b/src/agent_observability.zig
@@ -0,0 +1,11 @@
+//! Small per-request operational-observability helpers kept out of Agent's
+//! already-near-limit definition and the provider-specific stream parsers.
+
+pub fn firstToken(self: anytype) void {
+ if (self.first_token_traced) return;
+ const started = self.request_started orelse return;
+ self.first_token_traced = true;
+ const tracer = self.tracer orelse return;
+ const ms: i64 = @intCast(@max(0, started.untilNow(self.io, .awake).toMilliseconds()));
+ tracer.firstToken(self.label, self.sub, self.provider.model, ms);
+}
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 23cecb16..192c22da 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -235,6 +235,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// GRAFF_REQ_STATS=1: per-call request anatomy + body dumps (req_stats.zig).
req_stats.report(self.io, body, tools, self.sys_normal);
const t0: Io.Timestamp = .now(self.io, .awake);
+ self.request_started = t0;
+ self.first_token_traced = false;
if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_started", .provider = self.provider.id, .model = self.provider.model });
// HTTP calls are flaky: a kept-alive connection the server closed
// (HttpConnectionClosing), a reset, a truncated TLS read. Retry a
@@ -393,6 +395,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
};
defer self.gpa.free(resp_body);
const ms: i64 = t0.untilNow(self.io, .awake).toMilliseconds();
+ if (!live) self.traceFirstToken();
// object — pull the final `response` out of it (or an error).
// object — pull the final `response` out of it (or an error).
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 540baaa9..0c10afd0 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -22,7 +22,7 @@ const util = @import("util.zig");
const eval_control = @import("agent_eval_control.zig");
const codex_chain = @import("codex_chain.zig");
const toolResultMessage = messages_mod.toolResultMessage;
-const vision_queue = @import("vision_queue.zig");
+const turn_checkpoint = @import("turn_checkpoint.zig");
fn surfaceUnstreamedText(self: *Agent, text: []const u8) !void {
if (self.sub or self.streamed_text or text.len == 0) return;
@@ -143,7 +143,7 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
const fco = try toolResultMessage(self.arena, .responses, call.id, r.text, r.is_error);
try self.messages.append(fco);
}
- try vision_queue.flushPending(self);
+ try turn_checkpoint.afterToolBatch(self);
if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) {
if (try grantRepairTurn(self)) return null;
return eval_control.verifier_hard_stop;
@@ -204,7 +204,7 @@ pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
try user_msg.put(self.arena, "role", .{ .string = "user" });
try user_msg.put(self.arena, "content", .{ .array = blocks });
try self.messages.append(.{ .object = user_msg });
- try vision_queue.flushPending(self);
+ try turn_checkpoint.afterToolBatch(self);
if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) {
if (try grantRepairTurn(self)) return null;
@@ -293,7 +293,7 @@ pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
const tool_msg = try toolResultMessage(self.arena, .openai, call.id, r.text, r.is_error);
try self.messages.append(tool_msg);
}
- try vision_queue.flushPending(self);
+ try turn_checkpoint.afterToolBatch(self);
if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) {
if (try grantRepairTurn(self)) return null;
return eval_control.verifier_hard_stop;
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 6892cc7c..7335450c 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -397,6 +397,7 @@ pub fn printDelta(self: *Agent, raw_line: []const u8) void {
defer parsed.deinit();
if (parsed.value != .object) return;
const obj = parsed.value.object;
+ if (modelOutputStarted(self.provider.kind, obj)) self.traceFirstToken();
self.argLiveDelta(obj);
if (no_ui) return;
const text: []const u8 = switch (self.provider.kind) {
@@ -432,9 +433,54 @@ pub fn printDelta(self: *Agent, raw_line: []const u8) void {
// the wire's `reasoning` event, or the live "Thinking" block / spinner.
const sink = engine_sink.forAgent(self);
const reasoning = reasoningDelta(self.provider.kind, obj);
+ if (reasoning.len != 0 or text.len != 0) self.traceFirstToken();
if (reasoning.len != 0) sink.emit(self.io, .{ .reasoning_delta = .{ .text = reasoning } });
if (text.len == 0) return;
self.streamed_text = true;
self.partial_text.appendSlice(self.arena, text) catch {}; // Esc-interrupt capture
sink.emit(self.io, .{ .text_delta = .{ .text = text } });
}
+
+/// Protocol envelopes (response.created, ping, usage) are not tokens. These
+/// are the first event families that contain model-authored prose, reasoning,
+/// or function-call bytes across the three streaming wires.
+fn modelOutputStarted(kind: @import("provider.zig").Provider.Kind, obj: std.json.ObjectMap) bool {
+ return switch (kind) {
+ .anthropic => blk: {
+ const t = obj.get("type") orelse break :blk false;
+ if (t != .string) break :blk false;
+ break :blk std.mem.eql(u8, t.string, "content_block_start") or std.mem.eql(u8, t.string, "content_block_delta");
+ },
+ .openai => blk: {
+ const choices = obj.get("choices") orelse break :blk false;
+ if (choices != .array or choices.array.items.len == 0) break :blk false;
+ const first = choices.array.items[0];
+ if (first != .object) break :blk false;
+ const delta = first.object.get("delta") orelse break :blk false;
+ break :blk delta == .object and delta.object.count() > 0;
+ },
+ .responses => blk: {
+ const t = obj.get("type") orelse break :blk false;
+ if (t != .string) break :blk false;
+ break :blk std.mem.startsWith(u8, t.string, "response.output_") or
+ std.mem.startsWith(u8, t.string, "response.function_call_arguments.") or
+ std.mem.startsWith(u8, t.string, "response.reasoning_");
+ },
+ };
+}
+
+fn testModelOutputStarted(kind: @import("provider.zig").Provider.Kind, json: []const u8) !bool {
+ const parsed = try std.json.parseFromSlice(Value, std.testing.allocator, json, .{});
+ defer parsed.deinit();
+ return modelOutputStarted(kind, parsed.value.object);
+}
+
+test "first-token signal ignores envelopes and sees prose, reasoning, and tool bytes (#602)" {
+ try std.testing.expect(!try testModelOutputStarted(.responses, "{\"type\":\"response.created\"}"));
+ try std.testing.expect(try testModelOutputStarted(.responses, "{\"type\":\"response.output_item.added\"}"));
+ try std.testing.expect(try testModelOutputStarted(.responses, "{\"type\":\"response.function_call_arguments.delta\"}"));
+ try std.testing.expect(!try testModelOutputStarted(.openai, "{\"choices\":[{\"delta\":{}}]}"));
+ try std.testing.expect(try testModelOutputStarted(.openai, "{\"choices\":[{\"delta\":{\"tool_calls\":[{}]}}]}"));
+ try std.testing.expect(!try testModelOutputStarted(.anthropic, "{\"type\":\"message_start\"}"));
+ try std.testing.expect(try testModelOutputStarted(.anthropic, "{\"type\":\"content_block_delta\"}"));
+}
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 5a88e594..0dfa87fc 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -19,7 +19,6 @@
const std = @import("std");
const Io = std.Io;
-
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
@@ -570,6 +569,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
// fires (output_item.added/done open and close the tracked call).
if (!text_seen and sig.flowing(gpa, fbuf.items)) {
text_seen = true;
+ self.traceFirstToken();
if (self.tracer) |tr| tr.note("ws", "first output text — tightening stall budget");
}
@@ -594,6 +594,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
}
if (orig_tio != null and escPressed(true)) return error.Interrupted;
}
+ self.traceFirstToken(); // tool-only responses fall back to completion time
self.codex_ws_used_ms = nowAwakeMs(self.io); // completed turn — restart the idle window (#codex-ws)
return full.toOwnedSlice();
}
diff --git a/src/behavior_trace_tests.zig b/src/behavior_trace_tests.zig
index 3d66483b..bb3cda33 100644
--- a/src/behavior_trace_tests.zig
+++ b/src/behavior_trace_tests.zig
@@ -315,7 +315,7 @@ test "BehaviorTrace: metadata-default upload is an exact content-free projection
.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);
+ tracer.tool("mcp__private_server__lookup_customer", 1, 7, true, 80, true);
behavior.finish(.closed);
behavior.finish(.failed);
// Late callbacks may race terminal teardown. They must observe closure and
diff --git a/src/commands_trajectory.zig b/src/commands_trajectory.zig
index b98c67ca..c9901ca7 100644
--- a/src/commands_trajectory.zig
+++ b/src/commands_trajectory.zig
@@ -75,26 +75,36 @@ pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writ
}
// Tree shows this invocation; scores still come from the whole archive.
const current_run_id = if (root.tracer) |tr| tr.identity.run_id else if (trace.g_traj) |tj| tj.identity.run_id else "";
- var turns: usize = 0;
+ // A live turn and its closed outcome are append-only revisions with the
+ // same id. Keep only the newest revision for display/counting; archive
+ // readers still see the unchanged `kind:"turn"` record vocabulary.
+ var current_turns: std.ArrayList(std.json.ObjectMap) = .empty;
for (objs.items) |o| {
if (!std.mem.eql(u8, S.str(o, "run_id"), current_run_id)) continue;
- if (std.mem.eql(u8, S.str(o, "kind"), "turn")) turns += 1;
+ if (!std.mem.eql(u8, S.str(o, "kind"), "turn")) continue;
+ var replaced = false;
+ for (current_turns.items, 0..) |prior, idx| {
+ if (S.int(prior, "id") != S.int(o, "id")) continue;
+ current_turns.items[idx] = o;
+ replaced = true;
+ break;
+ }
+ if (!replaced) current_turns.append(arena, o) catch {};
}
+ const turns = current_turns.items.len;
if (turns == 0) {
try out.print("no trajectory recorded yet — run a turn first (current file: {s})\n", .{if (trace.g_traj) |tj| tj.path else trace.trajectories_dir});
try out.flush();
return true;
}
try out.print("{s}session trajectory{s} — {d} turn(s); current: {s}; archive: {s} ({d} record(s) total)\n", .{ style.bold, style.reset, turns, if (trace.g_traj) |tj| tj.path else "", trace.trajectories_dir, objs.items.len });
- for (objs.items) |o| {
- if (!std.mem.eql(u8, S.str(o, "run_id"), current_run_id)) continue;
- if (!std.mem.eql(u8, S.str(o, "kind"), "turn")) continue;
+ for (current_turns.items) |o| {
const turn_id = S.int(o, "id");
out.print("{s}●{s} turn {d} {s} {d}ms · prompt {s}{s}{s}{s} · {s}", .{
style.accent,
style.reset,
turn_id,
- if (S.flag(o, "ok")) "✓" else "✗",
+ if (S.flag(o, "live")) "…" else if (S.flag(o, "ok")) "✓" else "✗",
S.int(o, "ms"),
style.dim,
S.str(o, "prompt_sha"),
diff --git a/src/exec.zig b/src/exec.zig
index a001cdf7..308fee86 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -125,7 +125,7 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
var out = blocked;
out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
if (ctx.tracer) |tr| {
- tr.tool(call.name, out.ms, true, out.text.len, ctx.from_sub);
+ tr.tool(call.name, call_id, out.ms, true, out.text.len, ctx.from_sub);
tr.toolFinished(call.name, call_id, out.ms, true, out.text.len);
}
if (ctx.tools_used) |ts| ts.add(ctx.io, ctx.gpa, call.name, true);
@@ -142,7 +142,7 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
};
out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
if (ctx.tracer) |tr| {
- tr.tool(call.name, out.ms, out.is_error, out.text.len, ctx.from_sub);
+ tr.tool(call.name, call_id, out.ms, out.is_error, out.text.len, ctx.from_sub);
tr.toolFinished(call.name, call_id, out.ms, out.is_error, out.text.len);
}
if (ctx.tools_used) |ts| ts.add(ctx.io, ctx.gpa, call.name, out.is_error);
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 9bd0caec..cdf93ca9 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -410,6 +410,7 @@ pub fn run(ctx: *Ctx) !void {
try ctx.out.flush();
}
const turn_before = mainloop_trace.begin(ctx.root, ctx.io);
+ mainloop_trace.recordLive(ctx.root, base_msg, turn_id, prev_turn_id);
const turn_started = Io.Timestamp.now(ctx.io, .awake);
// Turn failures are surfaced without killing the session.
const turn_result = providers.runTurnWithFallback(ctx.root, ctx.keys, ctx.arena, ctx.out);
diff --git a/src/mainloop_trace.zig b/src/mainloop_trace.zig
index 837f0c9a..f7edaa5b 100644
--- a/src/mainloop_trace.zig
+++ b/src/mainloop_trace.zig
@@ -26,6 +26,35 @@ pub fn begin(root: *agent_mod.Agent, io: Io) Before {
};
}
+/// Append the open revision of a root turn before the provider runs. The DGM
+/// archive stays append-only and keeps its existing `kind:"turn"` vocabulary;
+/// record() appends the closed revision with the same id when the turn ends.
+pub fn recordLive(root: *agent_mod.Agent, task: []const u8, turn_id: u64, parent_turn_id: u64) void {
+ const trajectory = trace.g_traj orelse return;
+ if (turn_id == 0) return;
+ const prompt = root.systemPrompt();
+ const prompt_fp = scoring.promptFingerprint(prompt);
+ const task_class = recipe.classifyTask(task);
+ const current_recipe = recipe.snapshot(root.provider.id, root.provider.model, @tagName(root.reasoning), prompt, root.toolsJson(), task_class);
+ trajectory.capturePrompt(prompt_fp, prompt);
+ trajectory.node(.{
+ .id = turn_id,
+ .parent = parent_turn_id,
+ .kind = "turn",
+ .label = root.provider.model,
+ .t = trajectory.elapsedMs(),
+ .live = true,
+ .prompt_sha = &prompt_fp,
+ .recipe_sha = &current_recipe.recipe_sha,
+ .recipe_provider = root.provider.id,
+ .recipe_model = root.provider.model,
+ .recipe_effort = @tagName(root.reasoning),
+ .recipe_toolset_sha = &current_recipe.toolset_sha,
+ .task_class = task_class,
+ .task = util.utf8Prefix(task, 160),
+ });
+}
+
/// Shape of the turn's final assistant response: counts and block types
/// only, never a byte of the content itself (#270). An unrelated text-only
/// refusal and a turn where the model emitted nothing looked identical in
@@ -262,6 +291,44 @@ fn testShape(json: []const u8) !ResponseShape {
return finalResponseShape(parsed.value.array.items);
}
+test "live turn revision reaches the DGM archive before an outcome (#602)" {
+ const io = std.testing.io;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var trajectory: trace.Trajectory = .{
+ .io = io,
+ .gpa = std.testing.allocator,
+ .out = &aw.writer,
+ .start = Io.Timestamp.now(io, .awake),
+ .identity = .{ .run_id = "live-run", .pid = 9, .session_id = "session" },
+ };
+ defer trajectory.deinit();
+ const previous = trace.g_traj;
+ trace.g_traj = &trajectory;
+ defer trace.g_traj = previous;
+
+ var root: agent_mod.Agent = undefined;
+ root.provider = .{ .id = "xai", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "", .model = "grok-test", .context = 100_000 };
+ root.reasoning = .high;
+ root.review_mode = false;
+ root.sub = false;
+ root.strict = false;
+ root.ultracode_mode = false;
+ root.sys_normal = "system prompt";
+ root.tools_anthropic = "[]";
+ recordLive(&root, "inspect the workspace", 4, 3);
+
+ var lines = std.mem.tokenizeScalar(u8, aw.writer.buffered(), '\n');
+ _ = lines.next(); // prompt dictionary record
+ var parsed = try std.json.parseFromSlice(Value, std.testing.allocator, lines.next().?, .{});
+ defer parsed.deinit();
+ const obj = parsed.value.object;
+ try std.testing.expectEqualStrings("turn", obj.get("kind").?.string);
+ try std.testing.expectEqual(@as(i64, 4), obj.get("id").?.integer);
+ try std.testing.expect(obj.get("live").?.bool);
+ try std.testing.expect(obj.get("ok") == null);
+}
+
test "#270: the turn record separates a text-only response from an empty turn" {
var buf: [40]u8 = undefined;
diff --git a/src/trace.zig b/src/trace.zig
index e86a4de6..944e82b2 100644
--- a/src/trace.zig
+++ b/src/trace.zig
@@ -112,6 +112,7 @@ pub const Tracer = struct {
identity: Identity = .{},
path: []const u8 = "",
enabled: bool = true,
+ next_call_id: std.atomic.Value(u64) = .init(1),
// Assigned once before the first root turn. Keeping this on the stable
// shared tracer avoids a process-global pointer race on worker callbacks.
behavior: ?*BehaviorTrace = null,
@@ -138,7 +139,7 @@ pub const Tracer = struct {
});
}
- pub fn tool(self: *Tracer, name: []const u8, ms: i64, is_error: bool, result_bytes: usize, from_sub: bool) void {
+ pub fn tool(self: *Tracer, name: []const u8, call_id: u64, ms: i64, is_error: bool, result_bytes: usize, from_sub: bool) void {
if (telemetry.g_telem) |t| t.countTool(is_error);
const behavior_turn = if (self.behavior) |behavior|
behavior.recordToolMetric(name, from_sub, ms, result_bytes, is_error)
@@ -148,6 +149,7 @@ pub const Tracer = struct {
.t = self.elapsedMs(),
.ev = "tool",
.turn = behavior_turn,
+ .call_id = call_id,
.name = name,
.ms = ms,
.result_bytes = result_bytes,
@@ -156,16 +158,16 @@ pub const Tracer = struct {
});
}
- /// Reserve a call_id and emit `tool_started` (#255, opt-in rich capture
- /// only — behavior.toolStarted no-ops when rich is off). 0 means there is
- /// no behavioral sink to attribute against; toolFinished/actionTaken
- /// below treat that the same way turn 0 means "unattributed" elsewhere
- /// in this file. `args` is serialized into a bounded scratch buffer —
+ /// Reserve a process-local call_id for the operational trace, then emit
+ /// `tool_started` to the rich behavior stream when that privacy gate is
+ /// enabled. The operational id exists even without a behavior sink, so
+ /// every default `ev=tool` outcome is independently pairable (#602).
+ /// `args` is serialized into a bounded scratch buffer —
/// BehaviorTrace's own max_tool_args_bytes cap does the real truncation,
/// this just keeps an oversized adapter payload off the stack.
pub fn toolStarted(self: *Tracer, name: []const u8, args: Value) u64 {
- const behavior = self.behavior orelse return 0;
- const call_id = behavior.reserveCallId();
+ const call_id = self.next_call_id.fetchAdd(1, .monotonic);
+ const behavior = self.behavior orelse return call_id;
var buf: [8192]u8 = undefined;
var w: Io.Writer = .fixed(&buf);
var s: std.json.Stringify = .{ .writer = &w };
@@ -174,6 +176,21 @@ pub const Tracer = struct {
return call_id;
}
+ /// First semantic model output for one API request. Content-free and
+ /// default-on: `ms` is time-to-first-token from request send (#602).
+ pub fn firstToken(self: *Tracer, label: []const u8, from_subagent: bool, model: []const u8, ms: i64) void {
+ const behavior_turn = if (self.behavior) |behavior| behavior.currentTurn() else 0;
+ self.write(.{
+ .t = self.elapsedMs(),
+ .ev = "first_token",
+ .turn = behavior_turn,
+ .agent = label,
+ .model = model,
+ .from_sub = from_subagent,
+ .ms = ms,
+ });
+ }
+
/// Emit `tool_finished`, then `action_taken` for state-mutating tool
/// classes (#255). Both are no-ops when call_id is 0 (toolStarted found
/// no behavioral sink) or rich capture is off.
@@ -463,6 +480,30 @@ test "writeJsonLine: one complete newline-terminated JSON record per call" {
}
}
+test "operational tool outcomes carry monotonic call ids without rich tracing (#602)" {
+ const io = std.testing.io;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var tracer: Tracer = .{
+ .io = io,
+ .gpa = std.testing.allocator,
+ .out = &aw.writer,
+ .start = Io.Timestamp.now(io, .awake),
+ .identity = .{ .run_id = "ops", .pid = 7, .session_id = "session" },
+ };
+ var args = try std.json.parseFromSlice(Value, std.testing.allocator, "{}", .{});
+ defer args.deinit();
+ const first = tracer.toolStarted("bash", args.value);
+ const second = tracer.toolStarted("read_file", args.value);
+ try std.testing.expectEqual(first + 1, second);
+ tracer.tool("bash", first, 9, false, 12, false);
+
+ var parsed = try std.json.parseFromSlice(Value, std.testing.allocator, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), .{});
+ defer parsed.deinit();
+ try std.testing.expectEqualStrings("tool", parsed.value.object.get("ev").?.string);
+ try std.testing.expectEqual(@as(i64, @intCast(first)), parsed.value.object.get("call_id").?.integer);
+}
+
test "writeJsonLine signals a file-write failure so the tracer can disable (#242)" {
// A fixed sink too small for a whole record forces the file write to fail.
// writeJsonLine must return false so the caller drops the writer instead of
diff --git a/src/turn_checkpoint.zig b/src/turn_checkpoint.zig
new file mode 100644
index 00000000..de94719f
--- /dev/null
+++ b/src/turn_checkpoint.zig
@@ -0,0 +1,12 @@
+//! Mid-turn durability after an executed tool batch (#602). The append-only
+//! transcript is written synchronously by queueSave; only the replaceable
+//! session snapshot's disk write remains on the existing background writer.
+
+const session = @import("session.zig");
+const vision_queue = @import("vision_queue.zig");
+
+pub fn afterToolBatch(self: anytype) !void {
+ try vision_queue.flushPending(self);
+ if (self.sub or self.session_name.len == 0) return;
+ session.saveSessionAsync(self, self.arena, self.session_name) catch {};
+}