graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(ultracode): funnel every system-prompt write through one function (#326)
Rach Pradhane94fbfce02f7
diff --git a/src/agent.zig b/src/agent.zigindex 8b305ccc..87039413 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -68,8 +68,7 @@ pub const Agent = struct {/// #124: per-turn transient parse garbage (per-SSE-event envelope parses,/// isStreamEnd) allocates here and is reset each request(), so the long-lived/// ROOT agent's session arena stops growing unboundedly. Optional — null on- /// subagents/one-shots (they free their own arena per task); scratchAlloc()- /// then falls back to arena, so their behavior is unchanged.+ /// subagents/one-shots (scratchAlloc() then falls back to arena, unchanged).scratch_arena: ?*std.heap.ArenaAllocator = null,/// Optional allocator for a temporary request transaction. compact() points/// this at its arena so failed summaries do not leak message rewrites or@@ -143,6 +142,8 @@ pub const Agent = struct {session_name: []const u8 = "last", // autosave/resume target (<name>.session.json)session_title: ?[]const u8 = null, // human-readable title/rename metadatasys_strict: []const u8 = prompts.main_system_prompt_strict,+ sys_ultra: []const u8 = prompts.main_system_prompt ++ prompts.ultracode_system_note, // #326: comptime defaults only — prompts.setSystemPrompts() is the sole production writer+ sys_ultra_strict: []const u8 = prompts.main_system_prompt_strict ++ prompts.ultracode_system_note, // composes onto sys_strict, never replaces ittools_anthropic: []const u8 = schema.tools_anthropic_sub,tools_openai: []const u8 = schema.tools_openai_sub,tools_responses: []const u8 = schema.tools_responses_sub,@@ -287,7 +288,8 @@ pub const Agent = struct {pub fn systemPrompt(self: *const Agent) []const u8 {if (self.review_mode) return self.sys_override orelse self.sys_normal;if (self.sub) return self.sys_override orelse prompts.sub_system_prompt;- return if (self.strict) self.sys_strict else self.sys_normal;+ // #326: ultra composes onto normal/strict rather than replacing it.+ return if (self.strict) (if (prompts.ultracodeActive(self)) self.sys_ultra_strict else self.sys_strict) else (if (prompts.ultracodeActive(self)) self.sys_ultra else self.sys_normal);}/// Whether the active provider honors a reasoning-effort hint: the@@ -490,10 +492,9 @@ pub const Agent = struct {// and through reasoning-model thinking deltas (which print nothing) —// cleared the moment the first visible text byte streams (printDelta)// or the stream ends (postStream's defer). Root + interactive TTY only;- // single-threaded start/stop (root thread), the task itself is on the- // pool and polls the stop flag every 20ms so stopping is near-instant.- // The animation is picked via /animation (ported in spirit from- // arpagon/pi-animations, MIT) and persists in .harness/settings.json.+ // single-threaded start/stop, polling the stop flag every 20ms on the+ // pool so stopping is near-instant. Picked via /animation (ported in+ // spirit from arpagon/pi-animations, MIT), persists in settings.json.pub var g_spin_stop: std.atomic.Value(bool) = .init(true);pub var g_spin_future: ?Io.Future(void) = null;pub const spinnerTask = @import("agent_stream.zig").spinnerTask;diff --git a/src/agent_context.zig b/src/agent_context.zigindex c0bf8cd8..02b76e38 100644--- a/src/agent_context.zig+++ b/src/agent_context.zig@@ -539,3 +539,41 @@ test "recordUsageResponses: usage fallbacks never lower an authoritative meter"recordUsageResponses(&agent, missing, 4_000);try std.testing.expectEqual(@max(fullRequestEstimateTokens(&agent), @as(u64, 1_000)), agent.last_context_tokens);}++// #326: systemPrompt() must gate the ultra variant on the SAME condition the+// persistent-steering call sites use (session_run.zig/mainloop.zig both call+// prompts.ultracodeActive(root)), and must COMPOSE it with strict rather than+// replace it. Attempt 1 broke both: (1) gated on ultracode_mode alone, so a+// bare /effort ultra session got sys_normal — never sys_ultra — and (2)+// returned sys_ultra before the strict check, so /strict + /ultracode+// together silently dropped strict. Distinct marker strings (not real prose)+// prove the dispatch logic itself, independent of setSystemPrompts' own tests.+test "systemPrompt (#326): all four {ultracode, strict} combos, plus /effort ultra without ultracode_mode" {+ var agent: Agent = undefined;+ agent.review_mode = false;+ agent.sub = false;+ agent.sys_override = null;+ agent.sys_normal = "NORMAL";+ agent.sys_strict = "STRICT";+ agent.sys_ultra = "ULTRA";+ agent.sys_ultra_strict = "ULTRA_STRICT";+ agent.strict = false;+ agent.ultracode_mode = false;+ agent.reasoning = .medium;++ try std.testing.expectEqualStrings("NORMAL", agent.systemPrompt()); // off, off+ agent.strict = true;+ try std.testing.expectEqualStrings("STRICT", agent.systemPrompt()); // off, strict+ agent.ultracode_mode = true;+ try std.testing.expectEqualStrings("ULTRA_STRICT", agent.systemPrompt()); // on, strict — composes, not replaces+ agent.strict = false;+ try std.testing.expectEqualStrings("ULTRA", agent.systemPrompt()); // on, off++ // /effort ultra sets reasoning == .ultra, NOT ultracode_mode — attempt 1's+ // regression 1 dropped the catalog entirely on this exact path.+ agent.ultracode_mode = false;+ agent.reasoning = .ultra;+ try std.testing.expectEqualStrings("ULTRA", agent.systemPrompt());+ agent.strict = true;+ try std.testing.expectEqualStrings("ULTRA_STRICT", agent.systemPrompt());+}diff --git a/src/main.zig b/src/main.zigindex 0dff15be..90802ffd 100644--- a/src/main.zig+++ b/src/main.zig@@ -405,10 +405,9 @@ pub fn main(init: std.process.Init) !void {}// Root system-prompt layering (base + AGENTS.md/HARNESS.md/CLAUDE.md + --append-system-prompt + active-skill lines + connected-MCP notes) lives- // in startup.zig as buildSystemPrompt() — pure over io/arena, returns both prompt strings by value.- const sys_prompt = try startup.buildSystemPrompt(io, arena, out, flags.system_prompt_flag, flags.append_system_flag, json_mode or flags.oneshot_prompt != null, mcp_tools, g_codedbpro_licensed, init.environ_map.get("GRAFF_LEARNED_PROMPT"));- const sys_normal = sys_prompt.sys_normal;- const sys_strict = sys_prompt.sys_strict;+ // in startup.zig as buildSystemPrompt() — pure over io/arena, returns the composed base by value. buildRootAgent derives every prompt variant+ // from it via prompts.setSystemPrompts() (#326).+ const sys_normal = try startup.buildSystemPrompt(io, arena, out, flags.system_prompt_flag, flags.append_system_flag, json_mode or flags.oneshot_prompt != null, mcp_tools, g_codedbpro_licensed, init.environ_map.get("GRAFF_LEARNED_PROMPT"));boot.mark(io, "system prompt");session_run.learningNotice(io, arena, init.environ_map, out, json_mode or flags.oneshot_prompt != null);@@ -426,7 +425,7 @@ pub fn main(init: std.process.Init) !void {// Root Agent construction + post-construction config (session name, persisted thinking/goal/eval settings, session-start trace note) + the// backgrounded fleet-champion pull live in session_start.zig. `root`'s pointer fields (snapshots/client/tracer/approvals/registry) all reference// already-stable main()-owned storage passed in by address, so returning the constructed Agent by value here is safe.- var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, subagent_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, sys_strict, &snaps, flags, telem.endpoint);+ var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, subagent_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, &snaps, flags, telem.endpoint);root.run_budget = &invocation_budget;root.model_catalog = resolved_keys.model_catalog;root.stored_keys_loaded = resolved_keys.stored_keys_loaded;@@ -524,7 +523,6 @@ pub fn main(init: std.process.Init) !void {.linebuf = &linebuf,.interactive = interactive,.sys_normal = sys_normal,- .sys_strict = sys_strict,};try mainloop.run(&loop_ctx);try session_run.finalizeSession(gpa, io, arena, out, &root, json_mode);diff --git a/src/mainloop.zig b/src/mainloop.zigindex d313c7e3..5852ef14 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -53,8 +53,7 @@ pub const Ctx = struct {history: *std.ArrayList([]const u8),linebuf: *std.ArrayList(u8),interactive: bool,- sys_normal: []const u8,- sys_strict: []const u8,+ sys_normal: []const u8, // startup-composed BASE; set_agent's reset-to-original path re-derives from this via prompts.setSystemPrompts() (#326)};/// Run turns until EOF/quit; main then performs final save/worktree cleanup.@@ -209,8 +208,7 @@ pub fn run(ctx: *Ctx) !void {if (std.mem.eql(u8, rtype, "set_agent")) {const id = if (parsed.object.get("id")) |v| (if (v == .string) v.string else "") else "";if (id.len == 0) {- ctx.root.sys_normal = ctx.sys_normal;- ctx.root.sys_strict = ctx.sys_strict;+ try prompts.setSystemPrompts(ctx.root, ctx.sys_normal, ctx.arena); // #326: reset to the startup base, all four variantsctx.root.rebaseContextMeter();ctx.root.emit(.{ .type = "agent", .ok = true, .id = id, .chars = ctx.root.sys_normal.len });continue;@@ -220,8 +218,8 @@ pub fn run(ctx: *Ctx) !void {ctx.root.emit(.{ .type = "error", .message = message });continue;};- ctx.root.sys_normal = try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ ctx.sys_normal, prompt });- ctx.root.sys_strict = try std.fmt.allocPrint(ctx.arena, "{s}{s}", .{ ctx.root.sys_normal, prompts.strict_note });+ const persona_base = try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ ctx.sys_normal, prompt });+ try prompts.setSystemPrompts(ctx.root, persona_base, ctx.arena); // #326: recomputes strict + ultra tooctx.root.rebaseContextMeter();ctx.root.emit(.{ .type = "agent", .ok = true, .id = id, .chars = ctx.root.sys_normal.len });continue;@@ -266,11 +264,11 @@ pub fn run(ctx: *Ctx) !void {}if (std.mem.eql(u8, rtype, "set_system_prompt")) {const append = if (parsed.object.get("append")) |v| v == .bool and v.bool else false;- ctx.root.sys_normal = if (append)+ const new_base = if (append)try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ ctx.root.sys_normal, text })elsetry ctx.arena.dupe(u8, text);- ctx.root.sys_strict = try std.fmt.allocPrint(ctx.arena, "{s}{s}", .{ ctx.root.sys_normal, prompts.strict_note });+ try prompts.setSystemPrompts(ctx.root, new_base, ctx.arena); // #326: recomputes strict + ultra tooctx.root.rebaseContextMeter();ctx.root.emit(.{ .type = "system_prompt", .ok = true, .append = append, .chars = ctx.root.sys_normal.len });continue;@@ -367,7 +365,7 @@ pub fn run(ctx: *Ctx) !void {const ultracode_msg = if (ctx.root.review_mode)pickers.UltracodeMessage{ .text = msg, .explicit = false }else- try pickers.applyUltracodeSteering(ctx.arena, msg, base_msg, ctx.root.ultracode_mode or ctx.root.reasoning == .ultra);+ try pickers.applyUltracodeSteering(ctx.arena, msg, base_msg, prompts.ultracodeActive(ctx.root));if (ultracode_msg.explicit) {if (!main_mod.json_mode) {if (ctx.interactive) {diff --git a/src/pickers.zig b/src/pickers.zigindex aedffc8c..d2b39599 100644--- a/src/pickers.zig+++ b/src/pickers.zig@@ -398,75 +398,10 @@ pub fn listPickerAt(root: *Agent, arena: Allocator, out: *Io.Writer, title: []co}}-pub const UltracodeMessage = struct {- text: []const u8,- explicit: bool,-};--const ultracode_explicit_head =- \\[harness note: the user invoked the "ultracode" codeword, opting- \\this turn into multi-agent orchestration. Fulfill the request with- \\the workflow tool.- \\Tell code-exploration subagents to go through the repo with the- \\codedb tool (search / symbol / callers / outline / context) before- \\reaching for bash grep — it is indexed and structural.- \\Use the workflow even if you could do the work solo; skip it only- \\if the message needs a purely conversational reply.-;--const ultracode_persistent_head =- \\[harness note: ultracode mode is enabled for this session. Use the- \\workflow tool for coding tasks. Tell code-exploration subagents to go- \\through the repo with the codedb tool (search / symbol / callers /- \\outline / context) before reaching for bash grep — it is indexed and- \\structural.-;--// Both steering notes carry the shape catalog (#293), so an ultracode turn-// instantiates one of the five known shapes under canonical slot names instead-// of inventing a fresh structure each run — scores from differently-shaped runs-// are not comparable, which is what kept the fleet from accruing real fitness.-const ultracode_explicit_note = ultracode_explicit_head ++ "\n\n" ++ shapes.shape_catalog_note ++ "]";-const ultracode_persistent_note = ultracode_persistent_head ++ "\n\n" ++ shapes.shape_catalog_note ++ "]";--/// `raw` is what the user actually typed this turn; `msg` is the assembled-/// turn message (goal/eval/loop/plan notes may already be appended). The-/// explicit-codeword scan runs ONLY on `raw`: harness-assembled notes replay-/// prior context — a /goal set during an ultracode task, a todo echoed-/// through the goal note — and scanning them made the codeword sticky, so-/// every turn after /clear bannered as explicit even though the user never-/// typed the word (#178).-pub fn applyUltracodeSteering(arena: Allocator, msg: []const u8, raw: []const u8, persistent_enabled: bool) !UltracodeMessage {- const explicit = util.indexOfIgnoreCase(raw, "ultracode") != null;- if (explicit) {- return .{ .text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ msg, ultracode_explicit_note }), .explicit = true };- }- if (persistent_enabled) {- return .{ .text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ msg, ultracode_persistent_note }), .explicit = false };- }- return .{ .text = msg, .explicit = false };-}--test "applyUltracodeSteering (#178): the codeword scan runs on the raw typed text, not the assembled msg" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();- // The word arriving via an appended harness note (e.g. a standing goal)- // must NOT count as an invocation — and with persistent mode off, the- // message passes through untouched.- const assembled = "write the report\n\n[harness note: goal — ultracode the pipeline]";- const via_note = try applyUltracodeSteering(a, assembled, "write the report", false);- try std.testing.expect(!via_note.explicit);- try std.testing.expectEqualStrings(assembled, via_note.text);- // The user actually typing it does (case-insensitive) and appends the note.- const typed = try applyUltracodeSteering(a, "ULTRACODE fix the bug", "ULTRACODE fix the bug", false);- try std.testing.expect(typed.explicit);- try std.testing.expect(std.mem.indexOf(u8, typed.text, "codeword") != null);- // Persistent mode still applies its note without ever claiming explicit.- const persistent = try applyUltracodeSteering(a, assembled, "write the report", true);- try std.testing.expect(!persistent.explicit);- try std.testing.expect(std.mem.indexOf(u8, persistent.text, "ultracode mode is enabled") != null);-}+// applyUltracodeSteering()/UltracodeMessage moved to shapes.zig (#326: the+// steering notes are a shape-catalog concern, and pickers.zig is at cap).+pub const UltracodeMessage = shapes.UltracodeMessage;+pub const applyUltracodeSteering = shapes.applyUltracodeSteering;const ultracode_on_first = [_]PickItem{.{ .name = "on", .desc = "Enable ultracode orchestration" },@@ -584,13 +519,13 @@ test "applyUltracodeSteering handles explicit and persistent modes" {try std.testing.expect(std.mem.indexOf(u8, explicit.text, "user invoked the \"ultracode\" codeword") != null);try std.testing.expect(std.mem.indexOf(u8, explicit.text, "ultracode mode is enabled") == null);- // #293: BOTH steering paths must carry the shape catalog — a turn steered- // into orchestration without it is exactly the free-form case the catalog- // exists to remove. Check a slot word and the closing bracket, so a broken- // concatenation (dropped catalog, or a note left unterminated) fails here.- for ([_][]const u8{ explicit.text, persistent.text }) |steered| {- try std.testing.expect(std.mem.indexOf(u8, steered, "Pick ONE shape") != null);- try std.testing.expect(std.mem.indexOf(u8, steered, "synthesize") != null);- try std.testing.expect(std.mem.endsWith(u8, steered, "]"));- }+ // #293: the explicit codeword note carries the shape catalog. Slot word ++ // closing bracket catches a dropped/unterminated concatenation.+ try std.testing.expect(std.mem.indexOf(u8, explicit.text, "Pick ONE shape") != null);+ try std.testing.expect(std.mem.indexOf(u8, explicit.text, "synthesize") != null);+ try std.testing.expect(std.mem.endsWith(u8, explicit.text, "]"));+ // #326: the PERSISTENT note must NOT carry the catalog — that re-paste is+ // exactly what this fix removes. setSystemPrompts() puts the catalog in+ // sys_ultra/sys_ultra_strict once instead.+ try std.testing.expect(std.mem.indexOf(u8, persistent.text, "Pick ONE shape") == null);}diff --git a/src/prompts.zig b/src/prompts.zigindex 2becc9dc..55cda55a 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -4,6 +4,16 @@//! the Agent struct's default field values (sys_normal/sys_strict) and//! main()'s prompt-selection logic read unchanged; compact_instruction stays//! pub — agent_compact.zig already back-imports it as `root.compact_instruction`.+//!+//! setSystemPrompts()/ultracodeActive() live here too (#326): the ultra+//! variants are pre-built strings exactly like sys_normal/sys_strict, so+//! this is the one place that derives all four from a base, next to the+//! constants it composes them from.++const std = @import("std");+const Allocator = std.mem.Allocator;+const shapes = @import("shapes.zig");+const Agent = @import("agent.zig").Agent;pub const main_system_prompt =\\You are a coding agent running in a minimal terminal harness on the@@ -68,6 +78,48 @@ pub const strict_note =pub const main_system_prompt_strict = main_system_prompt ++ strict_note;+/// Appended once to the active system-prompt variant when ultracode mode is+/// active (#326), instead of pasted onto every turn's user message the way+/// the old persistent steering note did — that re-paste put the shape+/// catalog in compaction input on every single turn. setSystemPrompts()+/// composes this onto whichever base (normal or strict) is active.+pub const ultracode_system_note =+ \\+ \\+ \\ULTRACODE MODE: use the workflow tool for coding tasks. Tell+ \\code-exploration subagents to go through the repo with the codedb tool+ \\(search / symbol / callers / outline / context) before reaching for+ \\bash grep — it is indexed and structural.+ \\+ \\+++ shapes.shape_catalog_note;++/// The exact condition the persistent-steering call sites (session_run.zig,+/// mainloop.zig) use to decide a turn is ultracode-steered: `/effort ultra`+/// sets reasoning == .ultra WITHOUT ultracode_mode, and the two toggle+/// independently. systemPrompt() gates its ultra variant on this SAME+/// condition (#326 attempt 1 gated on ultracode_mode alone and lost the+/// catalog entirely on the /effort ultra path).+pub fn ultracodeActive(agent: *const Agent) bool {+ return agent.ultracode_mode or agent.reasoning == .ultra;+}++/// #326: the ONLY function that may write sys_normal/sys_strict/sys_ultra/+/// sys_ultra_strict. systemPrompt() returns a slice and cannot allocate, so+/// all four have to be pre-built from `base` — and pre-building means any+/// site that mutates the prompt by hand instead of through here goes stale+/// (attempt 2's regression: startup composed the ultra variants once, but+/// the repl and the JSON set_agent/set_system_prompt handlers wrote+/// sys_normal directly and never recomputed them). `ultra` COMPOSES onto+/// whichever base is active rather than replacing it, so /strict and+/// /ultracode stay independent toggles.+pub fn setSystemPrompts(agent: *Agent, base: []const u8, arena: Allocator) !void {+ agent.sys_normal = base;+ agent.sys_strict = try std.fmt.allocPrint(arena, "{s}{s}", .{ base, strict_note });+ agent.sys_ultra = try std.fmt.allocPrint(arena, "{s}{s}", .{ base, ultracode_system_note });+ agent.sys_ultra_strict = try std.fmt.allocPrint(arena, "{s}{s}", .{ agent.sys_strict, ultracode_system_note });+}+pub const sub_system_prompt =\\You are a subagent spawned by an orchestrator agent inside a terminal\\harness. Complete the assigned task using your tools, without asking@@ -85,10 +137,70 @@ pub const compact_instruction =;test "root prompt permits explicit external targets without weakening confinement" {- const std = @import("std");try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "explicitly names") != null);try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "permission-gated bash") != null);try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "not covered by /rewind") != null);try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "Do not claim a relaunch is required") != null);try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "Never extend") != null);}++// #326: setSystemPrompts is the single funnel every production site must go+// through. This asserts what it actually PRODUCES — the comptime+// prompts.zig defaults on the Agent struct are what hid attempt 1's+// regression, since a startup-composed value overwrote them in every real+// session while the untested default kept the suite green.+test "setSystemPrompts (#326): derives all four variants from base, composing ultra onto strict rather than replacing it" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent: Agent = undefined;++ try setSystemPrompts(&agent, "BASE-A", a);+ try std.testing.expectEqualStrings("BASE-A", agent.sys_normal);+ for ([_][]const u8{ agent.sys_strict, agent.sys_ultra, agent.sys_ultra_strict }) |v|+ try std.testing.expect(std.mem.indexOf(u8, v, "BASE-A") != null);+ // The catalog rides on both ultra variants, and ONLY the ultra variants.+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_ultra, "Pick ONE shape") != null);+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_ultra_strict, "Pick ONE shape") != null);+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "Pick ONE shape") == null);+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_strict, "Pick ONE shape") == null);+ // sys_ultra_strict still carries STRICT MODE — composed onto the strict+ // base, never a replacement of it (#326 attempt 1 regression 2).+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_ultra_strict, "STRICT MODE") != null);+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_strict, "STRICT MODE") != null);+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_ultra, "STRICT MODE") == null);+}++// The structural bug attempt 2 shipped: buildSystemPrompt composed the+// ultra variants ONCE at startup, but the repl and the JSON protocol's+// set_agent/set_system_prompt handlers wrote sys_normal directly afterward+// and never recomputed sys_ultra/sys_ultra_strict, so systemPrompt() served+// the STALE startup-composed prompt once a persona or custom prompt landed.+// A single funnel called at every mutation site is what closes that gap;+// this proves the funnel itself has no such staleness — a later call with a+// new base fully supersedes the first, in every variant.+test "setSystemPrompts (#326): a later mutation (set_agent/set_system_prompt-style) replaces ALL four variants, none stay stale" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent: Agent = undefined;++ try setSystemPrompts(&agent, "STARTUP-BASE", a); // e.g. buildRootAgent at process start+ try setSystemPrompts(&agent, "MUTATED-BASE", a); // e.g. a later set_agent/set_system_prompt+ 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, "MUTATED-BASE") != null);+ try std.testing.expect(std.mem.indexOf(u8, v, "STARTUP-BASE") == null);+ }+}++test "ultracodeActive (#326): matches the persistent-steering gate exactly, including /effort ultra without ultracode_mode" {+ var agent: Agent = undefined;+ agent.ultracode_mode = false;+ agent.reasoning = .medium;+ try std.testing.expect(!ultracodeActive(&agent));+ agent.ultracode_mode = true;+ try std.testing.expect(ultracodeActive(&agent));+ agent.ultracode_mode = false;+ agent.reasoning = .ultra; // /effort ultra: reasoning == .ultra, ultracode_mode stays false+ try std.testing.expect(ultracodeActive(&agent));+}diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 53eac064..89a1b764 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -6,15 +6,13 @@//! (save/loadThinkingSettings). Split out of main.zig (600-line goal, #123).//!//! The mutable steer/thinking globals (g_steer_buf, g_steer_queue,-//! g_steer_echoed, g_steer_visible, g_out) stay declared in main.zig — they're-//! shared live with agent_interrupt.zig/agent_stream.zig via the same-//! `main_mod.g_x` pattern those files already use — so every access here goes-//! through `main_mod.g_x`, never a local alias (aliasing a `var` would freeze-//! its value at import time).+//! g_steer_echoed, g_steer_visible, g_out) stay declared in main.zig — shared+//! live with agent_interrupt.zig/agent_stream.zig via the same `main_mod.g_x`+//! pattern those files already use, so every access here goes through+//! `main_mod.g_x`, never a local alias (would freeze its value at import time).//!//! parseEvalScore/steerEcho/saveThinkingSettings stay pub — subagent.zig,-//! agent_compact.zig, agent_interrupt.zig, and commands_model.zig already-//! back-import them as `main_mod.parseEvalScore` etc.+//! agent_compact.zig, agent_interrupt.zig, commands_model.zig back-import them.const std = @import("std");const Io = std.Io;@@ -40,6 +38,7 @@ const providers = @import("providers.zig");const trace = @import("trace.zig");const serde = @import("serde.zig");const fallback_config = @import("fallback_config.zig");+const prompts = @import("prompts.zig");pub const ReplCtx = struct {io: Io,@@ -325,7 +324,6 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu.tracer = c.tracer,.run_budget = c.run_budget,.approvals = &approvals,- .sys_normal = sys,.tools_anthropic = c.tools_anthropic,.tools_openai = c.tools_openai,.tools_responses = c.tools_responses,@@ -344,6 +342,9 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu.ultracode_mode = params.ultracode,.show_thinking = params.thinking,};+ // #326: the funnel — also recomputes sys_ultra/sys_ultra_strict from+ // `sys`, so ultracode/effort-ultra here carries the REAL composed base.+ prompts.setSystemPrompts(&agent, sys, arena) catch return null;defer agent.tools_used.deinit(gpa);for (history) |t| {const role = switch (t.role) {diff --git a/src/session_run.zig b/src/session_run.zigindex 2d913e7d..2994d034 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -60,6 +60,7 @@ const learn_init = @import("learn_init.zig");const run_budget_mod = @import("run_budget.zig");const learning_privacy = @import("learning_privacy.zig");const commands_privacy = @import("commands_privacy.zig");+const prompts = @import("prompts.zig");/// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL/// agent loop — each prompt runs a full root turn (tools + MCP) via@@ -119,7 +120,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mroot.in = null; // gate: deny instead of prompt; ask_user: self-decideroot.out = null; // tool progress → stderr; stdout carries only the answerroot.stream_quiet = true;- const ultracode_msg = try pickers.applyUltracodeSteering(arena, prompt_text, prompt_text, root.ultracode_mode or root.reasoning == .ultra);+ const ultracode_msg = try pickers.applyUltracodeSteering(arena, prompt_text, prompt_text, prompts.ultracodeActive(root));if (ultracode_msg.explicit) {tracer.note("ultracode", prompt_text[0..@min(prompt_text.len, 120)]);if (telemetry.g_telem) |t| t.ultracode();@@ -216,8 +217,10 @@ pub fn initApprovalsHooksFleet(io: Io, gpa: Allocator, arena: Allocator, environ/// storage, not anything local to this function (see this file's header)./// Also does the post-construction config (session name, persisted/// thinking/goal/eval settings, the session-start trace note) and kicks off-/// the backgrounded fleet-champion pull, all moved out of main() verbatim-/// (600-line goal).+/// the backgrounded fleet-champion pull, moved out of main() verbatim+/// (600-line goal). `sys_normal` is the startup-composed BASE; this calls+/// prompts.setSystemPrompts() to derive sys_strict/sys_ultra/sys_ultra_strict+/// from it, the same funnel every later prompt mutation must use (#326).pub fn buildRootAgent(gpa: Allocator,arena: Allocator,@@ -232,7 +235,6 @@ pub fn buildRootAgent(approvals: *approvals_mod.Approvals,tracer: *trace.Tracer,sys_normal: []const u8,- sys_strict: []const u8,snaps: *tools_mod.Snapshots,flags: args.Flags,telem_endpoint: []const u8,@@ -255,12 +257,11 @@ pub fn buildRootAgent(.registry = registry,.approvals = approvals,.tracer = tracer,- .sys_normal = sys_normal,- .sys_strict = sys_strict,.tools_anthropic = "",.tools_openai = "",.tools_responses = "",};+ try prompts.setSystemPrompts(&root, sys_normal, arena);// Startup pays for one provider format, not all three. Other formats are// rendered on first switch with the same built-in + live MCP inputs.try root.ensureRootTools(default_provider.kind);@@ -373,9 +374,8 @@ pub const ThemeSetup = struct {theme_on: bool,limyuxi_glam: bool,/// True when a PTY self-test already ran + printed its render — main()- /// should return immediately without going any- /// further (but AFTER registering the theme/limyuxi reset defers below,- /// exactly like the original inline code did).+ /// should return immediately (but AFTER registering the theme/limyuxi+ /// reset defers below, exactly like the original inline code did).should_exit: bool,};diff --git a/src/shapes.zig b/src/shapes.zigindex e9fd2b6f..53f1ffbe 100644--- a/src/shapes.zig+++ b/src/shapes.zig@@ -3,11 +3,15 @@//! name their phases with, and the steering text appended to an ultracode//! turn.//!-//! Lives outside pickers.zig (which owns the steering call site) for two-//! reasons: pickers.zig is at the 600-line cap, and the slot vocabulary is-//! not a picker concern — it is the third component of the MAP-Elites cell-//! key (#290). Keeping this a std-only leaf module, prompts.zig-style, lets-//! both the steering path and the fleet scoring path import it with no cycle.+//! Also applyUltracodeSteering() itself (#326, moved from pickers.zig which+//! is at the 600-line cap): the explicit-codeword and persistent steering+//! notes are shape-catalog concerns first, picker concerns second.+//!+//! Lives outside pickers.zig for two reasons: pickers.zig is at the+//! 600-line cap, and the slot vocabulary is not a picker concern — it is+//! the third component of the MAP-Elites cell key (#290). A leaf module+//! (std + util.zig, itself std-only), prompts.zig-style, so both the+//! steering path and the fleet scoring path import it with no cycle.//!//! Why a fixed catalog at all: left to itself the model authors a different//! workflow shape every run, so two scores for the same persona are not@@ -16,6 +20,8 @@//! accrues real fitness across runs.const std = @import("std");+const Allocator = std.mem.Allocator;+const util = @import("util.zig");/// Canonical phase/stage labels an ultracode workflow names its slots with.///@@ -202,3 +208,83 @@ test "shape catalog never tells a dependent chain to isolate into worktrees" {// The old unconditional phrasing must not come back.try std.testing.expect(std.mem.indexOf(u8, shape_catalog_note, "Give file-editing tasks isolation") == null);}++pub const UltracodeMessage = struct {+ text: []const u8,+ explicit: bool,+};++const ultracode_explicit_head =+ \\[harness note: the user invoked the "ultracode" codeword, opting+ \\this turn into multi-agent orchestration. Fulfill the request with+ \\the workflow tool.+ \\Tell code-exploration subagents to go through the repo with the+ \\codedb tool (search / symbol / callers / outline / context) before+ \\reaching for bash grep — it is indexed and structural.+ \\Use the workflow even if you could do the work solo; skip it only+ \\if the message needs a purely conversational reply.+;++// The explicit-codeword note carries the shape catalog (#293): a one-shot+// invocation can't rely on the system prompt already having it, so it+// instantiates one of the five known shapes under canonical slot names here.+const ultracode_explicit_note = ultracode_explicit_head ++ "\n\n" ++ shape_catalog_note ++ "]";++// No catalog here (#326): it used to ride on every turn while ultracode was+// on, landing in compaction input every turn. setSystemPrompts() composes+// it into sys_ultra/sys_ultra_strict once; this note just points at it.+const ultracode_persistent_note =+ \\[harness note: ultracode mode is enabled for this session. Use the+ \\workflow tool for coding tasks — your system prompt already has the+ \\shape catalog; instantiate one of those shapes rather than freeforming+ \\a structure. Tell code-exploration subagents to go through the repo+ \\with the codedb tool (search / symbol / callers / outline / context)+ \\before reaching for bash grep — it is indexed and structural.]+;++/// `raw` is what the user actually typed this turn; `msg` is the assembled+/// turn message (goal/eval/loop/plan notes may already be appended). The+/// explicit-codeword scan runs ONLY on `raw`: harness-assembled notes replay+/// prior context — a /goal set during an ultracode task, a todo echoed+/// through the goal note — and scanning them made the codeword sticky, so+/// every turn after /clear bannered as explicit even though the user never+/// typed the word (#178).+pub fn applyUltracodeSteering(arena: Allocator, msg: []const u8, raw: []const u8, persistent_enabled: bool) !UltracodeMessage {+ const explicit = util.indexOfIgnoreCase(raw, "ultracode") != null;+ if (explicit) {+ return .{ .text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ msg, ultracode_explicit_note }), .explicit = true };+ }+ if (persistent_enabled) {+ return .{ .text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ msg, ultracode_persistent_note }), .explicit = false };+ }+ return .{ .text = msg, .explicit = false };+}++test "applyUltracodeSteering (#178): the codeword scan runs on the raw typed text, not the assembled msg" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ // The word arriving via an appended harness note (e.g. a standing goal)+ // must NOT count as an invocation — and with persistent mode off, the+ // message passes through untouched.+ const assembled = "write the report\n\n[harness note: goal — ultracode the pipeline]";+ const via_note = try applyUltracodeSteering(a, assembled, "write the report", false);+ try std.testing.expect(!via_note.explicit);+ try std.testing.expectEqualStrings(assembled, via_note.text);+ // The user actually typing it does (case-insensitive) and appends the note.+ const typed = try applyUltracodeSteering(a, "ULTRACODE fix the bug", "ULTRACODE fix the bug", false);+ try std.testing.expect(typed.explicit);+ try std.testing.expect(std.mem.indexOf(u8, typed.text, "codeword") != null);+ // Persistent mode still applies its note without ever claiming explicit.+ const persistent = try applyUltracodeSteering(a, assembled, "write the report", true);+ try std.testing.expect(!persistent.explicit);+ try std.testing.expect(std.mem.indexOf(u8, persistent.text, "ultracode mode is enabled") != null);+ // #326: explicit carries the catalog (can't rely on the system prompt);+ // persistent does not — that every-turn re-paste is what #326 removes,+ // since setSystemPrompts() composes it into sys_ultra/sys_ultra_strict.+ try std.testing.expect(std.mem.indexOf(u8, typed.text, "Pick ONE shape") != null);+ try std.testing.expect(std.mem.indexOf(u8, typed.text, "synthesize") != null);+ try std.testing.expect(std.mem.endsWith(u8, typed.text, "]"));+ try std.testing.expect(std.mem.indexOf(u8, persistent.text, "Pick ONE shape") == null);+ try std.testing.expect(std.mem.indexOf(u8, persistent.text, "already has the") != null);+}diff --git a/src/startup.zig b/src/startup.zigindex b09367b9..bce22cf5 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -300,11 +300,6 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytypreturn .{ .keys = keys, .default_provider = default_provider, .stale_saved_model = stale_saved_model, .preferred_provider = preferred_provider, .codex_account = codex_account, .model_catalog = model_catalog, .stored_keys_loaded = stored_keys_loaded };}-pub const SystemPrompt = struct {- sys_normal: []const u8,- sys_strict: []const u8,-};-/// Root system-prompt layering, frozen at startup so it stays/// KV-cache-friendly: built-in base (or its --system-prompt replacement),/// then project instructions from the first of AGENTS.md/HARNESS.md/@@ -339,7 +334,7 @@ pub fn buildSystemPrompt(mcp_tools: []const mcp.Tool,codedbpro_licensed: bool,learned_policy_env: ?[]const u8,-) !SystemPrompt {+) ![]const u8 {// A learned policy is used unless this session opted out of it.const learned: ?learn_store.ActiveAgent = if (system_prompt_flag == null and learn_auto.enabled(learned_policy_env)) learnedRootPolicy(io, arena) else null;if (learned) |policy| if (!quiet) {@@ -377,8 +372,12 @@ pub fn buildSystemPrompt(const note = skills.codedbproNote(mn.server, codedbpro_licensed, mn.note);sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ sys_normal, note });}- const sys_strict: []const u8 = try std.fmt.allocPrint(arena, "{s}{s}", .{ sys_normal, prompts.strict_note });- return .{ .sys_normal = sys_normal, .sys_strict = sys_strict };+ // #326: this returns the composed BASE only. prompts.setSystemPrompts()+ // (called once by buildRootAgent, the sole consumer) derives+ // sys_normal/sys_strict/sys_ultra/sys_ultra_strict from it — the single+ // funnel every later mutation (repl, set_agent, set_system_prompt) must+ // also go through, so none of the four ever go stale independently.+ return sys_normal;}const args = @import("args.zig");