graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
merge: wip/shared-checkout-2026-08-14 into release/v0.0.258
Rach Pradhan3d18c9f370ad
diff --cc TUI/key.zigindex 5d2b00be,42048767..7d9464b4--- a/TUI/key.zig+++ b/TUI/key.zig@@@ -90,28 -91,16 +92,36 @@@ fn escapeSeq(bytes: []const u8, i: *usii.* += 1;return .shift_enter;}- if (c0 != '[') return .escape;+ if (c0 == 0x1b) return .escape; // ESC ESC — deliver one, reparse the rest+ if (c0 == 'O') return ss3(bytes, i);+ if (c0 == ']' or c0 == 'P' or c0 == '_' or c0 == '^' or c0 == 'X') return stringSeq(bytes, i);+ if (c0 != '[') {+ // Unbound Alt+<char> chord: swallow both bytes so the char is not+ // typed into the composer behind a phantom Escape.+ i.* += 1;+ return .ignore;+ }i.* += 1;+ // X10 mouse (1000h without 1006): CSI M + 3 raw bytes.+ if (i.* < bytes.len and bytes[i.*] == 'M' and (i.* + 1 >= bytes.len or bytes[i.* + 1] != ';')) {+ if (i.* + 3 >= bytes.len) {+ i.* -= 2;+ return null;+ }+ i.* += 1;+ const btn = bytes[i.*];+ i.* += 1;+ const x = bytes[i.*];+ i.* += 1;+ const y = bytes[i.*];+ i.* += 1;+ return .{ .mouse = .{+ .btn = if (btn >= 32) btn - 32 else btn,+ .x = if (x >= 32) @as(u16, x) - 32 else x,+ .y = if (y >= 32) @as(u16, y) - 32 else y,+ .down = true,+ } };+ }const start = i.*;while (i.* < bytes.len) : (i.* += 1) {const c = bytes[i.*];@@@ -166,33 -223,30 +244,34 @@@ fn csiMods(params: []const u8) u32return mods;}- /// CSI unicode[:shifted[:base]] ; mods[:event] ; text u+ /// kitty event-type sub-param (field 2 after ':'): 1 press, 2 repeat, 3 release.+ fn eventOf(params: []const u8) u32 {+ const s = std.mem.indexOfScalar(u8, params, ';') orelse return 1;+ const rest = params[s + 1 ..];+ const c = std.mem.indexOfScalar(u8, rest, ':') orelse return 1;+ return leadingInt(rest[c + 1 ..]);+ }++ /// CSI unicode ; mods u — kitty/ghostty. mods bit 2 = ctrl, 1 = shift.fn kitty(params: []const u8) Key {- const code = leadingInt(params);+ var it = std.mem.splitScalar(u8, params, ';');+ const keys = it.next() orelse "";+ const code = leadingInt(keys);+ var shifted: u32 = 0;+ if (std.mem.indexOfScalar(u8, keys, ':')) |c| shifted = leadingInt(keys[c + 1 ..]);var mods: u32 = 0;- if (it.next()) |m| {- mods = leadingInt(m);- if (mods > 0) mods -= 1;+ var has_mods = false;+ if (std.mem.indexOfScalar(u8, params, ';')) |s| {+ has_mods = true;+ mods = leadingInt(params[s + 1 ..]);+ if (mods > 0) mods -= 1; // kitty encodes mods+1}- const text = leadingInt(it.next() orelse "");- const ev = kittyEvent(params);- if (code == 57444 or code == 57448) {- if (ev == 3) held &= ~@as(u32, 8) else held |= 8;- return .ignore;- }- if (code == 57443 or code == 57447) {- if (ev == 3) held &= ~@as(u32, 2) else held |= 2;- return .ignore;- }- if (code >= 57441 and code <= 57448) return .ignore;+ const ev = eventOf(params);+ if (code >= 57344 and code <= 57454) return functional(code, mods, ev);if (ev == 3) return .ignore;- const shift = mods & 1 != 0;- if (text >= 32 and text < 127) return mapCode(text, mods & ~@as(u32, 1));- if (shift and shifted >= 32 and shifted < 127) return mapCode(shifted, mods & ~@as(u32, 1));+ // A live key with an explicit mods field is ground truth for held+ // modifiers — resync so a missed release can't latch alt/super forever.+ if (has_mods) held = mods & 10;return mapCode(code, mods);}@@@ -230,43 -310,16 +335,46 @@@ fn mapCode(code: u32, mods: u32) Keyif ((ctrl or super) and !shift and (ch == 'z' or ch == 'Z')) return .undo;if (ctrl and ch >= 'a' and ch <= 'z') return .{ .ctrl = ch };if (ctrl and ch >= 'A' and ch <= 'Z') return .{ .ctrl = ch + 32 };+ if (shift) return .{ .char = shiftedAscii(ch) };return .{ .char = ch };}- return .escape;+ if (code >= 57344 and code <= 57454) return .ignore; // functional block, handled upstream+ if (code >= 128 and code <= 0x10ffff) return .{ .codepoint = @intCast(code) };+ // Unknown code: inert. Only a real Esc (27) may become .escape.+ return .ignore;}+/// Kitty/modifyOtherKeys report the unshifted key + Shift. US layout.+fn shiftedAscii(ch: u8) u8 {+ return switch (ch) {+ 'a'...'z' => ch - 32,+ '1' => '!',+ '2' => '@',+ '3' => '#',+ '4' => '$',+ '5' => '%',+ '6' => '^',+ '7' => '&',+ '8' => '*',+ '9' => '(',+ '0' => ')',+ '-' => '_',+ '=' => '+',+ '[' => '{',+ ']' => '}',+ '\\' => '|',+ ';' => ':',+ '\'' => '"',+ ',' => '<',+ '.' => '>',+ '/' => '?',+ '`' => '~',+ else => ch,+ };+}+fn sgrMouse(params: []const u8, down: bool) Key {- if (params.len == 0 or params[0] != '<') return .escape;+ if (params.len == 0 or params[0] != '<') return .ignore;var it = std.mem.splitScalar(u8, params[1..], ';');const btn = leadingInt(it.next() orelse "0");const x = leadingInt(it.next() orelse "1");@@@ -386,60 -405,120 +495,177 @@@ test "lone trailing ESC stays pending,try std.testing.expect(next("\x1b", &i) == null);try std.testing.expectEqual(@as(usize, 0), i);}++ test "ESC ESC delivers an Escape and leaves the second pending" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.escape, next("\x1b\x1b", &i).?);+ try std.testing.expectEqual(@as(usize, 1), i);+ try std.testing.expect(next("\x1b\x1b", &i) == null);+ try std.testing.expectEqual(@as(usize, 1), i);+ }++ test "kitty release events never fire keys" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[1;1:3A", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[3;1:3~", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[5;1:3~", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[97;1:3u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.up, next("\x1b[1;1:2A", &i).?); // repeat acts+ }++ test "right-side modifiers follow the real kitty table, never Escape" {+ held = 0;+ var i: usize = 0;+ // Right-Shift (57447) and Right-Ctrl (57448) must not latch held bits.+ try std.testing.expectEqual(Key.ignore, next("\x1b[57447;1:1u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57448;1:1u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ // Right-Alt (57449) latches alt; its release clears it.+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:1u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.delete_word, next("\x7f", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:3u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ held = 0;+ }++ test "unknown keys and replies are inert, never Escape" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57376u", &i).?); // F13+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[17~", &i).?); // F6+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[2~", &i).?); // Insert+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[?1;2c", &i).?); // DA reply+ }++ test "kitty functional arrows and keypad map; a stale super latch resyncs" {+ held = 8; // pretend we missed the Super release+ var i: usize = 0;+ try std.testing.expectEqual(Key.up, next("\x1b[57352u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97;1u", &i).?);+ try std.testing.expectEqual(@as(u32, 0), held);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.enter, next("\x1b[57414u", &i).?); // KP_ENTER+ held = 0;+ }++ test "SS3 application keys and unbound alt-chords" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.up, next("\x1bOA", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.f1, next("\x1bOP", &i).?);+ i = 0;+ // Split SS3 stays pending.+ try std.testing.expect(next("\x1bO", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+ i = 0;+ // Unbound Alt+p swallows both bytes — no phantom Escape, no stray 'p'.+ try std.testing.expectEqual(Key.ignore, next("\x1bp", &i).?);+ try std.testing.expectEqual(@as(usize, 2), i);+ try std.testing.expect(next("\x1bp", &i) == null);+ }++ test "X10 mouse fallback consumes its payload instead of typing it" {+ var i: usize = 0;+ const ev = next("\x1b[M\x20\x2c\x28", &i).?;+ try std.testing.expect(ev == .mouse);+ try std.testing.expectEqual(@as(u8, 0), ev.mouse.btn);+ try std.testing.expectEqual(@as(u16, 12), ev.mouse.x);+ try std.testing.expectEqual(@as(u16, 8), ev.mouse.y);+ try std.testing.expect(ev.mouse.down);+ try std.testing.expectEqual(@as(usize, 6), i);+ i = 0;+ // Split short — wait for the rest.+ try std.testing.expect(next("\x1b[M\x20", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+ }++ test "non-ASCII CSI-u codepoints type text instead of Escape" {+ var i: usize = 0;+ try std.testing.expectEqual(Key{ .codepoint = 0xe9 }, next("\x1b[233;1u", &i).?);+ held = 0;+ }++ test "OSC and APC replies on stdin are consumed, never typed" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b]11;rgb:14/14/14\x07", &i).?);+ try std.testing.expectEqual(@as(usize, 18), i);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b_Gi=1;OK\x1b\\", &i).?);+ try std.testing.expectEqual(@as(usize, 11), i);+ i = 0;+ // Unterminated reply stays pending until the rest arrives.+ try std.testing.expect(next("\x1b]11;rgb:14", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+ }++test "orphan SGR mouse is never inserted as letters" {+ var i: usize = 0;+ const k = next("39;33;23M", &i).?;+ try std.testing.expect(k == .mouse);+ try std.testing.expectEqual(@as(u8, 39), k.mouse.btn);+ try std.testing.expectEqual(@as(u16, 33), k.mouse.x);+ try std.testing.expectEqual(@as(usize, 9), i);+ i = 0;+ const k2 = next("<64;4;8Mhi", &i).?;+ try std.testing.expect(k2 == .mouse);+ try std.testing.expectEqual(@as(u8, 64), k2.mouse.btn);+ try std.testing.expectEqual(Key{ .char = 'h' }, next("<64;4;8Mhi", &i).?);+}++test "SGR mouse flood does not leak digits" {+ const seq = "\x1b[<39;33;23M\x1b[<39;26;20M\x1b[<39;25;19M";+ var i: usize = 0;+ var n: usize = 0;+ while (next(seq, &i)) |k| {+ try std.testing.expect(k == .mouse);+ n += 1;+ }+ try std.testing.expectEqual(@as(usize, 3), n);+ try std.testing.expectEqual(seq.len, i);+}++test "orphan kitty CSI-u is ignore, never letters or Escape" {+ var i: usize = 0;+ const seq = "3u7444;9u7441;10u";+ var n: usize = 0;+ while (next(seq, &i)) |k| {+ try std.testing.expect(k == .ignore);+ n += 1;+ }+ try std.testing.expectEqual(@as(usize, 3), n);+ try std.testing.expectEqual(seq.len, i);+ i = 0;+ try std.testing.expectEqual(Key{ .char = 'h' }, next("hi", &i).?);+}++test "Shift+9 is open-paren, Shift+0 is close-paren" {+ var i: usize = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = ')' }, next("\x1b[48;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57:40;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2;40u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '!' }, next("\x1b[49;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = 'A' }, next("\x1b[97;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[27;2;57~", &i).?);+}diff --cc TUI/root.zigindex 5021d61a,70ce760d..e33fdf2c--- a/TUI/root.zig+++ b/TUI/root.zig@@@ -49,8 -49,10 +49,11 @@@ test_ = @import("sim.zig");_ = @import("render.zig");_ = @import("tty.zig");+ _ = @import("restore.zig");+ _ = @import("files.zig");+ _ = @import("overlays.zig");_ = run_mod;+ _ = @import("traj.zig");}pub fn main(init: std.process.Init) !void {diff --cc TUI/run.zigindex 6c4f81c4,24ee32e5..686b710a--- a/TUI/run.zig+++ b/TUI/run.zig@@@ -12,9 -13,14 +13,15 @@@ const restore_mod = @import("restore.ziconst theme_mod = @import("theme.zig");const turn = @import("turn.zig");const tty = @import("tty.zig");+const traj = @import("traj.zig");const Model = app.Model;+ // 1000/1003/1006: click + hover + wheel as buttons 64/65 (not arrows).+ // 2004: bracketed paste. 7l: no autowrap into the prompt.+ // >11u: kitty disambiguate + event types + all-keys (Cmd+Delete / Super latch).+ // >4;2m: xterm modifyOtherKeys so Super+Backspace also arrives as CSI 27;9;127~.+ const enable_seq = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m";+pub const RunOpts = struct {turn_ctx: ?*anyopaque = null,turn_fn: ?engine.TurnFn = null,@@@ -56,15 -70,10 +71,11 @@@ pub fn runvar out_buf: [64 * 1024]u8 = undefined;var stdout = Io.File.stdout().writer(io, &out_buf);const w = &stdout.interface;- // 1000/1006: click + wheel as 64/65. Not 1003h — motion floods leak as text.- // 2004: bracketed paste. 7l: no autowrap into the prompt.- // >31u: kitty disambiguate + events + alternates + all-keys + text (Shift+9 is "(").- // >4;2m: xterm modifyOtherKeys so Super+Backspace also arrives as CSI 27;9;127~.- w.writeAll("\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1006h\x1b[?7l\x1b[>31u\x1b[>4;2m") catch {};+ w.writeAll(enable_seq) catch {};w.flush() catch {};+ traj.open(io);defer {- w.writeAll("\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l") catch {};+ w.writeAll(restore_mod.seq) catch {};w.flush() catch {};}@@@ -105,15 -113,31 +115,32 @@@saw_gfx = has_gfx;}- const wait: i32 = if (m.pending != null) 50 else 200;- if (!tty.poll(wait)) continue;+ // Short wait while an unfinished escape sequence is pending: if+ // nothing follows, the lone ESC was a real Escape keypress (#94).+ const wait: i32 = if (pending_len > 0) 25 else if (m.pending != null) 50 else 200;+ if (!tty.poll(wait)) {+ if (pending_len > 0) {+ esc_stall += 1;+ if (esc_stall >= 2) {+ if (inbuf[0] == 0x1b and keys.handle(&m, .escape) == .quit) m.running = false;+ pending_len = 0;+ esc_stall = 0;+ }+ }+ continue;+ }+ esc_stall = 0;const got = tty.readStdin(inbuf[pending_len..]);- const n = pending_len + got;- if (got > 0) traj.note(io, m.now_ms, inbuf[pending_len..n]);- if (n == 0) {- pending_len = 0;++ if (got > 0) traj.note(io, m.now_ms, inbuf[pending_len .. pending_len + got]);+ if (got == 0) {+ // poll says readable but read gives nothing: hangup or transient+ // error. Three in a row means the TTY is gone.+ zero_reads += 1;+ if (zero_reads >= 3) m.running = false;continue;}+ zero_reads = 0;+ const n = pending_len + got;var i: usize = 0;while (key_mod.next(inbuf[0..n], &i)) |k| {switch (keys.handle(&m, k)) {diff --cc scripts/eval/tier1-manifest.jsonindex c380f4d4,b9e6866b..865e9bf3--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@@ -15,7 -15,7 +15,7 @@@"src/repl.zig","TUI/root.zig"],- "test_count_baseline": 1272,- "test_count_baseline": 1246,++ "test_count_baseline": 1279,"test_count_slack": 25,"required_invariants": [{diff --cc src/agent_request_body_responses.zigindex 00000000,b5934303..1c934220mode 000000,100644..100644--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@@ -1,0 -1,195 +1,195 @@@+ //! The Responses-wire request body (codex / xAI #502), split from+ //! agent_request_body.zig under the 600-line ceiling, plus the structured-+ //! output writers (text.format here, response_format for the chat wire).++ const std = @import("std");+ const Value = std.json.Value;++ const Agent = @import("agent.zig").Agent;+ const serde = @import("serde.zig");+ const http_headers = @import("http_headers.zig");+ const codex_chain = @import("codex_chain.zig");+ const server_compact = @import("agent_server_compact.zig");++ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_tool: bool) !void {+ // Responses API (codex / ChatGPT backend, and xAI behind GRAFF_XAI_WIRE).+ // system prompt → instructions; history items are valid input items;+ // stream is required (we buffer + parse the SSE); reasoning items return+ // encrypted and are passed back per turn.+ const is_codex = std.mem.eql(u8, self.provider.id, "codex");+ try s.objectField("instructions");+ try s.write(try schemaAwarePrompt(self));+ if (is_codex) {+ // Pin our full resends to a per-session cache partition, the way+ // openai/codex does (it defaults this to the same session UUID it+ // puts in the `session_id` header). xAI documents automatic prompt+ // caching and no such field, so it stays codex-only.+ var ckbuf: [96]u8 = undefined;+ try s.objectField("prompt_cache_key");+ try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));+ }+ // Codex WS delta: once a response.id is held on a live WS session, send+ // previous_response_id + only the items the server does not yet hold.+ // codex_chain gates this to codex — xAI's WS stalls silently on a+ // store:false chained turn (probed 2026-08-15). ONE gate for both fields.+ const chain = codex_chain.chainUsable(self);+ if (chain) {+ try s.objectField("previous_response_id");+ try s.write(self.codex_prev_id.?);+ }+ try s.objectField("input");+ if (chain) {+ var delta = std.json.Array.init(self.arena);+ for (self.messages.items[self.codex_sent_upto..]) |m| try delta.append(m);+ try s.write(Value{ .array = delta });+ } else {+ try s.write(Value{ .array = self.messages });+ }+ if (tools) |t| {+ try s.objectField("tools");+ try serde.writeOpenAITools(s, self.scratchAlloc(), t); // #261 follow-up+ try s.objectField("tool_choice");+ try s.write(if (force_tool) "required" else "auto");+ try s.objectField("parallel_tool_calls");+ try s.write(true);+ }+ // Codex "fast" mode (/fast): priority service tier — a ChatGPT-backend+ // field the other Responses providers must never see.+ if (self.fast and is_codex) {+ try s.objectField("service_tier");+ try s.write("priority");+ }+ try s.objectField("reasoning");+ try s.beginObject();+ try s.objectField("effort");+ // Ultra preset → wire value `max`. #379: compaction summaries run at low+ // effort — a high-effort reasoner can complete with only reasoning items+ // and zero output text, i.e. an empty summary.- try s.write(if (self.compaction_request) "low" else if (self.reasoning == .ultra) "max" else @tagName(self.reasoning));++ try s.write(if (self.compaction_request or self.server_compaction_request) "low" else if (self.reasoning == .ultra) "max" else @tagName(self.reasoning));+ try s.endObject();+ try s.objectField("include");+ try s.beginArray();+ try s.write("reasoning.encrypted_content");+ try s.endArray();+ try s.objectField("store");+ try s.write(false);+ server_compact.noteExposure(self);+ try server_compact.writeContextManagement(self, s);+ if (self.output_schema) |schema_json| try writeTextFormat(s, schema_json);+ // No top-level max_output_tokens: the codex backend rejects it+ // ("Unsupported parameter") on gpt-5.6-* — codex sets it only as a tool argument.+ try s.objectField("stream");+ try s.write(true);+ }++ /// With --output-schema the strict grammar tempts the model to answer+ /// immediately instead of touching tools (graff-evals caught grok-4.6+ /// answering a file-inspection task without reading the file). One standing+ /// line restores tools-first behavior; without a schema the prompt is+ /// byte-identical to before.+ pub fn schemaAwarePrompt(self: *Agent) ![]const u8 {+ const base = self.systemPrompt();+ if (self.output_schema == null) return base;+ return std.mem.concat(self.scratchAlloc(), u8, &.{+ base,+ "\n\nA JSON output schema is enforced on your final message. Use tools first to gather every fact you need; only the final message must match the schema — never guess values.",+ });+ }++ /// Structured outputs on the Responses wire (xAI/OpenAI): `text.format` with+ /// the user's JSON schema the final answer must satisfy (--output-schema).+ pub fn writeTextFormat(s: *std.json.Stringify, schema_json: []const u8) !void {+ try s.objectField("text");+ try s.beginObject();+ try s.objectField("format");+ try s.beginObject();+ try s.objectField("type");+ try s.write("json_schema");+ try s.objectField("name");+ try s.write("result");+ try s.objectField("strict");+ try s.write(true);+ try s.objectField("schema");+ try s.print("{s}", .{schema_json});+ try s.endObject();+ try s.endObject();+ }++ /// Structured outputs on the chat-completions wire: response_format+ /// json_schema (the shape xAI/OpenAI/compatible routers document).+ pub fn writeResponseFormat(s: *std.json.Stringify, schema_json: []const u8) !void {+ try s.objectField("response_format");+ try s.beginObject();+ try s.objectField("type");+ try s.write("json_schema");+ try s.objectField("json_schema");+ try s.beginObject();+ try s.objectField("name");+ try s.write("result");+ try s.objectField("strict");+ try s.write(true);+ try s.objectField("schema");+ try s.print("{s}", .{schema_json});+ try s.endObject();+ try s.endObject();+ }++ fn testAgentFor(arena: std.mem.Allocator, id: []const u8, kind: @import("provider.zig").Provider.Kind, model: []const u8) !Agent {+ var messages = std.json.Array.init(arena);+ var user: std.json.ObjectMap = .empty;+ try user.put(arena, "role", .{ .string = "user" });+ try user.put(arena, "content", .{ .string = "hello" });+ try messages.append(.{ .object = user });+ return .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{ .id = id, .kind = kind, .auth = .bearer, .url = "", .api_key = "k", .model = model, .context = 500_000 },+ .messages = messages,+ .sub = false,+ .label = "main",+ .out = null,+ .sys_normal = "system",+ };+ }++ test "xai Responses body is bearer-clean: no codex-isms, xAI-legal fields only (#502)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var agent = try testAgentFor(arena_state.allocator(), "xai", .responses, "grok-4.6");+ agent.fast = true; // must NOT leak service_tier off codex+ const body = try agent.buildBody(null, false, true, true);+ defer std.testing.allocator.free(body);+ try std.testing.expect(std.mem.indexOf(u8, body, "\"instructions\":\"system\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "\"store\":false") != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "\"reasoning\":{\"effort\":\"medium\"}") != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "prompt_cache_key") == null);+ try std.testing.expect(std.mem.indexOf(u8, body, "service_tier") == null);+ try std.testing.expect(std.mem.indexOf(u8, body, "context_management") == null);+ try std.testing.expect(std.mem.indexOf(u8, body, "previous_response_id") == null);+ }++ test "--output-schema rides text.format on Responses and response_format on chat (#502)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const schema = "{\"type\":\"object\",\"properties\":{\"answer\":{\"type\":\"string\"}},\"required\":[\"answer\"],\"additionalProperties\":false}";+ var agent = try testAgentFor(arena_state.allocator(), "xai", .responses, "grok-4.6");+ agent.output_schema = schema;+ const responses_body = try agent.buildBody(null, false, true, true);+ defer std.testing.allocator.free(responses_body);+ try std.testing.expect(std.mem.indexOf(u8, responses_body, "\"text\":{\"format\":{\"type\":\"json_schema\",\"name\":\"result\",\"strict\":true,\"schema\":{\"type\":\"object\"") != null);++ var chat = try testAgentFor(arena_state.allocator(), "xai", .openai, "grok-4.6");+ chat.output_schema = schema;+ const chat_body = try chat.buildBody(null, false, true, true);+ defer std.testing.allocator.free(chat_body);+ try std.testing.expect(std.mem.indexOf(u8, chat_body, "\"response_format\":{\"type\":\"json_schema\",\"json_schema\":{\"name\":\"result\",\"strict\":true,\"schema\":{\"type\":\"object\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, chat_body, "\"text\":{\"format\"") == null);++ // No schema set → neither field appears (the overwhelmingly common path).+ var plain = try testAgentFor(arena_state.allocator(), "xai", .openai, "grok-4.6");+ const plain_body = try plain.buildBody(null, false, true, true);+ defer std.testing.allocator.free(plain_body);+ try std.testing.expect(std.mem.indexOf(u8, plain_body, "response_format") == null);+ }diff --cc src/agent_server_compact.zigindex 4bbaa82d,e9292511..86656e66--- a/src/agent_server_compact.zig+++ b/src/agent_server_compact.zig@@@ -26,9 -26,10 +26,10 @@@ const Io = std.Ioconst main_mod = @import("main.zig");const Agent = @import("agent.zig").Agent;const Provider = @import("provider.zig").Provider;+const http = @import("http.zig");const telemetry = @import("telemetry.zig");const keys_cli = @import("keys_cli.zig");-const http = @import("http.zig"); // #502: the explicit xAI compact POST+ const goal_flow = @import("goal_flow.zig");/// GRAFF_SERVER_COMPACT=0/false/off forces the client arm, =1 forces the/// server arm (session_settings.applyEnvKnobs). Default: A/B assignment.@@@ -106,21 -107,19 +107,24 @@@ pub fn noteClientSummary(chars: usize)pushExp(d);}-/// Emit the compaction directive on a Responses request body. The threshold-/// mirrors the client-side trigger (compactAt: 80% of the window,-/// GRAFF_COMPACT_PCT-aware) so the server compacts at the point graff would-/// have.+/// Emit the automatic directive at compactAt, or force an explicit Codex pass+/// independently of the experiment assignment. The backend's minimum threshold+/// of 1,000 guarantees every real graff context crosses it; the flag is route-+/// gated so a non-OpenAI Responses provider can never enter this path.pub fn writeContextManagement(self: *const Agent, s: anytype) !void {+ // #502: an explicit-compact provider (xAI) ignores the in-stream directive+ // — probed live; compaction goes through explicitCompact instead.+ if (self.provider.serverCompactUrl() != null) return;- if (!enabled(self.provider)) return;- try writeContextManagementBody(self, s);+ const threshold = if (self.server_compaction_request and manualRoute(self.provider) == .in_stream)+ @as(u64, 1_000)+ else if (enabled(self.provider))+ self.provider.compactAt()+ else+ return;+ try writeContextManagementBody(s, threshold);}-fn writeContextManagementBody(self: *const Agent, s: anytype) !void {+fn writeContextManagementBody(s: anytype, threshold: u64) !void {try s.objectField("context_management");try s.beginArray();try s.beginObject();@@@ -362,11 -198,17 +366,20 @@@ fn pruneIf(self: *Agent, server_arm: bopub fn autocompact(self: *Agent, recovery_meter: u64) void {autocompactIf(self, recovery_meter, enabled(self.provider));}+pub fn autocompactResumed(self: *Agent) void {+ autocompactIf(self, 0, enabled(self.provider));+}fn autocompactIf(self: *Agent, recovery_meter: u64, server_arm: bool) void {+ // #502: an explicit-compact provider (xAI) gets first-party compaction —+ // one POST folds the whole history into an opaque blob, no summary model+ // call. Any failure falls through to the client policy so a broken+ // endpoint can never wedge the session.+ if (self.provider.serverCompactUrl() != null) {+ if (explicitCompact(self)) return;+ self.compactOrRecover(self.provider.nearContextLimit(recovery_meter));+ return;+ }if (!server_arm or self.provider.kind != .responses) {self.compactOrRecover(self.provider.nearContextLimit(recovery_meter));return;diff --cc src/mcp_lifecycle.zigindex d70f240a,74b663a0..3a7e236b--- a/src/mcp_lifecycle.zig+++ b/src/mcp_lifecycle.zig@@@ -208,74 -208,3 +208,75 @@@ fn expectDecision(body: []const u8, staconst got = decideDiscover(arena_state.allocator(), status, body);try std.testing.expectEqual(want, std.meta.activeTag(got));}++++test "Auto: server/discover listing 2026-07-28 is modern_list" {+ try expectDecision(+ \\{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2026-07-28","2025-11-25"]}}+ , 200, .modern_list);+}++test "Auto: discover without 2026-07-28 falls back (no_modern_version)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const got = decideDiscover(arena_state.allocator(), 200,+ \\{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2025-11-25"]}}+ );+ try std.testing.expectEqual(Decision{ .legacy_handshake = .no_modern_version }, got);+}++test "Auto: METHOD_NOT_FOUND (-32601) falls back like rust-sdk Auto" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const got = decideDiscover(arena_state.allocator(), 200,+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}+ );+ try std.testing.expectEqual(Decision{ .legacy_handshake = .rejected }, got);+}++test "Auto: initialize-first rejection falls back" {+ try expectDecision(+ \\{"jsonrpc":"2.0","error":{"code":-32000,"message":"Bad Request: Server not initialized"},"id":null}+ , 200, .legacy_handshake);+}++test "Auto: -32020 is a modern reject, never a legacy fallback" {+ try expectDecision(+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"header mismatch"}}+ , 400, .reject_modern);+}++test "Auto: -32022 listing only 2025-11-25 is a legacy handshake" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const got = decideDiscover(arena_state.allocator(), 400,+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32022,"data":{"supported":["2025-11-25"]}}}+ );+ try std.testing.expectEqual(Decision{ .legacy_handshake = .no_modern_version }, got);+}++test "Auto: -32022 that also lists 2026-07-28 retries once" {+ try expectDecision(+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32022,"data":{"supported":["2026-07-28"]}}}+ , 400, .retry);+}++test "Auto: cached legacy era is a first-class Decision path" {+ try std.testing.expectEqual(mcp_rpc.LegacyReason.cached_legacy, .cached_legacy);+}++test "Auto: known modern era lists without server/discover" {+ const src = @embedFile("mcp_lifecycle.zig");+ try std.testing.expect(std.mem.indexOf(u8, src, "if (known_era == .modern)") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "tools/list") != null);+}++test "Auto: first-launch overlaps initialize with the modern probes" {+ const src = @embedFile("mcp_lifecycle.zig");+ try std.testing.expect(std.mem.indexOf(u8, src, "io.concurrent(initTask") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "dropHttpSession") != null);+}++test {+ _ = @import("mcp_cache.zig");+}diff --cc src/router_catalog_tests.zigindex aa0ebad8,0ff320e8..9a2b0574--- a/src/router_catalog_tests.zig+++ b/src/router_catalog_tests.zig@@@ -275,9 -261,51 +275,60 @@@ test "router discovery replaces only ittry std.testing.expect(pricing.providerModelInTable("codex", "gpt-5.6-sol"));}+test "startup catalog loads fan out concurrently with Kimi" {+ const src = @embedFile("router_catalog.zig");+ try std.testing.expect(std.mem.indexOf(u8, src, "io.concurrent(fetchSpecTask") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "io.concurrent(kimiFetchTask") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "fn spawnKimi") != null);+}+++ // ── provider.zig routing tests parked here under its 600-line ceiling ──────++ test "providerFor (#377): family-prefixed spelling routes to the direct provider, not the gateway" {+ // kimi's catalog row is `k3`; gateways catalog the same model as `kimi-k3`.+ // The prefixed spelling must seat the keyed direct provider on its NATIVE+ // name — before this fix it fell through to the codegraff gateway and a+ // flat-rate subscription silently became metered/licensed usage.+ const Keys = provider.Keys;+ const all = Keys{ .values = @splat("k") };+ const p = try all.providerFor("kimi-k3");+ try std.testing.expectEqualStrings("kimi", p.id);+ try std.testing.expectEqualStrings("k3", p.model);+ // Exact catalog names keep absolute priority over the family alias.+ try std.testing.expectEqualStrings("gpt-5.6-sol", (try all.providerFor("gpt-5.6-sol")).model);+ // Without the kimi credential the prefixed spelling behaves exactly as+ // before: uncatalogued in the compiled table, so the gateway fallback.+ var values: [provider.provider_specs.len]?[]const u8 = @splat("k");+ for (provider.provider_specs, 0..) |spec, i| {+ if (std.mem.eql(u8, spec.id, "kimi")) values[i] = null;+ }+ const no_kimi = Keys{ .values = values };+ try std.testing.expectEqualStrings("codegraff", (try no_kimi.providerFor("kimi-k3")).id);+ }++ test "GRAFF_XAI_WIRE=responses moves xAI onto the Responses wire (#502)" {+ const Keys = provider.Keys;+ const Provider = provider.Provider;+ const all = Keys{ .values = @splat("k") };+ const chat = try all.providerById("xai", "grok-4.3");+ try std.testing.expectEqual(Provider.Kind.openai, chat.kind);+ try std.testing.expect(chat.serverCompactUrl() == null); // chat wire: no blob replay path+ provider.g_xai_responses = true;+ defer provider.g_xai_responses = false;+ const resp = try all.providerById("xai", "grok-4.3");+ try std.testing.expectEqual(Provider.Kind.responses, resp.kind);+ try std.testing.expectEqualStrings(provider.xai_responses_url, resp.url);+ try std.testing.expectEqualStrings(provider.xai_compact_url, resp.serverCompactUrl().?);+ // withModel keeps the wire choice.+ const moved = resp.withModel("grok-4.6");+ try std.testing.expectEqual(Provider.Kind.responses, moved.kind);+ try std.testing.expectEqualStrings(provider.xai_responses_url, moved.url);+ // codex keeps in-stream compaction — never the explicit endpoint.+ const codex = try all.providerById("codex", "gpt-5.6-sol");+ try std.testing.expect(codex.serverCompactUrl() == null);- // every other provider is untouched by the knob.++ // every other provider is untouched by the knob: openai keeps its native++ // Responses wire (default since v0.0.250) and its own endpoint.+ const oai = try all.providerById("openai", "gpt-5.6");- try std.testing.expectEqual(Provider.Kind.openai, oai.kind);++ try std.testing.expectEqual(Provider.Kind.responses, oai.kind);++ try std.testing.expect(std.mem.indexOf(u8, oai.url, "api.openai.com") != null);+ }diff --cc src/session_run.zigindex 4117ae3c,d7b77136..ef93f94d--- a/src/session_run.zig+++ b/src/session_run.zig@@@ -142,8 -142,16 +142,16 @@@ pub fn runOneshotPrompt(gpa: Allocatorvar oneshot_user = if (goal_note.len > 0) try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ ultracode_msg.text, goal_note }) else ultracode_msg.text;if (eval_note.len > 0) oneshot_user = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ oneshot_user, eval_note });try root.messages.append(try messages_mod.textMessage(arena, "user", oneshot_user));- if (telemetry.g_telem) |t| t.countTurn();+ if (telemetry.g_telem) |t| t.beginTurn(@intCast(@min(prompt_text.len, std.math.maxInt(u32))), root.provider.model);- const final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| {+ // #502: --output-schema runs TWO-PHASE. A strict grammar on every message+ // pulls the model into answering immediately instead of touching tools+ // (graff-evals caught grok-4.6 guessing a file-inspection answer), so the+ // agentic phase runs unconstrained and one tools-off formatting turn then+ // restates the final answer under the schema — same conversation, so it+ // reads the real evidence.+ const pending_schema = root.output_schema;+ root.output_schema = null;+ var final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| {// std.process.fatal does not unwind main's defers. Mirror their order:// join the fleet, reap jobs/pumps, then the terminal behavioral event.fleet.joinElites(io);@@@ -293,18 -316,21 +316,29 @@@ pub fn buildRootAgent// #469: register this root session so co-resident graffs see it (and it// them) BEFORE anyone touches the shared tree — a live co-owner is named// at birth here, not discovered mid-collision.- if (presence.announce(io, gpa, arena, root.home, root.session_name, if (root.goal) |g| g.objective else "")) |warning| {- if (!main_mod.json_mode and flags.oneshot_prompt == null) try out.print("{s}", .{warning});+ if (presence.announce(io, gpa, arena, root.home, root.session_name, if (root.goal) |g| g.objective else "")) |owner| {+ if (!main_mod.json_mode and flags.oneshot_prompt == null) {+ const age_ms = util.unixMs(io) - owner.last_seen_ms;+ engine_sink.writerSink(out).emit(io, .{ .shared_worktree_owner = .{+ .session_id = owner.session_id,+ .pid = owner.pid,+ .active_minutes = @divTrunc(if (age_ms > 0) age_ms else 0, std.time.ms_per_min),+ .goal = owner.goal,+ } });+ }}if (flags.eval_cmd_flag) |c| root.eval_cmd = try arena.dupe(u8, c);+ // #502: --output-schema (inline JSON or @file) → structured outputs.+ if (flags.output_schema_flag) |schema_arg| {+ const trimmed = std.mem.trim(u8, schema_arg, " \t");+ root.output_schema = if (std.mem.startsWith(u8, trimmed, "@"))+ std.Io.Dir.cwd().readFileAlloc(io, trimmed[1..], arena, .limited(1024 * 1024)) catch |e| blk: {+ if (!main_mod.json_mode) try out.print("warning: --output-schema {s}: {t} — ignored\n", .{ trimmed[1..], e });+ break :blk null;+ }+ else+ try arena.dupe(u8, trimmed);+ }if (flags.eval_target_flag) |t| root.eval_target = t;if (flags.eval_niche_flag) |n| root.eval_niche = try arena.dupe(u8, n);_ = recipe.record(tracer, trace.g_traj, root.provider.id, root.provider.model, @tagName(root.reasoning), root.systemPrompt(), root.toolsJson(), if (root.eval_niche.len > 0) root.eval_niche else "interactive");