graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(prompt): defer the #410 transcript line to the first compaction
Rach Pradhanc2f64407807f
diff --git a/src/agent_compact.zig b/src/agent_compact.zigindex 22170b3d..bf08754f 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -206,6 +206,13 @@ pub fn compact(self: *Agent) anyerror!usize {self.goal_note_fp = 0; // the injected goal note died with the old history - re-state in full (#318)self.history_rewrites +%= 1; // readers of pasted state (the /loop checklist gate) re-carry it (#318)installed_summary = true;+ // #445: the history the model was reading is gone and the durable file is+ // now the only place its exact wording survives, so THIS is where the #410+ // transcript line starts being worth its tokens. It rides this boundary+ // deliberately: the rewrite above already invalidated the provider's cached+ // prefix, so mutating the system prompt here costs nothing extra. Root-only+ // and once per session — prompts.noteSessionCompacted owns both rules.+ prompts.noteSessionCompacted(self, self.arena);if (!main_mod.json_mode) try self.say("[history compacted to a {d}-char summary]\n", .{summary.len});return summary.len;}@@ -553,6 +560,12 @@ pub fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {if (dropped > 0) {self.compact_transport_failures = 0;self.compact_summary_failures = 0;+ // #445: a trim is the harsher half of the same boundary — the model+ // lost that history WITHOUT even a summary standing in for it, so+ // the transcript line is worth more here, not less. Hooked at this+ // call site rather than inside emergencyTrim() because the direct+ // emergencyTrim callers drive partially-initialized test agents.+ prompts.noteSessionCompacted(self, self.arena);if (main_mod.json_mode)self.emit(.{ .type = "compact", .ok = true, .trimmed = dropped })elsediff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zigindex 8249512c..829afea8 100644--- a/src/prompt_snapshot_tests.zig+++ b/src/prompt_snapshot_tests.zig@@ -284,9 +284,10 @@ test "#410: the transcript line rides the funnel, so a persona swap cannot dropdefer a_state.deinit();const a = a_state.allocator();var agent: agent_mod.Agent = undefined;- defer prompts.armSessionTranscript(a, "", .{}); // leave the global as the rest of the suite expects it+ defer prompts.armSessionTranscript(a, "", .{}, false); // leave the global as the rest of the suite expects it- prompts.armSessionTranscript(a, "session-42", .{});+ // Armed as #445 arms it in production: after the first compaction.+ prompts.armSessionTranscript(a, "session-42", .{}, true);try prompts.setSystemPrompts(&agent, "BASE", a);for ([_][]const u8{ agent.sys_normal, agent.sys_strict, agent.sys_ultra, agent.sys_ultra_strict }) |v| {try std.testing.expect(std.mem.indexOf(u8, v, "BASE") != null);@@ -300,12 +301,70 @@ test "#410: the transcript line rides the funnel, so a persona swap cannot droptry std.testing.expectEqualStrings("PERSONA", agent.sys_base);try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, agent.sys_normal, "session-42.session.json"));- // Unreadable session file (#330 removed read_file/bash): no line at all.- prompts.armSessionTranscript(a, "session-42", .{ .local_tools = false });+ // Unreadable session file (#330 removed read_file/bash): no line at all,+ // compacted or not — the capability half of the gate is independent.+ prompts.armSessionTranscript(a, "session-42", .{ .local_tools = false }, true);try prompts.setSystemPrompts(&agent, "BASE", a);try std.testing.expectEqualStrings("BASE", agent.sys_normal);}+// #445: the measured cost of the #421/#410 prompt additions was ~240 input+// tokens on EVERY call, and the transcript line's share of it buys nothing+// until the live window stops being a superset of the file it names. So the+// line is deferred to the first compaction, and this pins both ends of that:+// absent on a fresh session, present once the boundary has been crossed.+test "#445: the transcript line is absent until the first compaction, then rides every variant" {+ var a_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer a_state.deinit();+ const a = a_state.allocator();+ const saved = prompts.g_session_compacted;+ defer prompts.g_session_compacted = saved;+ defer prompts.armSessionTranscript(a, "", .{}, false); // leave the global as the rest of the suite expects it++ var agent: agent_mod.Agent = undefined;+ agent.sub = false;+ agent.session_name = "session-445";+ prompts.g_session_compacted = false;++ // A fresh session: setRootSystemPrompts arms with the flag as it stands,+ // so every variant is exactly the base and the session pays nothing.+ prompts.armSessionTranscript(a, agent.session_name, .{}, prompts.g_session_compacted);+ try prompts.setSystemPrompts(&agent, "BASE", a);+ try std.testing.expectEqualStrings("BASE", agent.sys_normal);+ for ([_][]const u8{ agent.sys_normal, agent.sys_strict, agent.sys_ultra, agent.sys_ultra_strict }) |v|+ try std.testing.expect(std.mem.indexOf(u8, v, "session-445.session.json") == null);++ // The compaction boundary re-derives all four, in place, from sys_base.+ prompts.noteSessionCompacted(&agent, a);+ try std.testing.expect(prompts.g_session_compacted);+ for ([_][]const u8{ agent.sys_normal, agent.sys_strict, agent.sys_ultra, agent.sys_ultra_strict }) |v| {+ try std.testing.expect(std.mem.indexOf(u8, v, "BASE") != null);+ try std.testing.expect(std.mem.indexOf(u8, v, "session-445.session.json") != null);+ }+ try std.testing.expectEqualStrings("BASE", agent.sys_base); // still the pure base++ // Idempotent: a session that compacts ten times still carries ONE line.+ prompts.noteSessionCompacted(&agent, a);+ prompts.noteSessionCompacted(&agent, a);+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, agent.sys_normal, "session-445.session.json"));+ // And a later persona swap keeps it — the #326 staleness class stays closed.+ try prompts.setSystemPrompts(&agent, "PERSONA", a);+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "session-445.session.json") != null);++ // A compacting SUBAGENT has no durable session of its own, and must not+ // spend the root's tokens on a line about a file it never wrote.+ prompts.g_session_compacted = false;+ prompts.armSessionTranscript(a, "", .{}, false);+ var child: agent_mod.Agent = undefined;+ child.sub = true;+ child.session_name = "session-child";+ child.sys_base = "CHILD-BASE";+ prompts.noteSessionCompacted(&child, a);+ try std.testing.expect(!prompts.g_session_compacted);+ try prompts.setSystemPrompts(&child, "CHILD-BASE", a);+ try std.testing.expectEqualStrings("CHILD-BASE", child.sys_normal);+}+test "#421: MCP, skill and optional-tool guidance all cost zero when absent" {var a_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer a_state.deinit();diff --git a/src/prompts.zig b/src/prompts.zigindex 9e768059..2f8239e4 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -21,6 +21,10 @@//! #410: setRootSystemPrompts also composes the one line naming this session's//! durable transcript. It rides in the funnel, not at the call site, so a//! persona swap or a `set_system_prompt` cannot silently drop it.+//!+//! #445: ...but not from turn one. That line only helps a model recover+//! wording the live window no longer holds, so it waits for the first+//! compaction and rides that boundary — see transcriptLineWanted below.const std = @import("std");const Io = std.Io;@@ -152,6 +156,12 @@ pub fn baseForSession(arena: Allocator) ![]const u8 {/// unit test — the same arming discipline playbook.g_root_inject uses.var g_transcript_note: []const u8 = "";+/// #445: has THIS process's root session compacted at least once? False at+/// startup, set once by noteSessionCompacted, never lowered again. Public only+/// so a test can save and restore it, exactly like playbook.g_root_inject —+/// noteSessionCompacted is the sole production writer.+pub var g_session_compacted: bool = false;+/// One line naming the durable transcript. Deliberately NOT described as/// JSONL: `.graff/sessions/<name>.session.json` is a single JSON object (the/// JSONL files are the `.graff/traces` event streams the paragraph above@@ -242,16 +252,65 @@ pub fn setRootSystemPrompts(agent: *Agent, base: []const u8, arena: Allocator) !// #410: only the root has a durable session, and only a session file this// process can still open is worth a line of context — with the native file// and shell tools removed (#330) the path is unreadable from here.- armSessionTranscript(arena, agent.session_name, detectCaps());+ // #445: and a session that has not compacted yet gets nothing at all. A+ // RESUMED session starts false too: the earlier compactions belong to a+ // dead process, and what that process left in the file is exactly the+ // context this one loaded, so the line would again describe what is here.+ armSessionTranscript(arena, agent.session_name, detectCaps(), g_session_compacted);return setSystemPrompts(agent, base, arena);}/// #410's arming step, split out so the funnel is testable without the/// filesystem read setRootSystemPrompts also performs (playbook.composeRoot).-/// An empty `session_name`, or a session whose file this process can no longer-/// open, both arm to "" — the line is only worth context when it is actionable.-pub fn armSessionTranscript(arena: Allocator, session_name: []const u8, caps: Caps) void {- g_transcript_note = if (caps.local_tools) sessionTranscriptNote(arena, session_name) else "";+/// An empty `session_name`, a session whose file this process cannot open, and+/// a session that has not compacted yet all arm to "" — the line is only worth+/// context when it is both actionable and not already redundant.+pub fn armSessionTranscript(arena: Allocator, session_name: []const u8, caps: Caps, compacted: bool) void {+ g_transcript_note = if (transcriptLineWanted(caps, compacted)) sessionTranscriptNote(arena, session_name) else "";+}++/// #445: the transcript line's gate, in one predicate, ANDing two conditions+/// that are different in kind and neither of which is sufficient alone:+///+/// - `caps.local_tools` is a CAPABILITY, read from the same catalog every+/// other segment gate is read from: with #330's native file and shell+/// tools removed, nothing in the session can open the path the line names.+/// - `compacted` is session STATE, and it is why this predicate exists.+/// Before the first compaction the live context is a SUPERSET of the+/// transcript file — the line can only point the model at wording it can+/// already see, and compaction rewrites the file in place anyway, so its+/// marginal value there is ~zero. Live A/B evals put the #421/#410 prompt+/// additions at +960 chars ≈ +240 input tokens on every single call at+/// full capability, which the overwhelming majority of sessions (the ones+/// that never compact at all) were paying for nothing. After a compaction+/// the file holds wording the window no longer does: the case #410 is for.+///+/// Deliberately NOT a `Caps` field. `Caps` is what the tool catalog reports,+/// and `detectCaps()` is settled before startup.buildSystemPrompt runs; this+/// flips mid-session, by definition after the first request. Folding it in+/// would make both of those statements false, and would put a non-segment+/// condition into the predicate `composeBase`/`full()` short-circuit on.+pub fn transcriptLineWanted(caps: Caps, compacted: bool) bool {+ return caps.has(.local_tools) and compacted;+}++/// #445: the compaction boundary — the one moment the line starts earning its+/// tokens, and the one moment mutating the system prompt is free. Compaction+/// has already replaced the history sitting behind any cached KV prefix, so+/// re-composing here adds no SECOND invalidation point; deferring to the next+/// turn boundary instead would throw away a live cache for the same text.+///+/// Root-only (a subagent has no durable session file of its own, and must not+/// flip the flag for the root) and idempotent: a session that compacts ten+/// times re-derives its prompt once. Best-effort, exactly like+/// playbook_glue.refreshRoot — a failed re-compose leaves the previous, still+/// valid prompt in place and the next mutation through the funnel picks it up.+pub fn noteSessionCompacted(agent: *Agent, arena: Allocator) void {+ if (agent.sub or g_session_compacted) return;+ g_session_compacted = true;+ armSessionTranscript(arena, agent.session_name, detectCaps(), true);+ if (agent.sys_base.len == 0) return; // never went through the funnel: nothing to re-derive from+ setSystemPrompts(agent, agent.sys_base, arena) catch {};}pub const sub_system_prompt =