Skip to content

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

Python

feat(telemetry): task-outcome events per goal, labeled by compaction arm

Rach Pradhane13e7f3e320c
diff --git a/src/agent.zig b/src/agent.zig
index ea4ecdc8..ee63256b 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -57,6 +57,11 @@ pub const Goal = struct {
standing: bool = false, // seeded by --goal: steering policy for the WHOLE session that the model can never retire; only the user can, with /goal clear|pause|<new> (#318)
created_ms: i64 = 0,
updated_ms: i64 = 0,
+ // Effort snapshots for task-outcome telemetry (task_outcome.zig): session
+ // counters at goal-set time, diffed at completion/abandon.
+ turns_at_set: u64 = 0,
+ calls_at_set: u64 = 0,
+ compacts_at_set: u64 = 0,
};
/// One agent: a message history plus the POST/tool-dispatch loop. The root
/// agent prints to stdout; subagents (sub = true) run on pool threads and
diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zig
index 1bea6e2c..2b1a080b 100644
--- a/src/agent_server_compact.zig
+++ b/src/agent_server_compact.zig
@@ -83,8 +83,14 @@ pub fn noteExposure(self: *Agent) void {
pushExp(if (enabled(self.provider)) "arm=server" else "arm=client");
}
+/// Session compaction counters (all providers) for per-goal effort diffs in
+/// task_outcome.zig. Monotonic per process; saturating adds, never reset.
+pub var session_prunes: u64 = 0;
+pub var session_summaries: u64 = 0;
+
/// Record a successful server-side prune (the treatment arm doing work).
fn notePrune(dropped: usize) void {
+ session_prunes +|= 1;
var buf: [24]u8 = undefined;
const d = std.fmt.bufPrint(&buf, "prune_items={d}", .{dropped}) catch return;
pushExp(d);
@@ -93,6 +99,7 @@ fn notePrune(dropped: usize) void {
/// Record a successful client-side summary on a .responses provider — the
/// control arm doing work (auto at >=95%, or manual /compact on codex).
pub fn noteClientSummary(chars: usize) void {
+ session_summaries +|= 1;
var buf: [28]u8 = undefined;
const d = std.fmt.bufPrint(&buf, "summary_chars={d}", .{chars}) catch return;
pushExp(d);
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index e738f0ad..09faf014 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -35,6 +35,7 @@ const schema = @import("schema.zig");
const isMetaName = schema.isMetaName;
const eval_control = @import("agent_eval_control.zig");
const goal_state = @import("goal_state.zig");
+const task_outcome = @import("task_outcome.zig");
const goal_todo = @import("goal_todo.zig"); // todo_write's replace path + the omitted-completed preserve rule
const peer_channel = @import("peer_channel.zig"); // #469: peer_message's handler
pub const toolInvalidatesEval = eval_control.toolInvalidatesEval;
@@ -315,6 +316,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
}
const result = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "result") orelse "") else "";
self.completed = try self.arena.dupe(u8, result);
+ if (!self.sub) task_outcome.noteGoalCompleted(self);
// .complete retires the epoch (goal_state.currentEpoch) and the checklist parks - readable, no longer current, never deleted (#318).
// A --goal standing objective is exempt: the completion is recorded above, the steering stays, and only /goal clear|pause|<new> retires it.
if (goal_state.retireOnCompletion(self, util.unixMs(self.io))) {
diff --git a/src/goal_flow.zig b/src/goal_flow.zig
index 80da0102..3bde5283 100644
--- a/src/goal_flow.zig
+++ b/src/goal_flow.zig
@@ -11,6 +11,7 @@ const agent_mod = @import("agent.zig");
const goal_state = @import("goal_state.zig");
const repl_glue = @import("repl_glue.zig");
const presence = @import("presence.zig");
+const task_outcome = @import("task_outcome.zig");
const utf8Prefix = @import("util.zig").utf8Prefix;
const Agent = agent_mod.Agent;
const TodoItem = agent_mod.TodoItem;
@@ -56,6 +57,7 @@ pub fn reapplyFlagGoal(arena: Allocator, root: *Agent, objective: []const u8, no
}
const displaced: ?agent_mod.Goal = if (root.goal) |old| (if (old.status == .complete) null else old) else null;
root.goal = standingGoalFromFlag(objective, root.goal, root.todos.items, now_ms);
+ task_outcome.noteGoalSet(root);
presence.noteGoal(root.io, root.gpa, root.arena, objective); // #469: co-resident sessions read our goal off the presence record
root.goal_note_fp = 0; // re-state the (now standing) note on the next turn
goal_state.resetCompletionGate(root); // a new objective is fresh evidence for the double-check
@@ -150,6 +152,7 @@ pub fn applyGoalSet(root: *Agent, objective: []const u8, now_ms: i64) GoalSetRes
goal_state.adoptTodos(root.todos.items, goal_state.currentEpoch(root.goal), epoch);
const parked_open = goal_state.parkedOpenCount(root.todos.items, epoch);
root.goal = .{ .objective = objective, .status = .active, .epoch = epoch, .created_ms = now_ms, .updated_ms = now_ms };
+ task_outcome.noteGoalSet(root);
presence.noteGoal(root.io, root.gpa, root.arena, objective); // #469: keep the presence record's goal current for peers
root.goal_note_fp = 0; // re-state the note on the next turn, not a stale-suppressed repeat
goal_state.resetCompletionGate(root); // a new objective is new evidence for the completion double-check
diff --git a/src/main.zig b/src/main.zig
index 0297aeb3..180501ee 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -306,7 +306,6 @@ pub fn main(init: std.process.Init) !void {
var stdout_writer = Io.File.stdout().writer(io, &stdout_buf);
const out = &stdout_writer.interface;
g_out = out;
-
if (try session_start.runTitleCommand(io, gpa, arena, &client, default_provider, out, flags, &invocation_budget)) return;
// Generate identity before opening either JSONL. The score channel and both
// files share this run id; session_id is a separate runtime correlation id.
@@ -589,6 +588,7 @@ test { // pull in tests from imported modules (mcp.zig)
_ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped
_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests
_ = @import("agent_server_compact.zig"); // server-side autocompact (codex Responses)
+ _ = @import("task_outcome.zig"); // goal-outcome telemetry events
_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here
_ = @import("readline_history.zig");
_ = @import("goal_pacing_autonomous_test.zig");
diff --git a/src/session_run.zig b/src/session_run.zig
index 63485146..35a82b6f 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -373,6 +373,9 @@ pub fn compactResumedSession(root: *agent_mod.Agent) void {
/// final turn left uncommitted. Moved out of main() verbatim (600-line
/// goal); `root` is already stable main()-owned storage.
pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, json_mode: bool) !void {
+ // Task-outcome telemetry: a working goal that never completed counts as
+ // abandoned. Before presence.retire so the event can't outlive the flush.
+ @import("task_outcome.zig").noteSessionEnd(root);
// #469: our presence record leaves the registry with us; a crashed session
// skips this and gets reaped by the next reader's liveness probe instead.
presence.retire(io);
diff --git a/src/task_outcome.zig b/src/task_outcome.zig
new file mode 100644
index 00000000..c2b483e2
--- /dev/null
+++ b/src/task_outcome.zig
@@ -0,0 +1,128 @@
+//! Task-outcome telemetry (#compact-ab follow-up): did the session's goal
+//! actually get DONE, and at what effort — per compaction arm.
+//!
+//! One OTLP record per goal outcome: body="task", kind="goal",
+//! detail="completed|abandoned arm=server|client|other", plus numeric attrs
+//! (turns, calls, compactions, duration_ms) serialized by telemetry.zig's
+//! body=="task" branch and stored verbatim in the worker's attrs JSON. The
+//! /v1/stats rollup (TASK_OUTCOME_SQL in zigrepper's harness-telemetry)
+//! groups these by arm — completion rate and effort per arm is the
+//! ship/rollback signal for server-side compaction.
+//!
+//! Emission points:
+//! - noteGoalSet: goal_flow's two set sites — snapshots the session
+//! counters into the Goal so completion can diff effort.
+//! - noteGoalCompleted: agent_tools handleMeta attempt_completion (root
+//! only, after the gates pass).
+//! - noteSessionEnd: session_run.finalizeSession — a non-standing goal
+//! still active/blocked at exit counts as abandoned. Paused is a user
+//! decision and standing goals are open-ended by design: neither counts.
+//!
+//! Static/numeric content only — the goal's TEXT never leaves the process.
+
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const Goal = @import("agent.zig").Goal;
+const Provider = @import("provider.zig").Provider;
+const telemetry = @import("telemetry.zig");
+const server_compact = @import("agent_server_compact.zig");
+const util = @import("util.zig");
+
+/// Which compaction arm a session on this provider is in, for the detail
+/// label. Non-Responses providers have no server path at all: "other".
+pub fn armLabel(p: Provider) []const u8 {
+ if (p.kind != .responses) return "other";
+ return if (server_compact.enabled(p)) "server" else "client";
+}
+
+pub const Effort = struct { turns: u64, calls: u64, compacts: u64 };
+
+/// Pure diff of session counters against the goal-set snapshot. Saturating:
+/// counters only move forward, but a restored session could see smaller ones.
+pub fn effortSince(goal: Goal, turns: u64, calls: u64, compacts: u64) Effort {
+ return .{
+ .turns = turns -| goal.turns_at_set,
+ .calls = calls -| goal.calls_at_set,
+ .compacts = compacts -| goal.compacts_at_set,
+ };
+}
+
+fn sessionTurns() u64 {
+ const t = telemetry.g_telem orelse return 0;
+ return t.turns;
+}
+
+fn sessionCalls() u64 {
+ const t = telemetry.g_telem orelse return 0;
+ return t.tool_calls;
+}
+
+fn sessionCompacts() u64 {
+ return server_compact.session_prunes +| server_compact.session_summaries;
+}
+
+/// Snapshot the effort counters into a freshly set goal. Call right after
+/// root.goal is assigned.
+pub fn noteGoalSet(root: *Agent) void {
+ if (root.goal) |*g| {
+ g.turns_at_set = sessionTurns();
+ g.calls_at_set = sessionCalls();
+ g.compacts_at_set = sessionCompacts();
+ }
+}
+
+fn pushTask(self: *Agent, outcome: []const u8) void {
+ const t = telemetry.g_telem orelse return;
+ if (!t.on()) return;
+ const g = self.goal orelse return;
+ const e = effortSince(g, sessionTurns(), sessionCalls(), sessionCompacts());
+ var buf: [40]u8 = undefined;
+ const detail = std.fmt.bufPrint(&buf, "{s} arm={s}", .{ outcome, armLabel(self.provider) }) catch return;
+ const dup = t.gpa.dupe(u8, detail) catch "";
+ t.mutex.lockUncancelable(t.io);
+ t.push(.{
+ .t_ms = t.elapsedMsLocked(),
+ .body = "task",
+ .kind = "goal",
+ .detail = dup,
+ .tasks = @intCast(e.turns),
+ .phases = @intCast(e.calls),
+ .failed = @intCast(e.compacts),
+ .ms = util.unixMs(self.io) - g.created_ms,
+ });
+ t.mutex.unlock(t.io);
+ t.maybeFlushEvents();
+}
+
+/// attempt_completion passed its gates (agent_tools handleMeta, root only).
+pub fn noteGoalCompleted(self: *Agent) void {
+ pushTask(self, "completed");
+}
+
+/// finalizeSession: a working goal that never completed counts as abandoned.
+pub fn noteSessionEnd(root: *Agent) void {
+ const g = root.goal orelse return;
+ if (g.standing) return; // open-ended by design (#318)
+ if (g.status != .active and g.status != .blocked) return;
+ pushTask(root, "abandoned");
+}
+
+test "armLabel: responses follows the arm, others are out of the experiment" {
+ var p: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "m", .context = 272_000 };
+ try std.testing.expectEqualStrings("client", armLabel(p)); // unassigned in tests → client
+ p.kind = .anthropic;
+ try std.testing.expectEqualStrings("other", armLabel(p));
+ p.kind = .openai;
+ try std.testing.expectEqualStrings("other", armLabel(p));
+}
+
+test "effortSince: diffs the snapshot, saturates on restored sessions" {
+ const g: Goal = .{ .objective = "x", .turns_at_set = 3, .calls_at_set = 10, .compacts_at_set = 1 };
+ const e = effortSince(g, 8, 25, 4);
+ try std.testing.expectEqual(@as(u64, 5), e.turns);
+ try std.testing.expectEqual(@as(u64, 15), e.calls);
+ try std.testing.expectEqual(@as(u64, 3), e.compacts);
+ const odd = effortSince(g, 1, 0, 0); // counters below the snapshot
+ try std.testing.expectEqual(@as(u64, 0), odd.turns);
+ try std.testing.expectEqual(@as(u64, 0), odd.calls);
+}
diff --git a/src/telemetry.zig b/src/telemetry.zig
index b0c444aa..87f4d12a 100644
--- a/src/telemetry.zig
+++ b/src/telemetry.zig
@@ -522,6 +522,14 @@ pub const Telemetry = struct {
} else {
if (e.kind.len > 0) try attr(&s, "kind", .{ .str = e.kind });
if (e.detail.len > 0) try attr(&s, "detail", .{ .str = e.detail });
+ if (std.mem.eql(u8, e.body, "task")) {
+ // task_outcome.zig goal events: effort rides as numeric
+ // attrs; the worker stores the attrs JSON verbatim.
+ try attr(&s, "turns", .{ .int = e.tasks });
+ try attr(&s, "calls", .{ .int = e.phases });
+ try attr(&s, "compactions", .{ .int = e.failed });
+ try attr(&s, "duration_ms", .{ .int = e.ms });
+ }
if (std.mem.eql(u8, e.body, "workflow")) {
try attr(&s, "phases", .{ .int = e.phases });
try attr(&s, "tasks", .{ .int = e.tasks });