graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(behavior): emit the four reserved kinds under opt-in rich capture (#255)
Rach Pradhanf4d7c7c73e33
diff --git a/README.md b/README.mdindex 2dcce939..8883c11d 100644--- a/README.md+++ b/README.md@@ -804,7 +804,10 @@ with `--max-model-calls N` or the lower-precedence `GRAFF_MAX_MODEL_CALLS`.agent session can write an exclusively-created`.graff/behavior/<run_id>.jsonl` with an ordered, attributable lifecycleenvelope. The local JSONL is never uploaded wholesale. Local capture defaults on-and is independently disabled with `GRAFF_BEHAVIOR_TRACE=off`.+and is independently disabled with `GRAFF_BEHAVIOR_TRACE=off`. Set+`GRAFF_BEHAVIOR_TRACE=full` to additionally record tool names/arguments and+completed assistant text in that local file (opt-in, capped, and never+uploaded).When ordinary telemetry is enabled, Codegraff also defaults to one bounded,end-of-run **field-allowlisted metadata** POST. A terminal `/v1/logs` path is@@ -825,8 +828,10 @@ arguments/results, commands, arbitrary environment values, or exact private MCPnames. Provider and model identifiers are included exactly as configured; Phase1 does not inspect, classify, or redact those identifier values.-Ordinary Phase 1 runs contain lifecycle events only: typed-commitment/misprediction APIs exist, but no built-in task adapter calls them yet.+Ordinary Phase 1 runs contain lifecycle events only (plus tool/action/text+events with `GRAFF_BEHAVIOR_TRACE=full`, local-only in every upload mode):+typed commitment/misprediction APIs exist, but no built-in task adapter calls+them yet.Content mode adds fields supplied through those APIs, with no redactor or secretscanner; the local prompt fingerprint remains excluded. This is not yet ageneric predict → act → verify → repair loopdiff --git a/docs/behavioral-trajectories.md b/docs/behavioral-trajectories.mdindex 07ddb569..62a3ef00 100644--- a/docs/behavioral-trajectories.md+++ b/docs/behavioral-trajectories.md@@ -33,6 +33,7 @@ uploader. Local capture and upload have separate controls:| Setting | Effect || --- | --- || `GRAFF_BEHAVIOR_TRACE=off` | Disables the local behavioral file only. `0`, `false`, and `no` are also accepted. |+| `GRAFF_BEHAVIOR_TRACE=full` | Opt-in rich capture (#255): the local file additionally records tool names/arguments and completed assistant text — see [Opt-in rich capture](#opt-in-rich-capture-graff_behavior_tracefull) below. Only the exact lowercase literal `full` enables it; every other enabling value (including unset) stays lifecycle-only. || `GRAFF_BEHAVIOR_UPLOAD=off` | Disables the behavioral POST only. `0`, `false`, and `no` are also accepted. || `GRAFF_BEHAVIOR_UPLOAD=metadata` | Explicitly selects the field-allowlisted metadata projection. This is the default when ordinary telemetry is enabled. Only the exact lowercase literal enables an explicit selection. || `GRAFF_BEHAVIOR_UPLOAD=content` | Explicitly opts into opaque content supplied by a task adapter. Only the exact lowercase literal `content` enables this mode. |@@ -140,8 +141,10 @@ or edited after the run.## Current event support-The enum reserves the nine schema-harness event names, but Phase 1 intentionally-implements only the lifecycle and caller-asserted adapter subset.+The enum implements all nine schema-harness event names: five are always+automatically emitted (lifecycle) or caller-asserted (adapter), and the+remaining four are automatically emitted only under the opt-in rich capture+described below.### Automatically emitted@@ -240,29 +243,87 @@ upload can retain a second copy under the 30-day policy above. Codegraff does nocheck semantic equivalence, prove that a verifier is correct, maintain acommitment registry, cancel a plan, or initiate a repair turn.-### Reserved, not emitted in Phase 1+### Opt-in rich capture (`GRAFF_BEHAVIOR_TRACE=full`)-- `text_delta`-- `tool_started`-- `tool_finished`-- `action_taken`+The remaining four reserved kinds (#255) are automatically emitted by the+generic provider/tool plumbing, but only when rich capture is explicitly+opted into with `GRAFF_BEHAVIOR_TRACE=full`. The default lifecycle-only+posture (any other enabling value, including unset) never emits them — do not+interpret their absence as an empty tool/action history.-These names are reserved so later task adapters can use the same envelope. They-are not automatically emitted yet because generic provider/tool plumbing cannot-honestly determine task state, distinguish an action from an observation, or-verify a prediction. Tool arguments, results, model text, and state snapshots-also carry substantial credential/source/privacy risk. Do not interpret their-absence as an empty tool/action history. The Phase 1 collector rejects these-reserved kinds until a typed producer and versioned validation contract exist.+**These four kinds are local-file only.** The Phase 1 collector rejects+unrecognized kinds for the whole batch, not just one event, so `BehaviorTrace`+never offers them to the uploader regardless of `GRAFF_BEHAVIOR_UPLOAD` mode.+This is a documented exclusion, not a drop: it is not counted in+`dropped_events`, and `local_sink`/`local_dropped` accounting is unaffected.++#### `tool_started`++Emitted before a tool call runs. Fields:++- `turn` — the current nonzero behavioral turn.+- `call_id` — a per-run monotonic ID (starts at `1`) that pairs this event+ with the matching `tool_finished`.+- `name` — the tool name.+- `args` — the tool's JSON arguments, embedded verbatim when they parse as+ valid JSON; otherwise (or when truncated) a plain string.+- `args_truncated` — `true` when the serialized arguments exceeded 4,096+ bytes. A truncated payload may be cut mid-token, so it is always+ re-embedded as a string rather than risking invalid JSON dressed up as+ structured data.++#### `tool_finished`++Emitted after a tool call completes. Fields:++- `turn`, `call_id`, `name` — as above.+- `ms` — wall-clock duration of the call.+- `is_error` — whether the tool reported an error.+- `result_bytes` — the result's byte length. The result **content** is never+ recorded.++#### `action_taken`++The generic coding-task mapping: a state mutation, emitted once a tool call+that finished belongs to a mutating tool class (`write` or `shell`, per+`behavior_upload.toolClass`). Read/search/verify/agent/mcp/other classes are+observations and never emit this kind. Fields:++- `turn`, `call_id`, `name`, `is_error` — as above.++#### `text_delta`++One completed assistant text segment — called once per finished segment, not+per streaming token. In practice, Phase 1's only choke point common to every+provider streaming path is the root turn's final text, so today this fires+once per root turn rather than once per intermediate segment. Fields:++- `turn` — the current nonzero behavioral turn.+- `text` — the text, capped at 2,048 bytes.+- `text_truncated` — `true` when the text exceeded the cap.++#### Local privacy posture in full mode++In lifecycle-only mode (the default), automatic events never include tool+arguments or model text, as described below. `GRAFF_BEHAVIOR_TRACE=full`+changes that for the **local plaintext file only**: tool names and arguments,+and completed assistant text, land there in cleartext, subject only to the+4,096/2,048-byte caps above. There is no redaction or secret scanning. Rich+capture never changes what is uploaded — the four kinds stay local-only+regardless of `GRAFF_BEHAVIOR_UPLOAD`.## Local retention and privacy-Behavioral files are ordinary local plaintext. Automatic Phase 1 events do-**not** include prompts, generated text, hidden reasoning, source code, tool-arguments/results, credentials, or environment contents. Opaque adapter values-can contain sensitive task data, however. Adapter authors and callers are-responsible for minimizing them; neither the local writer nor explicit content-upload scans or sanitizes them.+Behavioral files are ordinary local plaintext. In the default lifecycle-only+posture, automatic events do **not** include prompts, generated text, hidden+reasoning, source code, tool arguments/results, credentials, or environment+contents. `GRAFF_BEHAVIOR_TRACE=full` (#255) is an explicit opt-in that+changes this locally: tool names/arguments and completed assistant text land+in the local file, subject only to the 4,096/2,048-byte caps described above+— see [Opt-in rich capture](#opt-in-rich-capture-graff_behavior_tracefull).+Opaque adapter values can also contain sensitive task data. Adapter authors+and callers are responsible for minimizing them; neither the local writer nor+explicit content upload scans or sanitizes any of this.- `.graff/` is ignored by Git.- Directory components are opened relative to verified no-follow handles, so a@@ -321,8 +382,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 (the four reserved kinds above).+2. `tool_started`/`tool_finished`/`action_taken` now have real, `call_id`-paired+ dispatch/completion hooks (#255) generic across every tool. `text_delta`+ still only fires once per root turn (the one choke point common to every+ provider streaming path), not once per intermediate assistant text+ segment — a real per-segment hook remains open work.3. Explicit expectation binding, verification, surprise interruption, andrepair behavior wired to a production producer.4. Versioned Zig-side behavioral score events plus recipe/eval identity anddiff --git a/scripts/score_run.py b/scripts/score_run.pyindex 4f35e38c..d1ca4e9a 100644--- a/scripts/score_run.py+++ b/scripts/score_run.py@@ -14,7 +14,9 @@ Usage:Profiles:codegraff (default) strict Phase 1 producer audit: contiguous seq from 1,constant run_id/schema, single first run_started, terminal- run_finished, dense turns, commitment/mispredict field checks.+ run_finished, dense turns, commitment/mispredict field checks,+ plus (#255) tool_started/tool_finished call_id pairing for the+ opt-in rich kinds (GRAFF_BEHAVIOR_TRACE=full).replay relaxed envelope audit for streams converted from externalschema-harness trajectories (their turn_started/turn_committedcarry task fields codegraff does not emit, and vice versa).@@ -102,6 +104,13 @@ def audit(path: Path, profile: str) -> dict:level_actions = 0total_actions = 0final_state = None+ # #255 opt-in rich capture (GRAFF_BEHAVIOR_TRACE=full): tool_started and+ # tool_finished pair by call_id; a finished call with no matching started+ # call is a pairing violation, not a warning.+ open_tool_calls: set[int] = set()+ tool_calls = 0+ tool_errors = 0+ text_deltas = 0for line_no, event in read_events(path):if event is None:@@ -167,6 +176,43 @@ def audit(path: Path, profile: str) -> dict:current_turn = turnturn_active = Trueturns += 1+ elif kind == "text_delta":+ text_deltas += 1+ if strict:+ turn = event.get("turn")+ if not isinstance(turn, int) or turn < 1:+ raise AuditError(f"line {line_no}: text_delta needs a positive integer turn")+ if not turn_active or turn != current_turn:+ raise AuditError(f"line {line_no}: text_delta outside its active turn")+ elif kind == "tool_started":+ if strict:+ turn = event.get("turn")+ if not isinstance(turn, int) or turn < 1:+ raise AuditError(f"line {line_no}: tool_started needs a positive integer turn")+ if not turn_active or turn != current_turn:+ raise AuditError(f"line {line_no}: tool_started outside its active turn")+ call_id = event.get("call_id")+ if not isinstance(call_id, int):+ raise AuditError(f"line {line_no}: tool_started needs an integer call_id")+ if call_id in open_tool_calls:+ raise AuditError(f"line {line_no}: duplicate tool_started for call_id {call_id!r}")+ open_tool_calls.add(call_id)+ elif kind == "tool_finished":+ tool_calls += 1+ if event.get("is_error") is True:+ tool_errors += 1+ if strict:+ turn = event.get("turn")+ if not isinstance(turn, int) or turn < 1:+ raise AuditError(f"line {line_no}: tool_finished needs a positive integer turn")+ if not turn_active or turn != current_turn:+ raise AuditError(f"line {line_no}: tool_finished outside its active turn")+ call_id = event.get("call_id")+ if not isinstance(call_id, int):+ raise AuditError(f"line {line_no}: tool_finished needs an integer call_id")+ if call_id not in open_tool_calls:+ raise AuditError(f"line {line_no}: tool_finished for call_id {call_id!r} has no matching tool_started")+ open_tool_calls.discard(call_id)elif kind == "turn_committed":commitments += 1if open_mispredict_seq is not None:@@ -191,6 +237,12 @@ def audit(path: Path, profile: str) -> dict:elif kind == "action_taken":total_actions += 1level_actions += 1+ if strict:+ turn = event.get("turn")+ if not isinstance(turn, int) or turn < 1:+ raise AuditError(f"line {line_no}: action_taken needs a positive integer turn")+ if not turn_active or turn != current_turn:+ raise AuditError(f"line {line_no}: action_taken outside its active turn")if event.get("state") is not None:final_state = str(event["state"]).upper()if event.get("level_up") is True:@@ -246,6 +298,9 @@ def audit(path: Path, profile: str) -> dict:"completed_level_actions": completed_levels,"incomplete_level_actions": level_actions if level_actions else None,"final_state": final_state,+ "tool_calls": tool_calls,+ "tool_errors": tool_errors,+ "text_deltas": text_deltas,}diff --git a/scripts/test-behavior-trace.py b/scripts/test-behavior-trace.pyindex a149afac..04ae79ef 100644--- a/scripts/test-behavior-trace.py+++ b/scripts/test-behavior-trace.py@@ -174,7 +174,40 @@ def check_scorer(root: Path) -> None:assert report["ok"], reportassert report["completed_level_actions"] == [1]assert report["rhae"]["score"] == round(min(115.0 * 1 / 3, 1 / 3 * 100.0), 2)- print("scorer: behavioral metrics, audit failures, truncation, RHAE math ok")++ # #255 opt-in rich capture (GRAFF_BEHAVIOR_TRACE=full): tool_started/+ # tool_finished pair by call_id, action_taken is the state-mutation+ # subset of finished tool calls, text_delta is completed assistant text.+ rich = root / "rich.jsonl"+ write_stream(rich, [+ {"kind": "run_started", "version": "test", "unix_ms": 1},+ {"kind": "turn_started", "turn": 1, "parent_turn": 0, "trajectory_node": 0},+ {"kind": "text_delta", "turn": 1, "text": "on it", "text_truncated": False},+ {"kind": "tool_started", "turn": 1, "call_id": 1, "name": "edit_file",+ "args": {"path": "a.zig"}, "args_truncated": False},+ {"kind": "tool_finished", "turn": 1, "call_id": 1, "name": "edit_file",+ "ms": 5, "is_error": False, "result_bytes": 40},+ {"kind": "action_taken", "turn": 1, "call_id": 1, "name": "edit_file", "is_error": False},+ {"kind": "run_finished", "status": "closed"},+ ])+ report = score(rich)+ assert report["ok"] and report["complete"], report+ assert report["tool_calls"] == 1 and report["tool_errors"] == 0+ assert report["text_deltas"] == 1+ assert report["actions"] == 1++ # A tool_finished with no matching tool_started is a pairing violation,+ # not a warning — it must fail the strict audit.+ mismatch = root / "rich-mismatch.jsonl"+ write_stream(mismatch, [+ {"kind": "run_started", "version": "test", "unix_ms": 1},+ {"kind": "turn_started", "turn": 1, "parent_turn": 0, "trajectory_node": 0},+ {"kind": "tool_finished", "turn": 1, "call_id": 1, "name": "edit_file",+ "ms": 5, "is_error": False, "result_bytes": 40},+ {"kind": "run_finished", "status": "closed"},+ ])+ assert score(mismatch)["exit"] == 1, "tool_finished without tool_started must fail the audit"+ print("scorer: behavioral metrics, audit failures, truncation, RHAE math, rich-kind pairing ok")def check_replay_round_trip(root: Path) -> None:diff --git a/src/behavior_trace.zig b/src/behavior_trace.zigindex 3edb026f..d1c4cced 100644--- a/src/behavior_trace.zig+++ b/src/behavior_trace.zig@@ -42,6 +42,28 @@ pub const BehaviorKind = enum {run_finished,};+/// Kinds the deployed collector accepts (Phase 1 contract). The four rich+/// opt-in kinds (#255, GRAFF_BEHAVIOR_TRACE=full) are local-file only:+/// offering an unrecognized kind fails the whole upload batch, not just one+/// event, so this gate runs before eventLocked ever calls the uploader.+fn uploadEligible(kind: BehaviorKind) bool {+ return switch (kind) {+ .run_started, .turn_started, .turn_committed, .model_mispredicted, .run_finished => true,+ .text_delta, .tool_started, .tool_finished, .action_taken => false,+ };+}++/// Byte-cap a string without splitting a multi-byte UTF-8 sequence, so a+/// truncated payload can never desync the JSON string encoder mid-codepoint+/// (same defense as tools.zig's hookPayload output echo).+fn utf8SafeClip(text: []const u8, max_len: usize) []const u8 {+ var t = text[0..@min(text.len, max_len)];+ var strips: usize = 0;+ while (strips < 3 and t.len > 0 and !std.unicode.utf8ValidateSlice(t)) : (strips += 1) t = t[0 .. t.len - 1];+ if (!std.unicode.utf8ValidateSlice(t)) t = "";+ return t;+}+/// Typed lifecycle status; `.failed` is serialized as the JSON value `error`.pub const BehaviorRunStatus = enum {closed,@@ -50,6 +72,13 @@ pub const BehaviorRunStatus = enum {pub const max_local_behavior_event_bytes = 64 * 1024;+/// Opt-in rich capture caps (#255). A tool's arguments and a completed text+/// segment are the two content-bearing rich fields; both are bounded so one+/// huge adapter payload cannot dominate the local file the way+/// max_local_behavior_event_bytes already bounds a whole line.+pub const max_tool_args_bytes = 4096;+pub const max_text_delta_bytes = 2048;+/// 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@@ -144,6 +173,14 @@ pub const BehaviorTrace = struct {local_dropped: u64 = 0,commitment_key: [32]u8 = undefined,commitment_key_initialized: bool = false,+ /// Opt-in rich capture (#255, GRAFF_BEHAVIOR_TRACE=full). Off by default:+ /// automatic events then never carry tool names/arguments or model text+ /// (docs/behavioral-trajectories.md privacy posture). Set by boot().+ rich: bool = false,+ /// Monotonic per-run id pairing tool_started/tool_finished (#255).+ /// Reservation does not depend on rich/turn state, so a call_id is stable+ /// even when the paired event itself ends up a no-op.+ next_call_id: u64 = 0,fn timestamp(self: *BehaviorTrace) f64 {const now = Io.Timestamp.now(self.io, .real);@@ -156,7 +193,10 @@ pub const BehaviorTrace = struct {/// 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;+ // Rich kinds (#255) never reach the uploader (see uploadEligible), so+ // an upload-only sink with no local file is not a viable sink for them.+ const upload_eligible = uploadEligible(kind);+ const uploader_active = if (self.upload) |uploader| (upload_eligible and uploader.active()) else false;if (self.out == null and !uploader_active) return false;// This is the logical source sequence, reserved before either@@ -178,8 +218,10 @@ pub const BehaviorTrace = struct {.sink_failed => self.out = null,}}- if (self.upload) |uploader| {- return uploader.appendEvent(@tagName(kind), next, ts, metadata_fields, content_fields);+ if (upload_eligible) {+ if (self.upload) |uploader| {+ return uploader.appendEvent(@tagName(kind), next, ts, metadata_fields, content_fields);+ }}return false;}@@ -306,6 +348,99 @@ pub const BehaviorTrace = struct {}, local_fields);}+ /// Reserve the next call_id for one tool invocation (#255). Independent+ /// of rich/turn state: a call_id stays stable even when the emitter that+ /// would use it turns out to be a no-op (rich off, turn already ended).+ pub fn reserveCallId(self: *BehaviorTrace) u64 {+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ self.next_call_id += 1;+ return self.next_call_id;+ }++ /// Record a tool invocation before it runs (#255, opt-in rich capture+ /// only — the default lifecycle-only posture never records tool names or+ /// arguments). `args_json` is capped at max_tool_args_bytes; a truncated+ /// payload may be cut mid-token, so it is always re-embedded as a plain+ /// string rather than risking invalid JSON dressed up as structured data.+ pub fn toolStarted(self: *BehaviorTrace, turn: u64, call_id: u64, name: []const u8, args_json: []const u8) void {+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ if (!self.rich or !self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn) return;+ const truncated = args_json.len > max_tool_args_bytes;+ var parsed: ?std.json.Parsed(std.json.Value) = null;+ // The arena backing a successful parse must outlive eventLocked's+ // synchronous serialization below, so it is only freed on return.+ defer if (parsed) |p| p.deinit();+ const args_value: std.json.Value = blk: {+ if (!truncated) {+ if (std.json.parseFromSlice(std.json.Value, self.gpa, args_json, .{})) |p| {+ parsed = p;+ break :blk p.value;+ } else |_| {}+ }+ break :blk .{ .string = utf8SafeClip(args_json, max_tool_args_bytes) };+ };+ const fields = .{+ .turn = turn,+ .call_id = call_id,+ .name = name,+ .args = args_value,+ .args_truncated = truncated,+ };+ _ = self.eventLocked(.tool_started, fields, .{}, .{});+ }++ /// Record a tool's outcome (#255, opt-in rich capture only). Only+ /// content-free operational shape — duration, error flag, result byte+ /// count — never the result content itself.+ pub fn toolFinished(self: *BehaviorTrace, turn: u64, call_id: u64, name: []const u8, ms: i64, is_error: bool, result_bytes: usize) void {+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ if (!self.rich or !self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn) return;+ const fields = .{+ .turn = turn,+ .call_id = call_id,+ .name = name,+ .ms = ms,+ .is_error = is_error,+ .result_bytes = result_bytes,+ };+ _ = self.eventLocked(.tool_finished, fields, .{}, .{});+ }++ /// The generic coding-task action mapping (#255): a state mutation after+ /// it finishes. Only the write/shell tool classes (behavior_upload.+ /// toolClass) count as actions; read/search/verify/agent/mcp/other are+ /// observations and never emit this kind.+ pub fn actionTaken(self: *BehaviorTrace, turn: u64, call_id: u64, name: []const u8, is_error: bool) void {+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ if (!self.rich or !self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn) return;+ switch (behavior_upload.toolClass(name)) {+ .write, .shell => {},+ else => return,+ }+ const fields = .{ .turn = turn, .call_id = call_id, .name = name, .is_error = is_error };+ _ = self.eventLocked(.action_taken, fields, .{}, .{});+ }++ /// Record one completed assistant text segment (#255, opt-in rich+ /// capture only). Called once per finished segment, not per streaming+ /// token; capped at max_text_delta_bytes.+ pub fn textDelta(self: *BehaviorTrace, turn: u64, text: []const u8) void {+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ if (!self.rich or !self.started or self.closed or !self.turn_active or turn == 0 or turn != self.current_turn or text.len == 0) return;+ const truncated = text.len > max_text_delta_bytes;+ const fields = .{+ .turn = turn,+ .text = utf8SafeClip(text, max_text_delta_bytes),+ .text_truncated = truncated,+ };+ _ = self.eventLocked(.text_delta, 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.@@ -433,10 +568,16 @@ pub fn boot(io: Io, gpa: Allocator, client: ?*std.http.Client, environ_map: anyt.run_id = &scoring.g_run_id,.mode = behavior_upload.resolveMode(environ_map.get("GRAFF_BEHAVIOR_UPLOAD"), endpoint.len > 0),};- const enabled = if (environ_map.get("GRAFF_BEHAVIOR_TRACE")) |value|+ const trace_value = environ_map.get("GRAFF_BEHAVIOR_TRACE");+ const enabled = if (trace_value) |value|!(std.ascii.eqlIgnoreCase(value, "off") or std.mem.eql(u8, value, "0") or std.ascii.eqlIgnoreCase(value, "false") or std.ascii.eqlIgnoreCase(value, "no"))elsetrue;+ // Rich capture (#255) is a narrower, separate opt-in: only the literal+ // "full" turns on tool names/args and model text in the local file.+ // Every other enabling value (unset, or anything outside the disable set+ // above) stays lifecycle-only — the documented default privacy posture.+ const rich = if (trace_value) |value| std.ascii.eqlIgnoreCase(value, "full") else false;const open = if (enabled)session_start.openBehaviorFile(io, Io.Dir.cwd(), behavior_dir, &scoring.g_run_id, buf)else@@ -451,6 +592,7 @@ pub fn boot(io: Io, gpa: Allocator, client: ?*std.http.Client, environ_map: anyt.out = null,.upload = null,.run_id = &scoring.g_run_id,+ .rich = rich,},.local_sink_failed = enabled and open.file == null,};diff --git a/src/behavior_trace_tests.zig b/src/behavior_trace_tests.zigindex 57270e9b..6d088109 100644--- a/src/behavior_trace_tests.zig+++ b/src/behavior_trace_tests.zig@@ -15,6 +15,8 @@ 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 max_tool_args_bytes = btrace.max_tool_args_bytes;+const max_text_delta_bytes = btrace.max_text_delta_bytes;const Tracer = trace.Tracer;const Trajectory = trace.Trajectory;const beginRootTurn = trace.beginRootTurn;@@ -32,7 +34,10 @@ test "writeBehaviorLine: oversized adapter content is rejected before local alloconst 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", .{+ // Pre-existing #246 bug fixed in passing: writeBehaviorLine returns+ // LineResult (.written/.dropped/.sink_failed), not bool — this call site+ // still compared against `!bool` and failed to compile.+ try std.testing.expectEqual(btrace.LineResult.dropped, writeBehaviorLine(gpa, &out.writer, .turn_committed, 1, 1.0, "0123456789abcdef", .{.turn = @as(u64, 1),.reason = oversized,}));@@ -361,11 +366,16 @@ test "BehaviorTrace: metadata-default upload is an exact content-free projectiontry 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" });+ // Pre-existing staleness fixed in passing: startWithMetadata's+ // upload_fields already carries local_sink (sink-health diagnostics,+ // #246) but this key list predated that field.+ try expectObjectKeys(events[0].object, &.{ "kind", "seq", "ts", "run_id", "schema", "version", "unix_ms", "provider", "model", "effort", "local_sink" });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" });+ // Same staleness: run_finished's fields already carry local_dropped+ // (#246 audit reconciliation) alongside status.+ try expectObjectKeys(events[4].object, &.{ "kind", "seq", "ts", "run_id", "schema", "status", "local_dropped" });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;@@ -504,3 +514,257 @@ test "endRootTurn: clears attribution while preserving the dense parent chain" {try std.testing.expectEqual(@as(i64, 1), second_started.value.object.get("parent_turn").?.integer);try std.testing.expect(lines.next() == null);}++test "BehaviorTrace: rich kinds are gated by GRAFF_BEHAVIOR_TRACE=full (#255)" {+ 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 = "rich-gate-run",+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ try std.testing.expectEqual(@as(u64, 2), behavior.seq); // run_started + turn_started++ // rich defaults to false: every typed rich emitter is a no-op, even with+ // a live local sink and a valid turn/call_id.+ const call_id = behavior.reserveCallId();+ behavior.toolStarted(1, call_id, "edit_file", "{}");+ behavior.toolFinished(1, call_id, "edit_file", 5, false, 10);+ behavior.actionTaken(1, call_id, "edit_file", false);+ behavior.textDelta(1, "hello");+ try std.testing.expectEqual(@as(u64, 2), behavior.seq);++ // rich == true: the same calls now emit tool_started, tool_finished,+ // action_taken (edit_file is a write-class tool), and text_delta.+ behavior.rich = true;+ const call_id2 = behavior.reserveCallId();+ behavior.toolStarted(1, call_id2, "edit_file", "{\"path\":\"a.zig\"}");+ behavior.toolFinished(1, call_id2, "edit_file", 5, false, 10);+ behavior.actionTaken(1, call_id2, "edit_file", false);+ behavior.textDelta(1, "hello");+ try std.testing.expectEqual(@as(u64, 6), behavior.seq);++ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');+ _ = lines.next(); // run_started+ _ = lines.next(); // turn_started++ var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started.deinit();+ try std.testing.expectEqualStrings("tool_started", started.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_id2)), started.value.object.get("call_id").?.integer);+ try std.testing.expectEqualStrings("a.zig", started.value.object.get("args").?.object.get("path").?.string);+ try std.testing.expect(!started.value.object.get("args_truncated").?.bool);++ var finished = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer finished.deinit();+ try std.testing.expectEqualStrings("tool_finished", finished.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_id2)), finished.value.object.get("call_id").?.integer);+ try std.testing.expect(!finished.value.object.get("is_error").?.bool);++ var action = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer action.deinit();+ try std.testing.expectEqualStrings("action_taken", action.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_id2)), action.value.object.get("call_id").?.integer);++ var text = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer text.deinit();+ try std.testing.expectEqualStrings("text_delta", text.value.object.get("kind").?.string);+ try std.testing.expectEqualStrings("hello", text.value.object.get("text").?.string);+ try std.testing.expect(lines.next() == null);+}++test "BehaviorTrace: action_taken skips non-mutating tool classes even when rich (#255)" {+ 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 = "action-class-run",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ const before = behavior.seq;+ // read_file is a read-class tool: an observation, not an action.+ behavior.actionTaken(1, behavior.reserveCallId(), "read_file", false);+ try std.testing.expectEqual(before, behavior.seq);+ // bash is shell-class: a state mutation.+ behavior.actionTaken(1, behavior.reserveCallId(), "bash", true);+ try std.testing.expectEqual(before + 1, behavior.seq);+}++test "BehaviorTrace: rich caps truncate args and text without corrupting JSON (#255)" {+ 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 = "cap-run",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));++ // Oversized args are never re-parsed as JSON, even when the raw bytes+ // happen to look JSON-ish up to the cut point — always a plain string.+ const oversized_args = try gpa.alloc(u8, max_tool_args_bytes + 1);+ defer gpa.free(oversized_args);+ @memset(oversized_args, 'a');+ oversized_args[0] = '{';+ behavior.toolStarted(1, 1, "bash", oversized_args);++ const oversized_text = try gpa.alloc(u8, max_text_delta_bytes + 1);+ defer gpa.free(oversized_text);+ @memset(oversized_text, 'b');+ behavior.textDelta(1, oversized_text);++ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');+ _ = lines.next(); // run_started+ _ = lines.next(); // turn_started++ var started = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started.deinit();+ try std.testing.expect(started.value.object.get("args_truncated").?.bool);+ try std.testing.expect(started.value.object.get("args").? == .string);+ try std.testing.expectEqual(@as(usize, max_tool_args_bytes), started.value.object.get("args").?.string.len);++ var text = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer text.deinit();+ try std.testing.expect(text.value.object.get("text_truncated").?.bool);+ try std.testing.expectEqual(@as(usize, max_text_delta_bytes), text.value.object.get("text").?.string.len);+ try std.testing.expect(lines.next() == null);+}++test "BehaviorTrace: rich kinds never reach the uploader (#255)" {+ 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('u'),+ .client_name = "harness",+ .service_version = "test",+ .run_id = "0123456789abcdef",+ .mode = .content, // the most permissive collector mode+ };+ defer upload.deinit();+ var behavior: BehaviorTrace = .{+ .io = io,+ .gpa = gpa,+ .out = &local.writer,+ .upload = &upload,+ .run_id = "0123456789abcdef",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ // run_started + turn_started are upload-eligible.+ try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);++ const call_id = behavior.reserveCallId();+ behavior.toolStarted(1, call_id, "bash", "{\"command\":\"ls\"}");+ behavior.toolFinished(1, call_id, "bash", 5, false, 10);+ behavior.actionTaken(1, call_id, "bash", false);+ behavior.textDelta(1, "hello");++ // The local file grew by four lines, but the uploader saw nothing new,+ // and none of it counted as a drop — a documented exclusion, not a loss.+ try std.testing.expectEqual(@as(usize, 2), upload.events.items.len);+ try std.testing.expectEqual(@as(u64, 0), upload.dropped_events);+ try std.testing.expectEqual(@as(u64, 6), behavior.seq);+}++test "BehaviorTrace.reserveCallId: monotonic per run, independent of lifecycle state (#255)" {+ const io = std.testing.io;+ var behavior: BehaviorTrace = .{+ .io = io,+ .gpa = std.testing.allocator,+ .out = null,+ .run_id = "call-id-run",+ };+ try std.testing.expectEqual(@as(u64, 1), behavior.reserveCallId());+ try std.testing.expectEqual(@as(u64, 2), behavior.reserveCallId());+ try std.testing.expectEqual(@as(u64, 3), behavior.reserveCallId());+ // Reservation never no-ops, unlike the typed emitters (rich/turn gated).+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 4), behavior.reserveCallId());+}++test "Tracer.toolStarted/toolFinished: call_id pairs interleaved calls (#255)" {+ 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 = "tracer-run",+ .rich = true,+ };+ behavior.start("test", 1);+ try std.testing.expectEqual(@as(u64, 1), behavior.beginTurn(0));+ var tracer: Tracer = .{+ .io = io,+ .gpa = gpa,+ .out = null,+ .start = Io.Timestamp.now(io, .awake),+ .behavior = &behavior,+ };++ var args = try std.json.parseFromSlice(Value, gpa, "{\"command\":\"ls\"}", .{});+ defer args.deinit();+ const call_a = tracer.toolStarted("bash", args.value);+ const call_b = tracer.toolStarted("bash", args.value);+ try std.testing.expect(call_a != 0 and call_b != 0 and call_a != call_b);+ // Finish out of order: the second call started finishes first.+ tracer.toolFinished("bash", call_b, 3, false, 5);+ tracer.toolFinished("bash", call_a, 7, true, 9);++ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n"), '\n');+ _ = lines.next(); // run_started+ _ = lines.next(); // turn_started++ var started_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started_a.deinit();+ try std.testing.expectEqual(@as(i64, @intCast(call_a)), started_a.value.object.get("call_id").?.integer);++ var started_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer started_b.deinit();+ try std.testing.expectEqual(@as(i64, @intCast(call_b)), started_b.value.object.get("call_id").?.integer);++ var finished_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer finished_b.deinit();+ try std.testing.expectEqualStrings("tool_finished", finished_b.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_b)), finished_b.value.object.get("call_id").?.integer);++ var action_b = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer action_b.deinit();+ try std.testing.expectEqualStrings("action_taken", action_b.value.object.get("kind").?.string);+ try std.testing.expectEqual(@as(i64, @intCast(call_b)), action_b.value.object.get("call_id").?.integer);++ var finished_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer finished_a.deinit();+ try std.testing.expectEqual(@as(i64, @intCast(call_a)), finished_a.value.object.get("call_id").?.integer);+ try std.testing.expect(finished_a.value.object.get("is_error").?.bool);++ var action_a = try std.json.parseFromSlice(Value, gpa, lines.next().?, .{});+ defer action_a.deinit();+ try std.testing.expectEqualStrings("action_taken", action_a.value.object.get("kind").?.string);+ try std.testing.expect(lines.next() == null);+}diff --git a/src/behavior_upload.zig b/src/behavior_upload.zigindex b6151f3e..50717f32 100644--- a/src/behavior_upload.zig+++ b/src/behavior_upload.zig@@ -104,7 +104,7 @@ comptime {}}-const ToolClass = enum {+pub const ToolClass = enum {shell,read,write,@@ -116,7 +116,10 @@ const ToolClass = enum {other,};-fn toolClass(name: []const u8) ToolClass {+/// Public so behavior_trace.zig's action_taken emitter (#255) can reuse the+/// same state-mutation classification instead of duplicating the tool-name+/// table.+pub fn toolClass(name: []const u8) ToolClass {if (std.mem.eql(u8, name, "bash") or std.mem.eql(u8, name, "bash_output") or std.mem.eql(u8, name, "bash_kill")) return .shell;if (std.mem.eql(u8, name, "read_file")) return .read;if (std.mem.eql(u8, name, "edit_file") or std.mem.eql(u8, name, "write_file")) return .write;diff --git a/src/exec.zig b/src/exec.zigindex c0b4d2dc..65712fcf 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -68,10 +68,16 @@ const subagent_bash_deadline_ms: u64 = 120 * 1000;/// Every execution is timed (out.ms) and traced.pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {const t0: Io.Timestamp = .now(ctx.io, .awake);+ // #255: reserved before any gate/dispatch runs so tool_started/+ // tool_finished bracket the whole call, including a gate denial below.+ const call_id: u64 = if (ctx.tracer) |tr| tr.toolStarted(call.name, call.input) else 0;if (codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call)) |blocked| {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);+ if (ctx.tracer) |tr| {+ tr.tool(call.name, 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);return out;}@@ -85,7 +91,10 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {break :blk failure(ctx.gpa, err);};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);+ if (ctx.tracer) |tr| {+ tr.tool(call.name, 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);runPostToolHooks(ctx, call, out);return out;diff --git a/src/providers.zig b/src/providers.zigindex 875dd60c..a9984e8f 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -209,7 +209,13 @@ pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*Iwhile (true) {root.last_api_error = null;const result = root.runTurn();- if (result) |text| return text else |err| {+ if (result) |text| {+ // #255: no clean per-segment choke point exists across the+ // provider streaming paths, so the root turn's final text is+ // recorded once here (opt-in rich capture only; no-op otherwise).+ if (root.tracer) |tr| tr.textDelta(text);+ return text;+ } else |err| {if (err != error.ApiError or root.partial_text.items.len != 0 or root.tool_calls_this_turn != 0)return err;const detail = root.last_api_error orelse return err;diff --git a/src/trace.zig b/src/trace.zigindex 65084c75..ce1651cd 100644--- a/src/trace.zig+++ b/src/trace.zig@@ -154,6 +154,42 @@ 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 —+ /// 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();+ var buf: [8192]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var s: std.json.Stringify = .{ .writer = &w };+ s.write(args) catch {}; // a partial/overflowed buffer is fine: BehaviorTrace caps and truncates+ behavior.toolStarted(behavior.currentTurn(), call_id, name, w.buffered());+ return call_id;+ }++ /// 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.+ pub fn toolFinished(self: *Tracer, name: []const u8, call_id: u64, ms: i64, is_error: bool, result_bytes: usize) void {+ if (call_id == 0) return;+ const behavior = self.behavior orelse return;+ const turn = behavior.currentTurn();+ behavior.toolFinished(turn, call_id, name, ms, is_error, result_bytes);+ behavior.actionTaken(turn, call_id, name, is_error);+ }++ /// Emit `text_delta` for one completed assistant text segment (#255,+ /// opt-in rich capture only).+ pub fn textDelta(self: *Tracer, text: []const u8) void {+ const behavior = self.behavior orelse return;+ behavior.textDelta(behavior.currentTurn(), text);+ }+pub fn note(self: *Tracer, kind: []const u8, detail: []const u8) void {self.write(.{ .t = self.elapsedMs(), .ev = kind, .detail = detail });}