graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(behavior): unblock the local stream and make both sinks account for loss (#246)
Rach Pradhand9c8b861f601
diff --git a/README.md b/README.mdindex 460df639..2dcce939 100644--- a/README.md+++ b/README.md@@ -802,7 +802,7 @@ with `--max-model-calls N` or the lower-precedence `GRAFF_MAX_MODEL_CALLS`.**Behavioral trajectories are a separate experimental stream.** Each initializedagent session can write an exclusively-created-`.graff/trajectories/<run_id>.jsonl` with an ordered, attributable lifecycle+`.graff/behavior/<run_id>.jsonl` with an ordered, attributable lifecycleenvelope. The local JSONL is never uploaded wholesale. Local capture defaults onand is independently disabled with `GRAFF_BEHAVIOR_TRACE=off`.diff --git a/docs/behavioral-trajectories.md b/docs/behavioral-trajectories.mdindex 04c39da2..07ddb569 100644--- a/docs/behavioral-trajectories.md+++ b/docs/behavioral-trajectories.md@@ -14,7 +14,7 @@ scoring, or fleet/DGM selection from those scores.| Stream | Lifetime | Purpose || --- | --- | --- || `harness.trace.jsonl` | Truncated at startup | Operational API/tool latency and error counters, with active behavioral-turn attribution, used to debug the harness. |-| `.graff/trajectories/<run_id>.jsonl` | Up to one exclusively-created file per initialized agent session | Experimental lifecycle and caller-asserted belief events. |+| `.graff/behavior/<run_id>.jsonl` | Up to one exclusively-created file per initialized agent session | Experimental lifecycle and caller-asserted belief events. || `harness.trajectory.jsonl` | Append-only across runs | Existing DGM/MAP-Elites lineage and fitness ledger. Its record shapes are unchanged. |Behavioral events are deliberately not mixed into the legacy DGM ledger. This@@ -64,8 +64,9 @@ The batch schema is `codegraff.behavior.batch.v1`; projected events retain`codegraff.behavior.v1`. In metadata mode the batch contains pseudonymousinstall/run attribution, a controlled client class (`harness`, `sdk-ts`, or`sdk-py`), lifecycle and turn relationships, an initial provider/model/effort-snapshot, terminal and drop status, keyed opaque commitment references, and-content-free per-turn API/tool aggregates. The local deterministic prompt+snapshot, local-sink health (`local_sink` on `run_started`, `local_dropped` on+`run_finished`), terminal and drop status, keyed opaque commitment references,+and content-free per-turn API/tool aggregates. The local deterministic promptfingerprint is deliberately omitted from all behavioral uploads becauselow-entropy prompt variants can be recovered by enumeration. Tool aggregates usecontrolled classes (`shell`, `read`, `write`, `search`, `web`, `agent`, `verify`,@@ -105,7 +106,7 @@ Every complete line is one flat JSON object with these required envelope fields:| Field | Type | Meaning || --- | --- | --- || `kind` | string | One of the nine event-kind names below. |-| `seq` | positive integer | Logical source-event order. A healthy local file is a contiguous prefix starting at `1`; a bounded upload projection can have gaps reported by its drop counters. |+| `seq` | positive integer | Logical source-event order, reserved before either sink is attempted. A healthy local file starts at `1` and is contiguous except for events rejected before write, which the terminal `run_finished` accounts for in `local_dropped`; a bounded upload projection can have gaps reported by its own drop counters. || `ts` | number | Wall-clock Unix time in fractional seconds. It can repeat or move backwards if the system clock changes. || `run_id` | string | The run's random hexadecimal identifier, also used in the filename. || `schema` | string | `codegraff.behavior.v1`. |@@ -115,16 +116,22 @@ Consumers should ignore unknown top-level fields so compatible additions remainpossible.A logical `seq` is reserved once before either sink is attempted. Each local-record is built completely in memory, written, and flushed as one line. If local-serialization or output fails, local capture is disabled for the rest of the-process while upload remains independent; an upload admission failure likewise-does not disable the local file. This makes a healthy local stream a contiguous-prefix, while an upload may contain source-sequence gaps accounted for by-`dropped_events`. A local event is capped at 64 KiB to bound temporary-serialization memory; exceeding that cap disables the local sink for the rest of-the run but does not disable metadata upload. Directory creation,-private-permission setup, and exclusive-open collisions are best-effort; a-failure silently leaves only local behavioral capture disabled. An I/O failure+record is built completely in memory, written, and flushed as one line.+Failures that happen before any byte reaches the file (allocation,+serialization, or the 64 KiB per-event cap that bounds temporary+serialization memory) drop only that event: the local stream stays alive, the+drop is counted, and the terminal `run_finished` declares the total as+`local_dropped` so an auditor can reconcile every gap. A failure of the file+write itself still disables local capture for the rest of the process, because+a partial tail may exist and later records must not be appended after it.+Upload remains independent in both directions: an upload admission failure+does not disable the local file, and an upload may contain source-sequence+gaps accounted for by its own `dropped_events`. Directory creation and+private-permission setup are best-effort; if the local file cannot be created,+the harness prints one stderr warning, reports `local_sink=false` in the+uploaded `run_started` projection, and leaves only local capture disabled. If+secure entropy is unavailable at run start, behavioral upload is disabled for+the run instead of degrading the commitment-reference key. An I/O failurecan still leave one malformed finalline; consumers should process only complete JSON lines and treat a missingterminal `run_finished` as incomplete. The files currently have no manifest,@@ -187,6 +194,8 @@ key. One-shot and zigzag modes preserve their old DGM behavior and currently useRequired field:- `status` — currently `closed` or `error`.+- `local_dropped` — how many events were rejected before reaching the local+ file (each one leaves a `seq` gap that this count must equal).`closed` means that the initialized agent session returned without propagatinga Zig error. It is **not** a task-success verdict and does not prove that every@@ -258,7 +267,7 @@ upload scans or sanitizes them.- `.graff/` is ignored by Git.- Directory components are opened relative to verified no-follow handles, so aworkspace symlink cannot redirect the trace outside the working directory.- On POSIX, the trajectories directory is set to mode `0700`; new files request+ On POSIX, the behavior directory is set to mode `0700`; new files requesta maximum mode of `0600`, which a restrictive process umask may reducefurther. On Windows, access follows the directory's inherited ACLs.- The local JSONL bytes are never automatically uploaded. A separately built@@ -267,7 +276,7 @@ upload scans or sanitizes them.- Local capture is enabled by default and independent of the operational`/trace` toggle and behavioral upload setting.- Local files have no automatic retention limit. Delete files from- `.graff/trajectories/` when they are no longer needed. Git ignore rules do not+ `.graff/behavior/` when they are no longer needed. Git ignore rules do notprevent backups, artifact collectors, support bundles, workspace-capableagent tools, or manual uploads from reading or copying them.- Behavioral events are not consumed for fleet/DGM selection in Phase 1.@@ -281,9 +290,31 @@ upload scans or sanitizes them.{"kind":"turn_started","seq":2,"ts":1770000001.25,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","turn":1,"parent_turn":0,"trajectory_node":1}{"kind":"turn_committed","seq":3,"ts":1770000002.5,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","turn":1,"commitment_id":"build-1","action":{"kind":"edit"},"expect":{"build":"passes"},"reason":"verify the patch"}{"kind":"model_mispredicted","seq":4,"ts":1770000003.75,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","turn":1,"commitment_id":"build-1","predicted":{"build":"passes"},"actual":{"build":"fails"},"detail":"compiler verification contradicted the expectation"}-{"kind":"run_finished","seq":5,"ts":1770000004.0,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","status":"closed"}+{"kind":"run_finished","seq":5,"ts":1770000004.0,"run_id":"0123456789abcdef","schema":"codegraff.behavior.v1","status":"closed","local_dropped":0}```+## Recomputable scoring and replay++Two stdlib-only tools make the stream auditable on its own, mirroring the+schema-harness `score_trajectories.py` contract:++- `scripts/score_run.py <stream.jsonl>` audits a local behavioral file+ (envelope, seq/gap reconciliation against `local_dropped`, turn density,+ commitment fields) and derives behavioral metrics from events alone:+ turns, commitments, mispredicts, mispredict rate, commitment coverage, and+ mean repair gap. With `--profile replay --baseline <csv> --game <id>` it+ scores a converted external trajectory with the reference RHAE math+ (per-level `min(115, 100*(baseline/actions)^2)`, level-index weights,+ completion cap).+- `scripts/replay_schema_harness.py events.jsonl out.jsonl` converts a+ schema-harness trajectory into this envelope mechanically.++Round-trip validation: converting the published+`claude_fable_opus/claude-fable-5_max_ft09_100.0` trajectory and re-scoring+the converted stream reproduces its published 100.0 RHAE exactly (the issue+#246 validation criterion). CI runs a hermetic version of the same round trip+plus the live-session audit in `scripts/test-behavior-trace.py`.+## Deferred work for the full issueA complete predict–verify implementation still needs:@@ -291,12 +322,11 @@ A complete predict–verify implementation still needs:1. Task adapters that define state snapshots, legal actions, action/observationboundaries, and outcome semantics.2. Stable agent/invocation identities and real dispatch/completion hooks for- concurrent tool events.+ concurrent tool events (the four reserved kinds above).3. Explicit expectation binding, verification, surprise interruption, and- repair behavior.-4. Versioned, recomputable behavioral scorers plus recipe/eval identity and- trace-integrity metadata.+ repair behavior wired to a production producer.+4. Versioned Zig-side behavioral score events plus recipe/eval identity and+ trace-integrity metadata (the stdlib auditor above recomputes metrics and+ replay scores, but no built-in run emits a score-bearing outcome yet).5. Admission of only trusted recomputed scores into eval, fleet, MAP-Elites,and DGM selection.-6. Replay of the published schema-harness ft09 trajectory and reproduction of- its reference score.diff --git a/src/behavior_trace.zig b/src/behavior_trace.zigindex 8ce127d4..3edb026f 100644--- a/src/behavior_trace.zig+++ b/src/behavior_trace.zig@@ -19,7 +19,13 @@ test {// ── Behavioral trace (one experimental event file per run) ────────────────-pub const behavior_dir = ".graff/trajectories";+// Behavioral events get their own directory. The legacy DGM trajectory file+// is already created earlier in startup as+// `.graff/trajectories/<g_run_id>.jsonl` (main.zig trajectoryPath), and the+// behavioral stream is named by the same run id, so sharing that directory+// made the exclusive create collide every session and silently disabled+// local behavioral capture.+pub const behavior_dir = ".graff/behavior";pub const behavior_schema = "codegraff.behavior.v1";/// Task-agnostic behavioral records. Per-kind fields stay flat, matching the@@ -44,28 +50,35 @@ pub const BehaviorRunStatus = enum {pub const max_local_behavior_event_bytes = 64 * 1024;+/// How one local write attempt ended. `dropped` failures happen before any+/// byte reaches the file (allocation, serialization, or the size cap), so the+/// stream stays healthy and later events may follow; the drop is counted and+/// declared on `run_finished` as `local_dropped`. `sink_failed` means the+/// file write itself failed and a partial tail may exist, so the caller must+/// stop using the sink.+pub const LineResult = enum { written, dropped, sink_failed };+/// 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;+/// causing unbounded temporary allocation.+pub fn writeBehaviorLine(gpa: Allocator, w: *Io.Writer, kind: BehaviorKind, seq: u64, ts: f64, run_id: []const u8, fields: anytype) LineResult {+ const backing = gpa.alloc(u8, max_local_behavior_event_bytes + 1) catch return .dropped;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;+ s.beginObject() catch return .dropped;+ s.objectField("kind") catch return .dropped;+ s.write(@tagName(kind)) catch return .dropped;+ s.objectField("seq") catch return .dropped;+ s.write(seq) catch return .dropped;+ s.objectField("ts") catch return .dropped;+ s.write(ts) catch return .dropped;+ s.objectField("run_id") catch return .dropped;+ s.write(run_id) catch return .dropped;+ s.objectField("schema") catch return .dropped;+ s.write(behavior_schema) catch return .dropped;inline for (comptime std.meta.fieldNames(@TypeOf(fields))) |name| {comptime {if (std.mem.eql(u8, name, "kind") or@@ -77,15 +90,15 @@ pub fn writeBehaviorLine(gpa: Allocator, w: *Io.Writer, kind: BehaviorKind, seq:@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.objectField(name) catch return .dropped;+ s.write(@field(fields, name)) catch return .dropped;}- 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;+ s.endObject() catch return .dropped;+ if (line.buffered().len > max_local_behavior_event_bytes) return .dropped;+ line.writeByte('\n') catch return .dropped;+ w.writeAll(line.buffered()) catch return .sink_failed;+ w.flush() catch return .sink_failed;+ return .written;}/// Per-run behavioral event stream written to@@ -125,6 +138,10 @@ pub const BehaviorTrace = struct {turn_active: bool = false,started: bool = false,closed: bool = false,+ /// Events rejected before any byte reached the local file (oversize,+ /// allocation, serialization). Declared on `run_finished` so a local seq+ /// gap is distinguishable from truncation or tampering.+ local_dropped: u64 = 0,commitment_key: [32]u8 = undefined,commitment_key_initialized: bool = false,@@ -150,10 +167,15 @@ pub const BehaviorTrace = struct {self.seq = next;const ts = self.timestamp();if (self.out) |w| {- if (!writeBehaviorLine(self.gpa, w, kind, next, ts, self.run_id, local_fields)) {+ switch (writeBehaviorLine(self.gpa, w, kind, next, ts, self.run_id, local_fields)) {+ .written => {},+ // Nothing reached the file: count the gap and keep the stream+ // alive. One oversized opaque payload must not erase the rest+ // of the run (and run_finished) from the local record.+ .dropped => self.local_dropped +|= 1,// Do not append after a possible partial write. Upload remains// independent so a local disk failure need not erase metadata.- self.out = null;+ .sink_failed => self.out = null,}}if (self.upload) |uploader| {@@ -172,7 +194,14 @@ pub const BehaviorTrace = struct {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.io.randomSecure(&self.commitment_key) catch {+ // Fail closed: without secure entropy the keyed commitment+ // references become dictionary-recoverable, so drop the upload+ // sink rather than silently degrade to weaker randomness. The+ // local file never uses the key.+ self.commitment_key = @splat(0);+ self.upload = null;+ };self.commitment_key_initialized = true;self.started = true;const local_fields = .{@@ -193,6 +222,10 @@ pub const BehaviorTrace = struct {.provider = metadata.provider,.model = metadata.model,.effort = metadata.effort,+ // Sink health, so collector-side data knows whether a local+ // stream exists to reconcile against (the local file is the+ // source of truth when both are present).+ .local_sink = self.out != null,};_ = self.eventLocked(.run_started, local_fields, upload_fields, upload_fields);}@@ -315,7 +348,10 @@ pub const BehaviorTrace = struct {var terminal_retained = false;if (self.started) {- const fields = .{ .status = status_name };+ // Declaring the local drop count on the terminal event makes a+ // seq-gapped local file auditable: a scorer can verify that+ // max seq == lines present + local_dropped.+ const fields = .{ .status = status_name, .local_dropped = self.local_dropped };terminal_retained = self.eventLocked(.run_finished, fields, fields, fields);}self.turn_active = false;@@ -354,6 +390,10 @@ pub const Boot = struct {uploader: behavior_upload.Upload,open: session_start.FileWriterOpen,behavior: BehaviorTrace,+ /// True when local capture was requested but the file could not be+ /// created (directory failure, exclusive-open collision). Callers surface+ /// one warning so a dead local sink is not silent (#246 review).+ local_sink_failed: bool = false,/// Point the behavior stream at this Boot's settled storage and assign/// the shared tracer. All root/subagent callbacks already share that@@ -412,5 +452,6 @@ pub fn boot(io: Io, gpa: Allocator, client: ?*std.http.Client, environ_map: anyt.upload = null,.run_id = &scoring.g_run_id,},+ .local_sink_failed = enabled and open.file == null,};}diff --git a/src/behavior_upload.zig b/src/behavior_upload.zigindex e75e089e..b6151f3e 100644--- a/src/behavior_upload.zig+++ b/src/behavior_upload.zig@@ -7,6 +7,7 @@const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;+const http = @import("http.zig");pub const batch_schema = "codegraff.behavior.batch.v1";pub const event_schema = "codegraff.behavior.v1";@@ -94,6 +95,15 @@ pub const TurnMetrics = struct {tool_other: u64 = 0,};+comptime {+ // turn_metrics rows bypass assertMetadataFields, so close the same+ // privacy hole structurally: every field must stay a content-free u64+ // counter, and a string or nested payload cannot ride along unnoticed.+ for (@typeInfo(TurnMetrics).@"struct".fields) |field| {+ if (field.type != u64) @compileError("TurnMetrics fields must be content-free u64 counters: " ++ field.name);+ }+}+const ToolClass = enum {shell,read,@@ -147,7 +157,12 @@ fn isMetadataField(comptime name: []const u8) bool {std.mem.eql(u8, name, "parent_turn") orstd.mem.eql(u8, name, "trajectory_node") orstd.mem.eql(u8, name, "commitment_ref") or- std.mem.eql(u8, name, "status");+ std.mem.eql(u8, name, "status") or+ // Sink-health diagnostics: whether the local JSONL opened at run start+ // and how many events it dropped before write. Counters and booleans+ // only; nothing content-bearing.+ std.mem.eql(u8, name, "local_sink") or+ std.mem.eql(u8, name, "local_dropped");}fn assertMetadataFields(comptime T: type) void {@@ -434,6 +449,11 @@ pub fn behaviorUrl(gpa: Allocator, endpoint: []const u8) !?[]u8 {}pub fn postBatch(client: *std.http.Client, url: []const u8, payload: []const u8, auth_key: []const u8) bool {+ // Same gate as Telemetry.postOtlp: the terminal upload can run before the+ // shared client's CA-bundle prewarm has joined (finishAndClose is+ // registered after the prewarm-join defer), and an ungated fetch then+ // races the prewarm task on the shared client (#131).+ http.waitForClientReady(client.io);const auth_header = [_]std.http.Header{.{ .name = "x-harness-key", .value = auth_key }};const extra_headers: []const std.http.Header = if (auth_key.len > 0) &auth_header else &.{};const response = client.fetch(.{diff --git a/src/behavior_upload_tests.zig b/src/behavior_upload_tests.zigindex 86268712..0a3ed68e 100644--- a/src/behavior_upload_tests.zig+++ b/src/behavior_upload_tests.zig@@ -111,7 +111,10 @@ test "upload deadline synchronously cancels and joins a stalled POST" {try std.testing.expect(accepted.load(.acquire));try std.testing.expectEqual(SendResult.deadline, upload.last_send_result);try std.testing.expect(elapsed >= 100 * std.time.ns_per_ms);- try std.testing.expect(elapsed < 3 * std.time.ns_per_s);+ // Generous upper bound: the .deadline result and the 100ms lower bound+ // already prove the behavior; a tight wall-clock ceiling only buys CI+ // flakes on loaded runners.+ try std.testing.expect(elapsed < 30 * std.time.ns_per_s);}test "behavior POST sends the collector key and rejects non-success status" {diff --git a/src/main.zig b/src/main.zigindex 07a44b44..92998940 100644--- a/src/main.zig+++ b/src/main.zig@@ -462,6 +462,12 @@ pub fn main(init: std.process.Init) !void {var behavior_buf: [8 * 1024]u8 = undefined;var behavior_boot = behavior_trace.boot(io, gpa, &client, init.environ_map, telem.endpoint, telem.auth_key, telem.install_id, telem.client_name, harness_version, &behavior_buf);behavior_boot.link(&tracer);+ // A dead local sink must not be silent: the collision that disabled local+ // capture in every session shipped invisibly because every failure path+ // was a silent null (#246 review). stderr, so JSON/one-shot stdout stays+ // protocol-clean.+ if (behavior_boot.local_sink_failed)+ std.debug.print("warning: behavioral trace file could not be created under {s}; local capture is off for this run\n", .{behavior_dir});defer behavior_boot.finishAndClose(&tracer, .closed);// Registered after the normal defer so error unwinding records `error`// first; finish() is idempotent and keeps that status terminal.diff --git a/src/session_run.zig b/src/session_run.zigindex 564ba710..e81211b4 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -128,6 +128,10 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m// then emit/upload the terminal behavioral event.fleet.joinElites(io);jobs.jobsReap(gpa, io);+ // Mirror main's teardown fully: flush buffered OTLP telemetry too,+ // not just the behavioral batch, so a fatal one-shot is not invisible+ // in ordinary telemetry while visible in behavioral data.+ if (telemetry.g_telem) |t| t.flush();if (tracer.behavior) |behavior| behavior.finish(.failed);switch (err) {error.FallbackConsentRequired => std.process.fatal("saved model unavailable; provider '{s}' is not allowlisted — run graff interactively, then /fallback allow {s}", .{ root.provider.id, root.provider.id }),