Skip to content

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

Python

fix(agent): pin a subagent's task prompt through compaction (#B3)

Rach Pradhan5fe278e0f6dc
diff --git a/src/agent.zig b/src/agent.zig
index 6d2f17b4..8b305ccc 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -100,6 +100,7 @@ pub const Agent = struct {
last_cache_read: u64 = 0, // KV-cache read tokens from the latest response
sys_normal: []const u8 = prompts.main_system_prompt, // root system prompt (+ project instructions)
sys_override: ?[]const u8 = null, // per-child custom prompt or transient isolated-review base
+ task_prompt: ?[]const u8 = null, // a subagent's mandate, pinned once before the first history rewrite so compaction can restate it verbatim (recentContextStart can keep no verbatim suffix for a child - its only clean user turn is index 0)
agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their own
tools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)
tool_calls_this_turn: u64 = 0,
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index e77e0e30..434ca4d8 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -27,6 +27,11 @@ pub const runJudge = agent_eval.runJudge;
pub const recent_context_tokens: u64 = 8_000;
+/// Head-cap for a child's pinned task prompt when restated in a handoff.
+/// ~2k tokens; head-capped because a workflow child's prompt carries the
+/// previous phase's results as a TAIL, so the head is the instruction.
+pub const task_pin_cap: usize = 8_000;
+
/// Pick the earliest clean user-turn boundary whose suffix fits in the recent
/// context budget. Returning items.len means "summarize everything". We never
/// split at a tool output, so retained call/result history stays valid.
@@ -80,6 +85,7 @@ pub fn compact(self: *Agent) anyerror!usize {
if (!main_mod.json_mode) try self.say("nothing to compact\n", .{});
return 0;
}
+ pinChildTask(self);
self.last_request_context_overflow = false;
if (!main_mod.json_mode) try self.say("[compacting ~{d} tokens…]\n", .{self.effectiveContextTokens()});
// #163: reclaim room BEFORE the summarization request so it fits under the
@@ -174,8 +180,24 @@ pub fn compact(self: *Agent) anyerror!usize {
/// goalSteeringNote would move that note's diff-gate fingerprint on every
/// compaction, defeating the suppression the gate exists for. With no live goal
/// the text is byte-identical to what it always was.
+///
+/// A subagent's ONLY clean user turn is its task prompt at index 0 (#B3):
+/// recentContextStart never keeps a verbatim suffix for a child, since every
+/// message after it is either assistant or a tool_result/tool-role turn.
+/// Without a pin, compaction would summarize the mandate away with nothing
+/// left to restate it - childHandoff below restates it verbatim instead of
+/// re-deriving it, so it can never drift or compound across compactions.
pub fn handoffMessage(self: *Agent, summary: []const u8) ![]const u8 {
- const base = try std.fmt.allocPrint(self.arena,
+ const base = if (self.sub)
+ (if (self.task_prompt) |tp| try childHandoff(self, tp, summary) else try rootHandoff(self, summary))
+ else
+ try rootHandoff(self, summary);
+ const standing = (try goal_flow.compactionSnapshot(self.arena, self)) orelse return base;
+ return std.fmt.allocPrint(self.arena, "{s}\n\n{s}", .{ base, standing });
+}
+
+fn rootHandoff(self: *Agent, summary: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(self.arena,
\\Context: the earlier conversation was compacted to save space.
\\Summary of the earlier work:
\\
@@ -183,8 +205,26 @@ pub fn handoffMessage(self: *Agent, summary: []const u8) ![]const u8 {
\\
\\Continue assisting the user based on this summary.
, .{summary});
- const standing = (try goal_flow.compactionSnapshot(self.arena, self)) orelse return base;
- return std.fmt.allocPrint(self.arena, "{s}\n\n{s}", .{ base, standing });
+}
+
+fn childHandoff(self: *Agent, task_prompt: []const u8, summary: []const u8) ![]const u8 {
+ const capped = utf8Prefix(task_prompt, task_pin_cap);
+ const truncated_note = if (capped.len < task_prompt.len)
+ "\n[task prompt truncated for the handoff - the head above is the mandate]"
+ else
+ "";
+ return std.fmt.allocPrint(self.arena,
+ \\Your assigned task, restated verbatim. The conversation that carried it was compacted; this is still your mandate and the only thing you have to deliver:
+ \\
+ \\{s}{s}
+ \\
+ \\Context: the earlier conversation was compacted to save space.
+ \\Summary of the earlier work:
+ \\
+ \\{s}
+ \\
+ \\Continue the assigned task above using this summary of the work already done, and report back as the task requires.
+ , .{ capped, truncated_note, summary });
}
/// Clone JSON arrays/objects while borrowing immutable leaf strings. Send-time
@@ -212,6 +252,23 @@ pub fn cloneJsonArray(arena: Allocator, src: std.json.Array) Allocator.Error!std
return out;
}
+/// Capture a subagent's task prompt ONCE, before the first history rewrite.
+/// Capturing once is the whole point: after a compaction messages[0] IS the
+/// handoff, so re-deriving it would fold each summary into the next without
+/// bound. Best-effort - a shape we do not recognise simply leaves the pin unset
+/// and behaviour unchanged.
+pub fn pinChildTask(self: *Agent) void {
+ if (!self.sub or self.task_prompt != null) return;
+ if (self.messages.items.len == 0) return;
+ const m = self.messages.items[0];
+ if (m != .object) return;
+ const role = m.object.get("role") orelse return;
+ if (role != .string or !std.mem.eql(u8, role.string, "user")) return;
+ const c = m.object.get("content") orelse return;
+ if (c != .string or c.string.len == 0) return;
+ self.task_prompt = self.arena.dupe(u8, c.string) catch null;
+}
+
pub fn cleanUserTurn(m: Value) bool {
if (m != .object) return false;
const role = m.object.get("role") orelse return false;
diff --git a/src/agent_compact_test.zig b/src/agent_compact_test.zig
index 8d99174a..0d6ba103 100644
--- a/src/agent_compact_test.zig
+++ b/src/agent_compact_test.zig
@@ -20,6 +20,9 @@ const cleanUserTurn = compact.cleanUserTurn;
const emergencyCutIndex = compact.emergencyCutIndex;
const emergencyTrim = compact.emergencyTrim;
const handoffMessage = compact.handoffMessage;
+const pinChildTask = compact.pinChildTask;
+const task_pin_cap = compact.task_pin_cap;
+const th = @import("agent_compact_test_support.zig");
test "compaction accepts only complete provider terminal states" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
@@ -439,6 +442,7 @@ test "a compaction handoff carries the live checklist across the summary (#318)"
const a = arena_state.allocator();
var agent: Agent = undefined;
agent.arena = a;
+ agent.task_prompt = null; // this test flips agent.sub to true below (#B3)
agent.sub = false;
agent.review_mode = false;
agent.todos = .empty;
@@ -533,3 +537,64 @@ test "an emergency trim re-queues the standing state, never over a user note (#3
_ = emergencyTrim(&agent);
try std.testing.expect(agent.pending_goal_note == null);
}
+test "recentContextStart keeps NOTHING verbatim for a subagent-shaped history (the #318-shaped failure one level down)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const short = try th.paddedSubHistory(a, 1, "ok");
+ try std.testing.expectEqual(short.items.len, recentContextStart(short.items, 8000));
+ const pad = util.repeatBytes("x", 4000);
+ const long = try th.paddedSubHistory(a, 10, &pad);
+ try std.testing.expectEqual(long.items.len, recentContextStart(long.items, 8000));
+}
+test "a compacting subagent's handoff restates its task prompt verbatim" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = th.subAgent(a, true);
+ agent.task_prompt = "AUDIT src/foo.zig and report every unguarded json deref";
+ const handoff = try handoffMessage(&agent, "the model summarized the earlier work");
+ try std.testing.expect(std.mem.indexOf(u8, handoff, agent.task_prompt.?) != null and std.mem.indexOf(u8, handoff, "the model summarized the earlier work") != null and std.mem.indexOf(u8, handoff, "still your mandate") != null);
+}
+test "the root handoff is byte-identical to before the child pin" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = th.subAgent(a, false);
+ const handoff = try handoffMessage(&agent, "the model summarized the earlier work");
+ try std.testing.expectEqualStrings("Context: the earlier conversation was compacted to save space.\nSummary of the earlier work:\n\nthe model summarized the earlier work\n\nContinue assisting the user based on this summary.", handoff);
+}
+test "pinChildTask captures the mandate once, never re-pins, and ignores a root agent or an unrecognised head" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = th.subAgent(a, true);
+ agent.messages = try th.msg1(a, "user", "TASK X");
+ pinChildTask(&agent);
+ agent.messages = try th.msg1(a, "user", "Context: the earlier conversation was compacted...");
+ pinChildTask(&agent);
+ try std.testing.expectEqualStrings("TASK X", agent.task_prompt.?);
+ for ([_]struct { s: bool, r: ?[]const u8 }{ .{ .s = false, .r = "user" }, .{ .s = true, .r = "assistant" }, .{ .s = true, .r = null } }) |c| {
+ var ag = th.subAgent(a, c.s);
+ ag.messages = if (c.r) |r| try th.msg1(a, r, "x") else std.json.Array.init(a);
+ pinChildTask(&ag);
+ try std.testing.expect(ag.task_prompt == null);
+ }
+}
+test "an oversized task prompt is head-capped in the child handoff" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = th.subAgent(a, true);
+ const big = util.repeatBytes("T", 20000);
+ agent.task_prompt = &big;
+ const handoff = try handoffMessage(&agent, "summary text");
+ try std.testing.expect(handoff.len < 12_000 and std.mem.indexOf(u8, handoff, "task prompt truncated for the handoff") != null and std.mem.indexOf(u8, handoff, big[0..100]) != null and std.mem.indexOf(u8, handoff, &big) == null);
+}
+test "emergencyCutIndex finds no cut in a subagent-shaped history, so the pinned mandate survives an emergency trim" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const items = try th.paddedSubHistory(a, 6, "ok");
+ try std.testing.expectEqual(@as(?usize, null), emergencyCutIndex(items.items));
+}
diff --git a/src/agent_compact_test_support.zig b/src/agent_compact_test_support.zig
new file mode 100644
index 00000000..8f17c6b1
--- /dev/null
+++ b/src/agent_compact_test_support.zig
@@ -0,0 +1,41 @@
+//! Shared builders for agent_compact_test.zig's subagent-task-pin tests
+//! (#B3). Kept out of agent_compact_test.zig to stay under its 600-line cap;
+//! this file has no `test` blocks of its own so it needs no main.zig hook.
+
+const std = @import("std");
+const Value = std.json.Value;
+const Agent = @import("agent.zig").Agent;
+const textMessage = @import("messages.zig").textMessage;
+
+/// A subagent-or-root Agent with just enough fields set for handoffMessage /
+/// pinChildTask to run without touching uninitialized memory.
+pub fn subAgent(a: std.mem.Allocator, sub: bool) Agent {
+ var agent: Agent = undefined;
+ agent.arena = a;
+ agent.sub = sub;
+ agent.review_mode = false;
+ agent.todos = .empty;
+ agent.goal = null;
+ agent.task_prompt = null;
+ return agent;
+}
+
+/// A one-message std.json.Array, the shape a fresh subagent history starts as.
+pub fn msg1(a: std.mem.Allocator, role: []const u8, text: []const u8) !std.json.Array {
+ return std.json.Array.fromOwnedSlice(a, try a.dupe(Value, &.{try textMessage(a, role, text)}));
+}
+
+/// An anthropic user message carrying a single tool_result block - the
+/// response half of a tool call, and NOT a clean user turn.
+pub fn toolResultMsg(a: std.mem.Allocator, content: []const u8) !Value {
+ const s = try std.fmt.allocPrint(a, "{{\"role\":\"user\",\"content\":[{{\"type\":\"tool_result\",\"content\":\"{s}\"}}]}}", .{content});
+ return std.json.parseFromSliceLeaky(Value, a, s, .{});
+}
+
+/// A subagent-shaped history: one clean user turn at index 0, followed by
+/// `n` assistant/tool_result pairs - i.e. no other clean user turn anywhere.
+pub fn paddedSubHistory(a: std.mem.Allocator, n: usize, pad: []const u8) !std.json.Array {
+ var out = try msg1(a, "user", "AUDIT src/foo.zig");
+ for (0..n) |_| try out.appendSlice(&.{ try textMessage(a, "assistant", pad), try toolResultMsg(a, "result") });
+ return out;
+}